diff --git a/.gitignore b/.gitignore index 56827d4..2946fc1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,6 @@ *.ini *.log *.db +*.mo /.idea venv/ diff --git a/README.md b/README.md index 3d113ff..a019543 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,27 @@ -什么是ScriptFan.com -=================== +# 什么是ScriptFan.com -ScriptFan.com 是西安一个线下技术沙龙的官方网站程序, 沙龙的名字是**ScriptFan技术沙龙**, 主要以讨论脚本语言为主, 比如 Python, Perl, PHP, Ruby, Shell, JavaScript, CoffeeScript 等. +[ScriptFan.com](http://scriptfan.com) 是西安一个线下技术沙龙的官方网站程序, 沙龙的名字是**ScriptFan技术沙龙**, +主要以讨论脚本语言为主, 比如 Python, Perl, PHP, Ruby, Shell, JavaScript, CoffeeScript 等. ## 网站主要功能 -1. 发布活动和新闻 -2. 用户名片 -3. 用户讨论 -4. 每期线下活动的话题的总结 + 1. 发布活动和新闻 + 2. 用户名片 + 3. 用户讨论 + 4. 每期线下活动的话题的总结 ## 网站程序简介 -网站使用Python语言写成, 用到了Flask作为主要框架, SqlAlchemy作为ORM框架,页面效果使用的是Bootstrap。 +网站使用 Python 语言写成, 用到了 Flask 作为主要框架, SqlAlchemy 作为 ORM 框架,页面效果使用的是 Bootstrap。 ## 贡献代码,从这里开始 -> 欢迎熟悉 Python, Flask, SqlAlchemy 的朋友一起参与开发 ,数据库的 Migration 工具采用 SqlAlchemy 作者开发的 [alembic](http://alembic.readthedocs.org/en/latest/tutorial.html#editing-the-ini-file), 方便在开发过程中持续的改进数据库结构, 有兴趣参与开发的同学需要先学习下. +> 欢迎熟悉 Python, Flask, SqlAlchemy 的朋友一起参与开发 ,数据库的 Migration 工具采用 SqlAlchemy 作者开发的 +> [alembic](http://alembic.readthedocs.org/en/latest/tutorial.html#editing-the-ini-file), +> 方便在开发过程中持续的改进数据库结构, 有兴趣参与开发的同学需要先学习下. > 申请开发权限,请联系 david.scriptfan#gmail.com -**1. 下载项目并安装依赖库** +### 1. 下载项目并安装依赖库 $ git@github.com:kingheaven/ScriptFan.com.git $ cd ScriptFan.com @@ -28,22 +30,31 @@ ScriptFan.com 是西安一个线下技术沙龙的官方网站程序, 沙龙的 $ . venv/bin/activate (venv) $ pip install -v -r requirements.txt -**2. 数据库配置** +### 2. 数据库配置 -在本地数据库中建立一个数据库,如 ``scriptfan_dev`` +在本地数据库中建立一个数据库,如 `scriptfan_dev` + +**注意:** 请确保数据库、表及字段的 Collation 为 utf8 `utf8_unicode_ci` 类型 修改配置文件 $ cp website/scriptfan/scriptfan.cfg.sample website/scriptfan/scriptfan.cfg $ cp website/alembic.ini.sample website/alembic.ini -将 ``website/scriptfan/scriptfan.cfg`` 中的 ``SQLALCHEMY_DATABASE_URI`` 及 ``website/alembic.ini`` 中的 ``sqlalchemy.url`` 替换为你的数据库配置 +将 `website/scriptfan/scriptfan.cfg` 中的 `SQLALCHEMY_DATABASE_URI` 及 `website/alembic.ini` 中的 `sqlalchemy.url` 替换为你的数据库配置 -**3. 生成数据库** +### 3. 更新数据库结构 $ cd website $ alembic upgrade head -**4. 启动本地开发服务器** +### 4. 启动本地开发服务器 $ python manager.py runserver + +### 5. 更新i18n语言文件 + +在 `website/scriptfan` 目录下执行 + + $ python manage.py translate + diff --git a/requirements.txt b/requirements.txt index 4c2e5e7..30b7d5d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,11 +1,25 @@ -flask >= 0.8 -flask-script >= 0.3.3 -flask-sqlalchemy >= 0.16 -flask-login >= 0.1.3 -flask-wtf >= 0.8 -flask-admin >= 1.0.1 -flask-openid >= 1.0.1 -flask-principal >= 0.3 -mysql-python >= 1.2.4c1 -sqlalchemy >= 0.7 -alembic >= 0.4.0 +Babel==0.9.6 +Flask==0.9 +Flask-Admin==1.0.4 +Flask-Babel==0.8 +Flask-Login==0.1.3 +Flask-OpenID==1.1.1 +Flask-Principal==0.3.4 +Flask-SQLAlchemy==0.16 +Flask-Script==0.5.3 +Flask-WTF==0.8.3 +Jinja2==2.6 +Mako==0.7.3 +MarkupSafe==0.15 +MySQL-python==1.2.4 +SQLAlchemy==0.8.0 +WTForms==1.0.3 +Werkzeug==0.8.3 +alembic==0.4.2 +blinker==1.2 +markdown2==2.1.0 +mysql-connector-python==1.0.9 +python-openid==2.2.5 +pytz==2013b +speaklater==1.3 +wsgiref==0.1.2 diff --git a/website/scriptfan/utils/__init__.py b/website/__init__.py similarity index 100% rename from website/scriptfan/utils/__init__.py rename to website/__init__.py diff --git a/website/alembic.ini.sample b/website/alembic.ini.sample index 2e3080c..71e23ab 100644 --- a/website/alembic.ini.sample +++ b/website/alembic.ini.sample @@ -11,7 +11,7 @@ script_location = migrate # the 'revision' command, regardless of autogenerate # revision_environment = false -sqlalchemy.url = mysql://root:root@localhost/scriptfan_dev?charset=utf8 +sqlalchemy.url = mysql+mysqlconnector://root:root@localhost/scriptfan_dev?charset=utf8&use_unicode=1 # Logging configuration diff --git a/website/manage.py b/website/manage.py index cad7164..dbe7f19 100644 --- a/website/manage.py +++ b/website/manage.py @@ -3,11 +3,9 @@ import os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) -import logging -logging.basicConfig(level=logging.INFO) - -from flaskext.script import Manager, Shell -from scriptfan import app, db, oid, config_app, dispatch_handlers, dispatch_apps +from flask.ext.script import Manager, Shell +from scriptfan import app, db, oid, config_app, dispatch_handlers, \ + register_blueprints, register_jinja_env manager = Manager(app, with_default_commands=False) @@ -17,23 +15,38 @@ def _make_context(): manager.add_command('shell', Shell(make_context=_make_context)) @manager.option('-c', '--config', dest='config', help='Configuration file name', default='scriptfan.cfg') -def runserver(config): +@manager.option('-H', '--host', dest='host', help='Host address', default='0.0.0.0') +@manager.option('-p', '--port', dest='port', help='Application port', default=5000) +def runserver(config, host, port): config_app(app, config) dispatch_handlers(app) - dispatch_apps(app) - app.run(host='0.0.0.0') - -@manager.option('-c', '--config', dest='config', help='Configuration file name', default='scriptfan.cfg') -def initdb(config='scriptfan.cfg'): - config_app(app, config) - + register_blueprints(app) + register_jinja_env(app) + app.run(host=host, port=port, threaded=True) + +@manager.option('-l', '--lang', dest='lang', help='Language to translate', default=None) +def translate(lang): + if lang: + dirs = [lang,] + else: + trans_dir = os.path.join('scriptfan', 'translations') + dirs = os.listdir(trans_dir) try: - db.drop_all() - db.create_all() - print 'Create tables success' + import subprocess + print 'Scanning translations under path:', trans_dir + for language in dirs: + message_dir = os.path.join(trans_dir, language, 'LC_MESSAGES') + message_source = os.path.join(message_dir, 'messages.po') + message_target = os.path.join(message_dir, 'messages.mo') + if os.path.exists(message_source): + print ' Translateing', language, 'messages...' + args = ['msgfmt', message_source, '-o', message_target, '-v'] + cmd = " ".join(args) + pin, pout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr= subprocess.PIPE).communicate() + for line in pout.split('\n'): + print ' ', line except Exception as e: - print 'Create tables fail:', e - sys.exit(0) + print ' Translateing failed:', e if __name__ == '__main__': manager.run() diff --git a/website/migrate/versions/107b4efd0f7c_rename_security_to_p.py b/website/migrate/versions/107b4efd0f7c_rename_security_to_p.py new file mode 100644 index 0000000..9a69bee --- /dev/null +++ b/website/migrate/versions/107b4efd0f7c_rename_security_to_p.py @@ -0,0 +1,31 @@ +"""rename_security_to_privacy + +Revision ID: 107b4efd0f7c +Revises: 30cb49648d54 +Create Date: 2012-11-24 00:50:50.629688 + +""" + +# revision identifiers, used by Alembic. +revision = '107b4efd0f7c' +down_revision = '30cb49648d54' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.alter_column('users', 'email_security', name='email_privacy', + existing_type=sa.Integer) + op.alter_column('users', 'phone_security', name='phone_privacy', + existing_type=sa.Integer) + op.alter_column('users', 'photo_security', name='photo_privacy', + existing_type=sa.Integer) + +def downgrade(): + op.alter_column('users', 'email_privacy', name='email_security', + existing_type=sa.Integer) + op.alter_column('users', 'phone_privacy', name='phone_security', + existing_type=sa.Integer) + op.alter_column('users', 'photo_privacy', name='photo_security', + existing_type=sa.Integer) diff --git a/website/migrate/versions/19f590834366_add_activity_tables.py b/website/migrate/versions/19f590834366_add_activity_tables.py deleted file mode 100644 index 013bbc3..0000000 --- a/website/migrate/versions/19f590834366_add_activity_tables.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Add activity tables - -Revision ID: 19f590834366 -Revises: 43cda5e14cf0 -Create Date: 2012-11-14 23:31:56.202053 - -""" - -# revision identifiers, used by Alembic. -revision = '19f590834366' -down_revision = '43cda5e14cf0' - -from alembic import op -import sqlalchemy as db - - -def upgrade(): - op.create_table('activities', - db.Column('id', db.Integer, primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id')), - db.Column('title', db.String(255)), - db.Column('content', db.Text), - db.Column('slug', db.String(255)), - db.Column('start_time', db.DateTime), - db.Column('end_time', db.DateTime), - db.Column('address', db.String(255)), - db.Column('longitude', db.Numeric(10, 7)), - db.Column('latitude', db.Numeric(10, 7)), - db.Column('created_time', db.DateTime), - db.Column('modified_time', db.DateTime)) - - op.create_table('activity_users', - db.Column('activity_id', db.Integer, db.ForeignKey('activities.id'), primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)) - - op.create_table('resources', - db.Column('id', db.Integer, primary_key=True), - db.Column('cser_id', db.Integer, db.ForeignKey('users.id')), - db.Column('filetype', db.String(50)), - db.Column('url', db.String(255)), - db.Column('created_time', db.DateTime), - db.Column('modified_time', db.DateTime)) - - op.create_table('activity_resources', - db.Column('activity_id', db.Integer, db.ForeignKey('activities.id'), primary_key=True), - db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), primary_key=True)) - - op.create_table('activity_comments', - db.Column('id', db.Integer, primary_key=True), - db.Column('author_name', db.String(50)), - db.Column('author_email', db.String(255)), - db.Column('author_site', db.String(255)), - db.Column('content', db.Text, nullable=False), - db.Column('created_time', db.DateTime), - db.Column('modified_time', db.DateTime), - db.Column('parent_id', db.Integer, db.ForeignKey('activity_comments.id')), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'))) - - op.create_table('topics', - db.Column('id', db.Integer, primary_key=True), - db.Column('name', db.String(255)), - db.Column('inro', db.Text), - db.Column('rate_count', db.Integer, default=0), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), nullable=False)) - - op.create_table('topic_resources', - db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), - db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), primary_key=True)) - - op.create_table('topic_users', - db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)) - -def downgrade(): - op.drop_table('topic_users') - op.drop_table('topic_resources') - op.drop_table('topics') - op.drop_table('activity_comments') - op.drop_table('activity_resources') - op.drop_table('resources') - op.drop_table('activity_users') - op.drop_table('activities') diff --git a/website/migrate/versions/24c171278ca6_add_privilege.py b/website/migrate/versions/24c171278ca6_add_privilege.py new file mode 100644 index 0000000..4e3fcc6 --- /dev/null +++ b/website/migrate/versions/24c171278ca6_add_privilege.py @@ -0,0 +1,21 @@ +"""add privilege + +Revision ID: 24c171278ca6 +Revises: 107b4efd0f7c +Create Date: 2012-11-26 22:34:28.876708 + +""" + +# revision identifiers, used by Alembic. +revision = '24c171278ca6' +down_revision = '107b4efd0f7c' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.add_column('users', sa.Column('privilege', sa.Integer)) + +def downgrade(): + op.drop_column('users', 'privilege') diff --git a/website/migrate/versions/2f640415ab56_create_users.py b/website/migrate/versions/2f640415ab56_create_users.py new file mode 100644 index 0000000..40c3736 --- /dev/null +++ b/website/migrate/versions/2f640415ab56_create_users.py @@ -0,0 +1,42 @@ +"""create_users + +Revision ID: 2f640415ab56 +Revises: None +Create Date: 2012-11-23 23:37:50.277992 + +""" + +# revision identifiers, used by Alembic. +revision = '2f640415ab56' +down_revision = None + +from alembic import op +import sqlalchemy as sa + +def upgrade(): + op.create_table('users', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('slug', sa.String(255)), + sa.Column('nickname', sa.String(255)), + sa.Column('password', sa.String(255)), + sa.Column('email', sa.String(255)), + sa.Column('email_security', sa.Integer), + sa.Column('phone', sa.String(255)), + sa.Column('phone_security', sa.Integer), + sa.Column('photo', sa.String(255)), + sa.Column('photo_security', sa.Integer), + sa.Column('motoo', sa.String(255)), + sa.Column('intro', sa.Text), + sa.Column('login_time', sa.DateTime), + sa.Column('created_time', sa.DateTime), + sa.Column('updated_time', sa.DateTime)) + + op.create_table('user_openids', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('provider', sa.String(255)), + sa.Column('user_id', sa.Integer), + sa.Column('openid', sa.String(255))) + +def downgrade(): + op.drop_table('user_openids') + op.drop_table('users') diff --git a/website/migrate/versions/308b76f8dee7_remove_type_field_fr.py b/website/migrate/versions/308b76f8dee7_remove_type_field_fr.py new file mode 100644 index 0000000..57229ca --- /dev/null +++ b/website/migrate/versions/308b76f8dee7_remove_type_field_fr.py @@ -0,0 +1,22 @@ +"""remove type field from articles + +Revision ID: 308b76f8dee7 +Revises: 504407e54867 +Create Date: 2013-03-14 08:12:18.234000 + +""" + +# revision identifiers, used by Alembic. +revision = '308b76f8dee7' +down_revision = '504407e54867' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.drop_column('articles', 'type') + + +def downgrade(): + op.add_column('articles', sa.Column('type', sa.Integer)) diff --git a/website/migrate/versions/30cb49648d54_create_events.py b/website/migrate/versions/30cb49648d54_create_events.py new file mode 100644 index 0000000..a08316a --- /dev/null +++ b/website/migrate/versions/30cb49648d54_create_events.py @@ -0,0 +1,47 @@ +"""create_events + +Revision ID: 30cb49648d54 +Revises: 2f640415ab56 +Create Date: 2012-11-24 00:11:32.773938 + +""" + +# revision identifiers, used by Alembic. +revision = '30cb49648d54' +down_revision = '2f640415ab56' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.create_table('events', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('title', sa.String(255)), + sa.Column('content', sa.Text), + sa.Column('content_html', sa.Text), + sa.Column('address', sa.String(255)), + sa.Column('lat', sa.Numeric(10,7)), + sa.Column('lng', sa.Numeric(10,7)), + sa.Column('status', sa.Integer), + sa.Column('creator_id', sa.DateTime), + sa.Column('created_time', sa.DateTime), + sa.Column('updated_time', sa.DateTime)) + + op.create_table('event_durations', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('event_id', sa.Integer), + sa.Column('date', sa.Date), + sa.Column('start_time', sa.Time), + sa.Column('end_time', sa.Time)) + + op.create_table('event_members', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('event_id', sa.Integer), + sa.Column('member_id', sa.Integer), + sa.Column('status', sa.Integer)) + +def downgrade(): + op.drop_table('event_members') + op.drop_table('event_durations') + op.drop_table('events') diff --git a/website/migrate/versions/3473402c38bc_create_user_tables.py b/website/migrate/versions/3473402c38bc_create_user_tables.py deleted file mode 100644 index 176278b..0000000 --- a/website/migrate/versions/3473402c38bc_create_user_tables.py +++ /dev/null @@ -1,26 +0,0 @@ -"""create user tables - -Revision ID: 3473402c38bc -Revises: None -Create Date: 2012-11-14 22:35:40.666134 - -""" - -# revision identifiers, used by Alembic. -revision = '3473402c38bc' -down_revision = None - -from alembic import op -import sqlalchemy as sa - -def upgrade(): - op.create_table('user_info', - sa.Column('id', sa.Integer, primary_key=True), - sa.Column('motoo', sa.String(255)), - sa.Column('introduction', sa.Text), - sa.Column('phone', sa.String(15), unique=True, nullable=True), - sa.Column('phone_status', sa.Integer, nullable=True), - sa.Column('photo', sa.String(255), nullable=True)) - -def downgrade(): - op.drop_table('user_info') diff --git a/website/migrate/versions/43cda5e14cf0_update_user_tables.py b/website/migrate/versions/43cda5e14cf0_update_user_tables.py deleted file mode 100644 index 4b406ad..0000000 --- a/website/migrate/versions/43cda5e14cf0_update_user_tables.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Update user tables - -Revision ID: 43cda5e14cf0 -Revises: 3473402c38bc -Create Date: 2012-11-14 23:11:34.817678 - -""" - - -revision = '43cda5e14cf0' -down_revision = '3473402c38bc' - -from alembic import op -import sqlalchemy as db -from datetime import datetime - -def upgrade(): - op.create_table('users', - db.Column('id', db.Integer, primary_key=True), - db.Column('email', db.String(50), unique=True, nullable=False), - db.Column('email_status', db.Integer, nullable=True, default=0), - db.Column('nickname', db.String(50), unique=True, nullable=False), - db.Column('password', db.String(50), nullable=True), - db.Column('is_email_verified', db.Boolean, nullable=False, default=True), - db.Column('slug', db.String(50), nullable=True), - db.Column('created_time', db.DateTime, nullable=False, default=datetime.now), - db.Column('modified_time', db.DateTime, nullable=False, default=datetime.now), - db.Column('last_login_time', db.DateTime), - db.Column('privilege', db.Integer, default=3), - db.Column('user_info_id', db.Integer, db.ForeignKey('user_info.id'), nullable=False)) - - op.create_table('user_openids', - db.Column('id', db.Integer, primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), nullable=False), - db.Column('openid', db.String(255), nullable=False, unique=True), - db.Column('provider', db.String(50), nullable=False)) - -def downgrade(): - op.drop_table('user_openids') - op.drop_table('users') diff --git a/website/migrate/versions/4b005d73a873_fix_categories.py b/website/migrate/versions/4b005d73a873_fix_categories.py new file mode 100644 index 0000000..49a1904 --- /dev/null +++ b/website/migrate/versions/4b005d73a873_fix_categories.py @@ -0,0 +1,24 @@ +"""fix categories + +Revision ID: 4b005d73a873 +Revises: 308b76f8dee7 +Create Date: 2013-03-29 00:41:36.953000 + +""" + +# revision identifiers, used by Alembic. +revision = '4b005d73a873' +down_revision = '308b76f8dee7' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.alter_column('categories', 'name', existing_type=sa.Integer, existing_nullable=False, type_=sa.String(255)) + op.drop_column('categories', 'slug') + + +def downgrade(): + op.alter_column('categories', 'name', existing_type=sa.String(255), type_=sa.Integer) + op.add_column('categories', sa.Column('slug', sa.Integer, nullable=False, unique=True)) diff --git a/website/migrate/versions/504407e54867_create_articles_tabl.py b/website/migrate/versions/504407e54867_create_articles_tabl.py new file mode 100644 index 0000000..4592814 --- /dev/null +++ b/website/migrate/versions/504407e54867_create_articles_tabl.py @@ -0,0 +1,36 @@ +"""create articles table + +Revision ID: 504407e54867 +Revises: 24c171278ca6 +Create Date: 2013-03-13 00:31:25.500000 + +""" + +# revision identifiers, used by Alembic. +revision = '504407e54867' +down_revision = '24c171278ca6' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.create_table('categories', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('name', sa.Integer, nullable=False, unique=True), + sa.Column('slug', sa.Integer, nullable=False, unique=True)) + + op.create_table('articles', + sa.Column('id', sa.Integer, primary_key=True), + sa.Column('title', sa.String(255), nullable=False), + sa.Column('type', sa.Integer), # news/anno/posts/ + sa.Column('content', sa.Text, nullable=False), + sa.Column('content_html', sa.Text, nullable=True), + sa.Column('author_id', sa.Integer), + sa.Column('category_id', sa.Integer), + sa.Column('created_time', sa.DateTime), + sa.Column('updated_time', sa.DateTime)) + +def downgrade(): + op.drop_table('articles') + op.drop_table('categories') diff --git a/website/scriptfan/__init__.py b/website/scriptfan/__init__.py index 826c618..ba3a27a 100644 --- a/website/scriptfan/__init__.py +++ b/website/scriptfan/__init__.py @@ -1,22 +1,45 @@ -#!/usr/bin/env python -#-*-coding:utf-8-*- -import logging -logger = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +""" + scriptfan + ~~~~~~~~~~~~~~ + + Module to initialize and config flask application. +""" import os from flask import Flask, render_template, abort, url_for -from extensions import oid, db, login_manager +from flask.ext.openid import OpenID +from flask.ext.sqlalchemy import SQLAlchemy +from flask.ext.login import LoginManager +from flask.ext.babel import Babel + +# Create extension instances +oid = OpenID() +db = SQLAlchemy() +login_manager = LoginManager() +babel = Babel() + +# Create flask application instance instance_path = os.path.abspath(os.path.dirname(__file__)) -app = Flask(__name__, instance_path=instance_path, instance_relative_config=True) +app = Flask(__name__, instance_path=instance_path, \ + instance_relative_config=True) +app.debug_log_format = '[%(levelname)s] %(message)s' +app.debug = True +# Configuration application def config_app(app, config): - logger.info('Setting up application...') + app.logger.info('Setting up application...') + + app.logger.info('- Loading config file: %s' % config) app.config.from_pyfile(config) + + app.logger.info('- Setting up extensions...') db.init_app(app) oid.init_app(app) login_manager.init_app(app) - + babel.init_app(app) + @app.after_request def after_request(response): try: @@ -26,38 +49,45 @@ def after_request(response): abort(500) return response + def dispatch_handlers(app): d = {} - @app.errorhandler(403) - def permission_error(error): - d['title'] = u'您没有权限' - d['message'] = u'您没有权限执行当前的操作, 请登陆或检查url是否错误.' - return render_template('error.html', **d), 403 - - @app.errorhandler(404) - def page_not_found(error): - d['title'] = u'页面不存在' - d['message'] = u'您所访问的页面不存在, 是不是打错地址了啊?' - return render_template('error.html', **d), 404 - - @app.errorhandler(500) - def page_error(error): - d['title'] = u'页面出错啦' - d['message'] = u'您所访问的页面出错啦! 待会再来吧!' - return render_template('error.html', **d), 500 - -def dispatch_apps(app): - from scriptfan.views import siteapp, userapp, activityapp - app.register_blueprint(siteapp, url_prefix='/') - app.register_blueprint(activityapp, url_prefix='/activities') - app.register_blueprint(userapp) - - from scriptfan.utils.filters import dateformat, empty, time_passed, \ - error_class, error_text - app.jinja_env.filters['error_class'] = error_class - app.jinja_env.filters['error_text'] = error_text - app.jinja_env.filters['dateformat'] = dateformat - app.jinja_env.filters['empty'] = empty - app.jinja_env.filters['time_passed'] = time_passed + # @app.errorhandler(403) + # def permission_error(error): + # d['title'] = u'您没有权限' + # d['message'] = u'您没有权限执行当前的操作, 请登陆或检查url是否错误.' + # return render_template('error.html', **d), 403 + + # @app.errorhandler(404) + # def page_not_found(error): + # d['title'] = u'页面不存在' + # d['message'] = u'您所访问的页面不存在, 是不是打错地址了啊?' + # return render_template('error.html', **d), 404 + + # @app.errorhandler(500) + # def page_error(error): + # d['title'] = u'页面出错啦' + # d['message'] = u'您所访问的页面出错啦! 待会再来吧!' + # return render_template('error.html', **d), 500 + + +def register_blueprints(app): + app.logger.info('Register blueprints...') + from scriptfan.views import home, events, users, articles + app.register_blueprint(home.blueprint, url_prefix='') + app.register_blueprint(users.blurprint, url_prefix='/users') + app.register_blueprint(events.blueprint, url_prefix='/events') + app.register_blueprint(articles.blueprint, url_prefix='/articles') + + +def register_jinja_env(app): + app.logger.info('Register jinja filters...') + from scriptfan import filters + + for filter in filters.__all__: + app.logger.info('- Register filter: %s' % filter) + app.jinja_env.filters[filter] = getattr(filters, filter) + + app.logger.info('Register jinja variables...') app.jinja_env.globals['static'] = (lambda filename: \ url_for('static', filename=filename)) diff --git a/website/scriptfan/extensions/__init__.py b/website/scriptfan/extensions/__init__.py deleted file mode 100644 index 044307d..0000000 --- a/website/scriptfan/extensions/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#-*- coding: utf-8 -*- -from flaskext.openid import OpenID -from flask.ext.sqlalchemy import SQLAlchemy -from flask.ext.login import LoginManager - -__all__ = [ 'oid', 'db', 'login_manager' ] - -oid = OpenID() -db = SQLAlchemy() -login_manager = LoginManager() diff --git a/website/scriptfan/utils/filters.py b/website/scriptfan/filters.py similarity index 53% rename from website/scriptfan/utils/filters.py rename to website/scriptfan/filters.py index ba36d56..e17aff8 100644 --- a/website/scriptfan/utils/filters.py +++ b/website/scriptfan/filters.py @@ -1,10 +1,20 @@ -#!/usr/bin/env python #-*-coding:utf-8-*- +""" + scriptfan.filters + ~~~~~~~~~~~~~~~~~~ + + Jiaja2 filters for scriptfan +""" + from datetime import datetime +import markdown2 + +__all__ = ['dateformat', 'empty', 'markdown', + 'error_class', 'error_text', 'time_passed'] -def dateformat(value, format="%Y-%m-%d %H:%M"): - return value.strftime(format) +def dateformat(value, fmt="%Y-%m-%d %H:%M"): + return value.strftime(fmt) def empty(value, text=None): @@ -14,16 +24,20 @@ def empty(value, text=None): return value +def markdown(value): + return value and markdown2.markdown(value) or '' + + def error_class(filed): - """ 用于显示 bootstrap 表单的 control-group 中添加 ``error`` 类 + u""" 用于显示 bootstrap 表单的 control-group 中添加 ``error`` 类 如果表单字段中存在错误,则返回 error,否则返回空。 """ return filed.errors and 'error' or '' -def error_text(field, default='', sep=';'): - """ 如果表单项中存在砥中,则显示错误,否则显示默认文本 """ +def error_text(field, default='', sep='; '): + u""" 如果表单项中存在砥中,则显示错误,否则显示默认文本 """ return field.errors and sep.join(field.errors) or default diff --git a/website/scriptfan/forms/__init__.py b/website/scriptfan/forms/__init__.py index 5fd578b..77513ea 100644 --- a/website/scriptfan/forms/__init__.py +++ b/website/scriptfan/forms/__init__.py @@ -1,18 +1,8 @@ -#-*-coding:utf-8-*- -from flask import request, url_for, redirect -from scriptfan.utils.functions import get_redirect_target, is_safe_url -from flask.ext.wtf import Form, HiddenField +# -*- coding: utf-8 -*- +""" + scriptfan.forms + ~~~~~~~~~~~~~~~~~~~~~` + Forms package for scriptfan +""" -class RedirectForm(Form): - next = HiddenField() - - def __init__(self, *args, **kwargs): - Form.__init__(self, *args, **kwargs) - if not self.next.data: - self.next.data = get_redirect_target() or '' - - def redirect(self, endpoint='index', **values): - if is_safe_url(self.next.data): - return redirect(self.next.data) - target = get_redirect_target() - return redirect(target or url_for(endpoint, **values)) \ No newline at end of file +from .event import EventForm diff --git a/website/scriptfan/forms/articles.py b/website/scriptfan/forms/articles.py new file mode 100644 index 0000000..ed68759 --- /dev/null +++ b/website/scriptfan/forms/articles.py @@ -0,0 +1,27 @@ +#-*- coding: utf-8 -*- + +""" + scriptfan/forms/articles + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Forms for articles and categories +""" + +from flask.ext import wtf +from scriptfan.forms.base import RedirectForm + + +class ArticleForm(RedirectForm): + """ Form for article create and update """ + + title = wtf.TextField('title', validators=[wtf.Required(message=u'请填写标题')]) + content = wtf.TextAreaField('content', validators=[wtf.Required(message=u'文章内容不能为空')]) + # TODO: Fill article category dropdown with categories + # category_id = wtf.SelectField('category_id') + + +class CategoryForm(RedirectForm): + """ Form for category create and update """ + + # TODO: Unique validation for name + name = wtf.TextField("name", validators=[wtf.Required(message=u'名称不能为空')]) diff --git a/website/scriptfan/forms/base.py b/website/scriptfan/forms/base.py new file mode 100644 index 0000000..4505643 --- /dev/null +++ b/website/scriptfan/forms/base.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +""" + scriptfan.forms.base + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + Base redirect form +""" + +from flask import url_for, redirect +from scriptfan.functions import get_redirect_target, is_safe_url +from flask.ext.wtf import Form, HiddenField + +class RedirectForm(Form): + next = HiddenField() + + def __init__(self, *args, **kwargs): + Form.__init__(self, *args, **kwargs) + if not self.next.data: + self.next.data = get_redirect_target() or '' + + def redirect(self, endpoint='index', **values): + if is_safe_url(self.next.data): + return redirect(self.next.data) + target = get_redirect_target() + return redirect(target or url_for(endpoint, **values)) \ No newline at end of file diff --git a/website/scriptfan/forms/activity.py b/website/scriptfan/forms/event.py similarity index 54% rename from website/scriptfan/forms/activity.py rename to website/scriptfan/forms/event.py index c632318..f4992e2 100644 --- a/website/scriptfan/forms/activity.py +++ b/website/scriptfan/forms/event.py @@ -1,21 +1,24 @@ #-*- coding: utf-8 -*- """ - forms/activity.py - ~~~~~~~~~~~~~~~~~~ - 定义活动相关的表单 + scriptfan.forms.event + ~~~~~~~~~~~~~~~~~~~~~~~ + Forms for events """ from flask.ext import wtf -from scriptfan.forms import RedirectForm +from scriptfan.forms.base import RedirectForm +from datetime import date -class ActivityForm(RedirectForm): +class EventForm(RedirectForm): title = wtf.TextField(u'活动标题', validators=[ \ wtf.Required(message=u'请为活动填写一个标题')]) content = wtf.TextAreaField(u'活动简介', validators=[ \ wtf.Length(min=10, max=5000, message=u'简介至少10个字')]) - start_time = wtf.TextField(u'开始时间', validators=[ \ + date = wtf.TextField(u'活动日期', default=date.today, + validators=[ wtf.Required(message=u'需要指定活动日期')]) + start_time = wtf.TextField(u'开始时间', default='13:30', validators=[ \ wtf.Required(message=u'需要指定开始时间')]) - end_time = wtf.TextField(u'结束时间', validators=[ \ + end_time = wtf.TextField(u'结束时间', default='17:00', validators=[ \ wtf.Required(message=u'需要指定结束时间')]) address = wtf.TextField(u'活动地点') latitude = wtf.HiddenField() diff --git a/website/scriptfan/forms/user.py b/website/scriptfan/forms/user.py index 841c8b5..2b58293 100644 --- a/website/scriptfan/forms/user.py +++ b/website/scriptfan/forms/user.py @@ -1,106 +1,95 @@ #-*- coding: utf-8 -*- + """ - forms/user.py - ~~~~~~~~~~~~~~~~~~ - 定义用户相关页面所用到的表单 + scriptfan/forms/users.py + ~~~~~~~~~~~~~~~~~~~~~~~ + 定义用户相关页面所用到的表单, 包括注册、登陆、基本资料修改、密码修改、邮箱修改等。 """ -from flask import session -from scriptfan.models import (get_user, User, UserInfo, UserOpenID) -from scriptfan.forms import RedirectForm + from flask.ext import wtf from flask.ext.login import current_user +from scriptfan.models import User +from scriptfan.forms.base import RedirectForm +from flask.ext.openid import COMMON_PROVIDERS -class SigninForm(wtf.Form): +class SigninForm(RedirectForm): email = wtf.TextField('email', validators=[ wtf.Required(message=u'请填写电子邮件'), wtf.Email(message=u'无效的电子邮件')]) password = wtf.PasswordField('password', validators=[ - wtf.Required(message=u'请填写密码'), - wtf.Length(min=5, max=20, message=u'密应应为5到20位字符')]) - next = wtf.HiddenField('next') + wtf.Required(message=u'请填写密码')]) remember = wtf.BooleanField('remember') - openid_identifier = wtf.HiddenField('openid_identifier') - openid_provider = wtf.HiddenField('openid_provider') + def validate(self): + if not super(RedirectForm, self).validate(): return False + + user = User.get_by_email(self.email.data) + if not user: + self.email.errors.append(u'该邮箱未注册') + elif not user.check_password(self.password.data): + self.password.errors.append(u'密码错误') + else: + self.user = user + + return not self.errors - def __init__(self, *args, **kargs): - wtf.Form.__init__(self, *args, **kargs) - self.user = None - def validate(self): - # 验证邮箱是否注册 - if wtf.Form.validate(self): - user = get_user(email=self.email.data) - if not user: - self.email.errors.append(u'该邮箱尚未在本站注册') - elif not user.check_password(self.password.data): - self.password.errors.append(u'密码错误') - else: - self.user = user - - return len(self.errors) == 0 - -class SignupForm(wtf.Form): +class SignupForm(RedirectForm): email = wtf.TextField('email', validators=[ wtf.Required(message=u'请填写电子邮件'), wtf.Email(message=u'无效的电子邮件')]) nickname = wtf.TextField('nickname', validators=[ - wtf.Required(message=u'请填写昵称'), - wtf.Length(min=2, max=20, message=u'昵称应为2到20字符')]) - password = wtf.PasswordField('password', validators=[ - wtf.Required(message=u'请填写密码'), - wtf.Length(min=5, max=20, message=u'密码应为5到20位字符')]) - repassword = wtf.PasswordField('repassword', validators=[ - wtf.Required(message=u'请填写确认密码'), - wtf.EqualTo('password', message=u'两次输入的密码不一致')]) - next = wtf.HiddenField('next') - - def __init__(self, *args, **kargs): - wtf.Form.__init__(self, *args, **kargs) - self.user = None - - def validate(self): - wtf.Form.validate(self) + wtf.Required(message=u'请填写昵称')]) + password1 = wtf.PasswordField('password1', validators=[ + wtf.Required(message=u'请填写密码')]) + password2 = wtf.PasswordField('password2', validators=[ + wtf.Required(message=u'再次填写密码'), + wtf.EqualTo('password1', message=u'两次输入的密码不一致')]) - # 验证邮箱是否注册 - if not self.email.errors: - user = get_user(email=self.email.data) - user and self.email.errors.append(u'该邮箱已被注册') + def validate_email(form, field): + if User.get_by_email(field.data): + raise wtf.ValidationError(u'该邮箱已被注册') - self.user = User(email=self.email.data, nickname=self.nickname.data, openids=[ - UserOpenID(provider=session['openid_provider'], openid=session['current_openid'])]) - self.user.set_password(self.password.data) - self.user.info = UserInfo() - return len(self.errors) == 0 - -class ProfileForm(wtf.Form): - nickname = wtf.TextField('nickname', validators=[wtf.Required(message=u'请填写昵称')]) - slug = wtf.TextField('slug', validators=[ - wtf.Regexp(regex=r'^([a-zA-Z][a-zA-Z0-9_-]{4,23})?$', message=u'长度应为5~24位,仅能包含数字、英文字母及下划线(_)和减号(-),并且需要以字母开头')]) +class EditProfileForm(RedirectForm): + nickname = wtf.TextField('nickname', validators=[ + wtf.Required(message=u'请填写昵称')]) phone = wtf.TextField('phone', validators=[ wtf.Regexp(regex=r'^(1\d{10})?$', message=u'请输入有效的手机号码')]) - phone_status = wtf.RadioField('phone_status', choices=[ + phone_privacy = wtf.RadioField('phone_privacy', choices=[ ('0', u'不公开'), ('1', u'公开'), ('2', u'仅向会员公开')], default='0') # photo = db.Column(db.String(255), nullable=True) # 存一张照片,既然有线下的聚会的,总得认得人才行 motoo = wtf.TextAreaField('motoo', validators=[ wtf.Length(min=0, max=255, message=u'座右铭最多为255个字符')]) - introduction = wtf.TextAreaField('introduction', validators=[ + intro = wtf.TextAreaField('introduction', validators=[ wtf.Length(min=0, max=3000, message=u'个人介绍最多为3000个字')]) - def __init__(self, *args, **kargs): - wtf.Form.__init__(self, *args, **kargs) - self.user = None -class EditPassForm(RedirectForm): - old_password= wtf.PasswordField(u'当前密码', validators=[wtf.Required(message=u'请提供当前密码')]) - password = wtf.PasswordField(u'新密码', validators=[ \ - wtf.Required(message=u'请填写新密码,不能少与5位字符'), \ - wtf.EqualTo('confirm', message=u'两次输入的密码不一致'), \ - wtf.Length(min=5, max=20, message=u'密码应为5到20位字符') - ]) - confirm = wtf.PasswordField(u'确认密码', validators=[wtf.Required(message=u'请再次输入新密码')]) +class EditPasswordForm(RedirectForm): + old_password = wtf.PasswordField(u'当前密码', validators=[]) + #wtf.Required(message=u'请提供当前密码')]) + password = wtf.PasswordField(u'新密码', validators=[ + wtf.Required(message=u'请填写新密码,不能少与5位字符'), + wtf.Length(min=5, max=20, message=u'密码应为5到20位字符')]) + confirm = wtf.PasswordField(u'确认密码', validators=[ + wtf.Required(message=u'请再次输入新密码'), + wtf.EqualTo('password', message=u'两次输入的密码不一致')]) def validate_old_password(form, field): - if not current_user.user.check_password(field.data): + # 当用户密码为空时,跳过原始密码验证,是否存在安全隐患? + if current_user.user.password and (not current_user.user.check_password(field.data)): raise wtf.ValidationError(u'提供的原始密码不正确') + + +class EditSlugForm(RedirectForm): + # FIXME: 验证 slug 是否已经被占用 + slug = wtf.TextField('slug', validators=[ + wtf.Regexp(regex=r'^([a-zA-Z][a-zA-Z0-9_-]{4,23})?$', + message=u'长度应为5~24位,仅能包含数字、英文字母及下划线(_)和减号(-),并且需要以字母开头')]) + + +class ManageOpenIDForm(RedirectForm): + method = wtf.HiddenField('method', validators=[ + wtf.AnyOf(['add', 'delete'], message=u'不支持该操作'), ]) + provider = wtf.HiddenField('provider', validators=[ + wtf.AnyOf(COMMON_PROVIDERS, message=u'还不能绑定到该OpenID'), ]) diff --git a/website/scriptfan/utils/functions.py b/website/scriptfan/functions.py similarity index 83% rename from website/scriptfan/utils/functions.py rename to website/scriptfan/functions.py index d96e011..aee89ef 100644 --- a/website/scriptfan/utils/functions.py +++ b/website/scriptfan/functions.py @@ -1,4 +1,10 @@ -#-*-coding:utf-8-*- +# -*- coding: utf-8 -*- +""" + scriptfan.functions + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + Common unctions. +""" + import hashlib from urlparse import urlparse, urljoin from flask import request diff --git a/website/scriptfan/models/__init__.py b/website/scriptfan/models/__init__.py index c28128d..124bdb6 100644 --- a/website/scriptfan/models/__init__.py +++ b/website/scriptfan/models/__init__.py @@ -1,190 +1,45 @@ -#!/usr/bin/env python -#-*-coding:utf-8-*- -from flask import request, url_for -from datetime import datetime -from scriptfan.extensions import db -from scriptfan.utils.functions import md5 - -def get_user(slug=None, user_id=None, email=None): - user = None - - if email: - user = User.query.filter_by(email=email).first() - elif slug: - user = User.query.filter_by(slug=slug).first() - elif user_id: - user = User.query.filter_by(id=user_id).first() - - return user - -class UserInfo(db.Model): - """ - 用户信息表 - """ - __tablename__ = 'user_info' - - id = db.Column(db.Integer, primary_key=True) - motoo = db.Column(db.String(255)) # 座右铭 - introduction = db.Column(db.Text) # 个人简介 - phone = db.Column(db.String(15), unique=True, nullable=True) # 手机号码 - phone_status = db.Column(db.Integer, nullable=True) # 手机可见度: 0-不公开 1-公开 2-向成员公开 - photo = db.Column(db.String(255), nullable=True) # 存一张照片,既然有线下的聚会的,总得认得人才行 - - user = db.relationship('User', backref='info', uselist=False) - - def __repr__(self): - return "" % self.user.id - -class User(db.Model): - """ - 用户表 - 修改email地址时需要经过验证 - """ - __tablename__ = 'users' - - id = db.Column(db.Integer, primary_key=True) - email = db.Column(db.String(50), unique=True, nullable=False) # 登陆使用的 - email_status = db.Column(db.Integer, nullable=True, default=0) # 邮箱可见度: 0-不公开 1-公开 2-向成员公开 - nickname = db.Column(db.String(50), unique=True, nullable=False) # 昵称, 显示时用的 - password = db.Column(db.String(50), nullable=True) # 密码 - is_email_verified = db.Column(db.Boolean, nullable=False, default=True) - slug = db.Column(db.String(50), nullable=True) # 用户页面 - created_time = db.Column(db.DateTime, nullable=False, default=datetime.now) # 用户注册时间 - modified_time = db.Column(db.DateTime, nullable=False, default=datetime.now) # 用户更新时间 - last_login_time = db.Column(db.DateTime) # 最后一次登陆时间 - privilege = db.Column(db.Integer, default=3) # 权重:3-普通用户 4-管理员 - - user_info_id = db.Column(db.Integer, db.ForeignKey('user_info.id'), nullable=False) - - openids = db.relationship('UserOpenID', backref=db.backref('user')) - - def __repr__(self): - return "" % (self.nickname, self.email) - - def set_password(self, password): - self.password = md5(password) - - def check_password(self, password): - return self.password == md5(password) - - @property - def url(self): - if self.slug: - return url_for('user.profile', slug=self.slug) - return url_for('user.profile', user_id=self.id) - - def get_avatar_url(self, size=20): - url_tpl = 'http://www.gravatar.com/avatar/%s?size=%s&d=%s%s' - return url_tpl % (md5(self.email), size, request.url_root, url_for('static', filename='images/avatars/default.png')) - -class UserOpenID(db.Model): - """ - 用户绑定OpenID的表 - 一个用户可以对应多个OpenID - """ - __tablename__ = 'user_openids' - - id = db.Column(db.Integer, primary_key=True) - user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) # openid关联的用户 - openid = db.Column(db.String(255), nullable=False, unique=True) # 记录的 openid, 不能重复 - provider = db.Column(db.String(50), nullable=False) # openid的提供商,比如 google - -class Resource(db.Model): - """ - 资源表 - 汇集图片、视频、演示文稿等资源, 用于嵌入活动中 - """ - __tablename__ = 'resources' - id = db.Column(db.Integer, primary_key=True) - user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # 发布者 - filetype = db.Column(db.String(50)) # 类型: video, audio, image, slides, pdf, webpage, ... - url = db.Column(db.String(255)) # 资源地址,可以是外部地址,也可以是内部地址 - created_time = db.Column(db.DateTime) - modified_time = db.Column(db.DateTime) +# -*-coding: utf-8-*- +""" + scriptfan.models + ~~~~~~~~~~~~~~~~~~ + + Model package for scriptfan +""" + +from .user import User +from .user_openid import UserOpenID +from .event import Event +from .event_duration import EventDuration +from .resource import Resource +from .article import Article +from .category import Category +from .book import Book +from .book import BookRecord # 活动相关资源 -topic_resources = db.Table('topic_resources', - db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), - db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), primary_key=True), -) +# topic_resources = db.Table('topic_resources', +# db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), +# db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), primary_key=True), +# ) # 用户参与投票的跟踪表(活动关闭后可清除此表数据) -topic_users = db.Table('topic_users', - db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True), -) - -class Topic(db.Model): - """ - 活动的话题 - """ - __tablename__ = 'topics' - - id = db.Column(db.Integer, primary_key=True) - name = db.Column(db.String(255)) # 话题名称 - inro = db.Column(db.Text) # 简要介绍 - rate_count = db.Column(db.Integer, default=0) # 投票数 - followers = db.relationship(User, secondary=topic_users) # 参与者 - resources = db.relationship(Resource, secondary=topic_resources) # 话题相关资源 - - user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) - user = db.relationship(User, backref='topics', lazy='dynamic') - -# 用户参与活动的跟踪表 -activity_users = db.Table('activity_users', - db.Column('activity_id', db.Integer, db.ForeignKey('activities.id'), primary_key=True), - db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True), -) - -# 活动相关资源 -activity_resources = db.Table('activity_resources', - db.Column('activity_id', db.Integer, db.ForeignKey('activities.id'), primary_key=True), - db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), primary_key=True), -) - - -class Activity(db.Model): - """ - 活动表 - 每期活动需要一个公告 - """ - __tablename__ = 'activities' - - id = db.Column(db.Integer, primary_key=True) - user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # 发起人 - title = db.Column(db.String(255)) # 活动标题 - content = db.Column(db.Text) # 活动介绍 - slug = db.Column(db.String(255)) # 页面地址 - start_time = db.Column(db.DateTime) # 活动开始时间 - end_time = db.Column(db.DateTime) # 活动结束时间 - address = db.Column(db.String(255)) # 活动地址 - longitude = db.Column(db.Numeric(10, 7)) # 经度 - latitude = db.Column(db.Numeric(10, 7)) # 纬度 - created_time = db.Column(db.DateTime) # 活动创建时间 - modified_time = db.Column(db.DateTime) # 活动更新时间 - - followers = db.relationship(User, secondary=activity_users, - backref=db.backref('activities', lazy='dynamic')) # 参与者 - resources = db.relationship(Resource, secondary=activity_resources, - backref=db.backref('activities', lazy='dynamic')) # 话题相关资源 - -class ActivityComment(db.Model): - """ - 活动评论表 - 如果是未注册用户使用openid注册,则仅将openid记录在cookie中 - """ - __tablename__ = 'activity_comments' - - id = db.Column(db.Integer, primary_key=True) - author_name = db.Column(db.String(50), nullable=False) # 作者昵称 - author_email = db.Column(db.String(255)) # 作者邮件地址 - author_site = db.Column(db.String(255)) # 作者网址 - content = db.Column(db.Text, nullable=False) # 评论内容 - created_time = db.Column(db.DateTime) # 创建日期 - modified_time = db.Column(db.DateTime) # 更新日期 - - parent_id = db.Column(db.Integer, db.ForeignKey('activity_comments.id'), nullable=True) - children = db.relationship('ActivityComment', backref='parent', remote_side=[id]) # 回复评论的引用 - - user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) - user = db.relationship('User', backref=db.backref('comments', lazy='dynamic')) +# topic_users = db.Table('topic_users', +# db.Column('topic_id', db.Integer, db.ForeignKey('topics.id'), primary_key=True), +# db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True), +# ) + +# class Topic(db.Model): +# """ +# 活动的话题 +# """ +# __tablename__ = 'topics' +# +# id = db.Column(db.Integer, primary_key=True) +# name = db.Column(db.String(255)) # 话题名称 +# inro = db.Column(db.Text) # 简要介绍 +# rate_count = db.Column(db.Integer, default=0) # 投票数 +# followers = db.relationship(User, secondary=topic_users) # 参与者 +# resources = db.relationship(Resource, secondary=topic_resources) # 话题相关资源 +# +# user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) +# users = db.relationship(User, backref='topics', lazy='dynamic') diff --git a/website/scriptfan/models/article.py b/website/scriptfan/models/article.py new file mode 100644 index 0000000..f93631d --- /dev/null +++ b/website/scriptfan/models/article.py @@ -0,0 +1,27 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.articles + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: articles +""" + +from scriptfan import db +from datetime import datetime + +class Article(db.Model): + __tablename__ = 'articles' + + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String(255), nullable=False) + content = db.Column(db.Text, nullable=True) + #: Parsed html content + content_html = db.Column(db.Text) + author_id = db.Column(db.Integer, db.ForeignKey('users.id')) + category_id = db.Column(db.Integer, db.ForeignKey('categories.id')) + created_time = db.Column(db.DateTime, default=datetime.now) + updated_time = db.Column(db.DateTime, default=datetime.now) + + @classmethod + def get_by_id(cls, id): + return cls.query.filter_by(id=id).first() diff --git a/website/scriptfan/models/book.py b/website/scriptfan/models/book.py new file mode 100644 index 0000000..eed770c --- /dev/null +++ b/website/scriptfan/models/book.py @@ -0,0 +1,38 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.articles + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: articles +""" + +from scriptfan import db +from datetime import datetime + + +class Book(db.Model): + __tablename__ = 'books' + + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(255), nullable=False) + url = db.Column(db.String(255), nullable=True) + isbn = db.Column(db.String(255), nullable=True) + created_time = db.Column(db.DateTime, default=datetime.now) + updated_time = db.Column(db.DateTime, default=datetime.now) + + @classmethod + def get_by_id(cls, id): + return cls.query.filter_by(id=id).first() + + +class BookRecord(db.Model): + __tablename__ = 'book_record' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id')) + book_id = db.Column(db.Integer, db.ForeignKey('books.id')) + created_time = db.Column(db.DateTime, default=datetime.now) + return_time = db.Column(db.DateTime, default=datetime.now) + + user = db.relationship('User', backref=db.backref('users')) + book = db.relationship('Book', backref=db.backref('books')) diff --git a/website/scriptfan/models/category.py b/website/scriptfan/models/category.py new file mode 100644 index 0000000..233eaf0 --- /dev/null +++ b/website/scriptfan/models/category.py @@ -0,0 +1,18 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.category + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: categories +""" + +from scriptfan import db +from datetime import datetime + +class Category(db.Model): + __tablename__ = 'categories' + + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(255), nullable=False, unique=True) + + articles = db.relationship('Article', backref=db.backref('category')) diff --git a/website/scriptfan/models/event.py b/website/scriptfan/models/event.py new file mode 100644 index 0000000..93bd60e --- /dev/null +++ b/website/scriptfan/models/event.py @@ -0,0 +1,52 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.event + ~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: events +""" + +from scriptfan import db + +class Event(db.Model): + """ + 活动表 + 每期活动需要一个公告 + """ + __tablename__ = 'events' + + id = db.Column(db.Integer, primary_key=True) + creator_id = db.Column(db.Integer, db.ForeignKey('users.id')) # 发起人 + title = db.Column(db.String(255)) # 活动标题 + content = db.Column(db.Text) # 活动介绍 + content_html = db.Column(db.Text) # 转换后的省劲介绍内容 + address = db.Column(db.String(255)) # 活动地址 + lat = db.Column(db.Numeric(10, 7)) # 纬度 + lng = db.Column(db.Numeric(10, 7)) # 经度 + created_time = db.Column(db.DateTime) # 活动创建时间 + updated_time = db.Column(db.DateTime) # 活动更新时间 + + durations = db.relationship('EventDuration', backref=db.backref('event')) + + followers = db.relationship('User', secondary='event_members', + backref=db.backref('events', lazy='dynamic')) # 参与者 + resources = db.relationship('Resource', secondary='event_resources', + backref=db.backref('events', lazy='dynamic')) # 话题相关资源 + + +# 用户参与活动的跟踪表 +event_members = db.Table('event_members', + db.Column('event_id', db.Integer, db.ForeignKey('events.id'), + primary_key=True), + db.Column('member_id', db.Integer, db.ForeignKey('users.id'), + primary_key=True), +) + + +# 活动相关资源 +event_resources = db.Table('event_resources', + db.Column('event_id', db.Integer, db.ForeignKey('events.id'), + primary_key=True), + db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'), + primary_key=True), +) \ No newline at end of file diff --git a/website/scriptfan/models/event_duration.py b/website/scriptfan/models/event_duration.py new file mode 100644 index 0000000..565cb68 --- /dev/null +++ b/website/scriptfan/models/event_duration.py @@ -0,0 +1,37 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.event_duration + ~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: event_durations +""" + +from scriptfan import db + +class EventDuration(db.Model): + """Event duration assignment + + Samples: + * 1 Day + - Date: 2013-03-16, Start_Time: 13:30, End_Time: 17:00 + * 2 Days + - Date: 2013-03-16, Start_Time: 09:00, End_Time: 17:00 + - Date: 2013-03-17, Start_Time: 09:30, End_Time: 11:30 + + It seems that ScriptFan will not create an event that repeats by + week/month/year, so the data model is enough. + """ + + __tablename__ = 'event_durations' + + id = db.Column(db.Integer, primary_key=True) + + #: Date part o event. 2013-03-16 + date = db.Column(db.Date) + #: Start time of date part. 13:30 + start_time = db.Column(db.Time, default='13:30') + #: End time of date part. 17:00 + end_time = db.Column(db.Time, default='17:00') + + #: Related event of time duration + event_id = db.Column(db.Integer, db.ForeignKey('events.id'), nullable=False) \ No newline at end of file diff --git a/website/scriptfan/models/resource.py b/website/scriptfan/models/resource.py new file mode 100644 index 0000000..eeeb330 --- /dev/null +++ b/website/scriptfan/models/resource.py @@ -0,0 +1,23 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.resource + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: resources +""" + +from scriptfan import db + + +class Resource(db.Model): + """ + 资源表 + 汇集图片、视频、演示文稿等资源, 用于嵌入活动中 + """ + __tablename__ = 'resources' + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # 发布者 + filetype = db.Column(db.String(50)) # 类型: video, audio, image, slides, pdf, webpage, ... + url = db.Column(db.String(255)) # 资源地址,可以是外部地址,也可以是内部地址 + created_time = db.Column(db.DateTime) + modified_time = db.Column(db.DateTime) diff --git a/website/scriptfan/models/user.py b/website/scriptfan/models/user.py new file mode 100644 index 0000000..5b6a134 --- /dev/null +++ b/website/scriptfan/models/user.py @@ -0,0 +1,83 @@ +# -*-coding: utf-8-*- +""" + scriptfan.models.users + ~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: users +""" + +from scriptfan import db +from flask import current_app as app +from scriptfan.functions import md5 +from datetime import datetime +from flask import url_for, request + +class User(db.Model): + __tablename__ = 'users' + + id = db.Column(db.Integer, primary_key=True) + #: 用户页面的地址后缀,比如 http://scriptfan.com/profile/greatghoul 中的 greatghoul + # 如果要填写,不能重复,因为 slug 要能够唯一标识一个用户 + slug = db.Column(db.String(255), unique=True) + #: 用户的昵称,昵称只是用户的称呼,可能重复 + nickname = db.Column(db.String(255), unique=True, nullable=False) + #: 用户的密码(经过MD5加密的) + password = db.Column(db.String(255)) + #: 邮件地址,可以不填,如果填写,不能重复 + email = db.Column(db.String(255), unique=True) + #: 邮件的隐私度,0为不公开,1为对会员公司,2为完全公开 + email_privacy = db.Column(db.Integer, default=0) + #: 用户的联系电话,可以不填写, 但如果填写的话,不能重复 + phone = db.Column(db.String(255), unique=True) + #: 电话的隐私度,参考 `email_privacy` + phone_privacy = db.Column(db.Integer, default=0) + #: 用户的照片,考虑到是线下社区,所以留张照片能够方便大家互相认识,可以不上传 + photo = db.Column(db.String(255)) + #: 照片的隐私度,参考 `email_privacy` + photo_privacy = db.Column(db.Integer, default=0) + #: 一句话的座右铭 + motoo = db.Column(db.String(255)) + #: 用户的自己介绍,会通过 markdown 转换成 html 文本 + intro = db.Column(db.Text) + #: 上次登陆的时间 + login_time = db.Column(db.DateTime) + #: 注册时间 + created_time = db.Column(db.DateTime, default=datetime.now) + #: 上次更新资料的时间 + updated_time = db.Column(db.DateTime, default=datetime.now) + #: 简单的权限控制,控制级别:3-普通用户 4-管理员 (目前就这么简单,后面再讨论) + privilege = db.Column(db.Integer, default=3) + + #: 用户 openid 的绑定列表 + openids = db.relationship('UserOpenID', backref=db.backref('user')) + + #: User articles + articles = db.relationship('Article', backref=db.backref('author')) + + def __repr__(self): + return u'' % (self.nickname, self.email) + + # 增加一段扰乱信息,这样更难破解 + def set_password(self, password): + self.password = md5(password + app.config['PASSWORD_SALT']) + + def check_password(self, password): + return self.password == md5(password + app.config['PASSWORD_SALT']) + + @classmethod + def get_by_email(cls, email): + return User.query.filter_by(email=email).first() + + @classmethod + def get_by_slug(cls, slug): + return User.query.filter_by(slug=slug).first() + + @property + def url(self): + if self.slug: + return url_for('users.profile', slug=self.slug) + return url_for('users.profile', user_id=self.id) + + def get_avatar_url(self, size=20): + url_tpl = 'http://www.gravatar.com/avatar/%s?size=%s&d=%s%s' + return url_tpl % (md5(self.email), size, request.url_root, url_for('static', filename='images/avatars/default.png')) diff --git a/website/scriptfan/models/user_openid.py b/website/scriptfan/models/user_openid.py new file mode 100644 index 0000000..da5f7c6 --- /dev/null +++ b/website/scriptfan/models/user_openid.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" + scriptfan.models.user_openid + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Model for table: user_openids +""" + +from scriptfan import db + +class UserOpenID(db.Model): + """ 用户OpenID绑定表 """ + + __tablename__ = 'user_openids' + + id = db.Column(db.Integer, primary_key=True) + #: openid 关联的用户 + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), \ + nullable=False) + #: openid 授权的值 + openid = db.Column(db.String(255), nullable=False, unique=True) + #: opendid 提供商, 例如 google + provider = db.Column(db.String(50), nullable=False) diff --git a/website/scriptfan/scriptfan.cfg.sample b/website/scriptfan/scriptfan.cfg.sample index 8ec0e80..1f8721b 100644 --- a/website/scriptfan/scriptfan.cfg.sample +++ b/website/scriptfan/scriptfan.cfg.sample @@ -12,8 +12,14 @@ SECRET_KEY='youshouldnotknowthis' PAGE_SIZE=20 # database settings -SQLALCHEMY_DATABASE_URI='mysql://root:root@localhost/scriptfan_dev?charset=utf8' +SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://root:root@localhost/scriptfan_dev?charset=utf8&use_unicode=1' SQLALCHEMY_ECHO=False # LOGGING CONFIG LOGGER_NAME='scriptfan' + +# babel +BABEL_DEFAULT_LOCALE='zh_CN' + +# 密码盐,用于增加密码的安全性 +PASSWORD_SALT = 'udontkown@must#complicated' diff --git a/website/scriptfan/static/css/activity.css b/website/scriptfan/static/css/activity.css new file mode 100644 index 0000000..5f14e18 --- /dev/null +++ b/website/scriptfan/static/css/activity.css @@ -0,0 +1,8 @@ +#map-canvas { + width: 600px; + height: 400px; +} + +#map-canvas img { + max-width: none; +} diff --git a/website/scriptfan/static/css/articles.css b/website/scriptfan/static/css/articles.css new file mode 100644 index 0000000..7518314 --- /dev/null +++ b/website/scriptfan/static/css/articles.css @@ -0,0 +1,22 @@ +.article-list { + list-style-type: none; + margin-left: 0; + padding-left: 0; +} + +#epiceditor { + width: 100%; + height: 349px; + border-radius: 3px; + background-color: #fff; + margin-bottom: 9px; + border: 1px solid #ccc; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); + -moz-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 linear .2s,box-shadow linear .2s; + -moz-transition: border linear .2s,box-shadow linear .2s; + -o-transition: border linear .2s,box-shadow linear .2s; + transition: border linear .2s,box-shadow linear .2s; +} + diff --git a/website/scriptfan/static/css/styles.css b/website/scriptfan/static/css/styles.css index 426190f..2bae80d 100644 --- a/website/scriptfan/static/css/styles.css +++ b/website/scriptfan/static/css/styles.css @@ -12,31 +12,36 @@ body > div.navbar > div.navbar-inner > div.container > div > form > input { height:26px; } -.container > .content { - -webkit-box-shadow: inset 0 1px 0 white,0 2px 5px #eee; - -moz-box-shadow: inset 0 1px 0 white,0 2px 5px #eee; - box-shadow: inset 0 1px 0 white,0 2px 5px #eee; - border: 1px solid #e6e6e6; - border-bottom-color: #d6d6d6; - background-color: #ffffff; - padding: 10px; - min-height: 38px; - border-radius: 6px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - -moz-background-clip: padding; - -webkit-background-clip: padding-box; - background-clip: padding-box; -} -.content form, -.content .form-actions { - margin-bottom: 0; -} - -.content .page-header { - margin-top: 0; - margin-bottom: 20px; - padding-bottom: 0; +.content { + background-color: white; + padding: 20px; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, .15); + -moz-box-shadow: 0 2px 4px rgba(0,0,0,.15); + box-shadow: 0 2px 4px rgba(0, 0, 0, .15); +} + +.form-horizontal { + margin-bottom: 0px; +} + +.form-actions { + margin: auto -20px -20px -20px; +} + +.page-header { + background-color: whiteSmoke; + padding: 20px 20px 10px; + margin: -20px -20px 20px; + height: 40px; +} + +.page-header h1 { + margin: 0; + font-size: 30px; + line-height: 1; } .page-header .avatar-large { @@ -45,4 +50,8 @@ body > div.navbar > div.navbar-inner > div.container > div > form > input { width: 110px; height: 110px; background: #eeeeee, -} \ No newline at end of file +} + +.sidebar-list { + padding: 9px 0; +} diff --git a/website/scriptfan/static/js/activity.js b/website/scriptfan/static/js/activity.js new file mode 100644 index 0000000..114add3 --- /dev/null +++ b/website/scriptfan/static/js/activity.js @@ -0,0 +1,72 @@ +var xian = new google.maps.LatLng(34.198564,108.895614); +var map, marker, input_address, autocomplete, search; + +function initialize() { + // Initialize map instance + var map_canvas = document.getElementById('map-canvas'); + var map_options = { + zoom: 15, + mapTypeId: google.maps.MapTypeId.ROADMAP, + center: xian + }; + map = new google.maps.Map(map_canvas, map_options); + + // Initialize autocomplete instance + var ac_options = { + bounds: map.getBounds() + // types: ['establishment'] + }; + input_address = document.getElementById('address'); + autocomplete = new google.maps.places.Autocomplete(input_address, ac_options); + autocomplete.bindTo('bounds', map); + autocomplete.addListener('place_changed', place_changed); + + // Initialize marker instance + marker = new google.maps.Marker({ + // map:map, + draggable: true, + animation: google.maps.Animation.DROP + // position: xian + }); + marker.addListener('dragend', marker_dragend); + google.maps.event.addListener(marker, 'click', toggle_bounce); +} + +function place_changed() { + var position = autocomplete.getPlace().geometry.location; + show_position(position); + marker.setPosition(position); + marker.setMap(map); + // map.setCenter(position); + map.panTo(position); + return false; +} + +function marker_dragend() { + var position = marker.getPosition(); + show_position(position); + // map.setCenter(position); + map.panTo(position); // smoothly +} + + +function show_position(position) { + $('#latitude').val(position.lat()); + $('#longitude').val(position.lng()); +} + +function toggle_bounce() { + if (marker.getAnimation() != null) { + marker.setAnimation(null); + } else { + marker.setAnimation(google.maps.Animation.BOUNCE); + } +} + +$(function() { + initialize(); + // 阻止地址输入框回车时提交表单 + $('#address').keydown(function(event) { + return event.keyCode != 13; + }); +}); diff --git a/website/scriptfan/static/js/application.js b/website/scriptfan/static/js/application.js index b0fae60..7a3f61f 100644 --- a/website/scriptfan/static/js/application.js +++ b/website/scriptfan/static/js/application.js @@ -1,3 +1,3 @@ $(function() { - $('.alert-messages .alert').delay(2000).slideUp(); -}); \ No newline at end of file + $('.flash .alert').delay(3000).fadeOut(); +}); diff --git a/website/scriptfan/static/js/articles.js b/website/scriptfan/static/js/articles.js new file mode 100644 index 0000000..9212c83 --- /dev/null +++ b/website/scriptfan/static/js/articles.js @@ -0,0 +1,17 @@ +$(function() { + var editor = new EpicEditor({ + basePath: ENV.STATIC + 'lib/epiceditor', + theme: { + base:'/themes/base/epiceditor.css', + preview:'/themes/preview/preview-dark.css', + editor:'/themes/editor/epic-light.css' + } + }).load(); + editor.importFile('post', $('#content').val()); + + $('#form-article-create').submit(function() { + var content = editor.exportFile(); + $('#content').val(content); + console.log(content); + }); +}); diff --git a/website/scriptfan/static/js/user-edit.js b/website/scriptfan/static/js/user-edit.js index 86808bf..e69de29 100644 --- a/website/scriptfan/static/js/user-edit.js +++ b/website/scriptfan/static/js/user-edit.js @@ -1,11 +0,0 @@ -/** - * 用户资料修改 - * - * @author greatghoul - */ -$(function() { - var $form = $('#form-user-edit'); - var $submit = $form.find(':submit'); - - $form.bform(); -}); diff --git a/website/scriptfan/static/lib/bootstrap.bform.js b/website/scriptfan/static/lib/bootstrap.bform.js deleted file mode 100644 index 249ff3e..0000000 --- a/website/scriptfan/static/lib/bootstrap.bform.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * bootstrap.bform.js v0.1 - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Simple bootstrap form utilities. - */ -!function ($) { - var BForm = function (element, options) { - this.init(element, options); - }; - - BForm.prototype = { - - constructor: BForm, - - init: function (element, options) { - var self = this; - this.isForm = element.tagName === 'FORM'; - this.$element = $(element); - this.options = $.extend({}, $.fn.bform.defaults, options); - this.$alerts = $(this.options.alerts); - - // 如果是表单,绑定提交事件,如果是链接或者按钮,则模拟提交事件 - if (this.isForm) { - this.$element.on('submit', $.proxy(this.submit, this)); - // 保存field中的原有提示信息 - this.$element.find(this.options.fieldHelp).each(function() { - $(this).data('default', $(this).html()); - }); - this.$element.find('[name]').each(function() { - var $field = $(this); - $field.blur(function() { self.clear($field.attr('name')); }); - $field.change(function() { self.clear($field.attr('name')); }); - }); - } else { - this.$element.on('click.bform', $.proxy(this.click, this)); - } - }, - - click: function(event) { - event.preventDefault(); - this.clear(); - - $.ajax({ - url: this.$element.attr('href') || this.$element.data('action'), - dataType: this.options.dataType, - type: this.$element.data('method') || this.options.method, - success: $.proxy(this.success, this), - error: $.proxy(this.error, this) - }); - }, - - submit: function(event) { - event.preventDefault(); - this.clear(); - - $.ajax({ - url: this.$element.attr('action'), - data: this.$element.serialize(), - dataType: this.options.dataType, - type: this.$element.attr('method') || this.options.method, - success: $.proxy(this.success, this), - error: $.proxy(this.error, this) - }); - }, - - success: function(data) { - this.showMessages(data.messages); - var redirect = null; - - if (data.success) { - redirect = data.redirect || this.options.redirect; - } else { - this.showErrors(data.errors); - } - - this.$alerts.find('.alert').delay(this.options.delay).fadeOut(function() { - if (redirect) window.location = redirect; - $(this).remove(); - }); - }, - - error: function(jqXHR, textStatus, errorThrown) { - this.showMessages({ error: '服务器错误,请稍候再试'}); - }, - - clear: function(field) { - this.$alerts.empty(); - - if (field) { - var $field = this.$element.find(fmt('[name="%{1}"]', field)); - $field.parents('.control-group').removeClass('error'); - var $help = this.getFieldHelp($field); - var data = $help.data('default'); - data !== undefined && $help.html(data); - } else { - this.$element.find('.control-group').removeClass('error'); - this.$element.find(this.options.fieldHelp).each(function() { - var $help = $(this); - var data = $help.data('default'); - data !== undefined && $help.html(data); - }); - } - }, - - getFieldHelp: function($field) { - var $help = $field.nextAll(this.options.fieldHelp); - if ($help.size() === 0) { - $help = $field.parents('.controls').find(this.options.fieldHelp); - } - return $help; - }, - - showErrors: function(errors) { - var $this = this; - $.each(errors || {}, function(field, message) { - var $field = $this.$element.find(fmt('[name="%{1}"]', field)); - $field.parents('.control-group').addClass('error'); - $this.getFieldHelp($field).html($.isArray(message) ? message[0] : message); - }); - }, - - showMessages: function(messages) { - var $this = this; - $.each(messages || {}, function(category, message) { - $this.$alerts.append(fmt($this.options.tpls.alert, category, message)); - }); - } - }; - - /* PRIVATE FUNCTIONS - *=================*/ - function fmt() { - var args = arguments; - return args[0].replace(/%\{(.*?)}/g, function(match, prop) { - return function(obj, props) { - var prop = /\d+/.test(props[0]) ? parseInt(props[0]) : props[0]; - if (props.length > 1) { - return arguments.callee(obj[prop], props.slice(1)); - } else { - return obj[prop] || ''; - } - }(typeof args[1] === 'object' ? args[1] : args, prop.split(/\.|\[|\]\[|\]\./)); - }); - } - - /* BOOTSTRAP FORM PLUGIN DEFINITION - * ========================= */ - - $.fn.bform = function ( option ) { - return this.each(function () { - var $this = $(this); - var data = $this.data('bform'); - var options = typeof option == 'object' && option; - if (!data) $this.data('bform', (data = new BForm(this, options))); - if (typeof option == 'string') data[option](); - }); - }; - - $.fn.bform.Constructor = BForm; - - $.fn.bform.defaults = { - method: 'GET', - dataType: 'json', - alerts: '.alert-messages', - fieldHelp: '.help-inline, .help-block', - tpls: { - alert: '
%{2}
' - }, - redirect: window.location.toString(), - delay: 1000 - } -}(window.jQuery); \ No newline at end of file diff --git a/website/scriptfan/static/lib/epiceditor/images/edit.png b/website/scriptfan/static/lib/epiceditor/images/edit.png new file mode 100644 index 0000000..ebb9e93 Binary files /dev/null and b/website/scriptfan/static/lib/epiceditor/images/edit.png differ diff --git a/website/scriptfan/static/lib/epiceditor/images/fullscreen.png b/website/scriptfan/static/lib/epiceditor/images/fullscreen.png new file mode 100644 index 0000000..04cf59e Binary files /dev/null and b/website/scriptfan/static/lib/epiceditor/images/fullscreen.png differ diff --git a/website/scriptfan/static/lib/epiceditor/images/preview.png b/website/scriptfan/static/lib/epiceditor/images/preview.png new file mode 100644 index 0000000..4fa34f6 Binary files /dev/null and b/website/scriptfan/static/lib/epiceditor/images/preview.png differ diff --git a/website/scriptfan/static/lib/epiceditor/js/epiceditor.js b/website/scriptfan/static/lib/epiceditor/js/epiceditor.js new file mode 100644 index 0000000..c53d89a --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/js/epiceditor.js @@ -0,0 +1,2141 @@ +/** + * EpicEditor - An Embeddable JavaScript Markdown Editor (https://github.com/OscarGodson/EpicEditor) + * Copyright (c) 2011-2012, Oscar Godson. (MIT Licensed) + */ + +(function (window, undefined) { + /** + * Applies attributes to a DOM object + * @param {object} context The DOM obj you want to apply the attributes to + * @param {object} attrs A key/value pair of attributes you want to apply + * @returns {undefined} + */ + function _applyAttrs(context, attrs) { + for (var attr in attrs) { + if (attrs.hasOwnProperty(attr)) { + context[attr] = attrs[attr]; + } + } + } + + /** + * Applies styles to a DOM object + * @param {object} context The DOM obj you want to apply the attributes to + * @param {object} attrs A key/value pair of attributes you want to apply + * @returns {undefined} + */ + function _applyStyles(context, attrs) { + for (var attr in attrs) { + if (attrs.hasOwnProperty(attr)) { + context.style[attr] = attrs[attr]; + } + } + } + + /** + * Returns a DOM objects computed style + * @param {object} el The element you want to get the style from + * @param {string} styleProp The property you want to get from the element + * @returns {string} Returns a string of the value. If property is not set it will return a blank string + */ + function _getStyle(el, styleProp) { + var x = el + , y = null; + if (window.getComputedStyle) { + y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); + } + else if (x.currentStyle) { + y = x.currentStyle[styleProp]; + } + return y; + } + + /** + * Saves the current style state for the styles requested, then applys styles + * to overwrite the existing one. The old styles are returned as an object so + * you can pass it back in when you want to revert back to the old style + * @param {object} el The element to get the styles of + * @param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles + * @param {object} styles Key/value style/property pairs + * @returns {object} + */ + function _saveStyleState(el, type, styles) { + var returnState = {} + , style; + if (type === 'save') { + for (style in styles) { + if (styles.hasOwnProperty(style)) { + returnState[style] = _getStyle(el, style); + } + } + // After it's all done saving all the previous states, change the styles + _applyStyles(el, styles); + } + else if (type === 'apply') { + _applyStyles(el, styles); + } + return returnState; + } + + /** + * Gets an elements total width including it's borders and padding + * @param {object} el The element to get the total width of + * @returns {int} + */ + function _outerWidth(el) { + var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10) + , p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10) + , w = el.offsetWidth + , t; + // For IE in case no border is set and it defaults to "medium" + if (isNaN(b)) { b = 0; } + t = b + p + w; + return t; + } + + /** + * Gets an elements total height including it's borders and padding + * @param {object} el The element to get the total width of + * @returns {int} + */ + function _outerHeight(el) { + var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10) + , p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10) + , w = el.offsetHeight + , t; + // For IE in case no border is set and it defaults to "medium" + if (isNaN(b)) { b = 0; } + t = b + p + w; + return t; + } + + /** + * Inserts a tag specifically for CSS + * @param {string} path The path to the CSS file + * @param {object} context In what context you want to apply this to (document, iframe, etc) + * @param {string} id An id for you to reference later for changing properties of the + * @returns {undefined} + */ + function _insertCSSLink(path, context, id) { + id = id || ''; + var headID = context.getElementsByTagName("head")[0] + , cssNode = context.createElement('link'); + + _applyAttrs(cssNode, { + type: 'text/css' + , id: id + , rel: 'stylesheet' + , href: path + , name: path + , media: 'screen' + }); + + headID.appendChild(cssNode); + } + + // Simply replaces a class (o), to a new class (n) on an element provided (e) + function _replaceClass(e, o, n) { + e.className = e.className.replace(o, n); + } + + // Feature detects an iframe to get the inner document for writing to + function _getIframeInnards(el) { + return el.contentDocument || el.contentWindow.document; + } + + // Grabs the text from an element and preserves whitespace + function _getText(el) { + var theText; + // Make sure to check for type of string because if the body of the page + // doesn't have any text it'll be "" which is falsey and will go into + // the else which is meant for Firefox and shit will break + if (typeof document.body.innerText == 'string') { + theText = el.innerText; + } + else { + // First replace
s before replacing the rest of the HTML + theText = el.innerHTML.replace(/
/gi, "\n"); + // Now we can clean the HTML + theText = theText.replace(/<(?:.|\n)*?>/gm, ''); + // Now fix HTML entities + theText = theText.replace(/</gi, '<'); + theText = theText.replace(/>/gi, '>'); + } + return theText; + } + + function _setText(el, content) { + // If you want to know why we check for typeof string, see comment + // in the _getText function + if (typeof document.body.innerText == 'string') { + content = content.replace(/ /g, '\u00a0'); + el.innerText = content; + } + else { + // Don't convert lt/gt characters as HTML when viewing the editor window + // TODO: Write a test to catch regressions for this + content = content.replace(//g, '>'); + content = content.replace(/\n/g, '
'); + // Make sure to look for TWO spaces and replace with a space and   + // If you find and replace every space with a   text will not wrap. + // Hence the name (Non-Breaking-SPace). + content = content.replace(/\s\s/g, '  ') + el.innerHTML = content; + } + return true; + } + + /** + * Will return the version number if the browser is IE. If not will return -1 + * TRY NEVER TO USE THIS AND USE FEATURE DETECTION IF POSSIBLE + * @returns {Number} -1 if false or the version number if true + */ + function _isIE() { + var rv = -1 // Return value assumes failure. + , ua = navigator.userAgent + , re; + if (navigator.appName == 'Microsoft Internet Explorer') { + re = /MSIE ([0-9]{1,}[\.0-9]{0,})/; + if (re.exec(ua) != null) { + rv = parseFloat(RegExp.$1, 10); + } + } + return rv; + } + + /** + * Same as the isIE(), but simply returns a boolean + * THIS IS TERRIBLE AND IS ONLY USED BECAUSE FULLSCREEN IN SAFARI IS BORKED + * If some other engine uses WebKit and has support for fullscreen they + * probably wont get native fullscreen until Safari's fullscreen is fixed + * @returns {Boolean} true if Safari + */ + function _isSafari() { + var n = window.navigator; + return n.userAgent.indexOf('Safari') > -1 && n.userAgent.indexOf('Chrome') == -1; + } + + /** + * Determines if supplied value is a function + * @param {object} object to determine type + */ + function _isFunction(functionToCheck) { + var getType = {}; + return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; + } + + /** + * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 + * @param {boolean} [deepMerge=false] If true, will deep merge meaning it will merge sub-objects like {obj:obj2{foo:'bar'}} + * @param {object} first object + * @param {object} second object + * @returnss {object} a new object based on obj1 and obj2 + */ + function _mergeObjs() { + // copy reference to target object + var target = arguments[0] || {} + , i = 1 + , length = arguments.length + , deep = false + , options + , name + , src + , copy + + // Handle a deep copy situation + if (typeof target === "boolean") { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if (typeof target !== "object" && !_isFunction(target)) { + target = {}; + } + // extend jQuery itself if only one argument is passed + if (length === i) { + target = this; + --i; + } + + for (; i < length; i++) { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) { + // Extend the base object + for (name in options) { + // @NOTE: added hasOwnProperty check + if (options.hasOwnProperty(name)) { + src = target[name]; + copy = options[name]; + // Prevent never-ending loop + if (target === copy) { + continue; + } + // Recurse if we're merging object values + if (deep && copy && typeof copy === "object" && !copy.nodeType) { + target[name] = _mergeObjs(deep, + // Never move original objects, clone them + src || (copy.length != null ? [] : {}) + , copy); + } else if (copy !== undefined) { // Don't bring in undefined values + target[name] = copy; + } + } + } + } + } + + // Return the modified object + return target; + } + + /** + * Initiates the EpicEditor object and sets up offline storage as well + * @class Represents an EpicEditor instance + * @param {object} options An optional customization object + * @returns {object} EpicEditor will be returned + */ + function EpicEditor(options) { + // Default settings will be overwritten/extended by options arg + var self = this + , opts = options || {} + , _defaultFileSchema + , _defaultFile + , defaults = { container: 'epiceditor' + , basePath: 'epiceditor' + , clientSideStorage: true + , localStorageName: 'epiceditor' + , useNativeFullscreen: true + , file: { name: null + , defaultContent: '' + , autoSave: 100 // Set to false for no auto saving + } + , theme: { base: '/themes/base/epiceditor.css' + , preview: '/themes/preview/github.css' + , editor: '/themes/editor/epic-dark.css' + } + , focusOnLoad: false + , shortcut: { modifier: 18 // alt keycode + , fullscreen: 70 // f keycode + , preview: 80 // p keycode + } + , parser: typeof marked == 'function' ? marked : null + } + , defaultStorage; + + self.settings = _mergeObjs(true, defaults, opts); + + if (!(typeof self.settings.parser == 'function' && typeof self.settings.parser('TEST') == 'string')) { + self.settings.parser = function (str) { + return str; + } + } + + + // Grab the container element and save it to self.element + // if it's a string assume it's an ID and if it's an object + // assume it's a DOM element + if (typeof self.settings.container == 'string') { + self.element = document.getElementById(self.settings.container); + } + else if (typeof self.settings.container == 'object') { + self.element = self.settings.container; + } + + // Figure out the file name. If no file name is given we'll use the ID. + // If there's no ID either we'll use a namespaced file name that's incremented + // based on the calling order. As long as it doesn't change, drafts will be saved. + if (!self.settings.file.name) { + if (typeof self.settings.container == 'string') { + self.settings.file.name = self.settings.container; + } + else if (typeof self.settings.container == 'object') { + if (self.element.id) { + self.settings.file.name = self.element.id; + } + else { + if (!EpicEditor._data.unnamedEditors) { + EpicEditor._data.unnamedEditors = []; + } + EpicEditor._data.unnamedEditors.push(self); + self.settings.file.name = '__epiceditor-untitled-' + EpicEditor._data.unnamedEditors.length; + } + } + } + + // Protect the id and overwrite if passed in as an option + // TODO: Put underscrore to denote that this is private + self._instanceId = 'epiceditor-' + Math.round(Math.random() * 100000); + self._storage = {}; + self._canSave = true; + + // Setup local storage of files + self._defaultFileSchema = function () { + return { + content: self.settings.file.defaultContent + , created: new Date() + , modified: new Date() + } + } + + if (localStorage && self.settings.clientSideStorage) { + this._storage = localStorage; + if (this._storage[self.settings.localStorageName] && self.getFiles(self.settings.file.name) === undefined) { + _defaultFile = self.getFiles(self.settings.file.name); + _defaultFile = self._defaultFileSchema(); + _defaultFile.content = self.settings.file.defaultContent; + } + } + + if (!this._storage[self.settings.localStorageName]) { + defaultStorage = {}; + defaultStorage[self.settings.file.name] = self._defaultFileSchema(); + defaultStorage = JSON.stringify(defaultStorage); + this._storage[self.settings.localStorageName] = defaultStorage; + } + + // This needs to replace the use of classes to check the state of EE + self._eeState = { + fullscreen: false + , preview: false + , edit: false + , loaded: false + , unloaded: false + } + + // Now that it exists, allow binding of events if it doesn't exist yet + if (!self.events) { + self.events = {}; + } + + return this; + } + + /** + * Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.load = function (callback) { + + // Get out early if it's already loaded + if (this.is('loaded')) { return this; } + + // TODO: Gotta get the privates with underscores! + // TODO: Gotta document what these are for... + var self = this + , _HtmlTemplates + , iframeElement + , baseTag + , utilBtns + , utilBar + , utilBarTimer + , keypressTimer + , mousePos = { y: -1, x: -1 } + , _elementStates + , _isInEdit + , nativeFs = false + , fsElement + , isMod = false + , isCtrl = false + , eventableIframes + , i; // i is reused for loops + + if (self.settings.useNativeFullscreen) { + nativeFs = document.body.webkitRequestFullScreen ? true : false + } + + // Fucking Safari's native fullscreen works terribly + // REMOVE THIS IF SAFARI 7 WORKS BETTER + if (_isSafari()) { + nativeFs = false; + } + + // It opens edit mode by default (for now); + if (!self.is('edit') && !self.is('preview')) { + self._eeState.edit = true; + } + + callback = callback || function () {}; + + // The editor HTML + // TODO: edit-mode class should be dynamically added + _HtmlTemplates = { + // This is wrapping iframe element. It contains the other two iframes and the utilbar + chrome: '
' + + '' + + '' + + '
' + + ' ' + + ' ' + + '' + + '
' + + '
' + + // The previewer is just an empty box for the generated HTML to go into + , previewer: '
' + }; + + // Write an iframe and then select it for the editor + self.element.innerHTML = ''; + + // Because browsers add things like invisible padding and margins and stuff + // to iframes, we need to set manually set the height so that the height + // doesn't keep increasing (by 2px?) every time reflow() is called. + // FIXME: Figure out how to fix this without setting this + self.element.style.height = self.element.offsetHeight + 'px'; + + iframeElement = document.getElementById(self._instanceId); + + // Store a reference to the iframeElement itself + self.iframeElement = iframeElement; + + // Grab the innards of the iframe (returns the document.body) + // TODO: Change self.iframe to self.iframeDocument + self.iframe = _getIframeInnards(iframeElement); + self.iframe.open(); + self.iframe.write(_HtmlTemplates.chrome); + + // Now that we got the innards of the iframe, we can grab the other iframes + self.editorIframe = self.iframe.getElementById('epiceditor-editor-frame') + self.previewerIframe = self.iframe.getElementById('epiceditor-previewer-frame'); + + // Setup the editor iframe + self.editorIframeDocument = _getIframeInnards(self.editorIframe); + self.editorIframeDocument.open(); + // Need something for... you guessed it, Firefox + self.editorIframeDocument.write(''); + self.editorIframeDocument.close(); + + // Setup the previewer iframe + self.previewerIframeDocument = _getIframeInnards(self.previewerIframe); + self.previewerIframeDocument.open(); + self.previewerIframeDocument.write(_HtmlTemplates.previewer); + + // Base tag is added so that links will open a new tab and not inside of the iframes + baseTag = self.previewerIframeDocument.createElement('base'); + baseTag.target = '_blank'; + self.previewerIframeDocument.getElementsByTagName('head')[0].appendChild(baseTag); + + self.previewerIframeDocument.close(); + + self.reflow(); + + // Insert Base Stylesheet + _insertCSSLink(self.settings.basePath + self.settings.theme.base, self.iframe, 'theme'); + + // Insert Editor Stylesheet + _insertCSSLink(self.settings.basePath + self.settings.theme.editor, self.editorIframeDocument, 'theme'); + + // Insert Previewer Stylesheet + _insertCSSLink(self.settings.basePath + self.settings.theme.preview, self.previewerIframeDocument, 'theme'); + + // Add a relative style to the overall wrapper to keep CSS relative to the editor + self.iframe.getElementById('epiceditor-wrapper').style.position = 'relative'; + + // Now grab the editor and previewer for later use + self.editor = self.editorIframeDocument.body; + self.previewer = self.previewerIframeDocument.getElementById('epiceditor-preview'); + + self.editor.contentEditable = true; + + // Firefox's gets all fucked up so, to be sure, we need to hardcode it + self.iframe.body.style.height = this.element.offsetHeight + 'px'; + + // Should actually check what mode it's in! + this.previewerIframe.style.display = 'none'; + + // FIXME figure out why it needs +2 px + if (_isIE() > -1) { + this.previewer.style.height = parseInt(_getStyle(this.previewer, 'height'), 10) + 2; + } + + // If there is a file to be opened with that filename and it has content... + this.open(self.settings.file.name); + + if (self.settings.focusOnLoad) { + // We need to wait until all three iframes are done loading by waiting until the parent + // iframe's ready state == complete, then we can focus on the contenteditable + self.iframe.addEventListener('readystatechange', function () { + if (self.iframe.readyState == 'complete') { + self.editorIframeDocument.body.focus(); + } + }); + } + + utilBtns = self.iframe.getElementById('epiceditor-utilbar'); + + _elementStates = {} + self._goFullscreen = function (el) { + + if (self.is('fullscreen')) { + self._exitFullscreen(el); + return; + } + + if (nativeFs) { + el.webkitRequestFullScreen(); + } + + _isInEdit = self.is('edit'); + + // Set the state of EE in fullscreen + // We set edit and preview to true also because they're visible + // we might want to allow fullscreen edit mode without preview (like a "zen" mode) + self._eeState.fullscreen = true; + self._eeState.edit = true; + self._eeState.preview = true; + + // Cache calculations + var windowInnerWidth = window.innerWidth + , windowInnerHeight = window.innerHeight + , windowOuterWidth = window.outerWidth + , windowOuterHeight = window.outerHeight; + + // Without this the scrollbars will get hidden when scrolled to the bottom in faux fullscreen (see #66) + if (!nativeFs) { + windowOuterHeight = window.innerHeight; + } + + // This MUST come first because the editor is 100% width so if we change the width of the iframe or wrapper + // the editor's width wont be the same as before + _elementStates.editorIframe = _saveStyleState(self.editorIframe, 'save', { + 'width': windowOuterWidth / 2 + 'px' + , 'height': windowOuterHeight + 'px' + , 'float': 'left' // Most browsers + , 'cssFloat': 'left' // FF + , 'styleFloat': 'left' // Older IEs + , 'display': 'block' + }); + + // the previewer + _elementStates.previewerIframe = _saveStyleState(self.previewerIframe, 'save', { + 'width': windowOuterWidth / 2 + 'px' + , 'height': windowOuterHeight + 'px' + , 'float': 'right' // Most browsers + , 'cssFloat': 'right' // FF + , 'styleFloat': 'right' // Older IEs + , 'display': 'block' + }); + + // Setup the containing element CSS for fullscreen + _elementStates.element = _saveStyleState(self.element, 'save', { + 'position': 'fixed' + , 'top': '0' + , 'left': '0' + , 'width': '100%' + , 'z-index': '9999' // Most browsers + , 'zIndex': '9999' // Firefox + , 'border': 'none' + , 'margin': '0' + // Should use the base styles background! + , 'background': _getStyle(self.editor, 'background-color') // Try to hide the site below + , 'height': windowInnerHeight + 'px' + }); + + // The iframe element + _elementStates.iframeElement = _saveStyleState(self.iframeElement, 'save', { + 'width': windowOuterWidth + 'px' + , 'height': windowInnerHeight + 'px' + }); + + // ...Oh, and hide the buttons and prevent scrolling + utilBtns.style.visibility = 'hidden'; + + if (!nativeFs) { + document.body.style.overflow = 'hidden'; + } + + self.preview(); + + self.editorIframeDocument.body.focus(); + + self.emit('fullscreenenter'); + }; + + self._exitFullscreen = function (el) { + _saveStyleState(self.element, 'apply', _elementStates.element); + _saveStyleState(self.iframeElement, 'apply', _elementStates.iframeElement); + _saveStyleState(self.editorIframe, 'apply', _elementStates.editorIframe); + _saveStyleState(self.previewerIframe, 'apply', _elementStates.previewerIframe); + + // We want to always revert back to the original styles in the CSS so, + // if it's a fluid width container it will expand on resize and not get + // stuck at a specific width after closing fullscreen. + self.element.style.width = self._eeState.reflowWidth ? self._eeState.reflowWidth : ''; + self.element.style.height = self._eeState.reflowHeight ? self._eeState.reflowHeight : ''; + + utilBtns.style.visibility = 'visible'; + + if (!nativeFs) { + document.body.style.overflow = 'auto'; + } + else { + document.webkitCancelFullScreen(); + } + // Put the editor back in the right state + // TODO: This is ugly... how do we make this nicer? + self._eeState.fullscreen = false; + + if (_isInEdit) { + self.edit(); + } + else { + self.preview(); + } + + self.reflow(); + + self.emit('fullscreenexit'); + }; + + // This setups up live previews by triggering preview() IF in fullscreen on keyup + self.editor.addEventListener('keyup', function () { + if (keypressTimer) { + window.clearTimeout(keypressTimer); + } + keypressTimer = window.setTimeout(function () { + if (self.is('fullscreen')) { + self.preview(); + } + }, 250); + }); + + fsElement = self.iframeElement; + + // Sets up the onclick event on utility buttons + utilBtns.addEventListener('click', function (e) { + var targetClass = e.target.className; + if (targetClass.indexOf('epiceditor-toggle-preview-btn') > -1) { + self.preview(); + } + else if (targetClass.indexOf('epiceditor-toggle-edit-btn') > -1) { + self.edit(); + } + else if (targetClass.indexOf('epiceditor-fullscreen-btn') > -1) { + self._goFullscreen(fsElement); + } + }); + + // Sets up the NATIVE fullscreen editor/previewer for WebKit + if (document.body.webkitRequestFullScreen) { + fsElement.addEventListener('webkitfullscreenchange', function () { + if (!document.webkitIsFullScreen) { + self._exitFullscreen(fsElement); + } + }, false); + } + + utilBar = self.iframe.getElementById('epiceditor-utilbar'); + + // Hide it at first until they move their mouse + utilBar.style.display = 'none'; + + utilBar.addEventListener('mouseover', function () { + if (utilBarTimer) { + clearTimeout(utilBarTimer); + } + }); + + function utilBarHandler(e) { + // Here we check if the mouse has moves more than 5px in any direction before triggering the mousemove code + // we do this for 2 reasons: + // 1. On Mac OS X lion when you scroll and it does the iOS like "jump" when it hits the top/bottom of the page itll fire off + // a mousemove of a few pixels depending on how hard you scroll + // 2. We give a slight buffer to the user in case he barely touches his touchpad or mouse and not trigger the UI + if (Math.abs(mousePos.y - e.pageY) >= 5 || Math.abs(mousePos.x - e.pageX) >= 5) { + utilBar.style.display = 'block'; + // if we have a timer already running, kill it out + if (utilBarTimer) { + clearTimeout(utilBarTimer); + } + + // begin a new timer that hides our object after 1000 ms + utilBarTimer = window.setTimeout(function () { + utilBar.style.display = 'none'; + }, 1000); + } + mousePos = { y: e.pageY, x: e.pageX }; + } + + // Add keyboard shortcuts for convenience. + function shortcutHandler(e) { + if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var + if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s + + // Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview + if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) { + e.preventDefault(); + if (self.is('edit')) { + self.preview(); + } + else { + self.edit(); + } + } + // Check for alt+f - default shortcut to make editor fullscreen + if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen) { + e.preventDefault(); + self._goFullscreen(fsElement); + } + + // Set the modifier key to false once *any* key combo is completed + // or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133) + if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) { + isMod = false; + } + + // When a user presses "esc", revert everything! + if (e.keyCode == 27 && self.is('fullscreen')) { + self._exitFullscreen(fsElement); + } + + // Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing + if (isCtrl === true && e.keyCode == 83) { + self.save(); + e.preventDefault(); + isCtrl = false; + } + + // Do the same for Mac now (metaKey == cmd). + if (e.metaKey && e.keyCode == 83) { + self.save(); + e.preventDefault(); + } + + } + + function shortcutUpHandler(e) { + if (e.keyCode == self.settings.shortcut.modifier) { isMod = false } + if (e.keyCode == 17) { isCtrl = false } + } + + // Hide and show the util bar based on mouse movements + eventableIframes = [self.previewerIframeDocument, self.editorIframeDocument]; + + for (i = 0; i < eventableIframes.length; i++) { + eventableIframes[i].addEventListener('mousemove', function (e) { + utilBarHandler(e); + }); + eventableIframes[i].addEventListener('scroll', function (e) { + utilBarHandler(e); + }); + eventableIframes[i].addEventListener('keyup', function (e) { + shortcutUpHandler(e); + }); + eventableIframes[i].addEventListener('keydown', function (e) { + shortcutHandler(e); + }); + } + + // Save the document every 100ms by default + if (self.settings.file.autoSave) { + self.saveInterval = window.setInterval(function () { + if (!self._canSave) { + return; + } + self.save(); + }, self.settings.file.autoSave); + } + + window.addEventListener('resize', function () { + // If NOT webkit, and in fullscreen, we need to account for browser resizing + // we don't care about webkit because you can't resize in webkit's fullscreen + if (!self.iframe.webkitRequestFullScreen && self.is('fullscreen')) { + _applyStyles(self.iframeElement, { + 'width': window.outerWidth + 'px' + , 'height': window.innerHeight + 'px' + }); + + _applyStyles(self.element, { + 'height': window.innerHeight + 'px' + }); + + _applyStyles(self.previewerIframe, { + 'width': window.outerWidth / 2 + 'px' + , 'height': window.innerHeight + 'px' + }); + + _applyStyles(self.editorIframe, { + 'width': window.outerWidth / 2 + 'px' + , 'height': window.innerHeight + 'px' + }); + } + // Makes the editor support fluid width when not in fullscreen mode + else if (!self.is('fullscreen')) { + self.reflow(); + } + }); + + // Set states before flipping edit and preview modes + self._eeState.loaded = true; + self._eeState.unloaded = false; + + if (self.is('preview')) { + self.preview(); + } + else { + self.edit(); + } + + self.iframe.close(); + // The callback and call are the same thing, but different ways to access them + callback.call(this); + this.emit('load'); + return this; + } + + /** + * Will remove the editor, but not offline files + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.unload = function (callback) { + + // Make sure the editor isn't already unloaded. + if (this.is('unloaded')) { + throw new Error('Editor isn\'t loaded'); + } + + var self = this + , editor = window.parent.document.getElementById(self._instanceId); + + editor.parentNode.removeChild(editor); + self._eeState.loaded = false; + self._eeState.unloaded = true; + callback = callback || function () {}; + + if (self.saveInterval) { + window.clearInterval(self.saveInterval); + } + + callback.call(this); + self.emit('unload'); + return self; + } + + /** + * reflow allows you to dynamically re-fit the editor in the parent without + * having to unload and then reload the editor again. + * + * @param {string} kind Can either be 'width' or 'height' or null + * if null, both the height and width will be resized + * + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.reflow = function (kind) { + var self = this + , widthDiff = _outerWidth(self.element) - self.element.offsetWidth + , heightDiff = _outerHeight(self.element) - self.element.offsetHeight + , elements = [self.iframeElement, self.editorIframe, self.previewerIframe] + , newWidth + , newHeight; + + + for (var x = 0; x < elements.length; x++) { + if (!kind || kind == 'width') { + newWidth = self.element.offsetWidth - widthDiff + 'px'; + elements[x].style.width = newWidth; + self._eeState.reflowWidth = newWidth; + } + if (!kind || kind == 'height') { + newHeight = self.element.offsetHeight - heightDiff + 'px'; + elements[x].style.height = newHeight; + self._eeState.reflowHeight = newHeight + } + } + return self; + } + + /** + * Will take the markdown and generate a preview view based on the theme + * @param {string} theme The path to the theme you want to preview in + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.preview = function (theme) { + var self = this + , x + , anchors; + + theme = theme || self.settings.basePath + self.settings.theme.preview; + + _replaceClass(self.getElement('wrapper'), 'epiceditor-edit-mode', 'epiceditor-preview-mode'); + + // Check if no CSS theme link exists + if (!self.previewerIframeDocument.getElementById('theme')) { + _insertCSSLink(theme, self.previewerIframeDocument, 'theme'); + } + else if (self.previewerIframeDocument.getElementById('theme').name !== theme) { + self.previewerIframeDocument.getElementById('theme').href = theme; + } + + // Add the generated HTML into the previewer + self.previewer.innerHTML = self.exportFile(null, 'html'); + + // Because we have a tag so all links open in a new window we + // need to prevent hash links from opening in a new window + anchors = self.previewer.getElementsByTagName('a'); + for (x in anchors) { + // If the link is a hash AND the links hostname is the same as the + // current window's hostname (same page) then set the target to self + if (anchors[x].hash && anchors[x].hostname == window.location.hostname) { + anchors[x].target = '_self'; + } + } + + // Hide the editor and display the previewer + if (!self.is('fullscreen')) { + self.editorIframe.style.display = 'none'; + self.previewerIframe.style.display = 'block'; + self._eeState.preview = true; + self._eeState.edit = false; + self.previewerIframe.focus(); + } + + self.emit('preview'); + return self; + } + + /** + * Puts the editor into fullscreen mode + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.enterFullscreen = function () { + if (this.is('fullscreen')) { return this; } + this._goFullscreen(this.iframeElement); + return this; + } + + /** + * Closes fullscreen mode if opened + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.exitFullscreen = function () { + if (!this.is('fullscreen')) { return this; } + this._exitFullscreen(this.iframeElement); + return this; + } + + /** + * Hides the preview and shows the editor again + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.edit = function () { + var self = this; + _replaceClass(self.getElement('wrapper'), 'epiceditor-preview-mode', 'epiceditor-edit-mode'); + self._eeState.preview = false; + self._eeState.edit = true; + self.editorIframe.style.display = 'block'; + self.previewerIframe.style.display = 'none'; + self.editorIframe.focus(); + self.emit('edit'); + return this; + } + + /** + * Grabs a specificed HTML node. Use it as a shortcut to getting the iframe contents + * @param {String} name The name of the node (can be document, body, editor, previewer, or wrapper) + * @returns {Object|Null} + */ + EpicEditor.prototype.getElement = function (name) { + var available = { + "container": this.element + , "wrapper": this.iframe.getElementById('epiceditor-wrapper') + , "wrapperIframe": this.iframeElement + , "editor": this.editorIframeDocument + , "editorIframe": this.editorIframe + , "previewer": this.previewerIframeDocument + , "previewerIframe": this.previewerIframe + } + + // Check that the given string is a possible option and verify the editor isn't unloaded + // without this, you'd be given a reference to an object that no longer exists in the DOM + if (!available[name] || this.is('unloaded')) { + return null; + } + else { + return available[name]; + } + } + + /** + * Returns a boolean of each "state" of the editor. For example "editor.is('loaded')" // returns true/false + * @param {String} what the state you want to check for + * @returns {Boolean} + */ + EpicEditor.prototype.is = function (what) { + var self = this; + switch (what) { + case 'loaded': + return self._eeState.loaded; + case 'unloaded': + return self._eeState.unloaded + case 'preview': + return self._eeState.preview + case 'edit': + return self._eeState.edit; + case 'fullscreen': + return self._eeState.fullscreen; + default: + return false; + } + } + + /** + * Opens a file + * @param {string} name The name of the file you want to open + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.open = function (name) { + var self = this + , defaultContent = self.settings.file.defaultContent + , fileObj; + name = name || self.settings.file.name; + self.settings.file.name = name; + if (this._storage[self.settings.localStorageName]) { + fileObj = self.getFiles(); + if (fileObj[name] !== undefined) { + _setText(self.editor, fileObj[name].content); + self.emit('read'); + } + else { + _setText(self.editor, defaultContent); + self.save(); // ensure a save + self.emit('create'); + } + self.previewer.innerHTML = self.exportFile(null, 'html'); + self.emit('open'); + } + return this; + } + + /** + * Saves content for offline use + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.save = function () { + var self = this + , storage + , isUpdate = false + , file = self.settings.file.name + , content = _getText(this.editor); + + // This could have been false but since we're manually saving + // we know it's save to start autoSaving again + this._canSave = true; + + storage = JSON.parse(this._storage[self.settings.localStorageName]); + + // If the file doesn't exist we need to create it + if (storage[file] === undefined) { + storage[file] = self._defaultFileSchema(); + } + + // If it does, we need to check if the content is different and + // if it is, send the update event and update the timestamp + else if (content !== storage[file].content) { + storage[file].modified = new Date(); + isUpdate = true; + } + + storage[file].content = content; + this._storage[self.settings.localStorageName] = JSON.stringify(storage); + + // After the content is actually changed, emit update so it emits the updated content + if (isUpdate) { + self.emit('update'); + } + + this.emit('save'); + return this; + } + + /** + * Removes a page + * @param {string} name The name of the file you want to remove from localStorage + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.remove = function (name) { + var self = this + , s; + name = name || self.settings.file.name; + + // If you're trying to delete a page you have open, block saving + if (name == self.settings.file.name) { + self._canSave = false; + } + + s = JSON.parse(this._storage[self.settings.localStorageName]); + delete s[name]; + this._storage[self.settings.localStorageName] = JSON.stringify(s); + this.emit('remove'); + return this; + }; + + /** + * Renames a file + * @param {string} oldName The old file name + * @param {string} newName The new file name + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.rename = function (oldName, newName) { + var self = this + , s = JSON.parse(this._storage[self.settings.localStorageName]); + s[newName] = s[oldName]; + delete s[oldName]; + this._storage[self.settings.localStorageName] = JSON.stringify(s); + self.open(newName); + return this; + }; + + /** + * Imports a file and it's contents and opens it + * @param {string} name The name of the file you want to import (will overwrite existing files!) + * @param {string} content Content of the file you want to import + * @param {string} kind The kind of file you want to import (TBI) + * @param {object} meta Meta data you want to save with your file. + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.importFile = function (name, content, kind, meta) { + var self = this + , isNew = false; + + name = name || self.settings.file.name; + content = content || ''; + kind = kind || 'md'; + meta = meta || {}; + + if (JSON.parse(this._storage[self.settings.localStorageName])[name] === undefined) { + isNew = true; + } + + // Set our current file to the new file and update the content + self.settings.file.name = name; + _setText(self.editor, content); + + if (isNew) { + self.emit('create'); + } + + self.save(); + + if (self.is('fullscreen')) { + self.preview(); + } + + return this; + }; + + /** + * Exports a file as a string in a supported format + * @param {string} name Name of the file you want to export (case sensitive) + * @param {string} kind Kind of file you want the content in (currently supports html and text) + * @returns {string|undefined} The content of the file in the content given or undefined if it doesn't exist + */ + EpicEditor.prototype.exportFile = function (name, kind) { + var self = this + , file + , content; + + name = name || self.settings.file.name; + kind = kind || 'text'; + + file = self.getFiles(name); + + // If the file doesn't exist just return early with undefined + if (file === undefined) { + return; + } + + content = file.content; + + switch (kind) { + case 'html': + // Get this, 2 spaces in a content editable actually converts to: + // 0020 00a0, meaning, "space no-break space". So, manually convert + // no-break spaces to spaces again before handing to marked. + // Also, WebKit converts no-break to unicode equivalent and FF HTML. + content = content.replace(/\u00a0/g, ' ').replace(/ /g, ' '); + return self.settings.parser(content); + case 'text': + content = content.replace(/\u00a0/g, ' ').replace(/ /g, ' '); + return content; + default: + return content; + } + } + + EpicEditor.prototype.getFiles = function (name) { + var files = JSON.parse(this._storage[this.settings.localStorageName]); + if (name) { + return files[name]; + } + else { + return files; + } + } + + // EVENTS + // TODO: Support for namespacing events like "preview.foo" + /** + * Sets up an event handler for a specified event + * @param {string} ev The event name + * @param {function} handler The callback to run when the event fires + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.on = function (ev, handler) { + var self = this; + if (!this.events[ev]) { + this.events[ev] = []; + } + this.events[ev].push(handler); + return self; + }; + + /** + * This will emit or "trigger" an event specified + * @param {string} ev The event name + * @param {any} data Any data you want to pass into the callback + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.emit = function (ev, data) { + var self = this + , x; + + data = data || self.getFiles(self.settings.file.name); + + if (!this.events[ev]) { + return; + } + + function invokeHandler(handler) { + handler.call(self, data); + } + + for (x = 0; x < self.events[ev].length; x++) { + invokeHandler(self.events[ev][x]); + } + + return self; + }; + + /** + * Will remove any listeners added from EpicEditor.on() + * @param {string} ev The event name + * @param {function} handler Handler to remove + * @returns {object} EpicEditor will be returned + */ + EpicEditor.prototype.removeListener = function (ev, handler) { + var self = this; + if (!handler) { + this.events[ev] = []; + return self; + } + if (!this.events[ev]) { + return self; + } + // Otherwise a handler and event exist, so take care of it + this.events[ev].splice(this.events[ev].indexOf(handler), 1); + return self; + } + + EpicEditor.version = '0.2.0'; + + // Used to store information to be shared across editors + EpicEditor._data = {}; + + window.EpicEditor = EpicEditor; +})(window); + +/** + * marked - A markdown parser (https://github.com/chjj/marked) + * Copyright (c) 2011-2012, Christopher Jeffrey. (MIT Licensed) + */ + +;(function() { + +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^( *[-*_]){3,} *(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, + lheading: /^([^\n]+)\n *(=|-){3,} *\n*/, + blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/, + list: /^( *)(bull) [^\0]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, + def: /^ *\[([^\]]+)\]: *([^\s]+)(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, + paragraph: /^([^\n]+\n?(?!body))+\n*/, + text: /^[^\n]+/ +}; + +block.bullet = /(?:[*+-]|\d+\.)/; +block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; +block.item = replace(block.item, 'gm') + (/bull/g, block.bullet) + (); + +block.list = replace(block.list) + (/bull/g, block.bullet) + ('hr', /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/) + (); + +block.html = replace(block.html) + ('comment', //) + ('closed', /<(tag)[^\0]+?<\/\1>/) + ('closing', /])*?>/) + (/tag/g, tag()) + (); + +block.paragraph = (function() { + var paragraph = block.paragraph.source + , body = []; + + (function push(rule) { + rule = block[rule] ? block[rule].source : rule; + body.push(rule.replace(/(^|[^\[])\^/g, '$1')); + return push; + }) + ('hr') + ('heading') + ('lheading') + ('blockquote') + ('<' + tag()) + ('def'); + + return new + RegExp(paragraph.replace('body', body.join('|'))); +})(); + +block.normal = { + fences: block.fences, + paragraph: block.paragraph +}; + +block.gfm = { + fences: /^ *``` *(\w+)? *\n([^\0]+?)\s*``` *(?:\n+|$)/, + paragraph: /^/ +}; + +block.gfm.paragraph = replace(block.paragraph) + ('(?!', '(?!' + block.gfm.fences.source.replace(/(^|[^\[])\^/g, '$1') + '|') + (); + +/** + * Block Lexer + */ + +block.lexer = function(src) { + var tokens = []; + + tokens.links = {}; + + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' '); + + return block.token(src, tokens, true); +}; + +block.token = function(src, tokens, top) { + var src = src.replace(/^ +$/gm, '') + , next + , loose + , cap + , item + , space + , i + , l; + + while (src) { + // newline + if (cap = block.newline.exec(src)) { + src = src.substring(cap[0].length); + if (cap[0].length > 1) { + tokens.push({ + type: 'space' + }); + } + } + + // code + if (cap = block.code.exec(src)) { + src = src.substring(cap[0].length); + cap = cap[0].replace(/^ {4}/gm, ''); + tokens.push({ + type: 'code', + text: !options.pedantic + ? cap.replace(/\n+$/, '') + : cap + }); + continue; + } + + // fences (gfm) + if (cap = block.fences.exec(src)) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'code', + lang: cap[1], + text: cap[2] + }); + continue; + } + + // heading + if (cap = block.heading.exec(src)) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }); + continue; + } + + // lheading + if (cap = block.lheading.exec(src)) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }); + continue; + } + + // hr + if (cap = block.hr.exec(src)) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'hr' + }); + continue; + } + + // blockquote + if (cap = block.blockquote.exec(src)) { + src = src.substring(cap[0].length); + + tokens.push({ + type: 'blockquote_start' + }); + + cap = cap[0].replace(/^ *> ?/gm, ''); + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + block.token(cap, tokens, top); + + tokens.push({ + type: 'blockquote_end' + }); + + continue; + } + + // list + if (cap = block.list.exec(src)) { + src = src.substring(cap[0].length); + + tokens.push({ + type: 'list_start', + ordered: isFinite(cap[2]) + }); + + // Get each top-level item. + cap = cap[0].match(block.item); + + next = false; + l = cap.length; + i = 0; + + for (; i < l; i++) { + item = cap[i]; + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length; + item = item.replace(/^ *([*+-]|\d+\.) +/, ''); + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length; + item = !options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, ''); + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item); + if (i !== l - 1) { + next = item[item.length-1] === '\n'; + if (!loose) loose = next; + } + + tokens.push({ + type: loose + ? 'loose_item_start' + : 'list_item_start' + }); + + // Recurse. + block.token(item, tokens); + + tokens.push({ + type: 'list_item_end' + }); + } + + tokens.push({ + type: 'list_end' + }); + + continue; + } + + // html + if (cap = block.html.exec(src)) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'html', + pre: cap[1] === 'pre', + text: cap[0] + }); + continue; + } + + // def + if (top && (cap = block.def.exec(src))) { + src = src.substring(cap[0].length); + tokens.links[cap[1].toLowerCase()] = { + href: cap[2], + title: cap[3] + }; + continue; + } + + // top-level paragraph + if (top && (cap = block.paragraph.exec(src))) { + src = src.substring(cap[0].length); + tokens.push({ + type: 'paragraph', + text: cap[0] + }); + continue; + } + + // text + if (cap = block.text.exec(src)) { + // Top-level should never reach here. + src = src.substring(cap[0].length); + tokens.push({ + type: 'text', + text: cap[0] + }); + continue; + } + } + + return tokens; +}; + +/** + * Inline Processing + */ + +var inline = { + escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, + autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, + url: noop, + tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, + link: /^!?\[(inside)\]\(href\)/, + reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, + nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, + strong: /^__([^\0]+?)__(?!_)|^\*\*([^\0]+?)\*\*(?!\*)/, + em: /^\b_((?:__|[^\0])+?)_\b|^\*((?:\*\*|[^\0])+?)\*(?!\*)/, + code: /^(`+)([^\0]*?[^`])\1(?!`)/, + br: /^ {2,}\n(?!\s*$)/, + text: /^[^\0]+?(?=[\\?(?:\s+['"]([^\0]*?)['"])?\s*/; + +inline.link = replace(inline.link) + ('inside', inline._linkInside) + ('href', inline._linkHref) + (); + +inline.reflink = replace(inline.reflink) + ('inside', inline._linkInside) + (); + +inline.normal = { + url: inline.url, + strong: inline.strong, + em: inline.em, + text: inline.text +}; + +inline.pedantic = { + strong: /^__(?=\S)([^\0]*?\S)__(?!_)|^\*\*(?=\S)([^\0]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([^\0]*?\S)_(?!_)|^\*(?=\S)([^\0]*?\S)\*(?!\*)/ +}; + +inline.gfm = { + url: /^(https?:\/\/[^\s]+[^.,:;"')\]\s])/, + text: /^[^\0]+?(?=[\\' + + text + + ''; + continue; + } + + // url (gfm) + if (cap = inline.url.exec(src)) { + src = src.substring(cap[0].length); + text = escape(cap[1]); + href = text; + out += '' + + text + + ''; + continue; + } + + // tag + if (cap = inline.tag.exec(src)) { + src = src.substring(cap[0].length); + out += options.sanitize + ? escape(cap[0]) + : cap[0]; + continue; + } + + // link + if (cap = inline.link.exec(src)) { + src = src.substring(cap[0].length); + out += outputLink(cap, { + href: cap[2], + title: cap[3] + }); + continue; + } + + // reflink, nolink + if ((cap = inline.reflink.exec(src)) + || (cap = inline.nolink.exec(src))) { + src = src.substring(cap[0].length); + link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = links[link.toLowerCase()]; + if (!link || !link.href) { + out += cap[0][0]; + src = cap[0].substring(1) + src; + continue; + } + out += outputLink(cap, link); + continue; + } + + // strong + if (cap = inline.strong.exec(src)) { + src = src.substring(cap[0].length); + out += '' + + inline.lexer(cap[2] || cap[1]) + + ''; + continue; + } + + // em + if (cap = inline.em.exec(src)) { + src = src.substring(cap[0].length); + out += '' + + inline.lexer(cap[2] || cap[1]) + + ''; + continue; + } + + // code + if (cap = inline.code.exec(src)) { + src = src.substring(cap[0].length); + out += '' + + escape(cap[2], true) + + ''; + continue; + } + + // br + if (cap = inline.br.exec(src)) { + src = src.substring(cap[0].length); + out += '
'; + continue; + } + + // text + if (cap = inline.text.exec(src)) { + src = src.substring(cap[0].length); + out += escape(cap[0]); + continue; + } + } + + return out; +}; + +function outputLink(cap, link) { + if (cap[0][0] !== '!') { + return '' + + inline.lexer(cap[1]) + + ''; + } else { + return ''
+      + escape(cap[1])
+      + ''; + } +} + +/** + * Parsing + */ + +var tokens + , token; + +function next() { + return token = tokens.pop(); +} + +function tok() { + switch (token.type) { + case 'space': { + return ''; + } + case 'hr': { + return '
\n'; + } + case 'heading': { + return '' + + inline.lexer(token.text) + + '\n'; + } + case 'code': { + if (options.highlight) { + token.code = options.highlight(token.text, token.lang); + if (token.code != null && token.code !== token.text) { + token.escaped = true; + token.text = token.code; + } + } + + if (!token.escaped) { + token.text = escape(token.text, true); + } + + return '
'
+        + token.text
+        + '
\n'; + } + case 'blockquote_start': { + var body = ''; + + while (next().type !== 'blockquote_end') { + body += tok(); + } + + return '
\n' + + body + + '
\n'; + } + case 'list_start': { + var type = token.ordered ? 'ol' : 'ul' + , body = ''; + + while (next().type !== 'list_end') { + body += tok(); + } + + return '<' + + type + + '>\n' + + body + + '\n'; + } + case 'list_item_start': { + var body = ''; + + while (next().type !== 'list_item_end') { + body += token.type === 'text' + ? parseText() + : tok(); + } + + return '
  • ' + + body + + '
  • \n'; + } + case 'loose_item_start': { + var body = ''; + + while (next().type !== 'list_item_end') { + body += tok(); + } + + return '
  • ' + + body + + '
  • \n'; + } + case 'html': { + if (options.sanitize) { + return inline.lexer(token.text); + } + return !token.pre && !options.pedantic + ? inline.lexer(token.text) + : token.text; + } + case 'paragraph': { + return '

    ' + + inline.lexer(token.text) + + '

    \n'; + } + case 'text': { + return '

    ' + + parseText() + + '

    \n'; + } + } +} + +function parseText() { + var body = token.text + , top; + + while ((top = tokens[tokens.length-1]) + && top.type === 'text') { + body += '\n' + next().text; + } + + return inline.lexer(body); +} + +function parse(src) { + tokens = src.reverse(); + + var out = ''; + while (next()) { + out += tok(); + } + + tokens = null; + token = null; + + return out; +} + +/** + * Helpers + */ + +function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function mangle(text) { + var out = '' + , l = text.length + , i = 0 + , ch; + + for (; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + + return out; +} + +function tag() { + var tag = '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + + '|span|br|wbr|ins|del|img)\\b)\\w+'; + + return tag; +} + +function replace(regex, opt) { + regex = regex.source; + opt = opt || ''; + return function self(name, val) { + if (!name) return new RegExp(regex, opt); + regex = regex.replace(name, val.source || val); + return self; + }; +} + +function noop() {} +noop.exec = noop; + +/** + * Marked + */ + +function marked(src, opt) { + setOptions(opt); + return parse(block.lexer(src)); +} + +/** + * Options + */ + +var options + , defaults; + +function setOptions(opt) { + if (!opt) opt = defaults; + if (options === opt) return; + options = opt; + + if (options.gfm) { + block.fences = block.gfm.fences; + block.paragraph = block.gfm.paragraph; + inline.text = inline.gfm.text; + inline.url = inline.gfm.url; + } else { + block.fences = block.normal.fences; + block.paragraph = block.normal.paragraph; + inline.text = inline.normal.text; + inline.url = inline.normal.url; + } + + if (options.pedantic) { + inline.em = inline.pedantic.em; + inline.strong = inline.pedantic.strong; + } else { + inline.em = inline.normal.em; + inline.strong = inline.normal.strong; + } +} + +marked.options = +marked.setOptions = function(opt) { + defaults = opt; + setOptions(opt); + return marked; +}; + +marked.setOptions({ + gfm: true, + pedantic: false, + sanitize: false, + highlight: null +}); + +/** + * Expose + */ + +marked.parser = function(src, opt) { + setOptions(opt); + return parse(src); +}; + +marked.lexer = function(src, opt) { + setOptions(opt); + return block.lexer(src); +}; + +marked.parse = marked; + +if (typeof module !== 'undefined') { + module.exports = marked; +} else { + this.marked = marked; +} + +}).call(function() { + return this || (typeof window !== 'undefined' ? window : global); +}()); diff --git a/website/scriptfan/static/lib/epiceditor/js/epiceditor.min.js b/website/scriptfan/static/lib/epiceditor/js/epiceditor.min.js new file mode 100644 index 0000000..f2f68d5 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/js/epiceditor.min.js @@ -0,0 +1,4 @@ +/** + * EpicEditor - An Embeddable JavaScript Markdown Editor (https://github.com/OscarGodson/EpicEditor) + * Copyright (c) 2011-2012, Oscar Godson. (MIT Licensed) + */(function(e,t){function n(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function r(e,t){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n])}function i(t,n){var r=t,i=null;return e.getComputedStyle?i=document.defaultView.getComputedStyle(r,null).getPropertyValue(n):r.currentStyle&&(i=r.currentStyle[n]),i}function s(e,t,n){var s={},o;if(t==="save"){for(o in n)n.hasOwnProperty(o)&&(s[o]=i(e,o));r(e,n)}else t==="apply"&&r(e,n);return s}function o(e){var t=parseInt(i(e,"border-left-width"),10)+parseInt(i(e,"border-right-width"),10),n=parseInt(i(e,"padding-left"),10)+parseInt(i(e,"padding-right"),10),r=e.offsetWidth,s;return isNaN(t)&&(t=0),s=t+n+r,s}function u(e){var t=parseInt(i(e,"border-top-width"),10)+parseInt(i(e,"border-bottom-width"),10),n=parseInt(i(e,"padding-top"),10)+parseInt(i(e,"padding-bottom"),10),r=e.offsetHeight,s;return isNaN(t)&&(t=0),s=t+n+r,s}function a(e,t,r){r=r||"";var i=t.getElementsByTagName("head")[0],s=t.createElement("link");n(s,{type:"text/css",id:r,rel:"stylesheet",href:e,name:e,media:"screen"}),i.appendChild(s)}function f(e,t,n){e.className=e.className.replace(t,n)}function l(e){return e.contentDocument||e.contentWindow.document}function c(e){var t;return typeof document.body.innerText=="string"?t=e.innerText:(t=e.innerHTML.replace(/
    /gi,"\n"),t=t.replace(/<(?:.|\n)*?>/gm,""),t=t.replace(/</gi,"<"),t=t.replace(/>/gi,">")),t}function h(e,t){return typeof document.body.innerText=="string"?(t=t.replace(/ /g," "),e.innerText=t):(t=t.replace(//g,">"),t=t.replace(/\n/g,"
    "),t=t.replace(/\s\s/g,"  "),e.innerHTML=t),!0}function p(){var e=-1,t=navigator.userAgent,n;return navigator.appName=="Microsoft Internet Explorer"&&(n=/MSIE ([0-9]{1,}[\.0-9]{0,})/,n.exec(t)!=null&&(e=parseFloat(RegExp.$1,10))),e}function d(){var t=e.navigator;return t.userAgent.indexOf("Safari")>-1&&t.userAgent.indexOf("Chrome")==-1}function v(e){var t={};return e&&t.toString.call(e)==="[object Function]"}function m(){var e=arguments[0]||{},n=1,r=arguments.length,i=!1,s,o,u,a;typeof e=="boolean"&&(i=e,e=arguments[1]||{},n=2),typeof e!="object"&&!v(e)&&(e={}),r===n&&(e=this,--n);for(;n=5||Math.abs(g.x-t.pageX)>=5)h.style.display="block",v&&clearTimeout(v),v=e.setTimeout(function(){h.style.display="none"},1e3);g={y:t.pageY,x:t.pageX}}function k(e){e.keyCode==n.settings.shortcut.modifier&&(S=!0),e.keyCode==17&&(x=!0),S===!0&&e.keyCode==n.settings.shortcut.preview&&!n.is("fullscreen")&&(e.preventDefault(),n.is("edit")?n.preview():n.edit()),S===!0&&e.keyCode==n.settings.shortcut.fullscreen&&(e.preventDefault(),n._goFullscreen(E)),S===!0&&e.keyCode!==n.settings.shortcut.modifier&&(S=!1),e.keyCode==27&&n.is("fullscreen")&&n._exitFullscreen(E),x===!0&&e.keyCode==83&&(n.save(),e.preventDefault(),x=!1),e.metaKey&&e.keyCode==83&&(n.save(),e.preventDefault())}function L(e){e.keyCode==n.settings.shortcut.modifier&&(S=!1),e.keyCode==17&&(x=!1)}if(this.is("loaded"))return this;var n=this,o,u,f,c,h,v,m,g={y:-1,x:-1},y,b,w=!1,E,S=!1,x=!1,T,N;n.settings.useNativeFullscreen&&(w=document.body.webkitRequestFullScreen?!0:!1),d()&&(w=!1),!n.is("edit")&&!n.is("preview")&&(n._eeState.edit=!0),t=t||function(){},o={chrome:'
    '+' '+''+"
    "+"
    ",previewer:'
    '},n.element.innerHTML='',n.element.style.height=n.element.offsetHeight+"px",u=document.getElementById(n._instanceId),n.iframeElement=u,n.iframe=l(u),n.iframe.open(),n.iframe.write(o.chrome),n.editorIframe=n.iframe.getElementById("epiceditor-editor-frame"),n.previewerIframe=n.iframe.getElementById("epiceditor-previewer-frame"),n.editorIframeDocument=l(n.editorIframe),n.editorIframeDocument.open(),n.editorIframeDocument.write(""),n.editorIframeDocument.close(),n.previewerIframeDocument=l(n.previewerIframe),n.previewerIframeDocument.open(),n.previewerIframeDocument.write(o.previewer),f=n.previewerIframeDocument.createElement("base"),f.target="_blank",n.previewerIframeDocument.getElementsByTagName("head")[0].appendChild(f),n.previewerIframeDocument.close(),n.reflow(),a(n.settings.basePath+n.settings.theme.base,n.iframe,"theme"),a(n.settings.basePath+n.settings.theme.editor,n.editorIframeDocument,"theme"),a(n.settings.basePath+n.settings.theme.preview,n.previewerIframeDocument,"theme"),n.iframe.getElementById("epiceditor-wrapper").style.position="relative",n.editor=n.editorIframeDocument.body,n.previewer=n.previewerIframeDocument.getElementById("epiceditor-preview"),n.editor.contentEditable=!0,n.iframe.body.style.height=this.element.offsetHeight+"px",this.previewerIframe.style.display="none",p()>-1&&(this.previewer.style.height=parseInt(i(this.previewer,"height"),10)+2),this.open(n.settings.file.name),n.settings.focusOnLoad&&n.iframe.addEventListener("readystatechange",function(){n.iframe.readyState=="complete"&&n.editorIframeDocument.body.focus()}),c=n.iframe.getElementById("epiceditor-utilbar"),y={},n._goFullscreen=function(t){if(n.is("fullscreen")){n._exitFullscreen(t);return}w&&t.webkitRequestFullScreen(),b=n.is("edit"),n._eeState.fullscreen=!0,n._eeState.edit=!0,n._eeState.preview=!0;var r=e.innerWidth,o=e.innerHeight,u=e.outerWidth,a=e.outerHeight;w||(a=e.innerHeight),y.editorIframe=s(n.editorIframe,"save",{width:u/2+"px",height:a+"px","float":"left",cssFloat:"left",styleFloat:"left",display:"block"}),y.previewerIframe=s(n.previewerIframe,"save",{width:u/2+"px",height:a+"px","float":"right",cssFloat:"right",styleFloat:"right",display:"block"}),y.element=s(n.element,"save",{position:"fixed",top:"0",left:"0",width:"100%","z-index":"9999",zIndex:"9999",border:"none",margin:"0",background:i(n.editor,"background-color"),height:o+"px"}),y.iframeElement=s(n.iframeElement,"save",{width:u+"px",height:o+"px"}),c.style.visibility="hidden",w||(document.body.style.overflow="hidden"),n.preview(),n.editorIframeDocument.body.focus(),n.emit("fullscreenenter")},n._exitFullscreen=function(e){s(n.element,"apply",y.element),s(n.iframeElement,"apply",y.iframeElement),s(n.editorIframe,"apply",y.editorIframe),s(n.previewerIframe,"apply",y.previewerIframe),n.element.style.width=n._eeState.reflowWidth?n._eeState.reflowWidth:"",n.element.style.height=n._eeState.reflowHeight?n._eeState.reflowHeight:"",c.style.visibility="visible",w?document.webkitCancelFullScreen():document.body.style.overflow="auto",n._eeState.fullscreen=!1,b?n.edit():n.preview(),n.reflow(),n.emit("fullscreenexit")},n.editor.addEventListener("keyup",function(){m&&e.clearTimeout(m),m=e.setTimeout(function(){n.is("fullscreen")&&n.preview()},250)}),E=n.iframeElement,c.addEventListener("click",function(e){var t=e.target.className;t.indexOf("epiceditor-toggle-preview-btn")>-1?n.preview():t.indexOf("epiceditor-toggle-edit-btn")>-1?n.edit():t.indexOf("epiceditor-fullscreen-btn")>-1&&n._goFullscreen(E)}),document.body.webkitRequestFullScreen&&E.addEventListener("webkitfullscreenchange",function(){document.webkitIsFullScreen||n._exitFullscreen(E)},!1),h=n.iframe.getElementById("epiceditor-utilbar"),h.style.display="none",h.addEventListener("mouseover",function(){v&&clearTimeout(v)}),T=[n.previewerIframeDocument,n.editorIframeDocument];for(N=0;N"+t.lexer(e[1])+"":''+f(e[1])+'"}function s(){return i=r.pop()}function o(){switch(i.type){case"space":return"";case"hr":return"
    \n";case"heading":return""+t.lexer(i.text)+"\n";case"code":return v.highlight&&(i.code=v.highlight(i.text,i.lang),i.code!=null&&i.code!==i.text&&(i.escaped=!0,i.text=i.code)),i.escaped||(i.text=f(i.text,!0)),"
    "+i.text+"
    \n";case"blockquote_start":var e="";while(s().type!=="blockquote_end")e+=o();return"
    \n"+e+"
    \n";case"list_start":var n=i.ordered?"ol":"ul",e="";while(s().type!=="list_end")e+=o();return"<"+n+">\n"+e+"\n";case"list_item_start":var e="";while(s().type!=="list_item_end")e+=i.type==="text"?u():o();return"
  • "+e+"
  • \n";case"loose_item_start":var e="";while(s().type!=="list_item_end")e+=o();return"
  • "+e+"
  • \n";case"html":return v.sanitize?t.lexer(i.text):!i.pre&&!v.pedantic?t.lexer(i.text):i.text;case"paragraph":return"

    "+t.lexer(i.text)+"

    \n";case"text":return"

    "+u()+"

    \n"}}function u(){var e=i.text,n;while((n=r[r.length-1])&&n.type==="text")e+="\n"+s().text;return t.lexer(e)}function a(e){r=e.reverse();var t="";while(s())t+=o();return r=null,i=null,t}function f(e,t){return e.replace(t?/&/g:/&(?!#?\w+;)/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function l(e){var t="",n=e.length,r=0,i;for(;r.5&&(i="x"+i.toString(16)),t+="&#"+i+";";return t}function c(){var e="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+";return e}function h(e,t){return e=e.source,t=t||"",function n(r,i){return r?(e=e.replace(r,i.source||i),n):new RegExp(e,t)}}function p(){}function d(t,n){return g(n),a(e.lexer(t))}function g(n){n||(n=m);if(v===n)return;v=n,v.gfm?(e.fences=e.gfm.fences,e.paragraph=e.gfm.paragraph,t.text=t.gfm.text,t.url=t.gfm.url):(e.fences=e.normal.fences,e.paragraph=e.normal.paragraph,t.text=t.normal.text,t.url=t.normal.url),v.pedantic?(t.em=t.pedantic.em,t.strong=t.pedantic.strong):(t.em=t.normal.em,t.strong=t.normal.strong)}var e={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:p,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,lheading:/^([^\n]+)\n *(=|-){3,} *\n*/,blockquote:/^( *>[^\n]+(\n[^\n]+)*\n*)+/,list:/^( *)(bull) [^\0]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,def:/^ *\[([^\]]+)\]: *([^\s]+)(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,paragraph:/^([^\n]+\n?(?!body))+\n*/,text:/^[^\n]+/};e.bullet=/(?:[*+-]|\d+\.)/,e.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,e.item=h(e.item,"gm")(/bull/g,e.bullet)(),e.list=h(e.list)(/bull/g,e.bullet)("hr",/\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/)(),e.html=h(e.html)("comment",//)("closed",/<(tag)[^\0]+?<\/\1>/)("closing",/])*?>/)(/tag/g,c())(),e.paragraph=function(){var t=e.paragraph.source,n=[];return function r(t){return t=e[t]?e[t].source:t,n.push(t.replace(/(^|[^\[])\^/g,"$1")),r}("hr")("heading")("lheading")("blockquote")("<"+c())("def"),new RegExp(t.replace("body",n.join("|")))}(),e.normal={fences:e.fences,paragraph:e.paragraph},e.gfm={fences:/^ *``` *(\w+)? *\n([^\0]+?)\s*``` *(?:\n+|$)/,paragraph:/^/},e.gfm.paragraph=h(e.paragraph)("(?!","(?!"+e.gfm.fences.source.replace(/(^|[^\[])\^/g,"$1")+"|")(),e.lexer=function(t){var n=[];return n.links={},t=t.replace(/\r\n|\r/g,"\n").replace(/\t/g," "),e.token(t,n,!0)},e.token=function(t,n,r){var t=t.replace(/^ +$/gm,""),i,s,o,u,a,f,l;while(t){if(o=e.newline.exec(t))t=t.substring(o[0].length),o[0].length>1&&n.push({type:"space"});if(o=e.code.exec(t)){t=t.substring(o[0].length),o=o[0].replace(/^ {4}/gm,""),n.push({type:"code",text:v.pedantic?o:o.replace(/\n+$/,"")});continue}if(o=e.fences.exec(t)){t=t.substring(o[0].length),n.push({type:"code",lang:o[1],text:o[2]});continue}if(o=e.heading.exec(t)){t=t.substring(o[0].length),n.push({type:"heading",depth:o[1].length,text:o[2]});continue}if(o=e.lheading.exec(t)){t=t.substring(o[0].length),n.push({type:"heading",depth:o[2]==="="?1:2,text:o[1]});continue}if(o=e.hr.exec(t)){t=t.substring(o[0].length),n.push({type:"hr"});continue}if(o=e.blockquote.exec(t)){t=t.substring(o[0].length),n.push({type:"blockquote_start"}),o=o[0].replace(/^ *> ?/gm,""),e.token(o,n,r),n.push({type:"blockquote_end"});continue}if(o=e.list.exec(t)){t=t.substring(o[0].length),n.push({type:"list_start",ordered:isFinite(o[2])}),o=o[0].match(e.item),i=!1,l=o.length,f=0;for(;f])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:p,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([^\0]+?)__(?!_)|^\*\*([^\0]+?)\*\*(?!\*)/,em:/^\b_((?:__|[^\0])+?)_\b|^\*((?:\*\*|[^\0])+?)\*(?!\*)/,code:/^(`+)([^\0]*?[^`])\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,text:/^[^\0]+?(?=[\\?(?:\s+['"]([^\0]*?)['"])?\s*/,t.link=h(t.link)("inside",t._linkInside)("href",t._linkHref)(),t.reflink=h(t.reflink)("inside",t._linkInside)(),t.normal={url:t.url,strong:t.strong,em:t.em,text:t.text},t.pedantic={strong:/^__(?=\S)([^\0]*?\S)__(?!_)|^\*\*(?=\S)([^\0]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([^\0]*?\S)_(?!_)|^\*(?=\S)([^\0]*?\S)\*(?!\*)/},t.gfm={url:/^(https?:\/\/[^\s]+[^.,:;"')\]\s])/,text:/^[^\0]+?(?=[\\'+u+"";continue}if(c=t.url.exec(e)){e=e.substring(c[0].length),u=f(c[1]),a=u,i+=''+u+"";continue}if(c=t.tag.exec(e)){e=e.substring(c[0].length),i+=v.sanitize?f(c[0]):c[0];continue}if(c=t.link.exec(e)){e=e.substring(c[0].length),i+=n(c,{href:c[2],title:c[3]});continue}if((c=t.reflink.exec(e))||(c=t.nolink.exec(e))){e=e.substring(c[0].length),o=(c[2]||c[1]).replace(/\s+/g," "),o=s[o.toLowerCase()];if(!o||!o.href){i+=c[0][0],e=c[0].substring(1)+e;continue}i+=n(c,o);continue}if(c=t.strong.exec(e)){e=e.substring(c[0].length),i+=""+t.lexer(c[2]||c[1])+"";continue}if(c=t.em.exec(e)){e=e.substring(c[0].length),i+=""+t.lexer(c[2]||c[1])+"";continue}if(c=t.code.exec(e)){e=e.substring(c[0].length),i+=""+f(c[2],!0)+"";continue}if(c=t.br.exec(e)){e=e.substring(c[0].length),i+="
    ";continue}if(c=t.text.exec(e)){e=e.substring(c[0].length),i+=f(c[0]);continue}}return i};var r,i;p.exec=p;var v,m;d.options=d.setOptions=function(e){return m=e,g(e),d},d.setOptions({gfm:!0,pedantic:!1,sanitize:!1,highlight:null}),d.parser=function(e,t){return g(t),a(e)},d.lexer=function(t,n){return g(n),e.lexer(t)},d.parse=d,typeof module!="undefined"?module.exports=d:this.marked=d}.call(function(){return this||(typeof window!="undefined"?window:global)}()); \ No newline at end of file diff --git a/website/scriptfan/static/lib/epiceditor/themes/base/epiceditor.css b/website/scriptfan/static/lib/epiceditor/themes/base/epiceditor.css new file mode 100644 index 0000000..35ad611 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/base/epiceditor.css @@ -0,0 +1,31 @@ +html, body, iframe, div { margin:0; padding:0; } + +#epiceditor-utilbar { + position:fixed; + bottom:10px; + right:10px; + padding:5px; +} + +#epiceditor-utilbar img { + display:block; + float:left; + width: 30px; + height: 30px; +} + +#epiceditor-utilbar img:last-child { + margin-left: 15px; +} + +#epiceditor-utilbar img:hover { + cursor:pointer; +} + +.epiceditor-edit-mode #epiceditor-utilbar img.epiceditor-toggle-edit-btn { + display: none; +} + +.epiceditor-preview-mode #epiceditor-utilbar img.epiceditor-toggle-preview-btn { + display: none; +} diff --git a/website/scriptfan/static/lib/epiceditor/themes/editor/epic-dark.css b/website/scriptfan/static/lib/epiceditor/themes/editor/epic-dark.css new file mode 100644 index 0000000..058ace6 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/editor/epic-dark.css @@ -0,0 +1,13 @@ +html { padding:10px; } + +body { + border:0; + background:rgb(41,41,41); + font-family:monospace; + font-size:14px; + padding:10px; + color:#ddd; + line-height:1.35em; + margin:0; + padding:0; +} diff --git a/website/scriptfan/static/lib/epiceditor/themes/editor/epic-light.css b/website/scriptfan/static/lib/epiceditor/themes/editor/epic-light.css new file mode 100644 index 0000000..9411cec --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/editor/epic-light.css @@ -0,0 +1,12 @@ +html { padding:10px; } + +body { + border:0; + background:#fcfcfc; + font-family:monospace; + font-size:14px; + padding:10px; + line-height:1.35em; + margin:0; + padding:0; +} diff --git a/website/scriptfan/static/lib/epiceditor/themes/preview/bartik.css b/website/scriptfan/static/lib/epiceditor/themes/preview/bartik.css new file mode 100644 index 0000000..2ffb6d5 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/preview/bartik.css @@ -0,0 +1,167 @@ +body { + font-family: Georgia, "Times New Roman", Times, serif; + line-height: 1.5; + font-size: 87.5%; + word-wrap: break-word; + margin: 2em; + padding: 0; + border: 0; + outline: 0; + background: #fff; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 1.0em 0 0.5em; + font-weight: inherit; +} + +h1 { + font-size: 1.357em; + color: #000; +} + +h2 { + font-size: 1.143em; +} + +p { + margin: 0 0 1.2em; +} + +del { + text-decoration: line-through; +} + +tr:nth-child(odd) { + background-color: #dddddd; +} + +img { + outline: 0; +} + +code { + background-color: #f2f2f2; + background-color: rgba(40, 40, 0, 0.06); +} + +pre { + background-color: #f2f2f2; + background-color: rgba(40, 40, 0, 0.06); + margin: 10px 0; + overflow: hidden; + padding: 15px; + white-space: pre-wrap; +} + +pre code { + font-size: 100%; + background-color: transparent; +} + +blockquote { + background: #f7f7f7; + border-left: 1px solid #bbb; + font-style: italic; + margin: 1.5em 10px; + padding: 0.5em 10px; +} + +blockquote:before { + color: #bbb; + content: "\201C"; + font-size: 3em; + line-height: 0.1em; + margin-right: 0.2em; + vertical-align: -.4em; +} + +blockquote:after { + color: #bbb; + content: "\201D"; + font-size: 3em; + line-height: 0.1em; + vertical-align: -.45em; +} + +blockquote > p:first-child { + display: inline; +} + +table { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + border: 0; + border-spacing: 0; + font-size: 0.857em; + margin: 10px 0; + width: 100%; +} + +table table { + font-size: 1em; +} + +table tr th { + background: #757575; + background: rgba(0, 0, 0, 0.51); + border-bottom-style: none; +} + +table tr th, +table tr th a, +table tr th a:hover { + color: #FFF; + font-weight: bold; +} + +table tbody tr th { + vertical-align: top; +} + +tr td, +tr th { + padding: 4px 9px; + border: 1px solid #fff; + text-align: left; /* LTR */ +} + +tr:nth-child(odd) { + background: #e4e4e4; + background: rgba(0, 0, 0, 0.105); +} + +tr, +tr:nth-child(even) { + background: #efefef; + background: rgba(0, 0, 0, 0.063); +} + +a { + color: #0071B3; +} + +a:hover, +a:focus { + color: #018fe2; +} + +a:active { + color: #23aeff; +} + +a:link, +a:visited { + text-decoration: none; +} + +a:hover, +a:active, +a:focus { + text-decoration: underline; +} + diff --git a/website/scriptfan/static/lib/epiceditor/themes/preview/github.css b/website/scriptfan/static/lib/epiceditor/themes/preview/github.css new file mode 100644 index 0000000..4c78db4 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/preview/github.css @@ -0,0 +1,368 @@ +html { padding:0 10px; } + +body { + margin:0; + padding:0; + background:#fff; +} + +#epiceditor-wrapper{ + background:white; +} + +#epiceditor-preview{ + padding-top:10px; + padding-bottom:10px; + font-family: Helvetica,arial,freesans,clean,sans-serif; + font-size:13px; + line-height:1.6; +} + +#epiceditor-preview>*:first-child{ + margin-top:0!important; +} + +#epiceditor-preview>*:last-child{ + margin-bottom:0!important; +} + +#epiceditor-preview a{ + color:#4183C4; + text-decoration:none; +} + +#epiceditor-preview a:hover{ + text-decoration:underline; +} + +#epiceditor-preview h1, +#epiceditor-preview h2, +#epiceditor-preview h3, +#epiceditor-preview h4, +#epiceditor-preview h5, +#epiceditor-preview h6{ + margin:20px 0 10px; + padding:0; + font-weight:bold; + -webkit-font-smoothing:antialiased; +} + +#epiceditor-preview h1 tt, +#epiceditor-preview h1 code, +#epiceditor-preview h2 tt, +#epiceditor-preview h2 code, +#epiceditor-preview h3 tt, +#epiceditor-preview h3 code, +#epiceditor-preview h4 tt, +#epiceditor-preview h4 code, +#epiceditor-preview h5 tt, +#epiceditor-preview h5 code, +#epiceditor-preview h6 tt, +#epiceditor-preview h6 code{ + font-size:inherit; +} + +#epiceditor-preview h1{ + font-size:28px; + color:#000; +} + +#epiceditor-preview h2{ + font-size:24px; + border-bottom:1px solid #ccc; + color:#000; +} + +#epiceditor-preview h3{ + font-size:18px; +} + +#epiceditor-preview h4{ + font-size:16px; +} + +#epiceditor-preview h5{ + font-size:14px; +} + +#epiceditor-preview h6{ + color:#777; + font-size:14px; +} + +#epiceditor-preview p, +#epiceditor-preview blockquote, +#epiceditor-preview ul, +#epiceditor-preview ol, +#epiceditor-preview dl, +#epiceditor-preview li, +#epiceditor-preview table, +#epiceditor-preview pre{ + margin:15px 0; +} + +#epiceditor-preview hr{ + background:transparent url('../../images/modules/pulls/dirty-shade.png') repeat-x 0 0; + border:0 none; + color:#ccc; + height:4px; + padding:0; +} + +#epiceditor-preview>h2:first-child, +#epiceditor-preview>h1:first-child, +#epiceditor-preview>h1:first-child+h2, +#epiceditor-preview>h3:first-child, +#epiceditor-preview>h4:first-child, +#epiceditor-preview>h5:first-child, +#epiceditor-preview>h6:first-child{ + margin-top:0; + padding-top:0; +} + +#epiceditor-preview h1+p, +#epiceditor-preview h2+p, +#epiceditor-preview h3+p, +#epiceditor-preview h4+p, +#epiceditor-preview h5+p, +#epiceditor-preview h6+p{ + margin-top:0; +} + +#epiceditor-preview li p.first{ + display:inline-block; +} + +#epiceditor-preview ul, +#epiceditor-preview ol{ + padding-left:30px; +} + +#epiceditor-preview ul li>:first-child, +#epiceditor-preview ol li>:first-child{ + margin-top:0; +} + +#epiceditor-preview ul li>:last-child, +#epiceditor-preview ol li>:last-child{ + margin-bottom:0; +} + +#epiceditor-preview dl{ + padding:0; +} + +#epiceditor-preview dl dt{ + font-size:14px; + font-weight:bold; + font-style:italic; + padding:0; + margin:15px 0 5px; +} + +#epiceditor-preview dl dt:first-child{ + padding:0; +} + +#epiceditor-preview dl dt>:first-child{ + margin-top:0; +} + +#epiceditor-preview dl dt>:last-child{ + margin-bottom:0; +} + +#epiceditor-preview dl dd{ + margin:0 0 15px; + padding:0 15px; +} + +#epiceditor-preview dl dd>:first-child{ + margin-top:0; +} + +#epiceditor-preview dl dd>:last-child{ + margin-bottom:0; +} + +#epiceditor-preview blockquote{ + border-left:4px solid #DDD; + padding:0 15px; + color:#777; +} + +#epiceditor-preview blockquote>:first-child{ + margin-top:0; +} + +#epiceditor-preview blockquote>:last-child{ + margin-bottom:0; +} + +#epiceditor-preview table{ + padding:0; + border-collapse: collapse; + border-spacing: 0; + font-size: 100%; + font: inherit; +} + +#epiceditor-preview table tr{ + border-top:1px solid #ccc; + background-color:#fff; + margin:0; + padding:0; +} + +#epiceditor-preview table tr:nth-child(2n){ + background-color:#f8f8f8; +} + +#epiceditor-preview table tr th{ + font-weight:bold; +} + +#epiceditor-preview table tr th, +#epiceditor-preview table tr td{ + border:1px solid #ccc; + text-align:left; + margin:0; + padding:6px 13px; +} + +#epiceditor-preview table tr th>:first-child, +#epiceditor-preview table tr td>:first-child{ + margin-top:0; +} + +#epiceditor-preview table tr th>:last-child, +#epiceditor-preview table tr td>:last-child{ + margin-bottom:0; +} + +#epiceditor-preview img{ + max-width:100%; +} + +#epiceditor-preview span.frame{ + display:block; + overflow:hidden; +} + +#epiceditor-preview span.frame>span{ + border:1px solid #ddd; + display:block; + float:left; + overflow:hidden; + margin:13px 0 0; + padding:7px; + width:auto; +} + +#epiceditor-preview span.frame span img{ + display:block; + float:left; +} + +#epiceditor-preview span.frame span span{ + clear:both; + color:#333; + display:block; + padding:5px 0 0; +} + +#epiceditor-preview span.align-center{ + display:block; + overflow:hidden; + clear:both; +} + +#epiceditor-preview span.align-center>span{ + display:block; + overflow:hidden; + margin:13px auto 0; + text-align:center; +} + +#epiceditor-preview span.align-center span img{ + margin:0 auto; + text-align:center; +} + +#epiceditor-preview span.align-right{ + display:block; + overflow:hidden; + clear:both; +} + +#epiceditor-preview span.align-right>span{ + display:block; + overflow:hidden; + margin:13px 0 0; + text-align:right; +} + +#epiceditor-preview span.align-right span img{ + margin:0; + text-align:right; +} + +#epiceditor-preview span.float-left{ + display:block; + margin-right:13px; + overflow:hidden; + float:left; +} + +#epiceditor-preview span.float-left span{ + margin:13px 0 0; +} + +#epiceditor-preview span.float-right{ + display:block; + margin-left:13px; + overflow:hidden; + float:right; +} + +#epiceditor-preview span.float-right>span{ + display:block; + overflow:hidden; + margin:13px auto 0; + text-align:right; +} + +#epiceditor-preview code, +#epiceditor-preview tt{ + margin:0 2px; + padding:0 5px; + white-space:nowrap; + border:1px solid #eaeaea; + background-color:#f8f8f8; + border-radius:3px; +} + +#epiceditor-preview pre>code{ + margin:0; + padding:0; + white-space:pre; + border:none; + background:transparent; +} + +#epiceditor-preview .highlight pre, +#epiceditor-preview pre{ + background-color:#f8f8f8; + border:1px solid #ccc; + font-size:13px; + line-height:19px; + overflow:auto; + padding:6px 10px; + border-radius:3px; +} + +#epiceditor-preview pre code, +#epiceditor-preview pre tt{ + background-color:transparent; + border:none; +} diff --git a/website/scriptfan/static/lib/epiceditor/themes/preview/preview-dark.css b/website/scriptfan/static/lib/epiceditor/themes/preview/preview-dark.css new file mode 100644 index 0000000..620c193 --- /dev/null +++ b/website/scriptfan/static/lib/epiceditor/themes/preview/preview-dark.css @@ -0,0 +1,121 @@ +html { padding:0 10px; } + +body { + margin:0; + padding:10px 0; + background:#000; +} + +#epiceditor-preview h1, +#epiceditor-preview h2, +#epiceditor-preview h3, +#epiceditor-preview h4, +#epiceditor-preview h5, +#epiceditor-preview h6, +#epiceditor-preview p, +#epiceditor-preview blockquote { + margin: 0; + padding: 0; +} +#epiceditor-preview { + background:#000; + font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif; + font-size: 13px; + line-height: 18px; + color: #ccc; +} +#epiceditor-preview a { + color: #fff; +} +#epiceditor-preview a:hover { + color: #00ff00; + text-decoration: none; +} +#epiceditor-preview a img { + border: none; +} +#epiceditor-preview p { + margin-bottom: 9px; +} +#epiceditor-preview h1, +#epiceditor-preview h2, +#epiceditor-preview h3, +#epiceditor-preview h4, +#epiceditor-preview h5, +#epiceditor-preview h6 { + color: #cdcdcd; + line-height: 36px; +} +#epiceditor-preview h1 { + margin-bottom: 18px; + font-size: 30px; +} +#epiceditor-preview h2 { + font-size: 24px; +} +#epiceditor-preview h3 { + font-size: 18px; +} +#epiceditor-preview h4 { + font-size: 16px; +} +#epiceditor-preview h5 { + font-size: 14px; +} +#epiceditor-preview h6 { + font-size: 13px; +} +#epiceditor-preview hr { + margin: 0 0 19px; + border: 0; + border-bottom: 1px solid #ccc; +} +#epiceditor-preview blockquote { + padding: 13px 13px 21px 15px; + margin-bottom: 18px; + font-family:georgia,serif; + font-style: italic; +} +#epiceditor-preview blockquote:before { + content:"\201C"; + font-size:40px; + margin-left:-10px; + font-family:georgia,serif; + color:#eee; +} +#epiceditor-preview blockquote p { + font-size: 14px; + font-weight: 300; + line-height: 18px; + margin-bottom: 0; + font-style: italic; +} +#epiceditor-preview code, #epiceditor-preview pre { + font-family: Monaco, Andale Mono, Courier New, monospace; +} +#epiceditor-preview code { + background-color: #000; + color: #f92672; + padding: 1px 3px; + font-size: 12px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +#epiceditor-preview pre { + display: block; + padding: 14px; + color:#66d9ef; + margin: 0 0 18px; + line-height: 16px; + font-size: 11px; + border: 1px solid #d9d9d9; + white-space: pre-wrap; + word-wrap: break-word; +} +#epiceditor-preview pre code { + background-color: #000; + color:#ccc; + font-size: 11px; + padding: 0; +} diff --git a/website/scriptfan/static/lib/jquery-1.7.2.min.js b/website/scriptfan/static/lib/jquery-1.7.2.min.js deleted file mode 100644 index 16ad06c..0000000 --- a/website/scriptfan/static/lib/jquery-1.7.2.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! 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?"":"")+""),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;g0){if(c!=="border")for(;e=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)[^>]*$|#([\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(;j0)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(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?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
    a",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>",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="
    "+""+"
    ",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="
    t
    ",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="
    ",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;e1,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.length1)},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-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=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=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=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;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?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;h0){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+~,(\[\\]+)+|[>+~])(\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;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=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 bc[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=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.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.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="

    ";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="
    ";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;h0)for(h=g;h=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-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:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_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
    ","
    "]),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>");try{for(;d1&&l0?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>");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]===""&&!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;i1)},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>/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("
    ").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=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-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/website/scriptfan/static/lib/jquery-1.8.3.min.js b/website/scriptfan/static/lib/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/website/scriptfan/static/lib/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
    a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
    t
    ",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
    ",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
    ",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

    ",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
    ","
    "]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
    ").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[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","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/website/scriptfan/static/lib/jquery-openid.js b/website/scriptfan/static/lib/jquery-openid.js deleted file mode 100644 index 87937a1..0000000 --- a/website/scriptfan/static/lib/jquery-openid.js +++ /dev/null @@ -1,29 +0,0 @@ -!function($) { - $.fn.openid = function(options) { - return this.each(function() { - var $this = $(this); - var options = $.extend({}, $.fn.openid.defaults, $this.data(), options); - var provider = $this.data('provider'); - $this.click(function() { - // 从mapping 中查找openid配置并提交表单 - if (options.provider in options.mappings) { - $(options.provider_selector).val(options.provider); - $(options.identifier_selector).val(options.mappings[options.provider]); - $this.parents('form').submit(); - } - }); - }); - }; - - $.fn.openid.defaults = { - identifier_selector: '#openid_identifier', - provider_selector: '#openid_provider', - mappings: { - 'google': 'https://www.google.com/accounts/o8/id' - } - } - - $(function() { - $('[rel=openid]').openid(); - }); -}(window.jQuery); diff --git a/website/scriptfan/templates/_helpers.html b/website/scriptfan/templates/_helpers.html index 6b083f0..559c7d7 100644 --- a/website/scriptfan/templates/_helpers.html +++ b/website/scriptfan/templates/_helpers.html @@ -1,7 +1,7 @@ -{% macro script_tag(filename, scope=None) -%} - +{% macro js(filename, scope=None, external=false) -%} + {%- endmacro %} -{%- macro style_tag(filename, scope=None) -%} - -{%- endmacro %} \ No newline at end of file +{%- macro css(filename, scope=None, external=false) -%} + +{%- endmacro %} diff --git a/website/scriptfan/templates/activities/create.html b/website/scriptfan/templates/activities/create.html deleted file mode 100644 index 639723f..0000000 --- a/website/scriptfan/templates/activities/create.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} - -{% block title %}创建活动{% endblock %} - -{% block content %} -
    - - - {% import 'activities/_form.html' as f %} - {{ f.form(form, action=url_for('activity.create')) }} -
    - -{% endblock %} diff --git a/website/scriptfan/templates/activities/index.html b/website/scriptfan/templates/activities/index.html deleted file mode 100644 index 367fd8c..0000000 --- a/website/scriptfan/templates/activities/index.html +++ /dev/null @@ -1,12 +0,0 @@ -{% extends "base.html" %} - -{% block title %}社区活动{% endblock %} - -{% block content %} -
    - -
    -{% endblock %} diff --git a/website/scriptfan/templates/articles/_form.html b/website/scriptfan/templates/articles/_form.html new file mode 100644 index 0000000..f16f05a --- /dev/null +++ b/website/scriptfan/templates/articles/_form.html @@ -0,0 +1,19 @@ +
    + {{ form.hidden_tag() }} +
    +
    + {{ form.title(placeholder=_('models.article.title'), class='input-xxlarge') }} + {{ form.title | error_text }} +
    +
    +
    +
    + {{ form.content(style='display: none;') }} +
    + {{ form.content | error_text }} +
    +
    +
    + +
    + diff --git a/website/scriptfan/templates/articles/_sidebar.html b/website/scriptfan/templates/articles/_sidebar.html new file mode 100644 index 0000000..d68d93b --- /dev/null +++ b/website/scriptfan/templates/articles/_sidebar.html @@ -0,0 +1,8 @@ + diff --git a/website/scriptfan/templates/articles/edit.html b/website/scriptfan/templates/articles/edit.html new file mode 100644 index 0000000..d5159dd --- /dev/null +++ b/website/scriptfan/templates/articles/edit.html @@ -0,0 +1,21 @@ +{% extends "articles/layout.html" %} + +{% block title %}{{ _('views.articles.edit.title') % form.title.data }}{% endblock %} + +{% block styles %} + +{% endblock %} + +{% block scripts %} + +{{ super() }} +{% endblock %} + +{% block content_body %} + + + {% include 'articles/_form.html' %} +{% endblock %} + diff --git a/website/scriptfan/templates/articles/index.html b/website/scriptfan/templates/articles/index.html new file mode 100644 index 0000000..e4c8fa9 --- /dev/null +++ b/website/scriptfan/templates/articles/index.html @@ -0,0 +1,24 @@ +{% extends "articles/layout.html" %} + +{% block title %}{{ _('articles') }}{% endblock %} + +{% block content_body %} + + +
      + {% for article in articles %} +
    • +
      +

      {{ article.title }}

      + +
      +
      + {{ article.content | markdown | safe }} +
      +
    • + {% endfor %} +
    +{% endblock %} diff --git a/website/scriptfan/templates/articles/layout.html b/website/scriptfan/templates/articles/layout.html new file mode 100644 index 0000000..a314ad1 --- /dev/null +++ b/website/scriptfan/templates/articles/layout.html @@ -0,0 +1,11 @@ +{% extends "layout.html" %} + +{% block content %} +
    +
    + {% block content_body %}{% endblock %} +
    + + {% include 'articles/_sidebar.html'%} +
    +{% endblock %} diff --git a/website/scriptfan/templates/articles/new.html b/website/scriptfan/templates/articles/new.html new file mode 100644 index 0000000..083c54d --- /dev/null +++ b/website/scriptfan/templates/articles/new.html @@ -0,0 +1,21 @@ +{% extends "articles/layout.html" %} + +{% block title %}{{ _('views.articles.new.title') }}{% endblock %} + +{% block styles %} + +{% endblock %} + +{% block scripts %} + +{{ super() }} +{% endblock %} + +{% block content_body %} + + + {% include 'articles/_form.html' %} +{% endblock %} + diff --git a/website/scriptfan/templates/articles/show.html b/website/scriptfan/templates/articles/show.html new file mode 100644 index 0000000..990911b --- /dev/null +++ b/website/scriptfan/templates/articles/show.html @@ -0,0 +1,22 @@ +{% extends "articles/layout.html" %} + +{% block title %}{{ article.title }}{% endblock %} + +{% block content_body %} + + +
    +
    + +
    +
    + {# TODO: Use article.content_html instead of content #} + {{ article.content | markdown | safe }} +
    +
    +{% endblock %} diff --git a/website/scriptfan/templates/base.html b/website/scriptfan/templates/base.html deleted file mode 100644 index 2d6ba84..0000000 --- a/website/scriptfan/templates/base.html +++ /dev/null @@ -1,69 +0,0 @@ - -{% import '_helpers.html' as tags %} - - - - {% block title %}{% endblock %} - ScriptFan.com - - - {{ tags.style_tag('lib/bootstrap/css/bootstrap.min.css') }} - {{ tags.style_tag('css/styles.css') }} - - - {% block styles %}{% endblock %} - - - {{ tags.script_tag('lib/jquery-1.7.2.min.js') }} - {{ tags.script_tag('lib/bootstrap/js/bootstrap.min.js') }} - {{ tags.script_tag('lib/bootstrap.bform.js') }} - {{ tags.script_tag('js/application.js') }} - - - {% block scripts %}{% endblock %} - - - -
    -
    - {% for category, message in get_flashed_messages(with_categories=true) %} -
    - - {{ message }} -
    - {% endfor %} -
    - - {% block content %}{% endblock %} - -
    - - diff --git a/website/scriptfan/templates/enviroment.html b/website/scriptfan/templates/enviroment.html new file mode 100644 index 0000000..3c0b8a4 --- /dev/null +++ b/website/scriptfan/templates/enviroment.html @@ -0,0 +1 @@ +fdsa diff --git a/website/scriptfan/templates/enviroment.js b/website/scriptfan/templates/enviroment.js new file mode 100644 index 0000000..769c823 --- /dev/null +++ b/website/scriptfan/templates/enviroment.js @@ -0,0 +1,6 @@ +ENV = { + ROOT: '{{ request.url_root }}', + STATIC: '{{ url_for('static', filename='') }}', + VERSION: '1.0' +}; + diff --git a/website/scriptfan/templates/activities/_form.html b/website/scriptfan/templates/events/_form.html similarity index 82% rename from website/scriptfan/templates/activities/_form.html rename to website/scriptfan/templates/events/_form.html index 8ce3ceb..42c333c 100644 --- a/website/scriptfan/templates/activities/_form.html +++ b/website/scriptfan/templates/events/_form.html @@ -1,5 +1,5 @@ {% macro form(form, action=None, class="form-horizontal") -%} -
    + {{ form.hidden_tag() }}
    @@ -12,7 +12,9 @@
    - {{ form.start_time }}  至  {{ form.end_time }} + {{ form.date(class='input-small', placeholder='请输入日期') }}   + {{ form.start_time(class='input-mini') }} - + {{ form.end_time(class='input-mini') }} {{ form.start_time | error_text }} {{ form.end_time | error_text }} @@ -25,6 +27,7 @@
    {{ form.address(class='input-xxlarge') }} +
    diff --git a/website/scriptfan/templates/events/create.html b/website/scriptfan/templates/events/create.html new file mode 100644 index 0000000..4e279e5 --- /dev/null +++ b/website/scriptfan/templates/events/create.html @@ -0,0 +1,24 @@ +{% extends "layout.html" %} + +{% block title %}创建活动{% endblock %} + +{% block styles %} +{{ t.css('css/event.css') }} +{% endblock %} + +{% block scripts %} +{{ t.js('http://maps.google.com/maps/api/js?v=3.exp&sensor=false&libraries=places', external=true) }} +{{ t.js('js/event.js') }} +{% endblock %} + +{% block content %} +
    + + + {% import 'events/_form.html' as f %} + {{ f.form(form, action=url_for('events.create')) }} +
    + +{% endblock %} diff --git a/website/scriptfan/templates/events/index.html b/website/scriptfan/templates/events/index.html new file mode 100644 index 0000000..47e844a --- /dev/null +++ b/website/scriptfan/templates/events/index.html @@ -0,0 +1,26 @@ +{% extends "layout.html" %} + +{% block title %}社区活动{% endblock %} + +{% block content %} +
    + + +
      + {% for event in events %} +
    • +
      +

      {{ event.title }}

      + {{ event.created_time | dateformat }} +
      +
      + {{ event.content | markdown | safe }} +
      +
    • + {% endfor %} +
    +
    +{% endblock %} diff --git a/website/scriptfan/templates/index.html b/website/scriptfan/templates/index.html index 9f8edc2..523290a 100644 --- a/website/scriptfan/templates/index.html +++ b/website/scriptfan/templates/index.html @@ -1,3 +1,2 @@ -{% extends "base.html" %} - -{% block title %}首面{% endblock %} +{% extends "layout.html" %} +{% block title %}{{ _("index") }}{% endblock %} diff --git a/website/scriptfan/templates/layout.html b/website/scriptfan/templates/layout.html new file mode 100644 index 0000000..367d090 --- /dev/null +++ b/website/scriptfan/templates/layout.html @@ -0,0 +1,95 @@ + +{% import '_helpers.html' as t %} + + + + {% block title %}{% endblock %} - ScriptFan.com + + + {{ t.css('lib/bootstrap/css/bootstrap.min.css') }} + {{ t.css('css/styles.css') }} + + {% block styles %} + {{ t.css('css/%s.css' % request.blueprint) }} + {% endblock %} + + + +
    +
    + {% for category, message in get_flashed_messages(with_categories=true) %} +
    + + {{ message | safe }} +
    + {% endfor %} +
    + + {% if current_user.is_authenticated() %} + {% if not skip_slug_info and not current_user.user.slug %} +
    + + 你尚未设置个性域名,个性域名提供更友好的页面页面地址。 + {# TODO: 添加个性域名提示不再显示功能 #} + 不再提示 + 前往设置 +
    + {% endif %} + + {% if not skip_password_info and not current_user.user.password %} +
    + + 你尚未设置密码,为了帐号的安全,请尽快设置密码。 + {# TODO: 添加密码设置提示不再显示功能 #} + 不再提示 + 前往设置 +
    + {% endif %} + {% endif %} + + {% block content %}{% endblock %} + +
    + + + {{ t.js('lib/jquery-1.8.3.min.js') }} + {{ t.js('lib/bootstrap/js/bootstrap.min.js') }} + {{ t.js(url_for('home.env'), external=True) }} + {{ t.js('js/application.js') }} + + {% block scripts %} + {{ t.js('js/%s.js' % request.blueprint) }} + {% endblock %} + + diff --git a/website/scriptfan/templates/user/edit.html b/website/scriptfan/templates/user/edit.html deleted file mode 100644 index eaa1b53..0000000 --- a/website/scriptfan/templates/user/edit.html +++ /dev/null @@ -1,116 +0,0 @@ -{% extends "base.html" %} -{% block title %}资料修改{% endblock %} - -{% block scripts %} -{{ tags.script_tag('js/user-edit.js') }} -{% endblock %} - -{% block content %} -
    - - -
    - {{ form.hidden_tag() }} -
    - -
    - {{ form.nickname }} - -
    -
    - -
    - -
    - greatghoul@gmail.com - 修改邮箱 -
    -
    - -
    - -
    - ●●●●●●●● - 修改密码 -
    -
    - -
    - -
    - {% if form.slug.data %} - - {{ request.url_root }}profile/{{ form.slug.data }} - {% else %} -
    - {{ form.slug(placeholder='user-slug') }} -
    - 设定你的个性域名,以便通过 - {{ request.url_root }}profile/yourname 访问。
    - 注意:域名设定后不能修改
    - {% endif %} -
    -
    - -
    - -
    - {{ form.phone }} - -
    -
    - -
    -
    - {% for radio in form.phone_status %} - - {% endfor %} -
    -
    - -
    - -
    - {{ form.motoo }} - -
    -
    - -
    - -
    - {{ form.introduction }} - -
    -
    - -
    - -
    - - - -
    -{% endblock %} diff --git a/website/scriptfan/templates/user/edit_pass.html b/website/scriptfan/templates/user/edit_pass.html deleted file mode 100644 index deee12e..0000000 --- a/website/scriptfan/templates/user/edit_pass.html +++ /dev/null @@ -1,42 +0,0 @@ -{% extends "base.html" %} -{% block title %}修改密码{% endblock %} - -{% block content %} -
    - - -
    - {{ form.hidden_tag() }} -
    - -
    - {{ form.old_password }} - {{ form.old_password | error_text }} -
    -
    - -
    - -
    - {{ form.password }} - {{ form.password | error_text('5到20位字符') }} -
    -
    - -
    - -
    - {{ form.confirm }} - {{ form.confirm | error_text }} -
    -
    - -
    - - 返回 -
    - -
    -{% endblock %} diff --git a/website/scriptfan/templates/user/signin.html b/website/scriptfan/templates/user/signin.html deleted file mode 100644 index 7a7d71a..0000000 --- a/website/scriptfan/templates/user/signin.html +++ /dev/null @@ -1,39 +0,0 @@ -{% extends "base.html" %} -{% block title %}会员登陆{% endblock %} - -{% block scripts %} -{{ tags.script_tag('lib/jquery-openid.js') }} -{% endblock %} - -{% block content %} -

    用户登陆

    -
    - {{ form.hidden_tag() }} -
    - -
    - {{ form.email }} - {{ form.email.errors | first }} -
    -
    -
    - -
    - {{ form.password }} - {{ form.password.errors | first }} -
    -
    - {% if error %} -
    - 错误: {{ error }} -
    - {% endif %} -
    -    - -
    使用 Gmail帐户 登陆
    -
    - -{% endblock %} diff --git a/website/scriptfan/templates/user/signup.html b/website/scriptfan/templates/user/signup.html deleted file mode 100644 index 6ed18e5..0000000 --- a/website/scriptfan/templates/user/signup.html +++ /dev/null @@ -1,44 +0,0 @@ -{% extends "base.html" %} -{% block title %}注册会员{% endblock %} -{% block content %} -

    用户注册

    - -
    -
    - -
    - {{ form.email }} - {{ form.email.errors | first }} -
    -
    -
    - -
    - {{ form.nickname }} - {{ form.nickname.errors | first }} -
    -
    -
    - -
    - {{ form.password }} - {{ form.password.errors | first }} -
    -
    -
    - -
    - {{ form.repassword }} - {{ form.repassword.errors | first }} -
    -
    - {% if session.current_openid %} -
    - 正在通过 {{ session.openid_provider }} OpenID 注册,填写密码以完成注册! -
    - {% endif %} -
    - -
    - -{% endblock %} diff --git a/website/scriptfan/templates/users/_sidebar.html b/website/scriptfan/templates/users/_sidebar.html new file mode 100644 index 0000000..3938828 --- /dev/null +++ b/website/scriptfan/templates/users/_sidebar.html @@ -0,0 +1,20 @@ +{% set pwd_action = current_user.user.password and 'reset' or 'set' -%} +{% set navbar_items = [ + (url_for('users.slug'), 'slug', _('views.users.slug.title')), + (url_for('users.general'), 'general', _('views.users.general.title')), + ('#', 'email', _('views.users.email.title')), + (url_for('users.password'), 'password', _('views.users.password.title.' + pwd_action)), + (url_for('users.openid_manage'), 'openids', _('views.users.openids.title')), +] -%} + + diff --git a/website/scriptfan/templates/users/general.html b/website/scriptfan/templates/users/general.html new file mode 100644 index 0000000..6edb61f --- /dev/null +++ b/website/scriptfan/templates/users/general.html @@ -0,0 +1,74 @@ +{% extends "users/layout.html" %} + +{% block title %}{{ _('views.users.general.title') }}{% endblock %} + +{% block content_body %} +
    + {{ form.hidden_tag() }} + +
    + +
    + {{ form.nickname }} + {{ form.nickname | error_text }} +
    +
    + +
    + +
    + {{ form.phone }} + {{ form.phone | error_text }} +
    +
    + +
    +
    + {% for radio in form.phone_privacy %} + + {% endfor %} +
    +
    + +
    + +
    + {{ form.motoo }} + +
    +
    + +
    + +
    + {{ form.intro }} + +
    +
    + +
    + +
    + + +{% endblock %} diff --git a/website/scriptfan/templates/users/layout.html b/website/scriptfan/templates/users/layout.html new file mode 100644 index 0000000..a67676d --- /dev/null +++ b/website/scriptfan/templates/users/layout.html @@ -0,0 +1,15 @@ +{% extends "layout.html" %} + +{% block content %} +
    +
    + + + {% block content_body %}{% endblock %} +
    + + {% include 'users/_sidebar.html' %} +
    +{% endblock %} diff --git a/website/scriptfan/templates/users/openid.html b/website/scriptfan/templates/users/openid.html new file mode 100644 index 0000000..cdc867d --- /dev/null +++ b/website/scriptfan/templates/users/openid.html @@ -0,0 +1,57 @@ +{% extends "users/layout.html" %} + +{% block title %}{{ _('views.users.openids.title') }}{% endblock %} + +{% block scripts %} + +{% endblock %} + +{% block content_body %} +
    +{{ form.hidden_tag() }} +{% for errors in form.errors.values() %} +
    {% for error in errors %} {{ error }} {% endfor %}
    +{% endfor %} +
    + + + + + {% for provider, registed in providers %} + + + + + + + {% endfor %} + +
    可绑定的OpenID绑定情况添加/解除绑定
    {{ loop.index }}{{ provider }}{% if registed %}已绑定{% else %}未绑定{% endif %} + {% if registed %} + + {% else %} + + {% endif %} +
    + +{% endblock %} diff --git a/website/scriptfan/templates/users/password.html b/website/scriptfan/templates/users/password.html new file mode 100644 index 0000000..e7eddbe --- /dev/null +++ b/website/scriptfan/templates/users/password.html @@ -0,0 +1,39 @@ +{% extends "users/layout.html" %} + +{% set pwd_action = current_user.user.password and 'reset' or 'set' -%} +{% block title %}{{ _('views.users.password.title.' + pwd_action) }}{% endblock %} + +{% block content_body %} +
    + {{ form.hidden_tag() }} + {% if current_user.user.password %} +
    + +
    + {{ form.old_password }} + {{ form.old_password | error_text }} +
    +
    + {% endif %} + +
    + +
    + {{ form.password }} + {{ form.password | error_text }} +
    +
    + +
    + +
    + {{ form.confirm }} + {{ form.confirm | error_text }} +
    +
    + +
    + +
    +
    +{% endblock %} diff --git a/website/scriptfan/templates/user/profile.html b/website/scriptfan/templates/users/profile.html similarity index 55% rename from website/scriptfan/templates/user/profile.html rename to website/scriptfan/templates/users/profile.html index 8fa8abc..d0a0eb8 100644 --- a/website/scriptfan/templates/user/profile.html +++ b/website/scriptfan/templates/users/profile.html @@ -1,32 +1,32 @@ -{% extends "base.html" %} +{% extends "layout.html" %} {% block title %}{{ user.nickname }}{% endblock %} {% block styles %} -{{ tags.style_tag('css/profile.css') }} +{{ t.css('css/profile.css') }} {% endblock %} {% block content %}
    电子邮件:{{ user.email }}
    {% if user.id == current_user.user.id %} -
    手机号码:{{ user.info.phone }}
    +
    手机号码:{{ user.phone }}
    {% elif not current_user.is_anonymous() %} - {% if user.info.phone_status in (1, 2) %} -
    手机号码:{{ user.info.phone }}
    + {% if user.phone_privacy in (1, 2) %} +
    手机号码:{{ user.phone }}
    {% endif %} - {% elif user.info.phone_status == 1 %} -
    手机号码:{{ user.info.phone }}
    + {% elif user.phone_privacy == 1 %} +
    手机号码:{{ user.phone }}
    {% endif %} -
    座右铭:{{ user.info.motoo }}
    -
    个人介绍:{{ user.info.introduction }}
    +
    座右铭:{{ user.motoo }}
    +
    个人介绍:{{ user.intro }}
    注册日期:{{ user.created_time | dateformat }}
    diff --git a/website/scriptfan/templates/users/signin.html b/website/scriptfan/templates/users/signin.html new file mode 100644 index 0000000..d39e0dc --- /dev/null +++ b/website/scriptfan/templates/users/signin.html @@ -0,0 +1,37 @@ +{% extends "layout.html" %} + +{% block title %}会员登陆{% endblock %} + +{% block content %} +
    + + +
    + {{ form.hidden_tag() }} +
    + +
    + {{ form.email }} + {{ form.email | error_text }} +
    +
    +
    + +
    + {{ form.password }} + {{ form.password | error_text }} +
    +
    +
    +    + +
    使用 Gmail帐户 登陆
    +
    +
    +
    +{% endblock %} + diff --git a/website/scriptfan/templates/users/signup.html b/website/scriptfan/templates/users/signup.html new file mode 100644 index 0000000..0b8b907 --- /dev/null +++ b/website/scriptfan/templates/users/signup.html @@ -0,0 +1,48 @@ +{% extends "layout.html" %} + +{% block title %}注册会员{% endblock %} + +{% block content %} +
    + + +
    + {{ form.hidden_tag() }} +
    + +
    + {{ form.email }} + {{ form.email | error_text }} +
    +
    +
    + +
    + {{ form.nickname }} + {{ form.nickname | error_text }} +
    +
    +
    + +
    + {{ form.password1 }} + {{ form.password1 | error_text }} +
    +
    +
    + +
    + {{ form.password2 }} + {{ form.password2 | error_text }} +
    +
    +
    + +   或者直接 使用Google登陆 +
    +
    +
    +{% endblock %} + diff --git a/website/scriptfan/templates/users/slug.html b/website/scriptfan/templates/users/slug.html new file mode 100644 index 0000000..d14cff5 --- /dev/null +++ b/website/scriptfan/templates/users/slug.html @@ -0,0 +1,34 @@ +{% extends "users/layout.html" %} + +{% block title %}{{ _('views.users.general.title') }}{% endblock %} + +{% block scripts %} + +{% endblock %} + +{% block content_body %} +
    + {{ form.hidden_tag() }} + +
    注意:个性域名设定后不能修改
    + +
    + +
    +
    + {{ request.url_root }}profile/ + {{ form.slug(placeholder='user-slug') }} +
    +
    +
    + +
    + +
    +
    +{% endblock %} diff --git a/website/scriptfan/translations/zh_CN/LC_MESSAGES/.gitkeep b/website/scriptfan/translations/zh_CN/LC_MESSAGES/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/website/scriptfan/translations/zh_CN/LC_MESSAGES/messages.pot b/website/scriptfan/translations/zh_CN/LC_MESSAGES/messages.pot new file mode 100644 index 0000000..0864d75 --- /dev/null +++ b/website/scriptfan/translations/zh_CN/LC_MESSAGES/messages.pot @@ -0,0 +1,84 @@ +# ScriptFan.com +# vim: ft=config +msgid "" +msgstr "" +"Content-Type: text/plain; charset=utf-8\n" + +## Users + +msgid "views.users.slug.title" +msgstr "设置个性域名" + +msgid "views.users.general.title" +msgstr "修改个人资料" + +msgid "views.users.email.title" +msgstr "修改登陆邮箱" + +msgid "views.users.password.title.set" +msgstr "设置密码" + +msgid "views.users.password.title.reset" +msgstr "修改密码" + +msgid "views.users.openids.title" +msgstr "管理服务绑定" + + + +msgid "index" +msgstr "首页" + +msgid "articles" +msgstr "文章" + +msgid "models.article.title" +msgstr "标题" + +msgid "articles.create" +msgstr "发布文章" + +msgid "articles.edit" +msgstr "修改文章" + +msgid "articles.update %(title)s" +msgstr "修改 %(title)s" + +msgid "views.articles.edit.title" +msgstr "编辑文章:%%s" + +msgid "views.articles.new.title" +msgstr "发布文章" + +msgid "articles.update" +msgstr "编辑文章" + +msgid "views.articles.categories" +msgstr "文章分类" + +msgid "event" +msgstr "活动" + +msgid "my_profile" +msgstr "个人页面" + +msgid "signup" +msgstr "注册" + +msgid "manage" +msgstr "设置" + +msgid "signin" +msgstr "登陆" + +msgid "logout" +msgstr "注销" + +msgid "title" +msgstr "标题" + +msgid "content" +msgstr "内容" + +msgid "submit" +msgstr "提交" diff --git a/website/scriptfan/views/__init__.py b/website/scriptfan/views/__init__.py index 7872b0b..8acc2ad 100644 --- a/website/scriptfan/views/__init__.py +++ b/website/scriptfan/views/__init__.py @@ -1,6 +1,8 @@ -#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" + scriptfan.views + ~~~~~~~~~~~~~~~~~~~~ + View controllers package +""" -from site import siteapp -from user import userapp -from post import postapp -from activity import activityapp +import events, post, home, users \ No newline at end of file diff --git a/website/scriptfan/views/activity.py b/website/scriptfan/views/activity.py deleted file mode 100644 index 0c9a10d..0000000 --- a/website/scriptfan/views/activity.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python -#-*-coding:utf-8-*- -import logging -logger = logging.getLogger(__name__) - -from flask import Blueprint, render_template -from scriptfan.forms.activity import ActivityForm - -activityapp = Blueprint("activity", __name__) - -@activityapp.route('/', methods=['GET']) -def index(): - return render_template('activities/index.html') - -@activityapp.route('/create', methods=['GET']) -def create(): - form = ActivityForm(cref_enabled=False) - return render_template('activities/create.html', form=form) diff --git a/website/scriptfan/views/articles.py b/website/scriptfan/views/articles.py new file mode 100644 index 0000000..92ab677 --- /dev/null +++ b/website/scriptfan/views/articles.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +""" + scriptfan.views.articles + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Views controllers for articles and categoirs +""" + +from flask import (Blueprint, render_template, redirect, + flash, url_for, request, current_app as app) +from flask.ext.login import current_user +from flask.ext.babel import gettext as _ + +from scriptfan import db +from scriptfan.forms.articles import ArticleForm +from scriptfan.models import Article, Category + + +blueprint = Blueprint("articles", __name__) + + +@blueprint.route('/', methods=['GET']) +def index(): + articles = Article.query.all() + categories = Category.query.all() + # app.logger.info(articles[0].title) + return render_template('articles/index.html', articles=articles, categories=categories) + +@blueprint.route('/', methods=['GET']) +def show(article_id): + article = Article.get_by_id(article_id) + categories = Category.query.all() + return render_template('articles/show.html', article=article, categories=categories) + + +@blueprint.route('/create', methods=['GET', 'POST']) +def create(): + form = ArticleForm() + if form.validate_on_submit(): + article = Article() + form.populate_obj(article) + db.session.add(article) + db.session.commit() + flash('Add article successfully!', 'success') + return redirect(url_for('.show', article_id=article.id)) + + categories = Category.query.all() + return render_template('articles/new.html', form=form, categories=categories) + + +@blueprint.route('/edit/', methods=['GET', 'POST']) +def update(article_id): + article = Article.get_by_id(article_id) + form = ArticleForm(obj=article) + if form.validate_on_submit(): + form.populate_obj(article) + db.session.commit() + flash('Update article successfully!', 'success') + return redirect(url_for('.index')) + + + categories = Category.query.all() + return render_template('articles/edit.html', form=form, categories=categories) diff --git a/website/scriptfan/views/events.py b/website/scriptfan/views/events.py new file mode 100644 index 0000000..eaccd63 --- /dev/null +++ b/website/scriptfan/views/events.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +""" + scriptfan.views.events + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Views controllers for events +""" + +from datetime import datetime + +from flask import Blueprint, render_template, redirect, flash, url_for +from scriptfan import db +from scriptfan.forms import EventForm +from scriptfan.models import Event, EventDuration + +from flask.ext.login import current_user + + +blueprint = Blueprint("events", __name__) + + +@blueprint.route('/', methods=['GET']) +def index(): + events = Event.query.all() + return render_template('events/index.html', events=events) + + +@blueprint.route('/create', methods=['GET', 'POST']) +def create(): + form = EventForm(cref_enabled=False) + if form.validate_on_submit(): + # TODO: Create event for more than one day. + event = Event() + duration = EventDuration() + form.populate_obj(event) + form.populate_obj(duration) + event.durations.append(duration) + + # 装填用户和创建时间等信息 + event.user_id = current_user.user.id + # TODO: 使用一些让SQLAlchemy能够自动更新模型中的 created_time 和 modified_time + event.created_time = datetime.now() + db.session.add(event) + flash(u'活动%s发布成功.' % form.data.get('title'), 'success') + return redirect(url_for('events.index')) + else: + return render_template('events/create.html', form=form) diff --git a/website/scriptfan/views/home.py b/website/scriptfan/views/home.py new file mode 100644 index 0000000..2cbef5b --- /dev/null +++ b/website/scriptfan/views/home.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +""" + scriptfan.views.home + ~~~~~~~~~~~~~~~~~~~~~~~ + Home view controller +""" + +from flask import Blueprint, render_template, make_response + + +blueprint = Blueprint('home', __name__) + + +@blueprint.route('/') +def index(): + return render_template('index.html') + +@blueprint.route('/enviroment.js') +def env(): + # TODO: Enable cache for global enviroment scripts + response = make_response(render_template('enviroment.js')) + response.headers['Content-Type'] = 'text/javascript; charset=utf-8' + return response diff --git a/website/scriptfan/views/site.py b/website/scriptfan/views/site.py deleted file mode 100644 index 8834854..0000000 --- a/website/scriptfan/views/site.py +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python -#-*-coding:utf-8-*- -from flask import Blueprint, render_template - -siteapp = Blueprint("site", __name__) - -@siteapp.route("/") -def index(): - return render_template("index.html") diff --git a/website/scriptfan/views/user.py b/website/scriptfan/views/user.py deleted file mode 100644 index 8145160..0000000 --- a/website/scriptfan/views/user.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python -#-*-coding:utf-8-*- -import logging -logger = logging.getLogger(__name__) - -from flask import Blueprint, request, session, url_for, redirect, jsonify, abort -from flask import render_template, flash -from flask import current_app as app -from flask.ext import login -from flask.ext.login import current_user -from scriptfan.extensions import db, oid, login_manager -from scriptfan.models import (User, UserOpenID) -from scriptfan.forms.user import (SignupForm, SigninForm, ProfileForm, EditPassForm) - -# import re - -userapp = Blueprint("user", __name__) - -class Anonymous(login.AnonymousUser): - user = User(nickname=u'游客', email='') - -class LoginUser(login.UserMixin): - """Wraps User object for Flask-Login""" - - def __init__(self, user): - self.id = user.id - self.user = user - -login_manager.anonymous_user = Anonymous -login_manager.login_view = 'user.signin' -login_manager.login_message = u'需要登陆后才能访问本页' - -@login_manager.user_loader -def load_user(user_id): - user = User.query.get(user_id) - return user and LoginUser(user) or None - -@userapp.route('/signin/', methods=['GET', 'POST']) -@oid.loginhandler -def signin(): - if current_user.is_authenticated(): - return redirect(url_for('user.profile')) - - form = SigninForm(csrf_enabled=False, next=oid.get_next_url()) - app.logger.info('>>> Signin user: ' + repr(dict(form.data, password=''))) - - if form.is_submitted() and form.openid_identifier.data: - session['openid_provider'] = form.openid_provider.data - session['openid_identifier'] = form.openid_identifier.data - return oid.try_login(form.openid_identifier.data, ask_for=['email', 'nickname', 'fullname']) - - if form.validate_on_submit(): - login.login_user(LoginUser(form.user), remember=form.remember) - flash(u'登陆成功') - # 如果指定了 next ,跳转到 next 页面 - # 如果用户注册了 slug ,则跳转到 slug 的profile 页面,否则跳转到 userid 的 profile 页面 - return redirect(form.next.data or url_for('user.profile')) - else: - return render_template('user/signin.html', form=form, openid_error=oid.fetch_error()) - -@oid.after_login -def create_or_login(resp): - app.logger.info('>>> OpenID Response: openid=%s, provider=%s', - resp.identity_url, session['openid_provider']) - session['current_openid'] = resp.identity_url - # TODO: 当使用新的OPENID登陆时,通过邮箱判定该用户以前是否注册过,邮箱未注册时,允许用户自己登陆以绑定帐号 - user_openid = UserOpenID.query.filter_by(openid=resp.identity_url).first() - if user_openid: - flash(u'登陆成功') - app.logger.info(u'Logging with user: ' + user_openid.user.email) - login.login_user(LoginUser(user_openid.user), remember=True) - return redirect(oid.get_next_url()) - return redirect(url_for('user.signup', next=oid.get_next_url(), - email=resp.email, - nickname=resp.nickname or resp.fullname)) - -@userapp.route('/signup/', methods=['GET', 'POST']) -def signup(): - if current_user.is_authenticated(): - return redirect(url_for('user.profile')) - - app.logger.info('request.form: ' + repr(request.values)) - form = SignupForm(request.values, csrf_enabled=False) - app.logger.info('>>> Signup user: ' + repr(dict(form.data, password=''))) - - if form.validate_on_submit(): - db.session.add(form.user) - db.session.commit() - return redirect(url_for('user.signin')) - else: - return render_template('user/signup.html', form=form) - -@userapp.route('/profile/') -@userapp.route('/profile/') -@login.login_required -def profile(slug_or_id=None): - if slug_or_id: - if slug_or_id.isdigit(): - user = User.query.get(int(slug_or_id)).first() - else: - user = User.query.filter_by(slug=slug_or_id).first() - return user and render_template('user/profile.html', user=user) or abort(404) - else: - return render_template('user/profile.html', user=current_user.user) - -@userapp.route('/userinfo/', methods=['GET', 'POST']) -@login.login_required -def edit(): - form = ProfileForm(csrf_enabled=False) - if form.is_submitted(): - logger.info('Updating user information...') - success = form.validate_on_submit() - if success: - try: - user = current_user.user - user.nickname = form.data['nickname'] - user.info.phone = form.data['phone'] - user.info.phone_status = form.data['phone_status'] - user.info.motoo = form.data['motoo'] - user.info.introduction = form.data['introduction'] - if form.data['slug']: - user.slug = form.data.get('slug') - return jsonify(success=True, messages=dict(success=u'用户资料更新成功')) - except Exception as e: - return jsonify(success=False, messages=dict(error=unicode(e))) - else: - return jsonify(success=False, messages=dict(error=u'用户资料更新失败'), \ - errors=form.errors) - else: - # 如果是编辑用户信息,则使用用户当前信息填充表单 - user = current_user.user - form.nickname.data = user.nickname - form.slug.data = user.slug - form.phone.data = user.info.phone - form.motoo.data = user.info.motoo - form.introduction.data = user.info.introduction - return render_template('user/edit.html', form=form) - - # TODO 处理更新用户资料的请求 - # TODO 用户照片上传 - -# TODO: 用户找回密码功能 - -@userapp.route('/edit-pass', methods=['GET', 'POST']) -@login.login_required -def edit_pass(): - form = EditPassForm(csrf_enabled=False) - if form.validate_on_submit(): - current_user.user.set_password(form.password.data) - flash(u'用户密码已经更新', 'success') - return form.redirect('user.profile') - else: - form.errors and flash(u'用户密码未能更新', 'error') - return render_template('user/edit_pass.html', form=form) - -@userapp.route('/email') -@login.login_required -def editemail(): - return 'email' - -@userapp.route('/signou/', methods=['GET']) -@login.login_required -def signout(): - login.logout_user() - del session['current_openid'] - return redirect(url_for('site.index')) diff --git a/website/scriptfan/views/users.py b/website/scriptfan/views/users.py new file mode 100644 index 0000000..093c3d0 --- /dev/null +++ b/website/scriptfan/views/users.py @@ -0,0 +1,321 @@ +#-*-coding:utf-8-*- +from datetime import datetime +from flask import Blueprint, session, request, url_for, redirect, abort, g +from flask import render_template, flash +from flask import current_app as app +from flask.ext import login +from flask.ext.login import current_user +from flask.ext.openid import COMMON_PROVIDERS +from scriptfan import db, oid, login_manager +from scriptfan.models import User, UserOpenID +from scriptfan.forms.user import SignupForm, SigninForm, EditProfileForm, \ + EditPasswordForm, EditSlugForm, \ + ManageOpenIDForm + +blurprint = Blueprint('users', __name__) + +class Anonymous(login.AnonymousUser): + user = User(nickname=u'游客', email='') + +class LoginUser(login.UserMixin): + """Wraps User object for Flask-Login""" + + def __init__(self, user): + self.id = user.id + self.user = user + +login_manager.anonymous_user = Anonymous +login_manager.login_view = 'users.signin' +login_manager.login_message = u'需要登陆后才能访问本页' + +@login_manager.user_loader +def load_user(user_id): + user = User.query.get(user_id) + return user and LoginUser(user) or None + +def login_user(user, remember=False): + """ 登陆用户并更新最近登陆时间 """ + login.login_user(LoginUser(user), remember=remember) + user.login_time = datetime.now() + app.logger.info('* Updated current users: %s, %s', user.id, user.email) + +# 开发资料修改页面中的OpenID绑定功能 +# FIXME: 第一次接触OpenID,实现得有点绕,是否还有漏洞没考虑到?一起讨论吧 +@blurprint.route('/openid/manage', methods=['GET', 'POST']) +@login.login_required +def openid_manage(): + g.actived_navitem = 'openids' + + form = ManageOpenIDForm(csrf_enabled=False) + if form.validate_on_submit(): + method = form.method.data + provider = form.provider.data + if method == 'add': + return redirect(url_for('users.openid_add', provider=provider)) + elif method == 'delete': + return _delete_openid(provider) + registed_providers = [openid.provider + for openid in current_user.user.openids] + providers = [(provider, provider in registed_providers) + for provider in COMMON_PROVIDERS] + return render_template('users/openid.html', providers = providers, form=form) + +# 解除绑定的实现 +def _delete_openid(provider): + user = current_user.user + openid = UserOpenID.query.filter_by(provider=provider, user=user).first() + if openid: + if len(user.openids) < 2 and not user.password: + flash(u'你只绑定了唯一一个OpenID,并且还没有设置密码, 不可以解除绑定哦!', + 'warning') + else: + db.session.delete(openid) + flash(u'成功解除与 %s 的绑定!' % openid.provider, + 'success') + else: + flash(u'解除OpenID绑定时发生了错误!', 'error') + return redirect(url_for('users.openid_manage')) + +# 添加绑定的实现 +@blurprint.route('/openid/add//', methods=['GET']) +@login.login_required +@oid.loginhandler +def openid_add(provider): + next_url = url_for('users.openid_manage') + if provider not in COMMON_PROVIDERS: + app.logger.warning('Invalid openid provider: %s' % provider) + flash(u'暂不支持绑定到 %s ' % provider, 'warning') + return redirect(next_url) + # 这里默认一个provider只能绑定一次 + openid = UserOpenID.query.filter_by(provider=provider, user=current_user.user).first() + if openid: + app.logger.warning('provider: %s has already bind to this acccount' % provider) + flash(u'你已经绑定到 %s 了' % provider, 'warning') + return redirect(next_url) + session['openid_provider'] = provider + # 用于openid回调函数create_or_login判断是登陆还是绑定 + session['openid_user_id'] = current_user.user.id + app.logger.info('Regist openid: %s, callback: %s', provider, next_url) + openid_error = oid.fetch_error() + if openid_error: + app.logger.error(openid_error) + flash(u'绑定OpenID失败: ' + openid_error) + return redirect(next_url) + app.logger.info(COMMON_PROVIDERS.get(provider)) + return oid.try_login(COMMON_PROVIDERS.get(provider), \ + ask_for=['email', 'fullname', 'nickname']) + +@blurprint.route('/openid//', methods=['GET']) +@oid.loginhandler +def openid(provider, next=None): + if current_user.is_authenticated(): + app.logger.info('User authenticated, redirecting to profile page') + return redirect(url_for('users.profile')) + + next_url = oid.get_next_url() + if provider not in COMMON_PROVIDERS: + app.logger.warning('Invalid openid provider: %s' % provider) + flash(u'暂不支持 %s 登陆' % provider, 'warning') + return redirect(next_url) + + session['openid_provider'] = provider + app.logger.info('Signin with openid: %s, callback: %s', provider, next_url) + + openid_error = oid.fetch_error() + if openid_error: + app.logger.error(openid_error) + flash(u'登陆失败: ' + openid_error) + return redirect(oid.get_next_url()) + + app.logger.info(COMMON_PROVIDERS.get(provider)) + return oid.try_login(COMMON_PROVIDERS.get(provider), \ + ask_for=['email', 'fullname', 'nickname']) + + +@blurprint.route('/signin/', methods=['GET', 'POST']) +def signin(): + # 如果用户已经登陆,跳转到用户资料页面 + if current_user.is_authenticated(): + return redirect(url_for('users.profile')) + + form = SigninForm(csrf_enabled=False) + + if form.validate_on_submit(): + app.logger.info('Signin users: %s', form.email.data) + login_user(form.user, remember=form.remember) + flash(u'登陆成功', 'success') + return form.redirect('users.profile') + + return render_template('users/signin.html', form=form) + + +@oid.after_login +def create_or_login(resp): + app.logger.info('OpenID Response: %s, %s, %s', + resp.email, resp.fullname, resp.nickname) + user_id = session.get('openid_user_id', None) + session.pop('openid_user_id', None) + # 这里分为两种情况 + if user_id: + # 绑定到已有帐号 + return _regist_openid(user_id, resp) + else: + # 用该OpenID登陆 + return _create_or_login(resp) + +# 这个方法用于绑定OpenID到已有帐号 +def _regist_openid(user_id, resp): + redirect_url = url_for('users.openid_manage') + # 清理Session里的键,这样不影响以后的登陆 + provider = session.get('openid_provider', None) + session.pop('openid_provider', None) + if provider and current_user.is_authenticated() \ + and user_id == current_user.user.id: + # 检查该openid是否已经存在 + openid = UserOpenID.query.filter_by(openid=resp.identity_url).first() + if openid: + flash(u'这个OpenID已经被绑定了', 'warning') + return redirect(redirect_url) + # 检查openid中注册的邮箱是否被其它用户占用 + user = User.query.filter_by(email=resp.email).first() + if user and user.id != user_id: + flash(u'邮箱 %s 已经被注册,如果你是该帐户的拥有者,请用该邮箱登陆后再绑定OpenID' % resp.email, 'warning') + return redirect(redirect_url) + # 绑定这个OpenID + openid = UserOpenID(openid=resp.identity_url, provider=provider) + current_user.user.openids.append(openid) + app.logger.info('bind openid: %s to users: %s', resp.identity_url, current_user.user) + flash(u'成功绑定到 %s 帐户,你可以用该帐户直接登陆了!' % provider, 'success') + return redirect(redirect_url) + else: + # 其它情况下不给用户具体信息 + flash(u'绑定OpenID失败!', 'error') + return redirect(redirect_url) + +# 这个方法用OpenID登陆 +def _create_or_login(resp): + # 如果openid未注册,先自动注册用户,并绑定openid + user = User.query.join(User.openids) \ + .filter(UserOpenID.openid==resp.identity_url).first() + + # 如果OpenID尚未绑定用户,直接创建用户并绑定OpenID + if not user: + # 如果邮箱已经被注册,提示手工绑定 + if User.query.filter_by(email=resp.email).first(): + flash(u'邮箱 %s 已经被注册,如果你是该帐户的拥有者,请登陆后再绑定OpenID' % resp.email, 'warning') + return redirect(url_for('users.signin')) + + # 邮箱没有注册,自动创建帐户并登陆 + app.logger.info('Creating users with openid: %s', resp.identity_url) + user = User(email=resp.email, nickname=resp.nickname or resp.fullname) + openid = UserOpenID(openid=resp.identity_url, provider=session['openid_provider']) + user.openids.append(openid) + db.session.add(user) + db.session.commit() + + flash(u'帐号已经创建, 可以在资料修改页面补充密码等信息'% url_for('users.general'), 'success') + + app.logger.info('Signin users: %s', user.email) + login_user(user, remember=True) + flash(u'登陆成功') + + return redirect(oid.get_next_url()) + +@blurprint.route('/signup/', methods=['GET', 'POST']) +def signup(): + if current_user.is_authenticated(): + return redirect(url_for('users.profile')) + + form = SignupForm(csrf_enabled=False) + app.logger.info('Signup with email: %(email)s, nickname: %(nickname)s', form.data) + + if form.validate_on_submit(): + user = User() + form.populate_obj(user) + user.set_password(form.password1.data) + db.session.add(user) + app.logger.info(u'New users added: %s', user) + flash(u'注册成功', 'success') + return redirect(url_for('users.signin')) + + return render_template('users/signup.html', form=form) + +# FIXME: Slug should not be same as an exists user_id +@blurprint.route('/profile/') +@blurprint.route('/profile/') +@login.login_required +def profile(slug_or_id=None): + if slug_or_id: + if slug_or_id.isdigit(): + user = User.query.get(int(slug_or_id)).first() + else: + user = User.query.filter_by(slug=slug_or_id).first() + return user and render_template('users/profile.html', user=user) or abort(404) + else: + return render_template('users/profile.html', user=current_user.user) + +@blurprint.route('/general', methods=['GET', 'POST']) +@login.login_required +def general(): + g.actived_navitem = 'general' + + form = EditProfileForm(csrf_enabled=False) + if form.validate_on_submit(): + app.logger.info(u'* Updating users information...') + app.logger.info(u'Form data: %s', repr(form.data)) + form.populate_obj(current_user.user) + flash(u'用户资料已经更新', 'success') + return form.redirect('users.general') + + # 如果是编辑用户信息,则使用用户当前信息填充表单 + form.process(obj=current_user.user) + return render_template('users/general.html', form=form) + + # TODO 处理更新用户资料的请求 + # TODO 用户照片上传 + +# TODO: 用户找回密码功能 + +# 更新用户slug功能 +@blurprint.route('/slug', methods=['GET', 'POST']) +@login.login_required +def slug(): + g.actived_navitem = 'slug' + + form = EditSlugForm() + if form.validate_on_submit(): + form.populate_obj(current_user.user) + flash(u'修改域名已经设置', 'success') + return redirect(url_for('users.profile', slug_or_id=current_user.user.slug)) + + form.process(obj=current_user.user) + return render_template('users/slug.html', form=form, skip_slug_info=True) + + +@blurprint.route('/password', methods=['GET', 'POST']) +@login.login_required +def password(): + g.actived_navitem = 'password' + + form = EditPasswordForm(csrf_enabled=False) + if form.validate_on_submit(): + current_user.user.set_password(form.password.data) + flash(u'用户密码已经更新', 'success') + return form.redirect('users.general') + + form.errors and flash(u'用户密码未能更新', 'error') + return render_template('users/password.html', form=form, skip_password_info=True) + +@blurprint.route('/email') +@login.login_required +def editemail(): + return 'email' + +@blurprint.route('/signout/', methods=['GET']) +@login.login_required +def signout(): + login.logout_user() + if 'openid_provider' in session: + del session['openid_provider'] + return redirect(url_for('home.index')) + diff --git a/website/start.bat b/website/start.bat new file mode 100644 index 0000000..1a02a4e --- /dev/null +++ b/website/start.bat @@ -0,0 +1,4 @@ +@echo off +title ScriptFan Development Server +echo Staring ScriptFan dev server... +python manage.py runserver -H localhost