tgids
tgids

file:b/.gitattributes (new)
  * text=auto
file:b/.gitignore (new)
  *.wav
  *.pyc
  /nbproject/private/
  /output.txt
 
  bin
  gen
  target
  .settings
  .classpath
  .project
  *.keystore
  *.swp
  *.orig
  *.log
  *.properties
  seed.txt
  map.txt
 
[submodule "pynma"] [submodule "pynma"]
path = pynma path = pynma
url = git://github.com/uskr/pynma.git url = git://github.com/uskr/pynma.git
  [submodule "js/flotr2"]
  path = js/flotr2
  url = https://github.com/HumbleSoftware/Flotr2.git
   
file:b/.htaccess (new)
  # Apache configuration file
  # httpd.apache.org/docs/2.2/mod/quickreference.html
 
  # Note .htaccess files are an overhead, this logic should be in your Apache
  # config if possible: httpd.apache.org/docs/2.2/howto/htaccess.html
 
  # Techniques in here adapted from all over, including:
  # Kroc Camen: camendesign.com/.htaccess
  # perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/
  # Sample .htaccess file of CMS MODx: modxcms.com
 
 
  # ----------------------------------------------------------------------
  # Better website experience for IE users
  # ----------------------------------------------------------------------
 
  # Force the latest IE version, in various cases when it may fall back to IE7 mode
  # github.com/rails/rails/commit/123eb25#commitcomment-118920
  # Use ChromeFrame if it's installed for a better experience for the poor IE folk
 
  <IfModule mod_headers.c>
  Header set X-UA-Compatible "IE=Edge,chrome=1"
  # mod_headers can't match by content-type, but we don't want to send this header on *everything*...
  <FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$" >
  Header unset X-UA-Compatible
  </FilesMatch>
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Cross-domain AJAX requests
  # ----------------------------------------------------------------------
 
  # Serve cross-domain Ajax requests, disabled by default.
  # enable-cors.org
  # code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
 
  # <IfModule mod_headers.c>
  # Header set Access-Control-Allow-Origin "*"
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # CORS-enabled images (@crossorigin)
  # ----------------------------------------------------------------------
 
  # Send CORS headers if browsers request them; enabled by default for images.
  # developer.mozilla.org/en/CORS_Enabled_Image
  # blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
  # hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
  # wiki.mozilla.org/Security/Reviews/crossoriginAttribute
 
  <IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
  # mod_headers, y u no match by Content-Type?!
  <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
  SetEnvIf Origin ":" IS_CORS
  Header set Access-Control-Allow-Origin "*" env=IS_CORS
  </FilesMatch>
  </IfModule>
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Webfont access
  # ----------------------------------------------------------------------
 
  # Allow access from all domains for webfonts.
  # Alternatively you could only whitelist your
  # subdomains like "subdomain.example.com".
 
  <IfModule mod_headers.c>
  <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
  Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Proper MIME type for all files
  # ----------------------------------------------------------------------
 
  # JavaScript
  # Normalize to standard type (it's sniffed in IE anyways)
  # tools.ietf.org/html/rfc4329#section-7.2
  AddType application/javascript js jsonp
  AddType application/json json
 
  # Audio
  AddType audio/ogg oga ogg
  AddType audio/mp4 m4a f4a f4b
 
  # Video
  AddType video/ogg ogv
  AddType video/mp4 mp4 m4v f4v f4p
  AddType video/webm webm
  AddType video/x-flv flv
 
  # SVG
  # Required for svg webfonts on iPad
  # twitter.com/FontSquirrel/status/14855840545
  AddType image/svg+xml svg svgz
  AddEncoding gzip svgz
 
  # Webfonts
  AddType application/vnd.ms-fontobject eot
  AddType application/x-font-ttf ttf ttc
  AddType font/opentype otf
  AddType application/x-font-woff woff
 
  # Assorted types
  AddType image/x-icon ico
  AddType image/webp webp
  AddType text/cache-manifest appcache manifest
  AddType text/x-component htc
  AddType application/xml rss atom xml rdf
  AddType application/x-chrome-extension crx
  AddType application/x-opera-extension oex
  AddType application/x-xpinstall xpi
  AddType application/octet-stream safariextz
  AddType application/x-web-app-manifest+json webapp
  AddType text/x-vcard vcf
  AddType application/x-shockwave-flash swf
  AddType text/vtt vtt
 
 
  # ----------------------------------------------------------------------
  # Allow concatenation from within specific js and css files
  # ----------------------------------------------------------------------
 
  # e.g. Inside of script.combined.js you could have
  # <!--#include file="libs/jquery-1.5.0.min.js" -->
  # <!--#include file="plugins/jquery.idletimer.js" -->
  # and they would be included into this single file.
 
  # This is not in use in the boilerplate as it stands. You may
  # choose to use this technique if you do not have a build process.
 
  #<FilesMatch "\.combined\.js$">
  # Options +Includes
  # AddOutputFilterByType INCLUDES application/javascript application/json
  # SetOutputFilter INCLUDES
  #</FilesMatch>
 
  #<FilesMatch "\.combined\.css$">
  # Options +Includes
  # AddOutputFilterByType INCLUDES text/css
  # SetOutputFilter INCLUDES
  #</FilesMatch>
 
 
  # ----------------------------------------------------------------------
  # Gzip compression
  # ----------------------------------------------------------------------
 
  <IfModule mod_deflate.c>
 
  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
  SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
  RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
  </IfModule>
  </IfModule>
 
  # Compress all output labeled with one of the following MIME-types
  <IfModule mod_filter.c>
  AddOutputFilterByType DEFLATE application/atom+xml \
  application/javascript \
  application/json \
  application/rss+xml \
  application/vnd.ms-fontobject \
  application/x-font-ttf \
  application/xhtml+xml \
  application/xml \
  font/opentype \
  image/svg+xml \
  image/x-icon \
  text/css \
  text/html \
  text/plain \
  text/x-component \
  text/xml
  </IfModule>
 
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Expires headers (for better cache control)
  # ----------------------------------------------------------------------
 
  # These are pretty far-future expires headers.
  # They assume you control versioning with filename-based cache busting
  # Additionally, consider that outdated proxies may miscache
  # www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
 
  # If you don't use filenames to version, lower the CSS and JS to something like
  # "access plus 1 week".
 
  <IfModule mod_expires.c>
  ExpiresActive on
 
  # Perhaps better to whitelist expires rules? Perhaps.
  ExpiresDefault "access plus 1 month"
 
  # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest "access plus 0 seconds"
 
  # Your document html
  ExpiresByType text/html "access plus 0 seconds"
 
  # Data
  ExpiresByType text/xml "access plus 0 seconds"
  ExpiresByType application/xml "access plus 0 seconds"
  ExpiresByType application/json "access plus 0 seconds"
 
  # Feed
  ExpiresByType application/rss+xml "access plus 1 hour"
  ExpiresByType application/atom+xml "access plus 1 hour"
 
  # Favicon (cannot be renamed)
  ExpiresByType image/x-icon "access plus 1 week"
 
  # Media: images, video, audio
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"
 
  # HTC files (css3pie)
  ExpiresByType text/x-component "access plus 1 month"
 
  # Webfonts
  ExpiresByType application/x-font-ttf "access plus 1 month"
  ExpiresByType font/opentype "access plus 1 month"
  ExpiresByType application/x-font-woff "access plus 1 month"
  ExpiresByType image/svg+xml "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
 
  # CSS and JavaScript
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"
 
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Prevent mobile network providers from modifying your site
  # ----------------------------------------------------------------------
 
  # The following header prevents modification of your code over 3G on some
  # European providers.
  # This is the official 'bypass' suggested by O2 in the UK.
 
  # <IfModule mod_headers.c>
  # Header set Cache-Control "no-transform"
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # ETag removal
  # ----------------------------------------------------------------------
 
  # FileETag None is not enough for every server.
  <IfModule mod_headers.c>
  Header unset ETag
  </IfModule>
 
  # Since we're sending far-future expires, we don't need ETags for
  # static content.
  # developer.yahoo.com/performance/rules.html#etags
  FileETag None
 
 
  # ----------------------------------------------------------------------
  # Stop screen flicker in IE on CSS rollovers
  # ----------------------------------------------------------------------
 
  # The following directives stop screen flicker in IE on CSS rollovers - in
  # combination with the "ExpiresByType" rules for images (see above).
 
  # BrowserMatch "MSIE" brokenvary=1
  # BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
  # BrowserMatch "Opera" !brokenvary
  # SetEnvIf brokenvary 1 force-no-vary
 
 
  # ----------------------------------------------------------------------
  # Set Keep-Alive Header
  # ----------------------------------------------------------------------
 
  # Keep-Alive allows the server to send multiple requests through one
  # TCP-connection. Be aware of possible disadvantages of this setting. Turn on
  # if you serve a lot of static content.
 
  # <IfModule mod_headers.c>
  # Header set Connection Keep-Alive
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Cookie setting from iframes
  # ----------------------------------------------------------------------
 
  # Allow cookies to be set from iframes (for IE only)
  # If needed, specify a path or regex in the Location directive.
 
  # <IfModule mod_headers.c>
  # Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Start rewrite engine
  # ----------------------------------------------------------------------
 
  # Turning on the rewrite engine is necessary for the following rules and
  # features. FollowSymLinks must be enabled for this to work.
 
  # Some cloud hosting services require RewriteBase to be set: goo.gl/HOcPN
  # If using the h5bp in a subdirectory, use `RewriteBase /foo` instead where
  # 'foo' is your directory.
 
  # If your web host doesn't allow the FollowSymlinks option, you may need to
  # comment it out and use `Options +SymLinksOfOwnerMatch`, but be aware of the
  # performance impact: http://goo.gl/Mluzd
 
  <IfModule mod_rewrite.c>
  Options +FollowSymlinks
  # Options +SymLinksIfOwnerMatch
  RewriteEngine On
  # RewriteBase /
  </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Suppress or force the "www." at the beginning of URLs
  # ----------------------------------------------------------------------
 
  # The same content should never be available under two different URLs -
  # especially not with and without "www." at the beginning, since this can cause
  # SEO problems (duplicate content). That's why you should choose one of the
  # alternatives and redirect the other one.
 
  # By default option 1 (no "www.") is activated.
  # no-www.org/faq.php?q=class_b
 
  # If you'd prefer to use option 2, just comment out all option 1 lines
  # and uncomment option 2.
 
  # IMPORTANT: NEVER USE BOTH RULES AT THE SAME TIME!
 
  # ----------------------------------------------------------------------
 
  # Option 1:
  # Rewrite "www.example.com -> example.com".
 
  <IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
  </IfModule>
 
  # ----------------------------------------------------------------------
 
  # Option 2:
  # Rewrite "example.com -> www.example.com".
  # Be aware that the following rule might not be a good idea if you use "real"
  # subdomains for certain parts of your website.
 
  # <IfModule mod_rewrite.c>
  # RewriteCond %{HTTPS} !=on
  # RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Built-in filename-based cache busting
  # ----------------------------------------------------------------------
 
  # If you're not using the build script to manage your filename version revving,
  # you might want to consider enabling this, which will route requests for
  # /css/style.20110203.css to /css/style.css
 
  # To understand why this is important and a better idea than all.css?v1231,
  # read: github.com/h5bp/html5-boilerplate/wiki/cachebusting
 
  # <IfModule mod_rewrite.c>
  # RewriteCond %{REQUEST_FILENAME} !-f
  # RewriteCond %{REQUEST_FILENAME} !-d
  # RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Prevent SSL cert warnings
  # ----------------------------------------------------------------------
 
  # Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent
  # https://www.example.com when your cert only allows https://secure.example.com
 
  # <IfModule mod_rewrite.c>
  # RewriteCond %{SERVER_PORT} !^443
  # RewriteRule ^ https://example-domain-please-change-me.com%{REQUEST_URI} [R=301,L]
  # </IfModule>
 
 
  # ----------------------------------------------------------------------
  # Prevent 404 errors for non-existing redirected folders
  # ----------------------------------------------------------------------
 
  # without -MultiViews, Apache will give a 404 for a rewrite if a folder of the
  # same name does not exist.
  # webmasterworld.com/apache/3808792.htm
 
  Options -MultiViews
 
 
  # ----------------------------------------------------------------------
  # Custom 404 page
  # ----------------------------------------------------------------------
 
  # You can add custom pages to handle 500 or 403 pretty easily, if you like.
  # If you are hosting your site in subdirectory, adjust this accordingly
  # e.g. ErrorDocument 404 /subdir/404.html
  ErrorDocument 404 /404.html
 
 
  # ----------------------------------------------------------------------
  # UTF-8 encoding
  # ----------------------------------------------------------------------
 
  # Use UTF-8 encoding for anything served text/plain or text/html
  AddDefaultCharset utf-8
 
  # Force UTF-8 for a number of file formats
  AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
 
 
  # ----------------------------------------------------------------------
  # A little more security
  # ----------------------------------------------------------------------
 
  # To avoid displaying the exact version number of Apache being used, add the
  # following to httpd.conf (it will not work in .htaccess):
  # ServerTokens Prod
 
  # "-Indexes" will have Apache block users from browsing folders without a
  # default document Usually you should leave this activated, because you
  # shouldn't allow everybody to surf through every folder on your server (which
  # includes rather private places like CMS system folders).
  <IfModule mod_autoindex.c>
  Options -Indexes
  </IfModule>
 
  # Block access to "hidden" directories or files whose names begin with a
  # period. This includes directories used by version control systems such as
  # Subversion or Git.
  <IfModule mod_rewrite.c>
  RewriteCond %{SCRIPT_FILENAME} -d [OR]
  RewriteCond %{SCRIPT_FILENAME} -f
  RewriteRule "(^|/)\." - [F]
  </IfModule>
 
  # Block access to backup and source files. These files may be left by some
  # text/html editors and pose a great security danger, when anyone can access
  # them.
  <FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
  Order allow,deny
  Deny from all
  Satisfy All
  </FilesMatch>
 
  # If your server is not already configured as such, the following directive
  # should be uncommented in order to set PHP's register_globals option to OFF.
  # This closes a major security hole that is abused by most XSS (cross-site
  # scripting) attacks. For more information: http://php.net/register_globals
  #
  # IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS:
  #
  # Your server does not allow PHP directives to be set via .htaccess. In that
  # case you must make this change in your php.ini file instead. If you are
  # using a commercial web host, contact the administrators for assistance in
  # doing this. Not all servers allow local php.ini files, and they should
  # include all PHP configurations (not just this one), or you will effectively
  # reset everything to PHP defaults. Consult www.php.net for more detailed
  # information about setting PHP directives.
 
  # php_flag register_globals Off
 
  # Rename session cookie to something else, than PHPSESSID
  # php_value session.name sid
 
  # Disable magic quotes (This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)
  # php_flag magic_quotes_gpc Off
 
  # Do not show you are using PHP
  # Note: Move this line to php.ini since it won't work in .htaccess
  # php_flag expose_php Off
 
  # Level of log detail - log all errors
  # php_value error_reporting -1
 
  # Write errors to log file
  # php_flag log_errors On
 
  # Do not display errors in browser (production - Off, development - On)
  # php_flag display_errors Off
 
  # Do not display startup errors (production - Off, development - On)
  # php_flag display_startup_errors Off
 
  # Format errors in plain text
  # Note: Leave this setting 'On' for xdebug's var_dump() output
  # php_flag html_errors Off
 
  # Show multiple occurrence of error
  # php_flag ignore_repeated_errors Off
 
  # Show same errors from different sources
  # php_flag ignore_repeated_source Off
 
  # Size limit for error messages
  # php_value log_errors_max_len 1024
 
  # Don't precede error with string (doesn't accept empty string, use whitespace if you need)
  # php_value error_prepend_string " "
 
  # Don't prepend to error (doesn't accept empty string, use whitespace if you need)
  # php_value error_append_string " "
 
  # Increase cookie security
  <IfModule php5_module>
  php_value session.cookie_httponly true
  </IfModule>
 
file:b/.idea/.name (new)
  scannr
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="CompilerConfiguration">
  <option name="DEFAULT_COMPILER" value="Javac" />
  <resourceExtensions />
  <wildcardResourcePatterns>
  <entry name="!?*.java" />
  <entry name="!?*.form" />
  <entry name="!?*.class" />
  <entry name="!?*.groovy" />
  <entry name="!?*.scala" />
  <entry name="!?*.flex" />
  <entry name="!?*.kt" />
  <entry name="!?*.clj" />
  </wildcardResourcePatterns>
  <annotationProcessing>
  <profile default="true" name="Default" enabled="false">
  <processorPath useClasspath="true" />
  </profile>
  </annotationProcessing>
  </component>
  </project>
 
 
  <component name="CopyrightManager">
  <settings default="">
  <module2copyright />
  </settings>
  </component>
  <component name="ProjectDictionaryState">
  <dictionary name="Madoka">
  <words>
  <w>tgid</w>
  <w>timefrom</w>
  <w>timeto</w>
  <w>tzoffset</w>
  </words>
  </dictionary>
  </component>
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
  </project>
 
 
file:b/.idea/misc.xml (new)
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="ProjectResources">
  <default-html-doctype>jar:file:\C:\Program Files (x86)\JetBrains\PhpStorm 5.0.2\lib\webide.jar!\resources\html5-schema\html5.rnc</default-html-doctype>
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_3" assert-keyword="false" jdk-15="false" />
  </project>
 
 
file:b/.idea/modules.xml (new)
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="ProjectModuleManager">
  <modules>
  <module fileurl="file://$PROJECT_DIR$/.idea/scannr.iml" filepath="$PROJECT_DIR$/.idea/scannr.iml" />
  </modules>
  </component>
  </project>
 
 
file:b/.idea/scannr.iml (new)
  <?xml version="1.0" encoding="UTF-8"?>
  <module type="WEB_MODULE" version="4">
  <component name="FacetManager">
  <facet type="Python" name="Python">
  <configuration sdkName="" />
  </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="false">
  <content url="file://$MODULE_DIR$" />
  <orderEntry type="inheritedJdk" />
  <orderEntry type="sourceFolder" forTests="false" />
  </component>
  </module>
 
 
  <component name="DependencyValidationManager">
  <state>
  <option name="SKIP_IMPORT_STATEMENTS" value="false" />
  </state>
  </component>
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="Palette2">
  <group name="Swing">
  <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
  </item>
  <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
  </item>
  <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
  <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
  <initial-values>
  <property name="text" value="Button" />
  </initial-values>
  </item>
  <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="RadioButton" />
  </initial-values>
  </item>
  <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="CheckBox" />
  </initial-values>
  </item>
  <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="Label" />
  </initial-values>
  </item>
  <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
  <preferred-size width="200" height="200" />
  </default-constraints>
  </item>
  <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
  <preferred-size width="200" height="200" />
  </default-constraints>
  </item>
  <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
  </item>
  <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
  <preferred-size width="-1" height="20" />
  </default-constraints>
  </item>
  <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
  </item>
  <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
  </item>
  </group>
  </component>
  </project>
 
 
file:b/.idea/vcs.xml (new)
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="VcsDirectoryMappings">
  <mapping directory="$PROJECT_DIR$" vcs="Git" />
  <mapping directory="$PROJECT_DIR$/js/flotr2" vcs="Git" />
  <mapping directory="$PROJECT_DIR$/pynma" vcs="Git" />
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="ChangeListManager">
  <list default="true" id="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" name="Default" comment="">
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/Chart.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/Chart.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/Color.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/Color.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/Flotr.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/Flotr.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/Graph.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/Graph.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/lib/base64.js" afterPath="$PROJECT_DIR$/js/flotr2/lib/base64.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/basic.json" afterPath="$PROJECT_DIR$/js/flotr2/make/basic.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/build.json" afterPath="$PROJECT_DIR$/js/flotr2/make/build.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/examples.js" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/examples.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/examples.json" afterPath="$PROJECT_DIR$/js/flotr2/make/examples.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/extending-flotr.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/extending-flotr.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/flotr2.json" afterPath="$PROJECT_DIR$/js/flotr2/make/flotr2.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/js/flotr2.stable.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/js/flotr2.stable.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/lib/codemirror/lib/util/formatting.js" afterPath="$PROJECT_DIR$/js/flotr2/examples/lib/codemirror/lib/util/formatting.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/generateHourlys.php" afterPath="$PROJECT_DIR$/generateHourlys.php" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/ie.json" afterPath="$PROJECT_DIR$/js/flotr2/make/ie.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/index.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/index.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/index.html" afterPath="$PROJECT_DIR$/js/flotr2/spec/index.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine-html.js" afterPath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine-html.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine.css" afterPath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine.css" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine.js" afterPath="$PROJECT_DIR$/js/flotr2/lib/jasmine/jasmine.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json-data.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json-data.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json-real-data.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json-real-data.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json.txt" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/json.txt" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/make/lib.json" afterPath="$PROJECT_DIR$/js/flotr2/make/lib.json" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/logarithmic-scale.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/logarithmic-scale.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/mouse-zoom-preview.html" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/mouse-zoom-preview.html" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/lib/prototype.js" afterPath="$PROJECT_DIR$/js/flotr2/lib/prototype.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/examples/old_examples/style.css" afterPath="$PROJECT_DIR$/js/flotr2/examples/old_examples/style.css" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/js/test-background.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/js/test-background.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/js/test-boundaries.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/js/test-boundaries.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/flotr2/spec/js/test-mountain-nulls.js" afterPath="$PROJECT_DIR$/js/flotr2/spec/js/test-mountain-nulls.js" />
  <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
  </list>
  <ignored path="scannr.iws" />
  <ignored path=".idea/workspace.xml" />
  <file path="/Dummy.txt" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356959804071" ignored="false" />
  <file path="/calllog.php" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356153807482" ignored="false" />
  <file path="/scannr.py" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356154551131" ignored="false" />
  <file path="/start_script.py" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356155203132" ignored="false" />
  <file path="/a.java" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356155211924" ignored="false" />
  <file path="/a.php" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356155216083" ignored="false" />
  <file path="/calls.json.php" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356155700744" ignored="false" />
  <file path="/generateHourlys.php" changelist="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" time="1356960167594" ignored="false" />
  <option name="TRACKING_ENABLED" value="true" />
  <option name="SHOW_DIALOG" value="false" />
  <option name="HIGHLIGHT_CONFLICTS" value="true" />
  <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
  <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
  <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
  <disable_hints />
  </component>
  <component name="DebuggerManager">
  <breakpoint_any default_suspend_policy="SuspendAll" default_condition_enabled="true">
  <breakpoint>
  <option name="NOTIFY_CAUGHT" value="true" />
  <option name="NOTIFY_UNCAUGHT" value="true" />
  <option name="ENABLED" value="false" />
  <option name="LOG_ENABLED" value="false" />
  <option name="LOG_EXPRESSION_ENABLED" value="false" />
  <option name="SUSPEND_POLICY" value="SuspendAll" />
  <option name="SUSPEND" value="true" />
  <option name="COUNT_FILTER_ENABLED" value="false" />
  <option name="COUNT_FILTER" value="0" />
  <option name="CONDITION_ENABLED" value="true" />
  <option name="CLASS_FILTERS_ENABLED" value="false" />
  <option name="INSTANCE_FILTERS_ENABLED" value="false" />
  <option name="CONDITION" value="" />
  <option name="LOG_MESSAGE" value="" />
  </breakpoint>
  <breakpoint>
  <option name="NOTIFY_CAUGHT" value="true" />
  <option name="NOTIFY_UNCAUGHT" value="true" />
  <option name="ENABLED" value="false" />
  <option name="LOG_ENABLED" value="false" />
  <option name="LOG_EXPRESSION_ENABLED" value="false" />
  <option name="SUSPEND_POLICY" value="SuspendAll" />
  <option name="SUSPEND" value="true" />
  <option name="COUNT_FILTER_ENABLED" value="false" />
  <option name="COUNT_FILTER" value="0" />
  <option name="CONDITION_ENABLED" value="true" />
  <option name="CLASS_FILTERS_ENABLED" value="false" />
  <option name="INSTANCE_FILTERS_ENABLED" value="false" />
  <option name="CONDITION" value="" />
  <option name="LOG_MESSAGE" value="" />
  </breakpoint>
  </breakpoint_any>
  <ui_properties default_suspend_policy="SuspendAll" default_condition_enabled="true" />
  <breakpoint_rules />
  <ui_properties />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
  <favorites_list name="scannr" />
  </component>
  <component name="FileEditorManager">
  <leaf>
  <file leaf-file-name="calllog.php" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/calllog.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="2" column="0" selection-start="34" selection-end="226" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="calls.json.php" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/calls.json.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="13" column="53" selection-start="499" selection-end="499" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="generateConvos.php" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/generateConvos.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="generateHourlys.php" pinned="false" current="true" current-in-tab="true">
  <entry file="file://$PROJECT_DIR$/generateHourlys.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="23" column="6" selection-start="1012" selection-end="1012" vertical-scroll-proportion="0.68944097">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="getfile.php" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/getfile.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="11" column="13" selection-start="471" selection-end="539" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  </leaf>
  </component>
  <component name="FindManager">
  <FindUsagesManager>
  <setting name="OPEN_NEW_TAB" value="false" />
  </FindUsagesManager>
  </component>
  <component name="Git.Settings">
  <option name="SYNC_SETTING" value="DONT" />
  <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="GitLogSettings">
  <option name="myDateState">
  <MyDateState />
  </option>
  </component>
  <component name="IdeDocumentHistory">
  <option name="changedFiles">
  <list>
  <option value="$PROJECT_DIR$/common.inc.php" />
  <option value="$PROJECT_DIR$/viewcalls.php" />
  <option value="$PROJECT_DIR$/calllog.php" />
  <option value="$PROJECT_DIR$/scannr.py" />
  <option value="$PROJECT_DIR$/calls.json.php" />
  <option value="$PROJECT_DIR$/generateHourlys.php" />
  </list>
  </option>
  </component>
  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" interpreter_name="PHP" />
  <component name="ProjectFrameBounds">
  <option name="y" value="22" />
  <option name="width" value="1680" />
  <option name="height" value="936" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="true">
  <OptionsSetting value="true" id="Add" />
  <OptionsSetting value="true" id="Remove" />
  <OptionsSetting value="true" id="Checkout" />
  <OptionsSetting value="true" id="Update" />
  <OptionsSetting value="true" id="Status" />
  <OptionsSetting value="true" id="Edit" />
  <ConfirmationsSetting value="0" id="Add" />
  <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectReloadState">
  <option name="STATE" value="0" />
  </component>
  <component name="ProjectView">
  <navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
  <flattenPackages />
  <showMembers />
  <showModules />
  <showLibraryContents ProjectPane="true" />
  <hideEmptyPackages />
  <abbreviatePackageNames />
  <autoscrollToSource />
  <autoscrollFromSource />
  <sortByType />
  </navigator>
  <panes>
  <pane id="Scope" />
  <pane id="PackagesPane" />
  <pane id="ProjectPane">
  <subPane>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannr" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  </PATH>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannr" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannr" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  </PATH>
  </subPane>
  </pane>
  </panes>
  </component>
  <component name="PropertiesComponent">
  <property name="options.splitter.main.proportions" value="0.3" />
  <property name="WebServerToolWindowFactoryState" value="false" />
  <property name="options.lastSelected" value="tasks" />
  <property name="last_opened_file_path" value="$PROJECT_DIR$/../disclosr" />
  <property name="FullScreen" value="false" />
  <property name="options.searchVisible" value="true" />
  <property name="options.splitter.details.proportions" value="0.2" />
  </component>
  <component name="PyConsoleOptionsProvider">
  <option name="myPythonConsoleState">
  <PyConsoleSettings />
  </option>
  <option name="myDjangoConsoleState">
  <PyConsoleSettings />
  </option>
  </component>
  <component name="RecentsManager">
  <key name="CopyFile.RECENT_KEYS">
  <recent name="$PROJECT_DIR$" />
  </key>
  </component>
  <component name="RunManager">
  <configuration default="true" type="PHPUnitRunConfigurationType" factoryName="PHPUnit">
  <TestRunner />
  <method />
  </configuration>
  <configuration default="true" type="PhpLocalRunConfigurationType" factoryName="PHP Console">
  <method />
  </configuration>
  <configuration default="true" type="tests" factoryName="Doctests">
  <option name="INTERPRETER_OPTIONS" value="" />
  <option name="PARENT_ENVS" value="true" />
  <envs />
  <option name="SDK_HOME" value="" />
  <option name="WORKING_DIRECTORY" value="" />
  <option name="IS_MODULE_SDK" value="false" />
  <module name="scannr" />
  <EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
  <option name="SCRIPT_NAME" value="" />
  <option name="CLASS_NAME" value="" />
  <option name="METHOD_NAME" value="" />
  <option name="FOLDER_NAME" value="" />
  <option name="TEST_TYPE" value="TEST_SCRIPT" />
  <option name="PATTERN" value="" />
  <option name="USE_PATTERN" value="false" />
  <method />
  </configuration>
  <configuration default="true" type="JavascriptDebugSession" factoryName="Local" singleton="true">
  <JSDebuggerConfigurationSettings>
  <option name="engineId" value="embedded" />
  <option name="fileUrl" />
  </JSDebuggerConfigurationSettings>
  <method />
  </configuration>
  <list size="0" />
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="SvnConfiguration" maxAnnotateRevisions="500" myUseAcceleration="nothing" myAutoUpdateAfterCommit="false" cleanupOnStartRun="false">
  <option name="USER" value="" />
  <option name="PASSWORD" value="" />
  <option name="mySSHConnectionTimeout" value="30000" />
  <option name="mySSHReadTimeout" value="30000" />
  <option name="LAST_MERGED_REVISION" />
  <option name="MERGE_DRY_RUN" value="false" />
  <option name="MERGE_DIFF_USE_ANCESTRY" value="true" />
  <option name="UPDATE_LOCK_ON_DEMAND" value="false" />
  <option name="IGNORE_SPACES_IN_MERGE" value="false" />
  <option name="DETECT_NESTED_COPIES" value="true" />
  <option name="CHECK_NESTED_FOR_QUICK_MERGE" value="false" />
  <option name="IGNORE_SPACES_IN_ANNOTATE" value="true" />
  <option name="SHOW_MERGE_SOURCES_IN_ANNOTATE" value="true" />
  <option name="FORCE_UPDATE" value="false" />
  <option name="IGNORE_EXTERNALS" value="false" />
  <myIsUseDefaultProxy>false</myIsUseDefaultProxy>
  </component>
  <component name="TaskManager">
  <task active="true" id="Default" summary="Default task">
  <changelist id="f90ee5b5-97e4-47ec-9b14-d4f4e896f100" name="Default" comment="" />
  <created>1350026709905</created>
  <updated>1350026709905</updated>
  </task>
  <servers />
  </component>
  <component name="ToolWindowManager">
  <frame x="0" y="22" width="1680" height="936" extended-state="6" />
  <editor active="true" />
  <layout>
  <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
  <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32843137" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
  <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
  <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
  <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" />
  <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
  <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.19645043" sideWeight="0.67156863" order="0" side_tool="false" content_ui="combo" />
  <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
  <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
  <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
  <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
  <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
  <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
  </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
  <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
  <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
  <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
  <option name="CHECK_NEW_TODO" value="true" />
  <option name="myTodoPanelSettings">
  <value>
  <are-packages-shown value="false" />
  <are-modules-shown value="false" />
  <flatten-packages value="false" />
  <is-autoscroll-to-source value="false" />
  </value>
  </option>
  <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
  <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
  <option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
  <option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="false" />
  <option name="CHANGED_ON_SERVER_INTERVAL" value="60" />
  <option name="SHOW_ONLY_CHANGED_IN_SELECTION_DIFF" value="true" />
  <option name="CHECK_COMMIT_MESSAGE_SPELLING" value="true" />
  <option name="DEFAULT_PATCH_EXTENSION" value="patch" />
  <option name="SHORT_DIFF_HORISONTALLY" value="true" />
  <option name="SHORT_DIFF_EXTRA_LINES" value="2" />
  <option name="SOFT_WRAPS_IN_SHORT_DIFF" value="true" />
  <option name="INCLUDE_TEXT_INTO_PATCH" value="false" />
  <option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
  <option name="SHOW_FILE_HISTORY_DETAILS" value="true" />
  <option name="SHOW_VCS_ERROR_NOTIFICATIONS" value="true" />
  <option name="SHOW_DIRTY_RECURSIVELY" value="false" />
  <option name="LIMIT_HISTORY" value="true" />
  <option name="MAXIMUM_HISTORY_ROWS" value="1000" />
  <option name="FORCE_NON_EMPTY_COMMENT" value="false" />
  <option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="false" />
  <option name="LAST_COMMIT_MESSAGE" />
  <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="false" />
  <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
  <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
  <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
  <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
  <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
  <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
  <option name="ACTIVE_VCS_NAME" />
  <option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
  <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
  <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
  <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
  </component>
  <component name="XDebuggerManager">
  <breakpoint-manager />
  </component>
  <component name="antWorkspaceConfiguration">
  <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" />
  <option name="FILTER_TARGETS" value="false" />
  </component>
  <component name="editorHistoryManager">
  <entry file="file://$PROJECT_DIR$/viewcalls.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="2" column="13" selection-start="46" selection-end="46" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/common.inc.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="34" column="0" selection-start="1179" selection-end="1179" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/calls.json.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="2" column="9" selection-start="42" selection-end="42" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/trunklog.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/../disclosr/include/template.inc.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="72" column="93" selection-start="2545" selection-end="2635" vertical-scroll-proportion="0.43404254" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/../disclosr/include/common.inc.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/../busui/myway/myway_timeliness.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="27" column="5" selection-start="1003" selection-end="1018" vertical-scroll-proportion="26.346153" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/snd.py">
  <provider selected="true" editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/common.inc.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="60" column="117" selection-start="2262" selection-end="2262" vertical-scroll-proportion="-39.23077" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/viewcalls.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="41" column="69" selection-start="1388" selection-end="1388" vertical-scroll-proportion="1.2659575" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/scannr.py">
  <provider selected="true" editor-type-id="text-editor">
  <state line="80" column="64" selection-start="2271" selection-end="2271" vertical-scroll-proportion="0.0" />
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/calllog.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="2" column="0" selection-start="34" selection-end="226" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/calls.json.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="13" column="53" selection-start="499" selection-end="499" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/generateConvos.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/getfile.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="11" column="13" selection-start="471" selection-end="539" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/generateHourlys.php">
  <provider selected="true" editor-type-id="text-editor">
  <state line="23" column="6" selection-start="1012" selection-end="1012" vertical-scroll-proportion="0.68944097">
  <folding />
  </state>
  </provider>
  </entry>
  </component>
  </project>
 
 
file:b/404.html (new)
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="utf-8">
  <title>Page Not Found :(</title>
  <style>
  ::-moz-selection {
  background: #b3d4fc;
  text-shadow: none;
  }
 
  ::selection {
  background: #b3d4fc;
  text-shadow: none;
  }
 
  html {
  padding: 30px 10px;
  font-size: 20px;
  line-height: 1.4;
  color: #737373;
  background: #f0f0f0;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  }
 
  html,
  input {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  }
 
  body {
  max-width: 500px;
  _width: 500px;
  padding: 30px 20px 50px;
  border: 1px solid #b3b3b3;
  border-radius: 4px;
  margin: 0 auto;
  box-shadow: 0 1px 10px #a7a7a7, inset 0 1px 0 #fff;
  background: #fcfcfc;
  }
 
  h1 {
  margin: 0 10px;
  font-size: 50px;
  text-align: center;
  }
 
  h1 span {
  color: #bbb;
  }
 
  h3 {
  margin: 1.5em 0 0.5em;
  }
 
  p {
  margin: 1em 0;
  }
 
  ul {
  padding: 0 0 0 40px;
  margin: 1em 0;
  }
 
  .container {
  max-width: 380px;
  _width: 380px;
  margin: 0 auto;
  }
 
  /* google search */
 
  #goog-fixurl ul {
  list-style: none;
  padding: 0;
  margin: 0;
  }
 
  #goog-fixurl form {
  margin: 0;
  }
 
  #goog-wm-qt,
  #goog-wm-sb {
  border: 1px solid #bbb;
  font-size: 16px;
  line-height: normal;
  vertical-align: top;
  color: #444;
  border-radius: 2px;
  }
 
  #goog-wm-qt {
  width: 220px;
  height: 20px;
  padding: 5px;
  margin: 5px 10px 0 0;
  box-shadow: inset 0 1px 1px #ccc;
  }
 
  #goog-wm-sb {
  display: inline-block;
  height: 32px;
  padding: 0 10px;
  margin: 5px 0 0;
  white-space: nowrap;
  cursor: pointer;
  background-color: #f5f5f5;
  background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0), #f1f1f1);
  background-image: -moz-linear-gradient(rgba(255, 255, 255, 0), #f1f1f1);
  background-image: -ms-linear-gradient(rgba(255, 255, 255, 0), #f1f1f1);
  background-image: -o-linear-gradient(rgba(255, 255, 255, 0), #f1f1f1);
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  *overflow: visible;
  *display: inline;
  *zoom: 1;
  }
 
  #goog-wm-sb:hover,
  #goog-wm-sb:focus {
  border-color: #aaa;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  background-color: #f8f8f8;
  }
 
  #goog-wm-qt:hover,
  #goog-wm-qt:focus {
  border-color: #105cb6;
  outline: 0;
  color: #222;
  }
 
  input::-moz-focus-inner {
  padding: 0;
  border: 0;
  }
  </style>
  </head>
  <body>
  <div class="container">
  <h1>Not found <span>:(</span></h1>
 
  <p>Sorry, but the page you were trying to view does not exist.</p>
 
  <p>It looks like this was the result of either:</p>
  <ul>
  <li>a mistyped address</li>
  <li>an out-of-date link</li>
  </ul>
  <script>
  var GOOG_FIXURL_LANG = (navigator.language || '').slice(0, 2), GOOG_FIXURL_SITE = location.host;
  </script>
  <script src="http://linkhelp.clients.google.com/tbproxy/lh/wm/fixurl.js"></script>
  </div>
  </body>
  </html>
 
file:b/CHANGELOG.md (new)
  ### HEAD
 
  ### 4.0.0 (28 August, 2012)
 
  * Improve the Apache compression configuration ([#1012](https://github.com/h5bp/html5-boilerplate/issues/1012), [#1173](https://github.com/h5bp/html5-boilerplate/issues/1173)).
  * Add a HiDPI example media query ([#1127](https://github.com/h5bp/html5-boilerplate/issues/1127)).
  * Add bundled docs ([#1154](https://github.com/h5bp/html5-boilerplate/issues/1154)).
  * Add MIT license ([#1139](https://github.com/h5bp/html5-boilerplate/issues/1139)).
  * Update to Normalize.css 1.0.1.
  * Separate Normalize.css from the rest of the CSS ([#1160](https://github.com/h5bp/html5-boilerplate/issues/1160)).
  * Improve `console.log` protection ([#1107](https://github.com/h5bp/html5-boilerplate/issues/1107)).
  * Replace hot pink text selection color with a neutral color.
  * Change image replacement technique ([#1149](https://github.com/h5bp/html5-boilerplate/issues/1149)).
  * Code format and consistency changes ([#1112](https://github.com/h5bp/html5-boilerplate/issues/1112)).
  * Rename CSS file and rename JS files and subdirectories.
  * Update to jQuery 1.8 ([#1161](https://github.com/h5bp/html5-boilerplate/issues/1161)).
  * Update to Modernizr 2.6.1 ([#1086](https://github.com/h5bp/html5-boilerplate/issues/1086)).
  * Remove uncompressed jQuery ([#1153](https://github.com/h5bp/html5-boilerplate/issues/1153)).
  * Remove superfluous inline comments ([#1150](https://github.com/h5bp/html5-boilerplate/issues/1150)).
 
  ### 3.0.2 (February 19, 2012)
 
  * Update to Modernizr 2.5.3.
 
  ### 3.0.1 (February 08, 2012).
 
  * Update to Modernizr 2.5.2 (includes html5shiv 3.3).
 
  ### 3.0.0 (February 06, 2012)
 
  * Improvements to `.htaccess`.
  * Improve 404 design.
  * Simplify JS folder structure.
  * Change `html` IE class names changed to target ranges rather than specific versions of IE.
  * Update CSS to include latest normalize.css changes and better typographic defaults ([#825](https://github.com/h5bp/html5-boilerplate/issues/825)).
  * Update to Modernizr 2.5 (includes yepnope 1.5 and html5shiv 3.2).
  * Update to jQuery 1.7.1.
  * Revert to async snippet for the Google Analytics script.
  * Remove the ant build script ([#826](https://github.com/h5bp/html5-boilerplate/issues/826)).
  * Remove Respond.js ([#816](https://github.com/h5bp/html5-boilerplate/issues/816)).
  * Remove the `demo/` directory ([#808](https://github.com/h5bp/html5-boilerplate/issues/808)).
  * Remove the `test/` directory ([#808](https://github.com/h5bp/html5-boilerplate/issues/808)).
  * Remove Google Chrome Frame script for IE6 users; replace with links to Chrome Frame and options for alternative browsers.
  * Remove `initial-scale=1` from the viewport `meta` ([#824](https://github.com/h5bp/html5-boilerplate/issues/824)).
  * Remove `defer` from all scripts to avoid legacy IE bugs.
  * Remove explicit Site Speed tracking for Google Analytics. It's now enabled by default.
 
  ### 2.0.0 (August 10, 2011)
 
  * Change starting CSS to be based on normalize.css instead of reset.css ([#500](https://github.com/h5bp/html5-boilerplate/issues/500)).
  * Add Respond.js media query polyfill.
  * Add Google Chrome Frame script prompt for IE6 users.
  * Simplify the `html` conditional comments for modern browsers and add an `oldie` class.
  * Update clearfix to use "micro clearfix".
  * Add placeholder CSS MQs for mobile-first approach.
  * Add `textarea { resize: vertical; }` to only allow vertical resizing.
  * Add `img { max-width: 100%; }` to the print styles; prevents images being truncated.
  * Add Site Speed tracking for Google Analytics.
  * Update to jQuery 1.6.2 (and use minified by default).
  * Update to Modernizr 2.0 Complete, Production minified (includes yepnope, html5shiv, and Respond.js).
  * Use `Modernizr.load()` to load the Google Analytics script.
  * Much faster build process.
  * Add build script options for CSSLint, JSLint, JSHint tools.
  * Build script now compresses all images in subfolders.
  * Build script now versions files by SHA hash.
  * Many `.htaccess` improvements including: disable directory browsing, improved support for all versions of Apache, more robust and extensive HTTP compression rules.
  * Remove `handheld.css` as it has very poor device support.
  * Remove touch-icon `link` elements from the HTML and include improved touch-icon support.
  * Remove the cache-busting query paramaters from files references in the HTML.
  * Remove IE6 PNGFix.
 
  ### 1.0.0 (March 21, 2011)
 
  * Rewrite build script to make it more customizable and flexible.
  * Add a humans.txt.
  * Numerous `.htaccess` improvements (including inline documentation).
  * Move the alternative server configurations to the H5BP server configs repo.
  * Use a protocol-relative url to reference jQuery and prevent mixed content warnings.
  * Optimize the Google Analytics snippet.
  * Use Eric Meyer's recent CSS reset update and the HTML5 Doctor reset.
  * More robust `sub`/`sup` CSS styles.
  * Add keyboard `.focusable` helper class that extends `.visuallyhidden`.
  * Print styles no longer print hash or JavaScript links.
  * Add a print reset for IE's proprietary filters.
  * Remove IE9-specific conditional class on the `html` element.
  * Remove margins from lists within `nav` elements.
  * Remove YUI profiling.
 
file:b/LICENSE.md (new)
  Copyright (c) HTML5 Boilerplate
 
  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  of the Software, and to permit persons to whom the Software is furnished to do
  so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
 
file:b/README.md (new)
  # [HTML5 Boilerplate](http://html5boilerplate.com)
 
  HTML5 Boilerplate is a professional front-end template for building fast,
  robust, and adaptable web apps or sites.
 
  This project is the product of many years of iterative development and combined
  community knowledge. It does not impose a specific development philosophy or
  framework, so you're free to architect your code in the way that you want.
 
  * Source: [https://github.com/h5bp/html5-boilerplate](https://github.com/h5bp/html5-boilerplate)
  * Homepage: [http://html5boilerplate.com](http://html5boilerplate.com)
  * Twitter: [@h5bp](http://twitter.com/h5bp)
 
 
  ## Quick start
 
  Choose one of the following options:
 
  1. Download the latest stable release from
  [html5boilerplate.com](http://html5boilerplate.com/) or a custom build from
  [Initializr](http://www.initializr.com).
  2. Clone the git repo — `git clone
  https://github.com/h5bp/html5-boilerplate.git` - and checkout the tagged
  release you'd like to use.
 
 
  ## Features
 
  * HTML5 ready. Use the new elements with confidence.
  * Cross-browser compatible (Chrome, Opera, Safari, Firefox 3.6+, IE6+).
  * Designed with progressive enhancement in mind.
  * Includes [Normalize.css](http://necolas.github.com/normalize.css/) for CSS
  normalizations and common bug fixes.
  * The latest [jQuery](http://jquery.com/) via CDN, with a local fallback.
  * The latest [Modernizr](http://modernizr.com/) build for feature detection.
  * IE-specific classes for easier cross-browser control.
  * Placeholder CSS Media Queries.
  * Useful CSS helpers.
  * Default print CSS, performance optimized.
  * Protection against any stray `console.log` causing JavaScript errors in
  IE6/7.
  * An optimized Google Analytics snippet.
  * Apache server caching, compression, and other configuration defaults for
  Grade-A performance.
  * Cross-domain Ajax and Flash.
  * "Delete-key friendly." Easy to strip out parts you don't need.
  * Extensive inline and accompanying documentation.
 
 
  ## Documentation
 
  Take a look at the [documentation table of
  contents](/h5bp/html5-boilerplate/blob/master/doc/README.md). This
  documentation is bundled with the project, which makes it readily available for
  offline reading and provides a useful starting point for any documentation
  you want to write about your project.
 
 
  ## Contributing
 
  Anyone and everyone is welcome to
  [contribute](/h5bp/html5-boilerplate/blob/master/doc/contribute.md). Hundreds
  of developers have helped make the HTML5 Boilerplate what it is today.
 
 Binary files /dev/null and b/apple-touch-icon-114x114-precomposed.png differ
 Binary files /dev/null and b/apple-touch-icon-144x144-precomposed.png differ
 Binary files /dev/null and b/apple-touch-icon-57x57-precomposed.png differ
 Binary files /dev/null and b/apple-touch-icon-72x72-precomposed.png differ
 Binary files /dev/null and b/apple-touch-icon-precomposed.png differ
 Binary files /dev/null and b/apple-touch-icon.png differ
file:b/calllog.php (new)
  <?php
  include ('common.inc.php');
  $sth = $conn->prepare('select * from recordings
  order by call_timestamp desc limit 1000');
 
  $sth->execute(Array());
 
  $row = 0;
  echo "<table>";
  foreach ($sth->fetchAll() as $data) {
 
 
  echo "<tr>";
  for ($c = 0; $c < count($data); $c++) {
  echo '<td>' . $data[$c] . "</td>\n";
  }
  echo "</tr>";
  }
  $row++;
  echo "</table>";
 
file:b/calls.json.php (new)
  <?php
  include('common.inc.php');
  function getTGIDValuesByHour($TGID, $timeFrom, $timeTo)
  {
  global $conn;
  $sth = $conn->prepare('select tgid, min(call_timestamp) as time, count(*), min(length), max(length), avg(length), stddev(length) from recordings
  where call_timestamp between to_timestamp(?) and to_timestamp(?)
  group by tgid, date_trunc(\'hour\', call_timestamp) order by time');
 
  $sth->execute(Array($timeFrom, $timeTo));
  return $sth->fetchAll(PDO::FETCH_ASSOC);
 
 
  }
 
  function getTGIDValuesByDay($TGID, $dayFrom, $dayTo)
  {
  global $conn;
  $sth = $conn->prepare('select min(time) as time, min(value), max(value), avg(value), stddev(value) from sensor_values where sensor_id = ?
  group by sensor_id, date_trunc(\'day\', time) order by time');
 
  $sth->execute(Array($TGID));
  return $sth->fetchAll(PDO::FETCH_ASSOC);
  }
  function getTGIDDataYears($TGID, $timeFrom, $timeTo)
  {
  global $conn;
  $sth = $conn->prepare("select distinct extract('year' from call_timestamp) as year from recordings where tgid = ? order by year");
 
  $sth->execute(Array($TGID));
  return $sth->fetchAll(PDO::FETCH_ASSOC);
  }
 
  function getTGIDDataMonths($TGID, $timeFrom, $timeTo)
  {
  global $conn;
  $sth = $conn->prepare("select distinct extract('month' from call_timestamp) as month, extract('year' from call_timestamp) as year from recordings where tgid = ? order by year, month");
 
  $sth->execute(Array($TGID));
  return $sth->fetchAll(PDO::FETCH_ASSOC);
  }
 
  function getTGIDDataDays($TGID, $timeFrom, $timeTo)
  {
  global $conn;
  $sth = $conn->prepare("select distinct extract('day' from call_timestamp) as day, extract('month' from call_timestamp) as month, extract('year' from call_timestamp) as year from recordings where tgid = ? order by year,month,day");
 
 
  $sth->execute(Array($TGID));
  return $sth->fetchAll(PDO::FETCH_ASSOC);
  }
  $action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
  $TGID = (isset($_REQUEST['tgid']) ? $_REQUEST['tgid'] : '');
  $timefrom = (isset($_REQUEST['from']) ? $_REQUEST['from'] : '');
  $timeto = (isset($_REQUEST['to']) ? $_REQUEST['to'] : '');
 
  if ($action == "data") {
  $sth = $conn->prepare('select * from recordings
  order by call_timestamp desc limit 100');
 
  $sth->execute(Array());
 
  echo json_encode ($sth->fetchAll(PDO::FETCH_ASSOC));
  }
  if ($action == "data_description") {
  $timefrom = strtotime($timefrom);
  $timeto = strtotime($timeto);
  $years = getTGIDDataYears($TGID, $timefrom, $timeto);
 
  $months = getTGIDDataMonths($TGID, $timefrom, $timeto);
  $days = getTGIDDataDays($TGID, $timefrom, $timeto);
 
  echo json_encode(Array("years" => $years, "months" => $months, "days" => $days
  ));
  }
 
 
  if (strpos($action, "graph") !== false) {
  $values = getTGIDValuesByHour($TGID, $timefrom, $timeto);
  $label = $TGID;
  $data = Array();
  $tzoffset = get_timezone_offset("UTC");
  foreach ($values as $value) {
  if ($action == "graphlength") {
  $data[$value['tgid']][] = Array((strtotime($value['time']) + $tzoffset) * 1000, intval($value['avg']));
  } else if ($action == "graphcount") {
  $data[$value['tgid']][] = Array((strtotime($value['time']) + $tzoffset) * 1000, intval($value['count']));
  }
  }
  echo json_encode(Array("label" => $label, "data" => $data,
  "previous" => Array(
  "from" => $timefrom - (24 * 60 * 60),
  "to" => $timefrom)
  ,
  "next" => Array(
  "to" => $timeto + (24 * 60 * 60),
  "from" => $timeto)
  )
  );
  }
 
 
 
  ?>
 
file:b/common.inc.php (new)
  <?php
  date_default_timezone_set("Australia/Sydney");
  try {
  $conn = new PDO("pgsql:dbname=scannr;user=postgres;password=snmc;host=localhost");
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch (PDOException $e) {
  die('Unable to connect to database server.');
  }
  catch (Exception $e) {
  die('Unknown error in ' . __FILE__ . '.');
  }
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  $basePath = "";
  $DATA_DIR = "./data";
 
  /** Returns the offset from the origin timezone to the remote timezone, in seconds.
  * @param $remote_tz;
  * @param $origin_tz; If null the servers current timezone is used as the origin.
  * @return int;
  */
  function get_timezone_offset($remote_tz, $origin_tz = null)
  {
  if ($origin_tz === null) {
  if (!is_string($origin_tz = date_default_timezone_get())) {
  return false; // A UTC timestamp was returned -- bail out!
  }
  }
  $origin_dtz = new DateTimeZone($origin_tz);
  $remote_dtz = new DateTimeZone($remote_tz);
  $origin_dt = new DateTime("now", $origin_dtz);
  $remote_dt = new DateTime("now", $remote_dtz);
  $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
  return $offset;
  }
 
 
  function include_header($title)
  {
  global $basePath;
  ?>
  <!DOCTYPE html>
  <!--[if lt IE 7]>
  <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
  <!--[if IE 7]>
  <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
  <!--[if IE 8]>
  <html class="no-js lt-ie9"> <![endif]-->
  <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">
 
  <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
 
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/main.css">
  <script src="js/vendor/modernizr-2.6.1.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  <!--<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.0.min.js"><\/script>')</script>-->
  <script type="text/javascript" src="<?php echo $basePath ?>js/flotr2/flotr2.js"></script>
  <script src="js/plugins.js"></script>
  <script src="js/main.js"></script>
  </head>
  <body>
  <!--[if lt IE 7]>
  <p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser
  today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to
  better experience this site.</p>
  <![endif]-->
 
  <!-- Add your site or application content here -->
  <?php
  }
 
  function include_footer()
  {
  global $basePath;
  ?>
 
 
  <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
  <script>
  var _gaq = [
  ['_setAccount', 'UA-XXXXX-X'],
  ['_trackPageview']
  ];
  (function (d, t) {
  var g = d.createElement(t), s = d.getElementsByTagName(t)[0];
  g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
  s.parentNode.insertBefore(g, s)
  }(document, 'script'));
  </script>
  </body>
  </html>
 
  <?php
 
  }
 
 
file:b/cron.php (new)
  <?php
  /*- scheduled tasks
  - combine recordings into conversations
  - using ffmpeg
  - conversations and recordings_to_conversations tables
  - remove all other wav files
  - delete old uninteresting conversations*/
  ?>
 
file:b/crossdomain.xml (new)
  <?xml version="1.0"?>
  <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
  <cross-domain-policy>
  <!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
 
  <!-- Most restrictive policy: -->
  <site-control permitted-cross-domain-policies="none"/>
 
  <!-- Least restrictive policy: -->
  <!--
  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*" to-ports="*" secure="false"/>
  <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
  -->
  </cross-domain-policy>
 
file:b/css/main.css (new)
  /*
  * HTML5 Boilerplate
  *
  * What follows is the result of much research on cross-browser styling.
  * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
  * Kroc Camen, and the H5BP dev community and team.
  */
 
  /* ==========================================================================
  Base styles: opinionated defaults
  ========================================================================== */
 
  html,
  button,
  input,
  select,
  textarea {
  color: #222;
  }
 
  body {
  font-size: 1em;
  line-height: 1.4;
  }
 
  /*
  * Remove text-shadow in selection highlight: h5bp.com/i
  * These selection declarations have to be separate.
  * Customize the background color to match your design.
  */
 
  ::-moz-selection {
  background: #b3d4fc;
  text-shadow: none;
  }
 
  ::selection {
  background: #b3d4fc;
  text-shadow: none;
  }
 
  /*
  * A better looking default horizontal rule
  */
 
  hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #ccc;
  margin: 1em 0;
  padding: 0;
  }
 
  /*
  * Remove the gap between images and the bottom of their containers: h5bp.com/i/440
  */
 
  img {
  vertical-align: middle;
  }
 
  /*
  * Remove default fieldset styles.
  */
 
  fieldset {
  border: 0;
  margin: 0;
  padding: 0;
  }
 
  /*
  * Allow only vertical resizing of textareas.
  */
 
  textarea {
  resize: vertical;
  }
 
  /* ==========================================================================
  Chrome Frame prompt
  ========================================================================== */
 
  .chromeframe {
  margin: 0.2em 0;
  background: #ccc;
  color: #000;
  padding: 0.2em 0;
  }
 
  /* ==========================================================================
  Author's custom styles
  ========================================================================== */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  /* ==========================================================================
  Helper classes
  ========================================================================== */
 
  /*
  * Image replacement
  */
 
  .ir {
  background-color: transparent;
  border: 0;
  overflow: hidden;
  /* IE 6/7 fallback */
  *text-indent: -9999px;
  }
 
  .ir:before {
  content: "";
  display: block;
  width: 0;
  height: 100%;
  }
 
  /*
  * Hide from both screenreaders and browsers: h5bp.com/u
  */
 
  .hidden {
  display: none !important;
  visibility: hidden;
  }
 
  /*
  * Hide only visually, but have it available for screenreaders: h5bp.com/v
  */
 
  .visuallyhidden {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
  }
 
  /*
  * Extends the .visuallyhidden class to allow the element to be focusable
  * when navigated to via the keyboard: h5bp.com/p
  */
 
  .visuallyhidden.focusable:active,
  .visuallyhidden.focusable:focus {
  clip: auto;
  height: auto;
  margin: 0;
  overflow: visible;
  position: static;
  width: auto;
  }
 
  /*
  * Hide visually and from screenreaders, but maintain layout
  */
 
  .invisible {
  visibility: hidden;
  }
 
  /*
  * Clearfix: contain floats
  *
  * For modern browsers
  * 1. The space content is one way to avoid an Opera bug when the
  * `contenteditable` attribute is included anywhere else in the document.
  * Otherwise it causes space to appear at the top and bottom of elements
  * that receive the `clearfix` class.
  * 2. The use of `table` rather than `block` is only necessary if using
  * `:before` to contain the top-margins of child elements.
  */
 
  .clearfix:before,
  .clearfix:after {
  content: " "; /* 1 */
  display: table; /* 2 */
  }
 
  .clearfix:after {
  clear: both;
  }
 
  /*
  * For IE 6/7 only
  * Include this rule to trigger hasLayout and contain floats.
  */
 
  .clearfix {
  *zoom: 1;
  }
 
  /* ==========================================================================
  EXAMPLE Media Queries for Responsive Design.
  Theses examples override the primary ('mobile first') styles.
  Modify as content requires.
  ========================================================================== */
 
  @media only screen and (min-width: 35em) {
  /* Style adjustments for viewports that meet the condition */
  }
 
  @media only screen and (-webkit-min-device-pixel-ratio: 1.5),
  only screen and (min-resolution: 144dpi) {
  /* Style adjustments for high resolution devices */
  }
 
  /* ==========================================================================
  Print styles.
  Inlined to avoid required HTTP connection: h5bp.com/r
  ========================================================================== */
 
  @media print {
  * {
  background: transparent !important;
  color: #000 !important; /* Black prints faster: h5bp.com/s */
  box-shadow:none !important;
  text-shadow: none !important;
  }
 
  a,
  a:visited {
  text-decoration: underline;
  }
 
  a[href]:after {
  content: " (" attr(href) ")";
  }
 
  abbr[title]:after {
  content: " (" attr(title) ")";
  }
 
  /*
  * Don't show links for images, or javascript/internal links
  */
 
  .ir a:after,
  a[href^="javascript:"]:after,
  a[href^="#"]:after {
  content: "";
  }
 
  pre,
  blockquote {
  border: 1px solid #999;
  page-break-inside: avoid;
  }
 
  thead {
  display: table-header-group; /* h5bp.com/t */
  }
 
  tr,
  img {
  page-break-inside: avoid;
  }
 
  img {
  max-width: 100% !important;
  }
 
  @page {
  margin: 0.5cm;
  }
 
  p,
  h2,
  h3 {
  orphans: 3;
  widows: 3;
  }
 
  h2,
  h3 {
  page-break-after: avoid;
  }
  }
 
file:b/css/normalize.css (new)
  /*! normalize.css v1.0.1 | MIT License | git.io/normalize */
 
  /* ==========================================================================
  HTML5 display definitions
  ========================================================================== */
 
  /*
  * Corrects `block` display not defined in IE 6/7/8/9 and Firefox 3.
  */
 
  article,
  aside,
  details,
  figcaption,
  figure,
  footer,
  header,
  hgroup,
  nav,
  section,
  summary {
  display: block;
  }
 
  /*
  * Corrects `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
  */
 
  audio,
  canvas,
  video {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  }
 
  /*
  * Prevents modern browsers from displaying `audio` without controls.
  * Remove excess height in iOS 5 devices.
  */
 
  audio:not([controls]) {
  display: none;
  height: 0;
  }
 
  /*
  * Addresses styling for `hidden` attribute not present in IE 7/8/9, Firefox 3,
  * and Safari 4.
  * Known issue: no IE 6 support.
  */
 
  [hidden] {
  display: none;
  }
 
  /* ==========================================================================
  Base
  ========================================================================== */
 
  /*
  * 1. Corrects text resizing oddly in IE 6/7 when body `font-size` is set using
  * `em` units.
  * 2. Prevents iOS text size adjust after orientation change, without disabling
  * user zoom.
  */
 
  html {
  font-size: 100%; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */
  -ms-text-size-adjust: 100%; /* 2 */
  }
 
  /*
  * Addresses `font-family` inconsistency between `textarea` and other form
  * elements.
  */
 
  html,
  button,
  input,
  select,
  textarea {
  font-family: sans-serif;
  }
 
  /*
  * Addresses margins handled incorrectly in IE 6/7.
  */
 
  body {
  margin: 0;
  }
 
  /* ==========================================================================
  Links
  ========================================================================== */
 
  /*
  * Addresses `outline` inconsistency between Chrome and other browsers.
  */
 
  a:focus {
  outline: thin dotted;
  }
 
  /*
  * Improves readability when focused and also mouse hovered in all browsers.
  */
 
  a:active,
  a:hover {
  outline: 0;
  }
 
  /* ==========================================================================
  Typography
  ========================================================================== */
 
  /*
  * Addresses font sizes and margins set differently in IE 6/7.
  * Addresses font sizes within `section` and `article` in Firefox 4+, Safari 5,
  * and Chrome.
  */
 
  h1 {
  font-size: 2em;
  margin: 0.67em 0;
  }
 
  h2 {
  font-size: 1.5em;
  margin: 0.83em 0;
  }
 
  h3 {
  font-size: 1.17em;
  margin: 1em 0;
  }
 
  h4 {
  font-size: 1em;
  margin: 1.33em 0;
  }
 
  h5 {
  font-size: 0.83em;
  margin: 1.67em 0;
  }
 
  h6 {
  font-size: 0.75em;
  margin: 2.33em 0;
  }
 
  /*
  * Addresses styling not present in IE 7/8/9, Safari 5, and Chrome.
  */
 
  abbr[title] {
  border-bottom: 1px dotted;
  }
 
  /*
  * Addresses style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
  */
 
  b,
  strong {
  font-weight: bold;
  }
 
  blockquote {
  margin: 1em 40px;
  }
 
  /*
  * Addresses styling not present in Safari 5 and Chrome.
  */
 
  dfn {
  font-style: italic;
  }
 
  /*
  * Addresses styling not present in IE 6/7/8/9.
  */
 
  mark {
  background: #ff0;
  color: #000;
  }
 
  /*
  * Addresses margins set differently in IE 6/7.
  */
 
  p,
  pre {
  margin: 1em 0;
  }
 
  /*
  * Corrects font family set oddly in IE 6, Safari 4/5, and Chrome.
  */
 
  code,
  kbd,
  pre,
  samp {
  font-family: monospace, serif;
  _font-family: 'courier new', monospace;
  font-size: 1em;
  }
 
  /*
  * Improves readability of pre-formatted text in all browsers.
  */
 
  pre {
  white-space: pre;
  white-space: pre-wrap;
  word-wrap: break-word;
  }
 
  /*
  * Addresses CSS quotes not supported in IE 6/7.
  */
 
  q {
  quotes: none;
  }
 
  /*
  * Addresses `quotes` property not supported in Safari 4.
  */
 
  q:before,
  q:after {
  content: '';
  content: none;
  }
 
  /*
  * Addresses inconsistent and variable font size in all browsers.
  */
 
  small {
  font-size: 80%;
  }
 
  /*
  * Prevents `sub` and `sup` affecting `line-height` in all browsers.
  */
 
  sub,
  sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
  }
 
  sup {
  top: -0.5em;
  }
 
  sub {
  bottom: -0.25em;
  }
 
  /* ==========================================================================
  Lists
  ========================================================================== */
 
  /*
  * Addresses margins set differently in IE 6/7.
  */
 
  dl,
  menu,
  ol,
  ul {
  margin: 1em 0;
  }
 
  dd {
  margin: 0 0 0 40px;
  }
 
  /*
  * Addresses paddings set differently in IE 6/7.
  */
 
  menu,
  ol,
  ul {
  padding: 0 0 0 40px;
  }
 
  /*
  * Corrects list images handled incorrectly in IE 7.
  */
 
  nav ul,
  nav ol {
  list-style: none;
  list-style-image: none;
  }
 
  /* ==========================================================================
  Embedded content
  ========================================================================== */
 
  /*
  * 1. Removes border when inside `a` element in IE 6/7/8/9 and Firefox 3.
  * 2. Improves image quality when scaled in IE 7.
  */
 
  img {
  border: 0; /* 1 */
  -ms-interpolation-mode: bicubic; /* 2 */
  }
 
  /*
  * Corrects overflow displayed oddly in IE 9.
  */
 
  svg:not(:root) {
  overflow: hidden;
  }
 
  /* ==========================================================================
  Figures
  ========================================================================== */
 
  /*
  * Addresses margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
  */
 
  figure {
  margin: 0;
  }
 
  /* ==========================================================================
  Forms
  ========================================================================== */
 
  /*
  * Corrects margin displayed oddly in IE 6/7.
  */
 
  form {
  margin: 0;
  }
 
  /*
  * Define consistent border, margin, and padding.
  */
 
  fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em;
  }
 
  /*
  * 1. Corrects color not being inherited in IE 6/7/8/9.
  * 2. Corrects text not wrapping in Firefox 3.
  * 3. Corrects alignment displayed oddly in IE 6/7.
  */
 
  legend {
  border: 0; /* 1 */
  padding: 0;
  white-space: normal; /* 2 */
  *margin-left: -7px; /* 3 */
  }
 
  /*
  * 1. Corrects font size not being inherited in all browsers.
  * 2. Addresses margins set differently in IE 6/7, Firefox 3+, Safari 5,
  * and Chrome.
  * 3. Improves appearance and consistency in all browsers.
  */
 
  button,
  input,
  select,
  textarea {
  font-size: 100%; /* 1 */
  margin: 0; /* 2 */
  vertical-align: baseline; /* 3 */
  *vertical-align: middle; /* 3 */
  }
 
  /*
  * Addresses Firefox 3+ setting `line-height` on `input` using `!important` in
  * the UA stylesheet.
  */
 
  button,
  input {
  line-height: normal;
  }
 
  /*
  * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
  * and `video` controls.
  * 2. Corrects inability to style clickable `input` types in iOS.
  * 3. Improves usability and consistency of cursor style between image-type
  * `input` and others.
  * 4. Removes inner spacing in IE 7 without affecting normal text inputs.
  * Known issue: inner spacing remains in IE 6.
  */
 
  button,
  html input[type="button"], /* 1 */
  input[type="reset"],
  input[type="submit"] {
  -webkit-appearance: button; /* 2 */
  cursor: pointer; /* 3 */
  *overflow: visible; /* 4 */
  }
 
  /*
  * Re-set default cursor for disabled elements.
  */
 
  button[disabled],
  input[disabled] {
  cursor: default;
  }
 
  /*
  * 1. Addresses box sizing set to content-box in IE 8/9.
  * 2. Removes excess padding in IE 8/9.
  * 3. Removes excess padding in IE 7.
  * Known issue: excess padding remains in IE 6.
  */
 
  input[type="checkbox"],
  input[type="radio"] {
  box-sizing: border-box; /* 1 */
  padding: 0; /* 2 */
  *height: 13px; /* 3 */
  *width: 13px; /* 3 */
  }
 
  /*
  * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome.
  * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome
  * (include `-moz` to future-proof).
  */
 
  input[type="search"] {
  -webkit-appearance: textfield; /* 1 */
  -moz-box-sizing: content-box;
  -webkit-box-sizing: content-box; /* 2 */
  box-sizing: content-box;
  }
 
  /*
  * Removes inner padding and search cancel button in Safari 5 and Chrome
  * on OS X.
  */
 
  input[type="search"]::-webkit-search-cancel-button,
  input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
  }
 
  /*
  * Removes inner padding and border in Firefox 3+.
  */
 
  button::-moz-focus-inner,
  input::-moz-focus-inner {
  border: 0;
  padding: 0;
  }
 
  /*
  * 1. Removes default vertical scrollbar in IE 6/7/8/9.
  * 2. Improves readability and alignment in all browsers.
  */
 
  textarea {
  overflow: auto; /* 1 */
  vertical-align: top; /* 2 */
  }
 
  /* ==========================================================================
  Tables
  ========================================================================== */
 
  /*
  * Remove most spacing between table cells.
  */
 
  table {
  border-collapse: collapse;
  border-spacing: 0;
  }
 
file:b/db.sql (new)
  -- /usr/pgsql-9.1/bin/pg_dump --schema-only scannr
  --
  -- PostgreSQL database dump
  --
 
  SET statement_timeout = 0;
  SET client_encoding = 'UTF8';
  SET standard_conforming_strings = on;
  SET check_function_bodies = false;
  SET client_min_messages = warning;
 
  --
  -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
  --
 
  CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
 
 
  --
  -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
  --
 
  COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
 
 
  SET search_path = public, pg_catalog;
 
  SET default_tablespace = '';
 
  SET default_with_oids = false;
 
  --
  -- Name: recordings; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
  --
 
  CREATE TABLE recordings (
  filename text NOT NULL,
  tgid text,
  tgname text,
  sitename text,
  call_timestamp timestamp with time zone DEFAULT now(),
  length integer
  );
 
 
  ALTER TABLE public.recordings OWNER TO postgres;
 
  --
  -- Name: tgids; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
  --
 
  CREATE TABLE tgids (
  tgid text NOT NULL,
  subfleet smallint,
  alpha_tag text NOT NULL,
  mode character(1) DEFAULT 'D'::bpchar NOT NULL,
  description text,
  service_tag text,
  category text
  );
 
 
  ALTER TABLE public.tgids OWNER TO postgres;
 
  --
  -- Name: recordings_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
  --
 
  ALTER TABLE ONLY recordings
  ADD CONSTRAINT recordings_pkey PRIMARY KEY (filename);
 
 
  --
  -- Name: tgids_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
  --
 
  ALTER TABLE ONLY tgids
  ADD CONSTRAINT tgids_pkey PRIMARY KEY (tgid);
 
 
  --
  -- Name: public; Type: ACL; Schema: -; Owner: postgres
  --
 
  REVOKE ALL ON SCHEMA public FROM PUBLIC;
  REVOKE ALL ON SCHEMA public FROM postgres;
  GRANT ALL ON SCHEMA public TO postgres;
  GRANT ALL ON SCHEMA public TO PUBLIC;
 
 
  --
  -- PostgreSQL database dump complete
  --
 
 
file:b/favicon.ico (new)
 Binary files /dev/null and b/favicon.ico differ
file:b/ffmpeg.exe (new)
 
  <?php
  //select tgid, extract(hour from call_timestamp) ahour, date_trunc('day', call_timestamp) aday, count(filename), array_to_string(array_agg(filename), ' ') from recordings group by tgid, ahour, aday order by aday, ahour, tgid
  include('common.inc.php');
  $sth = $conn->prepare('select * from recordings limit 100;');
 
  $sth->execute();
  $recordings = $sth->fetchAll();
  $convos = Array();
  $convo = Array();
  foreach ($recordings as $i => $recording) {
 
  if (count($convo) > 0) {
  echo "<br> " . strcasecmp($convos[count($convos) - 1][0]['call_timestamp'], $recording['call_timestamp']);
  if (abs(strcasecmp($convos[count($convos) - 1][0]['call_timestamp'], $recording['call_timestamp'])) > 2) {
  echo " " . $convos[count($convos) - 1][0]['call_timestamp'] . " " . $recording['call_timestamp'];
  }
  if (strcasecmp($convos[count($convos) - 1][0]['tgid'], $recording['tgid']) != 0) {
  $convos[] = $convo;
  $convo = Array();
  }
  }
  ;
  //print_r($recording);
  $convo[] = $recording;
  //print_r($convo);
  //echo "<br>\n";
  }
  foreach ($convos as $i => $convo) {
  foreach ($convo as $recording) {
  echo $recording['filename'] . " , ";
  }
  echo "<br><hr>\n";
  }
  ?>
 
 
  <?php
  include('common.inc.php');
  function processHourly($hourly) {
  $filename = $hourly['tgid'].'-'.str_replace(' 00:00:00+1','',$hourly['aday']).'-'.$hourly['ahour'].'.3gp';
 
  if(!file_exists("hourly/".$filename)) {
 
  $filenames = explode(",",$hourly['filenames']);
  $cmd = "/usr/local/bin/ffmpeg -filter_complex concat=n=".count($filenames).":v=0:a=1 -i data/".implode(" -i data/",$filenames)." -ar 8000 -ab 4.75k -ac 1 hourly/".$filename . ' 2>&1';
  //print_r($hourly);
  exec ( $cmd,$output,$returncode );
  echo $cmd."<br>\n";
  if ($returncode != 10) {
  //print_r($output);
  //die();
  }
  }
  }
  $sth = $conn->prepare("select tgid, extract(hour from call_timestamp) ahour, date_trunc('day', call_timestamp) aday, count(filename), array_to_string(array_agg(filename order by call_timestamp), ',') filenames from recordings group by tgid, ahour, aday order by aday DESC, ahour, tgid;");
 
  $sth->execute();
  $hourlies = $sth->fetchAll(PDO::FETCH_ASSOC);
  foreach($hourlies as $hourly) {
  processHourly($hourly);
  }
  $sth = $conn->prepare("select 'hour' as tgid, extract(hour from call_timestamp) ahour, date_trunc('day', call_timestamp) aday, count(filename), array_to_string(array_agg(filename order by call_timestamp), ',') filenames from recordings group by ahour, aday order by aday DESC, ahour;");
 
  $sth->execute();
  $hourlies = $sth->fetchAll(PDO::FETCH_ASSOC);
  foreach($hourlies as $hourly) {
  processHourly($hourly);
  }
 
file:b/getfile.php (new)
  <?php
  $reqfile = "path/to/file.3gp";
  $contenttype = "audio/3gpp";
 
  if ($fn = fopen($reqfile, "rba")) {
  header("Content-Type: " . $contenttype);
  header("Content-Length: " . filesize($reqfile));
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Pragma: no-cache");
  header("Expires: Mon, 26 Jul 1997 06:00:00 GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
  passthru("ffmpeg -i 2012-09-29-1348911268.34-demo.wav -ar 8000 -ab 4.75k -");
  fpassthru($fn);
  fclose($fn);
  } else {
  exit("error....");
  }
  exit();
  ?>
 
file:b/humans.txt (new)
  # humanstxt.org/
  # The humans responsible & technology colophon
 
  # TEAM
 
  <name> -- <role> -- <twitter>
 
  # THANKS
 
  <name>
 
  # TECHNOLOGY COLOPHON
 
  HTML5, CSS3
  jQuery, Modernizr
 
file:b/img/.gitignore (new)
 
  build
  .vimrc
  *.swp
  *.swm
  *.swo
  *.vim
  .jhw-cache
  node_modules
  dev
 
file:b/js/flotr2/LICENSE (new)
  Copyright (c) 2012 Carl Sutherland
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
 
  all: test flotr2
 
  test:
  cd spec; jasmine-headless-webkit -j jasmine.yml -c
 
  libraries:
  smoosh make/lib.json
  cat ./build/bean.js > build/lib.js
  cat ./build/underscore.js >> build/lib.js
  cat ./build/bean.min.js > build/lib.min.js
  echo ";" >> build/lib.min.js
  cat ./build/underscore.min.js >> build/lib.min.js
  echo ";" >> build/lib.min.js
 
  ie:
  smoosh make/ie.json
 
  flotr2: libraries ie
  smoosh make/flotr2.json
  cat build/lib.js build/flotr2.js > flotr2.js
  cat build/lib.min.js > flotr2.min.js
  cat build/flotr2.min.js >> flotr2.min.js
  echo ';' >> flotr2.min.js
  cp build/ie.min.js flotr2.ie.min.js
 
  flotr2-basic: libraries ie
  smoosh make/basic.json
  cat build/lib.min.js > flotr2-basic.min.js
  cat build/flotr2-basic.min.js >> flotr2-basic.min.js
 
  flotr-examples:
  smoosh make/examples.json
  cp build/examples.min.js flotr2.examples.min.js
  cp build/examples-types.js flotr2.examples.types.js
 
  flotr-amd: flotr2
  cat js/amd/pre.js > flotr2.amd.js
  cat build/flotr2.js >> flotr2.amd.js
  cat js/amd/post.js >> flotr2.amd.js
 
  Flotr2
  ======
 
  The Canvas graphing library.
 
  ![Google Groups](http://groups.google.com/intl/en/images/logos/groups_logo_sm.gif)
 
  http://groups.google.com/group/flotr2/
 
  Please fork http://jsfiddle.net/cesutherland/ZFBj5/ with your question or bug reproduction case.
 
 
  API
  ---
 
  The API consists of a primary draw method which accepts a configuration object, helper methods, and several microlibs.
 
  ### Example
 
  ```javascript
  var
  // Container div:
  container = document.getElementById("flotr-example-graph"),
  // First data series:
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]],
  // Second data series:
  d2 = [],
  // A couple flotr configuration options:
  options = {
  xaxis: {
  minorTickFreq: 4
  },
  grid: {
  minorVerticalLines: true
  }
  },
  i, graph;
 
  // Generated second data set:
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Draw the graph:
  graph = Flotr.draw(
  container, // Container element
  [ d1, d2 ], // Array of data series
  options // Configuration options
  );
  ```
 
  ### Microlibs
 
  * [underscore.js](http://documentcloud.github.com/underscore/)
  * [bean.js](https://github.com/fat/bean)
 
  Extending
  ---------
 
  Flotr may be extended by adding new plugins and graph types.
 
  ### Graph Types
 
  Graph types define how a particular chart is rendered. Examples include line, bar, pie.
 
  Existing graph types are found in `js/types/`.
 
  ### Plugins
 
  Plugins extend the core of flotr with new functionality. They can add interactions, new decorations, etc. Examples
  include titles, labels and selection.
 
  The plugins included are found in `js/plugins/`.
 
  Development
  -----------
 
  This project uses [smoosh](https://github.com/fat/smoosh) to build and [jasmine](http://pivotal.github.com/jasmine/)
  with [js-imagediff](https://github.com/HumbleSoftware/js-imagediff) to test. Tests may be executed by
  [jasmine-headless-webkit](http://johnbintz.github.com/jasmine-headless-webkit/) with
  `cd spec; jasmine-headless-webkit -j jasmine.yml -c` or by a browser by navigating to
  `flotr2/spec/SpecRunner.html`.
 
  Shoutouts
  ---------
 
  Thanks to Bas Wenneker, Fabien Ménager and others for all the work on the original Flotr.
  Thanks to Jochen Berger and Jordan Santell for their contributions to Flotr2.
 
 
  Flotr 2 Architecture Notes
 
 
  Global:
  ======
 
  Flotr.js -
  versioning information
  browser detection
  extension (plugins, graph types)
  draw
  clone / merge
  tick size
  tick formatter
  engineering notation
  magnitude
  rad, pixel, floor
  drawText
  measureText
  getBestTextAlign
  align map
  compatibility
 
 
  Graph Architecture:
  ===================
 
  Axis -
  all series
  orientation
  ticks (major, minor)
  scale (d2p, p2d, logarithmic)
  notion of stacks
 
  Series -
  per 'data'
  notion of range (x, y, min, max)
 
  Graph -
  DOM constructon
  event attachment
  options initialization
  data range calculations
  canvas spacing calculations
  event normalization
  draw methods
  DOM cleanup
  event cleanup
 
 
  Utilities:
  ==========
 
  Color
  build colors
  parse textual color data
  convert colors
  clone colors
 
  Text
  calculate text size
  canvas size
  html size
 
  Date
  formatting
  constants
 
 
  Spacing Calculation
  ===================
 
  Flotr
  calculate data
  calculate margins
 
  Chart
  calculate Data Ranges - Explicit or auto data minimum, maximums
  calculate Data Range Extensions - By chart type, extend data range with needs of chart type (ie. stacked bars, stacked lines)
  add Chart Padding - By chart type
 
  Text
  use explicit margins
  calculate label margins
  calculate title margins
 
 
  <!DOCTYPE html>
  <html>
 
  <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr Example Index Page</title>
  <link rel="stylesheet" href="lib/codemirror/lib/codemirror.css" type="text/css" />
  <link rel="stylesheet" href="examples.css" type="text/css" />
  <link rel="stylesheet" href="editor.css" type="text/css" />
  </head>
 
  <body>
  <div id="body-container">
  <div id="content-container">
  <div id="content">
  <div id="examples"></div>
  </div>
  </div>
  </div>
  </body>
 
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  <script type="text/javascript" src="js/includes.dev.js"></script>
 
  </html>
 
  /* Editor */
  .editor {
  position: relative;
  }
  .editor .render {
  height: 240px;
  width: 320px;
  margin: 8px auto;
  }
  .editor .source {
  border: 1px solid #ddd;
  border-radius: 3px;
  }
  .editor .controls {
  position: absolute;;
  z-index: 100;
  right: 8px;
  margin-top: -12px;
  }
  .editor .controls button {
  float: right;
  }
  .editor .errors {
  color: #ee0000;
  padding: 8px;
  font-size: 12px;
  background: #fee;
  border-bottom: 1px solid #eee;
  }
  .editor .errors .error {
  font-weight: bold
  }
  .editor .errors .message {
  font-style: italic;
  }
  .editor .errors .position {
  display: block;
  margin-top: 4px;
  }
  .editor.no-run .controls,
  .editor.no-run .render {
  display: none;
  }
 
  /* html type */
  .editor.html .render {
  height: 400px;
  width: 800px;
  text-align: center;
  }
  .editor.html .render iframe {
  height: 100%;
  width: 100%;
  border: none;
  }
 
  /* CodeMirror */
  .CodeMirror {
  background: #fafafa;
  }
  .CodeMirror.CodeMirror-focused {
  }
  .CodeMirror-scroll {
  height: auto;
  overflow: visible;
  overflow-x: auto;
  }
  .CodeMirror-lines pre,
  .CodeMirror-gutter pre {
  line-height: 16px;
  }
 
 
  body {
  font-family : sans-serif;
  padding: 0px;
  margin: 0px;
  }
 
  /* Example */
 
  .flotr-example {
  display: none;
  margin: 0px auto 48px auto;
  position: relative;
  }
  .flotr-example-label {
  font-size: 18px;
  padding: 14px 0px;
  }
  .flotr-example-editor .editor .render {
  width: 600px;
  height: 400px;
  margin: 12px auto 18px auto;
  }
  .flotr-example-editor .editor .source {
  width: 720px;
  }
 
  /* Chart no-select */
 
  .flotr-example-editor .editor .render,
  .flotr-examples-thumb {
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
  }
 
 
  /* Examples */
 
  .flotr-examples-thumbs {
  text-align: center;
  }
  .flotr-examples-reset {
  z-index: 100;
  cursor: pointer;
  text-decoration: underline;
  position: absolute;
  top: 260px;
  right: 24px;
  display: none;
  }
  .flotr-examples-collapsed .flotr-examples-reset {
  display: block;
  }
  .flotr-examples-thumb {
  display: inline-block;
  font-size : 11px;
  width : 300px;
  height : 200px;
  margin: 10px 15px;
  border: 2px solid transparent;
  }
  .flotr-examples-thumb.flotr-examples-highlight{
  font-size : 12px;
  width : 330px;
  height : 220px;
  margin: 0px 0px;
  }
  .flotr-examples-thumb .flotr-legend,
  .flotr-examples-thumb .flotr-mouse-value {
  display : none;
  }
 
  .flotr-examples-collapsed .flotr-examples-container {
  margin-top: 20px;
  position: relative;
  margin: 0px auto;
  }
 
  .flotr-examples-collapsed .flotr-examples-thumbs {
  position: relative;
  overflow-x: auto;
  white-space: nowrap;
  }
 
 
  /* Flotr Styles */
 
  .flotr-datagrid-container {
  border: 1px solid #999;
  border-bottom: none;
  background: #fff;
  }
  .flotr-datagrid {
  border-collapse: collapse;
  border-spacing: 0;
  }
  .flotr-datagrid td, .flotr-datagrid th {
  border: 1px solid #ccc;
  padding: 1px 3px;
  min-width: 2em;
  }
  .flotr-datagrid tr:hover, .flotr-datagrid col.hover {
  background: #f3f3f3;
  }
  .flotr-datagrid tr:hover th, .flotr-datagrid th.hover {
  background: #999;
  color: #fff;
  }
  .flotr-datagrid th {
  text-align: left;
  background: #e3e3e3;
  border: 2px outset #fff;
  }
  .flotr-datagrid-toolbar {
  padding: 1px;
  border-bottom: 1px solid #ccc;
  background: #f9f9f9;
  }
  .flotr-datagrid td:hover {
  background: #ccc;
  }
  .flotr-datagrid .first-row th {
  text-align: center;
  }
  .flotr-canvas {
  margin-bottom: -3px;
  padding-bottom: 1px;
  }
  .flotr-tabs-group {
  border-top: 1px solid #999;
  }
  .flotr-tab {
  border: 1px solid #666;
  border-top: none;
  margin: 0 3px;
  padding: 1px 4px;
  cursor: pointer;
  -moz-border-radius: 0 0 4px 4px;
  -webkit-border-bottom-left-radius: 4px;
  -webkit-border-bottom-right-radius: 4px;
  border-radius: 0 0 4px 4px;
  opacity: 0.5;
  -moz-opacity: 0.5;
  }
  .flotr-tab.selected {
  background: #ddd;
  opacity: 1;
  -moz-opacity: 1;
  }
  .flotr-tab:hover {
  background: #ccc;
  }
 
  /* Large */
  .flotr-examples-large .flotr-example {
  width: 1360px;
  margin: 0px auto;
  position: relative;
  }
  .flotr-examples-large .flotr-example-editor .editor .render {
  margin-left: 0px;
  margin-right: 0px;
  }
  .flotr-examples-large .flotr-example-editor .controls {
  top: 0px;
  }
  .flotr-examples-large .flotr-example-editor .source {
  position: absolute;
  top: 0px;
  right: 0px;
  }
 
  /* Veritical Thumbs */
 
  .flotr-examples-large.flotr-examples-collapsed .flotr-examples-reset,
  .flotr-examples-medium.flotr-examples-collapsed .flotr-examples-reset {
  top: 16px;
  }
 
  .flotr-examples-large.flotr-examples-collapsed .flotr-examples-thumbs,
  .flotr-examples-medium.flotr-examples-collapsed .flotr-examples-thumbs {
  position: fixed;
  width: 400px;
  left: 0px;
  top: 0px;
  overflow-y: auto;
  background: #fff;
  }
  .flotr-examples-large.flotr-examples-collapsed .flotr-examples-thumb,
  .flotr-examples-medium.flotr-examples-collapsed .flotr-examples-thumb {
  display: block;
  float: center;
  margin: 10px auto;
  }
 
  .flotr-examples-large.flotr-examples-collapsed .flotr-examples-container,
  .flotr-examples-medium.flotr-examples-collapsed .flotr-examples-container {
  margin-left: 400px;
  }
 
  /* Vertical Example */
 
  .flotr-examples-small .flotr-example,
  .flotr-examples-medium .flotr-example {
  width: 720px;
  }
  .flotr-examples-small .flotr-example-editor .source,
  .flotr-examples-medium .flotr-example-editor .source {
  position: relative;
  }
 
 Binary files /dev/null and b/js/flotr2/examples/images/butterfly.jpg differ
 Binary files /dev/null and b/js/flotr2/examples/images/checkmark.png differ
 Binary files /dev/null and b/js/flotr2/examples/images/xmark.png differ
  <!DOCTYPE html>
  <html>
 
  <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr Example Index Page</title>
  <link rel="stylesheet" href="lib/codemirror/lib/codemirror.css" type="text/css" />
  <link rel="stylesheet" href="examples.css" type="text/css" />
  <link rel="stylesheet" href="editor.css" type="text/css" />
  </head>
 
  <body>
  <div id="body-container">
  <div id="content-container">
  <div id="content">
  <div id="examples"></div>
  </div>
  </div>
  </div>
  </body>
 
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  <script type="text/javascript" src="js/includes.min.js"></script>
 
  </html>
 
  (function () {
 
  var
  ONERROR = window.onerror,
  COUNT = 0,
  TYPES = {},
 
  T_CONTROLS =
  '<div class="controls">' +
  '<button class="fiddle btn large primary">Fiddle</button>' +
  '<button class="run btn large primary">Run</button>' +
  '</div>',
  T_EDITOR = '<div class="editor"></div>',
  T_SOURCE = '<div class="source"></div>',
  T_ERRORS = '<div class="errors"></div>',
  T_RENDER = '<div class="render"></div>',
  T_IFRAME = '<iframe></iframe>';
 
 
  // Javascript type:
  TYPES.javascript = function Javascript (o) {
  this.onerror = o.onerror;
  };
  TYPES.javascript.prototype = {
  codeMirrorType : 'javascript',
  example : function (o) {
 
  var
  example = o.example,
  render = o.render,
  renderId = $(render).attr('id'),
  args = o.args ? ',' + o.args.toString() : '';
 
  return '(' + example + ')(document.getElementById("' + renderId+ '")' +
  args + ');';
  },
  render : function (o) {
  eval(o.example);
  }
  };
 
  // HTML Type:
  TYPES.html = function Html (o) {
  this.onerror = o.onerror;
  };
  TYPES.html.prototype = {
  codeMirrorType : 'htmlmixed',
  example : function (o) {
  return $.trim(o.example);
  },
  render : function (o) {
 
  var
  example = o.example,
  render = o.render,
  iframe = $(T_IFRAME),
  that = this,
  win, doc;
 
  render.html(iframe);
 
  win = iframe[0].contentWindow;
 
  doc = win.document;
  doc.open();
 
  // Error
  win.onerror = iframe.onerror = function () {
  that.onerror.apply(null, arguments);
  }
 
  doc.write(example);
  doc.close();
  }
  };
 
  // Editor
  function Editor (container, o) {
 
  var
  type = o.type || 'javascript',
  example = o.example || '',
  noRun = o.noRun || false,
  teardown = o.teardown || false,
  controls = $(T_CONTROLS),
  render = $(T_RENDER),
  errors = $(T_ERRORS),
  source = $(T_SOURCE),
  node = $(T_EDITOR),
  renderId = 'editor-render-' + COUNT,
  api,
  render,
  codeMirror;
 
  api = new TYPES[type]({
  onerror : onerror
  });
  if (!api) throw 'Invalid type: API not found for type `' + type + '`.';
 
  render
  .attr('id', renderId);
 
  errors
  .hide();
 
  node
  .append(render)
  .append(controls)
  .append(source)
  .addClass(type)
  .addClass(noRun ? 'no-run' : '');
 
  container = $(container);
  container
  .append(node);
 
  source
  .append(errors)
 
  example = api.example({
  args : o.args,
  example : example,
  render : render
  });
 
  codeMirror = CodeMirror(source[0], {
  value : example,
  readOnly : noRun,
  lineNumbers : true,
  mode : api.codeMirrorType
  });
 
  if (!noRun) {
  controls.delegate('.run', 'click', function () {
  example = codeMirror.getValue();
  execute();
  });
 
  execute();
  }
 
  controls.delegate('.fiddle', 'click', function () {
  fiddle();
  });
 
  // Error handling:
  window.onerror = function (message, url, line) {
 
  onerror(message, url, line);
  console.log(message);
 
  if (ONERROR && $.isFunction(ONERROR)) {
  return ONERROR(message, url, line);
  } else {
  return false;
  }
  }
 
  // Helpers
 
  function execute () {
  errors.hide();
  if (teardown) {
  teardown.call();
  }
  api.render({
  example : example,
  render : render
  });
  }
 
  function onerror (message, url, line) {
  // @TODO Find some js error normalizing lib
 
  var
  doThatSexyThang = false,
  html = '<span class="error">Error: </span>',
  error, stack;
 
  /*
  // Native error type handling:
  if (typeof (message) !== 'string') {
  error = message;
  message = error.message;
  stack = error.stack;
 
  //if (stack) {
  console.log(stack);
  //}
 
  //console.log(message);
 
  }
 
  */
 
  html += '<span class="message">' + message + '</span>';
  if (typeof (line) !== "undefined") {
  html += '<span class="position">';
  html += 'Line <span class="line">' + line + '</span>';
  console.log(url);
  if (url) {
  html += ' of ';
  if (url == window.location) {
  html += '<span class="url">script</span>';
  if (doThatSexyThang) {
  //codeMirror.setMarker(line, '&#8226;');
  }
  } else {
  html += '<span class="url">' + url + '</span>';
  }
  }
  html += '.</span>';
  }
 
  errors.show();
  errors.html(html);
  }
 
  function fiddle () {
  var
  url = 'http://jsfiddle.net/api/post/jquery/1.7/',
  form = $('<form method="post" action="' + url + '" target="_blank"></form>'),
  input;
 
  // Resources
  resources = [
  'https://raw.github.com/HumbleSoftware/Flotr2/master/flotr2.min.js',
  'https://raw.github.com/HumbleSoftware/Flotr2/master/examples/examples.css'
  ];
  input = $('<input type="hidden" name="resources">')
  .attr('value', resources.join(','));
  form.append(input);
 
  // HTML
  input = $('<input type="hidden" name="html">')
  .attr('value', '<div id="'+renderId+'"></div>');
  form.append(input);
 
  // CSS
  input = $('<input type="hidden" name="normalize_css" value="no">')
  form.append(input);
  input = $('<input type="hidden" name="css">')
  .attr('value',
  '#'+renderId+' {\n width: 340px;\n height: 220px;' +
  '\n margin: 24px auto;\n}'
  );
  form.append(input);
 
  // JS
  input = $('<input type="hidden" name="js">')
  .attr('value', '$(function () {\n' + example + '\n});');
 
  form.append(input);
 
  // Submit
  form.append(input);
  $(document.body).append(form);
  form.submit();
  }
 
  COUNT++;
 
  this.setExample = function (source, args) {
  example = api.example({
  args : args,
  example : source,
  render : render
  });
  codeMirror.setValue(example);
  codeMirror.refresh();
  execute();
  }
  }
 
  if (typeof Flotr.Examples === 'undefined') Flotr.Examples = {};
  Flotr.Examples.Editor = Editor;
  })();
 
  (function () {
 
  var
  _ = Flotr._,
 
  DOT = '.',
 
  CN_EXAMPLE = 'flotr-example',
  CN_LABEL = 'flotr-example-label',
  CN_TITLE = 'flotr-example-title',
  CN_MARKUP = 'flotr-example-description',
  CN_EDITOR = 'flotr-example-editor',
 
  ID_GRAPH = 'flotr-example-graph',
 
  TEMPLATE = '' +
  '<div class="' + CN_EXAMPLE + '">' +
  '<div class="' + CN_LABEL + ' ' + CN_TITLE + '"></div>' +
  '<div class="' + CN_MARKUP + '"></div>' +
  '<div class="' + CN_EDITOR + '"></div>' +
  '</div>',
 
  Example = function (o) {
 
  this.options = o;
  this.example = null;
 
  this._initNodes();
  };
 
  Example.prototype = {
 
  setExample : function (example) {
 
  var
  source = this.getSource(example),
  editorNode = this._editorNode;
 
  this.example = example;
 
  Math.seedrandom(example.key);
  this._exampleNode.css({ display: 'block' });
  this._titleNode.html(example.name || '');
  this._markupNode.html(example.description || '');
 
  if (!this._editor) {
  this._editor = new Flotr.Examples.Editor(editorNode, {
  args : example.args,
  example : source,
  teardown : function () {
  // Unbind event listeners from previous examples
  Flotr.EventAdapter.stopObserving($(editorNode).find('.render')[0]);
  $(editorNode).find('canvas').each(function (index, canvas) {
  Flotr.EventAdapter.stopObserving(canvas);
  });
  }
  });
  } else {
  this._editor.setExample(source, example.args);
  }
  },
 
  getSource : function (example) {
 
  var
  source = example.callback.toString();
 
  // Hack for FF code style
  if (navigator.userAgent.search(/firefox/i) !== -1)
  source = js_beautify(source);
 
  return source;
  },
 
  executeCallback : function (example, node) {
  if (!_.isElement(node)) node = node[0];
  var args = (example.args ? [node].concat(example.args) : [node]);
  Math.seedrandom(example.key);
  return example.callback.apply(this, args);
  },
 
  _initNodes : function () {
 
  var
  node = this.options.node,
  example = $(TEMPLATE);
 
  this._titleNode = example.find(DOT + CN_TITLE);
  this._markupNode = example.find(DOT + CN_MARKUP);
  this._editorNode = example.find(DOT + CN_EDITOR);
  this._exampleNode = example;
 
  node.append(example);
  }
  };
 
  Flotr.Examples.Example = Example;
 
  })();
 
  (function () {
 
  var ExampleList = function () {
 
  // Map of examples.
  this.examples = {};
 
  };
 
  ExampleList.prototype = {
 
  add : function (example) {
  this.examples[example.key] = example;
  },
 
  get : function (key) {
  return key ? (this.examples[key] || null) : this.examples;
  },
 
  getType : function (type) {
  return Flotr._.select(this.examples, function (example) {
  return (example.type === type);
  });
  }
  }
 
  Flotr.ExampleList = new ExampleList();
 
  })();
 
  (function () {
 
  var
  E = Flotr.EventAdapter,
  _ = Flotr._,
 
  CLICK = 'click',
  EXAMPLE = 'example',
  MOUSEENTER = 'mouseenter',
  MOUSELEAVE = 'mouseleave',
 
  DOT = '.',
 
  CN_EXAMPLES = 'flotr-examples',
  CN_CONTAINER = 'flotr-examples-container',
  CN_RESET = 'flotr-examples-reset',
  CN_THUMBS = 'flotr-examples-thumbs',
  CN_THUMB = 'flotr-examples-thumb',
  CN_COLLAPSED = 'flotr-examples-collapsed',
  CN_HIGHLIGHT = 'flotr-examples-highlight',
  CN_LARGE = 'flotr-examples-large',
  CN_MEDIUM = 'flotr-examples-medium',
  CN_SMALL = 'flotr-examples-small',
  CN_MOBILE = 'flotr-examples-mobile',
 
  T_THUMB = '<div class="' + CN_THUMB + '"></div>',
 
  TEMPLATE = '' +
  '<div class="' + CN_EXAMPLES + '">' +
  '<div class="' + CN_RESET + '">View All</div>' +
  '<div class="' + CN_THUMBS + '"></div>' +
  '<div class="' + CN_CONTAINER + '"></div>' +
  '</div>'
 
  Examples = function (o) {
 
  if (_.isUndefined(Flotr.ExampleList)) throw "Flotr.ExampleList not defined.";
 
  this.options = o;
  this.list = Flotr.ExampleList;
  this.current = null;
  this.single = false;
 
  this._initNodes();
  this._example = new Flotr.Examples.Example({
  node : this._exampleNode
  });
 
  //console.time(EXAMPLE);
  //console.profile();
  this._initExamples();
  //console.profileEnd();
  //console.timeEnd(EXAMPLE);
  };
 
  Examples.prototype = {
 
  examples : function () {
 
  var
  styles = {cursor : 'pointer'},
  thumbsNode = this._thumbsNode,
  list = this.list.get(),
  that = this;
 
  var
  order = [
  "basic",
  "basic-axis",
  "basic-bars",
  "basic-bars-horizontal",
  "basic-bar-stacked",
  "basic-stacked-horizontal",
  "basic-pie",
  "basic-radar",
  "basic-bubble",
  "basic-candle",
  "basic-legend",
  "mouse-tracking",
  "mouse-zoom",
  "mouse-drag",
  "basic-time",
  "negative-values",
  "click-example",
  "download-image",
  "download-data",
  "advanced-titles",
  "color-gradients",
  "basic-timeline",
  "advanced-markers"
  ];
 
  (function runner () {
  var
  key = order.shift(),
  example = list[key];
 
  if (example.type === 'profile' || example.type === 'test') return;
  var node = $(T_THUMB);
  node.data('example', example);
  thumbsNode.append(node);
  that._example.executeCallback(example, node);
  node.click(function () {that._loadExample(example)});
 
  if (order.length) setTimeout(runner, 20);
  })();
 
  function zoomHandler (e) {
  var
  node = $(e.currentTarget),
  example = node.data('example'),
  orientation = e.data.orientation;
  if (orientation ^ node.hasClass(CN_HIGHLIGHT)) {
  node.toggleClass(CN_HIGHLIGHT).css(styles);
  that._example.executeCallback(example, node);
  }
  }
 
  thumbsNode.delegate(DOT + CN_THUMB, 'mouseenter', {orientation : true}, zoomHandler);
  thumbsNode.delegate(DOT + CN_THUMB, 'mouseleave', {orientation : false}, zoomHandler);
 
  if ($(window).hashchange) {
  $(window).hashchange(function () {
  that._loadHash();
  });
  }
  },
 
  _loadExample : function (example) {
  if (example) {
  if (this._currentExample !== example) {
  this._currentExample = example;
  } else {
  return;
  }
 
  window.location.hash = '!'+(this.single ? 'single/' : '')+example.key;
 
  if (!scroller) {
  this._thumbsNode.css({
  position: 'absolute',
  height: '0px',
  overflow: 'hidden',
  width: '0px'
  });
  this._resetNode.css({
  top: '16px'
  });
  }
 
  this._examplesNode.addClass(CN_COLLAPSED);
  this._exampleNode.show();
  this._example.setExample(example);
  this._resize();
  $(document).scrollTop(0);
  }
  },
 
  _reset : function () {
  window.location.hash = '';
 
  if (!scroller) {
  this._thumbsNode.css({
  position: '',
  height: '',
  overflow: '',
  width: ''
  });
  }
 
  this._examplesNode.removeClass(CN_COLLAPSED);
  this._thumbsNode.height('');
  this._exampleNode.hide();
  },
 
  _initNodes : function () {
 
  var
  node = $(this.options.node),
  that = this,
  examplesNode = $(TEMPLATE);
 
  that._resetNode = examplesNode.find(DOT+CN_RESET);
  that._exampleNode = examplesNode.find(DOT+CN_CONTAINER);
  that._thumbsNode = examplesNode.find(DOT+CN_THUMBS);
  that._examplesNode = examplesNode;
 
  that._resetNode.click(function () {
  that._reset();
  });
 
  node.append(examplesNode);
 
  this._initResizer();
  },
 
  _initResizer : function () {
 
  var
  that = this,
  node = that._examplesNode,
  page = $(window),
  currentClass;
 
  $(window).resize(applySize);
  applySize();
 
  function applySize () {
 
  var
  height = page.height() - (that.options.thumbPadding || 0),
  width = page.width(),
  newClass;
 
  if (width > 1760) {
  newClass = CN_LARGE;
  that._thumbsNode.height(height);
  } else if (width > 1140) {
  newClass = CN_MEDIUM;
  that._thumbsNode.height(height);
  } else {
  newClass = CN_SMALL;
  that._thumbsNode.height('');
  }
 
  if (currentClass !== newClass) {
  if (currentClass)
  that._examplesNode.removeClass(currentClass);
  that._examplesNode.addClass(newClass);
  currentClass = newClass;
  }
  }
 
  this._resize = applySize;
  },
  _initExamples : function () {
  var
  hash = window.location.hash,
  example, params;
 
  hash = hash.substring(2);
  params = hash.split('/');
 
  if (params.length == 1) {
  this.examples();
  if (hash) {
  this._loadHash();
  }
  }
  else {
  if (params[0] == 'single') {
  this.single = true;
  this._loadExample(
  this.list.get(params[1])
  );
  }
  }
  },
  _loadHash : function () {
 
  var
  hash = window.location.hash,
  example;
 
  hash = hash.substring(2);
  if (hash) {
  example = this.list.get(hash);
  this._loadExample(example);
  } else {
  this._reset();
  }
  }
  }
 
  var scroller = (function () {
 
  var
  mobile = !!(
  navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/webOS/i) ||
  navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPod/i)
  ),
  mozilla = !!$.browser.mozilla;
 
  return (!mobile || mozilla);
  })();
 
  Flotr.Examples = Examples;
 
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._,
  CLICK = 'click',
 
  ID_EXAMPLE_PROFILE = 'example-profile',
  ID_EXAMPLES = 'examples',
 
  Profile = function (o) {
 
  if (_.isUndefined(Flotr.ExampleList)) throw "Flotr.ExampleList not defined.";
 
  this.editMode = 'off';
  this.list = Flotr.ExampleList;
  this.current = null;
  this.single = false;
 
  this.init();
  };
 
  Profile.prototype = _.extend({}, Flotr.Examples.prototype, {
 
  examples : function () {
  var
  examplesNode = document.getElementById(ID_EXAMPLES),
  listNode = D.node('<ul></ul>'),
  profileNode;
 
  _.each(this.list.getType('profile'), function (example) {
  profileNode = D.node('<li>' + example.name + '</li>');
  D.insert(listNode, profileNode);
  E.observe(profileNode, CLICK, _.bind(function () {
  this.example(example);
  }, this));
  }, this);
 
  D.insert(examplesNode, listNode);
  },
 
  example : function (example) {
  this._renderSource(example);
  this.profileStart(example);
  setTimeout(_.bind(function () {
  this._renderGraph(example);
  this.profileEnd();
  }, this), 50);
  },
 
  profileStart : function (example) {
  var profileNode = document.getElementById(ID_EXAMPLE_PROFILE);
  this._startTime = new Date();
  profileNode.innerHTML = '<div>Profile started for "'+example.name+'"...</div>';
  },
 
  profileEnd : function (example) {
  var
  profileNode = document.getElementById(ID_EXAMPLE_PROFILE);
  profileTime = (new Date()) - this._startTime;
 
  this._startTime = null;
 
  profileNode.innerHTML += '<div>Profile complete: '+profileTime+'ms<div>';
  }
 
  });
 
  Flotr.Profile = Profile;
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'advanced-markers',
  name : 'Advanced Markers',
  callback : advanced_markers,
  timeout : 150
  });
 
  function advanced_markers (container) {
 
  var
  xmark = new Image(),
  checkmark = new Image(),
  bars = {
  data: [],
  bars: {
  show: true,
  barWidth: 0.6,
  lineWidth: 0,
  fillOpacity: 0.8
  }
  }, markers = {
  data: [],
  markers: {
  show: true,
  position: 'ct',
  labelFormatter: function (o) {
  return (o.y >= 5) ? checkmark : xmark;
  }
  }
  },
  flotr = Flotr,
  point,
  graph,
  i;
 
 
  for (i = 0; i < 8; i++) {
  point = [i, Math.ceil(Math.random() * 10)];
  bars.data.push(point);
  markers.data.push(point);
  }
 
  var runner = function () {
  if (!xmark.complete || !checkmark.complete) {
  setTimeout(runner, 50);
  return;
  }
 
  graph = flotr.draw(
  container,
  [bars, markers], {
  yaxis: {
  min: 0,
  max: 11
  },
  xaxis: {
  min: -0.5,
  max: 7.5
  },
  grid: {
  verticalLines: false
  }
  }
  );
  }
 
  xmark.onload = runner;
  xmark.src = 'images/xmark.png';
  checkmark.src = 'images/checkmark.png';
  };
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'advanced-titles',
  name : 'Advanced Titles',
  callback : advanced_titles
  });
 
  function advanced_titles (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i;
 
  for (i = 0; i <= 10; i += 0.1) {
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if (i.toFixed(1)%1 == 0) {
  d5.push([i, 2*i]);
  }
  }
 
  // Draw the graph.
  graph = Flotr.draw(
  container,[
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3', yaxis : 2 },
  { data : d3, label : 'y = 5x + 3sin(4x)' },
  { data : d4, label : 'y = x' },
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ], {
  title : 'Advanced Titles Example',
  subtitle : 'You can save me as an image',
  xaxis : {
  noTicks : 7,
  tickFormatter : function (n) { return '('+n+')'; },
  min : 1,
  max : 7.5,
  labelsAngle : 45,
  title : 'x Axis'
  },
  yaxis : {
  ticks : [[0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max : 40,
  title : 'y = f(x)'
  },
  y2axis : { color : '#FF0000', max : 500, title : 'y = x^3' },
  grid : {
  verticalLines : false,
  backgroundColor : 'white'
  },
  HtmlText : false,
  legend : {
  position : 'nw'
  }
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-axis',
  name : 'Basic Axis',
  callback : basic_axis
  });
 
  function basic_axis (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [], // Data
  ticks = [[ 0, "Lower"], 10, 20, 30, [40, "Upper"]], // Ticks for the Y-Axis
  graph;
 
  for(var i = 0; i <= 10; i += 0.1){
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if( i.toFixed(1)%1 == 0 ){
  d5.push([i, 2*i]);
  }
  }
 
  d3[30][1] = null;
  d3[31][1] = null;
 
  function ticksFn (n) { return '('+n+')'; }
 
  graph = Flotr.draw(container, [
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3'},
  { data : d3, label : 'y = 5x + 3sin(4x)'},
  { data : d4, label : 'y = x'},
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ], {
  xaxis : {
  noTicks : 7, // Display 7 ticks.
  tickFormatter : ticksFn, // Displays tick values between brackets.
  min : 1, // Part of the series is not displayed.
  max : 7.5 // Part of the series is not displayed.
  },
  yaxis : {
  ticks : ticks, // Set Y-Axis ticks
  max : 40 // Maximum value along Y-Axis
  },
  grid : {
  verticalLines : false,
  backgroundColor : {
  colors : [[0,'#fff'], [1,'#ccc']],
  start : 'top',
  end : 'bottom'
  }
  },
  legend : {
  position : 'nw'
  },
  title : 'Basic Axis example',
  subtitle : 'This is a subtitle'
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bar-stacked',
  name : 'Stacked Bars',
  callback : bars_stacked
  });
 
  Flotr.ExampleList.add({
  key : 'basic-stacked-horizontal',
  name : 'Stacked Horizontal Bars',
  args : [true],
  callback : bars_stacked,
  tolerance : 5
  });
 
  function bars_stacked (container, horizontal) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  graph, i;
 
  for (i = -10; i < 10; i++) {
  if (horizontal) {
  d1.push([Math.random(), i]);
  d2.push([Math.random(), i]);
  d3.push([Math.random(), i]);
  } else {
  d1.push([i, Math.random()]);
  d2.push([i, Math.random()]);
  d3.push([i, Math.random()]);
  }
  }
 
  graph = Flotr.draw(container,[
  { data : d1, label : 'Serie 1' },
  { data : d2, label : 'Serie 2' },
  { data : d3, label : 'Serie 3' }
  ], {
  legend : {
  backgroundColor : '#D2E8FF' // Light blue
  },
  bars : {
  show : true,
  stacked : true,
  horizontal : horizontal,
  barWidth : 0.6,
  lineWidth : 1,
  shadowSize : 0
  },
  grid : {
  verticalLines : horizontal,
  horizontalLines : !horizontal
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bars',
  name : 'Basic Bars',
  callback : basic_bars
  });
 
  Flotr.ExampleList.add({
  key : 'basic-bars-horizontal',
  name : 'Horizontal Bars',
  args : [true],
  callback : basic_bars,
  tolerance : 5
  });
 
  function basic_bars (container, horizontal) {
 
  var
  horizontal = (horizontal ? true : false), // Show horizontal bars
  d1 = [], // First data series
  d2 = [], // Second data series
  point, // Data point variable declaration
  i;
 
  for (i = 0; i < 4; i++) {
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i];
  } else {
  point = [i, Math.ceil(Math.random()*10)];
  }
 
  d1.push(point);
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i+0.5];
  } else {
  point = [i+0.5, Math.ceil(Math.random()*10)];
  }
 
  d2.push(point);
  };
 
  // Draw the graph
  Flotr.draw(
  container,
  [d1, d2],
  {
  bars : {
  show : true,
  horizontal : horizontal,
  shadowSize : 0,
  barWidth : 0.5
  },
  mouse : {
  track : true,
  relative : true
  },
  yaxis : {
  min : 0,
  autoscaleMargin : 1
  }
  }
  );
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bubble',
  name : 'Basic Bubble',
  callback : basic_bubble
  });
 
  function basic_bubble (container) {
 
  var
  d1 = [],
  d2 = [],
  point, graph, i;
 
  for (i = 0; i < 10; i++ ){
  point = [i, Math.ceil(Math.random()*10), Math.ceil(Math.random()*10)];
  d1.push(point);
 
  point = [i, Math.ceil(Math.random()*10), Math.ceil(Math.random()*10)];
  d2.push(point);
  }
 
  // Draw the graph
  graph = Flotr.draw(container, [d1, d2], {
  bubbles : { show : true, baseRadius : 5 },
  xaxis : { min : -4, max : 14 },
  yaxis : { min : -4, max : 14 }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-candle',
  name : 'Basic Candle',
  callback : basic_candle
  });
 
  function basic_candle (container) {
 
  var
  d1 = [],
  price = 3.206,
  graph,
  i, a, b, c;
 
  for (i = 0; i < 50; i++) {
  a = Math.random();
  b = Math.random();
  c = (Math.random() * (a + b)) - b;
  d1.push([i, price, price + a, price - b, price + c]);
  price = price + c;
  }
 
  // Graph
  graph = Flotr.draw(container, [ d1 ], {
  candles : { show : true, candleWidth : 0.6 },
  xaxis : { noTicks : 10 }
  });
  }
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-legend',
  name : 'Basic Legend',
  callback : basic_legend
  });
 
  function basic_legend (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  data,
  graph, i;
 
  // Data Generation
  for (i = 0; i < 15; i += 0.5) {
  d1.push([i, i + Math.sin(i+Math.PI)]);
  d2.push([i, i]);
  d3.push([i, 15-Math.cos(i)]);
  }
 
  data = [
  { data : d1, label :'x + sin(x+&pi;)' },
  { data : d2, label :'x' },
  { data : d3, label :'15 - cos(x)' }
  ];
 
 
  // This function prepend each label with 'y = '
  function labelFn (label) {
  return 'y = ' + label;
  }
 
  // Draw graph
  graph = Flotr.draw(container, data, {
  legend : {
  position : 'se', // Position the legend 'south-east'.
  labelFormatter : labelFn, // Format the labels.
  backgroundColor : '#D2E8FF' // A light blue background color.
  },
  HtmlText : false
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-pie',
  name : 'Basic Pie',
  callback : basic_pie
  });
 
  function basic_pie (container) {
 
  var
  d1 = [[0, 4]],
  d2 = [[0, 3]],
  d3 = [[0, 1.03]],
  d4 = [[0, 3.5]],
  graph;
 
  graph = Flotr.draw(container, [
  { data : d1, label : 'Comedy' },
  { data : d2, label : 'Action' },
  { data : d3, label : 'Romance',
  pie : {
  explode : 50
  }
  },
  { data : d4, label : 'Drama' }
  ], {
  HtmlText : false,
  grid : {
  verticalLines : false,
  horizontalLines : false
  },
  xaxis : { showLabels : false },
  yaxis : { showLabels : false },
  pie : {
  show : true,
  explode : 6
  },
  mouse : { track : true },
  legend : {
  position : 'se',
  backgroundColor : '#D2E8FF'
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-radar',
  name : 'Basic Radar',
  callback : basic_radar
  });
 
  function basic_radar (container) {
 
  // Fill series s1 and s2.
  var
  s1 = { label : 'Actual', data : [[0, 3], [1, 8], [2, 5], [3, 5], [4, 3], [5, 9]] },
  s2 = { label : 'Target', data : [[0, 8], [1, 7], [2, 8], [3, 2], [4, 4], [5, 7]] },
  graph, ticks;
 
  // Radar Labels
  ticks = [
  [0, "Statutory"],
  [1, "External"],
  [2, "Videos"],
  [3, "Yippy"],
  [4, "Management"],
  [5, "oops"]
  ];
 
  // Draw the graph.
  graph = Flotr.draw(container, [ s1, s2 ], {
  radar : { show : true},
  grid : { circular : true, minorHorizontalLines : true},
  yaxis : { min : 0, max : 10, minorTickFreq : 2},
  xaxis : { ticks : ticks}
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-stacked',
  name : 'Basic Stacked',
  callback : basic_stacked,
  type : 'test'
  });
 
  function basic_stacked (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 2], [9, 3]], // First data series
  d2 = [[0, 2], [4, 3], [8, 8], [9, 4]], // Second data series
  i, graph;
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  lines: {
  show : true,
  stacked: true
  },
  xaxis: {
  minorTickFreq: 4
  },
  grid: {
  minorVerticalLines: true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-stepped',
  name : 'Basic Stepped',
  callback : basic_stepped,
  type : 'test'
  });
 
  function basic_stepped (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
  d2 = [], // Second data series
  i, graph;
 
  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  lines: {
  steps : true,
  show : true
  },
  xaxis: {
  minorTickFreq: 4
  },
  yaxis: {
  autoscale: true
  },
  grid: {
  minorVerticalLines: true
  },
  mouse : {
  track : true,
  relative : true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-time',
  name : 'Basic Time',
  callback : basic_time,
  description : "<p>Select an area of the graph to zoom. Click to reset the chart.</p>"
  });
 
  function basic_time (container) {
 
  var
  d1 = [],
  start = new Date("2009/01/01 01:00").getTime(),
  options,
  graph,
  i, x, o;
 
  for (i = 0; i < 100; i++) {
  x = start+(i*1000*3600*24*36.5);
  d1.push([x, i+Math.random()*30+Math.sin(i/20+Math.random()*2)*20+Math.sin(i/10+Math.random())*10]);
  }
 
  options = {
  xaxis : {
  mode : 'time',
  labelsAngle : 45
  },
  selection : {
  mode : 'x'
  },
  HtmlText : false,
  title : 'Time'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1 ],
  o
  );
  }
 
  graph = drawGraph();
 
  Flotr.EventAdapter.observe(container, 'flotr:select', function(area){
  // Draw selected area
  graph = drawGraph({
  xaxis : { min : area.x1, max : area.x2, mode : 'time', labelsAngle : 45 },
  yaxis : { min : area.y1, max : area.y2 }
  });
  });
 
  // When graph is clicked, draw the graph with default area.
  Flotr.EventAdapter.observe(container, 'flotr:click', function () { graph = drawGraph(); });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-timeline',
  name : 'Basic Timeline',
  callback : basic_timeline
  });
 
  function basic_timeline (container) {
 
  var
  d1 = [[1, 4, 5]],
  d2 = [[3.2, 3, 4]],
  d3 = [[1.9, 2, 2], [5, 2, 3.3]],
  d4 = [[1.55, 1, 9]],
  d5 = [[5, 0, 2.3]],
  data = [],
  timeline = { show : true, barWidth : .5 },
  markers = [],
  labels = ['Obama', 'Bush', 'Clinton', 'Palin', 'McCain'],
  i, graph, point;
 
  // Timeline
  Flotr._.each([d1, d2, d3, d4, d5], function (d) {
  data.push({
  data : d,
  timeline : Flotr._.clone(timeline)
  });
  });
 
  // Markers
  Flotr._.each([d1, d2, d3, d4, d5], function (d) {
  point = d[0];
  markers.push([point[0], point[1]]);
  });
  data.push({
  data: markers,
  markers: {
  show: true,
  position: 'rm',
  fontSize: 11,
  labelFormatter : function (o) { return labels[o.index]; }
  }
  });
 
  // Draw Graph
  graph = Flotr.draw(container, data, {
  xaxis: {
  noTicks: 3,
  tickFormatter: function (x) {
  var
  x = parseInt(x),
  months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return months[(x-1)%12];
  }
  },
  yaxis: {
  showLabels : false
  },
  grid: {
  horizontalLines : false
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic',
  name : 'Basic',
  callback : basic
  });
 
  function basic (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
  d2 = [], // Second data series
  i, graph;
 
  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  xaxis: {
  minorTickFreq: 4
  },
  grid: {
  minorVerticalLines: true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'click-example',
  name : 'Click Example',
  callback : click_example
  });
 
  function click_example (container) {
 
  var
  d1 = [[0,0]], // Point at origin
  options,
  graph;
 
  options = {
  xaxis: {min: 0, max: 15},
  yaxis: {min: 0, max: 15},
  lines: {show: true},
  points: {show: true},
  mouse: {track:true},
  title: 'Click Example'
  };
 
  graph = Flotr.draw(container, [d1], options);
 
  // Add a point to the series and redraw the graph
  Flotr.EventAdapter.observe(container, 'flotr:click', function(position){
 
  // Add a point to the series at the location of the click
  d1.push([position.x, position.y]);
 
  // Sort the series.
  d1 = d1.sort(function (a, b) { return a[0] - b[0]; });
 
  // Redraw the graph, with the new series.
  graph = Flotr.draw(container, [d1], options);
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'color-gradients',
  name : 'Color Gradients',
  callback : color_gradients
  });
 
  function color_gradients (container) {
 
  var
  bars = {
  data: [],
  bars: {
  show: true,
  barWidth: 0.8,
  lineWidth: 0,
  fillColor: {
  colors: ['#CB4B4B', '#fff'],
  start: 'top',
  end: 'bottom'
  },
  fillOpacity: 0.8
  }
  }, markers = {
  data: [],
  markers: {
  show: true,
  position: 'ct'
  }
  }, lines = {
  data: [],
  lines: {
  show: true,
  fillColor: ['#00A8F0', '#fff'],
  fill: true,
  fillOpacity: 1
  }
  },
  point,
  graph,
  i;
 
  for (i = 0; i < 8; i++) {
  point = [i, Math.ceil(Math.random() * 10)];
  bars.data.push(point);
  markers.data.push(point);
  }
 
  for (i = -1; i < 9; i += 0.01){
  lines.data.push([i, i*i/8+2]);
  }
 
  graph = Flotr.draw(
  container,
  [lines, bars, markers], {
  yaxis: {
  min: 0,
  max: 11
  },
  xaxis: {
  min: -0.5,
  max: 7.5
  },
  grid: {
  verticalLines: false,
  backgroundColor: ['#fff', '#ccc']
  }
  }
  );
  };
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'download-data',
  name : 'Download Data',
  callback : download_data
  });
 
  function download_data (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i,x;
 
  for (i = 0; i <= 100; i += 1) {
  x = i / 10;
  d1.push([x, 4 + Math.pow(x,1.5)]);
  d2.push([x, Math.pow(x,3)]);
  d3.push([x, i*5+3*Math.sin(x*4)]);
  d4.push([x, x]);
  if(x%1 === 0 ){
  d5.push([x, 2*x]);
  }
  }
 
  // Draw the graph.
  graph = Flotr.draw(
  container, [
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3' },
  { data : d3, label : 'y = 5x + 3sin(4x)' },
  { data : d4, label : 'y = x' },
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ],{
  xaxis : {
  noTicks : 7,
  tickFormatter : function (n) { return '('+n+')'; },
  min: 1, // Part of the series is not displayed.
  max: 7.5
  },
  yaxis : {
  ticks : [[ 0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max : 40
  },
  grid : {
  verticalLines : false,
  backgroundColor : 'white'
  },
  legend : {
  position : 'nw'
  },
  spreadsheet : {
  show : true,
  tickFormatter : function (e) { return e+''; }
  }
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'download-image',
  name : 'Download Image',
  callback : download_image,
  description : '' +
  '<form name="image-download" id="image-download" action="" onsubmit="return false">' +
  '<label><input type="radio" name="format" value="png" checked="checked" /> PNG</label>' +
  '<label><input type="radio" name="format" value="jpeg" /> JPEG</label>' +
 
  '<button name="to-image" onclick="CurrentExample(\'to-image\')">To Image</button>' +
  '<button name="download" onclick="CurrentExample(\'download\')">Download</button>' +
  '<button name="reset" onclick="CurrentExample(\'reset\')">Reset</button>' +
  '</form>'
  });
 
  function download_image (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i;
 
  for (i = 0; i <= 10; i += 0.1) {
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if( i.toFixed(1)%1 == 0 ){
  d5.push([i, 2*i]);
  }
  }
 
  // Draw the graph
  graph = Flotr.draw(
  container,[
  {data:d1, label:'y = 4 + x^(1.5)', lines:{fill:true}},
  {data:d2, label:'y = x^3', yaxis:2},
  {data:d3, label:'y = 5x + 3sin(4x)'},
  {data:d4, label:'y = x'},
  {data:d5, label:'y = 2x', lines: {show: true}, points: {show: true}}
  ],{
  title: 'Download Image Example',
  subtitle: 'You can save me as an image',
  xaxis:{
  noTicks: 7, // Display 7 ticks.
  tickFormatter: function(n){ return '('+n+')'; }, // => displays tick values between brackets.
  min: 1, // => part of the series is not displayed.
  max: 7.5, // => part of the series is not displayed.
  labelsAngle: 45,
  title: 'x Axis'
  },
  yaxis:{
  ticks: [[0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max: 40,
  title: 'y = f(x)'
  },
  y2axis:{color:'#FF0000', max: 500, title: 'y = x^3'},
  grid:{
  verticalLines: false,
  backgroundColor: 'white'
  },
  HtmlText: false,
  legend: {
  position: 'nw'
  }
  });
 
  this.CurrentExample = function (operation) {
 
  var
  format = $('#image-download input:radio[name=format]:checked').val();
  if (Flotr.isIE && Flotr.isIE < 9) {
  alert(
  "Your browser doesn't allow you to get a bitmap image from the plot, " +
  "you can only get a VML image that you can use in Microsoft Office.<br />"
  );
  }
 
  if (operation == 'to-image') {
  graph.download.saveImage(format, null, null, true)
  } else if (operation == 'download') {
  graph.download.saveImage(format);
  } else if (operation == 'reset') {
  graph.download.restoreCanvas();
  }
  };
 
  return graph;
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-drag',
  name : 'Mouse Drag',
  callback : mouse_drag
  });
 
  function mouse_drag (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  options,
  graph,
  start,
  i;
 
  for (i = -40; i < 40; i += 0.5) {
  d1.push([i, Math.sin(i)+3*Math.cos(i)]);
  d2.push([i, Math.pow(1.1, i)]);
  d3.push([i, 40 - i+Math.random()*10]);
  }
 
  options = {
  xaxis: {min: 0, max: 20},
  title : 'Mouse Drag'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  var o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1, d2, d3 ],
  o
  );
  }
 
  graph = drawGraph();
 
  function initializeDrag (e) {
  start = graph.getEventPosition(e);
  Flotr.EventAdapter.observe(document, 'mousemove', move);
  Flotr.EventAdapter.observe(document, 'mouseup', stopDrag);
  }
 
  function move (e) {
  var
  end = graph.getEventPosition(e),
  xaxis = graph.axes.x,
  offset = start.x - end.x;
 
  graph = drawGraph({
  xaxis : {
  min : xaxis.min + offset,
  max : xaxis.max + offset
  }
  });
  // @todo: refector initEvents in order not to remove other observed events
  Flotr.EventAdapter.observe(graph.overlay, 'mousedown', initializeDrag);
  }
 
  function stopDrag () {
  Flotr.EventAdapter.stopObserving(document, 'mousemove', move);
  }
 
  Flotr.EventAdapter.observe(graph.overlay, 'mousedown', initializeDrag);
 
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-tracking',
  name : 'Mouse Tracking',
  callback : mouse_tracking
  });
 
  function mouse_tracking (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  graph, i;
 
  for (i = 0; i < 20; i += 0.5) {
  d1.push([i, 2*i]);
  d2.push([i, i*1.5+1.5*Math.sin(i)]);
  d3.push([i, 3*Math.cos(i)+10]);
  }
 
  graph = Flotr.draw(
  container,
  [
  {
  data : d1,
  mouse : { track : false } // Disable mouse tracking for d1
  },
  d2,
  d3
  ],
  {
  mouse : {
  track : true, // Enable mouse tracking
  lineColor : 'purple',
  relative : true,
  position : 'ne',
  sensibility : 1,
  trackDecimals : 2,
  trackFormatter : function (o) { return 'x = ' + o.x +', y = ' + o.y; }
  },
  crosshair : {
  mode : 'xy'
  }
  }
  );
 
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-zoom',
  name : 'Mouse Zoom',
  callback : mouse_zoom,
  description : "<p>Select an area of the graph to zoom. Click to reset the chart.</p>"
  });
 
  function mouse_zoom (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  options,
  graph,
  i;
 
  for (i = 0; i < 40; i += 0.5) {
  d1.push([i, Math.sin(i)+3*Math.cos(i)]);
  d2.push([i, Math.pow(1.1, i)]);
  d3.push([i, 40 - i+Math.random()*10]);
  }
 
  options = {
  selection : { mode : 'x', fps : 30 },
  title : 'Mouse Zoom'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  var o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1, d2, d3 ],
  o
  );
  }
 
  // Actually draw the graph.
  graph = drawGraph();
 
  // Hook into the 'flotr:select' event.
  Flotr.EventAdapter.observe(container, 'flotr:select', function (area) {
 
  // Draw graph with new area
  graph = drawGraph({
  xaxis: {min:area.x1, max:area.x2},
  yaxis: {min:area.y1, max:area.y2}
  });
  });
 
  // When graph is clicked, draw the graph with default area.
  Flotr.EventAdapter.observe(container, 'flotr:click', function () { drawGraph(); });
  };
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'negative-values',
  name : 'Negative Values',
  callback : negative_values
  });
 
  function negative_values (container) {
 
  var
  d0 = [], // Line through y = 0
  d1 = [], // Random data presented as a scatter plot.
  d2 = [], // A regression line for the scatter.
  sx = 0,
  sy = 0,
  sxy = 0,
  sxsq = 0,
  xmean,
  ymean,
  alpha,
  beta,
  n, x, y;
 
  for (n = 0; n < 20; n++){
 
  x = n;
  y = x + Math.random()*8 - 15;
 
  d0.push([x, 0]);
  d1.push([x, y]);
 
  // Computations used for regression line
  sx += x;
  sy += y;
  sxy += x*y;
  sxsq += Math.pow(x,2);
  }
 
  xmean = sx/n;
  ymean = sy/n;
  beta = ((n*sxy) - (sx*sy))/((n*sxsq)-(Math.pow(sx,2)));
  alpha = ymean - (beta * xmean);
 
  // Compute the regression line.
  for (n = 0; n < 20; n++){
  d2.push([n, alpha + beta*n])
  }
 
  // Draw the graph
  graph = Flotr.draw(
  container, [
  { data : d0, shadowSize : 0, color : '#545454' }, // Horizontal
  { data : d1, label : 'y = x + (Math.random() * 8) - 15', points : { show : true } }, // Scatter
  { data : d2, label : 'y = ' + alpha.toFixed(2) + ' + ' + beta.toFixed(2) + '*x' } // Regression
  ],
  {
  legend : { position : 'se', backgroundColor : '#D2E8FF' },
  title : 'Negative Values'
  }
  );
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'profile-bars',
  name : 'Profile Bars',
  type : 'profile',
  callback : profile_bars
  });
 
  /*
  Flotr.ExampleList.add({
  key : 'basic-bars-horizontal',
  name : 'Horizontal Bars',
  args : [true],
  callback : basic_bars
  });
  */
 
  function profile_bars (container, horizontal) {
 
  var
  horizontal = (horizontal ? true : false), // Show horizontal bars
  d1 = [], // First data series
  d2 = [], // Second data series
  point, // Data point variable declaration
  i;
 
  for (i = 0; i < 5000; i++) {
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i];
  } else {
  point = [i, Math.ceil(Math.random()*10)];
  }
 
  d1.push(point);
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i+0.5];
  } else {
  point = [i+0.5, Math.ceil(Math.random()*10)];
  }
 
  d2.push(point);
  };
 
  // Draw the graph
  Flotr.draw(
  container,
  [d1, d2],
  {
  bars : {
  show : true,
  horizontal : horizontal,
  barWidth : 0.5
  },
  mouse : {
  track : true,
  relative : true
  },
  yaxis : {
  min : 0,
  autoscaleMargin : 1
  }
  }
  );
  }
 
  })();
 
  yepnope([
  // Libs
  '../lib/bean-min.js',
  '../lib/underscore-min.js',
  {
  test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
  // Load for IE < 9
  yep : [
  '../lib/excanvas.js',
  '../lib/base64.js',
  '../lib/canvastext.js'
  ]
  },
  'lib/codemirror/lib/codemirror.js',
  'lib/codemirror/mode/javascript/javascript.js',
  'lib/beautify.js',
  'lib/randomseed.js',
  'lib/jquery-1.7.1.min.js',
  'lib/jquery.ba-hashchange.min.js',
 
  // Flotr
  '../js/Flotr.js',
  '../js/DefaultOptions.js',
  '../js/Color.js',
  '../js/Date.js',
  '../js/DOM.js',
  '../js/EventAdapter.js',
  '../js/Text.js',
  '../js/Graph.js',
  '../js/Axis.js',
  '../js/Series.js',
  '../js/types/lines.js',
  '../js/types/bars.js',
  '../js/types/points.js',
  '../js/types/pie.js',
  '../js/types/candles.js',
  '../js/types/markers.js',
  '../js/types/radar.js',
  '../js/types/bubbles.js',
  '../js/types/gantt.js',
  '../js/types/timeline.js',
  '../js/plugins/download.js',
  '../js/plugins/selection.js',
  '../js/plugins/spreadsheet.js',
  '../js/plugins/grid.js',
  '../js/plugins/hit.js',
  '../js/plugins/crosshair.js',
  '../js/plugins/labels.js',
  '../js/plugins/legend.js',
  '../js/plugins/titles.js',
 
  // Examples
  'js/Examples.js',
  'js/ExampleList.js',
  'js/Example.js',
  'js/Editor.js',
  'js/Profile.js',
  'js/examples/basic.js',
  'js/examples/basic-axis.js',
  'js/examples/basic-bars.js',
  'js/examples/basic-bars-stacked.js',
  'js/examples/basic-pie.js',
  'js/examples/basic-radar.js',
  'js/examples/basic-bubble.js',
  'js/examples/basic-candle.js',
  'js/examples/basic-legend.js',
  'js/examples/mouse-tracking.js',
  'js/examples/mouse-zoom.js',
  'js/examples/mouse-drag.js',
  'js/examples/basic-time.js',
  'js/examples/negative-values.js',
  'js/examples/click-example.js',
  'js/examples/download-image.js',
  'js/examples/download-data.js',
  'js/examples/advanced-titles.js',
  'js/examples/color-gradients.js',
  'js/examples/profile-bars.js',
  'js/examples/basic-timeline.js',
  'js/examples/advanced-markers.js',
 
  { complete : function () {
  if (Flotr.ExamplesCallback) {
  Flotr.ExamplesCallback();
  } else {
  Examples = new Flotr.Examples({
  node : document.getElementById('examples')
  });
  }
  }
  }
  ]);
 
  yepnope([
  {
  test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
  // Load for IE < 9
  yep : [
  '../flotr2.ie.min.js'
  ]
  },
  '../flotr2.min.js',
 
  'lib/codemirror/lib/codemirror.js',
  'lib/codemirror/mode/javascript/javascript.js',
  'lib/beautify.js',
  'lib/randomseed.js',
  'lib/jquery-1.7.1.min.js',
  'lib/jquery.ba-hashchange.min.js',
 
  // Examples
  '../flotr2.examples.min.js',
  '../flotr2.examples.types.js',
 
  { complete : function () {
  if (Flotr.ExamplesCallback) {
  Flotr.ExamplesCallback();
  } else {
  Examples = new Flotr.Examples({
  node : document.getElementById('examples')
  });
  }
  }
  }
  ]);
 
 
  /*jslint onevar: false, plusplus: false */
  /*
 
  JS Beautifier
  ---------------
 
 
  Written by Einar Lielmanis, <einar@jsbeautifier.org>
  http://jsbeautifier.org/
 
  Originally converted to javascript by Vital, <vital76@gmail.com>
  "End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com>
 
  You are free to use this in any way you want, in case you find this useful or working for you.
 
  Usage:
  js_beautify(js_source_text);
  js_beautify(js_source_text, options);
 
  The options are:
  indent_size (default 4) — indentation size,
  indent_char (default space) — character to indent with,
  preserve_newlines (default true) — whether existing line breaks should be preserved,
  preserve_max_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk,
 
  jslint_happy (default false) — if true, then jslint-stricter mode is enforced.
 
  jslint_happy !jslint_happy
  ---------------------------------
  function () function()
 
  brace_style (default "collapse") - "collapse" | "expand" | "end-expand"
  put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.
 
  e.g
 
  js_beautify(js_source_text, {
  'indent_size': 1,
  'indent_char': '\t'
  });
 
 
  */
 
 
 
  function js_beautify(js_source_text, options) {
 
  var input, output, token_text, last_type, last_text, last_last_text, last_word, flags, flag_store, indent_string;
  var whitespace, wordchar, punct, parser_pos, line_starters, digits;
  var prefix, token_type, do_block_just_closed;
  var wanted_newline, just_added_newline, n_newlines;
  var preindent_string = '';
 
 
  // Some interpreters have unexpected results with foo = baz || bar;
  options = options ? options : {};
 
  var opt_brace_style;
 
  // compatibility
  if (options.space_after_anon_function !== undefined && options.jslint_happy === undefined) {
  options.jslint_happy = options.space_after_anon_function;
  }
  if (options.braces_on_own_line !== undefined) { //graceful handling of depricated option
  opt_brace_style = options.braces_on_own_line ? "expand" : "collapse";
  }
  opt_brace_style = options.brace_style ? options.brace_style : (opt_brace_style ? opt_brace_style : "collapse");
 
 
  var opt_indent_size = options.indent_size ? options.indent_size : 4;
  var opt_indent_char = options.indent_char ? options.indent_char : ' ';
  var opt_preserve_newlines = typeof options.preserve_newlines === 'undefined' ? true : options.preserve_newlines;
  var opt_max_preserve_newlines = typeof options.max_preserve_newlines === 'undefined' ? false : options.max_preserve_newlines;
  var opt_jslint_happy = options.jslint_happy === 'undefined' ? false : options.jslint_happy;
  var opt_keep_array_indentation = typeof options.keep_array_indentation === 'undefined' ? false : options.keep_array_indentation;
 
  just_added_newline = false;
 
  // cache the source's length.
  var input_length = js_source_text.length;
 
  function trim_output(eat_newlines) {
  eat_newlines = typeof eat_newlines === 'undefined' ? false : eat_newlines;
  while (output.length && (output[output.length - 1] === ' '
  || output[output.length - 1] === indent_string
  || output[output.length - 1] === preindent_string
  || (eat_newlines && (output[output.length - 1] === '\n' || output[output.length - 1] === '\r')))) {
  output.pop();
  }
  }
 
  function trim(s) {
  return s.replace(/^\s\s*|\s\s*$/, '');
  }
 
  function force_newline()
  {
  var old_keep_array_indentation = opt_keep_array_indentation;
  opt_keep_array_indentation = false;
  print_newline()
  opt_keep_array_indentation = old_keep_array_indentation;
  }
 
  function print_newline(ignore_repeated) {
 
  flags.eat_next_space = false;
  if (opt_keep_array_indentation && is_array(flags.mode)) {
  return;
  }
 
  ignore_repeated = typeof ignore_repeated === 'undefined' ? true : ignore_repeated;
 
  flags.if_line = false;
  trim_output();
 
  if (!output.length) {
  return; // no newline on start of file
  }
 
  if (output[output.length - 1] !== "\n" || !ignore_repeated) {
  just_added_newline = true;
  output.push("\n");
  }
  if (preindent_string) {
  output.push(preindent_string);
  }
  for (var i = 0; i < flags.indentation_level; i += 1) {
  output.push(indent_string);
  }
  if (flags.var_line && flags.var_line_reindented) {
  output.push(indent_string); // skip space-stuffing, if indenting with a tab
  }
  }
 
 
 
  function print_single_space() {
  if (flags.eat_next_space) {
  flags.eat_next_space = false;
  return;
  }
  var last_output = ' ';
  if (output.length) {
  last_output = output[output.length - 1];
  }
  if (last_output !== ' ' && last_output !== '\n' && last_output !== indent_string) { // prevent occassional duplicate space
  output.push(' ');
  }
  }
 
 
  function print_token() {
  just_added_newline = false;
  flags.eat_next_space = false;
  output.push(token_text);
  }
 
  function indent() {
  flags.indentation_level += 1;
  }
 
 
  function remove_indent() {
  if (output.length && output[output.length - 1] === indent_string) {
  output.pop();
  }
  }
 
  function set_mode(mode) {
  if (flags) {
  flag_store.push(flags);
  }
  flags = {
  previous_mode: flags ? flags.mode : 'BLOCK',
  mode: mode,
  var_line: false,
  var_line_tainted: false,
  var_line_reindented: false,
  in_html_comment: false,
  if_line: false,
  in_case: false,
  eat_next_space: false,
  indentation_baseline: -1,
  indentation_level: (flags ? flags.indentation_level + ((flags.var_line && flags.var_line_reindented) ? 1 : 0) : 0),
  ternary_depth: 0
  };
  }
 
  function is_array(mode) {
  return mode === '[EXPRESSION]' || mode === '[INDENTED-EXPRESSION]';
  }
 
  function is_expression(mode) {
  return mode === '[EXPRESSION]' || mode === '[INDENTED-EXPRESSION]' || mode === '(EXPRESSION)';
  }
 
  function restore_mode() {
  do_block_just_closed = flags.mode === 'DO_BLOCK';
  if (flag_store.length > 0) {
  flags = flag_store.pop();
  }
  }
 
  function all_lines_start_with(lines, c) {
  for (var i = 0; i < lines.length; i++) {
  if (trim(lines[i])[0] != c) {
  return false;
  }
  }
  return true;
  }
 
  function in_array(what, arr) {
  for (var i = 0; i < arr.length; i += 1) {
  if (arr[i] === what) {
  return true;
  }
  }
  return false;
  }
 
  function get_next_token() {
  n_newlines = 0;
 
  if (parser_pos >= input_length) {
  return ['', 'TK_EOF'];
  }
 
  wanted_newline = false;
 
  var c = input.charAt(parser_pos);
  parser_pos += 1;
 
 
  var keep_whitespace = opt_keep_array_indentation && is_array(flags.mode);
 
  if (keep_whitespace) {
 
  //
  // slight mess to allow nice preservation of array indentation and reindent that correctly
  // first time when we get to the arrays:
  // var a = [
  // ....'something'
  // we make note of whitespace_count = 4 into flags.indentation_baseline
  // so we know that 4 whitespaces in original source match indent_level of reindented source
  //
  // and afterwards, when we get to
  // 'something,
  // .......'something else'
  // we know that this should be indented to indent_level + (7 - indentation_baseline) spaces
  //
  var whitespace_count = 0;
 
  while (in_array(c, whitespace)) {
 
  if (c === "\n") {
  trim_output();
  output.push("\n");
  just_added_newline = true;
  whitespace_count = 0;
  } else {
  if (c === '\t') {
  whitespace_count += 4;
  } else if (c === '\r') {
  // nothing
  } else {
  whitespace_count += 1;
  }
  }
 
  if (parser_pos >= input_length) {
  return ['', 'TK_EOF'];
  }
 
  c = input.charAt(parser_pos);
  parser_pos += 1;
 
  }
  if (flags.indentation_baseline === -1) {
  flags.indentation_baseline = whitespace_count;
  }
 
  if (just_added_newline) {
  var i;
  for (i = 0; i < flags.indentation_level + 1; i += 1) {
  output.push(indent_string);
  }
  if (flags.indentation_baseline !== -1) {
  for (i = 0; i < whitespace_count - flags.indentation_baseline; i++) {
  output.push(' ');
  }
  }
  }
 
  } else {
  while (in_array(c, whitespace)) {
 
  if (c === "\n") {
  n_newlines += ( (opt_max_preserve_newlines) ? (n_newlines <= opt_max_preserve_newlines) ? 1: 0: 1 );
  }
 
 
  if (parser_pos >= input_length) {
  return ['', 'TK_EOF'];
  }
 
  c = input.charAt(parser_pos);
  parser_pos += 1;
 
  }
 
  if (opt_preserve_newlines) {
  if (n_newlines > 1) {
  for (i = 0; i < n_newlines; i += 1) {
  print_newline(i === 0);
  just_added_newline = true;
  }
  }
  }
  wanted_newline = n_newlines > 0;
  }
 
 
  if (in_array(c, wordchar)) {
  if (parser_pos < input_length) {
  while (in_array(input.charAt(parser_pos), wordchar)) {
  c += input.charAt(parser_pos);
  parser_pos += 1;
  if (parser_pos === input_length) {
  break;
  }
  }
  }
 
  // small and surprisingly unugly hack for 1E-10 representation
  if (parser_pos !== input_length && c.match(/^[0-9]+[Ee]$/) && (input.charAt(parser_pos) === '-' || input.charAt(parser_pos) === '+')) {
 
  var sign = input.charAt(parser_pos);
  parser_pos += 1;
 
  var t = get_next_token(parser_pos);
  c += sign + t[0];
  return [c, 'TK_WORD'];
  }
 
  if (c === 'in') { // hack for 'in' operator
  return [c, 'TK_OPERATOR'];
  }
  if (wanted_newline && last_type !== 'TK_OPERATOR'
  && last_type !== 'TK_EQUALS'
  && !flags.if_line && (opt_preserve_newlines || last_text !== 'var')) {
  print_newline();
  }
  return [c, 'TK_WORD'];
  }
 
  if (c === '(' || c === '[') {
  return [c, 'TK_START_EXPR'];
  }
 
  if (c === ')' || c === ']') {
  return [c, 'TK_END_EXPR'];
  }
 
  if (c === '{') {
  return [c, 'TK_START_BLOCK'];
  }
 
  if (c === '}') {
  return [c, 'TK_END_BLOCK'];
  }
 
  if (c === ';') {
  return [c, 'TK_SEMICOLON'];
  }
 
  if (c === '/') {
  var comment = '';
  // peek for comment /* ... */
  var inline_comment = true;
  if (input.charAt(parser_pos) === '*') {
  parser_pos += 1;
  if (parser_pos < input_length) {
  while (! (input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/') && parser_pos < input_length) {
  c = input.charAt(parser_pos);
  comment += c;
  if (c === '\x0d' || c === '\x0a') {
  inline_comment = false;
  }
  parser_pos += 1;
  if (parser_pos >= input_length) {
  break;
  }
  }
  }
  parser_pos += 2;
  if (inline_comment) {
  return ['/*' + comment + '*/', 'TK_INLINE_COMMENT'];
  } else {
  return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
  }
  }
  // peek for comment // ...
  if (input.charAt(parser_pos) === '/') {
  comment = c;
  while (input.charAt(parser_pos) !== '\r' && input.charAt(parser_pos) !== '\n') {
  comment += input.charAt(parser_pos);
  parser_pos += 1;
  if (parser_pos >= input_length) {
  break;
  }
  }
  parser_pos += 1;
  if (wanted_newline) {
  print_newline();
  }
  return [comment, 'TK_COMMENT'];
  }
 
  }
 
  if (c === "'" || // string
  c === '"' || // string
  (c === '/' &&
  ((last_type === 'TK_WORD' && in_array(last_text, ['return', 'do'])) ||
  (last_type === 'TK_COMMENT' || last_type === 'TK_START_EXPR' || last_type === 'TK_START_BLOCK' || last_type === 'TK_END_BLOCK' || last_type === 'TK_OPERATOR' || last_type === 'TK_EQUALS' || last_type === 'TK_EOF' || last_type === 'TK_SEMICOLON')))) { // regexp
  var sep = c;
  var esc = false;
  var resulting_string = c;
 
  if (parser_pos < input_length) {
  if (sep === '/') {
  //
  // handle regexp separately...
  //
  var in_char_class = false;
  while (esc || in_char_class || input.charAt(parser_pos) !== sep) {
  resulting_string += input.charAt(parser_pos);
  if (!esc) {
  esc = input.charAt(parser_pos) === '\\';
  if (input.charAt(parser_pos) === '[') {
  in_char_class = true;
  } else if (input.charAt(parser_pos) === ']') {
  in_char_class = false;
  }
  } else {
  esc = false;
  }
  parser_pos += 1;
  if (parser_pos >= input_length) {
  // incomplete string/rexp when end-of-file reached.
  // bail out with what had been received so far.
  return [resulting_string, 'TK_STRING'];
  }
  }
 
  } else {
  //
  // and handle string also separately
  //
  while (esc || input.charAt(parser_pos) !== sep) {
  resulting_string += input.charAt(parser_pos);
  if (!esc) {
  esc = input.charAt(parser_pos) === '\\';
  } else {
  esc = false;
  }
  parser_pos += 1;
  if (parser_pos >= input_length) {
  // incomplete string/rexp when end-of-file reached.
  // bail out with what had been received so far.
  return [resulting_string, 'TK_STRING'];
  }
  }
  }
 
 
 
  }
 
  parser_pos += 1;
 
  resulting_string += sep;
 
  if (sep === '/') {
  // regexps may have modifiers /regexp/MOD , so fetch those, too
  while (parser_pos < input_length && in_array(input.charAt(parser_pos), wordchar)) {
  resulting_string += input.charAt(parser_pos);
  parser_pos += 1;
  }
  }
  return [resulting_string, 'TK_STRING'];
  }
 
  if (c === '#') {
 
 
  if (output.length === 0 && input.charAt(parser_pos) === '!') {
  // shebang
  resulting_string = c;
  while (parser_pos < input_length && c != '\n') {
  c = input.charAt(parser_pos);
  resulting_string += c;
  parser_pos += 1;
  }
  output.push(trim(resulting_string) + '\n');
  print_newline();
  return get_next_token();
  }
 
 
 
  // Spidermonkey-specific sharp variables for circular references
  // https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
  // http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
  var sharp = '#';
  if (parser_pos < input_length && in_array(input.charAt(parser_pos), digits)) {
  do {
  c = input.charAt(parser_pos);
  sharp += c;
  parser_pos += 1;
  } while (parser_pos < input_length && c !== '#' && c !== '=');
  if (c === '#') {
  //
  } else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') {
  sharp += '[]';
  parser_pos += 2;
  } else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') {
  sharp += '{}';
  parser_pos += 2;
  }
  return [sharp, 'TK_WORD'];
  }
  }
 
  if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') {
  parser_pos += 3;
  flags.in_html_comment = true;
  return ['<!--', 'TK_COMMENT'];
  }
 
  if (c === '-' && flags.in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') {
  flags.in_html_comment = false;
  parser_pos += 2;
  if (wanted_newline) {
  print_newline();
  }
  return ['-->', 'TK_COMMENT'];
  }
 
  if (in_array(c, punct)) {
  while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) {
  c += input.charAt(parser_pos);
  parser_pos += 1;
  if (parser_pos >= input_length) {
  break;
  }
  }
 
  if (c === '=') {
  return [c, 'TK_EQUALS'];
  } else {
  return [c, 'TK_OPERATOR'];
  }
  }
 
  return [c, 'TK_UNKNOWN'];
  }
 
  //----------------------------------
  indent_string = '';
  while (opt_indent_size > 0) {
  indent_string += opt_indent_char;
  opt_indent_size -= 1;
  }
 
  while (js_source_text && (js_source_text[0] === ' ' || js_source_text[0] === '\t')) {
  preindent_string += js_source_text[0];
  js_source_text = js_source_text.substring(1);
  }
  input = js_source_text;
 
  last_word = ''; // last 'TK_WORD' passed
  last_type = 'TK_START_EXPR'; // last token type
  last_text = ''; // last token text
  last_last_text = ''; // pre-last token text
  output = [];
 
  do_block_just_closed = false;
 
  whitespace = "\n\r\t ".split('');
  wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split('');
  digits = '0123456789'.split('');
 
  punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::'.split(' ');
 
  // words which should always start on new line.
  line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(',');
 
  // states showing if we are currently in expression (i.e. "if" case) - 'EXPRESSION', or in usual block (like, procedure), 'BLOCK'.
  // some formatting depends on that.
  flag_store = [];
  set_mode('BLOCK');
 
  parser_pos = 0;
  while (true) {
  var t = get_next_token(parser_pos);
  token_text = t[0];
  token_type = t[1];
  if (token_type === 'TK_EOF') {
  break;
  }
 
  switch (token_type) {
 
  case 'TK_START_EXPR':
 
  if (token_text === '[') {
 
  if (last_type === 'TK_WORD' || last_text === ')') {
  // this is array index specifier, break immediately
  // a[x], fn()[x]
  if (in_array(last_text, line_starters)) {
  print_single_space();
  }
  set_mode('(EXPRESSION)');
  print_token();
  break;
  }
 
  if (flags.mode === '[EXPRESSION]' || flags.mode === '[INDENTED-EXPRESSION]') {
  if (last_last_text === ']' && last_text === ',') {
  // ], [ goes to new line
  if (flags.mode === '[EXPRESSION]') {
  flags.mode = '[INDENTED-EXPRESSION]';
  if (!opt_keep_array_indentation) {
  indent();
  }
  }
  set_mode('[EXPRESSION]');
  if (!opt_keep_array_indentation) {
  print_newline();
  }
  } else if (last_text === '[') {
  if (flags.mode === '[EXPRESSION]') {
  flags.mode = '[INDENTED-EXPRESSION]';
  if (!opt_keep_array_indentation) {
  indent();
  }
  }
  set_mode('[EXPRESSION]');
 
  if (!opt_keep_array_indentation) {
  print_newline();
  }
  } else {
  set_mode('[EXPRESSION]');
  }
  } else {
  set_mode('[EXPRESSION]');
  }
 
 
 
  } else {
  set_mode('(EXPRESSION)');
  }
 
  if (last_text === ';' || last_type === 'TK_START_BLOCK') {
  print_newline();
  } else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || last_text === '.') {
  // do nothing on (( and )( and ][ and ]( and .(
  } else if (last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
  print_single_space();
  } else if (last_word === 'function' || last_word === 'typeof') {
  // function() vs function ()
  if (opt_jslint_happy) {
  print_single_space();
  }
  } else if (in_array(last_text, line_starters) || last_text === 'catch') {
  print_single_space();
  }
  print_token();
 
  break;
 
  case 'TK_END_EXPR':
  if (token_text === ']') {
  if (opt_keep_array_indentation) {
  if (last_text === '}') {
  // trim_output();
  // print_newline(true);
  remove_indent();
  print_token();
  restore_mode();
  break;
  }
  } else {
  if (flags.mode === '[INDENTED-EXPRESSION]') {
  if (last_text === ']') {
  restore_mode();
  print_newline();
  print_token();
  break;
  }
  }
  }
  }
  restore_mode();
  print_token();
  break;
 
  case 'TK_START_BLOCK':
 
  if (last_word === 'do') {
  set_mode('DO_BLOCK');
  } else {
  set_mode('BLOCK');
  }
  if (opt_brace_style=="expand") {
  if (last_type !== 'TK_OPERATOR') {
  if (last_text === 'return' || last_text === '=') {
  print_single_space();
  } else {
  print_newline(true);
  }
  }
  print_token();
  indent();
  } else {
  if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
  if (last_type === 'TK_START_BLOCK') {
  print_newline();
  } else {
  print_single_space();
  }
  } else {
  // if TK_OPERATOR or TK_START_EXPR
  if (is_array(flags.previous_mode) && last_text === ',') {
  if (last_last_text === '}') {
  // }, { in array context
  print_single_space();
  } else {
  print_newline(); // [a, b, c, {
  }
  }
  }
  indent();
  print_token();
  }
 
  break;
 
  case 'TK_END_BLOCK':
  restore_mode();
  if (opt_brace_style=="expand") {
  if (last_text !== '{') {
  print_newline();
  }
  print_token();
  } else {
  if (last_type === 'TK_START_BLOCK') {
  // nothing
  if (just_added_newline) {
  remove_indent();
  } else {
  // {}
  trim_output();
  }
  } else {
  if (is_array(flags.mode) && opt_keep_array_indentation) {
  // we REALLY need a newline here, but newliner would skip that
  opt_keep_array_indentation = false;
  print_newline();
  opt_keep_array_indentation = true;
 
  } else {
  print_newline();
  }
  }
  print_token();
  }
  break;
 
  case 'TK_WORD':
 
  // no, it's not you. even I have problems understanding how this works
  // and what does what.
  if (do_block_just_closed) {
  // do {} ## while ()
  print_single_space();
  print_token();
  print_single_space();
  do_block_just_closed = false;
  break;
  }
 
  if (token_text === 'function') {
  if (flags.var_line) {
  flags.var_line_reindented = true;
  }
  if ((just_added_newline || last_text === ';') && last_text !== '{') {
  // make sure there is a nice clean space of at least one blank line
  // before a new function definition
  n_newlines = just_added_newline ? n_newlines : 0;
  if ( ! opt_preserve_newlines) {
  n_newlines = 1;
  }
 
  for (var i = 0; i < 2 - n_newlines; i++) {
  print_newline(false);
  }
  }
  }
 
  if (token_text === 'case' || token_text === 'default') {
  if (last_text === ':') {
  // switch cases following one another
  remove_indent();
  } else {
  // case statement starts in the same line where switch
  flags.indentation_level--;
  print_newline();
  flags.indentation_level++;
  }
  print_token();
  flags.in_case = true;
  break;
  }
 
  prefix = 'NONE';
 
  if (last_type === 'TK_END_BLOCK') {
 
  if (!in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) {
  prefix = 'NEWLINE';
  } else {
  if (opt_brace_style=="expand" || opt_brace_style=="end-expand") {
  prefix = 'NEWLINE';
  } else {
  prefix = 'SPACE';
  print_single_space();
  }
  }
  } else if (last_type === 'TK_SEMICOLON' && (flags.mode === 'BLOCK' || flags.mode === 'DO_BLOCK')) {
  prefix = 'NEWLINE';
  } else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) {
  prefix = 'SPACE';
  } else if (last_type === 'TK_STRING') {
  prefix = 'NEWLINE';
  } else if (last_type === 'TK_WORD') {
  if (last_text === 'else') {
  // eat newlines between ...else *** some_op...
  // won't preserve extra newlines in this place (if any), but don't care that much
  trim_output(true);
  }
  prefix = 'SPACE';
  } else if (last_type === 'TK_START_BLOCK') {
  prefix = 'NEWLINE';
  } else if (last_type === 'TK_END_EXPR') {
  print_single_space();
  prefix = 'NEWLINE';
  }
 
  if (in_array(token_text, line_starters) && last_text !== ')') {
  if (last_text == 'else') {
  prefix = 'SPACE';
  } else {
  prefix = 'NEWLINE';
  }
  }
 
  if (flags.if_line && last_type === 'TK_END_EXPR') {
  flags.if_line = false;
  }
  if (in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) {
  if (last_type !== 'TK_END_BLOCK' || opt_brace_style=="expand" || opt_brace_style=="end-expand") {
  print_newline();
  } else {
  trim_output(true);
  print_single_space();
  }
  } else if (prefix === 'NEWLINE') {
  if ((last_type === 'TK_START_EXPR' || last_text === '=' || last_text === ',') && token_text === 'function') {
  // no need to force newline on 'function': (function
  // DONOTHING
  } else if (token_text === 'function' && last_text == 'new') {
  print_single_space();
  } else if (last_text === 'return' || last_text === 'throw') {
  // no newline between 'return nnn'
  print_single_space();
  } else if (last_type !== 'TK_END_EXPR') {
  if ((last_type !== 'TK_START_EXPR' || token_text !== 'var') && last_text !== ':') {
  // no need to force newline on 'var': for (var x = 0...)
  if (token_text === 'if' && last_word === 'else' && last_text !== '{') {
  // no newline for } else if {
  print_single_space();
  } else {
  flags.var_line = false;
  flags.var_line_reindented = false;
  print_newline();
  }
  }
  } else if (in_array(token_text, line_starters) && last_text != ')') {
  flags.var_line = false;
  flags.var_line_reindented = false;
  print_newline();
  }
  } else if (is_array(flags.mode) && last_text === ',' && last_last_text === '}') {
  print_newline(); // }, in lists get a newline treatment
  } else if (prefix === 'SPACE') {
  print_single_space();
  }
  print_token();
  last_word = token_text;
 
  if (token_text === 'var') {
  flags.var_line = true;
  flags.var_line_reindented = false;
  flags.var_line_tainted = false;
  }
 
  if (token_text === 'if') {
  flags.if_line = true;
  }
  if (token_text === 'else') {
  flags.if_line = false;
  }
 
  break;
 
  case 'TK_SEMICOLON':
 
  print_token();
  flags.var_line = false;
  flags.var_line_reindented = false;
  if (flags.mode == 'OBJECT') {
  // OBJECT mode is weird and doesn't get reset too well.
  flags.mode = 'BLOCK';
  }
  break;
 
  case 'TK_STRING':
 
  if (last_type === 'TK_START_BLOCK' || last_type === 'TK_END_BLOCK' || last_type === 'TK_SEMICOLON') {
  print_newline();
  } else if (last_type === 'TK_WORD') {
  print_single_space();
  }
  print_token();
  break;
 
  case 'TK_EQUALS':
  if (flags.var_line) {
  // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
  flags.var_line_tainted = true;
  }
  print_single_space();
  print_token();
  print_single_space();
  break;
 
  case 'TK_OPERATOR':
 
  var space_before = true;
  var space_after = true;
 
  if (flags.var_line && token_text === ',' && (is_expression(flags.mode))) {
  // do not break on comma, for(var a = 1, b = 2)
  flags.var_line_tainted = false;
  }
 
  if (flags.var_line) {
  if (token_text === ',') {
  if (flags.var_line_tainted) {
  print_token();
  flags.var_line_reindented = true;
  flags.var_line_tainted = false;
  print_newline();
  break;
  } else {
  flags.var_line_tainted = false;
  }
  // } else if (token_text === ':') {
  // hmm, when does this happen? tests don't catch this
  // flags.var_line = false;
  }
  }
 
  if (last_text === 'return' || last_text === 'throw') {
  // "return" had a special handling in TK_WORD. Now we need to return the favor
  print_single_space();
  print_token();
  break;
  }
 
  if (token_text === ':' && flags.in_case) {
  print_token(); // colon really asks for separate treatment
  print_newline();
  flags.in_case = false;
  break;
  }
 
  if (token_text === '::') {
  // no spaces around exotic namespacing syntax operator
  print_token();
  break;
  }
 
  if (token_text === ',') {
  if (flags.var_line) {
  if (flags.var_line_tainted) {
  print_token();
  print_newline();
  flags.var_line_tainted = false;
  } else {
  print_token();
  print_single_space();
  }
  } else if (last_type === 'TK_END_BLOCK' && flags.mode !== "(EXPRESSION)") {
  print_token();
  if (flags.mode === 'OBJECT' && last_text === '}') {
  print_newline();
  } else {
  print_single_space();
  }
  } else {
  if (flags.mode === 'OBJECT') {
  print_token();
  print_newline();
  } else {
  // EXPR or DO_BLOCK
  print_token();
  print_single_space();
  }
  }
  break;
  // } else if (in_array(token_text, ['--', '++', '!']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS']) || in_array(last_text, line_starters) || in_array(last_text, ['==', '!=', '+=', '-=', '*=', '/=', '+', '-'])))) {
  } else if (in_array(token_text, ['--', '++', '!']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array(last_text, line_starters)))) {
  // unary operators (and binary +/- pretending to be unary) special cases
 
  space_before = false;
  space_after = false;
 
  if (last_text === ';' && is_expression(flags.mode)) {
  // for (;; ++i)
  // ^^^
  space_before = true;
  }
  if (last_type === 'TK_WORD' && in_array(last_text, line_starters)) {
  space_before = true;
  }
 
  if (flags.mode === 'BLOCK' && (last_text === '{' || last_text === ';')) {
  // { foo; --i }
  // foo(); --bar;
  print_newline();
  }
  } else if (token_text === '.') {
  // decimal digits or object.property
  space_before = false;
 
  } else if (token_text === ':') {
  if (flags.ternary_depth == 0) {
  flags.mode = 'OBJECT';
  space_before = false;
  } else {
  flags.ternary_depth -= 1;
  }
  } else if (token_text === '?') {
  flags.ternary_depth += 1;
  }
  if (space_before) {
  print_single_space();
  }
 
  print_token();
 
  if (space_after) {
  print_single_space();
  }
 
  if (token_text === '!') {
  // flags.eat_next_space = true;
  }
 
  break;
 
  case 'TK_BLOCK_COMMENT':
 
  var lines = token_text.split(/\x0a|\x0d\x0a/);
 
  if (all_lines_start_with(lines.slice(1), '*')) {
  // javadoc: reformat and reindent
  print_newline();
  output.push(lines[0]);
  for (i = 1; i < lines.length; i++) {
  print_newline();
  output.push(' ');
  output.push(trim(lines[i]));
  }
 
  } else {
 
  // simple block comment: leave intact
  if (lines.length > 1) {
  // multiline comment block starts with a new line
  print_newline();
  trim_output();
  } else {
  // single-line /* comment */ stays where it is
  print_single_space();
 
  }
 
  for (i = 0; i < lines.length; i++) {
  output.push(lines[i]);
  output.push('\n');
  }
 
  }
  print_newline();
  break;
 
  case 'TK_INLINE_COMMENT':
 
  print_single_space();
  print_token();
  if (is_expression(flags.mode)) {
  print_single_space();
  } else {
  force_newline();
  }
  break;
 
  case 'TK_COMMENT':
 
  // print_newline();
  if (wanted_newline) {
  print_newline();
  } else {
  print_single_space();
  }
  print_token();
  force_newline();
  break;
 
  case 'TK_UNKNOWN':
  if (last_text === 'return' || last_text === 'throw') {
  print_single_space();
  }
  print_token();
  break;
  }
 
  last_last_text = last_text;
  last_type = token_type;
  last_text = token_text;
  }
 
  var sweet_code = preindent_string + output.join('').replace(/[\n ]+$/, '');
  return sweet_code;
 
  }
 
  // Add support for CommonJS. Just put this file somewhere on your require.paths
  // and you will be able to `var js_beautify = require("beautify").js_beautify`.
  if (typeof exports !== "undefined")
  exports.js_beautify = js_beautify;
 
  Copyright (C) 2011 by Marijn Haverbeke <marijnh@gmail.com>
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
 
  # CodeMirror 2
 
  CodeMirror 2 is a rewrite of [CodeMirror
  1](http://github.com/marijnh/CodeMirror). The docs live
  [here](http://codemirror.net/doc/manual.html), and the project page is
  [http://codemirror.net/](http://codemirror.net/).
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Active Line Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/xml/xml.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
  .activeline {background: #f0fcff !important;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Active Line Demo</h1>
 
  <form><textarea id="code" name="code">
  <?xml version="1.0" encoding="UTF-8"?>
  <rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"
  xmlns:georss="http://www.georss.org/georss"
  xmlns:twitter="http://api.twitter.com">
  <channel>
  <title>Twitter / codemirror</title>
  <link>http://twitter.com/codemirror</link>
  <atom:link type="application/rss+xml"
  href="http://twitter.com/statuses/user_timeline/242283288.rss" rel="self"/>
  <description>Twitter updates from CodeMirror / codemirror.</description>
  <language>en-us</language>
  <ttl>40</ttl>
  <item>
  <title>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This one
  uses CodeMirror as its editor.</title>
  <description>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This
  one uses CodeMirror as its editor.</description>
  <pubDate>Thu, 17 Mar 2011 23:34:47 +0000</pubDate>
  <guid>http://twitter.com/codemirror/statuses/48527733722058752</guid>
  <link>http://twitter.com/codemirror/statuses/48527733722058752</link>
  <twitter:source>web</twitter:source>
  <twitter:place/>
  </item>
  <item>
  <title>codemirror: Posted a description of the CodeMirror 2 internals at
  http://codemirror.net/2/internals.html</title>
  <description>codemirror: Posted a description of the CodeMirror 2 internals at
  http://codemirror.net/2/internals.html</description>
  <pubDate>Wed, 02 Mar 2011 12:15:09 +0000</pubDate>
  <guid>http://twitter.com/codemirror/statuses/42920879788789760</guid>
  <link>http://twitter.com/codemirror/statuses/42920879788789760</link>
  <twitter:source>web</twitter:source>
  <twitter:place/>
  </item>
  </channel>
  </rss></textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: "application/xml",
  lineNumbers: true,
  onCursorActivity: function() {
  editor.setLineClass(hlLine, null);
  hlLine = editor.setLineClass(editor.getCursor().line, "activeline");
  }
  });
  var hlLine = editor.setLineClass(0, "activeline");
  </script>
 
  <p>Styling the current cursor line.</p>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Mode-Changing Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
  <script src="../mode/scheme/scheme.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border: 1px solid black;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Mode-Changing demo</h1>
 
  <form><textarea id="code" name="code">
  ;; If there is Scheme code in here, the editor will be in Scheme mode.
  ;; If you put in JS instead, it'll switch to JS mode.
 
  (define (double x)
  (* x x))
  </textarea></form>
 
  <p>On changes to the content of the above editor, a (crude) script
  tries to auto-detect the language used, and switches the editor to
  either JavaScript or Scheme mode based on that.</p>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: "scheme",
  lineNumbers: true,
  matchBrackets: true,
  tabMode: "indent",
  onChange: function() {
  clearTimeout(pending);
  setTimeout(update, 400);
  }
  });
  var pending;
  function looksLikeScheme(code) {
  return !/^\s*\(\s*function\b/.test(code) && /^\s*[;\(]/.test(code);
  }
  function update() {
  editor.setOption("mode", looksLikeScheme(editor.getValue()) ? "scheme" : "javascript");
  }
  </script>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Autocomplete Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../lib/util/simple-hint.js"></script>
  <link rel="stylesheet" href="../lib/util/simple-hint.css">
  <script src="../lib/util/javascript-hint.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
  <style type="text/css">.CodeMirror {border: 1px solid #eee;}</style>
  </head>
  <body>
  <h1>CodeMirror: Autocomplete demo</h1>
 
  <form><textarea id="code" name="code">
  function getCompletions(token, context) {
  var found = [], start = token.string;
  function maybeAdd(str) {
  if (str.indexOf(start) == 0) found.push(str);
  }
  function gatherCompletions(obj) {
  if (typeof obj == "string") forEach(stringProps, maybeAdd);
  else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
  else if (obj instanceof Function) forEach(funcProps, maybeAdd);
  for (var name in obj) maybeAdd(name);
  }
 
  if (context) {
  // If this is a property, see if it belongs to some object we can
  // find in the current environment.
  var obj = context.pop(), base;
  if (obj.className == "js-variable")
  base = window[obj.string];
  else if (obj.className == "js-string")
  base = "";
  else if (obj.className == "js-atom")
  base = 1;
  while (base != null && context.length)
  base = base[context.pop().string];
  if (base != null) gatherCompletions(base);
  }
  else {
  // If not, just look in the window object and any local scope
  // (reading into JS mode internals to get at the local variables)
  for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
  gatherCompletions(window);
  forEach(keywords, maybeAdd);
  }
  return found;
  }
  </textarea></form>
 
  <p>Press <strong>ctrl-space</strong> to activate autocompletion. See
  the code (<a href="../lib/util/simple-hint.js">here</a>
  and <a href="../lib/util/javascript-hint.js">here</a>) to figure out
  how it works.</p>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  extraKeys: {"Ctrl-Space": function(cm) {CodeMirror.simpleHint(cm, CodeMirror.javascriptHint);}}
  });
  </script>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Emacs bindings demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/clike/clike.js"></script>
  <script src="../keymap/emacs.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Emacs bindings demo</h1>
 
  <form><textarea id="code" name="code">
  #include "syscalls.h"
  /* getchar: simple buffered version */
  int getchar(void)
  {
  static char buf[BUFSIZ];
  static char *bufp = buf;
  static int n = 0;
  if (n == 0) { /* buffer is empty */
  n = read(0, buf, sizeof buf);
  bufp = buf;
  }
  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
  }
  </textarea></form>
 
  <p>The emacs keybindings are enabled by
  including <a href="../keymap/emacs.js">keymap/emacs.js</a> and setting
  the <code>keyMap</code> option to <code>"emacs"</code>. Because
  CodeMirror's internal API is quite different from Emacs, they are only
  a loose approximation of actual emacs bindings, though.</p>
 
  <p>Also note that a lot of browsers disallow certain keys from being
  captured. For example, Chrome blocks both Ctrl-W and Ctrl-N, with the
  result that idiomatic use of Emacs keys will constantly close your tab
  or open a new window.</p>
 
  <script>
  CodeMirror.commands.save = function() {
  var elt = editor.getWrapperElement();
  elt.style.background = "#def";
  setTimeout(function() { elt.style.background = ""; }, 300);
  };
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  mode: "text/x-csrc",
  keyMap: "emacs"
  });
  </script>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Code Folding Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../lib/util/foldcode.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
  .CodeMirror-gutter {min-width: 2.6em; cursor: pointer;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Code Folding Demo</h1>
 
  <form><div style="max-width: 50em"><textarea id="code" name="code"></textarea></div></form>
 
  <script id="script">
  window.onload = function() {
  var te = document.getElementById("code");
  var sc = document.getElementById("script");
  te.value = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\s*/, "");
 
  var foldFunc = CodeMirror.newFoldFunction(CodeMirror.braceRangeFinder);
  function keyEvent(cm, e) {
  if (e.keyCode == 81 && e.ctrlKey) {
  if (e.type == "keydown") {
  e.stop();
  setTimeout(function() {foldFunc(cm, cm.getCursor().line);}, 50);
  }
  return true;
  }
  }
 
  window.editor = CodeMirror.fromTextArea(te, {
  mode: "javascript",
  lineNumbers: true,
  lineWrapping: true,
  onGutterClick: foldFunc,
  extraKeys: {"Ctrl-Q": function(cm){foldFunc(cm, cm.getCursor().line);}}
  });
 
  foldFunc(editor, 6);
  foldFunc(editor, 16);
  };
  </script>
 
  <p>Demonstration of code folding using the code
  in <a href="../lib/util/foldcode.js"><code>foldcode.js</code></a>.
  Press ctrl-q or click on the gutter to fold a block, again
  to unfold.</p>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Formatting Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../lib/util/formatting.js"></script>
  <script src="../mode/css/css.js"></script>
  <script src="../mode/xml/xml.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
  <script src="../mode/htmlmixed/htmlmixed.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {
  border: 1px solid #eee;
  }
  td {
  padding-right: 20px;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: Formatting demo</h1>
 
  <form><textarea id="code" name="code"><script> function (s,e){ for(var i=0; i < 1; i++) test("test();a=1");} </script>
  <script>
  function test(c){ for (var i = 0; i < 10; i++){ process("a.b();c = null;", 300);}
  }
  </script>
  <table><tr><td>test 1</td></tr><tr><td>test 2</td></tr></table>
  <script> function test() { return 1;} </script>
  <style> .test { font-size: medium; font-family: monospace; }
  </style></textarea></form>
 
  <p>Select a piece of code and click one of the links below to apply automatic formatting to the selected text or comment/uncomment the selected text. Note that the formatting behavior depends on the current block's mode.
  <table>
  <tr>
  <td>
  <a href="javascript:autoFormatSelection()">
  Autoformat Selected
  </a>
  </td>
  <td>
  <a href="javascript:commentSelection(true)">
  Comment Selected
  </a>
  </td>
  <td>
  <a href="javascript:commentSelection(false)">
  Uncomment Selected
  </a>
  </td>
  </tr>
  </table>
  </p>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  mode: "htmlmixed"
  });
  CodeMirror.commands["selectAll"](editor);
 
  function getSelectedRange() {
  return { from: editor.getCursor(true), to: editor.getCursor(false) };
  }
 
  function autoFormatSelection() {
  var range = getSelectedRange();
  editor.autoFormatRange(range.from, range.to);
  }
 
  function commentSelection(isComment) {
  var range = getSelectedRange();
  editor.commentRange(isComment, range.from, range.to);
  }
  </script>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Full Screen Editing</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <link rel="stylesheet" href="../theme/night.css">
  <script src="../mode/xml/xml.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
  .fullscreen {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  margin: 0;
  padding: 0;
  border: 0px solid #BBBBBB;
  opacity: 1;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: Full Screen Editing</h1>
 
  <form><textarea id="code" name="code" rows="5">
  <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
  <dd>Whether, when indenting, the first N*8 spaces should be
  replaced by N tabs. Default is false.</dd>
 
  <dt id="option_tabMode"><code>tabMode (string)</code></dt>
  <dd>Determines what happens when the user presses the tab key.
  Must be one of the following:
  <dl>
  <dt><code>"classic" (the default)</code></dt>
  <dd>When nothing is selected, insert a tab. Otherwise,
  behave like the <code>"shift"</code> mode. (When shift is
  held, this behaves like the <code>"indent"</code> mode.)</dd>
  <dt><code>"shift"</code></dt>
  <dd>Indent all selected lines by
  one <a href="#option_indentUnit"><code>indentUnit</code></a>.
  If shift was held while pressing tab, un-indent all selected
  lines one unit.</dd>
  <dt><code>"indent"</code></dt>
  <dd>Indent the line the 'correctly', based on its syntactic
  context. Only works if the
  mode <a href="#indent">supports</a> it.</dd>
  <dt><code>"default"</code></dt>
  <dd>Do not capture tab presses, let the browser apply its
  default behaviour (which usually means it skips to the next
  control).</dd>
  </dl></dd>
 
  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
  <dd>Determines whether and how new lines are indented when the
  enter key is pressed. The following modes are supported:
  <dl>
  <dt><code>"indent" (the default)</code></dt>
  <dd>Use the mode's indentation rules to give the new line
  the correct indentation.</dd>
  <dt><code>"keep"</code></dt>
  <dd>Indent the line the same as the previous line.</dd>
  <dt><code>"flat"</code></dt>
  <dd>Do not indent the new line.</dd>
  </dl></dd>
 
  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
  <dd>Determines whether and how new lines are indented when the
  enter key is pressed. The following modes are supported:
  <dl>
  <dt><code>"indent" (the default)</code></dt>
  <dd>Use the mode's indentation rules to give the new line
  the correct indentation.</dd>
  <dt><code>"keep"</code></dt>
  <dd>Indent the line the same as the previous line.</dd>
  <dt><code>"flat"</code></dt>
  <dd>Do not indent the new line.</dd>
  </dl></dd>
 
  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
  <dd>Determines whether and how new lines are indented when the
  enter key is pressed. The following modes are supported:
  <dl>
  <dt><code>"indent" (the default)</code></dt>
  <dd>Use the mode's indentation rules to give the new line
  the correct indentation.</dd>
  <dt><code>"keep"</code></dt>
  <dd>Indent the line the same as the previous line.</dd>
  <dt><code>"flat"</code></dt>
  <dd>Do not indent the new line.</dd>
  </dl></dd>
 
  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
  <dd>Determines whether and how new lines are indented when the
  enter key is pressed. The following modes are supported:
  <dl>
  <dt><code>"indent" (the default)</code></dt>
  <dd>Use the mode's indentation rules to give the new line
  the correct indentation.</dd>
  <dt><code>"keep"</code></dt>
  <dd>Indent the line the same as the previous line.</dd>
  <dt><code>"flat"</code></dt>
  <dd>Do not indent the new line.</dd>
  </dl></dd>
 
  </textarea></form>
  <script>
 
  (function () {
 
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  theme: "night",
  extraKeys: {"F11": toggleFullscreenEditing, "Esc": toggleFullscreenEditing}
  });
 
  function toggleFullscreenEditing()
  {
  var editorDiv = $('.CodeMirror-scroll');
  if (!editorDiv.hasClass('fullscreen')) {
  toggleFullscreenEditing.beforeFullscreen = { height: editorDiv.height(), width: editorDiv.width() }
  editorDiv.addClass('fullscreen');
  editorDiv.height('100%');
  editorDiv.width('100%');
  editor.refresh();
  }
  else {
  editorDiv.removeClass('fullscreen');
  editorDiv.height(toggleFullscreenEditing.beforeFullscreen.height);
  editorDiv.width(toggleFullscreenEditing.beforeFullscreen.width);
  editor.refresh();
  }
  }
 
  })();
  </script>
 
  <p>Press <strong>F11</strong> (or <strong>ESC</strong> in Safari on Mac OS X) when cursor is in the editor to toggle full screen editing.</p>
 
  <p><strong>Note:</strong> Does not currently work correctly in IE
  6 and 7, where setting the height of something
  to <code>100%</code> doesn't make it full-screen.</p>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Breakpoint Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror-gutter {
  width: 3em;
  background: white;
  }
  .CodeMirror {
  border: 1px solid #aaa;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: Breakpoint demo</h1>
 
  <form><textarea id="code" name="code">
  CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  onGutterClick: function(cm, n) {
  var info = cm.lineInfo(n);
  if (info.markerText)
  cm.clearMarker(n);
  else
  cm.setMarker(n, "<span style=\"color: #900\">●</span> %N%");
  }
  });
  </textarea></form>
 
  <p>Click the line-number gutter to add or remove 'breakpoints'.</p>
 
  <script>
  CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  onGutterClick: function(cm, n) {
  var info = cm.lineInfo(n);
  if (info.markerText)
  cm.clearMarker(n);
  else
  cm.setMarker(n, "<span style=\"color: #900\">●</span> %N%");
  }
  });
  </script>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Overlay Parser Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../lib/util/overlay.js"></script>
  <script src="../mode/xml/xml.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border: 1px solid black;}
  .cm-mustache {color: #0ca;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Overlay Parser Demo</h1>
 
  <form><textarea id="code" name="code">
  <html>
  <body>
  <h1>{{title}}</h1>
  <p>These are links to {{things}}:</p>
  <ul>{{#links}}
  <li><a href="{{url}}">{{text}}</a></li>
  {{/links}}</ul>
  </body>
  </html>
  </textarea></form>
 
  <script>
  CodeMirror.defineMode("mustache", function(config, parserConfig) {
  var mustacheOverlay = {
  token: function(stream, state) {
  if (stream.match("{{")) {
  while ((ch = stream.next()) != null)
  if (ch == "}" && stream.next() == "}") break;
  return "mustache";
  }
  while (stream.next() != null && !stream.match("{{", false)) {}
  return null;
  }
  };
  return CodeMirror.overlayParser(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mustacheOverlay);
  });
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "mustache"});
  </script>
 
  <p>Demonstration of a mode that parses HTML, highlighting
  the <a href="http://mustache.github.com/">Mustache</a> templating
  directives inside of it by using the code
  in <a href="../lib/util/overlay.js"><code>overlay.js</code></a>. View
  source to see the 15 lines of code needed to accomplish this.</p>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: HTML5 preview</title>
  <meta charset=utf-8>
  <script src=../lib/codemirror.js></script>
  <script src=../mode/xml/xml.js></script>
  <script src=../mode/javascript/javascript.js></script>
  <script src=../mode/css/css.js></script>
  <script src=../mode/htmlmixed/htmlmixed.js></script>
  <link rel=stylesheet href=../lib/codemirror.css>
  <link rel=stylesheet href=../doc/docs.css>
  <style type=text/css>
  .CodeMirror {
  float: left;
  width: 50%;
  border: 1px solid black;
  }
  iframe {
  width: 49%;
  float: left;
  height: 300px;
  border: 1px solid black;
  border-left: 0px;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: HTML5 preview</h1>
  <textarea id=code name=code>
  <!doctype html>
  <html>
  <head>
  <meta charset=utf-8>
  <title>HTML5 canvas demo</title>
  <style>p {font-family: monospace;}</style>
  </head>
  <body>
  <p>Canvas pane goes here:</p>
  <canvas id=pane width=300 height=200></canvas>
  <script>
  var canvas = document.getElementById('pane');
  var context = canvas.getContext('2d');
 
  context.fillStyle = 'rgb(250,0,0)';
  context.fillRect(10, 10, 55, 50);
 
  context.fillStyle = 'rgba(0, 0, 250, 0.5)';
  context.fillRect(30, 30, 55, 50);
  </script>
  </body>
  </html></textarea>
  <iframe id=preview></iframe>
  <script>
  var delay;
  // Initialize CodeMirror editor with a nice html5 canvas demo.
  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
  mode: 'text/html',
  tabMode: 'indent',
  onChange: function() {
  clearTimeout(delay);
  delay = setTimeout(updatePreview, 300);
  }
  });
 
  function updatePreview() {
  var previewFrame = document.getElementById('preview');
  var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
  preview.open();
  preview.write(editor.getValue());
  preview.close();
  }
  setTimeout(updatePreview, 300);
  </script>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Autoresize Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/css/css.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {
  border: 1px solid #eee;
  }
  .CodeMirror-scroll {
  height: auto;
  overflow-y: hidden;
  overflow-x: auto;
  width: 100%;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: Autoresize demo</h1>
 
  <form><textarea id="code" name="code">
  .CodeMirror-scroll {
  height: auto;
  overflow-y: hidden;
  overflow-x: auto;
  width: 100%
  }</textarea></form>
 
  <p>By setting a few CSS properties, CodeMirror can be made to
  automatically resize to fit its content.</p>
 
  <script>
  CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true
  });
  </script>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Mode Runner Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../lib/util/runmode.js"></script>
  <script src="../mode/xml/xml.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Mode Runner Demo</h1>
 
  <textarea id="code" style="width: 90%; height: 7em; border: 1px solid black; padding: .2em .4em;">
  <foobar>
  <blah>Enter your xml here and press the button below to display
  it as highlighted by the CodeMirror XML mode</blah>
  <tag2 foo="2" bar="&amp;quot;bar&amp;quot;"/>
  </foobar></textarea><br>
  <button onclick="doHighlight();">Highlight!</button>
  <pre id="output" class="cm-s-default"></pre>
 
  <script>
  function doHighlight() {
  CodeMirror.runMode(document.getElementById("code").value, "application/xml",
  document.getElementById("output"));
  }
  </script>
 
  <p>Running a CodeMirror mode outside of the editor.
  The <code>CodeMirror.runMode</code> function, defined
  in <code><a href="../lib/util/runmode.js">lib/runmode.js</a></code> takes the following arguments:</p>
 
  <dl>
  <dt><code>text (string)</code></dt>
  <dd>The document to run through the highlighter.</dd>
  <dt><code>mode (<a href="../doc/manual.html#option_mode">mode spec</a>)</code></dt>
  <dd>The mode to use (must be loaded as normal).</dd>
  <dt><code>output (function or DOM node)</code></dt>
  <dd>If this is a function, it will be called for each token with
  two arguments, the token's text and the token's style class (may
  be <code>null</code> for unstyled tokens). If it is a DOM node,
  the tokens will be converted to <code>span</code> elements as in
  an editor, and inserted into the node
  (through <code>innerHTML</code>).</dd>
  </dl>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Search/Replace Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/xml/xml.js"></script>
  <script src="../lib/util/dialog.js"></script>
  <link rel="stylesheet" href="../lib/util/dialog.css">
  <script src="../lib/util/searchcursor.js"></script>
  <script src="../lib/util/search.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
  dt {font-family: monospace; color: #666;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Search/Replace Demo</h1>
 
  <form><textarea id="code" name="code">
  <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
  <dd>Whether, when indenting, the first N*8 spaces should be
  replaced by N tabs. Default is false.</dd>
 
  <dt id="option_tabMode"><code>tabMode (string)</code></dt>
  <dd>Determines what happens when the user presses the tab key.
  Must be one of the following:
  <dl>
  <dt><code>"classic" (the default)</code></dt>
  <dd>When nothing is selected, insert a tab. Otherwise,
  behave like the <code>"shift"</code> mode. (When shift is
  held, this behaves like the <code>"indent"</code> mode.)</dd>
  <dt><code>"shift"</code></dt>
  <dd>Indent all selected lines by
  one <a href="#option_indentUnit"><code>indentUnit</code></a>.
  If shift was held while pressing tab, un-indent all selected
  lines one unit.</dd>
  <dt><code>"indent"</code></dt>
  <dd>Indent the line the 'correctly', based on its syntactic
  context. Only works if the
  mode <a href="#indent">supports</a> it.</dd>
  <dt><code>"default"</code></dt>
  <dd>Do not capture tab presses, let the browser apply its
  default behaviour (which usually means it skips to the next
  control).</dd>
  </dl></dd>
 
  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
  <dd>Determines whether and how new lines are indented when the
  enter key is pressed. The following modes are supported:
  <dl>
  <dt><code>"indent" (the default)</code></dt>
  <dd>Use the mode's indentation rules to give the new line
  the correct indentation.</dd>
  <dt><code>"keep"</code></dt>
  <dd>Indent the line the same as the previous line.</dd>
  <dt><code>"flat"</code></dt>
  <dd>Do not indent the new line.</dd>
  </dl></dd>
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", lineNumbers: true});
  </script>
 
  <p>Demonstration of primitive search/replace functionality. The
  keybindings (which can be overridden by custom keymaps) are:</p>
  <dl>
  <dt>Ctrl-F / Cmd-F</dt><dd>Start searching</dd>
  <dt>Ctrl-G / Cmd-G</dt><dd>Find next</dd>
  <dt>Shift-Ctrl-G / Shift-Cmd-G</dt><dd>Find previous</dd>
  <dt>Shift-Ctrl-F / Cmd-Option-F</dt><dd>Replace</dd>
  <dt>Shift-Ctrl-R / Shift-Cmd-Option-F</dt><dd>Replace all</dd>
  </dl>
  <p>Searching is enabled by
  including <a href="../lib/util/search.js">lib/util/search.js</a>.
  For good-looking input dialogs, you also want to include
  <a href="../lib/util/dialog.js">lib/util/dialog.js</a>
  and <a href="../lib/util/dialog.css">lib/util/dialog.css</a>.</p>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Theme Demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <link rel="stylesheet" href="../theme/neat.css">
  <link rel="stylesheet" href="../theme/elegant.css">
  <link rel="stylesheet" href="../theme/night.css">
  <link rel="stylesheet" href="../theme/monokai.css">
  <link rel="stylesheet" href="../theme/cobalt.css">
  <link rel="stylesheet" href="../theme/eclipse.css">
  <link rel="stylesheet" href="../theme/rubyblue.css">
  <script src="../mode/javascript/javascript.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border: 1px solid black;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Theme demo</h1>
 
  <form><textarea id="code" name="code">
  function findSequence(goal) {
  function find(start, history) {
  if (start == goal)
  return history;
  else if (start > goal)
  return null;
  else
  return find(start + 5, "(" + history + " + 5)") ||
  find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
  }</textarea></form>
 
  <p>Select a theme: <select onchange="selectTheme(this)">
  <option selected>default</option>
  <option>night</option>
  <option>monokai</option>
  <option>neat</option>
  <option>elegant</option>
  <option>cobalt</option>
  <option>eclipse</option>
  <option>rubyblue</option>
  </select>
  </p>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true
  });
  function selectTheme(node) {
  var theme = node.options[node.selectedIndex].innerHTML;
  editor.setOption("theme", theme);
  }
  </script>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Vim bindings demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/clike/clike.js"></script>
  <script src="../keymap/vim.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Vim bindings demo</h1>
 
  <form><textarea id="code" name="code">
  #include "syscalls.h"
  /* getchar: simple buffered version */
  int getchar(void)
  {
  static char buf[BUFSIZ];
  static char *bufp = buf;
  static int n = 0;
  if (n == 0) { /* buffer is empty */
  n = read(0, buf, sizeof buf);
  bufp = buf;
  }
  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
  }
  </textarea></form>
 
  <p>The vim keybindings are enabled by
  including <a href="../keymap/vim.js">keymap/vim.js</a> and setting
  the <code>keyMap</code> option to <code>"vim"</code>. Because
  CodeMirror's internal API is quite different from Vim, they are only
  a loose approximation of actual vim bindings, though.</p>
 
  <script>
  CodeMirror.commands.save = function(){alert("Saving");};
  CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  mode: "text/x-csrc",
  keyMap: "vim"
  });
  </script>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Visible tabs demo</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/clike/clike.js"></script>
  <link rel="stylesheet" href="../doc/docs.css">
 
  <style type="text/css">
  .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
  .cm-tab:after {
  content: "\21e5";
  display: -moz-inline-block;
  display: -webkit-inline-block;
  display: inline-block;
  width: 0px;
  position: relative;
  overflow: visible;
  left: -1.4em;
  color: #aaa;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: Visible tabs demo</h1>
 
  <form><textarea id="code" name="code">
  #include "syscalls.h"
  /* getchar: simple buffered version */
  int getchar(void)
  {
  static char buf[BUFSIZ];
  static char *bufp = buf;
  static int n = 0;
  if (n == 0) { /* buffer is empty */
  n = read(0, buf, sizeof buf);
  bufp = buf;
  }
  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
  }
  </textarea></form>
 
  <p>Tabs inside the editor are spans with the
  class <code>cm-tab</code>, and can be styled. This demo uses
  an <code>:after</code> pseudo-class CSS hack that will not work on old
  browsers. You can use a more conservative technique like a background
  image as an alternative.</p>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  tabSize: 4,
  indentUnit: 4,
  indentWithTabs: true,
  mode: "text/x-csrc"
  });
  </script>
 
  </body>
  </html>
 
 Binary files /dev/null and b/js/flotr2/examples/lib/codemirror/doc/baboon.png differ
  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  <!-- Created with Inkscape (http://www.inkscape.org/) -->
 
  <svg
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:cc="http://creativecommons.org/ns#"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:svg="http://www.w3.org/2000/svg"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
  xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
  id="svg3181"
  version="1.1"
  inkscape:version="0.48.0 r9654"
  width="1750"
  height="960"
  xml:space="preserve"
  sodipodi:docname="baboon_vector.svg"><metadata
  id="metadata3187"><rdf:RDF><cc:Work
  rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
  rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
  id="defs3185"><clipPath
  clipPathUnits="userSpaceOnUse"
  id="clipPath3195"><path
  d="M 0,768 1400,768 1400,0 0,0 0,768 z"
  id="path3197" /></clipPath><clipPath
  clipPathUnits="userSpaceOnUse"
  id="clipPath3215"><path
  d="M 0,768 1400,768 1400,0 0,0 0,768 z"
  id="path3217" /></clipPath></defs><sodipodi:namedview
  pagecolor="#ffffff"
  bordercolor="#666666"
  borderopacity="1"
  objecttolerance="10"
  gridtolerance="10"
  guidetolerance="10"
  inkscape:pageopacity="0"
  inkscape:pageshadow="2"
  inkscape:window-width="1440"
  inkscape:window-height="851"
  id="namedview3183"
  showgrid="false"
  inkscape:zoom="0.20550291"
  inkscape:cx="1534.1667"
  inkscape:cy="795.78156"
  inkscape:window-x="0"
  inkscape:window-y="0"
  inkscape:window-maximized="1"
  inkscape:current-layer="g3189" /><g
  id="g3189"
  inkscape:groupmode="layer"
  inkscape:label="baboon_vector"
  transform="matrix(1.25,0,0,-1.25,0,960)"><g
  id="g3191"><g
  id="g3193"
  clip-path="url(#clipPath3195)"><g
  id="g3199"
  transform="translate(458.9561,569.9678)"><path
  d="m 0,0 59.835,69.355 87.034,26.518 133.949,-7.479 c 0,0 74.116,-32.639 74.795,-34.678 0.68,-2.04 84.314,-59.155 84.314,-59.155 l 12.238,-74.795 5.439,-97.912 -13.598,-25.159 -4.76,-40.797 -18.358,-23.118 24.39,-5.561 0.501,-5.192 -14.012,-60.641 16.477,-93.368 7.223,-49.972 -208.295,-51.754 -18.552,4.005 -37.468,8.325 -10.036,4.036 -66.885,10.101 c 0,0 -14.959,74.793 -16.999,73.433 -2.039,-1.359 -42.836,56.437 -42.836,56.437 l -19.719,65.274 12.48,74.571 -7.961,9.643 -26.479,16.187 -12.716,38.309 4.08,48.277 8.769,38.985 L 6.608,-74.308 0,0 z"
  style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3201" /></g><g
  id="g3203"
  transform="translate(78.8657,682.1582)"><path
  d="M 0,0 142.789,40.797 259.74,52.355 313.457,-232.543 204.665,-291.698 78.194,-293.738 0,0 z"
  style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3205" /></g><g
  id="g3207"
  transform="translate(269.5122,345.2344)"><path
  d="M 0,0 18.801,-74.425 40.728,-85.408 59.539,-59.541 40.259,13.503 36.821,15.669 0,0 z"
  style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3209" /></g></g></g><g
  id="g3223"
  transform="translate(741.918,109.0332)"><path
  d="m 0,0 -17.236,-9.401 -16.452,-22.721 -0.783,12.537 6.268,17.234 13.317,6.268 L 0,7.833 14.884,3.917 0,0 z m 172.622,-21.824 c -0.031,0.271 -0.081,0.535 -0.117,0.804 -20.85,7.653 -49.59,7.327 -66.874,10.927 -13.849,2.886 -23.047,9.119 -27.032,12.298 -9.863,-8.494 -12.025,-14.377 -12.025,-14.377 0,0 -9.816,15.309 -30.17,25.76 -7.05,3.621 -17.767,5.691 -29.341,5.691 -24.297,0 -52.384,-9.155 -58.339,-32.223 -10.458,-40.511 9.697,-76.594 49.814,-77.623 1.325,-0.034 2.623,-0.12 3.894,-0.12 36.131,0 48.855,8.572 58.323,15.478 0.027,0.021 0.104,0 0.104,0 0,0 25.126,-11.506 53.529,-11.506 4.419,0 9.156,0.415 14.249,1.063 31.641,4.018 47.989,28.124 43.985,63.828"
  style="fill:#df0019;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3225"
  inkscape:connector-curvature="0" /></g><g
  id="g3227"
  transform="translate(300.8481,270.0254)"><path
  d="m 0,0 c -3.063,-0.691 -12.535,0.784 -12.535,0.784 l 6.267,-25.853 43.481,13.319 -9.01,27.418 C 28.203,15.668 7.867,1.777 0,0"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3229"
  inkscape:connector-curvature="0" /></g><g
  id="g3231"
  transform="translate(211.66052,615.85984)"><path
  d="m 0,0 -16.243,-2.871 -15.462,-9.4 4.323,-10.938 14.568,9.89 L 2.75,-8.771 0,0 z"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3233"
  inkscape:connector-curvature="0" /></g><g
  id="g3235"
  transform="translate(274.15732,626.4084)"><path
  d="m 0,0 -15.64,0.407 -14.279,-3.608 2.008,-9.747 14.756,4.208 L 1.111,-8.215 0,0 z"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3237"
  inkscape:connector-curvature="0" /></g><path
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="M 436.65625 22.28125 C 436.65625 22.28125 338.18375 25.385 251 42.8125 C 163.24875 60.35375 70.40625 99.65625 70.40625 99.65625 L 175.1875 495.28125 L 327.96875 492.34375 L 337.75 527.59375 C 337.75 527.59375 365.095 523.25875 373 518.78125 C 376.31375 516.90375 383.78125 508 383.78125 508 L 377.75 484.65625 L 504.21875 407.15625 L 436.65625 22.28125 z M 410.53125 55.1875 L 465.6875 393.3125 L 346.59375 456.625 L 202.75 466.46875 L 112 114.40625 L 263 79.1875 L 410.53125 55.1875 z "
  transform="matrix(0.8,0,0,-0.8,0,768)"
  id="path3253" /><g
  id="g3247"
  transform="matrix(1.199238,-0.02879331,0.02673084,1.0520756,172.41935,498.37339)"><path
  d="m 0,0 c 0,0 -1.861,1.481 -9.143,-1.457 9.712,18.867 9.439,39.989 9.439,39.989 0,0 -3.106,-2.465 -11.311,-8.47 9.241,23.044 5.338,72.525 5.338,72.525 0,0 -17.493,40.746 -13.657,45.799 8.841,11.65 23.834,23.968 44.295,25.594 17.935,1.424 44.606,-4.953 55.865,-15.284 4.536,-4.161 23.367,-47.493 23.367,-47.493 0,0 6.104,-35.271 11.619,-54.108 5.513,-18.839 11.054,-26.674 21.284,-34.825 17.831,-14.207 27.076,-29.938 27.076,-29.938 L 143.399,3.945 c 3.655,-17.356 14.875,-34.28 27.39,-47.672 -12.863,1.507 -19.61,8.783 -19.61,8.783 0,0 2.151,-12.664 9.109,-26.554 l 28.712,15.264 -1.762,10.805 c -5.128,9.304 -9.336,15.534 -9.336,15.534 0,0 2.089,0.956 7.385,-3.572 l -2.005,12.296 c -4.814,9.391 -11.773,16.752 -25.115,31.113 5.944,-6.087 15.438,-5.379 20.751,-4.356 l -0.572,3.512 c -2.231,1.278 -5.494,3.171 -10.241,5.957 -12.43,7.299 -22.326,21.049 -22.326,21.049 0,0 12.85,1.815 20.513,11.022 -7.316,-2.641 -18.585,0.799 -18.585,0.799 -17.086,6.772 -15.022,30.217 -17.687,50.587 -2.667,20.37 -9.299,34.125 -9.299,34.125 0,0 -0.243,2.149 11.91,-5.906 -7.744,33.215 -35.545,44.94 -35.545,44.94 0,0 2.223,2.79 22.843,0.044 -16.469,15.817 -32.303,16.896 -32.303,16.896 0,0 10.077,2.25 23.611,0.24 0,0 -3.327,3.508 -7.549,6.453 L 35.985,194.291 -77.543,167.815 -8.211,-101.17 17.481,-99.413 C 8.602,-85.114 -0.371,-63.837 -2.15,-40.857 -4.911,-5.208 0,0 0,0"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3249"
  inkscape:connector-curvature="0" /></g><g
  id="g3255"
  transform="translate(204.22134,580.88353)"><path
  d="m 0,0 c 0,-1.418 0.43,-2.736 1.168,-3.83 1.523,0.677 3.551,1.094 5.786,1.094 2.164,0 4.133,-0.39 5.639,-1.029 0.711,1.081 1.129,2.374 1.129,3.765 0,3.79 -3.072,6.861 -6.861,6.861 C 3.071,6.861 0,3.79 0,0"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3257"
  inkscape:connector-curvature="0" /></g><g
  id="g3259"
  transform="translate(256.3311,595.31646)"><path
  d="m 0,0 c 0,-1.418 0.43,-2.736 1.168,-3.83 1.524,0.677 3.552,1.094 5.787,1.094 2.163,0 4.132,-0.39 5.638,-1.029 0.712,1.081 1.129,2.373 1.129,3.765 0,3.79 -3.072,6.861 -6.861,6.861 C 3.071,6.861 0,3.79 0,0"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3261"
  inkscape:connector-curvature="0" /></g><g
  id="g4174"
  transform="matrix(0.99694509,0.07810563,-0.07810563,0.99694509,47.348748,-15.348299)"><g
  transform="translate(222.5098,610.1558)"
  id="g3219"><path
  inkscape:connector-curvature="0"
  id="path3221"
  style="fill:#df0019;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="m 0,0 4.45,2.752 5.34,3.785 7.05,-8.226 7.093,-33.359 17.801,-51.259 13.86,-30.215 26.261,-1.55 -6.685,-35.653 c 0,0 -49.98,-21.871 -49.545,-21.911 -42.657,4.001 -12.553,43.066 -8.631,47.301 L 3.666,-47.869 0,0 z" /></g><g
  transform="translate(247.626,467.3545)"
  id="g3239"><path
  inkscape:connector-curvature="0"
  id="path3241"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="M 0,0 C -3.044,-0.345 -5.232,-3.092 -4.888,-6.136 -4.543,-9.18 1.576,-2.254 13.308,-4.961 13.971,-1.97 3.044,0.344 0,0" /></g><g
  transform="translate(279.4419,476.5762)"
  id="g3243"><path
  inkscape:connector-curvature="0"
  id="path3245"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="M 0,0 C 3.271,1.08 6.798,-0.697 7.88,-3.969 8.96,-7.24 -0.55,-3.044 -11.258,-11.329 -13.345,-8.586 -3.272,-1.081 0,0" /></g><g
  transform="translate(284.1929,525.9082)"
  id="g3263"><path
  inkscape:connector-curvature="0"
  id="path3265"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="M 0,0 C 0,0 -6.972,28.671 -6.972,29.355 L 1.585,2.864 9.999,-10.564 13.634,-32.697 7.922,-11.098 0,0 z M -0.633,-15.036 -9.19,-4.86 -16.478,25.776 c -0.202,0.684 9.106,-28.811 9.106,-28.811 l 8.64,-11.642 2.469,-17.336 -4.37,16.977 z m -6.339,-6.085 -10.457,16.826 -5.444,28.646 6.614,-27.842 11.311,-18.026 1.413,-9.583 -3.437,9.979 z m -53.462,-13.246 -1.437,24.944 -2.682,28.754 5.106,-29.895 1.212,-21.677 4.139,-18.236 -6.338,16.11 z m -4.265,-19.55 -6.665,15.516 0.404,29.205 -0.882,28.169 3.104,-28.396 0.808,-26.697 4.242,-15.972 2.423,-6.617 -3.434,4.792 z m -9.695,-2.967 -7.117,16.885 1.318,32.01 0,25.223 2.115,-25.061 -0.581,-31.259 5.869,-16.429 5.056,-8.671 -6.66,7.302 z m 103.144,-7.97 -6.676,20.38 2.141,11.54 L 16.499,-9.376 4.557,13.104 -5.879,53.97 c 0,0 -8.325,-7.41 -16.781,-8.08 -8.455,-0.671 -15.09,4.018 -15.09,4.018 0,0 3.592,-17.761 8.659,-37.597 5.069,-19.836 17.528,-44.866 17.528,-44.866 0,0 21.578,-8.197 24.302,-16.587 2.724,-8.391 -3.508,-22.911 -14.102,-26.551 -10.593,-3.64 -32.284,-8.262 -32.284,-8.262 0,0 -19,1.512 -20.438,14.26 0,0 4.131,16.406 10.418,19.225 6.285,2.819 21.362,11.174 21.362,11.174 l -8.254,1.332 -7.664,-1.332 c 0,0 -4.784,11.295 -10.973,35.086 -6.19,23.79 -8.967,42.485 -8.967,42.485 0,0 -3.912,-4.391 -14.199,-4.885 -10.286,-0.494 -16.031,7.988 -16.031,7.988 l 1.027,-30.185 -1.049,-25.83 -0.15,-29.22 5.102,-15.99 19.818,-30.448 c 0,0 14.102,-9.293 31.728,-9.293 16.453,1.328 51.131,18.047 51.131,18.047 l 9.536,16.687 z" /></g></g><g
  id="g3267"
  transform="translate(847.2637,321.5059)"><path
  d="m 0,0 c 2.252,3.516 6.693,15.3 6.693,15.3 0,0 3.778,-13.306 1.912,-17.213 -3.056,-6.404 -23.905,-15.3 -23.905,-15.3 0,0 12.196,12.364 15.3,17.213 m -33.514,23.16 -0.757,56.352 c 0,0 11.136,-14.028 11.843,-19.739 1.176,-9.491 -11.086,-36.613 -11.086,-36.613 m -17.575,236.921 c 0,0 12.453,-15.338 14.854,-21.39 1.424,-3.591 2.286,-15.287 2.286,-15.287 l -17.14,36.677 z M -98.574,-86.136 c -9.757,-0.906 -29.836,1.016 -38.912,4.708 -7.499,3.05 -25.734,19.656 -25.734,19.656 l 24.187,-10.86 -4.701,17.627 15.272,-22.009 41.813,-5.356 c 0,0 -8.812,-3.477 -11.925,-3.766 m -74.428,157.941 c -4.518,10.057 -1.763,44.065 -1.763,44.065 0,0 7.544,-31.093 12.338,-40.541 6.978,-13.754 37.015,-49.352 37.015,-49.352 0,0 -40.824,30.759 -47.59,45.828 m -17.833,-149.47 -40.407,24.724 1.636,-17.575 0.026,-0.035 -5.178,-29.811 -2.056,-10.701 0.383,-33.34 -4.982,36.406 6.41,41.45 -11.063,8.338 -17.532,43.159 23.502,-38.779 2.351,14.101 40.634,-25.695 11.924,-5.651 13.809,-28.871 -19.457,22.28 z m -85.522,138.863 17.212,-34.424 c 0,0 -12.972,11.185 -15.299,16.257 -1.905,4.152 -1.913,18.167 -1.913,18.167 m -2.367,66.042 c 0,0 -6.206,15.581 -6.323,21.082 -0.168,7.817 4.568,23.148 7.695,30.315 0.755,1.73 4.103,6.341 4.103,6.341 0,0 -4.654,-24.542 -5.347,-32.829 -0.518,-6.205 -0.128,-24.909 -0.128,-24.909 m -7.195,-114.809 c -0.334,3.363 1.912,13.387 1.912,13.387 l 3.825,-29.643 c 0,0 -5.313,11.967 -5.737,16.256 m -20.082,53.549 c -1.394,3.571 -0.956,15.301 -0.956,15.301 l 13.388,-30.6 c 0,0 -10.639,10.71 -12.432,15.299 m -6.03,106.795 c 0,0 -0.315,35.831 4.637,46.379 4.531,9.647 29.936,30.356 29.936,30.356 0,0 -17.824,-22.47 -21.503,-31.2 -5.089,-12.077 -10.119,-51.437 -10.119,-51.437 l -2.951,5.902 z M 50.121,205.01 c 3.335,-9.155 1.168,-38.956 1.168,-38.956 0,0 -5.451,29.987 -9.221,39.366 -4.214,10.487 -23.014,38.907 -23.014,38.907 0,0 26.78,-27.546 31.067,-39.317 M 54.506,95.624 c 0,0 6.884,-18.586 5.738,-24.861 -0.773,-4.241 -9.562,-14.345 -9.562,-14.345 0,0 2.414,12.874 2.868,17.212 0.573,5.474 0.956,21.994 0.956,21.994 M 19.125,-13.389 c 0,0 9.656,22.183 11.062,30.068 1.235,6.941 0,28.203 0,28.203 0,0 8.477,-22.819 7.106,-30.538 C 35.845,6.183 19.125,-13.389 19.125,-13.389 m 441.487,-40.965 c -3.249,8.935 -6.587,17.23 -10.01,24.928 l -1.862,28.873 -8.857,-4.876 -25.862,49.457 -4.828,-10.34 c -32.69,31.48 -70.457,34.284 -111.982,31.646 -65.568,-4.163 -91.587,-41.63 -79.098,-57.241 12.49,-15.613 18.733,-5.205 40.589,5.203 21.858,10.407 74.937,26.017 110.323,-2.082 35.386,-28.1 86.383,-109.281 50.997,-169.646 -35.386,-60.365 -105.626,-105.385 -182.135,-88.465 -86.422,19.112 -126.078,60.082 -177.675,74.811 -8.311,1.334 -18.347,2.789 -24.791,3.191 -12.671,0.792 -21.6,14.727 -21.6,14.727 l 17.181,-9.327 25.763,-2.36 c 2.331,14 9.395,49.054 9.395,49.054 l -8.688,87.29 -18.668,-27.06 -7.246,10.184 -21.349,-22.915 -15.473,-1.959 14.67,6.596 21.38,29.409 6.7,-13.754 19.485,24.691 0.004,-0.011 16.47,9.525 -3.123,68.69 10.407,-10.407 -4.163,40.59 22.173,71.502 -34.662,91.899 16.652,-4.162 -19.773,35.386 -40.591,38.509 9.368,17.693 -93.671,9.368 -20.229,-7.165 -18.437,38.292 13.22,8.813 -69.039,14.69 2.938,19.095 -80.791,-23.303 -26.147,-19.191 -116.339,0 8.814,-10.188 -42.501,-40.641 -8.911,-78.491 7.344,-1.494 8.814,-45.548 23.502,-24.978 19.096,45.533 -14.689,-4.409 41.13,48.474 30.848,26.44 -14.69,-1.469 19.096,16.158 105.763,2.938 72.917,15.799 -41.623,-14.742 -30.181,-7.285 -104.079,-1.043 1.04,-11.449 -64.526,-61.403 14.571,2.081 -27.844,-63.28 c -15.017,-13.719 -28.06,-55.016 -36.687,-75.145 -9.367,-21.856 -20.816,-39.55 -20.816,-39.55 0,0 -30.182,-6.244 -61.405,-18.734 -31.224,-12.489 -43.713,4.163 -43.713,4.163 l -3.122,-8.326 c 0,0 -18.28,-9.057 -39.303,-11.825 -16.43,-2.162 -9.967,-20.946 -9.613,-26.684 0.405,-6.57 4.294,-19.774 8.325,-24.978 3.227,-4.165 12.525,-10.425 17.694,-11.448 12.039,-2.385 28.101,5.204 45.794,17.693 74.936,-6.245 103.241,-10.321 126.974,8.326 14.572,11.448 29.142,22.897 41.631,40.59 l -15.611,42.671 -8.327,-14.569 -5.807,44.931 1.841,17.863 5.547,-51.234 7.789,9.257 35.387,-70.772 11.448,4.164 c 0,0 13.515,-18.583 23.057,-32.881 l -26.02,25.006 -10.224,-5.964 -11.076,22.152 c 0,0 -13.383,-2.353 -24.727,-18.027 -15.862,-21.915 -23.503,-24.678 -17.627,-78.735 5.876,-54.055 16.452,-54.055 64.632,-121.039 11.752,-16.452 14.601,-18.465 14.601,-18.465 l -51.03,-27.365 -22.327,-5.876 -21.384,-11.28 c 0,0 4.744,-8.174 7.495,-9.369 4.739,-2.062 20.613,1.56 20.613,1.56 0,0 15.603,-6.763 36.756,-6.763 21.152,0 32.903,8.225 47.005,8.225 14.101,0 38.78,-8.225 57.582,-5.876 18.802,2.351 22.328,12.927 22.328,12.927 l -51.706,54.057 -4.675,47.096 -56.605,75.769 -3.038,9.437 65.791,-82.24 5.107,-46.75 55.161,-61.405 37.468,-8.325 c 0,0 -0.257,1.226 -0.625,3.114 -6.146,15.664 -6.986,34.894 -1.999,54.214 6.975,27.012 38.85,36.596 64.029,36.596 12.506,0 24.179,-2.312 32.025,-6.341 12.912,-6.63 21.851,-15.076 27.029,-20.917 3.673,4.516 7.133,7.194 11.833,11.11 0,0 12.143,-11.751 45.047,-14.101 27.14,-1.939 45.048,-8.226 70.901,-19.585 53.676,-23.584 102.5,-61.785 207.618,-45.132 105.119,16.651 206.073,113.444 164.442,227.929"
  style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
  id="path3269"
  inkscape:connector-curvature="0" /></g><path
  inkscape:connector-curvature="0"
  style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
  d="m 329.26398,723.3082 -118.025,-19.2 -120.800003,-28.175 72.600003,-281.65 115.075,7.875 95.275,50.65 -44.125,270.5 z m -6.55,-10.575 40.675,-252.4 -87.85,-47.275 -106.125,-7.325 -66.95,262.8 111.4,26.275 108.85,17.925 z"
  id="path3253-3" /></g></svg>
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Compression Helper</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* Script compression
  helper */
  </pre>
 
  <p>To optimize loading CodeMirror, especially when including a
  bunch of different modes, it is recommended that you combine and
  minify (and preferably also gzip) the scripts. This page makes
  those first two steps very easy. Simply select the version and
  scripts you need in the form below, and
  click <strong>Compress</strong> to download the minified script
  file.</p>
 
  <form id="form" action="http://marijnhaverbeke.nl/uglifyjs" method="post">
  <input type="hidden" id="download" name="download" value="codemirror-compressed.js"/>
  <p>Version: <select id="version" onchange="setVersion(this);" style="padding: 1px">
  <option value="http://codemirror.net/">HEAD</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.2;f=">2.2</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.18;f=">2.18</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.16;f=">2.16</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.15;f=">2.15</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.13;f=">2.13</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.12;f=">2.12</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.11;f=">2.11</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.1;f=">2.1</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.02;f=">2.02</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.01;f=">2.01</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=v2.0;f=">2.0</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=beta2;f=">beta2</option>
  <option value="http://marijnhaverbeke.nl/git/codemirror2?a=blob_plain;hb=beta1;f=">beta1</option>
  </select></p>
 
  <select multiple="multiple" name="code_url" style="width: 40em;" class="field" id="files">
  <optgroup label="CodeMirror Library">
  <option value="http://codemirror.net/lib/codemirror.js" selected>codemirror.js</option>
  </optgroup>
  <optgroup label="Modes">
  <option value="http://codemirror.net/mode/clike/clike.js">clike.js</option>
  <option value="http://codemirror.net/mode/clojure/clojure.js">clojure.js</option>
  <option value="http://codemirror.net/mode/coffeescript/coffeescript.js">coffeescript.js</option>
  <option value="http://codemirror.net/mode/css/css.js">css.js</option>
  <option value="http://codemirror.net/mode/diff/diff.js">diff.js</option>
  <option value="http://codemirror.net/mode/gfm/gfm.js">gfm.js</option>
  <option value="http://codemirror.net/mode/groovy/groovy.js">groovy.js</option>
  <option value="http://codemirror.net/mode/haskell/haskell.js">haskell.js</option>
  <option value="http://codemirror.net/mode/htmlembedded/htmlembedded.js">htmlembedded.js</option>
  <option value="http://codemirror.net/mode/htmlmixed/htmlmixed.js">htmlmixed.js</option>
  <option value="http://codemirror.net/mode/javascript/javascript.js">javascript.js</option>
  <option value="http://codemirror.net/mode/jinja2/jinja2.js">jinja2.js</option>
  <option value="http://codemirror.net/mode/lua/lua.js">lua.js</option>
  <option value="http://codemirror.net/mode/markdown/markdown.js">markdown.js</option>
  <option value="http://codemirror.net/mode/ntriples/ntriples.js">ntriples.js</option>
  <option value="http://codemirror.net/mode/pascal/pascal.js">pascal.js</option>
  <option value="http://codemirror.net/mode/perl/perl.js">perl.js</option>
  <option value="http://codemirror.net/mode/php/php.js">php.js</option>
  <option value="http://codemirror.net/mode/plsql/plsql.js">plsql.js</option>
  <option value="http://codemirror.net/mode/python/python.js">python.js</option>
  <option value="http://codemirror.net/mode/r/r.js">r.js</option>
  <option value="http://codemirror.net/mode/rpm/changes/changes.js">rpm/changes.js</option>
  <option value="http://codemirror.net/mode/rpm/spec/spec.js">rpm/spec.js</option>
  <option value="http://codemirror.net/mode/rst/rst.js">rst.js</option>
  <option value="http://codemirror.net/mode/ruby/ruby.js">ruby.js</option>
  <option value="http://codemirror.net/mode/rust/rust.js">rust.js</option>
  <option value="http://codemirror.net/mode/scheme/scheme.js">scheme.js</option>
  <option value="http://codemirror.net/mode/smalltalk/smalltalk.js">smalltalk.js</option>
  <option value="http://codemirror.net/mode/sparql/sparql.js">sparql.js</option>
  <option value="http://codemirror.net/mode/stex/stex.js">stex.js</option>
  <option value="http://codemirror.net/mode/tiddlywiki/tiddlywiki.js">tiddlywiki.js</option>
  <option value="http://codemirror.net/mode/velocity/velocity.js">velocity.js</option>
  <option value="http://codemirror.net/mode/xml/xml.js">xml.js</option>
  <option value="http://codemirror.net/mode/yaml/yaml.js">yaml.js</option>
  </optgroup>
  <optgroup label="Utilities and add-ons">
  <option value="http://codemirror.net/lib/util/overlay.js">overlay.js</option>
  <option value="http://codemirror.net/lib/util/runmode.js">runmode.js</option>
  <option value="http://codemirror.net/lib/util/simple-hint.js">simple-hint.js</option>
  <option value="http://codemirror.net/lib/util/javascript-hint.js">javascript-hint.js</option>
  <option value="http://codemirror.net/lib/util/foldcode.js">codefold.js</option>
  <option value="http://codemirror.net/lib/util/dialog.js">dialog.js</option>
  <option value="http://codemirror.net/lib/util/search.js">search.js</option>
  </optgroup>
  <optgroup label="Keymaps">
  <option value="http://codemirror.net/keymap/emacs.js">emacs.js</option>
  </optgroup>
  </select></p>
 
  <p>
  <button type="submit">Compress</button> with <a href="http://github.com/mishoo/UglifyJS/">UglifyJS</a>
  </p>
 
  <p>Custom code to add to the compressed file:<textarea name="js_code" style="width: 100%; height: 15em;" class="field"></textarea></p>
  </form>
 
  <script type="text/javascript">
  function setVersion(ver) {
  var urlprefix = ver.options[ver.selectedIndex].value;
  var select = document.getElementById("files"), m;
  for (var optgr = select.firstChild; optgr; optgr = optgr.nextSibling)
  for (var opt = optgr.firstChild; opt; opt = opt.nextSibling) {
  if (opt.nodeName != "OPTION")
  continue;
  else if (m = opt.value.match(/^http:\/\/codemirror.net\/2\/(.*)$/))
  opt.value = urlprefix + m[1];
  else if (m = opt.value.match(/http:\/\/marijnhaverbeke.nl\/git\/codemirror\?a=blob_plain;hb=[^;]+;f=(.*)$/))
  opt.value = urlprefix + m[1];
  }
  }
  </script>
 
  </body>
  </html>
 
 
  body {
  font-family: Droid Sans, Arial, sans-serif;
  line-height: 1.5;
  max-width: 64.3em;
  margin: 3em auto;
  padding: 0 1em;
  }
 
  h1 {
  letter-spacing: -3px;
  font-size: 3.23em;
  font-weight: bold;
  margin: 0;
  }
 
  h2 {
  font-size: 1.23em;
  font-weight: bold;
  margin: .5em 0;
  letter-spacing: -1px;
  }
 
  h3 {
  font-size: 1em;
  font-weight: bold;
  margin: .4em 0;
  }
 
  pre {
  background-color: #eee;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  padding: 1em;
  }
 
  pre.code {
  margin: 0 1em;
  }
 
  .grey {
  font-size: 2.2em;
  padding: .5em 1em;
  line-height: 1.2em;
  margin-top: .5em;
  position: relative;
  }
 
  img.logo {
  position: absolute;
  right: -25px;
  bottom: 4px;
  }
 
  a:link, a:visited, .quasilink {
  color: #df0019;
  cursor: pointer;
  text-decoration: none;
  }
 
  a:hover, .quasilink:hover {
  color: #800004;
  }
 
  h1 a:link, h1 a:visited, h1 a:hover {
  color: black;
  }
 
  ul {
  margin: 0;
  padding-left: 1.2em;
  }
 
  a.download {
  color: white;
  background-color: #df0019;
  width: 100%;
  display: block;
  text-align: center;
  font-size: 1.23em;
  font-weight: bold;
  text-decoration: none;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  padding: .5em 0;
  margin-bottom: 1em;
  }
 
  a.download:hover {
  background-color: #bb0010;
  }
 
  .rel {
  margin-bottom: 0;
  }
 
  .rel-note {
  color: #777;
  font-size: .9em;
  margin-top: .1em;
  }
 
  .logo-braces {
  color: #df0019;
  position: relative;
  top: -4px;
  }
 
  .blk {
  float: left;
  }
 
  .left {
  width: 37em;
  padding-right: 6.53em;
  padding-bottom: 1em;
  }
 
  .left1 {
  width: 15.24em;
  padding-right: 6.45em;
  }
 
  .left2 {
  width: 15.24em;
  }
 
  .right {
  width: 20.68em;
  }
 
  .leftbig {
  width: 42.44em;
  padding-right: 6.53em;
  }
 
  .rightsmall {
  width: 15.24em;
  }
 
  .clear:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
  }
  .clear { display: inline-block; }
  /* start commented backslash hack \*/
  * html .clear { height: 1%; }
  .clear { display: block; }
  /* close commented backslash hack */
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Internals</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style>dl dl {margin: 0;} .update {color: #d40 !important}</style>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* (Re-) Implementing A Syntax-
  Highlighting Editor in JavaScript */
  </pre>
 
  <div class="clear"><div class="leftbig blk">
 
  <p style="font-size: 85%" id="intro">
  <strong>Topic:</strong> JavaScript, code editor implementation<br>
  <strong>Author:</strong> Marijn Haverbeke<br>
  <strong>Date:</strong> March 2nd 2011 (updated November 13th 2011)
  </p>
 
  <p>This is a followup to
  my <a href="http://codemirror.net/story.html">Brutal Odyssey to the
  Dark Side of the DOM Tree</a> story. That one describes the
  mind-bending process of implementing (what would become) CodeMirror 1.
  This one describes the internals of CodeMirror 2, a complete rewrite
  and rethink of the old code base. I wanted to give this piece another
  Hunter Thompson copycat subtitle, but somehow that would be out of
  place—the process this time around was one of straightforward
  engineering, requiring no serious mind-bending whatsoever.</p>
 
  <p>So, what is wrong with CodeMirror 1? I'd estimate, by mailing list
  activity and general search-engine presence, that it has been
  integrated into about a thousand systems by now. The most prominent
  one, since a few weeks,
  being <a href="http://googlecode.blogspot.com/2011/01/make-quick-fixes-quicker-on-google.html">Google
  code's project hosting</a>. It works, and it's being used widely.</a>
 
  <p>Still, I did not start replacing it because I was bored. CodeMirror
  1 was heavily reliant on <code>designMode</code>
  or <code>contentEditable</code> (depending on the browser). Neither of
  these are well specified (HTML5 tries
  to <a href="http://www.w3.org/TR/html5/editing.html#contenteditable">specify</a>
  their basics), and, more importantly, they tend to be one of the more
  obscure and buggy areas of browser functionality—CodeMirror, by using
  this functionality in a non-typical way, was constantly running up
  against browser bugs. WebKit wouldn't show an empty line at the end of
  the document, and in some releases would suddenly get unbearably slow.
  Firefox would show the cursor in the wrong place. Internet Explorer
  would insist on linkifying everything that looked like a URL or email
  address, a behaviour that can't be turned off. Some bugs I managed to
  work around (which was often a frustrating, painful process), others,
  such as the Firefox cursor placement, I gave up on, and had to tell
  user after user that they were known problems, but not something I
  could help.</p>
 
  <p>Also, there is the fact that <code>designMode</code> (which seemed
  to be less buggy than <code>contentEditable</code> in Webkit and
  Firefox, and was thus used by CodeMirror 1 in those browsers) requires
  a frame. Frames are another tricky area. It takes some effort to
  prevent getting tripped up by domain restrictions, they don't
  initialize synchronously, behave strangely in response to the back
  button, and, on several browsers, can't be moved around the DOM
  without having them re-initialize. They did provide a very nice way to
  namespace the library, though—CodeMirror 1 could freely pollute the
  namespace inside the frame.</p>
 
  <p>Finally, working with an editable document means working with
  selection in arbitrary DOM structures. Internet Explorer (8 and
  before) has an utterly different (and awkward) selection API than all
  of the other browsers, and even among the different implementations of
  <code>document.selection</code>, details about how exactly a selection
  is represented vary quite a bit. Add to that the fact that Opera's
  selection support tended to be very buggy until recently, and you can
  imagine why CodeMirror 1 contains 700 lines of selection-handling
  code.</p>
 
  <p>And that brings us to the main issue with the CodeMirror 1
  code base: The proportion of browser-bug-workarounds to real
  application code was getting dangerously high. By building on top of a
  few dodgy features, I put the system in a vulnerable position—any
  incompatibility and bugginess in these features, I had to paper over
  with my own code. Not only did I have to do some serious stunt-work to
  get it to work on older browsers (as detailed in the
  previous <a href="http://codemirror.net/story.html">story</a>), things
  also kept breaking in newly released versions, requiring me to come up
  with <em>new</em> scary hacks in order to keep up. This was starting
  to lose its appeal.</p>
 
  <h2 id="approach">General Approach</h2>
 
  <p>What CodeMirror 2 does is try to sidestep most of the hairy hacks
  that came up in version 1. I owe a lot to the
  <a href="http://ace.ajax.org">ACE</a> editor for inspiration on how to
  approach this.</p>
 
  <p>I absolutely did not want to be completely reliant on key events to
  generate my input. Every JavaScript programmer knows that key event
  information is horrible and incomplete. Some people (most awesomely
  Mihai Bazon with <a href="http://ymacs.org">Ymacs</a>) have been able
  to build more or less functioning editors by directly reading key
  events, but it takes a lot of work (the kind of never-ending, fragile
  work I described earlier), and will never be able to properly support
  things like multi-keystoke international character
  input. <a href="#keymap" class="update">[see below for caveat]</a></p>
 
  <p>So what I do is focus a hidden textarea, and let the browser
  believe that the user is typing into that. What we show to the user is
  a DOM structure we built to represent his document. If this is updated
  quickly enough, and shows some kind of believable cursor, it feels
  like a real text-input control.</p>
 
  <p>Another big win is that this DOM representation does not have to
  span the whole document. Some CodeMirror 1 users insisted that they
  needed to put a 30 thousand line XML document into CodeMirror. Putting
  all that into the DOM takes a while, especially since, for some
  reason, an editable DOM tree is slower than a normal one on most
  browsers. If we have full control over what we show, we must only
  ensure that the visible part of the document has been added, and can
  do the rest only when needed. (Fortunately, the <code>onscroll</code>
  event works almost the same on all browsers, and lends itself well to
  displaying things only as they are scrolled into view.)</p>
 
  <h2 id="input">Input</h2>
 
  <p>ACE uses its hidden textarea only as a text input shim, and does
  all cursor movement and things like text deletion itself by directly
  handling key events. CodeMirror's way is to let the browser do its
  thing as much as possible, and not, for example, define its own set of
  key bindings. One way to do this would have been to have the whole
  document inside the hidden textarea, and after each key event update
  the display DOM to reflect what's in that textarea.</p>
 
  <p>That'd be simple, but it is not realistic. For even medium-sized
  document the editor would be constantly munging huge strings, and get
  terribly slow. What CodeMirror 2 does is put the current selection,
  along with an extra line on the top and on the bottom, into the
  textarea.</p>
 
  <p>This means that the arrow keys (and their ctrl-variations), home,
  end, etcetera, do not have to be handled specially. We just read the
  cursor position in the textarea, and update our cursor to match it.
  Also, copy and paste work pretty much for free, and people get their
  native key bindings, without any special work on my part. For example,
  I have emacs key bindings configured for Chrome and Firefox. There is
  no way for a script to detect this. <a class="update"
  href="#keymap">[no longer the case]</a></p>
 
  <p>Of course, since only a small part of the document sits in the
  textarea, keys like page up and ctrl-end won't do the right thing.
  CodeMirror is catching those events and handling them itself.</p>
 
  <h2 id="selection">Selection</h2>
 
  <p>Getting and setting the selection range of a textarea in modern
  browsers is trivial—you just use the <code>selectionStart</code>
  and <code>selectionEnd</code> properties. On IE you have to do some
  insane stuff with temporary ranges and compensating for the fact that
  moving the selection by a 'character' will treat \r\n as a single
  character, but even there it is possible to build functions that
  reliably set and get the selection range.</p>
 
  <p>But consider this typical case: When I'm somewhere in my document,
  press shift, and press the up arrow, something gets selected. Then, if
  I, still holding shift, press the up arrow again, the top of my
  selection is adjusted. The selection remembers where its <em>head</em>
  and its <em>anchor</em> are, and moves the head when we shift-move.
  This is a generally accepted property of selections, and done right by
  every editing component built in the past twenty years.</p>
 
  <p>But not something that the browser selection APIs expose.</p>
 
  <p>Great. So when someone creates an 'upside-down' selection, the next
  time CodeMirror has to update the textarea, it'll re-create the
  selection as an 'upside-up' selection, with the anchor at the top, and
  the next cursor motion will behave in an unexpected way—our second
  up-arrow press in the example above will not do anything, since it is
  interpreted in exactly the same way as the first.</p>
 
  <p>No problem. We'll just, ehm, detect that the selection is
  upside-down (you can tell by the way it was created), and then, when
  an upside-down selection is present, and a cursor-moving key is
  pressed in combination with shift, we quickly collapse the selection
  in the textarea to its start, allow the key to take effect, and then
  combine its new head with its old anchor to get the <em>real</em>
  selection.</p>
 
  <p>In short, scary hacks could not be avoided entirely in CodeMirror
  2.</p>
 
  <p>And, the observant reader might ask, how do you even know that a
  key combo is a cursor-moving combo, if you claim you support any
  native key bindings? Well, we don't, but we can learn. The editor
  keeps a set known cursor-movement combos (initialized to the
  predictable defaults), and updates this set when it observes that
  pressing a certain key had (only) the effect of moving the cursor.
  This, of course, doesn't work if the first time the key is used was
  for extending an inverted selection, but it works most of the
  time.</p>
 
  <h2 id="update">Intelligent Updating</h2>
 
  <p>One thing that always comes up when you have a complicated internal
  state that's reflected in some user-visible external representation
  (in this case, the displayed code and the textarea's content) is
  keeping the two in sync. The naive way is to just update the display
  every time you change your state, but this is not only error prone
  (you'll forget), it also easily leads to duplicate work on big,
  composite operations. Then you start passing around flags indicating
  whether the display should be updated in an attempt to be efficient
  again and, well, at that point you might as well give up completely.</p>
 
  <p>I did go down that road, but then switched to a much simpler model:
  simply keep track of all the things that have been changed during an
  action, and then, only at the end, use this information to update the
  user-visible display.</p>
 
  <p>CodeMirror uses a concept of <em>operations</em>, which start by
  calling a specific set-up function that clears the state and end by
  calling another function that reads this state and does the required
  updating. Most event handlers, and all the user-visible methods that
  change state are wrapped like this. There's a method
  called <code>operation</code> that accepts a function, and returns
  another function that wraps the given function as an operation.</p>
 
  <p>It's trivial to extend this (as CodeMirror does) to detect nesting,
  and, when an operation is started inside an operation, simply
  increment the nesting count, and only do the updating when this count
  reaches zero again.</p>
 
  <p>If we have a set of changed ranges and know the currently shown
  range, we can (with some awkward code to deal with the fact that
  changes can add and remove lines, so we're dealing with a changing
  coordinate system) construct a map of the ranges that were left
  intact. We can then compare this map with the part of the document
  that's currently visible (based on scroll offset and editor height) to
  determine whether something needs to be updated.</p>
 
  <p>CodeMirror uses two update algorithms—a full refresh, where it just
  discards the whole part of the DOM that contains the edited text and
  rebuilds it, and a patch algorithm, where it uses the information
  about changed and intact ranges to update only the out-of-date parts
  of the DOM. When more than 30 percent (which is the current heuristic,
  might change) of the lines need to be updated, the full refresh is
  chosen (since it's faster to do than painstakingly finding and
  updating all the changed lines), in the other case it does the
  patching (so that, if you scroll a line or select another character,
  the whole screen doesn't have to be
  re-rendered). <span class="update">[the full-refresh
  algorithm was dropped, it wasn't really faster than the patching
  one]</span></p>
 
  <p>All updating uses <code>innerHTML</code> rather than direct DOM
  manipulation, since that still seems to be by far the fastest way to
  build documents. There's a per-line function that combines the
  highlighting, <a href="manual.html#markText">marking</a>, and
  selection info for that line into a snippet of HTML. The patch updater
  uses this to reset individual lines, the refresh updater builds an
  HTML chunk for the whole visible document at once, and then uses a
  single <code>innerHTML</code> update to do the refresh.</p>
 
  <h2 id="parse">Parsers can be Simple</h2>
 
  <p>When I wrote CodeMirror 1, I
  thought <a href="http://codemirror.net/story.html#parser">interruptable
  parsers</a> were a hugely scary and complicated thing, and I used a
  bunch of heavyweight abstractions to keep this supposed complexity
  under control: parsers
  were <a href="http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/">iterators</a>
  that consumed input from another iterator, and used funny
  closure-resetting tricks to copy and resume themselves.</p>
 
  <p>This made for a rather nice system, in that parsers formed strictly
  separate modules, and could be composed in predictable ways.
  Unfortunately, it was quite slow (stacking three or four iterators on
  top of each other), and extremely intimidating to people not used to a
  functional programming style.</p>
 
  <p>With a few small changes, however, we can keep all those
  advantages, but simplify the API and make the whole thing less
  indirect and inefficient. CodeMirror
  2's <a href="manual.html#modeapi">mode API</a> uses explicit state
  objects, and makes the parser/tokenizer a function that simply takes a
  state and a character stream abstraction, advances the stream one
  token, and returns the way the token should be styled. This state may
  be copied, optionally in a mode-defined way, in order to be able to
  continue a parse at a given point. Even someone who's never touched a
  lambda in his life can understand this approach. Additionally, far
  fewer objects are allocated in the course of parsing now.</p>
 
  <p>The biggest speedup comes from the fact that the parsing no longer
  has to touch the DOM though. In CodeMirror 1, on an older browser, you
  could <em>see</em> the parser work its way through the document,
  managing some twenty lines in each 50-millisecond time slice it got. It
  was reading its input from the DOM, and updating the DOM as it went
  along, which any experienced JavaScript programmer will immediately
  spot as a recipe for slowness. In CodeMirror 2, the parser usually
  finishes the whole document in a single 100-millisecond time slice—it
  manages some 1500 lines during that time on Chrome. All it has to do
  is munge strings, so there is no real reason for it to be slow
  anymore.</p>
 
  <h2 id="summary">What Gives?</h2>
 
  <p>Given all this, what can you expect from CodeMirror 2?</p>
 
  <ul>
 
  <li><strong>Small.</strong> the base library is
  some <span class="update">45k</span> when minified
  now, <span class="update">17k</span> when gzipped. It's smaller than
  its own logo.</li>
 
  <li><strong>Lightweight.</strong> CodeMirror 2 initializes very
  quickly, and does almost no work when it is not focused. This means
  you can treat it almost like a textarea, have multiple instances on a
  page without trouble.</li>
 
  <li><strong>Huge document support.</strong> Since highlighting is
  really fast, and no DOM structure is being built for non-visible
  content, you don't have to worry about locking up your browser when a
  user enters a megabyte-sized document.</li>
 
  <li><strong>Extended API.</strong> Some things kept coming up in the
  mailing list, such as marking pieces of text or lines, which were
  extremely hard to do with CodeMirror 1. The new version has proper
  support for these built in.</li>
 
  <li><strong>Tab support.</strong> Tabs inside editable documents were,
  for some reason, a no-go. At least six different people announced they
  were going to add tab support to CodeMirror 1, none survived (I mean,
  none delivered a working version). CodeMirror 2 no longer removes tabs
  from your document.</li>
 
  <li><strong>Sane styling.</strong> <code>iframe</code> nodes aren't
  really known for respecting document flow. Now that an editor instance
  is a plain <code>div</code> element, it is much easier to size it to
  fit the surrounding elements. You don't even have to make it scroll if
  you do not <a href="../demo/resize.html">want to</a>.</li>
 
  </ul>
 
  <p>On the downside, a CodeMirror 2 instance is <em>not</em> a native
  editable component. Though it does its best to emulate such a
  component as much as possible, there is functionality that browsers
  just do not allow us to hook into. Doing select-all from the context
  menu, for example, is not currently detected by CodeMirror.</p>
 
  <p id="changes" style="margin-top: 2em;"><span style="font-weight:
  bold">[Updates from November 13th 2011]</span> Recently, I've made
  some changes to the codebase that cause some of the text above to no
  longer be current. I've left the text intact, but added markers at the
  passages that are now inaccurate. The new situation is described
  below.</p>
 
  <h2 id="btree">Content Representation</h2>
 
  <p>The original implementation of CodeMirror 2 represented the
  document as a flat array of line objects. This worked well—splicing
  arrays will require the part of the array after the splice to be
  moved, but this is basically just a simple <code>memmove</code> of a
  bunch of pointers, so it is cheap even for huge documents.</p>
 
  <p>However, I recently added line wrapping and code folding (line
  collapsing, basically). Once lines start taking up a non-constant
  amount of vertical space, looking up a line by vertical position
  (which is needed when someone clicks the document, and to determine
  the visible part of the document during scrolling) can only be done
  with a linear scan through the whole array, summing up line heights as
  you go. Seeing how I've been going out of my way to make big documents
  fast, this is not acceptable.</p>
 
  <p>The new representation is based on a B-tree. The leaves of the tree
  contain arrays of line objects, with a fixed minimum and maximum size,
  and the non-leaf nodes simply hold arrays of child nodes. Each node
  stores both the amount of lines that live below them and the vertical
  space taken up by these lines. This allows the tree to be indexed both
  by line number and by vertical position, and all access has
  logarithmic complexity in relation to the document size.</p>
 
  <p>I gave line objects and tree nodes parent pointers, to the node
  above them. When a line has to update its height, it can simply walk
  these pointers to the top of the tree, adding or subtracting the
  difference in height from each node it encounters. The parent pointers
  also make it cheaper (in complexity terms, the difference is probably
  tiny in normal-sized documents) to find the current line number when
  given a line object. In the old approach, the whole document array had
  to be searched. Now, we can just walk up the tree and count the sizes
  of the nodes coming before us at each level.</p>
 
  <p>I chose B-trees, not regular binary trees, mostly because they
  allow for very fast bulk insertions and deletions. When there is a big
  change to a document, it typically involves adding, deleting, or
  replacing a chunk of subsequent lines. In a regular balanced tree, all
  these inserts or deletes would have to be done separately, which could
  be really expensive. In a B-tree, to insert a chunk, you just walk
  down the tree once to find where it should go, insert them all in one
  shot, and then break up the node if needed. This breaking up might
  involve breaking up nodes further up, but only requires a single pass
  back up the tree. For deletion, I'm somewhat lax in keeping things
  balanced—I just collapse nodes into a leaf when their child count goes
  below a given number. This means that there are some weird editing
  patterns that may result in a seriously unbalanced tree, but even such
  an unbalanced tree will perform well, unless you spend a day making
  strangely repeating edits to a really big document.</p>
 
  <h2 id="keymap">Keymaps</h2>
 
  <p><a href="#approach">Above</a>, I claimed that directly catching key
  events for things like cursor movement is impractical because it
  requires some browser-specific kludges. I then proceeded to explain
  some awful <a href="#selection">hacks</a> that were needed to make it
  possible for the selection changes to be detected through the
  textarea. In fact, the second hack is about as bad as the first.</p>
 
  <p>On top of that, in the presence of user-configurable tab sizes and
  collapsed and wrapped lines, lining up cursor movement in the textarea
  with what's visible on the screen becomes a nightmare. Thus, I've
  decided to move to a model where the textarea's selection is no longer
  depended on.</p>
 
  <p>So I moved to a model where all cursor movement is handled by my
  own code. This adds support for a goal column, proper interaction of
  cursor movement with collapsed lines, and makes it possible for
  vertical movement to move through wrapped lines properly, instead of
  just treating them like non-wrapped lines.</p>
 
  <p>The key event handlers now translate the key event into a string,
  something like <code>Ctrl-Home</code> or <code>Shift-Cmd-R</code>, and
  use that string to look up an action to perform. To make keybinding
  customizable, this lookup goes through
  a <a href="manual.html#option_keyMap">table</a>, using a scheme that
  allows such tables to be chained together (for example, the default
  Mac bindings fall through to a table named 'emacsy', which defines
  basic Emacs-style bindings like <code>Ctrl-F</code>, and which is also
  used by the custom Emacs bindings).</p>
 
  <p>A new
  option <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
  allows ad-hoc keybindings to be defined in a much nicer way than what
  was possible with the
  old <a href="manual.html#option_onKeyEvent"><code>onKeyEvent</code></a>
  callback. You simply provide an object mapping key identifiers to
  functions, instead of painstakingly looking at raw key events.</p>
 
  <p>Built-in commands map to strings, rather than functions, for
  example <code>"goLineUp"</code> is the default action bound to the up
  arrow key. This allows new keymaps to refer to them without
  duplicating any code. New commands can be defined by assigning to
  the <code>CodeMirror.commands</code> object, which maps such commands
  to functions.</p>
 
  <p>The hidden textarea now only holds the current selection, with no
  extra characters around it. This has a nice advantage: polling for
  input becomes much, much faster. If there's a big selection, this text
  does not have to be read from the textarea every time—when we poll,
  just noticing that something is still selected is enough to tell us
  that no new text was typed.</p>
 
  <p>The reason that cheap polling is important is that many browsers do
  not fire useful events on IME (input method engine) input, which is
  the thing where people inputting a language like Japanese or Chinese
  use multiple keystrokes to create a character or sequence of
  characters. Most modern browsers fire <code>input</code> when the
  composing is finished, but many don't fire anything when the character
  is updated <em>during</em> composition. So we poll, whenever the
  editor is focused, to provide immediate updates of the display.</p>
 
  </div><div class="rightsmall blk">
 
  <h2>Contents</h2>
 
  <ul>
  <li><a href="#intro">Introduction</a></li>
  <li><a href="#approach">General Approach</a></li>
  <li><a href="#input">Input</a></li>
  <li><a href="#selection">Selection</a></li>
  <li><a href="#update">Intelligent Updating</a></li>
  <li><a href="#parse">Parsing</a></li>
  <li><a href="#summary">What Gives?</a></li>
  <li><a href="#btree">Content Representation</a></li>
  <li><a href="#keymap">Key Maps</a></li>
  </ul>
 
  </div></div>
 
  <div style="height: 2em">&nbsp;</div>
 
  </body></html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: User Manual</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style>dl dl {margin: 0;}</style>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* User manual and
  reference guide */
  </pre>
 
  <div class="clear"><div class="leftbig blk">
 
  <h2 id="overview">Overview</h2>
 
  <p>CodeMirror is a code-editor component that can be embedded in
  Web pages. The code library provides <em>only</em> the editor
  component, no accompanying buttons, auto-completion, or other IDE
  functionality. It does provide a rich API on top of which such
  functionality can be straightforwardly implemented. See
  the <a href="#addons">add-ons</a> included in the distribution,
  and
  the <a href="http://www.octolabs.com/javascripts/codemirror-ui/">CodeMirror
  UI</a> project, for reusable implementations of extra features.</p>
 
  <p>CodeMirror works with language-specific modes. Modes are
  JavaScript programs that help color (and optionally indent) text
  written in a given language. The distribution comes with a few
  modes (see the <code>mode/</code> directory), and it isn't hard
  to <a href="#modeapi">write new ones</a> for other languages.</p>
 
  <h2 id="usage">Basic Usage</h2>
 
  <p>The easiest way to use CodeMirror is to simply load the script
  and style sheet found under <code>lib/</code> in the distribution,
  plus a mode script from one of the <code>mode/</code> directories
  and a theme stylesheet from <code>theme/</code>. (See
  also <a href="compress.html">the compression helper</a>.) For
  example:</p>
 
  <pre>&lt;script src="lib/codemirror.js">&lt;/script>
  &lt;link rel="stylesheet" href="../lib/codemirror.css">
  &lt;script src="mode/javascript/javascript.js">&lt;/script></pre>
 
  <p>Having done this, an editor instance can be created like
  this:</p>
 
  <pre>var myCodeMirror = CodeMirror(document.body);</pre>
 
  <p>The editor will be appended to the document body, will start
  empty, and will use the mode that we loaded. To have more control
  over the new editor, a configuration object can be passed
  to <code>CodeMirror</code> as a second argument:</p>
 
  <pre>var myCodeMirror = CodeMirror(document.body, {
  value: "function myScript(){return 100;}\n",
  mode: "javascript"
  });</pre>
 
  <p>This will initialize the editor with a piece of code already in
  it, and explicitly tell it to use the JavaScript mode (which is
  useful when multiple modes are loaded).
  See <a href="#config">below</a> for a full discussion of the
  configuration options that CodeMirror accepts.</p>
 
  <p>In cases where you don't want to append the editor to an
  element, and need more control over the way it is inserted, the
  first argument to the <code>CodeMirror</code> function can also
  be a function that, when given a DOM element, inserts it into the
  document somewhere. This could be used to, for example, replace a
  textarea with a real editor:</p>
 
  <pre>var myCodeMirror = CodeMirror(function(elt) {
  myTextArea.parentNode.replaceChild(elt, myTextArea);
  }, {value: myTextArea.value});</pre>
 
  <p>However, for this use case, which is a common way to use
  CodeMirror, the library provides a much more powerful
  shortcut:</p>
 
  <pre>var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>
 
  <p>This will, among other things, ensure that the textarea's value
  is updated when the form (if it is part of a form) is submitted.
  See the <a href="#fromTextArea">API reference</a> for a full
  description of this method.</p>
 
  <h2 id="config">Configuration</h2>
 
  <p>Both the <code>CodeMirror</code> function and
  its <code>fromTextArea</code> method take as second (optional)
  argument an object containing configuration options. Any option
  not supplied like this will be taken
  from <code>CodeMirror.defaults</code>, an object containing the
  default options. You can update this object to change the defaults
  on your page.</p>
 
  <p>Options are not checked in any way, so setting bogus option
  values is bound to lead to odd errors.</p>
 
  <p>These are the supported options:</p>
 
  <dl>
  <dt id="option_value"><code>value (string)</code></dt>
  <dd>The starting value of the editor.</dd>
 
  <dt id="option_mode"><code>mode (string or object)</code></dt>
  <dd>The mode to use. When not given, this will default to the
  first mode that was loaded. It may be a string, which either
  simply names the mode or is
  a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type
  associated with the mode. Alternatively, it may be an object
  containing configuration options for the mode, with
  a <code>name</code> property that names the mode (for
  example <code>{name: "javascript", json: true}</code>). The demo
  pages for each mode contain information about what configuration
  parameters the mode supports. You can ask CodeMirror which modes
  and MIME types are loaded with
  the <code>CodeMirror.listModes</code>
  and <code>CodeMirror.listMIMEs</code> functions.</dd>
 
  <dt id="option_theme"><code>theme (string)</code></dt>
  <dd>The theme to style the editor with. You must make sure the
  CSS file defining the corresponding <code>.cm-s-[name]</code>
  styles is loaded (see
  the <a href="../theme/"><code>theme</code></a> directory in the
  distribution). The default is <code>"default"</code>, for which
  colors are included in <code>codemirror.css</code>. It is
  possible to use multiple theming classes at once—for
  example <code>"foo bar"</code> will assign both
  the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes
  to the editor.</dd>
 
  <dt id="option_indentUnit"><code>indentUnit (integer)</code></dt>
  <dd>How many spaces a block (whatever that means in the edited
  language) should be indented. The default is 2.</dd>
 
  <dt id="option_tabSize"><code>tabSize (integer)</code></dt>
  <dd>The width of a tab character. Defaults to 4.</dd>
 
  <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
  <dd>Whether, when indenting, the first N*<code>tabSize</code>
  spaces should be replaced by N tabs. Default is false.</dd>
 
  <dt id="option_electricChars"><code>electricChars (boolean)</code></dt>
  <dd>Configures whether the editor should re-indent the current
  line when a character is typed that might change its proper
  indentation (only works if the mode supports indentation).
  Default is true.</dd>
 
  <dt id="option_keyMap"><code>keyMap (string)</code></dt>
  <dd>Configures the keymap to use. The default
  is <code>"default"</code>, which is the only keymap defined
  in <code>codemirror.js</code> itself. Extra keymaps are found in
  the <a href="../keymap/"><code>keymap</code></a> directory.</dd>
 
  <dt id="option_extraKeys"><code>extraKeys (object)</code></dt>
  <dd>Can be used to specify extra keybindings for the editor.
  When given, should be an object with property names
  like <code>Ctrl-A</code>, <code>Home</code>,
  and <code>Ctrl-Alt-Left</code>. See
  the <code>CodeMirror.keyNames</code> object for the names of all
  the keys. The values in this object can either be functions,
  which will be called with the CodeMirror instance when the key
  is pressed, or strings, which should name commands defined
  in <code>CodeMirror.commands</code> (not documented properly,
  but looking at the source and the definition of the built-in
  keymaps, they should be rather obvious).</dd>
 
  <dt id="option_lineWrapping"><code>lineWrapping (boolean)</code></dt>
  <dd>Whether CodeMirror should scroll or wrap for long lines.
  Defaults to <code>false</code> (scroll).</dd>
 
  <dt id="option_lineNumbers"><code>lineNumbers (boolean)</code></dt>
  <dd>Whether to show line numbers to the left of the editor.</dd>
 
  <dt id="option_firstLineNumber"><code>firstLineNumber (integer)</code></dt>
  <dd>At which number to start counting lines. Default is 1.</dd>
 
  <dt id="option_gutter"><code>gutter (boolean)</code></dt>
  <dd>Can be used to force a 'gutter' (empty space on the left of
  the editor) to be shown even when no line numbers are active.
  This is useful for setting <a href="#setMarker">markers</a>.</dd>
 
  <dt id="option_fixedGutter"><code>fixedGutter (boolean)</code></dt>
  <dd>When enabled (off by default), this will make the gutter
  stay visible when the document is scrolled horizontally.</dd>
 
  <dt id="option_readOnly"><code>readOnly (boolean)</code></dt>
  <dd>This disables editing of the editor content by the user.</dd>
 
  <dt id="option_onChange"><code>onChange (function)</code></dt>
  <dd>When given, this function will be called every time the
  content of the editor is changed. It will be given the editor
  instance as first argument, and an <code>{from, to, newText,
  next}</code> object containing information about the changes
  that occurred as second argument. <code>from</code>
  and <code>to</code> are the positions (in the pre-change
  coordinate system) where the change started and
  ended. <code>newText</code> is an array of strings representing
  the text that replaced the changed range (split by line). If
  multiple changes happened during a single operation, the object
  will have a <code>next</code> property pointing to another
  change object (which may point to another, etc).</dd>
 
  <dt id="option_onCursorActivity"><code>onCursorActivity (function)</code></dt>
  <dd>Will be called when the cursor or selection moves, or any
  change is made to the editor content.</dd>
 
  <dt id="option_onGutterClick"><code>onGutterClick (function)</code></dt>
  <dd>When given, will be called whenever the editor gutter (the
  line-number area) is clicked. Will be given the editor instance
  as first argument, the (zero-based) number of the line that was
  clicked as second argument, and the raw <code>mousedown</code>
  event object as third argument.</dd>
 
  <dt id="option_onFocus"><code>onFocus, onBlur (function)</code></dt>
  <dd>The given functions will be called whenever the editor is
  focused or unfocused.</dd>
 
  <dt id="option_onScroll"><code>onScroll (function)</code></dt>
  <dd>When given, will be called whenever the editor is
  scrolled.</dd>
 
  <dt id="option_onHighlightComplete"><code>onHighlightComplete (function)</code></dt>
  <dd>Whenever the editor's content has been fully highlighted,
  this function (if given) will be called. It'll be given a single
  argument, the editor instance.</dd>
 
  <dt id="option_onUpdate"><code>onUpdate (function)</code></dt>
  <dd>Will be called whenever CodeMirror updates its DOM display.</dd>
 
  <dt id="option_matchBrackets"><code>matchBrackets (boolean)</code></dt>
  <dd>Determines whether brackets are matched whenever the cursor
  is moved next to a bracket.</dd>
 
  <dt id="option_workTime"><code>workTime, workDelay (number)</code></dt>
  <dd>Highlighting is done by a pseudo background-thread that will
  work for <code>workTime</code> milliseconds, and then use
  timeout to sleep for <code>workDelay</code> milliseconds. The
  defaults are 200 and 300, you can change these options to make
  the highlighting more or less aggressive.</dd>
 
  <dt id="option_pollInterval"><code>pollInterval (number)</code></dt>
  <dd>Indicates how quickly CodeMirror should poll its input
  textarea for changes. Most input is captured by events, but some
  things, like IME input on some browsers, doesn't generate events
  that allow CodeMirror to properly detect it. Thus, it polls.
  Default is 100 milliseconds.</dd>
 
  <dt id="option_undoDepth"><code>undoDepth (integer)</code></dt>
  <dd>The maximum number of undo levels that the editor stores.
  Defaults to 40.</dd>
 
  <dt id="option_tabindex"><code>tabindex (integer)</code></dt>
  <dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab
  index</a> to assign to the editor. If not given, no tab index
  will be assigned.</dd>
 
  <dt id="option_document"><code>document (DOM document)</code></dt>
  <dd>Use this if you want to display the editor in another DOM.
  By default it will use the global <code>document</code>
  object.</dd>
 
  <dt id="option_onKeyEvent"><code>onKeyEvent (function)</code></dt>
  <dd>This provides a rather low-level hook into CodeMirror's key
  handling. If provided, this function will be called on
  every <code>keydown</code>, <code>keyup</code>,
  and <code>keypress</code> event that CodeMirror captures. It
  will be passed two arguments, the editor instance and the key
  event. This key event is pretty much the raw key event, except
  that a <code>stop()</code> method is always added to it. You
  could feed it to, for example, <code>jQuery.Event</code> to
  further normalize it.<br>This function can inspect the key
  event, and handle it if it wants to. It may return true to tell
  CodeMirror to ignore the event. Be wary that, on some browsers,
  stopping a <code>keydown</code> does not stop
  the <code>keypress</code> from firing, whereas on others it
  does. If you respond to an event, you should probably inspect
  its <code>type</code> property and only do something when it
  is <code>keydown</code> (or <code>keypress</code> for actions
  that need character data).</dd>
  </dl>
 
  <h2 id="styling">Customized Styling</h2>
 
  <p>Up to a certain extent, CodeMirror's look can be changed by
  modifying style sheet files. The style sheets supplied by modes
  simply provide the colors for that mode, and can be adapted in a
  very straightforward way. To style the editor itself, it is
  possible to alter or override the styles defined
  in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p>
 
  <p>Some care must be taken there, since a lot of the rules in this
  file are necessary to have CodeMirror function properly. Adjusting
  colors should be safe, of course, and with some care a lot of
  other things can be changed as well. The CSS classes defined in
  this file serve the following roles:</p>
 
  <dl>
  <dt id="class_CodeMirror"><code>CodeMirror</code></dt>
  <dd>The outer element of the editor. This should be used for
  borders and positioning. Can also be used to set styles that
  should hold for everything inside the editor (such as font
  and font size), or to set a background.</dd>
 
  <dt id="class_CodeMirror_scroll"><code>CodeMirror-scroll</code></dt>
  <dd>This determines whether the editor scrolls (<code>overflow:
  auto</code> + fixed height). By default, it does. Giving
  this <code>height: auto; overflow: visible;</code> will cause
  the editor to resize to fit its content.</dd>
 
  <dt id="class_CodeMirror_focused"><code>CodeMirror-focused</code></dt>
  <dd>Whenever the editor is focused, the top element gets this
  class. This is used to hide the cursor and give the selection a
  different color when the editor is not focused.</dd>
 
  <dt id="class_CodeMirror_gutter"><code>CodeMirror-gutter</code></dt>
  <dd>Use this for giving a background or a border to the editor
  gutter. Don't set any padding here,
  use <code>CodeMirror-gutter-text</code> for that. By default,
  the gutter is 'fluid', meaning it will adjust its width to the
  maximum line number or line marker width. You can also set a
  fixed width if you want.</dd>
 
  <dt id="class_CodeMirror_gutter_text"><code>CodeMirror-gutter-text</code></dt>
  <dd>Used to style the actual line numbers. For the numbers to
  line up, you must make sure that the font in the gutter is the
  same as the one in the rest of the editor, so you should
  probably only set font style and size in
  the <code>CodeMirror</code> class.</dd>
 
  <dt id="class_CodeMirror_lines"><code>CodeMirror-lines</code></dt>
  <dd>The visible lines. If this has vertical
  padding, <code>CodeMirror-gutter</code> should have the same
  padding.</dd>
 
  <dt id="class_CodeMirror_cursor"><code>CodeMirror-cursor</code></dt>
  <dd>The cursor is a block element that is absolutely positioned.
  You can make it look whichever way you want.</dd>
 
  <dt id="class_CodeMirror_selected"><code>CodeMirror-selected</code></dt>
  <dd>The selection is represented by <code>span</code> elements
  with this class.</dd>
 
  <dt id="class_CodeMirror_matchingbracket"><code>CodeMirror-matchingbracket</code>,
  <code>CodeMirror-nonmatchingbracket</code></dt>
  <dd>These are used to style matched (or unmatched) brackets.</dd>
  </dl>
 
  <p>The actual lines, as well as the cursor, are represented
  by <code>pre</code> elements. By default no text styling (such as
  bold) that might change line height is applied. If you do want
  such effects, you'll have to give <code>CodeMirror pre</code> a
  fixed height. Also, you must still take care that character width
  is constant.</p>
 
  <p>If your page's style sheets do funky things to
  all <code>div</code> or <code>pre</code> elements (you probably
  shouldn't do that), you'll have to define rules to cancel these
  effects out again for elements under the <code>CodeMirror</code>
  class.</p>
 
  <p>Themes are also simply CSS files, which define colors for
  various syntactic elements. See the files in
  the <a href="../theme/"><code>theme</code></a> directory.</p>
 
  <h2 id="api">Programming API</h2>
 
  <p>A lot of CodeMirror features are only available through its API.
  This has the disadvantage that you need to do work to enable them,
  and the advantage that CodeMirror will fit seamlessly into your
  application.</p>
 
  <p>Whenever points in the document are represented, the API uses
  objects with <code>line</code> and <code>ch</code> properties.
  Both are zero-based. CodeMirror makes sure to 'clip' any positions
  passed by client code so that they fit inside the document, so you
  shouldn't worry too much about sanitizing your coordinates. If you
  give <code>ch</code> a value of <code>null</code>, or don't
  specify it, it will be replaced with the length of the specified
  line.</p>
 
  <dl>
  <dt id="getValue"><code>getValue() → string</code></dt>
  <dd>Get the current editor content.</dd>
  <dt id="setValue"><code>setValue(string)</code></dt>
  <dd>Set the editor content.</dd>
 
  <dt id="getSelection"><code>getSelection() → string</code></dt>
  <dd>Get the currently selected code.</dd>
  <dt id="replaceSelection"><code>replaceSelection(string)</code></dt>
  <dd>Replace the selection with the given string.</dd>
 
  <dt id="focus"><code>focus()</code></dt>
  <dd>Give the editor focus.</dd>
 
  <dt id="setOption"><code>setOption(option, value)</code></dt>
  <dd>Change the configuration of the editor. <code>option</code>
  should the name of an <a href="#config">option</a>,
  and <code>value</code> should be a valid value for that
  option.</dd>
  <dt id="getOption"><code>getOption(option) → value</code></dt>
  <dd>Retrieves the current value of the given option for this
  editor instance.</dd>
 
  <dt id="cursorCoords"><code>cursorCoords(start) → object</code></dt>
  <dd>Returns an <code>{x, y, yBot}</code> object containing the
  coordinates of the cursor relative to the top-left corner of the
  page. <code>yBot</code> is the coordinate of the bottom of the
  cursor. <code>start</code> is a boolean indicating whether you
  want the start or the end of the selection.</dd>
  <dt id="charCoords"><code>charCoords(pos) → object</code></dt>
  <dd>Like <code>cursorCoords</code>, but returns the position of
  an arbitrary characters. <code>pos</code> should be
  a <code>{line, ch}</code> object.</dd>
  <dt id="coordsChar"><code>coordsChar(object) → pos</code></dt>
  <dd>Given an <code>{x, y}</code> object (in page coordinates),
  returns the <code>{line, ch}</code> position that corresponds to
  it.</dd>
 
  <dt id="undo"><code>undo()</code></dt>
  <dd>Undo one edit (if any undo events are stored).</dd>
  <dt id="redo"><code>redo()</code></dt>
  <dd>Redo one undone edit.</dd>
  <dt id="historySize"><code>historySize() → object</code></dt>
  <dd>Returns an object with <code>{undo, redo}</code> properties,
  both of which hold integers, indicating the amount of stored
  undo and redo operations.</dd>
  <dt id="clearHistory"><code>clearHistory()</code></dt>
  <dd>Clears the editor's undo history.</dd>
 
  <dt id="indentLine"><code>indentLine(line, dir)</code></dt>
  <dd>Reset the given line's indentation to the indentation
  prescribed by the mode. If the second argument is given,
  indentation will be increased (if <code>dir</code> is true) or
  decreased (if false) by an <a href="#option_indentUnit">indent
  unit</a> instead.</dd>
 
  <dt id="getTokenAt"><code>getTokenAt(pos) → object</code></dt>
  <dd>Retrieves information about the token the current mode found
  at the given position (a <code>{line, ch}</code> object). The
  returned object has the following properties:
  <dl>
  <dt><code>start</code></dt><dd>The character (on the given line) at which the token starts.</dd>
  <dt><code>end</code></dt><dd>The character at which the token ends.</dd>
  <dt><code>string</code></dt><dd>The token's string.</dd>
  <dt><code>className</code></dt><dd>The class the mode assigned
  to the token. (Can be null when no class was assigned.)</dd>
  <dt><code>state</code></dt><dd>The mode's state at the end of this token.</dd>
  </dl></dd>
 
  <dt id="markText"><code>markText(from, to, className) → object</code></dt>
  <dd>Can be used to mark a range of text with a specific CSS
  class name. <code>from</code> and <code>to</code> should
  be <code>{line, ch}</code> objects. The method will return an
  object with two methods, <code>clear()</code>, which removes the
  mark, and <code>find()</code>, which returns a <code>{from,
  to}</code> (both document positions), indicating the current
  position of the marked range.</dd>
 
  <dt id="setBookmark"><code>setBookmark(pos) → object</code></dt>
  <dd>Inserts a bookmark, a handle that follows the text around it
  as it is being edited, at the given position. A bookmark has two
  methods <code>find()</code> and <code>clear()</code>. The first
  returns the current position of the bookmark, if it is still in
  the document, and the second explicitly removes the
  bookmark.</dd>
 
  <dt id="setMarker"><code>setMarker(line, text, className) → lineHandle</code></dt>
  <dd>Add a gutter marker for the given line. Gutter markers are
  shown in the line-number area (instead of the number for this
  line). Both <code>text</code> and <code>className</code> are
  optional. Setting <code>text</code> to a Unicode character like
  ● tends to give a nice effect. To put a picture in the gutter,
  set <code>text</code> to a space and <code>className</code> to
  something that sets a background image. If you
  specify <code>text</code>, the given text (which may contain
  HTML) will, by default, replace the line number for that line.
  If this is not what you want, you can include the
  string <code>%N%</code> in the text, which will be replaced by
  the line number.</dd>
  <dt id="clearMarker"><code>clearMarker(line)</code></dt>
  <dd>Clears a marker created
  with <code>setMarker</code>. <code>line</code> can be either a
  number or a handle returned by <code>setMarker</code> (since a
  number may now refer to a different line if something was added
  or deleted).</dd>
  <dt id="setLineClass"><code>setLineClass(line, className) → lineHandle</code></dt>
  <dd>Set a CSS class name for the given line. <code>line</code>
  can be a number or a line handle (as returned
  by <code>setMarker</code> or this function).
  Pass <code>null</code> to clear the class for a line.</dd>
  <dt id="hideLine"><code>hideLine(line) → lineHandle</code></dt>
  <dd>Hide the given line (either by number or by handle). Hidden
  lines don't show up in the editor, and their numbers are skipped
  when <a href="#option_lineNumbers">line numbers</a> are enabled.
  Deleting a region around them does delete them, and coping a
  region around will include them in the copied text.</dd>
  <dt id="showLine"><code>showLine(line) → lineHandle</code></dt>
  <dd>The inverse of <code>hideLine</code>—re-shows a previously
  hidden line, by number or by handle.</dd>
 
  <dt id="onDeleteLine"><code>onDeleteLine(line, func)</code></dt>
  <dd>Register a function that should be called when the line is
  deleted from the document.</dd>
 
  <dt id="lineInfo"><code>lineInfo(line) → object</code></dt>
  <dd>Returns the line number, text content, and marker status of
  the given line, which can be either a number or a handle
  returned by <code>setMarker</code>. The returned object has the
  structure <code>{line, handle, text, markerText, markerClass}</code>.</dd>
 
  <dt id="getLineHandle"><code>getLineHandle(num) → lineHandle</code></dt>
  <dd>Fetches the line handle for the given line number.</dd>
 
  <dt id="addWidget"><code>addWidget(pos, node, scrollIntoView)</code></dt>
  <dd>Puts <code>node</code>, which should be an absolutely
  positioned DOM node, into the editor, positioned right below the
  given <code>{line, ch}</code> position.
  When <code>scrollIntoView</code> is true, the editor will ensure
  that the entire node is visible (if possible). To remove the
  widget again, simply use DOM methods (move it somewhere else, or
  call <code>removeChild</code> on its parent).</dd>
 
  <dt id="matchBrackets"><code>matchBrackets()</code></dt>
  <dd>Force matching-bracket-highlighting to happen.</dd>
 
  <dt id="lineCount"><code>lineCount() → number</code></dt>
  <dd>Get the number of lines in the editor.</dd>
 
  <dt id="getCursor"><code>getCursor(start) → object</code></dt>
  <dd><code>start</code> is a boolean indicating whether the start
  or the end of the selection must be retrieved. If it is not
  given, the current cursor pos, i.e. the side of the selection
  that would move if you pressed an arrow key, is chosen.
  A <code>{line, ch}</code> object will be returned.</dd>
  <dt id="somethingSelected"><code>somethingSelected() → boolean</code></dt>
  <dd>Return true if any text is selected.</dd>
  <dt id="setCursor"><code>setCursor(pos)</code></dt>
  <dd>Set the cursor position. You can either pass a
  single <code>{line, ch}</code> object, or the line and the
  character as two separate parameters.</dd>
  <dt id="setSelection"><code>setSelection(start, end)</code></dt>
  <dd>Set the selection range. <code>start</code>
  and <code>end</code> should be <code>{line, ch}</code> objects.</dd>
 
  <dt id="getLine"><code>getLine(n) → string</code></dt>
  <dd>Get the content of line <code>n</code>.</dd>
  <dt id="setLine"><code>setLine(n, text)</code></dt>
  <dd>Set the content of line <code>n</code>.</dd>
  <dt id="removeLine"><code>removeLine(n)</code></dt>
  <dd>Remove the given line from the document.</dd>
 
  <dt id="getRange"><code>getRange(from, to) → string</code></td>
  <dd>Get the text between the given points in the editor, which
  should be <code>{line, ch}</code> objects.</dd>
  <dt id="replaceRange"><code>replaceRange(string, from, to)</code></dt>
  <dd>Replace the part of the document between <code>from</code>
  and <code>to</code> with the given string. <code>from</code>
  and <code>to</code> must be <code>{line, ch}</code>
  objects. <code>to</code> can be left off to simply insert the
  string at position <code>from</code>.</dd>
 
  <dt id="posFromIndex"><code>posFromIndex(index) → object</code></dt>
  <dd>Calculates and returns a <code>{line, ch}</code> object for a
  zero-based <code>index</code> who's value is relative to the start of the
  editor's text. If the <code>index</code> is out of range of the text then
  the returned object is clipped to start or end of the text
  respectively.</dd>
  <dt id="indexFromPos"><code>indexFromPos(object) → number</code></dt>
  <dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd>
  </dl>
 
  <p>The following are more low-level methods:</p>
 
  <dl>
  <dt id="operation"><code>operation(func) → result</code></dt>
  <dd>CodeMirror internally buffers changes and only updates its
  DOM structure after it has finished performing some operation.
  If you need to perform a lot of operations on a CodeMirror
  instance, you can call this method with a function argument. It
  will call the function, buffering up all changes, and only doing
  the expensive update after the function returns. This can be a
  lot faster. The return value from this method will be the return
  value of your function.</dd>
 
  <dt id="refresh"><code>refresh()</code></dt>
  <dd>If your code does something to change the size of the editor
  element (window resizes are already listened for), or unhides
  it, you should probably follow up by calling this method to
  ensure CodeMirror is still looking as intended.</dd>
 
  <dt id="getInputField"><code>getInputField() → textarea</code></dt>
  <dd>Returns the hiden textarea used to read input.</dd>
  <dt id="getWrapperElement"><code>getWrapperElement() → node</code></dt>
  <dd>Returns the DOM node that represents the editor. Remove this
  from your tree to delete an editor instance.</dd>
  <dt id="getScrollerElement"><code>getScrollerElement() → node</code></dt>
  <dd>Returns the DOM node that is responsible for the sizing and
  the scrolling of the editor. You can change
  the <code>height</code> and <code>width</code> styles of this
  element to resize an editor. (You might have to call
  the <a href="#refresh"><code>refresh</code></a> method
  afterwards.)</dd>
  <dt id="getGutterElement"><code>getGutterElement() → node</code></dt>
  <dd>Fetches the DOM node that represents the editor gutter.</dd>
 
  <dt id="getStateAfter"><code>getStateAfter(line) → state</code></dt>
  <dd>Returns the mode's parser state, if any, at the end of the
  given line number. If no line number is given, the state at the
  end of the document is returned. This can be useful for storing
  parsing errors in the state, or getting other kinds of
  contextual information for a line.</dd>
  </dl>
 
  <p id="fromTextArea">Finally, the <code>CodeMirror</code> object
  itself has a method <code>fromTextArea</code>. This takes a
  textarea DOM node as first argument and an optional configuration
  object as second. It will replace the textarea with a CodeMirror
  instance, and wire up the form of that textarea (if any) to make
  sure the editor contents are put into the textarea when the form
  is submitted. A CodeMirror instance created this way has two
  additional methods:</p>
 
  <dl>
  <dt id="save"><code>save()</code></dt>
  <dd>Copy the content of the editor into the textarea.</dd>
 
  <dt id="toTextArea"><code>toTextArea()</code></dt>
  <dd>Remove the editor, and restore the original textarea (with
  the editor's current content).</dd>
 
  <dt id="getTextArea"><code>getTextArea() → textarea</code></dt>
  <dd>Returns the textarea that the instance was based on.</dd>
  </dl>
 
  <p id="defineExtension">If you want to define extra methods in terms
  of the CodeMirror API, it is possible to
  use <code>CodeMirror.defineExtension(name, value)</code>. This
  will cause the given value (usually a method) to be added to all
  CodeMirror instances created from then on.</p>
 
  <h2 id="addons">Add-ons</h2>
 
  <p>The <code>lib/util</code> directory in the distribution
  contains a number of reusable components that implement extra
  editor functionality. In brief, they are:</p>
 
  <dl>
  <dt id="util_dialog"><a href="../lib/util/dialog.js"><code>dialog.js</code></a></dt>
  <dd>Provides a very simple way to query users for text input.
  Adds an <code>openDialog</code> method to CodeMirror instances,
  which can be called with an HTML fragment that provides the
  prompt (should include an <code>input</code> tag), and a
  callback function that is called when text has been entered.
  Depends on <code>lib/util/dialog.css</code>.</dd>
  <dt id="util_searchcursor"><a href="../lib/util/searchcursor.js"><code>searchcursor.js</code></a></dt>
  <dd>Adds the <code>getSearchCursor(query, start, caseFold) →
  cursor</code> method to CodeMirror instances, which can be used
  to implement search/replace functionality. <code>query</code>
  can be a regular expression or a string (only strings will match
  across lines—if they contain newlines). <code>start</code>
  provides the starting position of the search. It can be
  a <code>{line, ch}</code> object, or can be left off to default
  to the start of the document. <code>caseFold</code> is only
  relevant when matching a string. It will cause the search to be
  case-insensitive. A search cursor has the following methods:
  <dl>
  <dt><code>findNext(), findPrevious() → boolean</code></dt>
  <dd>Search forward or backward from the current position.
  The return value indicates whether a match was found. If
  matching a regular expression, the return value will be the
  array returned by the <code>match</code> method, in case you
  want to extract matched groups.</dd>
  <dt><code>from(), to() → object</code></dt>
  <dd>These are only valid when the last call
  to <code>findNext</code> or <code>findPrevious</code> did
  not return false. They will return <code>{line, ch}</code>
  objects pointing at the start and end of the match.</dd>
  <dt><code>replace(text)</code></dt>
  <dd>Replaces the currently found match with the given text
  and adjusts the cursor position to reflect the
  replacement.</dd>
  </dl></dd>
 
  <dt id="util_search"><a href="../lib/util/search.js"><code>search.js</code></a></dt>
  <dd>Implements the search commands. CodeMirror has keys bound to
  these by default, but will not do anything with them unless an
  implementation is provided. Depends
  on <code>searchcursor.js</code>, and will make use
  of <a href="#util_dialog"><code>openDialog</code></a> when
  available to make prompting for search queries less ugly.</dd>
  <dt id="util_foldcode"><a href="../lib/util/foldcode.js"><code>foldcode.js</code></a></dt>
  <dd>Helps with code folding. See <a href="../demo/folding.html">the
  demo</a> for an example.
  Call <code>CodeMirror.newFoldFunction</code> with a range-finder
  helper function to create a function that will, when applied to
  a CodeMirror instance and a line number, attempt to fold or
  unfold the block starting at the given line. A range-finder is a
  language-specific functoin that also takes an instance and a
  line number, and returns an end line for the block, or null if
  no block is started on that line. This file
  provides <code>CodeMirror.braceRangeFinder</code>, which finds
  blocks in brace languages (JavaScript, C, Java, etc).</dd>
  <dt id="util_runmode"><a href="../lib/util/runmode.js"><code>runmode.js</code></a></dt>
  <dd>Can be used to run a CodeMirror mode over text without
  actually opening an editor instance.
  See <a href="../demo/runmode.html">the demo</a> for an
  example.</dd>
  <dt id="util_simple-hint"><a href="../lib/util/simple-hint.js"><code>simple-hint.js</code></a></dt>
  <dd>Provides a framework for showing autocompletion hints.
  Defines <code>CodeMirror.simpleHint</code>, which takes a
  CodeMirror instance and a hinting function, and pops up a widget
  that allows the user to select a completion. Hinting functions
  are function that take an editor instance, and return
  a <code>{list, from, to}</code> object, where <code>list</code>
  is an array of strings (the completions), and <code>from</code>
  and <code>to</code> give the start and end of the token that is
  being completed. Depends
  on <code>lib/util/simple-hint.css</code>.</dd>
  <dt id="util_javascript-hint"><a href="../lib/util/javascript-hint.js"><code>javascript-hint.js</code></a></dt>
  <dd>Defines <code>CodeMirror.javaScriptHint</code>, which is a
  simple hinting function for the JavaScript mode.</dd>
  </dl>
 
  <h2 id="modeapi">Writing CodeMirror Modes</h2>
 
  <p>Modes typically consist of a single JavaScript file. This file
  defines, in the simplest case, a lexer (tokenizer) for your
  language—a function that takes a character stream as input,
  advances it past a token, and returns a style for that token. More
  advanced modes can also handle indentation for the language.</p>
 
  <p id="defineMode">The mode script should
  call <code>CodeMirror.defineMode</code> to register itself with
  CodeMirror. This function takes two arguments. The first should be
  the name of the mode, for which you should use a lowercase string,
  preferably one that is also the name of the files that define the
  mode (i.e. <code>"xml"</code> is defined <code>xml.js</code>). The
  second argument should be a function that, given a CodeMirror
  configuration object (the thing passed to
  the <code>CodeMirror</code> function) and an optional mode
  configuration object (as in
  the <a href="#option_mode"><code>mode</code></a> option), returns
  a mode object.</p>
 
  <p>Typically, you should use this second argument
  to <code>defineMode</code> as your module scope function (modes
  should not leak anything into the global scope!), i.e. write your
  whole mode inside this function.</p>
 
  <p>The main responsibility of a mode script is <em>parsing</em>
  the content of the editor. Depending on the language and the
  amount of functionality desired, this can be done in really easy
  or extremely complicated ways. Some parsers can be stateless,
  meaning that they look at one element (<em>token</em>) of the code
  at a time, with no memory of what came before. Most, however, will
  need to remember something. This is done by using a <em>state
  object</em>, which is an object that is always passed when
  reading a token, and which can be mutated by the tokenizer.</p>
 
  <p id="startState">Modes that use a state must define
  a <code>startState</code> method on their mode object. This is a
  function of no arguments that produces a state object to be used
  at the start of a document.</p>
 
  <p id="token">The most important part of a mode object is
  its <code>token(stream, state)</code> method. All modes must
  define this method. It should read one token from the stream it is
  given as an argument, optionally update its state, and return a
  style string, or <code>null</code> for tokens that do not have to
  be styled. For your styles, you can either use the 'standard' ones
  defined in the themes (without the <code>cm-</code> prefix), or
  define your own (as the <a href="../mode/diff/index.html">diff</a>
  mode does) and have people include a custom CSS file for your
  mode.<p>
 
  <p id="StringStream">The stream object encapsulates a line of code
  (tokens may never span lines) and our current position in that
  line. It has the following API:</p>
 
  <dl>
  <dt><code>eol() → boolean</code></dt>
  <dd>Returns true only if the stream is at the end of the
  line.</dd>
  <dt><code>sol() → boolean</code></dt>
  <dd>Returns true only if the stream is at the start of the
  line.</dd>
 
  <dt><code>peek() → character</code></dt>
  <dd>Returns the next character in the stream without advancing
  it. Will return <code>undefined</code> at the end of the
  line.</dd>
  <dt><code>next() → character</code></dt>
  <dd>Returns the next character in the stream and advances it.
  Also returns <code>undefined</code> when no more characters are
  available.</dd>
 
  <dt><code>eat(match) → character</code></dt>
  <dd><code>match</code> can be a character, a regular expression,
  or a function that takes a character and returns a boolean. If
  the next character in the stream 'matches' the given argument,
  it is consumed and returned. Otherwise, <code>undefined</code>
  is returned.</dd>
  <dt><code>eatWhile(match) → boolean</code></dt>
  <dd>Repeatedly calls <code>eat</code> with the given argument,
  until it fails. Returns true if any characters were eaten.</dd>
  <dt><code>eatSpace() → boolean</code></dt>
  <dd>Shortcut for <code>eatWhile</code> when matching
  white-space.</dd>
  <dt><code>skipToEnd()</code></dt>
  <dd>Moves the position to the end of the line.</dd>
  <dt><code>skipTo(ch) → boolean</code></dt>
  <dd>Skips to the next occurrence of the given character, if
  found on the current line (doesn't advance the stream if the
  character does not occur on the line). Returns true if the
  character was found.</dd>
  <dt><code>match(pattern, consume, caseFold) → boolean</code></dt>
  <dd>Act like a
  multi-character <code>eat</code>—if <code>consume</code> is true
  or not given—or a look-ahead that doesn't update the stream
  position—if it is false. <code>pattern</code> can be either a
  string or a regular expression starting with <code>^</code>.
  When it is a string, <code>caseFold</code> can be set to true to
  make the match case-insensitive. When successfully matching a
  regular expression, the returned value will be the array
  returned by <code>match</code>, in case you need to extract
  matched groups.</dd>
 
  <dt><code>backUp(n)</code></dt>
  <dd>Backs up the stream <code>n</code> characters. Backing it up
  further than the start of the current token will cause things to
  break, so be careful.</dd>
  <dt><code>column() → integer</code></dt>
  <dd>Returns the column (taking into account tabs) at which the
  current token starts. Can be used to find out whether a token
  starts a new line.</dd>
  <dt><code>indentation() → integer</code></dt>
  <dd>Tells you how far the current line has been indented, in
  spaces. Corrects for tab characters.</dd>
 
  <dt><code>current() → string</code></dt>
  <dd>Get the string between the start of the current token and
  the current stream position.</dd>
  </dl>
 
  <p id="blankLine">By default, blank lines are simply skipped when
  tokenizing a document. For languages that have significant blank
  lines, you can define a <code>blankLine(state)</code> method on
  your mode that will get called whenever a blank line is passed
  over, so that it can update the parser state.</p>
 
  <p id="copyState">Because state object are mutated, and CodeMirror
  needs to keep valid versions of a state around so that it can
  restart a parse at any line, copies must be made of state objects.
  The default algorithm used is that a new state object is created,
  which gets all the properties of the old object. Any properties
  which hold arrays get a copy of these arrays (since arrays tend to
  be used as mutable stacks). When this is not correct, for example
  because a mode mutates non-array properties of its state object, a
  mode object should define a <code>copyState</code> method,
  which is given a state and should return a safe copy of that
  state.</p>
 
  <p id="compareStates">By default, CodeMirror will stop re-parsing
  a document as soon as it encounters a few lines that were
  highlighted the same in the old parse as in the new one. It is
  possible to provide an explicit way to test whether a state is
  equivalent to another one, which CodeMirror will use (instead of
  the unchanged-lines heuristic) to decide when to stop
  highlighting. You do this by providing
  a <code>compareStates</code> method on your mode object, which
  takes two state arguments and returns a boolean indicating whether
  they are equivalent. See the XML mode, which uses this to provide
  reliable highlighting of bad closing tags, as an example.</p>
 
  <p id="indent">If you want your mode to provide smart indentation
  (though the <a href="#indentLine"><code>indentLine</code></a>
  method and the <code>indentAuto</code>
  and <code>newlineAndIndent</code> commands, which keys can be
  <a href="#option_extraKeys">bound</a> to), you must define
  an <code>indent(state, textAfter)</code> method on your mode
  object.</p>
 
  <p>The indentation method should inspect the given state object,
  and optionally the <code>textAfter</code> string, which contains
  the text on the line that is being indented, and return an
  integer, the amount of spaces to indent. It should usually take
  the <a href="#option_indentUnit"><code>indentUnit</code></a>
  option into account.</p>
 
  <p id="electricChars">Finally, a mode may define
  an <code>electricChars</code> property, which should hold a string
  containing all the characters that should trigger the behaviour
  described for
  the <a href="#option_electricChars"><code>electricChars</code></a>
  option.</p>
 
  <p>So, to summarize, a mode <em>must</em> provide
  a <code>token</code> method, and it <em>may</em>
  provide <code>startState</code>, <code>copyState</code>,
  <code>compareStates</code>, and <code>indent</code> methods. For
  an example of a trivial mode, see
  the <a href="../mode/diff/diff.js">diff mode</a>, for a more involved
  example, see the <a href="../mode/clike/clike.js">C-like
  mode</a>.</p>
 
  <p>Sometimes, it is useful for modes to <em>nest</em>—to have one
  mode delegate work to another mode. An example of this kind of
  mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML
  mode</a>. To implement such nesting, it is usually necessary to
  create mode objects and copy states yourself. To create a mode
  object, there are <code>CodeMirror.getMode(options,
  parserConfig)</code>, where the first argument is a configuration
  object as passed to the mode constructor function, and the second
  argument is a mode specification as in
  the <a href="#option_mode"><code>mode</code></a> option. To copy a
  state object, call <code>CodeMirror.copyState(mode, state)</code>,
  where <code>mode</code> is the mode that created the given
  state.</p>
 
  <p>To make indentation work properly in a nested parser, it is
  advisable to give the <code>startState</code> method of modes that
  are intended to be nested an optional argument that provides the
  base indentation for the block of code. The JavaScript and CSS
  parser do this, for example, to allow JavaScript and CSS code
  inside the mixed-mode HTML mode to be properly indented.</p>
 
  <p>Finally, it is possible to associate your mode, or a certain
  configuration of your mode, with
  a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For
  example, the JavaScript mode associates itself
  with <code>text/javascript</code>, and its JSON variant
  with <code>application/json</code>. To do this,
  call <code>CodeMirror.defineMIME(mime, modeSpec)</code>,
  where <code>modeSpec</code> can be a string or object specifying a
  mode, as in the <a href="#option_mode"><code>mode</code></a>
  option.</p>
 
  </div><div class="rightsmall blk">
 
  <h2>Contents</h2>
 
  <ul>
  <li><a href="#overview">Overview</a></li>
  <li><a href="#usage">Basic Usage</a></li>
  <li><a href="#config">Configuration</a></li>
  <li><a href="#styling">Customized Styling</a></li>
  <li><a href="#api">Programming API</a></li>
  <li><a href="#addons">Add-ons</a></li>
  <li><a href="#modeapi">Writing CodeMirror Modes</a></li>
  </ul>
 
  </div></div>
 
  <div style="height: 2em">&nbsp;</div>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* Old release history */
 
  </pre>
  <p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.1.zip">Version 2.1</a>:</p>
  <p class="rel-note">Add
  a <a href="manual.html#option_theme">theme</a> system
  (<a href="../demo/theme.html">demo</a>). Note that this is not
  backwards-compatible—you'll have to update your styles and
  modes!</p>
 
  <p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.02.zip">Version 2.02</a>:</p>
  <ul class="rel-note">
  <li>Add a <a href="../mode/lua/index.html">Lua mode</a>.</li>
  <li>Fix reverse-searching for a regexp.</li>
  <li>Empty lines can no longer break highlighting.</li>
  <li>Rework scrolling model (the outer wrapper no longer does the scrolling).</li>
  <li>Solve horizontal jittering on long lines.</li>
  <li>Add <a href="../demo/runmode.html">runmode.js</a>.</li>
  <li>Immediately re-highlight text when typing.</li>
  <li>Fix problem with 'sticking' horizontal scrollbar.</li>
  </ul>
 
  <p class="rel">26-05-2011: <a href="http://codemirror.net/codemirror-2.01.zip">Version 2.01</a>:</p>
  <ul class="rel-note">
  <li>Add a <a href="../mode/smalltalk/index.html">Smalltalk mode</a>.</li>
  <li>Add a <a href="../mode/rst/index.html">reStructuredText mode</a>.</li>
  <li>Add a <a href="../mode/python/index.html">Python mode</a>.</li>
  <li>Add a <a href="../mode/plsql/index.html">PL/SQL mode</a>.</li>
  <li><code>coordsChar</code> now works</li>
  <li>Fix a problem where <code>onCursorActivity</code> interfered with <code>onChange</code>.</li>
  <li>Fix a number of scrolling and mouse-click-position glitches.</li>
  <li>Pass information about the changed lines to <code>onChange</code>.</li>
  <li>Support cmd-up/down on OS X.</li>
  <li>Add triple-click line selection.</li>
  <li>Don't handle shift when changing the selection through the API.</li>
  <li>Support <code>"nocursor"</code> mode for <code>readOnly</code> option.</li>
  <li>Add an <code>onHighlightComplete</code> option.</li>
  <li>Fix the context menu for Firefox.</li>
  </ul>
 
  <p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-2.0.zip">Version 2.0</a>:</p>
  <p class="rel-note">CodeMirror 2 is a complete rewrite that's
  faster, smaller, simpler to use, and less dependent on browser
  quirks. See <a href="internals.html">this</a>
  and <a href="http://groups.google.com/group/codemirror/browse_thread/thread/5a8e894024a9f580">this</a>
  for more information.</a>
 
  <p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-1.0.zip">Version 1.0</a>:</p>
  <ul class="rel-note">
  <li>Fix error when debug history overflows.</li>
  <li>Refine handling of C# verbatim strings.</li>
  <li>Fix some issues with JavaScript indentation.</li>
  </ul>
 
  <p class="rel">22-02-2011: <a href="https://github.com/marijnh/codemirror2/tree/beta2">Version 2.0 beta 2</a>:</p>
  <p class="rel-note">Somewhate more mature API, lots of bugs shaken out.</a>
 
  <p class="rel">17-02-2011: <a href="http://codemirror.net/codemirror-0.94.zip">Version 0.94</a>:</p>
  <ul class="rel-note">
  <li><code>tabMode: "spaces"</code> was modified slightly (now indents when something is selected).</li>
  <li>Fixes a bug that would cause the selection code to break on some IE versions.</li>
  <li>Disabling spell-check on WebKit browsers now works.</li>
  </ul>
 
  <p class="rel">08-02-2011: <a href="http://codemirror.net/">Version 2.0 beta 1</a>:</p>
  <p class="rel-note">CodeMirror 2 is a complete rewrite of
  CodeMirror, no longer depending on an editable frame.</p>
 
  <p class="rel">19-01-2011: <a href="http://codemirror.net/codemirror-0.93.zip">Version 0.93</a>:</p>
  <ul class="rel-note">
  <li>Added a <a href="contrib/regex/index.html">Regular Expression</a> parser.</li>
  <li>Fixes to the PHP parser.</li>
  <li>Support for regular expression in search/replace.</li>
  <li>Add <code>save</code> method to instances created with <code>fromTextArea</code>.</li>
  <li>Add support for MS T-SQL in the SQL parser.</li>
  <li>Support use of CSS classes for highlighting brackets.</li>
  <li>Fix yet another hang with line-numbering in hidden editors.</li>
  </ul>
 
  <p class="rel">17-12-2010: <a href="http://codemirror.net/codemirror-0.92.zip">Version 0.92</a>:</p>
  <ul class="rel-note">
  <li>Make CodeMirror work in XHTML documents.</li>
  <li>Fix bug in handling of backslashes in Python strings.</li>
  <li>The <code>styleNumbers</code> option is now officially
  supported and documented.</li>
  <li><code>onLineNumberClick</code> option added.</li>
  <li>More consistent names <code>onLoad</code> and
  <code>onCursorActivity</code> callbacks. Old names still work, but
  are deprecated.</li>
  <li>Add a <a href="contrib/freemarker/index.html">Freemarker</a> mode.</li>
  </ul>
 
  <p class="rel">11-11-2010: <a
  href="http://codemirror.net/codemirror-0.91.zip">Version 0.91</a>:</p>
  <ul class="rel-note">
  <li>Adds support for <a href="contrib/java">Java</a>.</li>
  <li>Small additions to the <a href="contrib/php">PHP</a> and <a href="contrib/sql">SQL</a> parsers.</li>
  <li>Work around various <a href="https://bugs.webkit.org/show_bug.cgi?id=47806">Webkit</a> <a href="https://bugs.webkit.org/show_bug.cgi?id=23474">issues</a>.</li>
  <li>Fix <code>toTextArea</code> to update the code in the textarea.</li>
  <li>Add a <code>noScriptCaching</code> option (hack to ease development).</li>
  <li>Make sub-modes of <a href="mixedtest.html">HTML mixed</a> mode configurable.</li>
  </ul>
 
  <p class="rel">02-10-2010: <a
  href="http://codemirror.net/codemirror-0.9.zip">Version 0.9</a>:</p>
  <ul class="rel-note">
  <li>Add support for searching backwards.</li>
  <li>There are now parsers for <a href="contrib/scheme/index.html">Scheme</a>, <a href="contrib/xquery/index.html">XQuery</a>, and <a href="contrib/ometa/index.html">OmetaJS</a>.</li>
  <li>Makes <code>height: "dynamic"</code> more robust.</li>
  <li>Fixes bug where paste did not work on OS X.</li>
  <li>Add a <code>enterMode</code> and <code>electricChars</code> options to make indentation even more customizable.</li>
  <li>Add <code>firstLineNumber</code> option.</li>
  <li>Fix bad handling of <code>@media</code> rules by the CSS parser.</li>
  <li>Take a new, more robust approach to working around the invisible-last-line bug in WebKit.</li>
  </ul>
 
  <p class="rel">22-07-2010: <a
  href="http://codemirror.net/codemirror-0.8.zip">Version 0.8</a>:</p>
  <ul class="rel-note">
  <li>Add a <code>cursorCoords</code> method to find the screen
  coordinates of the cursor.</li>
  <li>A number of fixes and support for more syntax in the PHP parser.</li>
  <li>Fix indentation problem with JSON-mode JS parser in Webkit.</li>
  <li>Add a <a href="compress.html">minification</a> UI.</li>
  <li>Support a <code>height: dynamic</code> mode, where the editor's
  height will adjust to the size of its content.</li>
  <li>Better support for IME input mode.</li>
  <li>Fix JavaScript parser getting confused when seeing a no-argument
  function call.</li>
  <li>Have CSS parser see the difference between selectors and other
  identifiers.</li>
  <li>Fix scrolling bug when pasting in a horizontally-scrolled
  editor.</li>
  <li>Support <code>toTextArea</code> method in instances created with
  <code>fromTextArea</code>.</li>
  <li>Work around new Opera cursor bug that causes the cursor to jump
  when pressing backspace at the end of a line.</li>
  </ul>
 
  <p class="rel">27-04-2010: <a
  href="http://codemirror.net/codemirror-0.67.zip">Version
  0.67</a>:</p>
  <p class="rel-note">More consistent page-up/page-down behaviour
  across browsers. Fix some issues with hidden editors looping forever
  when line-numbers were enabled. Make PHP parser parse
  <code>"\\"</code> correctly. Have <code>jumpToLine</code> work on
  line handles, and add <code>cursorLine</code> function to fetch the
  line handle where the cursor currently is. Add new
  <code>setStylesheet</code> function to switch style-sheets in a
  running editor.</p>
 
  <p class="rel">01-03-2010: <a
  href="http://codemirror.net/codemirror-0.66.zip">Version
  0.66</a>:</p>
  <p class="rel-note">Adds <code>removeLine</code> method to API.
  Introduces the <a href="contrib/plsql/index.html">PLSQL parser</a>.
  Marks XML errors by adding (rather than replacing) a CSS class, so
  that they can be disabled by modifying their style. Fixes several
  selection bugs, and a number of small glitches.</p>
 
  <p class="rel">12-11-2009: <a
  href="http://codemirror.net/codemirror-0.65.zip">Version
  0.65</a>:</p>
  <p class="rel-note">Add support for having both line-wrapping and
  line-numbers turned on, make paren-highlighting style customisable
  (<code>markParen</code> and <code>unmarkParen</code> config
  options), work around a selection bug that Opera
  <em>re</em>introduced in version 10.</p>
 
  <p class="rel">23-10-2009: <a
  href="http://codemirror.net/codemirror-0.64.zip">Version
  0.64</a>:</p>
  <p class="rel-note">Solves some issues introduced by the
  paste-handling changes from the previous release. Adds
  <code>setSpellcheck</code>, <code>setTextWrapping</code>,
  <code>setIndentUnit</code>, <code>setUndoDepth</code>,
  <code>setTabMode</code>, and <code>setLineNumbers</code> to
  customise a running editor. Introduces an <a
  href="contrib/sql/index.html">SQL</a> parser. Fixes a few small
  problems in the <a href="contrib/python/index.html">Python</a>
  parser. And, as usual, add workarounds for various newly discovered
  browser incompatibilities.</p>
 
  <p class="rel"><em>31-08-2009</em>: <a
  href="http://codemirror.net/codemirror-0.63.zip">Version
  0.63</a>:</p>
  <p class="rel-note"> Overhaul of paste-handling (less fragile), fixes for several
  serious IE8 issues (cursor jumping, end-of-document bugs) and a number
  of small problems.</p>
 
  <p class="rel"><em>30-05-2009</em>: <a
  href="http://codemirror.net/codemirror-0.62.zip">Version
  0.62</a>:</p>
  <p class="rel-note">Introduces <a href="contrib/python/index.html">Python</a>
  and <a href="contrib/lua/index.html">Lua</a> parsers. Add
  <code>setParser</code> (on-the-fly mode changing) and
  <code>clearHistory</code> methods. Make parsing passes time-based
  instead of lines-based (see the <code>passTime</code> option).</p>
 
  </body></html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Reporting Bugs</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style>li { margin-top: 1em; }</style>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* Reporting bugs
  effectively */
  </pre>
 
  <div class="left">
 
  <p>So you found a problem in CodeMirror. By all means, report it! Bug
  reports from users are the main drive behind improvements to
  CodeMirror. But first, please read over these points:</p>
 
  <ol>
  <li>CodeMirror is maintained by volunteers. They don't owe you
  anything, so be polite. Reports with an indignant or belligerent
  tone tend to be moved to the bottom of the pile.</li>
 
  <li>Include information about <strong>the browser in which the
  problem occurred</strong>. Even if you tested several browsers, and
  the problem occurred in all of them, mention this fact in the bug
  report. Also include browser version numbers and the operating
  system that you're on.</li>
 
  <li>Mention which release of CodeMirror you're using. Preferably,
  try also with the current development snapshot, to ensure the
  problem has not already been fixed.</li>
 
  <li>Mention very precisely what went wrong. "X is broken" is not a
  good bug report. What did you expect to happen? What happened
  instead? Describe the exact steps a maintainer has to take to make
  the problem occur. We can not fix something that we can not
  observe.</li>
 
  <li>If the problem can not be reproduced in any of the demos
  included in the CodeMirror distribution, please provide an HTML
  document that demonstrates the problem. The best way to do this is
  to go to <a href="http://jsbin.com/ihunin/edit">jsbin.com</a>, enter
  it there, press save, and include the resulting link in your bug
  report.</li>
  </ol>
 
  </div>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Upgrading to v2.2</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="baboon.png" class="logo" alt="logo"/>/* Upgrading to v2.2
  */
  </pre>
 
  <div class="left">
 
  <p>There are a few things in the 2.2 release that require some care
  when upgrading.</p>
 
  <h2>No more default.css</h2>
 
  <p>The default theme is now included
  in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>, so
  you do not have to included it separately anymore. (It was tiny, so
  even if you're not using it, the extra data overhead is negligible.)
 
  <h2>Different key customization</h2>
 
  <p>CodeMirror has moved to a system
  where <a href="manual.html#option_keyMap">keymaps</a> are used to
  bind behavior to keys. This means <a href="../demo/emacs.html">custom
  bindings</a> are now possible.</p>
 
  <p>Three options that influenced key
  behavior, <code>tabMode</code>, <code>enterMode</code>,
  and <code>smartHome</code>, are no longer supported. Instead, you can
  provide custom bindings to influence the way these keys act. This is
  done through the
  new <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
  option, which can hold an object mapping key names to functionality. A
  simple example would be:</p>
 
  <pre> extraKeys: {
  "Ctrl-S": function(instance) { saveText(instance.getValue()); },
  "Ctrl-/": "undo"
  }</pre>
 
  <p>Keys can be mapped either to functions, which will be given the
  editor instance as argument, or to strings, which are mapped through
  functions through the <code>CodeMirror.commands</code> table, which
  contains all the built-in editing commands, and can be inspected and
  extended by external code.</p>
 
  <p>By default, the <code>Home</code> key is bound to
  the <code>"goLineStartSmart"</code> command, which moves the cursor to
  the first non-whitespace character on the line. You can set do this to
  make it always go to the very start instead:</p>
 
  <pre> extraKeys: {"Home": "goLineStart"}</pre>
 
  <p>Similarly, <code>Enter</code> is bound
  to <code>"newLineAndIndent"</code> by default. You can bind it to
  something else to get different behavior. To disable special handling
  completely and only get a newline character inserted, you can bind it
  to <code>false</code>:</p>
 
  <pre> extraKeys: {"Enter": false}</pre>
 
  <p>The same works for <code>Tab</code>. If you don't want CodeMirror
  to handle it, bind it to <code>false</code>. The default behaviour is
  to indent the current line more (<code>"indentMore"</code> command),
  and indent it less when shift is held (<code>"indentLess"</code>).
  There are also <code>"indentAuto"</code> (smart indent)
  and <code>"insertTab"</code> commands provided for alternate
  behaviors. Or you can write your own handler function to do something
  different altogether.</p>
 
  <h2>Tabs</h2>
 
  <p>Handling of tabs changed completely. The display width of tabs can
  now be set with the <code>tabSize</code> option, and tabs can
  be <a href="../demo/visibletabs.html">styled</a> by setting CSS rules
  for the <code>cm-tab</code> class.</p>
 
  <p>The default width for tabs is now 4, as opposed to the 8 that is
  hard-wired into browsers. If you are relying on 8-space tabs, make
  sure you explicitly set <code>tabSize: 8</code> in your options.</p>
 
  </div>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror</title>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
  <link rel="stylesheet" type="text/css" href="doc/docs.css"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>
  </head>
  <body>
 
  <h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
 
  <pre class="grey">
  <img src="doc/baboon.png" class="logo" alt="logo"/>/* In-browser code editing
  made bearable */
  </pre>
 
  <div class="clear"><div class="left blk">
 
  <p style="margin-top: 0">CodeMirror is a JavaScript library that can
  be used to create a relatively pleasant editor interface for
  code-like content &#x2015; computer programs, HTML markup, and
  similar. If a mode has been written for the language you are
  editing, the code will be coloured, and the editor will optionally
  help you with indentation.</p>
 
  <p>This is the project page for CodeMirror 2, the currently more
  actively developed, and recommended
  version. <a href="1/index.html">CodeMirror 1</a> is still available
  from here.</p>
 
  <div class="clear"><div class="left1 blk">
 
  <h2 style="margin-top: 0">Supported modes:</h2>
 
  <ul>
  <li><a href="mode/clike/index.html">C, Java, C#, and similar</a></li>
  <li><a href="mode/clojure/index.html">Clojure</a></li>
  <li><a href="mode/coffeescript/index.html">CoffeeScript</a></li>
  <li><a href="mode/css/index.html">CSS</a></li>
  <li><a href="mode/diff/index.html">diff</a></li>
  <li><a href="mode/groovy/index.html">Groovy</a></li>
  <li><a href="mode/haskell/index.html">Haskell</a></li>
  <li><a href="mode/htmlembedded/index.html">HTML embedded scripts</a></li>
  <li><a href="mode/htmlmixed/index.html">HTML mixed-mode</a></li>
  <li><a href="mode/javascript/index.html">JavaScript</a></li>
  <li><a href="mode/jinja2/index.html">Jinja2</a></li>
  <li><a href="mode/lua/index.html">Lua</a></li>
  <li><a href="mode/markdown/index.html">Markdown</a> (<a href="mode/gfm/index.html">Github-flavour</a>)</li>
  <li><a href="mode/ntriples/index.html">NTriples</a></li>
  <li><a href="mode/pascal/index.html">Pascal</a></li>
  <li><a href="mode/perl/index.html">Perl</a></li>
  <li><a href="mode/php/index.html">PHP</a></li>
  <li><a href="mode/plsql/index.html">PL/SQL</a></li>
  <li><a href="mode/python/index.html">Python</a></li>
  <li><a href="mode/r/index.html">R</a></li>
  <li>RPM <a href="mode/rpm/spec/index.html">spec</a> and <a href="mode/rpm/changes/index.html">changelog</a></li>
  <li><a href="mode/rst/index.html">reStructuredText</a></li>
  <li><a href="mode/ruby/index.html">Ruby</a></li>
  <li><a href="mode/rust/index.html">Rust</a></li>
  <li><a href="mode/scheme/index.html">Scheme</a></li>
  <li><a href="mode/smalltalk/index.html">Smalltalk</a></li>
  <li><a href="mode/sparql/index.html">SPARQL</a></li>
  <li><a href="mode/stex/index.html">sTeX, LaTeX</a></li>
  <li><a href="mode/tiddlywiki/index.html">Tiddlywiki</a></li>
  <li><a href="mode/velocity/index.html">Velocity</a></li>
  <li><a href="mode/xml/index.html">XML/HTML</a> (<a href="mode/xmlpure/index.html">alternative XML</a>)</li>
  <li><a href="mode/yaml/index.html">YAML</a></li>
  </ul>
 
  </div><div class="left2 blk">
 
  <h2 style="margin-top: 0">Usage demos:</h2>
 
  <ul>
  <li><a href="demo/complete.html">Autocompletion</a></li>
  <li><a href="demo/mustache.html">Mode overlays</a></li>
  <li><a href="demo/search.html">Search/replace</a></li>
  <li><a href="demo/folding.html">Code folding</a></li>
  <li><a href="demo/preview.html">HTML editor with preview</a></li>
  <li><a href="demo/resize.html">Auto-resizing editor</a></li>
  <li><a href="demo/marker.html">Setting breakpoints</a></li>
  <li><a href="demo/activeline.html">Highlighting the current line</a></li>
  <li><a href="demo/theme.html">Theming</a></li>
  <li><a href="demo/runmode.html">Stand-alone highlighting</a></li>
  <li><a href="demo/fullscreen.html">Full-screen editing</a></li>
  <li><a href="demo/changemode.html">Mode auto-changing</a></li>
  <li><a href="demo/visibletabs.html">Visible tabs</a></li>
  <li><a href="demo/formatting.html">Autoformatting of code</a></li>
  <li><a href="demo/emacs.html">Emacs keybindings</a></li>
  <li><a href="demo/vim.html">Vim keybindings</a></li>
  </ul>
 
  <h2>Real-world uses:</h2>
 
  <ul>
  <li><a href="http://jsbin.com">jsbin.com</a> (JS playground)</li>
  <li><a href="http://buzzard.ups.edu/">Sage demo</a> (math system)</li>
  <li><a href="http://www.sourcelair.com/">sourceLair</a> (online IDE)</li>
  <li><a href="http://eloquentjavascript.net/chapter1.html">Eloquent JavaScript</a> (book)</a></li>
  <li><a href="http://www.mergely.com/">Mergely</a> (interactive diffing)</li>
  <li><a href="http://paperjs.org/">Paper.js</a> (graphics scripting)</li>
  <li><a href="http://www.wescheme.org/">WeScheme</a> (learning tool)</li>
  <li><a href="http://webglplayground.net/">WebGL playground</a></li>
  <li><a href="http://ql.io/">ql.io</a> (http API query helper)</li>
  <li><a href="http://elm-lang.org/Examples.elm">Elm language examples</a></li>
  </ul>
 
  </div></div>
 
  <h2 id="code">Getting the code</h2>
 
  <p>All of CodeMirror is released under a <a
  href="LICENSE">MIT-style</a> license. To get it, you can download
  the <a href="http://codemirror.net/codemirror.zip">latest
  release</a> or the current <a
  href="http://codemirror.net/codemirror2-latest.zip">development
  snapshot</a> as zip files. To create a custom minified script file,
  you can use the <a href="doc/compress.html">compression API</a>.</p>
 
  <p>We use <a href="http://git-scm.com/">git</a> for version control.
  The main repository can be fetched in this way:</p>
 
  <pre class="code">git clone http://marijnhaverbeke.nl/git/codemirror2</pre>
 
  <p>CodeMirror can also be found on GitHub at <a
  href="http://github.com/marijnh/CodeMirror2">marijnh/CodeMirror2</a>.
  If you plan to hack on the code and contribute patches, the best way
  to do it is to create a GitHub fork, and send pull requests.</p>
 
  <h2 id="documention">Documentation</h2>
 
  <p>The <a href="doc/manual.html">manual</a> is your first stop for
  learning how to use this library. It starts with a quick explanation
  of how to use the editor, and then describes the API in detail.</p>
 
  <p>For those who want to learn more about the code, there is
  an <a href="doc/internals.html">overview of the internals</a> available.
  The <a href="http://github.com/marijnh/CodeMirror2">source code</a>
  itself is, for the most part, also well commented.</p>
 
  <h2 id="support">Support and bug reports</h2>
 
  <p>There is
  a <a href="http://groups.google.com/group/codemirror">Google
  group</a> (a sort of mailing list/newsgroup thing) for discussion
  and news related to CodeMirror. When reporting a bug,
  <a href="doc/reporting.html">read this first</a>. If you have
  a <a href="http://github.com">github</a> account,
  simply <a href="http://github.com/marijnh/CodeMirror2/issues">open
  an issue there</a>. Otherwise, post something to
  the <a href="http://groups.google.com/group/codemirror">group</a>,
  or e-mail me directly: <a href="mailto:marijnh@gmail.com">Marijn
  Haverbeke</a>.</p>
 
  <h2 id="supported">Supported browsers</h2>
 
  <p>The following browsers are able to run CodeMirror:</p>
 
  <ul>
  <li>Firefox 2 or higher</li>
  <li>Chrome, any version</li>
  <li>Safari 3 or higher</li>
  <li>Internet Explorer 6 or higher</li>
  <li>Opera 9 or higher (with some key-handling problems on OS X)</li>
  </ul>
 
  <p>I am not actively testing against every new browser release, and
  vendors have a habit of introducing bugs all the time, so I am
  relying on the community to tell me when something breaks.
  See <a href="#support">here</a> for information on how to contact
  me.</p>
 
  <h2 id="commercial">Commercial support</h2>
 
  <p>CodeMirror is developed and maintained by me, Marijn Haverbeke,
  in my own time. If your company is getting value out of CodeMirror,
  please consider purchasing a support contract.</p>
 
  <ul>
  <li>You'll be funding further work on CodeMirror.</li>
  <li>You ensure that you get a quick response when you have a
  problem, even when I am otherwise busy.</li>
  </ul>
 
  <p>CodeMirror support contracts exist in two
  forms—<strong>basic</strong> at €100 per month,
  and <strong>premium</strong> at €500 per
  month. <a href="mailto:marijnh@gmail.com">Contact me</a> for further
  information.</p>
 
  </div>
 
  <div class="right blk">
 
  <a href="http://codemirror.net/codemirror.zip" class="download">Download the latest release</a>
 
  <h2>Support CodeMirror</h2>
 
  <ul>
  <li>Donate
  (<span onclick="document.getElementById('paypal').submit();"
  class="quasilink">Paypal</span>
  or <span onclick="document.getElementById('bankinfo').style.display = 'block';"
  class="quasilink">bank</span>)</li>
  <li>Purchase <a href="#commercial">commercial support</a></li>
  </ul>
 
  <p id="bankinfo" style="display: none;">
  Bank: <i>Rabobank</i><br/>
  Country: <i>Netherlands</i><br/>
  SWIFT: <i>RABONL2U</i><br/>
  Account: <i>147850770</i><br/>
  Name: <i>Marijn Haverbeke</i><br/>
  IBAN: <i>NL26 RABO 0147 8507 70</i>
  </p>
 
  <h2>Releases:</h2>
 
  <p class="rel">20-12-2011: <a href="http://codemirror.net/codemirror-2.2.zip">Version 2.2</a>:</p>
 
  <ul class="rel-note">
  <li>Slightly incompatible API changes. Read <a href="doc/upgrade_v2.2.html">this</a>.</li>
  <li>New approach
  to <a href="doc/manual.html#option_extraKeys">binding</a> keys,
  support for <a href="doc/manual.html#option_keyMap">custom
  bindings</a>.</li>
  <li>Support for overwrite (insert).</li>
  <li><a href="doc/manual.html#option_tabSize">Custom-width</a>
  and <a href="demo/visibletabs.html">stylable</a> tabs.</li>
  <li>Moved more code into <a href="doc/manual.html#addons">add-on scripts</a>.</li>
  <li>Support for sane vertical cursor movement in wrapped lines.</li>
  <li>More reliable handling of
  editing <a href="doc/manual.html#markText">marked text</a>.</li>
  <li>Add minimal <a href="demo/emacs.html">emacs</a>
  and <a href="demo/vim.html">vim</a> bindings.</li>
  <li>Rename <code>coordsFromIndex</code>
  to <a href="doc/manual.html#posFromIndex"><code>posFromIndex</code></a>,
  add <a href="doc/manual.html#indexFromPos"><code>indexFromPos</code></a>
  method.</li>
  </ul>
 
  <p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.18.zip">Version 2.18</a>:</p>
  <p class="rel-note">Fixes <code>TextMarker.clear</code>, which is broken in 2.17.</p>
 
  <p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.17.zip">Version 2.17</a>:</p>
  <ul class="rel-note">
  <li>Add support for <a href="doc/manual.html#option_lineWrapping">line
  wrapping</a> and <a href="doc/manual.html#hideLine">code
  folding</a>.</li>
  <li>Add <a href="mode/gfm/index.html">Github-style Markdown</a> mode.</li>
  <li>Add <a href="theme/monokai.css">Monokai</a>
  and <a href="theme/rubyblue.css">Rubyblue</a> themes.</li>
  <li>Add <a href="doc/manual.html#setBookmark"><code>setBookmark</code></a> method.</li>
  <li>Move some of the demo code into reusable components
  under <a href="lib/util/"><code>lib/util</code></a>.</li>
  <li>Make screen-coord-finding code faster and more reliable.</li>
  <li>Fix drag-and-drop in Firefox.</li>
  <li>Improve support for IME.</li>
  <li>Speed up content rendering.</li>
  <li>Fix browser's built-in search in Webkit.</li>
  <li>Make double- and triple-click work in IE.</li>
  <li>Various fixes to modes.</li>
  </ul>
 
  <p class="rel">27-10-2011: <a href="http://codemirror.net/codemirror-2.16.zip">Version 2.16</a>:</p>
  <ul class="rel-note">
  <li>Add <a href="mode/perl/index.html">Perl</a>, <a href="mode/rust/index.html">Rust</a>, <a href="mode/tiddlywiki/index.html">TiddlyWiki</a>, and <a href="mode/groovy/index.html">Groovy</a> modes.</li>
  <li>Dragging text inside the editor now moves, rather than copies.</li>
  <li>Add a <a href="doc/manual.html#coordsFromIndex"><code>coordsFromIndex</code></a> method.</li>
  <li><strong>API change</strong>: <code>setValue</code> now no longer clears history. Use <a href="doc/manual.html#clearHistory"><code>clearHistory</code></a> for that.</li>
  <li><strong>API change</strong>: <a href="doc/manual.html#markText"><code>markText</code></a> now
  returns an object with <code>clear</code> and <code>find</code>
  methods. Marked text is now more robust when edited.</li>
  <li>Fix editing code with tabs in Internet Explorer.</li>
  </ul>
 
  <p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.15.zip">Version 2.15</a>:</p>
  <p class="rel-note">Fix bug that snuck into 2.14: Clicking the
  character that currently has the cursor didn't re-focus the
  editor.</p>
 
  <p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.14.zip">Version 2.14</a>:</p>
  <ul class="rel-note">
  <li>Add <a href="mode/clojure/index.html">Clojure</a>, <a href="mode/pascal/index.html">Pascal</a>, <a href="mode/ntriples/index.html">NTriples</a>, <a href="mode/jinja2/index.html">Jinja2</a>, and <a href="mode/markdown/index.html">Markdown</a> modes.</li>
  <li>Add <a href="theme/cobalt.css">Cobalt</a> and <a href="theme/eclipse.css">Eclipse</a> themes.</li>
  <li>Add a <a href="doc/manual.html#option_fixedGutter"><code>fixedGutter</code></a> option.</li>
  <li>Fix bug with <code>setValue</code> breaking cursor movement.</li>
  <li>Make gutter updates much more efficient.</li>
  <li>Allow dragging of text out of the editor (on modern browsers).</li>
  </ul>
 
  <p class="rel">23-08-2011: <a href="http://codemirror.net/codemirror-2.13.zip">Version 2.13</a>:</p>
  <ul class="rel-note">
  <li>Add <a href="mode/ruby/index.html">Ruby</a>, <a href="mode/r/index.html">R</a>, <a href="mode/coffeescript/index.html">CoffeeScript</a>, and <a href="mode/velocity/index.html">Velocity</a> modes.</li>
  <li>Add <a href="doc/manual.html#getGutterElement"><code>getGutterElement</code></a> to API.</li>
  <li>Several fixes to scrolling and positioning.</li>
  <li>Add <a href="doc/manual.html#option_smartHome"><code>smartHome</code></a> option.</li>
  <li>Add an experimental <a href="mode/xmlpure/index.html">pure XML</a> mode.</li>
  </ul>
 
  <p class="rel">25-07-2011: <a href="http://codemirror.net/codemirror-2.12.zip">Version 2.12</a>:</p>
  <ul class="rel-note">
  <li>Add a <a href="mode/sparql/index.html">SPARQL</a> mode.</li>
  <li>Fix bug with cursor jumping around in an unfocused editor in IE.</li>
  <li>Allow key and mouse events to bubble out of the editor. Ignore widget clicks.</li>
  <li>Solve cursor flakiness after undo/redo.</li>
  <li>Fix block-reindent ignoring the last few lines.</li>
  <li>Fix parsing of multi-line attrs in XML mode.</li>
  <li>Use <code>innerHTML</code> for HTML-escaping.</li>
  <li>Some fixes to indentation in C-like mode.</li>
  <li>Shrink horiz scrollbars when long lines removed.</li>
  <li>Fix width feedback loop bug that caused the width of an inner DIV to shrink.</li>
  </ul>
 
  <p class="rel">04-07-2011: <a href="http://codemirror.net/codemirror-2.11.zip">Version 2.11</a>:</p>
  <ul class="rel-note">
  <li>Add a <a href="mode/scheme/index.html">Scheme mode</a>.</li>
  <li>Add a <code>replace</code> method to search cursors, for cursor-preserving replacements.</li>
  <li>Make the <a href="mode/clike/index.html">C-like mode</a> mode more customizeable.</li>
  <li>Update XML mode to spot mismatched tags.</li>
  <li>Add <code>getStateAfter</code> API and <code>compareState</code> mode API methods for finer-grained mode magic.</li>
  <li>Add a <code>getScrollerElement</code> API method to manipulate the scrolling DIV.</li>
  <li>Fix drag-and-drop for Firefox.</li>
  <li>Add a C# configuration for the <a href="mode/clike/index.html">C-like mode</a>.</li>
  <li>Add <a href="demo/fullscreen.html">full-screen editing</a> and <a href="demo/changemode.html">mode-changing</a> demos.</li>
  </ul>
 
  <p><a href="doc/oldrelease.html">Older releases...</a></p>
 
  </div></div>
 
  <div style="height: 2em">&nbsp;</div>
 
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paypal">
  <input type="hidden" name="cmd" value="_s-xclick"/>
  <input type="hidden" name="hosted_button_id" value="3FVHS5FGUY7CC"/>
  </form>
 
  </body>
  </html>
 
 
  // TODO number prefixes
  (function() {
  // Really primitive kill-ring implementation.
  var killRing = [];
  function addToRing(str) {
  killRing.push(str);
  if (killRing.length > 50) killRing.shift();
  }
  function getFromRing() { return killRing[killRing.length - 1] || ""; }
  function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
 
  CodeMirror.keyMap.emacs = {
  "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
  "Ctrl-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");},
  "Ctrl-Alt-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");},
  "Alt-W": function(cm) {addToRing(cm.getSelection());},
  "Ctrl-Y": function(cm) {cm.replaceSelection(getFromRing());},
  "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());},
  "Ctrl-/": "undo", "Shift-Ctrl--": "undo", "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
  "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
  "Ctrl-Z": "undo", "Cmd-Z": "undo",
  fallthrough: ["basic", "emacsy"]
  };
 
  CodeMirror.keyMap["emacs-Ctrl-X"] = {
  "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": "undo", "K": "close",
  auto: "emacs", catchall: function(cm) {/*ignore*/}
  };
  })();
 
  (function() {
  var count = "";
  function pushCountDigit(digit) { return function(cm) {count += digit;} }
  function popCount() { var i = parseInt(count); count = ""; return i || 1; }
  function countTimes(func) {
  if (typeof func == "string") func = CodeMirror.commands[func];
  return function(cm) { for (var i = 0, c = popCount(); i < c; ++i) func(cm); }
  }
 
  function iterObj(o, f) {
  for (var prop in o) if (o.hasOwnProperty(prop)) f(prop, o[prop]);
  }
 
  var word = [/\w/, /[^\w\s]/], bigWord = [/\S/];
  function findWord(line, pos, dir, regexps) {
  var stop = 0, next = -1;
  if (dir > 0) { stop = line.length; next = 0; }
  var start = stop, end = stop;
  // Find bounds of next one.
  outer: for (; pos != stop; pos += dir) {
  for (var i = 0; i < regexps.length; ++i) {
  if (regexps[i].test(line.charAt(pos + next))) {
  start = pos;
  for (; pos != stop; pos += dir) {
  if (!regexps[i].test(line.charAt(pos + next))) break;
  }
  end = pos;
  break outer;
  }
  }
  }
  return {from: Math.min(start, end), to: Math.max(start, end)};
  }
  function moveToWord(cm, regexps, dir, where) {
  var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line), word;
  while (true) {
  word = findWord(line, ch, dir, regexps);
  ch = word[where == "end" ? "to" : "from"];
  if (ch == cur.ch && word.from != word.to) ch = word[dir < 0 ? "from" : "to"];
  else break;
  }
  cm.setCursor(cur.line, word[where == "end" ? "to" : "from"], true);
  }
 
  var map = CodeMirror.keyMap.vim = {
  "0": function(cm) {count.length > 0 ? pushCountDigit("0")(cm) : CodeMirror.commands.goLineStart(cm);},
  "I": function(cm) {popCount(); cm.setOption("keyMap", "vim-insert");},
  "G": function(cm) {cm.setOption("keyMap", "vim-prefix-g");},
  catchall: function(cm) {/*ignore*/}
  };
  // Add bindings for number keys
  for (var i = 1; i < 10; ++i) map[i] = pushCountDigit(i);
  // Add bindings that are influenced by number keys
  iterObj({"H": "goColumnLeft", "L": "goColumnRight", "J": "goLineDown", "K": "goLineUp",
  "Left": "goColumnLeft", "Right": "goColumnRight", "Down": "goLineDown", "Up": "goLineUp",
  "Backspace": "goCharLeft", "Space": "goCharRight",
  "B": function(cm) {moveToWord(cm, word, -1, "end");},
  "E": function(cm) {moveToWord(cm, word, 1, "end");},
  "W": function(cm) {moveToWord(cm, word, 1, "start");},
  "Shift-B": function(cm) {moveToWord(cm, bigWord, -1, "end");},
  "Shift-E": function(cm) {moveToWord(cm, bigWord, 1, "end");},
  "Shift-W": function(cm) {moveToWord(cm, bigWord, 1, "start");},
  "U": "undo", "Ctrl-R": "redo", "Shift-4": "goLineEnd"},
  function(key, cmd) { map[key] = countTimes(cmd); });
 
  CodeMirror.keyMap["vim-prefix-g"] = {
  "E": countTimes(function(cm) { moveToWord(cm, word, -1, "start");}),
  "Shift-E": countTimes(function(cm) { moveToWord(cm, bigWord, -1, "start");}),
  auto: "vim", catchall: function(cm) {/*ignore*/}
  };
 
  CodeMirror.keyMap["vim-insert"] = {
  "Esc": function(cm) {cm.setOption("keyMap", "vim");},
  fallthrough: ["default"]
  };
  })();
 
  .CodeMirror {
  line-height: 1em;
  font-family: monospace;
  }
 
  .CodeMirror-scroll {
  overflow: auto;
  height: 300px;
  /* This is needed to prevent an IE[67] bug where the scrolled content
  is visible outside of the scrolling box. */
  position: relative;
  }
 
  .CodeMirror-gutter {
  position: absolute; left: 0; top: 0;
  z-index: 10;
  background-color: #f7f7f7;
  border-right: 1px solid #eee;
  min-width: 2em;
  height: 100%;
  }
  .CodeMirror-gutter-text {
  color: #aaa;
  text-align: right;
  padding: .4em .2em .4em .4em;
  white-space: pre !important;
  }
  .CodeMirror-lines {
  padding: .4em;
  }
 
  .CodeMirror pre {
  -moz-border-radius: 0;
  -webkit-border-radius: 0;
  -o-border-radius: 0;
  border-radius: 0;
  border-width: 0; margin: 0; padding: 0; background: transparent;
  font-family: inherit;
  font-size: inherit;
  padding: 0; margin: 0;
  white-space: pre;
  word-wrap: normal;
  }
 
  .CodeMirror-wrap pre {
  word-wrap: break-word;
  white-space: pre-wrap;
  }
  .CodeMirror-wrap .CodeMirror-scroll {
  overflow-x: hidden;
  }
 
  .CodeMirror textarea {
  outline: none !important;
  }
 
  .CodeMirror pre.CodeMirror-cursor {
  z-index: 10;
  position: absolute;
  visibility: hidden;
  border-left: 1px solid black;
  }
  .CodeMirror-focused pre.CodeMirror-cursor {
  visibility: visible;
  }
 
  span.CodeMirror-selected { background: #d9d9d9; }
  .CodeMirror-focused span.CodeMirror-selected { background: #d2dcf8; }
 
  .CodeMirror-searching {background: #ffa;}
 
  /* Default theme */
 
  .cm-s-default span.cm-keyword {color: #708;}
  .cm-s-default span.cm-atom {color: #219;}
  .cm-s-default span.cm-number {color: #164;}
  .cm-s-default span.cm-def {color: #00f;}
  .cm-s-default span.cm-variable {color: black;}
  .cm-s-default span.cm-variable-2 {color: #05a;}
  .cm-s-default span.cm-variable-3 {color: #085;}
  .cm-s-default span.cm-property {color: black;}
  .cm-s-default span.cm-operator {color: black;}
  .cm-s-default span.cm-comment {color: #a50;}
  .cm-s-default span.cm-string {color: #a11;}
  .cm-s-default span.cm-string-2 {color: #f50;}
  .cm-s-default span.cm-meta {color: #555;}
  .cm-s-default span.cm-error {color: #f00;}
  .cm-s-default span.cm-qualifier {color: #555;}
  .cm-s-default span.cm-builtin {color: #30a;}
  .cm-s-default span.cm-bracket {color: #cc7;}
  .cm-s-default span.cm-tag {color: #170;}
  .cm-s-default span.cm-attribute {color: #00c;}
  .cm-s-default span.cm-header {color: #a0a;}
  .cm-s-default span.cm-quote {color: #090;}
  .cm-s-default span.cm-hr {color: #999;}
  .cm-s-default span.cm-link {color: #00c;}
 
  span.cm-header, span.cm-strong {font-weight: bold;}
  span.cm-em {font-style: italic;}
  span.cm-emstrong {font-style: italic; font-weight: bold;}
  span.cm-link {text-decoration: underline;}
 
  div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
  div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
 
  // CodeMirror version 2.2
  //
  // All functions that need access to the editor's state live inside
  // the CodeMirror function. Below that, at the bottom of the file,
  // some utilities are defined.
 
  // CodeMirror is the only global var we claim
  var CodeMirror = (function() {
  // This is the function that produces an editor instance. It's
  // closure is used to store the editor state.
  function CodeMirror(place, givenOptions) {
  // Determine effective options based on given values and defaults.
  var options = {}, defaults = CodeMirror.defaults;
  for (var opt in defaults)
  if (defaults.hasOwnProperty(opt))
  options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
 
  var targetDocument = options["document"];
  // The element in which the editor lives.
  var wrapper = targetDocument.createElement("div");
  wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
  // This mess creates the base DOM structure for the editor.
  wrapper.innerHTML =
  '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea
  '<textarea style="position: absolute; padding: 0; width: 1px;" wrap="off" ' +
  'autocorrect="off" autocapitalize="off"></textarea></div>' +
  '<div class="CodeMirror-scroll" tabindex="-1">' +
  '<div style="position: relative">' + // Set to the height of the text, causes scrolling
  '<div style="position: relative">' + // Moved around its parent to cover visible view
  '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
  // Provides positioning relative to (visible) text origin
  '<div class="CodeMirror-lines"><div style="position: relative">' +
  '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden"></div>' +
  '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
  '<div></div>' + // This DIV contains the actual code
  '</div></div></div></div></div>';
  if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
  // I've never seen more elegant code in my life.
  var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
  scroller = wrapper.lastChild, code = scroller.firstChild,
  mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild,
  lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild,
  cursor = measure.nextSibling, lineDiv = cursor.nextSibling;
  themeChanged();
  // Needed to hide big blue blinking cursor on Mobile Safari
  if (/AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)) input.style.width = "0px";
  if (!webkit) lineSpace.draggable = true;
  if (options.tabindex != null) input.tabIndex = options.tabindex;
  if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
 
  // Check for problem with IE innerHTML not working when we have a
  // P (or similar) parent node.
  try { stringWidth("x"); }
  catch (e) {
  if (e.message.match(/runtime/i))
  e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
  throw e;
  }
 
  // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
  var poll = new Delayed(), highlight = new Delayed(), blinker;
 
  // mode holds a mode API object. doc is the tree of Line objects,
  // work an array of lines that should be parsed, and history the
  // undo history (instance of History constructor).
  var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
  loadMode();
  // The selection. These are always maintained to point at valid
  // positions. Inverted is used to remember that the user is
  // selecting bottom-to-top.
  var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
  // Selection-related flags. shiftSelecting obviously tracks
  // whether the user is holding shift.
  var shiftSelecting, lastClick, lastDoubleClick, draggingText, overwrite = false;
  // Variables used by startOperation/endOperation to track what
  // happened during the operation.
  var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
  gutterDirty, callbacks;
  // Current visible range (may be bigger than the view window).
  var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
  // bracketHighlighted is used to remember that a backet has been
  // marked.
  var bracketHighlighted;
  // Tracks the maximum line length so that the horizontal scrollbar
  // can be kept static when scrolling.
  var maxLine = "", maxWidth, tabText = computeTabText();
 
  // Initialize the content.
  operation(function(){setValue(options.value || ""); updateInput = false;})();
  var history = new History();
 
  // Register our event handlers.
  connect(scroller, "mousedown", operation(onMouseDown));
  connect(scroller, "dblclick", operation(onDoubleClick));
  connect(lineSpace, "dragstart", onDragStart);
  connect(lineSpace, "selectstart", e_preventDefault);
  // Gecko browsers fire contextmenu *after* opening the menu, at
  // which point we can't mess with it anymore. Context menu is
  // handled in onMouseDown for Gecko.
  if (!gecko) connect(scroller, "contextmenu", onContextMenu);
  connect(scroller, "scroll", function() {
  updateDisplay([]);
  if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
  if (options.onScroll) options.onScroll(instance);
  });
  connect(window, "resize", function() {updateDisplay(true);});
  connect(input, "keyup", operation(onKeyUp));
  connect(input, "input", fastPoll);
  connect(input, "keydown", operation(onKeyDown));
  connect(input, "keypress", operation(onKeyPress));
  connect(input, "focus", onFocus);
  connect(input, "blur", onBlur);
 
  connect(scroller, "dragenter", e_stop);
  connect(scroller, "dragover", e_stop);
  connect(scroller, "drop", operation(onDrop));
  connect(scroller, "paste", function(){focusInput(); fastPoll();});
  connect(input, "paste", fastPoll);
  connect(input, "cut", operation(function(){replaceSelection("");}));
 
  // IE throws unspecified error in certain cases, when
  // trying to access activeElement before onload
  var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
  if (hasFocus) setTimeout(onFocus, 20);
  else onBlur();
 
  function isLine(l) {return l >= 0 && l < doc.size;}
  // The instance object that we'll return. Mostly calls out to
  // local functions in the CodeMirror function. Some do some extra
  // range checking and/or clipping. operation is used to wrap the
  // call so that changes it makes are tracked, and the display is
  // updated afterwards.
  var instance = wrapper.CodeMirror = {
  getValue: getValue,
  setValue: operation(setValue),
  getSelection: getSelection,
  replaceSelection: operation(replaceSelection),
  focus: function(){focusInput(); onFocus(); fastPoll();},
  setOption: function(option, value) {
  var oldVal = options[option];
  options[option] = value;
  if (option == "mode" || option == "indentUnit") loadMode();
  else if (option == "readOnly" && value) {onBlur(); input.blur();}
  else if (option == "theme") themeChanged();
  else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
  else if (option == "tabSize") operation(tabsChanged)();
  if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme")
  operation(gutterChanged)();
  },
  getOption: function(option) {return options[option];},
  undo: operation(undo),
  redo: operation(redo),
  indentLine: operation(function(n, dir) {
  if (isLine(n)) indentLine(n, dir == null ? "smart" : dir ? "add" : "subtract");
  }),
  indentSelection: operation(indentSelected),
  historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
  clearHistory: function() {history = new History();},
  matchBrackets: operation(function(){matchBrackets(true);}),
  getTokenAt: operation(function(pos) {
  pos = clipPos(pos);
  return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch);
  }),
  getStateAfter: function(line) {
  line = clipLine(line == null ? doc.size - 1: line);
  return getStateBefore(line + 1);
  },
  cursorCoords: function(start){
  if (start == null) start = sel.inverted;
  return pageCoords(start ? sel.from : sel.to);
  },
  charCoords: function(pos){return pageCoords(clipPos(pos));},
  coordsChar: function(coords) {
  var off = eltOffset(lineSpace);
  return coordsChar(coords.x - off.left, coords.y - off.top);
  },
  markText: operation(markText),
  setBookmark: setBookmark,
  setMarker: operation(addGutterMarker),
  clearMarker: operation(removeGutterMarker),
  setLineClass: operation(setLineClass),
  hideLine: operation(function(h) {return setLineHidden(h, true);}),
  showLine: operation(function(h) {return setLineHidden(h, false);}),
  onDeleteLine: function(line, f) {
  if (typeof line == "number") {
  if (!isLine(line)) return null;
  line = getLine(line);
  }
  (line.handlers || (line.handlers = [])).push(f);
  return line;
  },
  lineInfo: lineInfo,
  addWidget: function(pos, node, scroll, vert, horiz) {
  pos = localCoords(clipPos(pos));
  var top = pos.yBot, left = pos.x;
  node.style.position = "absolute";
  code.appendChild(node);
  if (vert == "over") top = pos.y;
  else if (vert == "near") {
  var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
  hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
  if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
  top = pos.y - node.offsetHeight;
  if (left + node.offsetWidth > hspace)
  left = hspace - node.offsetWidth;
  }
  node.style.top = (top + paddingTop()) + "px";
  node.style.left = node.style.right = "";
  if (horiz == "right") {
  left = code.clientWidth - node.offsetWidth;
  node.style.right = "0px";
  } else {
  if (horiz == "left") left = 0;
  else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2;
  node.style.left = (left + paddingLeft()) + "px";
  }
  if (scroll)
  scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
  },
 
  lineCount: function() {return doc.size;},
  clipPos: clipPos,
  getCursor: function(start) {
  if (start == null) start = sel.inverted;
  return copyPos(start ? sel.from : sel.to);
  },
  somethingSelected: function() {return !posEq(sel.from, sel.to);},
  setCursor: operation(function(line, ch, user) {
  if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
  else setCursor(line, ch, user);
  }),
  setSelection: operation(function(from, to, user) {
  (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
  }),
  getLine: function(line) {if (isLine(line)) return getLine(line).text;},
  getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
  setLine: operation(function(line, text) {
  if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
  }),
  removeLine: operation(function(line) {
  if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
  }),
  replaceRange: operation(replaceRange),
  getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
 
  execCommand: function(cmd) {return commands[cmd](instance);},
  // Stuff used by commands, probably not much use to outside code.
  moveH: operation(moveH),
  deleteH: operation(deleteH),
  moveV: operation(moveV),
  toggleOverwrite: function() {overwrite = !overwrite;},
 
  posFromIndex: function(off) {
  var lineNo = 0, ch;
  doc.iter(0, doc.size, function(line) {
  var sz = line.text.length + 1;
  if (sz > off) { ch = off; return true; }
  off -= sz;
  ++lineNo;
  });
  return clipPos({line: lineNo, ch: ch});
  },
  indexFromPos: function (coords) {
  if (coords.line < 0 || coords.ch < 0) return 0;
  var index = coords.ch;
  doc.iter(0, coords.line, function (line) {
  index += line.text.length + 1;
  });
  return index;
  },
 
  operation: function(f){return operation(f)();},
  refresh: function(){updateDisplay(true);},
  getInputField: function(){return input;},
  getWrapperElement: function(){return wrapper;},
  getScrollerElement: function(){return scroller;},
  getGutterElement: function(){return gutter;}
  };
 
  function getLine(n) { return getLineAt(doc, n); }
  function updateLineHeight(line, height) {
  gutterDirty = true;
  var diff = height - line.height;
  for (var n = line; n; n = n.parent) n.height += diff;
  }
 
  function setValue(code) {
  var top = {line: 0, ch: 0};
  updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
  splitLines(code), top, top);
  updateInput = true;
  }
  function getValue(code) {
  var text = [];
  doc.iter(0, doc.size, function(line) { text.push(line.text); });
  return text.join("\n");
  }
 
  function onMouseDown(e) {
  setShift(e.shiftKey);
  // Check whether this is a click in a widget
  for (var n = e_target(e); n != wrapper; n = n.parentNode)
  if (n.parentNode == code && n != mover) return;
 
  // See if this is a click in the gutter
  for (var n = e_target(e); n != wrapper; n = n.parentNode)
  if (n.parentNode == gutterText) {
  if (options.onGutterClick)
  options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
  return e_preventDefault(e);
  }
 
  var start = posFromMouse(e);
 
  switch (e_button(e)) {
  case 3:
  if (gecko && !mac) onContextMenu(e);
  return;
  case 2:
  if (start) setCursor(start.line, start.ch, true);
  return;
  }
  // For button 1, if it was clicked inside the editor
  // (posFromMouse returning non-null), we have to adjust the
  // selection.
  if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
 
  if (!focused) onFocus();
 
  var now = +new Date;
  if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
  e_preventDefault(e);
  setTimeout(focusInput, 20);
  return selectLine(start.line);
  } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
  lastDoubleClick = {time: now, pos: start};
  e_preventDefault(e);
  return selectWordAt(start);
  } else { lastClick = {time: now, pos: start}; }
 
  var last = start, going;
  if (dragAndDrop && !posEq(sel.from, sel.to) &&
  !posLess(start, sel.from) && !posLess(sel.to, start)) {
  // Let the drag handler handle this.
  if (webkit) lineSpace.draggable = true;
  var up = connect(targetDocument, "mouseup", operation(function(e2) {
  if (webkit) lineSpace.draggable = false;
  draggingText = false;
  up();
  if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  e_preventDefault(e2);
  setCursor(start.line, start.ch, true);
  focusInput();
  }
  }), true);
  draggingText = true;
  return;
  }
  e_preventDefault(e);
  setCursor(start.line, start.ch, true);
 
  function extend(e) {
  var cur = posFromMouse(e, true);
  if (cur && !posEq(cur, last)) {
  if (!focused) onFocus();
  last = cur;
  setSelectionUser(start, cur);
  updateInput = false;
  var visible = visibleLines();
  if (cur.line >= visible.to || cur.line < visible.from)
  going = setTimeout(operation(function(){extend(e);}), 150);
  }
  }
 
  var move = connect(targetDocument, "mousemove", operation(function(e) {
  clearTimeout(going);
  e_preventDefault(e);
  extend(e);
  }), true);
  var up = connect(targetDocument, "mouseup", operation(function(e) {
  clearTimeout(going);
  var cur = posFromMouse(e);
  if (cur) setSelectionUser(start, cur);
  e_preventDefault(e);
  focusInput();
  updateInput = true;
  move(); up();
  }), true);
  }
  function onDoubleClick(e) {
  for (var n = e_target(e); n != wrapper; n = n.parentNode)
  if (n.parentNode == gutterText) return e_preventDefault(e);
  var start = posFromMouse(e);
  if (!start) return;
  lastDoubleClick = {time: +new Date, pos: start};
  e_preventDefault(e);
  selectWordAt(start);
  }
  function onDrop(e) {
  e.preventDefault();
  var pos = posFromMouse(e, true), files = e.dataTransfer.files;
  if (!pos || options.readOnly) return;
  if (files && files.length && window.FileReader && window.File) {
  function loadFile(file, i) {
  var reader = new FileReader;
  reader.onload = function() {
  text[i] = reader.result;
  if (++read == n) {
  pos = clipPos(pos);
  operation(function() {
  var end = replaceRange(text.join(""), pos, pos);
  setSelectionUser(pos, end);
  })();
  }
  };
  reader.readAsText(file);
  }
  var n = files.length, text = Array(n), read = 0;
  for (var i = 0; i < n; ++i) loadFile(files[i], i);
  }
  else {
  try {
  var text = e.dataTransfer.getData("Text");
  if (text) {
  var end = replaceRange(text, pos, pos);
  var curFrom = sel.from, curTo = sel.to;
  setSelectionUser(pos, end);
  if (draggingText) replaceRange("", curFrom, curTo);
  focusInput();
  }
  }
  catch(e){}
  }
  }
  function onDragStart(e) {
  var txt = getSelection();
  // This will reset escapeElement
  htmlEscape(txt);
  e.dataTransfer.setDragImage(escapeElement, 0, 0);
  e.dataTransfer.setData("Text", txt);
  }
  function handleKeyBinding(e) {
  var name = keyNames[e.keyCode], next = keyMap[options.keyMap].auto, bound, dropShift;
  if (name == null || e.altGraphKey) {
  if (next) options.keyMap = next;
  return null;
  }
  if (e.altKey) name = "Alt-" + name;
  if (e.ctrlKey) name = "Ctrl-" + name;
  if (e.metaKey) name = "Cmd-" + name;
  if (e.shiftKey && (bound = lookupKey("Shift-" + name, options.extraKeys, options.keyMap))) {
  dropShift = true;
  } else {
  bound = lookupKey(name, options.extraKeys, options.keyMap);
  }
  if (typeof bound == "string") {
  if (commands.propertyIsEnumerable(bound)) bound = commands[bound];
  else bound = null;
  }
  if (next && (bound || !isModifierKey(e))) options.keyMap = next;
  if (!bound) return false;
  if (dropShift) {
  var prevShift = shiftSelecting;
  shiftSelecting = null;
  bound(instance);
  shiftSelecting = prevShift;
  } else bound(instance);
  e_preventDefault(e);
  return true;
  }
  var lastStoppedKey = null;
  function onKeyDown(e) {
  if (!focused) onFocus();
  var code = e.keyCode;
  // IE does strange things with escape.
  if (ie && code == 27) { e.returnValue = false; }
  setShift(code == 16 || e.shiftKey);
  // First give onKeyEvent option a chance to handle this.
  if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  var handled = handleKeyBinding(e);
  if (window.opera) {
  lastStoppedKey = handled ? e.keyCode : null;
  // Opera has no cut event... we try to at least catch the key combo
  if (!handled && (mac ? e.metaKey : e.ctrlKey) && e.keyCode == 88)
  replaceSelection("");
  }
  }
  function onKeyPress(e) {
  if (window.opera && e.keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  if (window.opera && !e.which && handleKeyBinding(e)) return;
  if (options.electricChars && mode.electricChars) {
  var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode);
  if (mode.electricChars.indexOf(ch) > -1)
  setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
  }
  fastPoll();
  }
  function onKeyUp(e) {
  if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
  if (e.keyCode == 16) shiftSelecting = null;
  }
 
  function onFocus() {
  if (options.readOnly) return;
  if (!focused) {
  if (options.onFocus) options.onFocus(instance);
  focused = true;
  if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
  wrapper.className += " CodeMirror-focused";
  if (!leaveInputAlone) resetInput(true);
  }
  slowPoll();
  restartBlink();
  }
  function onBlur() {
  if (focused) {
  if (options.onBlur) options.onBlur(instance);
  focused = false;
  wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
  }
  clearInterval(blinker);
  setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
  }
 
  // Replace the range from from to to by the strings in newText.
  // Afterwards, set the selection to selFrom, selTo.
  function updateLines(from, to, newText, selFrom, selTo) {
  if (history) {
  var old = [];
  doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
  history.addChange(from.line, newText.length, old);
  while (history.done.length > options.undoDepth) history.done.shift();
  }
  updateLinesNoUndo(from, to, newText, selFrom, selTo);
  }
  function unredoHelper(from, to) {
  var change = from.pop();
  if (change) {
  var replaced = [], end = change.start + change.added;
  doc.iter(change.start, end, function(line) { replaced.push(line.text); });
  to.push({start: change.start, added: change.old.length, old: replaced});
  var pos = clipPos({line: change.start + change.old.length - 1,
  ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
  updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
  updateInput = true;
  }
  }
  function undo() {unredoHelper(history.done, history.undone);}
  function redo() {unredoHelper(history.undone, history.done);}
 
  function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
  var recomputeMaxLength = false, maxLineLength = maxLine.length;
  if (!options.lineWrapping)
  doc.iter(from.line, to.line, function(line) {
  if (line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
  });
  if (from.line != to.line || newText.length > 1) gutterDirty = true;
 
  var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
  // First adjust the line structure, taking some care to leave highlighting intact.
  if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
  // This is a whole-line replace. Treated specially to make
  // sure line objects move the way they are supposed to.
  var added = [], prevLine = null;
  if (from.line) {
  prevLine = getLine(from.line - 1);
  prevLine.fixMarkEnds(lastLine);
  } else lastLine.fixMarkStarts();
  for (var i = 0, e = newText.length - 1; i < e; ++i)
  added.push(Line.inheritMarks(newText[i], prevLine));
  if (nlines) doc.remove(from.line, nlines, callbacks);
  if (added.length) doc.insert(from.line, added);
  } else if (firstLine == lastLine) {
  if (newText.length == 1)
  firstLine.replace(from.ch, to.ch, newText[0]);
  else {
  lastLine = firstLine.split(to.ch, newText[newText.length-1]);
  firstLine.replace(from.ch, null, newText[0]);
  firstLine.fixMarkEnds(lastLine);
  var added = [];
  for (var i = 1, e = newText.length - 1; i < e; ++i)
  added.push(Line.inheritMarks(newText[i], firstLine));
  added.push(lastLine);
  doc.insert(from.line + 1, added);
  }
  } else if (newText.length == 1) {
  firstLine.replace(from.ch, null, newText[0]);
  lastLine.replace(null, to.ch, "");
  firstLine.append(lastLine);
  doc.remove(from.line + 1, nlines, callbacks);
  } else {
  var added = [];
  firstLine.replace(from.ch, null, newText[0]);
  lastLine.replace(null, to.ch, newText[newText.length-1]);
  firstLine.fixMarkEnds(lastLine);
  for (var i = 1, e = newText.length - 1; i < e; ++i)
  added.push(Line.inheritMarks(newText[i], firstLine));
  if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
  doc.insert(from.line + 1, added);
  }
  if (options.lineWrapping) {
  var perLine = scroller.clientWidth / charWidth() - 3;
  doc.iter(from.line, from.line + newText.length, function(line) {
  if (line.hidden) return;
  var guess = Math.ceil(line.text.length / perLine) || 1;
  if (guess != line.height) updateLineHeight(line, guess);
  });
  } else {
  doc.iter(from.line, i + newText.length, function(line) {
  var l = line.text;
  if (l.length > maxLineLength) {
  maxLine = l; maxLineLength = l.length; maxWidth = null;
  recomputeMaxLength = false;
  }
  });
  if (recomputeMaxLength) {
  maxLineLength = 0; maxLine = ""; maxWidth = null;
  doc.iter(0, doc.size, function(line) {
  var l = line.text;
  if (l.length > maxLineLength) {
  maxLineLength = l.length; maxLine = l;
  }
  });
  }
  }
 
  // Add these lines to the work array, so that they will be
  // highlighted. Adjust work lines if lines were added/removed.
  var newWork = [], lendiff = newText.length - nlines - 1;
  for (var i = 0, l = work.length; i < l; ++i) {
  var task = work[i];
  if (task < from.line) newWork.push(task);
  else if (task > to.line) newWork.push(task + lendiff);
  }
  var hlEnd = from.line + Math.min(newText.length, 500);
  highlightLines(from.line, hlEnd);
  newWork.push(hlEnd);
  work = newWork;
  startWorker(100);
  // Remember that these lines changed, for updating the display
  changes.push({from: from.line, to: to.line + 1, diff: lendiff});
  var changeObj = {from: from, to: to, text: newText};
  if (textChanged) {
  for (var cur = textChanged; cur.next; cur = cur.next) {}
  cur.next = changeObj;
  } else textChanged = changeObj;
 
  // Update the selection
  function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
  setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
 
  // Make sure the scroll-size div has the correct height.
  code.style.height = (doc.height * textHeight() + 2 * paddingTop()) + "px";
  }
 
  function replaceRange(code, from, to) {
  from = clipPos(from);
  if (!to) to = from; else to = clipPos(to);
  code = splitLines(code);
  function adjustPos(pos) {
  if (posLess(pos, from)) return pos;
  if (!posLess(to, pos)) return end;
  var line = pos.line + code.length - (to.line - from.line) - 1;
  var ch = pos.ch;
  if (pos.line == to.line)
  ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
  return {line: line, ch: ch};
  }
  var end;
  replaceRange1(code, from, to, function(end1) {
  end = end1;
  return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
  });
  return end;
  }
  function replaceSelection(code, collapse) {
  replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
  if (collapse == "end") return {from: end, to: end};
  else if (collapse == "start") return {from: sel.from, to: sel.from};
  else return {from: sel.from, to: end};
  });
  }
  function replaceRange1(code, from, to, computeSel) {
  var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
  var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
  updateLines(from, to, code, newSel.from, newSel.to);
  }
 
  function getRange(from, to) {
  var l1 = from.line, l2 = to.line;
  if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
  var code = [getLine(l1).text.slice(from.ch)];
  doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
  code.push(getLine(l2).text.slice(0, to.ch));
  return code.join("\n");
  }
  function getSelection() {
  return getRange(sel.from, sel.to);
  }
 
  var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
  function slowPoll() {
  if (pollingFast) return;
  poll.set(options.pollInterval, function() {
  startOperation();
  readInput();
  if (focused) slowPoll();
  endOperation();
  });
  }
  function fastPoll() {
  var missed = false;
  pollingFast = true;
  function p() {
  startOperation();
  var changed = readInput();
  if (!changed && !missed) {missed = true; poll.set(60, p);}
  else {pollingFast = false; slowPoll();}
  endOperation();
  }
  poll.set(20, p);
  }
 
  // Previnput is a hack to work with IME. If we reset the textarea
  // on every change, that breaks IME. So we look for changes
  // compared to the previous content instead. (Modern browsers have
  // events that indicate IME taking place, but these are not widely
  // supported or compatible enough yet to rely on.)
  var prevInput = "";
  function readInput() {
  if (leaveInputAlone || !focused || hasSelection(input)) return false;
  var text = input.value;
  if (text == prevInput) return false;
  shiftSelecting = null;
  var same = 0, l = Math.min(prevInput.length, text.length);
  while (same < l && prevInput[same] == text[same]) ++same;
  if (same < prevInput.length)
  sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
  else if (overwrite && posEq(sel.from, sel.to))
  sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
  replaceSelection(text.slice(same), "end");
  prevInput = text;
  return true;
  }
  function resetInput(user) {
  if (!posEq(sel.from, sel.to)) {
  prevInput = "";
  input.value = getSelection();
  input.select();
  } else if (user) prevInput = input.value = "";
  }
 
  function focusInput() {
  if (!options.readOnly) input.focus();
  }
 
  function scrollEditorIntoView() {
  if (!cursor.getBoundingClientRect) return;
  var rect = cursor.getBoundingClientRect();
  // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden
  if (ie && rect.top == rect.bottom) return;
  var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
  if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView();
  }
  function scrollCursorIntoView() {
  var cursor = localCoords(sel.inverted ? sel.from : sel.to);
  var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
  return scrollIntoView(x, cursor.y, x, cursor.yBot);
  }
  function scrollIntoView(x1, y1, x2, y2) {
  var pl = paddingLeft(), pt = paddingTop(), lh = textHeight();
  y1 += pt; y2 += pt; x1 += pl; x2 += pl;
  var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
  if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
  else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
 
  var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
  var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
  if (x1 < screenleft + gutterw) {
  if (x1 < 50) x1 = 0;
  scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw);
  scrolled = true;
  }
  else if (x2 > screenw + screenleft - 3) {
  scroller.scrollLeft = x2 + 10 - screenw;
  scrolled = true;
  if (x2 > code.clientWidth) result = false;
  }
  if (scrolled && options.onScroll) options.onScroll(instance);
  return result;
  }
 
  function visibleLines() {
  var lh = textHeight(), top = scroller.scrollTop - paddingTop();
  var from_height = Math.max(0, Math.floor(top / lh));
  var to_height = Math.ceil((top + scroller.clientHeight) / lh);
  return {from: lineAtHeight(doc, from_height),
  to: lineAtHeight(doc, to_height)};
  }
  // Uses a set of changes plus the current scroll position to
  // determine which DOM updates have to be made, and makes the
  // updates.
  function updateDisplay(changes, suppressCallback) {
  if (!scroller.clientWidth) {
  showingFrom = showingTo = displayOffset = 0;
  return;
  }
  // Compute the new visible window
  var visible = visibleLines();
  // Bail out if the visible area is already rendered and nothing changed.
  if (changes !== true && changes.length == 0 && visible.from >= showingFrom && visible.to <= showingTo) return;
  var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
  if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
  if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
 
  // Create a range of theoretically intact lines, and punch holes
  // in that using the change info.
  var intact = changes === true ? [] :
  computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
  // Clip off the parts that won't be visible
  var intactLines = 0;
  for (var i = 0; i < intact.length; ++i) {
  var range = intact[i];
  if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
  if (range.to > to) range.to = to;
  if (range.from >= range.to) intact.splice(i--, 1);
  else intactLines += range.to - range.from;
  }
  if (intactLines == to - from) return;
  intact.sort(function(a, b) {return a.domStart - b.domStart;});
 
  var th = textHeight(), gutterDisplay = gutter.style.display;
  lineDiv.style.display = gutter.style.display = "none";
  patchDisplay(from, to, intact);
  lineDiv.style.display = "";
 
  // Position the mover div to align with the lines it's supposed
  // to be showing (which will cover the visible display)
  var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
  // This is just a bogus formula that detects when the editor is
  // resized or the font size changes.
  if (different) lastSizeC = scroller.clientHeight + th;
  showingFrom = from; showingTo = to;
  displayOffset = heightAtLine(doc, from);
  mover.style.top = (displayOffset * th) + "px";
  code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
 
  // Since this is all rather error prone, it is honoured with the
  // only assertion in the whole file.
  if (lineDiv.childNodes.length != showingTo - showingFrom)
  throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
  " nodes=" + lineDiv.childNodes.length);
 
  if (options.lineWrapping) {
  maxWidth = scroller.clientWidth;
  var curNode = lineDiv.firstChild;
  doc.iter(showingFrom, showingTo, function(line) {
  if (!line.hidden) {
  var height = Math.round(curNode.offsetHeight / th) || 1;
  if (line.height != height) {updateLineHeight(line, height); gutterDirty = true;}
  }
  curNode = curNode.nextSibling;
  });
  } else {
  if (maxWidth == null) maxWidth = stringWidth(maxLine);
  if (maxWidth > scroller.clientWidth) {
  lineSpace.style.width = maxWidth + "px";
  // Needed to prevent odd wrapping/hiding of widgets placed in here.
  code.style.width = "";
  code.style.width = scroller.scrollWidth + "px";
  } else {
  lineSpace.style.width = code.style.width = "";
  }
  }
  gutter.style.display = gutterDisplay;
  if (different || gutterDirty) updateGutter();
  updateCursor();
  if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
  return true;
  }
 
  function computeIntact(intact, changes) {
  for (var i = 0, l = changes.length || 0; i < l; ++i) {
  var change = changes[i], intact2 = [], diff = change.diff || 0;
  for (var j = 0, l2 = intact.length; j < l2; ++j) {
  var range = intact[j];
  if (change.to <= range.from && change.diff)
  intact2.push({from: range.from + diff, to: range.to + diff,
  domStart: range.domStart});
  else if (change.to <= range.from || change.from >= range.to)
  intact2.push(range);
  else {
  if (change.from > range.from)
  intact2.push({from: range.from, to: change.from, domStart: range.domStart});
  if (change.to < range.to)
  intact2.push({from: change.to + diff, to: range.to + diff,
  domStart: range.domStart + (change.to - range.from)});
  }
  }
  intact = intact2;
  }
  return intact;
  }
 
  function patchDisplay(from, to, intact) {
  // The first pass removes the DOM nodes that aren't intact.
  if (!intact.length) lineDiv.innerHTML = "";
  else {
  function killNode(node) {
  var tmp = node.nextSibling;
  node.parentNode.removeChild(node);
  return tmp;
  }
  var domPos = 0, curNode = lineDiv.firstChild, n;
  for (var i = 0; i < intact.length; ++i) {
  var cur = intact[i];
  while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
  for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
  }
  while (curNode) curNode = killNode(curNode);
  }
  // This pass fills in the lines that actually changed.
  var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
  var sfrom = sel.from.line, sto = sel.to.line, inSel = sfrom < from && sto >= from;
  var scratch = targetDocument.createElement("div"), newElt;
  doc.iter(from, to, function(line) {
  var ch1 = null, ch2 = null;
  if (inSel) {
  ch1 = 0;
  if (sto == j) {inSel = false; ch2 = sel.to.ch;}
  } else if (sfrom == j) {
  if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
  else {inSel = true; ch1 = sel.from.ch;}
  }
  if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
  if (!nextIntact || nextIntact.from > j) {
  if (line.hidden) scratch.innerHTML = "<pre></pre>";
  else scratch.innerHTML = line.getHTML(ch1, ch2, true, tabText);
  lineDiv.insertBefore(scratch.firstChild, curNode);
  } else {
  curNode = curNode.nextSibling;
  }
  ++j;
  });
  }
 
  function updateGutter() {
  if (!options.gutter && !options.lineNumbers) return;
  var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
  gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
  var html = [], i = showingFrom;
  doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
  if (line.hidden) {
  html.push("<pre></pre>");
  } else {
  var marker = line.gutterMarker;
  var text = options.lineNumbers ? i + options.firstLineNumber : null;
  if (marker && marker.text)
  text = marker.text.replace("%N%", text != null ? text : "");
  else if (text == null)
  text = "\u00a0";
  html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
  for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
  html.push("</pre>");
  }
  ++i;
  });
  gutter.style.display = "none";
  gutterText.innerHTML = html.join("");
  var minwidth = String(doc.size).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
  while (val.length + pad.length < minwidth) pad += "\u00a0";
  if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
  gutter.style.display = "";
  lineSpace.style.marginLeft = gutter.offsetWidth + "px";
  gutterDirty = false;
  }
  function updateCursor() {
  var head = sel.inverted ? sel.from : sel.to, lh = textHeight();
  var pos = localCoords(head, true);
  var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
  inputDiv.style.top = (pos.y + lineOff.top - wrapOff.top) + "px";
  inputDiv.style.left = (pos.x + lineOff.left - wrapOff.left) + "px";
  if (posEq(sel.from, sel.to)) {
  cursor.style.top = pos.y + "px";
  cursor.style.left = (options.lineWrapping ? Math.min(pos.x, lineSpace.offsetWidth) : pos.x) + "px";
  cursor.style.display = "";
  }
  else cursor.style.display = "none";
  }
 
  function setShift(val) {
  if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
  else shiftSelecting = null;
  }
  function setSelectionUser(from, to) {
  var sh = shiftSelecting && clipPos(shiftSelecting);
  if (sh) {
  if (posLess(sh, from)) from = sh;
  else if (posLess(to, sh)) to = sh;
  }
  setSelection(from, to);
  userSelChange = true;
  }
  // Update the selection. Last two args are only used by
  // updateLines, since they have to be expressed in the line
  // numbers before the update.
  function setSelection(from, to, oldFrom, oldTo) {
  goalColumn = null;
  if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
  if (posEq(sel.from, from) && posEq(sel.to, to)) return;
  if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
 
  // Skip over hidden lines.
  if (from.line != oldFrom) from = skipHidden(from, oldFrom, sel.from.ch);
  if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
 
  if (posEq(from, to)) sel.inverted = false;
  else if (posEq(from, sel.to)) sel.inverted = false;
  else if (posEq(to, sel.from)) sel.inverted = true;
 
  // Some ugly logic used to only mark the lines that actually did
  // see a change in selection as changed, rather than the whole
  // selected range.
  if (posEq(from, to)) {
  if (!posEq(sel.from, sel.to))
  changes.push({from: oldFrom, to: oldTo + 1});
  }
  else if (posEq(sel.from, sel.to)) {
  changes.push({from: from.line, to: to.line + 1});
  }
  else {
  if (!posEq(from, sel.from)) {
  if (from.line < oldFrom)
  changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
  else
  changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
  }
  if (!posEq(to, sel.to)) {
  if (to.line < oldTo)
  changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
  else
  changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
  }
  }
  sel.from = from; sel.to = to;
  selectionChanged = true;
  }
  function skipHidden(pos, oldLine, oldCh) {
  function getNonHidden(dir) {
  var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
  while (lNo != end) {
  var line = getLine(lNo);
  if (!line.hidden) {
  var ch = pos.ch;
  if (ch > oldCh || ch > line.text.length) ch = line.text.length;
  return {line: lNo, ch: ch};
  }
  lNo += dir;
  }
  }
  var line = getLine(pos.line);
  if (!line.hidden) return pos;
  if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
  else return getNonHidden(-1) || getNonHidden(1);
  }
  function setCursor(line, ch, user) {
  var pos = clipPos({line: line, ch: ch || 0});
  (user ? setSelectionUser : setSelection)(pos, pos);
  }
 
  function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
  function clipPos(pos) {
  if (pos.line < 0) return {line: 0, ch: 0};
  if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
  var ch = pos.ch, linelen = getLine(pos.line).text.length;
  if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
  else if (ch < 0) return {line: pos.line, ch: 0};
  else return pos;
  }
 
  function findPosH(dir, unit) {
  var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
  var lineObj = getLine(line);
  function findNextLine() {
  for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
  var lo = getLine(l);
  if (!lo.hidden) { line = l; lineObj = lo; return true; }
  }
  }
  function moveOnce(boundToLine) {
  if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
  if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
  else return false;
  } else ch += dir;
  return true;
  }
  if (unit == "char") moveOnce();
  else if (unit == "column") moveOnce(true);
  else if (unit == "word") {
  var sawWord = false;
  for (;;) {
  if (dir < 0) if (!moveOnce()) break;
  if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
  else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
  if (dir > 0) if (!moveOnce()) break;
  }
  }
  return {line: line, ch: ch};
  }
  function moveH(dir, unit) {
  var pos = dir < 0 ? sel.from : sel.to;
  if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
  setCursor(pos.line, pos.ch, true);
  }
  function deleteH(dir, unit) {
  if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
  else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
  else replaceRange("", sel.from, findPosH(dir, unit));
  userSelChange = true;
  }
  var goalColumn = null;
  function moveV(dir, unit) {
  var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
  if (goalColumn != null) pos.x = goalColumn;
  if (unit == "page") dist = scroller.clientHeight;
  else if (unit == "line") dist = textHeight();
  var target = coordsChar(pos.x, pos.y + dist * dir + 2);
  setCursor(target.line, target.ch, true);
  goalColumn = pos.x;
  }
 
  function selectWordAt(pos) {
  var line = getLine(pos.line).text;
  var start = pos.ch, end = pos.ch;
  while (start > 0 && isWordChar(line.charAt(start - 1))) --start;
  while (end < line.length && isWordChar(line.charAt(end))) ++end;
  setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
  }
  function selectLine(line) {
  setSelectionUser({line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
  }
  function indentSelected(mode) {
  if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
  var e = sel.to.line - (sel.to.ch ? 0 : 1);
  for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
  }
 
  function indentLine(n, how) {
  if (!how) how = "add";
  if (how == "smart") {
  if (!mode.indent) how = "prev";
  else var state = getStateBefore(n);
  }
 
  var line = getLine(n), curSpace = line.indentation(options.tabSize),
  curSpaceString = line.text.match(/^\s*/)[0], indentation;
  if (how == "prev") {
  if (n) indentation = getLine(n-1).indentation(options.tabSize);
  else indentation = 0;
  }
  else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  else if (how == "add") indentation = curSpace + options.indentUnit;
  else if (how == "subtract") indentation = curSpace - options.indentUnit;
  indentation = Math.max(0, indentation);
  var diff = indentation - curSpace;
 
  if (!diff) {
  if (sel.from.line != n && sel.to.line != n) return;
  var indentString = curSpaceString;
  }
  else {
  var indentString = "", pos = 0;
  if (options.indentWithTabs)
  for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
  while (pos < indentation) {++pos; indentString += " ";}
  }
 
  replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
  }
 
  function loadMode() {
  mode = CodeMirror.getMode(options, options.mode);
  doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
  work = [0];
  startWorker();
  }
  function gutterChanged() {
  var visible = options.gutter || options.lineNumbers;
  gutter.style.display = visible ? "" : "none";
  if (visible) gutterDirty = true;
  else lineDiv.parentNode.style.marginLeft = 0;
  }
  function wrappingChanged(from, to) {
  if (options.lineWrapping) {
  wrapper.className += " CodeMirror-wrap";
  var perLine = scroller.clientWidth / charWidth() - 3;
  doc.iter(0, doc.size, function(line) {
  if (line.hidden) return;
  var guess = Math.ceil(line.text.length / perLine) || 1;
  if (guess != 1) updateLineHeight(line, guess);
  });
  lineSpace.style.width = code.style.width = "";
  } else {
  wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
  maxWidth = null; maxLine = "";
  doc.iter(0, doc.size, function(line) {
  if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
  if (line.text.length > maxLine.length) maxLine = line.text;
  });
  }
  changes.push({from: 0, to: doc.size});
  }
  function computeTabText() {
  for (var str = '<span class="cm-tab">', i = 0; i < options.tabSize; ++i) str += " ";
  return str + "</span>";
  }
  function tabsChanged() {
  tabText = computeTabText();
  updateDisplay(true);
  }
  function themeChanged() {
  scroller.className = scroller.className.replace(/\s*cm-s-\w+/g, "") +
  options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  }
 
  function TextMarker() { this.set = []; }
  TextMarker.prototype.clear = operation(function() {
  var min = Infinity, max = -Infinity;
  for (var i = 0, e = this.set.length; i < e; ++i) {
  var line = this.set[i], mk = line.marked;
  if (!mk || !line.parent) continue;
  var lineN = lineNo(line);
  min = Math.min(min, lineN); max = Math.max(max, lineN);
  for (var j = 0; j < mk.length; ++j)
  if (mk[j].set == this.set) mk.splice(j--, 1);
  }
  if (min != Infinity)
  changes.push({from: min, to: max + 1});
  });
  TextMarker.prototype.find = function() {
  var from, to;
  for (var i = 0, e = this.set.length; i < e; ++i) {
  var line = this.set[i], mk = line.marked;
  for (var j = 0; j < mk.length; ++j) {
  var mark = mk[j];
  if (mark.set == this.set) {
  if (mark.from != null || mark.to != null) {
  var found = lineNo(line);
  if (found != null) {
  if (mark.from != null) from = {line: found, ch: mark.from};
  if (mark.to != null) to = {line: found, ch: mark.to};
  }
  }
  }
  }
  }
  return {from: from, to: to};
  };
 
  function markText(from, to, className) {
  from = clipPos(from); to = clipPos(to);
  var tm = new TextMarker();
  function add(line, from, to, className) {
  getLine(line).addMark(new MarkedText(from, to, className, tm.set));
  }
  if (from.line == to.line) add(from.line, from.ch, to.ch, className);
  else {
  add(from.line, from.ch, null, className);
  for (var i = from.line + 1, e = to.line; i < e; ++i)
  add(i, null, null, className);
  add(to.line, null, to.ch, className);
  }
  changes.push({from: from.line, to: to.line + 1});
  return tm;
  }
 
  function setBookmark(pos) {
  pos = clipPos(pos);
  var bm = new Bookmark(pos.ch);
  getLine(pos.line).addMark(bm);
  return bm;
  }
 
  function addGutterMarker(line, text, className) {
  if (typeof line == "number") line = getLine(clipLine(line));
  line.gutterMarker = {text: text, style: className};
  gutterDirty = true;
  return line;
  }
  function removeGutterMarker(line) {
  if (typeof line == "number") line = getLine(clipLine(line));
  line.gutterMarker = null;
  gutterDirty = true;
  }
 
  function changeLine(handle, op) {
  var no = handle, line = handle;
  if (typeof handle == "number") line = getLine(clipLine(handle));
  else no = lineNo(handle);
  if (no == null) return null;
  if (op(line, no)) changes.push({from: no, to: no + 1});
  else return null;
  return line;
  }
  function setLineClass(handle, className) {
  return changeLine(handle, function(line) {
  if (line.className != className) {
  line.className = className;
  return true;
  }
  });
  }
  function setLineHidden(handle, hidden) {
  return changeLine(handle, function(line, no) {
  if (line.hidden != hidden) {
  line.hidden = hidden;
  updateLineHeight(line, hidden ? 0 : 1);
  if (hidden && (sel.from.line == no || sel.to.line == no))
  setSelection(skipHidden(sel.from, sel.from.line, sel.from.ch),
  skipHidden(sel.to, sel.to.line, sel.to.ch));
  return (gutterDirty = true);
  }
  });
  }
 
  function lineInfo(line) {
  if (typeof line == "number") {
  if (!isLine(line)) return null;
  var n = line;
  line = getLine(line);
  if (!line) return null;
  }
  else {
  var n = lineNo(line);
  if (n == null) return null;
  }
  var marker = line.gutterMarker;
  return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
  markerClass: marker && marker.style, lineClass: line.className};
  }
 
  function stringWidth(str) {
  measure.innerHTML = "<pre><span>x</span></pre>";
  measure.firstChild.firstChild.firstChild.nodeValue = str;
  return measure.firstChild.firstChild.offsetWidth || 10;
  }
  // These are used to go from pixel positions to character
  // positions, taking varying character widths into account.
  function charFromX(line, x) {
  if (x <= 0) return 0;
  var lineObj = getLine(line), text = lineObj.text;
  function getX(len) {
  measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, tabText, len) + "</span></pre>";
  return measure.firstChild.firstChild.offsetWidth;
  }
  var from = 0, fromX = 0, to = text.length, toX;
  // Guess a suitable upper bound for our search.
  var estimated = Math.min(to, Math.ceil(x / charWidth()));
  for (;;) {
  var estX = getX(estimated);
  if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
  else {toX = estX; to = estimated; break;}
  }
  if (x > toX) return to;
  // Try to guess a suitable lower bound as well.
  estimated = Math.floor(to * 0.8); estX = getX(estimated);
  if (estX < x) {from = estimated; fromX = estX;}
  // Do a binary search between these bounds.
  for (;;) {
  if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
  var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
  if (middleX > x) {to = middle; toX = middleX;}
  else {from = middle; fromX = middleX;}
  }
  }
 
  var tempId = Math.floor(Math.random() * 0xffffff).toString(16);
  function measureLine(line, ch) {
  var extra = "";
  // Include extra text at the end to make sure the measured line is wrapped in the right way.
  if (options.lineWrapping) {
  var end = line.text.indexOf(" ", ch + 2);
  extra = htmlEscape(line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)));
  }
  measure.innerHTML = "<pre>" + line.getHTML(null, null, false, tabText, ch) +
  '<span id="CodeMirror-temp-' + tempId + '">' + htmlEscape(line.text.charAt(ch) || " ") + "</span>" +
  extra + "</pre>";
  var elt = document.getElementById("CodeMirror-temp-" + tempId);
  var top = elt.offsetTop, left = elt.offsetLeft;
  // Older IEs report zero offsets for spans directly after a wrap
  if (ie && ch && top == 0 && left == 0) {
  var backup = document.createElement("span");
  backup.innerHTML = "x";
  elt.parentNode.insertBefore(backup, elt.nextSibling);
  top = backup.offsetTop;
  }
  return {top: top, left: left};
  }
  function localCoords(pos, inLineWrap) {
  var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
  if (pos.ch == 0) x = 0;
  else {
  var sp = measureLine(getLine(pos.line), pos.ch);
  x = sp.left;
  if (options.lineWrapping) y += Math.max(0, sp.top);
  }
  return {x: x, y: y, yBot: y + lh};
  }
  // Coords must be lineSpace-local
  function coordsChar(x, y) {
  if (y < 0) y = 0;
  var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
  var lineNo = lineAtHeight(doc, heightPos);
  if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
  var lineObj = getLine(lineNo), text = lineObj.text;
  var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
  if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
  function getX(len) {
  var sp = measureLine(lineObj, len);
  if (tw) {
  var off = Math.round(sp.top / th);
  return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
  }
  return sp.left;
  }
  var from = 0, fromX = 0, to = text.length, toX;
  // Guess a suitable upper bound for our search.
  var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
  for (;;) {
  var estX = getX(estimated);
  if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
  else {toX = estX; to = estimated; break;}
  }
  if (x > toX) return {line: lineNo, ch: to};
  // Try to guess a suitable lower bound as well.
  estimated = Math.floor(to * 0.8); estX = getX(estimated);
  if (estX < x) {from = estimated; fromX = estX;}
  // Do a binary search between these bounds.
  for (;;) {
  if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to};
  var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
  if (middleX > x) {to = middle; toX = middleX;}
  else {from = middle; fromX = middleX;}
  }
  }
  function pageCoords(pos) {
  var local = localCoords(pos, true), off = eltOffset(lineSpace);
  return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
  }
 
  var cachedHeight, cachedHeightFor, measureText;
  function textHeight() {
  if (measureText == null) {
  measureText = "<pre>";
  for (var i = 0; i < 49; ++i) measureText += "x<br/>";
  measureText += "x</pre>";
  }
  var offsetHeight = lineDiv.clientHeight;
  if (offsetHeight == cachedHeightFor) return cachedHeight;
  cachedHeightFor = offsetHeight;
  measure.innerHTML = measureText;
  cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
  measure.innerHTML = "";
  return cachedHeight;
  }
  var cachedWidth, cachedWidthFor = 0;
  function charWidth() {
  if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
  cachedWidthFor = scroller.clientWidth;
  return (cachedWidth = stringWidth("x"));
  }
  function paddingTop() {return lineSpace.offsetTop;}
  function paddingLeft() {return lineSpace.offsetLeft;}
 
  function posFromMouse(e, liberal) {
  var offW = eltOffset(scroller, true), x, y;
  // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
  // This is a mess of a heuristic to try and determine whether a
  // scroll-bar was clicked or not, and to return null if one was
  // (and !liberal).
  if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
  return null;
  var offL = eltOffset(lineSpace, true);
  return coordsChar(x - offL.left, y - offL.top);
  }
  function onContextMenu(e) {
  var pos = posFromMouse(e);
  if (!pos || window.opera) return; // Opera is difficult.
  if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
  operation(setCursor)(pos.line, pos.ch);
 
  var oldCSS = input.style.cssText;
  inputDiv.style.position = "absolute";
  input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
  "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  leaveInputAlone = true;
  var val = input.value = getSelection();
  focusInput();
  input.select();
  function rehide() {
  var newVal = splitLines(input.value).join("\n");
  if (newVal != val) operation(replaceSelection)(newVal, "end");
  inputDiv.style.position = "relative";
  input.style.cssText = oldCSS;
  leaveInputAlone = false;
  resetInput(true);
  slowPoll();
  }
 
  if (gecko) {
  e_stop(e);
  var mouseup = connect(window, "mouseup", function() {
  mouseup();
  setTimeout(rehide, 20);
  }, true);
  }
  else {
  setTimeout(rehide, 50);
  }
  }
 
  // Cursor-blinking
  function restartBlink() {
  clearInterval(blinker);
  var on = true;
  cursor.style.visibility = "";
  blinker = setInterval(function() {
  cursor.style.visibility = (on = !on) ? "" : "hidden";
  }, 650);
  }
 
  var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
  function matchBrackets(autoclear) {
  var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
  var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
  if (!match) return;
  var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
  for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
  if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
 
  var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
  function scan(line, from, to) {
  if (!line.text) return;
  var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
  for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
  var text = st[i];
  if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
  for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
  if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
  var match = matching[cur];
  if (match.charAt(1) == ">" == forward) stack.push(cur);
  else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
  else if (!stack.length) return {pos: pos, match: true};
  }
  }
  }
  }
  for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
  var line = getLine(i), first = i == head.line;
  var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
  if (found) break;
  }
  if (!found) found = {pos: null, match: false};
  var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
  var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
  two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
  var clear = operation(function(){one.clear(); two && two.clear();});
  if (autoclear) setTimeout(clear, 800);
  else bracketHighlighted = clear;
  }
 
  // Finds the line to start with when starting a parse. Tries to
  // find a line with a stateAfter, so that it can start with a
  // valid state. If that fails, it returns the line with the
  // smallest indentation, which tends to need the least context to
  // parse correctly.
  function findStartLine(n) {
  var minindent, minline;
  for (var search = n, lim = n - 40; search > lim; --search) {
  if (search == 0) return 0;
  var line = getLine(search-1);
  if (line.stateAfter) return search;
  var indented = line.indentation(options.tabSize);
  if (minline == null || minindent > indented) {
  minline = search - 1;
  minindent = indented;
  }
  }
  return minline;
  }
  function getStateBefore(n) {
  var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
  if (!state) state = startState(mode);
  else state = copyState(mode, state);
  doc.iter(start, n, function(line) {
  line.highlight(mode, state, options.tabSize);
  line.stateAfter = copyState(mode, state);
  });
  if (start < n) changes.push({from: start, to: n});
  if (n < doc.size && !getLine(n).stateAfter) work.push(n);
  return state;
  }
  function highlightLines(start, end) {
  var state = getStateBefore(start);
  doc.iter(start, end, function(line) {
  line.highlight(mode, state, options.tabSize);
  line.stateAfter = copyState(mode, state);
  });
  }
  function highlightWorker() {
  var end = +new Date + options.workTime;
  var foundWork = work.length;
  while (work.length) {
  if (!getLine(showingFrom).stateAfter) var task = showingFrom;
  else var task = work.pop();
  if (task >= doc.size) continue;
  var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
  if (state) state = copyState(mode, state);
  else state = startState(mode);
 
  var unchanged = 0, compare = mode.compareStates, realChange = false,
  i = start, bail = false;
  doc.iter(i, doc.size, function(line) {
  var hadState = line.stateAfter;
  if (+new Date > end) {
  work.push(i);
  startWorker(options.workDelay);
  if (realChange) changes.push({from: task, to: i + 1});
  return (bail = true);
  }
  var changed = line.highlight(mode, state, options.tabSize);
  if (changed) realChange = true;
  line.stateAfter = copyState(mode, state);
  if (compare) {
  if (hadState && compare(hadState, state)) return true;
  } else {
  if (changed !== false || !hadState) unchanged = 0;
  else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
  return true;
  }
  ++i;
  });
  if (bail) return;
  if (realChange) changes.push({from: task, to: i + 1});
  }
  if (foundWork && options.onHighlightComplete)
  options.onHighlightComplete(instance);
  }
  function startWorker(time) {
  if (!work.length) return;
  highlight.set(time, operation(highlightWorker));
  }
 
  // Operations are used to wrap changes in such a way that each
  // change won't have to update the cursor and display (which would
  // be awkward, slow, and error-prone), but instead updates are
  // batched and then all combined and executed at once.
  function startOperation() {
  updateInput = userSelChange = textChanged = null;
  changes = []; selectionChanged = false; callbacks = [];
  }
  function endOperation() {
  var reScroll = false, updated;
  if (selectionChanged) reScroll = !scrollCursorIntoView();
  if (changes.length) updated = updateDisplay(changes, true);
  else {
  if (selectionChanged) updateCursor();
  if (gutterDirty) updateGutter();
  }
  if (reScroll) scrollCursorIntoView();
  if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
 
  if (focused && !leaveInputAlone &&
  (updateInput === true || (updateInput !== false && selectionChanged)))
  resetInput(userSelChange);
 
  if (selectionChanged && options.matchBrackets)
  setTimeout(operation(function() {
  if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
  if (posEq(sel.from, sel.to)) matchBrackets(false);
  }), 20);
  var tc = textChanged, cbs = callbacks; // these can be reset by callbacks
  if (selectionChanged && options.onCursorActivity)
  options.onCursorActivity(instance);
  if (tc && options.onChange && instance)
  options.onChange(instance, tc);
  for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
  if (updated && options.onUpdate) options.onUpdate(instance);
  }
  var nestedOperation = 0;
  function operation(f) {
  return function() {
  if (!nestedOperation++) startOperation();
  try {var result = f.apply(this, arguments);}
  finally {if (!--nestedOperation) endOperation();}
  return result;
  };
  }
 
  for (var ext in extensions)
  if (extensions.propertyIsEnumerable(ext) &&
  !instance.propertyIsEnumerable(ext))
  instance[ext] = extensions[ext];
  return instance;
  } // (end of function CodeMirror)
 
  // The default configuration options.
  CodeMirror.defaults = {
  value: "",
  mode: null,
  theme: "default",
  indentUnit: 2,
  indentWithTabs: false,
  tabSize: 4,
  keyMap: "default",
  extraKeys: null,
  electricChars: true,
  onKeyEvent: null,
  lineWrapping: false,
  lineNumbers: false,
  gutter: false,
  fixedGutter: false,
  firstLineNumber: 1,
  readOnly: false,
  onChange: null,
  onCursorActivity: null,
  onGutterClick: null,
  onHighlightComplete: null,
  onUpdate: null,
  onFocus: null, onBlur: null, onScroll: null,
  matchBrackets: false,
  workTime: 100,
  workDelay: 200,
  pollInterval: 100,
  undoDepth: 40,
  tabindex: null,
  document: window.document
  };
 
  var mac = /Mac/.test(navigator.platform);
  var win = /Win/.test(navigator.platform);
 
  // Known modes, by name and by MIME
  var modes = {}, mimeModes = {};
  CodeMirror.defineMode = function(name, mode) {
  if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  modes[name] = mode;
  };
  CodeMirror.defineMIME = function(mime, spec) {
  mimeModes[mime] = spec;
  };
  CodeMirror.getMode = function(options, spec) {
  if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
  spec = mimeModes[spec];
  if (typeof spec == "string")
  var mname = spec, config = {};
  else if (spec != null)
  var mname = spec.name, config = spec;
  var mfactory = modes[mname];
  if (!mfactory) {
  if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
  return CodeMirror.getMode(options, "text/plain");
  }
  return mfactory(options, config || {});
  };
  CodeMirror.listModes = function() {
  var list = [];
  for (var m in modes)
  if (modes.propertyIsEnumerable(m)) list.push(m);
  return list;
  };
  CodeMirror.listMIMEs = function() {
  var list = [];
  for (var m in mimeModes)
  if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
  return list;
  };
 
  var extensions = CodeMirror.extensions = {};
  CodeMirror.defineExtension = function(name, func) {
  extensions[name] = func;
  };
 
  var commands = CodeMirror.commands = {
  selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
  killLine: function(cm) {
  var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
  if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
  else cm.replaceRange("", from, sel ? to : {line: from.line});
  },
  deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
  undo: function(cm) {cm.undo();},
  redo: function(cm) {cm.redo();},
  goDocStart: function(cm) {cm.setCursor(0, 0, true);},
  goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
  goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
  goLineStartSmart: function(cm) {
  var cur = cm.getCursor();
  var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
  cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
  },
  goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
  goLineUp: function(cm) {cm.moveV(-1, "line");},
  goLineDown: function(cm) {cm.moveV(1, "line");},
  goPageUp: function(cm) {cm.moveV(-1, "page");},
  goPageDown: function(cm) {cm.moveV(1, "page");},
  goCharLeft: function(cm) {cm.moveH(-1, "char");},
  goCharRight: function(cm) {cm.moveH(1, "char");},
  goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  goColumnRight: function(cm) {cm.moveH(1, "column");},
  goWordLeft: function(cm) {cm.moveH(-1, "word");},
  goWordRight: function(cm) {cm.moveH(1, "word");},
  delCharLeft: function(cm) {cm.deleteH(-1, "char");},
  delCharRight: function(cm) {cm.deleteH(1, "char");},
  delWordLeft: function(cm) {cm.deleteH(-1, "word");},
  delWordRight: function(cm) {cm.deleteH(1, "word");},
  indentAuto: function(cm) {cm.indentSelection("smart");},
  indentMore: function(cm) {cm.indentSelection("add");},
  indentLess: function(cm) {cm.indentSelection("subtract");},
  insertTab: function(cm) {cm.replaceSelection("\t", "end");},
  transposeChars: function(cm) {
  var cur = cm.getCursor(), line = cm.getLine(cur.line);
  if (cur.ch > 0 && cur.ch < line.length - 1)
  cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
  {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
  },
  newlineAndIndent: function(cm) {
  cm.replaceSelection("\n", "end");
  cm.indentLine(cm.getCursor().line);
  },
  toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  };
 
  var keyMap = CodeMirror.keyMap = {};
  keyMap.basic = {
  "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "indentMore", "Shift-Tab": "indentLess",
  "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
  };
  // Note that the save and find-related commands aren't defined by
  // default. Unknown commands are simply ignored.
  keyMap.pcDefault = {
  "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
  "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
  "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  fallthrough: "basic"
  };
  keyMap.macDefault = {
  "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
  "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
  "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
  "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  fallthrough: ["basic", "emacsy"]
  };
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  keyMap.emacsy = {
  "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
  "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  };
 
  function lookupKey(name, extraMap, map) {
  function lookup(name, map, ft) {
  var found = map[name];
  if (found != null) return found;
  if (ft == null) ft = map.fallthrough;
  if (ft == null) return map.catchall;
  if (typeof ft == "string") return lookup(name, keyMap[ft]);
  for (var i = 0, e = ft.length; i < e; ++i) {
  found = lookup(name, keyMap[ft[i]]);
  if (found != null) return found;
  }
  return null;
  }
  return extraMap ? lookup(name, extraMap, map) : lookup(name, keyMap[map]);
  }
  function isModifierKey(event) {
  var name = keyNames[event.keyCode];
  return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  }
 
  CodeMirror.fromTextArea = function(textarea, options) {
  if (!options) options = {};
  options.value = textarea.value;
  if (!options.tabindex && textarea.tabindex)
  options.tabindex = textarea.tabindex;
 
  function save() {textarea.value = instance.getValue();}
  if (textarea.form) {
  // Deplorable hack to make the submit method do the right thing.
  var rmSubmit = connect(textarea.form, "submit", save, true);
  if (typeof textarea.form.submit == "function") {
  var realSubmit = textarea.form.submit;
  function wrappedSubmit() {
  save();
  textarea.form.submit = realSubmit;
  textarea.form.submit();
  textarea.form.submit = wrappedSubmit;
  }
  textarea.form.submit = wrappedSubmit;
  }
  }
 
  textarea.style.display = "none";
  var instance = CodeMirror(function(node) {
  textarea.parentNode.insertBefore(node, textarea.nextSibling);
  }, options);
  instance.save = save;
  instance.getTextArea = function() { return textarea; };
  instance.toTextArea = function() {
  save();
  textarea.parentNode.removeChild(instance.getWrapperElement());
  textarea.style.display = "";
  if (textarea.form) {
  rmSubmit();
  if (typeof textarea.form.submit == "function")
  textarea.form.submit = realSubmit;
  }
  };
  return instance;
  };
 
  // Utility functions for working with state. Exported because modes
  // sometimes need to do this.
  function copyState(mode, state) {
  if (state === true) return state;
  if (mode.copyState) return mode.copyState(state);
  var nstate = {};
  for (var n in state) {
  var val = state[n];
  if (val instanceof Array) val = val.concat([]);
  nstate[n] = val;
  }
  return nstate;
  }
  CodeMirror.copyState = copyState;
  function startState(mode, a1, a2) {
  return mode.startState ? mode.startState(a1, a2) : true;
  }
  CodeMirror.startState = startState;
 
  // The character stream used by a mode's parser.
  function StringStream(string, tabSize) {
  this.pos = this.start = 0;
  this.string = string;
  this.tabSize = tabSize || 8;
  }
  StringStream.prototype = {
  eol: function() {return this.pos >= this.string.length;},
  sol: function() {return this.pos == 0;},
  peek: function() {return this.string.charAt(this.pos);},
  next: function() {
  if (this.pos < this.string.length)
  return this.string.charAt(this.pos++);
  },
  eat: function(match) {
  var ch = this.string.charAt(this.pos);
  if (typeof match == "string") var ok = ch == match;
  else var ok = ch && (match.test ? match.test(ch) : match(ch));
  if (ok) {++this.pos; return ch;}
  },
  eatWhile: function(match) {
  var start = this.pos;
  while (this.eat(match)){}
  return this.pos > start;
  },
  eatSpace: function() {
  var start = this.pos;
  while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  return this.pos > start;
  },
  skipToEnd: function() {this.pos = this.string.length;},
  skipTo: function(ch) {
  var found = this.string.indexOf(ch, this.pos);
  if (found > -1) {this.pos = found; return true;}
  },
  backUp: function(n) {this.pos -= n;},
  column: function() {return countColumn(this.string, this.start, this.tabSize);},
  indentation: function() {return countColumn(this.string, null, this.tabSize);},
  match: function(pattern, consume, caseInsensitive) {
  if (typeof pattern == "string") {
  function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
  if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
  if (consume !== false) this.pos += pattern.length;
  return true;
  }
  }
  else {
  var match = this.string.slice(this.pos).match(pattern);
  if (match && consume !== false) this.pos += match[0].length;
  return match;
  }
  },
  current: function(){return this.string.slice(this.start, this.pos);}
  };
  CodeMirror.StringStream = StringStream;
 
  function MarkedText(from, to, className, set) {
  this.from = from; this.to = to; this.style = className; this.set = set;
  }
  MarkedText.prototype = {
  attach: function(line) { this.set.push(line); },
  detach: function(line) {
  var ix = indexOf(this.set, line);
  if (ix > -1) this.set.splice(ix, 1);
  },
  split: function(pos, lenBefore) {
  if (this.to <= pos && this.to != null) return null;
  var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
  var to = this.to == null ? null : this.to - pos + lenBefore;
  return new MarkedText(from, to, this.style, this.set);
  },
  dup: function() { return new MarkedText(null, null, this.style, this.set); },
  clipTo: function(fromOpen, from, toOpen, to, diff) {
  if (this.from != null && this.from >= from)
  this.from = Math.max(to, this.from) + diff;
  if (this.to != null && this.to > from)
  this.to = to < this.to ? this.to + diff : from;
  if (fromOpen && to > this.from && (to < this.to || this.to == null))
  this.from = null;
  if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
  this.to = null;
  },
  isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
  sameSet: function(x) { return this.set == x.set; }
  };
 
  function Bookmark(pos) {
  this.from = pos; this.to = pos; this.line = null;
  }
  Bookmark.prototype = {
  attach: function(line) { this.line = line; },
  detach: function(line) { if (this.line == line) this.line = null; },
  split: function(pos, lenBefore) {
  if (pos < this.from) {
  this.from = this.to = (this.from - pos) + lenBefore;
  return this;
  }
  },
  isDead: function() { return this.from > this.to; },
  clipTo: function(fromOpen, from, toOpen, to, diff) {
  if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
  this.from = 0; this.to = -1;
  } else if (this.from > from) {
  this.from = this.to = Math.max(to, this.from) + diff;
  }
  },
  sameSet: function(x) { return false; },
  find: function() {
  if (!this.line || !this.line.parent) return null;
  return {line: lineNo(this.line), ch: this.from};
  },
  clear: function() {
  if (this.line) {
  var found = indexOf(this.line.marked, this);
  if (found != -1) this.line.marked.splice(found, 1);
  this.line = null;
  }
  }
  };
 
  // Line objects. These hold state related to a line, including
  // highlighting info (the styles array).
  function Line(text, styles) {
  this.styles = styles || [text, null];
  this.text = text;
  this.height = 1;
  this.marked = this.gutterMarker = this.className = this.handlers = null;
  this.stateAfter = this.parent = this.hidden = null;
  }
  Line.inheritMarks = function(text, orig) {
  var ln = new Line(text), mk = orig && orig.marked;
  if (mk) {
  for (var i = 0; i < mk.length; ++i) {
  if (mk[i].to == null && mk[i].style) {
  var newmk = ln.marked || (ln.marked = []), mark = mk[i];
  var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
  }
  }
  }
  return ln;
  }
  Line.prototype = {
  // Replace a piece of a line, keeping the styles around it intact.
  replace: function(from, to_, text) {
  var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
  copyStyles(0, from, this.styles, st);
  if (text) st.push(text, null);
  copyStyles(to, this.text.length, this.styles, st);
  this.styles = st;
  this.text = this.text.slice(0, from) + text + this.text.slice(to);
  this.stateAfter = null;
  if (mk) {
  var diff = text.length - (to - from);
  for (var i = 0, mark = mk[i]; i < mk.length; ++i) {
  mark.clipTo(from == null, from || 0, to_ == null, to, diff);
  if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
  }
  }
  },
  // Split a part off a line, keeping styles and markers intact.
  split: function(pos, textBefore) {
  var st = [textBefore, null], mk = this.marked;
  copyStyles(pos, this.text.length, this.styles, st);
  var taken = new Line(textBefore + this.text.slice(pos), st);
  if (mk) {
  for (var i = 0; i < mk.length; ++i) {
  var mark = mk[i];
  var newmark = mark.split(pos, textBefore.length);
  if (newmark) {
  if (!taken.marked) taken.marked = [];
  taken.marked.push(newmark); newmark.attach(taken);
  }
  }
  }
  return taken;
  },
  append: function(line) {
  var mylen = this.text.length, mk = line.marked, mymk = this.marked;
  this.text += line.text;
  copyStyles(0, line.text.length, line.styles, this.styles);
  if (mymk) {
  for (var i = 0; i < mymk.length; ++i)
  if (mymk[i].to == null) mymk[i].to = mylen;
  }
  if (mk && mk.length) {
  if (!mymk) this.marked = mymk = [];
  outer: for (var i = 0; i < mk.length; ++i) {
  var mark = mk[i];
  if (!mark.from) {
  for (var j = 0; j < mymk.length; ++j) {
  var mymark = mymk[j];
  if (mymark.to == mylen && mymark.sameSet(mark)) {
  mymark.to = mark.to == null ? null : mark.to + mylen;
  if (mymark.isDead()) {
  mymark.detach(this);
  mk.splice(i--, 1);
  }
  continue outer;
  }
  }
  }
  mymk.push(mark);
  mark.attach(this);
  mark.from += mylen;
  if (mark.to != null) mark.to += mylen;
  }
  }
  },
  fixMarkEnds: function(other) {
  var mk = this.marked, omk = other.marked;
  if (!mk) return;
  for (var i = 0; i < mk.length; ++i) {
  var mark = mk[i], close = mark.to == null;
  if (close && omk) {
  for (var j = 0; j < omk.length; ++j)
  if (omk[j].sameSet(mark)) {close = false; break;}
  }
  if (close) mark.to = this.text.length;
  }
  },
  fixMarkStarts: function() {
  var mk = this.marked;
  if (!mk) return;
  for (var i = 0; i < mk.length; ++i)
  if (mk[i].from == null) mk[i].from = 0;
  },
  addMark: function(mark) {
  mark.attach(this);
  if (this.marked == null) this.marked = [];
  this.marked.push(mark);
  this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
  },
  // Run the given mode's parser over a line, update the styles
  // array, which contains alternating fragments of text and CSS
  // classes.
  highlight: function(mode, state, tabSize) {
  var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
  var changed = false, curWord = st[0], prevWord;
  if (this.text == "" && mode.blankLine) mode.blankLine(state);
  while (!stream.eol()) {
  var style = mode.token(stream, state);
  var substr = this.text.slice(stream.start, stream.pos);
  stream.start = stream.pos;
  if (pos && st[pos-1] == style)
  st[pos-2] += substr;
  else if (substr) {
  if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
  st[pos++] = substr; st[pos++] = style;
  prevWord = curWord; curWord = st[pos];
  }
  // Give up when line is ridiculously long
  if (stream.pos > 5000) {
  st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
  break;
  }
  }
  if (st.length != pos) {st.length = pos; changed = true;}
  if (pos && st[pos-2] != prevWord) changed = true;
  // Short lines with simple highlights return null, and are
  // counted as changed by the driver because they are likely to
  // highlight the same way in various contexts.
  return changed || (st.length < 5 && this.text.length < 10 ? null : false);
  },
  // Fetch the parser token for a given character. Useful for hacks
  // that want to inspect the mode state (say, for completion).
  getTokenAt: function(mode, state, ch) {
  var txt = this.text, stream = new StringStream(txt);
  while (stream.pos < ch && !stream.eol()) {
  stream.start = stream.pos;
  var style = mode.token(stream, state);
  }
  return {start: stream.start,
  end: stream.pos,
  string: stream.current(),
  className: style || null,
  state: state};
  },
  indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
  // Produces an HTML fragment for the line, taking selection,
  // marking, and highlighting into account.
  getHTML: function(sfrom, sto, includePre, tabText, endAt) {
  var html = [], first = true;
  if (includePre)
  html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
  function span(text, style) {
  if (!text) return;
  // Work around a bug where, in some compat modes, IE ignores leading spaces
  if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
  first = false;
  if (style) html.push('<span class="', style, '">', htmlEscape(text).replace(/\t/g, tabText), "</span>");
  else html.push(htmlEscape(text).replace(/\t/g, tabText));
  }
  var st = this.styles, allText = this.text, marked = this.marked;
  if (sfrom == sto) sfrom = null;
  var len = allText.length;
  if (endAt != null) len = Math.min(endAt, len);
 
  if (!allText && endAt == null)
  span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
  else if (!marked && sfrom == null)
  for (var i = 0, ch = 0; ch < len; i+=2) {
  var str = st[i], style = st[i+1], l = str.length;
  if (ch + l > len) str = str.slice(0, len - ch);
  ch += l;
  span(str, style && "cm-" + style);
  }
  else {
  var pos = 0, i = 0, text = "", style, sg = 0;
  var markpos = -1, mark = null;
  function nextMark() {
  if (marked) {
  markpos += 1;
  mark = (markpos < marked.length) ? marked[markpos] : null;
  }
  }
  nextMark();
  while (pos < len) {
  var upto = len;
  var extraStyle = "";
  if (sfrom != null) {
  if (sfrom > pos) upto = sfrom;
  else if (sto == null || sto > pos) {
  extraStyle = " CodeMirror-selected";
  if (sto != null) upto = Math.min(upto, sto);
  }
  }
  while (mark && mark.to != null && mark.to <= pos) nextMark();
  if (mark) {
  if (mark.from > pos) upto = Math.min(upto, mark.from);
  else {
  extraStyle += " " + mark.style;
  if (mark.to != null) upto = Math.min(upto, mark.to);
  }
  }
  for (;;) {
  var end = pos + text.length;
  var appliedStyle = style;
  if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle;
  span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
  if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  pos = end;
  text = st[i++]; style = "cm-" + st[i++];
  }
  }
  if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
  }
  if (includePre) html.push("</pre>");
  return html.join("");
  },
  cleanUp: function() {
  this.parent = null;
  if (this.marked)
  for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
  }
  };
  // Utility used by replace and split above
  function copyStyles(from, to, source, dest) {
  for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
  var part = source[i], end = pos + part.length;
  if (state == 0) {
  if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
  if (end >= from) state = 1;
  }
  else if (state == 1) {
  if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
  else dest.push(part, source[i+1]);
  }
  pos = end;
  }
  }
 
  // Data structure that holds the sequence of lines.
  function LeafChunk(lines) {
  this.lines = lines;
  this.parent = null;
  for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
  lines[i].parent = this;
  height += lines[i].height;
  }
  this.height = height;
  }
  LeafChunk.prototype = {
  chunkSize: function() { return this.lines.length; },
  remove: function(at, n, callbacks) {
  for (var i = at, e = at + n; i < e; ++i) {
  var line = this.lines[i];
  this.height -= line.height;
  line.cleanUp();
  if (line.handlers)
  for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
  }
  this.lines.splice(at, n);
  },
  collapse: function(lines) {
  lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
  },
  insertHeight: function(at, lines, height) {
  this.height += height;
  this.lines.splice.apply(this.lines, [at, 0].concat(lines));
  for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
  },
  iterN: function(at, n, op) {
  for (var e = at + n; at < e; ++at)
  if (op(this.lines[at])) return true;
  }
  };
  function BranchChunk(children) {
  this.children = children;
  var size = 0, height = 0;
  for (var i = 0, e = children.length; i < e; ++i) {
  var ch = children[i];
  size += ch.chunkSize(); height += ch.height;
  ch.parent = this;
  }
  this.size = size;
  this.height = height;
  this.parent = null;
  }
  BranchChunk.prototype = {
  chunkSize: function() { return this.size; },
  remove: function(at, n, callbacks) {
  this.size -= n;
  for (var i = 0; i < this.children.length; ++i) {
  var child = this.children[i], sz = child.chunkSize();
  if (at < sz) {
  var rm = Math.min(n, sz - at), oldHeight = child.height;
  child.remove(at, rm, callbacks);
  this.height -= oldHeight - child.height;
  if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  if ((n -= rm) == 0) break;
  at = 0;
  } else at -= sz;
  }
  if (this.size - n < 25) {
  var lines = [];
  this.collapse(lines);
  this.children = [new LeafChunk(lines)];
  }
  },
  collapse: function(lines) {
  for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
  },
  insert: function(at, lines) {
  var height = 0;
  for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
  this.insertHeight(at, lines, height);
  },
  insertHeight: function(at, lines, height) {
  this.size += lines.length;
  this.height += height;
  for (var i = 0, e = this.children.length; i < e; ++i) {
  var child = this.children[i], sz = child.chunkSize();
  if (at <= sz) {
  child.insertHeight(at, lines, height);
  if (child.lines && child.lines.length > 50) {
  while (child.lines.length > 50) {
  var spilled = child.lines.splice(child.lines.length - 25, 25);
  var newleaf = new LeafChunk(spilled);
  child.height -= newleaf.height;
  this.children.splice(i + 1, 0, newleaf);
  newleaf.parent = this;
  }
  this.maybeSpill();
  }
  break;
  }
  at -= sz;
  }
  },
  maybeSpill: function() {
  if (this.children.length <= 10) return;
  var me = this;
  do {
  var spilled = me.children.splice(me.children.length - 5, 5);
  var sibling = new BranchChunk(spilled);
  if (!me.parent) { // Become the parent node
  var copy = new BranchChunk(me.children);
  copy.parent = me;
  me.children = [copy, sibling];
  me = copy;
  } else {
  me.size -= sibling.size;
  me.height -= sibling.height;
  var myIndex = indexOf(me.parent.children, me);
  me.parent.children.splice(myIndex + 1, 0, sibling);
  }
  sibling.parent = me.parent;
  } while (me.children.length > 10);
  me.parent.maybeSpill();
  },
  iter: function(from, to, op) { this.iterN(from, to - from, op); },
  iterN: function(at, n, op) {
  for (var i = 0, e = this.children.length; i < e; ++i) {
  var child = this.children[i], sz = child.chunkSize();
  if (at < sz) {
  var used = Math.min(n, sz - at);
  if (child.iterN(at, used, op)) return true;
  if ((n -= used) == 0) break;
  at = 0;
  } else at -= sz;
  }
  }
  };
 
  function getLineAt(chunk, n) {
  while (!chunk.lines) {
  for (var i = 0;; ++i) {
  var child = chunk.children[i], sz = child.chunkSize();
  if (n < sz) { chunk = child; break; }
  n -= sz;
  }
  }
  return chunk.lines[n];
  }
  function lineNo(line) {
  if (line.parent == null) return null;
  var cur = line.parent, no = indexOf(cur.lines, line);
  for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  for (var i = 0, e = chunk.children.length; ; ++i) {
  if (chunk.children[i] == cur) break;
  no += chunk.children[i].chunkSize();
  }
  }
  return no;
  }
  function lineAtHeight(chunk, h) {
  var n = 0;
  outer: do {
  for (var i = 0, e = chunk.children.length; i < e; ++i) {
  var child = chunk.children[i], ch = child.height;
  if (h < ch) { chunk = child; continue outer; }
  h -= ch;
  n += child.chunkSize();
  }
  return n;
  } while (!chunk.lines);
  for (var i = 0, e = chunk.lines.length; i < e; ++i) {
  var line = chunk.lines[i], lh = line.height;
  if (h < lh) break;
  h -= lh;
  }
  return n + i;
  }
  function heightAtLine(chunk, n) {
  var h = 0;
  outer: do {
  for (var i = 0, e = chunk.children.length; i < e; ++i) {
  var child = chunk.children[i], sz = child.chunkSize();
  if (n < sz) { chunk = child; continue outer; }
  n -= sz;
  h += child.height;
  }
  return h;
  } while (!chunk.lines);
  for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
  return h;
  }
 
  // The history object 'chunks' changes that are made close together
  // and at almost the same time into bigger undoable units.
  function History() {
  this.time = 0;
  this.done = []; this.undone = [];
  }
  History.prototype = {
  addChange: function(start, added, old) {
  this.undone.length = 0;
  var time = +new Date, last = this.done[this.done.length - 1];
  if (time - this.time > 400 || !last ||
  last.start > start + added || last.start + last.added < start - last.added + last.old.length)
  this.done.push({start: start, added: added, old: old});
  else {
  var oldoff = 0;
  if (start < last.start) {
  for (var i = last.start - start - 1; i >= 0; --i)
  last.old.unshift(old[i]);
  last.added += last.start - start;
  last.start = start;
  }
  else if (last.start < start) {
  oldoff = start - last.start;
  added += oldoff;
  }
  for (var i = last.added - oldoff, e = old.length; i < e; ++i)
  last.old.push(old[i]);
  if (last.added < added) last.added = added;
  }
  this.time = time;
  }
  };
 
  function stopMethod() {e_stop(this);}
  // Ensure an event has a stop method.
  function addStop(event) {
  if (!event.stop) event.stop = stopMethod;
  return event;
  }
 
  function e_preventDefault(e) {
  if (e.preventDefault) e.preventDefault();
  else e.returnValue = false;
  }
  function e_stopPropagation(e) {
  if (e.stopPropagation) e.stopPropagation();
  else e.cancelBubble = true;
  }
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  CodeMirror.e_stop = e_stop;
  CodeMirror.e_preventDefault = e_preventDefault;
  CodeMirror.e_stopPropagation = e_stopPropagation;
 
  function e_target(e) {return e.target || e.srcElement;}
  function e_button(e) {
  if (e.which) return e.which;
  else if (e.button & 1) return 1;
  else if (e.button & 2) return 3;
  else if (e.button & 4) return 2;
  }
 
  // Event handler registration. If disconnect is true, it'll return a
  // function that unregisters the handler.
  function connect(node, type, handler, disconnect) {
  if (typeof node.addEventListener == "function") {
  node.addEventListener(type, handler, false);
  if (disconnect) return function() {node.removeEventListener(type, handler, false);};
  }
  else {
  var wrapHandler = function(event) {handler(event || window.event);};
  node.attachEvent("on" + type, wrapHandler);
  if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
  }
  }
  CodeMirror.connect = connect;
 
  function Delayed() {this.id = null;}
  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
 
  // Detect drag-and-drop
  var dragAndDrop = function() {
  // IE8 has ondragstart and ondrop properties, but doesn't seem to
  // actually support ondragstart the way it's supposed to work.
  if (/MSIE [1-8]\b/.test(navigator.userAgent)) return false;
  var div = document.createElement('div');
  return "draggable" in div;
  }();
 
  var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
  var ie = /MSIE \d/.test(navigator.userAgent);
  var webkit = /WebKit\//.test(navigator.userAgent);
 
  var lineSep = "\n";
  // Feature-detect whether newlines in textareas are converted to \r\n
  (function () {
  var te = document.createElement("textarea");
  te.value = "foo\nbar";
  if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
  }());
 
  // Counts the column offset in a string, taking tabs into account.
  // Used mostly to find indentation.
  function countColumn(string, end, tabSize) {
  if (end == null) {
  end = string.search(/[^\s\u00a0]/);
  if (end == -1) end = string.length;
  }
  for (var i = 0, n = 0; i < end; ++i) {
  if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
  else ++n;
  }
  return n;
  }
 
  function computedStyle(elt) {
  if (elt.currentStyle) return elt.currentStyle;
  return window.getComputedStyle(elt, null);
  }
 
  // Find the position of an element by following the offsetParent chain.
  // If screen==true, it returns screen (rather than page) coordinates.
  function eltOffset(node, screen) {
  var bod = node.ownerDocument.body;
  var x = 0, y = 0, skipBody = false;
  for (var n = node; n; n = n.offsetParent) {
  var ol = n.offsetLeft, ot = n.offsetTop;
  // Firefox reports weird inverted offsets when the body has a border.
  if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); }
  else { x += ol, y += ot; }
  if (screen && computedStyle(n).position == "fixed")
  skipBody = true;
  }
  var e = screen && !skipBody ? null : bod;
  for (var n = node.parentNode; n != e; n = n.parentNode)
  if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
  return {left: x, top: y};
  }
  // Use the faster and saner getBoundingClientRect method when possible.
  if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) {
  // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
  // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
  try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
  catch(e) { box = {top: 0, left: 0}; }
  if (!screen) {
  // Get the toplevel scroll, working around browser differences.
  if (window.pageYOffset == null) {
  var t = document.documentElement || document.body.parentNode;
  if (t.scrollTop == null) t = document.body;
  box.top += t.scrollTop; box.left += t.scrollLeft;
  } else {
  box.top += window.pageYOffset; box.left += window.pageXOffset;
  }
  }
  return box;
  };
 
  // Get a node's text content.
  function eltText(node) {
  return node.textContent || node.innerText || node.nodeValue || "";
  }
 
  // Operations on {line, ch} objects.
  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
  function copyPos(x) {return {line: x.line, ch: x.ch};}
 
  var escapeElement = document.createElement("pre");
  function htmlEscape(str) {
  escapeElement.textContent = str;
  return escapeElement.innerHTML;
  }
  // Recent (late 2011) Opera betas insert bogus newlines at the start
  // of the textContent, so we strip those.
  if (htmlEscape("a") == "\na")
  htmlEscape = function(str) {
  escapeElement.textContent = str;
  return escapeElement.innerHTML.slice(1);
  };
  // Some IEs don't preserve tabs through innerHTML
  else if (htmlEscape("\t") != "\t")
  htmlEscape = function(str) {
  escapeElement.innerHTML = "";
  escapeElement.appendChild(document.createTextNode(str));
  return escapeElement.innerHTML;
  };
  CodeMirror.htmlEscape = htmlEscape;
 
  // Used to position the cursor after an undo/redo by finding the
  // last edited character.
  function editEnd(from, to) {
  if (!to) return from ? from.length : 0;
  if (!from) return to.length;
  for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
  if (from.charAt(i) != to.charAt(j)) break;
  return j + 1;
  }
 
  function indexOf(collection, elt) {
  if (collection.indexOf) return collection.indexOf(elt);
  for (var i = 0, e = collection.length; i < e; ++i)
  if (collection[i] == elt) return i;
  return -1;
  }
  function isWordChar(ch) {
  return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
  }
 
  // See if "".split is the broken IE version, if so, provide an
  // alternative way to split lines.
  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  var pos = 0, nl, result = [];
  while ((nl = string.indexOf("\n", pos)) > -1) {
  result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
  pos = nl + 1;
  }
  result.push(string.slice(pos));
  return result;
  } : function(string){return string.split(/\r?\n/);};
  CodeMirror.splitLines = splitLines;
 
  var hasSelection = window.getSelection ? function(te) {
  try { return te.selectionStart != te.selectionEnd; }
  catch(e) { return false; }
  } : function(te) {
  try {var range = te.ownerDocument.selection.createRange();}
  catch(e) {}
  if (!range || range.parentElement() != te) return false;
  return range.compareEndPoints("StartToEnd", range) != 0;
  };
 
  CodeMirror.defineMode("null", function() {
  return {token: function(stream) {stream.skipToEnd();}};
  });
  CodeMirror.defineMIME("text/plain", "null");
 
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 186: ";", 187: "=", 188: ",",
  189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp",
  63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right",
  63233: "Down", 63302: "Insert", 63272: "Delete"};
  CodeMirror.keyNames = keyNames;
  (function() {
  // Number keys
  for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
  // Alphabetic keys
  for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  // Function keys
  for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  })();
 
  return CodeMirror;
  })();
 
  .CodeMirror-dialog {
  position: relative;
  }
 
  .CodeMirror-dialog > div {
  position: absolute;
  top: 0; left: 0; right: 0;
  background: white;
  border-bottom: 1px solid #eee;
  z-index: 15;
  padding: .1em .8em;
  overflow: hidden;
  color: #333;
  }
 
  .CodeMirror-dialog input {
  border: none;
  outline: none;
  background: transparent;
  width: 20em;
  color: inherit;
  font-family: monospace;
  }
 
  // Open simple dialogs on top of an editor. Relies on dialog.css.
 
  (function() {
  function dialogDiv(cm, template) {
  var wrap = cm.getWrapperElement();
  var dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
  dialog.className = "CodeMirror-dialog";
  dialog.innerHTML = '<div>' + template + '</div>';
  return dialog;
  }
 
  CodeMirror.defineExtension("openDialog", function(template, callback) {
  var dialog = dialogDiv(this, template);
  var closed = false, me = this;
  function close() {
  if (closed) return;
  closed = true;
  dialog.parentNode.removeChild(dialog);
  }
  var inp = dialog.getElementsByTagName("input")[0];
  if (inp) {
  CodeMirror.connect(inp, "keydown", function(e) {
  if (e.keyCode == 13 || e.keyCode == 27) {
  CodeMirror.e_stop(e);
  close();
  me.focus();
  if (e.keyCode == 13) callback(inp.value);
  }
  });
  inp.focus();
  CodeMirror.connect(inp, "blur", close);
  }
  return close;
  });
 
  CodeMirror.defineExtension("openConfirm", function(template, callbacks) {
  var dialog = dialogDiv(this, template);
  var buttons = dialog.getElementsByTagName("button");
  var closed = false, me = this, blurring = 1;
  function close() {
  if (closed) return;
  closed = true;
  dialog.parentNode.removeChild(dialog);
  me.focus();
  }
  buttons[0].focus();
  for (var i = 0; i < buttons.length; ++i) {
  var b = buttons[i];
  (function(callback) {
  CodeMirror.connect(b, "click", function(e) {
  CodeMirror.e_preventDefault(e);
  close();
  if (callback) callback(me);
  });
  })(callbacks[i]);
  CodeMirror.connect(b, "blur", function() {
  --blurring;
  setTimeout(function() { if (blurring <= 0) close(); }, 200);
  });
  CodeMirror.connect(b, "focus", function() { ++blurring; });
  }
  });
  })();
  CodeMirror.braceRangeFinder = function(cm, line) {
  var lineText = cm.getLine(line);
  var startChar = lineText.lastIndexOf("{");
  if (startChar < 0 || lineText.lastIndexOf("}") > startChar) return;
  var tokenType = cm.getTokenAt({line: line, ch: startChar}).className;
  var count = 1, lastLine = cm.lineCount(), end;
  outer: for (var i = line + 1; i < lastLine; ++i) {
  var text = cm.getLine(i), pos = 0;
  for (;;) {
  var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", pos);
  if (nextOpen < 0) nextOpen = text.length;
  if (nextClose < 0) nextClose = text.length;
  pos = Math.min(nextOpen, nextClose);
  if (pos == text.length) break;
  if (cm.getTokenAt({line: i, ch: pos + 1}).className == tokenType) {
  if (pos == nextOpen) ++count;
  else if (!--count) { end = i; break outer; }
  }
  ++pos;
  }
  }
  if (end == null || end == line + 1) return;
  return end;
  };
 
 
  CodeMirror.newFoldFunction = function(rangeFinder, markText) {
  var folded = [];
  if (markText == null) markText = '<div style="position: absolute; left: 2px; color:#600">&#x25bc;</div>%N%';
 
  function isFolded(cm, n) {
  for (var i = 0; i < folded.length; ++i) {
  var start = cm.lineInfo(folded[i].start);
  if (!start) folded.splice(i--, 1);
  else if (start.line == n) return {pos: i, region: folded[i]};
  }
  }
 
  function expand(cm, region) {
  cm.clearMarker(region.start);
  for (var i = 0; i < region.hidden.length; ++i)
  cm.showLine(region.hidden[i]);
  }
 
  return function(cm, line) {
  cm.operation(function() {
  var known = isFolded(cm, line);
  if (known) {
  folded.splice(known.pos, 1);
  expand(cm, known.region);
  } else {
  var end = rangeFinder(cm, line);
  if (end == null) return;
  var hidden = [];
  for (var i = line + 1; i < end; ++i) {
  var handle = cm.hideLine(i);
  if (handle) hidden.push(handle);
  }
  var first = cm.setMarker(line, markText);
  var region = {start: first, hidden: hidden};
  cm.onDeleteLine(first, function() { expand(cm, region); });
  folded.push(region);
  }
  });
  };
  };
 
  // ============== Formatting extensions ============================
  // A common storage for all mode-specific formatting features
  if (!CodeMirror.modeExtensions) CodeMirror.modeExtensions = {};
 
  // Returns the extension of the editor's current mode
  CodeMirror.defineExtension("getModeExt", function () {
  return CodeMirror.modeExtensions[this.getOption("mode")];
  });
 
  // If the current mode is 'htmlmixed', returns the extension of a mode located at
  // the specified position (can be htmlmixed, css or javascript). Otherwise, simply
  // returns the extension of the editor's current mode.
  CodeMirror.defineExtension("getModeExtAtPos", function (pos) {
  var token = this.getTokenAt(pos);
  if (token && token.state && token.state.mode)
  return CodeMirror.modeExtensions[token.state.mode == "html" ? "htmlmixed" : token.state.mode];
  else
  return this.getModeExt();
  });
 
  // Comment/uncomment the specified range
  CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
  var curMode = this.getModeExtAtPos(this.getCursor());
  if (isComment) { // Comment range
  var commentedText = this.getRange(from, to);
  this.replaceRange(curMode.commentStart + this.getRange(from, to) + curMode.commentEnd
  , from, to);
  if (from.line == to.line && from.ch == to.ch) { // An empty comment inserted - put cursor inside
  this.setCursor(from.line, from.ch + curMode.commentStart.length);
  }
  }
  else { // Uncomment range
  var selText = this.getRange(from, to);
  var startIndex = selText.indexOf(curMode.commentStart);
  var endIndex = selText.lastIndexOf(curMode.commentEnd);
  if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
  // Take string till comment start
  selText = selText.substr(0, startIndex)
  // From comment start till comment end
  + selText.substring(startIndex + curMode.commentStart.length, endIndex)
  // From comment end till string end
  + selText.substr(endIndex + curMode.commentEnd.length);
  }
  this.replaceRange(selText, from, to);
  }
  });
 
  // Applies automatic mode-aware indentation to the specified range
  CodeMirror.defineExtension("autoIndentRange", function (from, to) {
  var cmInstance = this;
  this.operation(function () {
  for (var i = from.line; i <= to.line; i++) {
  cmInstance.indentLine(i);
  }
  });
  });
 
  // Applies automatic formatting to the specified range
  CodeMirror.defineExtension("autoFormatRange", function (from, to) {
  var absStart = this.indexFromPos(from);
  var absEnd = this.indexFromPos(to);
  // Insert additional line breaks where necessary according to the
  // mode's syntax
  var res = this.getModeExt().autoFormatLineBreaks(this.getValue(), absStart, absEnd);
  var cmInstance = this;
 
  // Replace and auto-indent the range
  this.operation(function () {
  cmInstance.replaceRange(res, from, to);
  var startLine = cmInstance.posFromIndex(absStart).line;
  var endLine = cmInstance.posFromIndex(absStart + res.length).line;
  for (var i = startLine; i <= endLine; i++) {
  cmInstance.indentLine(i);
  }
  });
  });
 
  // Define extensions for a few modes
 
  CodeMirror.modeExtensions["css"] = {
  commentStart: "/*",
  commentEnd: "*/",
  wordWrapChars: [";", "\\{", "\\}"],
  autoFormatLineBreaks: function (text) {
  return text.replace(new RegExp("(;|\\{|\\})([^\r\n])", "g"), "$1\n$2");
  }
  };
 
  CodeMirror.modeExtensions["javascript"] = {
  commentStart: "/*",
  commentEnd: "*/",
  wordWrapChars: [";", "\\{", "\\}"],
 
  getNonBreakableBlocks: function (text) {
  var nonBreakableRegexes = [
  new RegExp("for\\s*?\\(([\\s\\S]*?)\\)"),
  new RegExp("'([\\s\\S]*?)('|$)"),
  new RegExp("\"([\\s\\S]*?)(\"|$)"),
  new RegExp("//.*([\r\n]|$)")
  ];
  var nonBreakableBlocks = new Array();
  for (var i = 0; i < nonBreakableRegexes.length; i++) {
  var curPos = 0;
  while (curPos < text.length) {
  var m = text.substr(curPos).match(nonBreakableRegexes[i]);
  if (m != null) {
  nonBreakableBlocks.push({
  start: curPos + m.index,
  end: curPos + m.index + m[0].length
  });
  curPos += m.index + Math.max(1, m[0].length);
  }
  else { // No more matches
  break;
  }
  }
  }
  nonBreakableBlocks.sort(function (a, b) {
  return a.start - b.start;
  });
 
  return nonBreakableBlocks;
  },
 
  autoFormatLineBreaks: function (text) {
  var curPos = 0;
  var reLinesSplitter = new RegExp("(;|\\{|\\})([^\r\n])", "g");
  var nonBreakableBlocks = this.getNonBreakableBlocks(text);
  if (nonBreakableBlocks != null) {
  var res = "";
  for (var i = 0; i < nonBreakableBlocks.length; i++) {
  if (nonBreakableBlocks[i].start > curPos) { // Break lines till the block
  res += text.substring(curPos, nonBreakableBlocks[i].start).replace(reLinesSplitter, "$1\n$2");
  curPos = nonBreakableBlocks[i].start;
  }
  if (nonBreakableBlocks[i].start <= curPos
  && nonBreakableBlocks[i].end >= curPos) { // Skip non-breakable block
  res += text.substring(curPos, nonBreakableBlocks[i].end);
  curPos = nonBreakableBlocks[i].end;
  }
  }
  if (curPos < text.length - 1) {
  res += text.substr(curPos).replace(reLinesSplitter, "$1\n$2");
  }
  return res;
  }
  else {
  return text.replace(reLinesSplitter, "$1\n$2");
  }
  }
  };
 
  CodeMirror.modeExtensions["xml"] = {
  commentStart: "<!--",
  commentEnd: "-->",
  wordWrapChars: [">"],
 
  autoFormatLineBreaks: function (text) {
  var lines = text.split("\n");
  var reProcessedPortion = new RegExp("(^\\s*?<|^[^<]*?)(.+)(>\\s*?$|[^>]*?$)");
  var reOpenBrackets = new RegExp("<", "g");
  var reCloseBrackets = new RegExp("(>)([^\r\n])", "g");
  for (var i = 0; i < lines.length; i++) {
  var mToProcess = lines[i].match(reProcessedPortion);
  if (mToProcess != null && mToProcess.length > 3) { // The line starts with whitespaces and ends with whitespaces
  lines[i] = mToProcess[1]
  + mToProcess[2].replace(reOpenBrackets, "\n$&").replace(reCloseBrackets, "$1\n$2")
  + mToProcess[3];
  continue;
  }
  }
 
  return lines.join("\n");
  }
  };
 
  CodeMirror.modeExtensions["htmlmixed"] = {
  commentStart: "<!--",
  commentEnd: "-->",
  wordWrapChars: [">", ";", "\\{", "\\}"],
 
  getModeInfos: function (text, absPos) {
  var modeInfos = new Array();
  modeInfos[0] =
  {
  pos: 0,
  modeExt: CodeMirror.modeExtensions["xml"],
  modeName: "xml"
  };
 
  var modeMatchers = new Array();
  modeMatchers[0] =
  {
  regex: new RegExp("<style[^>]*>([\\s\\S]*?)(</style[^>]*>|$)", "i"),
  modeExt: CodeMirror.modeExtensions["css"],
  modeName: "css"
  };
  modeMatchers[1] =
  {
  regex: new RegExp("<script[^>]*>([\\s\\S]*?)(</script[^>]*>|$)", "i"),
  modeExt: CodeMirror.modeExtensions["javascript"],
  modeName: "javascript"
  };
 
  var lastCharPos = (typeof (absPos) !== "undefined" ? absPos : text.length - 1);
  // Detect modes for the entire text
  for (var i = 0; i < modeMatchers.length; i++) {
  var curPos = 0;
  while (curPos <= lastCharPos) {
  var m = text.substr(curPos).match(modeMatchers[i].regex);
  if (m != null) {
  if (m.length > 1 && m[1].length > 0) {
  // Push block begin pos
  var blockBegin = curPos + m.index + m[0].indexOf(m[1]);
  modeInfos.push(
  {
  pos: blockBegin,
  modeExt: modeMatchers[i].modeExt,
  modeName: modeMatchers[i].modeName
  });
  // Push block end pos
  modeInfos.push(
  {
  pos: blockBegin + m[1].length,
  modeExt: modeInfos[0].modeExt,
  modeName: modeInfos[0].modeName
  });
  curPos += m.index + m[0].length;
  continue;
  }
  else {
  curPos += m.index + Math.max(m[0].length, 1);
  }
  }
  else { // No more matches
  break;
  }
  }
  }
  // Sort mode infos
  modeInfos.sort(function sortModeInfo(a, b) {
  return a.pos - b.pos;
  });
 
  return modeInfos;
  },
 
  autoFormatLineBreaks: function (text, startPos, endPos) {
  var modeInfos = this.getModeInfos(text);
  var reBlockStartsWithNewline = new RegExp("^\\s*?\n");
  var reBlockEndsWithNewline = new RegExp("\n\\s*?$");
  var res = "";
  // Use modes info to break lines correspondingly
  if (modeInfos.length > 1) { // Deal with multi-mode text
  for (var i = 1; i <= modeInfos.length; i++) {
  var selStart = modeInfos[i - 1].pos;
  var selEnd = (i < modeInfos.length ? modeInfos[i].pos : endPos);
 
  if (selStart >= endPos) { // The block starts later than the needed fragment
  break;
  }
  if (selStart < startPos) {
  if (selEnd <= startPos) { // The block starts earlier than the needed fragment
  continue;
  }
  selStart = startPos;
  }
  if (selEnd > endPos) {
  selEnd = endPos;
  }
  var textPortion = text.substring(selStart, selEnd);
  if (modeInfos[i - 1].modeName != "xml") { // Starting a CSS or JavaScript block
  if (!reBlockStartsWithNewline.test(textPortion)
  && selStart > 0) { // The block does not start with a line break
  textPortion = "\n" + textPortion;
  }
  if (!reBlockEndsWithNewline.test(textPortion)
  && selEnd < text.length - 1) { // The block does not end with a line break
  textPortion += "\n";
  }
  }
  res += modeInfos[i - 1].modeExt.autoFormatLineBreaks(textPortion);
  }
  }
  else { // Single-mode text
  res = modeInfos[0].modeExt.autoFormatLineBreaks(text.substring(startPos, endPos));
  }
 
  return res;
  }
  };
 
  (function () {
  function forEach(arr, f) {
  for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
  }
 
  function arrayContains(arr, item) {
  if (!Array.prototype.indexOf) {
  var i = arr.length;
  while (i--) {
  if (arr[i] === item) {
  return true;
  }
  }
  return false;
  }
  return arr.indexOf(item) != -1;
  }
 
  CodeMirror.javascriptHint = function(editor) {
  // Find the token at the cursor
  var cur = editor.getCursor(), token = editor.getTokenAt(cur), tprop = token;
  // If it's not a 'word-style' token, ignore the token.
  if (!/^[\w$_]*$/.test(token.string)) {
  token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
  className: token.string == "." ? "property" : null};
  }
  // If it is a property, find out what it is a property of.
  while (tprop.className == "property") {
  tprop = editor.getTokenAt({line: cur.line, ch: tprop.start});
  if (tprop.string != ".") return;
  tprop = editor.getTokenAt({line: cur.line, ch: tprop.start});
  if (!context) var context = [];
  context.push(tprop);
  }
  return {list: getCompletions(token, context),
  from: {line: cur.line, ch: token.start},
  to: {line: cur.line, ch: token.end}};
  }
 
  var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
  "toUpperCase toLowerCase split concat match replace search").split(" ");
  var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
  "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
  var funcProps = "prototype apply call bind".split(" ");
  var keywords = ("break case catch continue debugger default delete do else false finally for function " +
  "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
 
  function getCompletions(token, context) {
  var found = [], start = token.string;
  function maybeAdd(str) {
  if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
  }
  function gatherCompletions(obj) {
  if (typeof obj == "string") forEach(stringProps, maybeAdd);
  else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
  else if (obj instanceof Function) forEach(funcProps, maybeAdd);
  for (var name in obj) maybeAdd(name);
  }
 
  if (context) {
  // If this is a property, see if it belongs to some object we can
  // find in the current environment.
  var obj = context.pop(), base;
  if (obj.className == "variable")
  base = window[obj.string];
  else if (obj.className == "string")
  base = "";
  else if (obj.className == "atom")
  base = 1;
  while (base != null && context.length)
  base = base[context.pop().string];
  if (base != null) gatherCompletions(base);
  }
  else {
  // If not, just look in the window object and any local scope
  // (reading into JS mode internals to get at the local variables)
  for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
  gatherCompletions(window);
  forEach(keywords, maybeAdd);
  }
  return found;
  }
  })();
 
  // Utility function that allows modes to be combined. The mode given
  // as the base argument takes care of most of the normal mode
  // functionality, but a second (typically simple) mode is used, which
  // can override the style of text. Both modes get to parse all of the
  // text, but when both assign a non-null style to a piece of code, the
  // overlay wins, unless the combine argument was true, in which case
  // the styles are combined.
 
  CodeMirror.overlayParser = function(base, overlay, combine) {
  return {
  startState: function() {
  return {
  base: CodeMirror.startState(base),
  overlay: CodeMirror.startState(overlay),
  basePos: 0, baseCur: null,
  overlayPos: 0, overlayCur: null
  };
  },
  copyState: function(state) {
  return {
  base: CodeMirror.copyState(base, state.base),
  overlay: CodeMirror.copyState(overlay, state.overlay),
  basePos: state.basePos, baseCur: null,
  overlayPos: state.overlayPos, overlayCur: null
  };
  },
 
  token: function(stream, state) {
  if (stream.start == state.basePos) {
  state.baseCur = base.token(stream, state.base);
  state.basePos = stream.pos;
  }
  if (stream.start == state.overlayPos) {
  stream.pos = stream.start;
  state.overlayCur = overlay.token(stream, state.overlay);
  state.overlayPos = stream.pos;
  }
  stream.pos = Math.min(state.basePos, state.overlayPos);
  if (stream.eol()) state.basePos = state.overlayPos = 0;
 
  if (state.overlayCur == null) return state.baseCur;
  if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
  else return state.overlayCur;
  },
 
  indent: function(state, textAfter) {
  return base.indent(state.base, textAfter);
  },
  electricChars: base.electricChars
  };
  };
 
  CodeMirror.runMode = function(string, modespec, callback) {
  var mode = CodeMirror.getMode({indentUnit: 2}, modespec);
  var isNode = callback.nodeType == 1;
  if (isNode) {
  var node = callback, accum = [];
  callback = function(string, style) {
  if (string == "\n")
  accum.push("<br>");
  else if (style)
  accum.push("<span class=\"cm-" + CodeMirror.htmlEscape(style) + "\">" + CodeMirror.htmlEscape(string) + "</span>");
  else
  accum.push(CodeMirror.htmlEscape(string));
  }
  }
  var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
  for (var i = 0, e = lines.length; i < e; ++i) {
  if (i) callback("\n");
  var stream = new CodeMirror.StringStream(lines[i]);
  while (!stream.eol()) {
  var style = mode.token(stream, state);
  callback(stream.current(), style, i, stream.start);
  stream.start = stream.pos;
  }
  }
  if (isNode)
  node.innerHTML = accum.join("");
  };
 
  // Define search commands. Depends on dialog.js or another
  // implementation of the openDialog method.
 
  // Replace works a little oddly -- it will do the replace on the next
  // Ctrl-G (or whatever is bound to findNext) press. You prevent a
  // replace by making sure the match is no longer selected when hitting
  // Ctrl-G.
 
  (function() {
  function SearchState() {
  this.posFrom = this.posTo = this.query = null;
  this.marked = [];
  }
  function getSearchState(cm) {
  return cm._searchState || (cm._searchState = new SearchState());
  }
  function dialog(cm, text, shortText, f) {
  if (cm.openDialog) cm.openDialog(text, f);
  else f(prompt(shortText, ""));
  }
  function confirmDialog(cm, text, shortText, fs) {
  if (cm.openConfirm) cm.openConfirm(text, fs);
  else if (confirm(shortText)) fs[0]();
  }
  function parseQuery(query) {
  var isRE = query.match(/^\/(.*)\/$/);
  return isRE ? new RegExp(isRE[1]) : query;
  }
  var queryDialog =
  'Search: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
  function doSearch(cm, rev) {
  var state = getSearchState(cm);
  if (state.query) return findNext(cm, rev);
  dialog(cm, queryDialog, "Search for:", function(query) {
  cm.operation(function() {
  if (!query || state.query) return;
  state.query = parseQuery(query);
  if (cm.lineCount() < 2000) { // This is too expensive on big documents.
  for (var cursor = cm.getSearchCursor(query); cursor.findNext();)
  state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching"));
  }
  state.posFrom = state.posTo = cm.getCursor();
  findNext(cm, rev);
  });
  });
  }
  function findNext(cm, rev) {cm.operation(function() {
  var state = getSearchState(cm);
  var cursor = cm.getSearchCursor(state.query, rev ? state.posFrom : state.posTo);
  if (!cursor.find(rev)) {
  cursor = cm.getSearchCursor(state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
  if (!cursor.find(rev)) return;
  }
  cm.setSelection(cursor.from(), cursor.to());
  state.posFrom = cursor.from(); state.posTo = cursor.to();
  })}
  function clearSearch(cm) {cm.operation(function() {
  var state = getSearchState(cm);
  if (!state.query) return;
  state.query = null;
  for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
  state.marked.length = 0;
  })}
 
  var replaceQueryDialog =
  'Replace: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
  var replacementQueryDialog = 'With: <input type="text" style="width: 10em">';
  var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
  function replace(cm, all) {
  dialog(cm, replaceQueryDialog, "Replace:", function(query) {
  if (!query) return;
  query = parseQuery(query);
  dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
  if (all) {
  cm.operation(function() {
  for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
  if (typeof query != "string") {
  var match = cm.getRange(cursor.from(), cursor.to()).match(query);
  cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];}));
  } else cursor.replace(text);
  }
  });
  } else {
  clearSearch(cm);
  var cursor = cm.getSearchCursor(query, cm.getCursor());
  function advance() {
  var start = cursor.from(), match;
  if (!(match = cursor.findNext())) {
  cursor = cm.getSearchCursor(query);
  if (!(match = cursor.findNext()) ||
  (cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
  }
  cm.setSelection(cursor.from(), cursor.to());
  confirmDialog(cm, doReplaceConfirm, "Replace?",
  [function() {doReplace(match);}, advance]);
  }
  function doReplace(match) {
  cursor.replace(typeof query == "string" ? text :
  text.replace(/\$(\d)/, function(w, i) {return match[i];}));
  advance();
  }
  advance();
  }
  });
  });
  }
 
  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  CodeMirror.commands.findNext = doSearch;
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  CodeMirror.commands.clearSearch = clearSearch;
  CodeMirror.commands.replace = replace;
  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
  })();
 
  (function(){
  function SearchCursor(cm, query, pos, caseFold) {
  this.atOccurrence = false; this.cm = cm;
  if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
 
  pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0};
  this.pos = {from: pos, to: pos};
 
  // The matches method is filled in based on the type of query.
  // It takes a position and a direction, and returns an object
  // describing the next occurrence of the query, or null if no
  // more matches were found.
  if (typeof query != "string") // Regexp match
  this.matches = function(reverse, pos) {
  if (reverse) {
  var line = cm.getLine(pos.line).slice(0, pos.ch), match = line.match(query), start = 0;
  while (match) {
  var ind = line.indexOf(match[0]);
  start += ind;
  line = line.slice(ind + 1);
  var newmatch = line.match(query);
  if (newmatch) match = newmatch;
  else break;
  start++;
  }
  }
  else {
  var line = cm.getLine(pos.line).slice(pos.ch), match = line.match(query),
  start = match && pos.ch + line.indexOf(match[0]);
  }
  if (match)
  return {from: {line: pos.line, ch: start},
  to: {line: pos.line, ch: start + match[0].length},
  match: match};
  };
  else { // String query
  if (caseFold) query = query.toLowerCase();
  var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
  var target = query.split("\n");
  // Different methods for single-line and multi-line queries
  if (target.length == 1)
  this.matches = function(reverse, pos) {
  var line = fold(cm.getLine(pos.line)), len = query.length, match;
  if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
  : (match = line.indexOf(query, pos.ch)) != -1)
  return {from: {line: pos.line, ch: match},
  to: {line: pos.line, ch: match + len}};
  };
  else
  this.matches = function(reverse, pos) {
  var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
  var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
  if (reverse ? offsetA >= pos.ch || offsetA != match.length
  : offsetA <= pos.ch || offsetA != line.length - match.length)
  return;
  for (;;) {
  if (reverse ? !ln : ln == cm.lineCount() - 1) return;
  line = fold(cm.getLine(ln += reverse ? -1 : 1));
  match = target[reverse ? --idx : ++idx];
  if (idx > 0 && idx < target.length - 1) {
  if (line != match) return;
  else continue;
  }
  var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
  if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
  return;
  var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
  return {from: reverse ? end : start, to: reverse ? start : end};
  }
  };
  }
  }
 
  SearchCursor.prototype = {
  findNext: function() {return this.find(false);},
  findPrevious: function() {return this.find(true);},
 
  find: function(reverse) {
  var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to);
  function savePosAndFail(line) {
  var pos = {line: line, ch: 0};
  self.pos = {from: pos, to: pos};
  self.atOccurrence = false;
  return false;
  }
 
  for (;;) {
  if (this.pos = this.matches(reverse, pos)) {
  this.atOccurrence = true;
  return this.pos.match || true;
  }
  if (reverse) {
  if (!pos.line) return savePosAndFail(0);
  pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length};
  }
  else {
  var maxLine = this.cm.lineCount();
  if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
  pos = {line: pos.line+1, ch: 0};
  }
  }
  },
 
  from: function() {if (this.atOccurrence) return this.pos.from;},
  to: function() {if (this.atOccurrence) return this.pos.to;},
 
  replace: function(newText) {
  var self = this;
  if (this.atOccurrence)
  self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to);
  }
  };
 
  CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
  return new SearchCursor(this, query, pos, caseFold);
  });
  })();
 
  .CodeMirror-completions {
  position: absolute;
  z-index: 10;
  overflow: hidden;
  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  }
  .CodeMirror-completions select {
  background: #fafafa;
  outline: none;
  border: none;
  padding: 0;
  margin: 0;
  font-family: monospace;
  }
 
  (function() {
  CodeMirror.simpleHint = function(editor, getHints) {
  // We want a single cursor position.
  if (editor.somethingSelected()) return;
  var result = getHints(editor);
  if (!result || !result.list.length) return;
  var completions = result.list;
  function insert(str) {
  editor.replaceRange(str, result.from, result.to);
  }
  // When there is only one completion, use it directly.
  if (completions.length == 1) {insert(completions[0]); return true;}
 
  // Build the select widget
  var complete = document.createElement("div");
  complete.className = "CodeMirror-completions";
  var sel = complete.appendChild(document.createElement("select"));
  // Opera doesn't move the selection when pressing up/down in a
  // multi-select, but it does properly support the size property on
  // single-selects, so no multi-select is necessary.
  if (!window.opera) sel.multiple = true;
  for (var i = 0; i < completions.length; ++i) {
  var opt = sel.appendChild(document.createElement("option"));
  opt.appendChild(document.createTextNode(completions[i]));
  }
  sel.firstChild.selected = true;
  sel.size = Math.min(10, completions.length);
  var pos = editor.cursorCoords();
  complete.style.left = pos.x + "px";
  complete.style.top = pos.yBot + "px";
  document.body.appendChild(complete);
  // Hack to hide the scrollbar.
  if (completions.length <= 10)
  complete.style.width = (sel.clientWidth - 1) + "px";
 
  var done = false;
  function close() {
  if (done) return;
  done = true;
  complete.parentNode.removeChild(complete);
  }
  function pick() {
  insert(completions[sel.selectedIndex]);
  close();
  setTimeout(function(){editor.focus();}, 50);
  }
  CodeMirror.connect(sel, "blur", close);
  CodeMirror.connect(sel, "keydown", function(event) {
  var code = event.keyCode;
  // Enter
  if (code == 13) {CodeMirror.e_stop(event); pick();}
  // Escape
  else if (code == 27) {CodeMirror.e_stop(event); close(); editor.focus();}
  else if (code != 38 && code != 40) {
  close(); editor.focus();
  setTimeout(function(){CodeMirror.simpleHint(editor, getHints);}, 50);
  }
  });
  CodeMirror.connect(sel, "dblclick", pick);
 
  sel.focus();
  // Opera sometimes ignores focusing a freshly created node
  if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100);
  return true;
  };
  })();
 
  CodeMirror.defineMode("clike", function(config, parserConfig) {
  var indentUnit = config.indentUnit,
  keywords = parserConfig.keywords || {},
  blockKeywords = parserConfig.blockKeywords || {},
  atoms = parserConfig.atoms || {},
  hooks = parserConfig.hooks || {},
  multiLineStrings = parserConfig.multiLineStrings;
  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
 
  var curPunc;
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  if (hooks[ch]) {
  var result = hooks[ch](stream, state);
  if (result !== false) return result;
  }
  if (ch == '"' || ch == "'") {
  state.tokenize = tokenString(ch);
  return state.tokenize(stream, state);
  }
  if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
  curPunc = ch;
  return null
  }
  if (/\d/.test(ch)) {
  stream.eatWhile(/[\w\.]/);
  return "number";
  }
  if (ch == "/") {
  if (stream.eat("*")) {
  state.tokenize = tokenComment;
  return tokenComment(stream, state);
  }
  if (stream.eat("/")) {
  stream.skipToEnd();
  return "comment";
  }
  }
  if (isOperatorChar.test(ch)) {
  stream.eatWhile(isOperatorChar);
  return "operator";
  }
  stream.eatWhile(/[\w\$_]/);
  var cur = stream.current();
  if (keywords.propertyIsEnumerable(cur)) {
  if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
  return "keyword";
  }
  if (atoms.propertyIsEnumerable(cur)) return "atom";
  return "word";
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  var escaped = false, next, end = false;
  while ((next = stream.next()) != null) {
  if (next == quote && !escaped) {end = true; break;}
  escaped = !escaped && next == "\\";
  }
  if (end || !(escaped || multiLineStrings))
  state.tokenize = tokenBase;
  return "string";
  };
  }
 
  function tokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize = tokenBase;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return "comment";
  }
 
  function Context(indented, column, type, align, prev) {
  this.indented = indented;
  this.column = column;
  this.type = type;
  this.align = align;
  this.prev = prev;
  }
  function pushContext(state, col, type) {
  return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
  var t = state.context.type;
  if (t == ")" || t == "]" || t == "}")
  state.indented = state.context.indented;
  return state.context = state.context.prev;
  }
 
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: null,
  context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
  indented: 0,
  startOfLine: true
  };
  },
 
  token: function(stream, state) {
  var ctx = state.context;
  if (stream.sol()) {
  if (ctx.align == null) ctx.align = false;
  state.indented = stream.indentation();
  state.startOfLine = true;
  }
  if (stream.eatSpace()) return null;
  curPunc = null;
  var style = (state.tokenize || tokenBase)(stream, state);
  if (style == "comment" || style == "meta") return style;
  if (ctx.align == null) ctx.align = true;
 
  if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
  else if (curPunc == "{") pushContext(state, stream.column(), "}");
  else if (curPunc == "[") pushContext(state, stream.column(), "]");
  else if (curPunc == "(") pushContext(state, stream.column(), ")");
  else if (curPunc == "}") {
  while (ctx.type == "statement") ctx = popContext(state);
  if (ctx.type == "}") ctx = popContext(state);
  while (ctx.type == "statement") ctx = popContext(state);
  }
  else if (curPunc == ctx.type) popContext(state);
  else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
  pushContext(state, stream.column(), "statement");
  state.startOfLine = false;
  return style;
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != tokenBase && state.tokenize != null) return 0;
  var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
  if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
  var closing = firstChar == ctx.type;
  if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
  else if (ctx.align) return ctx.column + (closing ? 0 : 1);
  else return ctx.indented + (closing ? 0 : indentUnit);
  },
 
  electricChars: "{}"
  };
  });
 
  (function() {
  function words(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
  var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
  "double static else struct entry switch extern typedef float union for unsigned " +
  "goto while enum void const signed volatile";
 
  function cppHook(stream, state) {
  if (!state.startOfLine) return false;
  stream.skipToEnd();
  return "meta";
  }
 
  // C#-style strings where "" escapes a quote.
  function tokenAtString(stream, state) {
  var next;
  while ((next = stream.next()) != null) {
  if (next == '"' && !stream.eat('"')) {
  state.tokenize = null;
  break;
  }
  }
  return "string";
  }
 
  CodeMirror.defineMIME("text/x-csrc", {
  name: "clike",
  keywords: words(cKeywords),
  blockKeywords: words("case do else for if switch while struct"),
  atoms: words("null"),
  hooks: {"#": cppHook}
  });
  CodeMirror.defineMIME("text/x-c++src", {
  name: "clike",
  keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
  "static_cast typeid catch operator template typename class friend private " +
  "this using const_cast inline public throw virtual delete mutable protected " +
  "wchar_t"),
  blockKeywords: words("catch class do else finally for if struct switch try while"),
  atoms: words("true false null"),
  hooks: {"#": cppHook}
  });
  CodeMirror.defineMIME("text/x-java", {
  name: "clike",
  keywords: words("abstract assert boolean break byte case catch char class const continue default " +
  "do double else enum extends final finally float for goto if implements import " +
  "instanceof int interface long native new package private protected public " +
  "return short static strictfp super switch synchronized this throw throws transient " +
  "try void volatile while"),
  blockKeywords: words("catch class do else finally for if switch try while"),
  atoms: words("true false null"),
  hooks: {
  "@": function(stream, state) {
  stream.eatWhile(/[\w\$_]/);
  return "meta";
  }
  }
  });
  CodeMirror.defineMIME("text/x-csharp", {
  name: "clike",
  keywords: words("abstract as base bool break byte case catch char checked class const continue decimal" +
  " default delegate do double else enum event explicit extern finally fixed float for" +
  " foreach goto if implicit in int interface internal is lock long namespace new object" +
  " operator out override params private protected public readonly ref return sbyte sealed short" +
  " sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked" +
  " unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" +
  " global group into join let orderby partial remove select set value var yield"),
  blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
  atoms: words("true false null"),
  hooks: {
  "@": function(stream, state) {
  if (stream.eat('"')) {
  state.tokenize = tokenAtString;
  return tokenAtString(stream, state);
  }
  stream.eatWhile(/[\w\$_]/);
  return "meta";
  }
  }
  });
  CodeMirror.defineMIME("text/x-groovy", {
  name: "clike",
  keywords: words("abstract as assert boolean break byte case catch char class const continue def default " +
  "do double else enum extends final finally float for goto if implements import " +
  "in instanceof int interface long native new package property private protected public " +
  "return short static strictfp super switch synchronized this throw throws transient " +
  "try void volatile while"),
  atoms: words("true false null"),
  hooks: {
  "@": function(stream, state) {
  stream.eatWhile(/[\w\$_]/);
  return "meta";
  }
  }
  });
  }());
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: C-like mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="clike.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style>.CodeMirror {border: 2px inset #dee;}</style>
  </head>
  <body>
  <h1>CodeMirror: C-like mode</h1>
 
  <form><textarea id="code" name="code">
  /* C demo code */
 
  #include <zmq.h>
  #include <pthread.h>
  #include <semaphore.h>
  #include <time.h>
  #include <stdio.h>
  #include <fcntl.h>
  #include <malloc.h>
 
  typedef struct {
  void* arg_socket;
  zmq_msg_t* arg_msg;
  char* arg_string;
  unsigned long arg_len;
  int arg_int, arg_command;
 
  int signal_fd;
  int pad;
  void* context;
  sem_t sem;
  } acl_zmq_context;
 
  #define p(X) (context->arg_##X)
 
  void* zmq_thread(void* context_pointer) {
  acl_zmq_context* context = (acl_zmq_context*)context_pointer;
  char ok = 'K', err = 'X';
  int res;
 
  while (1) {
  while ((res = sem_wait(&amp;context->sem)) == EINTR);
  if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
  switch(p(command)) {
  case 0: goto cleanup;
  case 1: p(socket) = zmq_socket(context->context, p(int)); break;
  case 2: p(int) = zmq_close(p(socket)); break;
  case 3: p(int) = zmq_bind(p(socket), p(string)); break;
  case 4: p(int) = zmq_connect(p(socket), p(string)); break;
  case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
  case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
  case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
  case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
  case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
  }
  p(command) = errno;
  write(context->signal_fd, &amp;ok, 1);
  }
  cleanup:
  close(context->signal_fd);
  free(context_pointer);
  return 0;
  }
 
  void* zmq_thread_init(void* zmq_context, int signal_fd) {
  acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
  pthread_t thread;
 
  context->context = zmq_context;
  context->signal_fd = signal_fd;
  sem_init(&amp;context->sem, 1, 0);
  pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
  pthread_detach(thread);
  return context;
  }
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "text/x-csrc"
  });
  </script>
 
  <p>Simple mode that tries to handle C-like languages as well as it
  can. Takes two configuration parameters: <code>keywords</code>, an
  object whose property names are the keywords in the language,
  and <code>useCPP</code>, which determines whether C preprocessor
  directives are recognized.</p>
 
  <p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
  (C code), <code>text/x-c++src</code> (C++
  code), <code>text/x-java</code> (Java
  code), <code>text/x-groovy</code> (Groovy code).</p>
  </body>
  </html>
 
  /**
  * Author: Hans Engel
  * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
  */
  CodeMirror.defineMode("clojure", function (config, mode) {
  var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", TAG = "tag",
  ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD="keyword";
  var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
 
  function makeKeywords(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
 
  var atoms = makeKeywords("true false nil");
 
  var keywords = makeKeywords(
  // Control structures
  "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle" +
 
  // Built-ins
  "* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq");
 
  var indentKeys = makeKeywords(
  // Built-ins
  "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch" +
 
  // Binding forms
  "let letfn binding loop for doseq dotimes when-let if-let" +
 
  // Data structures
  "defstruct struct-map assoc" +
 
  // clojure.test
  "testing deftest" +
 
  // contrib
  "handler-case handle dotrace deftrace");
 
  var tests = {
  digit: /\d/,
  digit_or_colon: /[\d:]/,
  hex: /[0-9a-fA-F]/,
  sign: /[+-]/,
  exponent: /[eE]/,
  keyword_char: /[^\s\(\[\;\)\]]/,
  basic: /[\w\$_\-]/,
  lang_keyword: /[\w*+!\-_?:\/]/
  };
 
  function stateStack(indent, type, prev) { // represents a state stack object
  this.indent = indent;
  this.type = type;
  this.prev = prev;
  }
 
  function pushStack(state, indent, type) {
  state.indentStack = new stateStack(indent, type, state.indentStack);
  }
 
  function popStack(state) {
  state.indentStack = state.indentStack.prev;
  }
 
  function isNumber(ch, stream){
  // hex
  if ( ch === '0' && 'x' == stream.peek().toLowerCase() ) {
  stream.eat('x');
  stream.eatWhile(tests.hex);
  return true;
  }
 
  // leading sign
  if ( ch == '+' || ch == '-' ) {
  stream.eat(tests.sign);
  ch = stream.next();
  }
 
  if ( tests.digit.test(ch) ) {
  stream.eat(ch);
  stream.eatWhile(tests.digit);
 
  if ( '.' == stream.peek() ) {
  stream.eat('.');
  stream.eatWhile(tests.digit);
  }
 
  if ( 'e' == stream.peek().toLowerCase() ) {
  stream.eat(tests.exponent);
  stream.eat(tests.sign);
  stream.eatWhile(tests.digit);
  }
 
  return true;
  }
 
  return false;
  }
 
  return {
  startState: function () {
  return {
  indentStack: null,
  indentation: 0,
  mode: false,
  };
  },
 
  token: function (stream, state) {
  if (state.indentStack == null && stream.sol()) {
  // update indentation, but only if indentStack is empty
  state.indentation = stream.indentation();
  }
 
  // skip spaces
  if (stream.eatSpace()) {
  return null;
  }
  var returnType = null;
 
  switch(state.mode){
  case "string": // multi-line string parsing mode
  var next, escaped = false;
  while ((next = stream.next()) != null) {
  if (next == "\"" && !escaped) {
 
  state.mode = false;
  break;
  }
  escaped = !escaped && next == "\\";
  }
  returnType = STRING; // continue on in string mode
  break;
  default: // default parsing mode
  var ch = stream.next();
 
  if (ch == "\"") {
  state.mode = "string";
  returnType = STRING;
  } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
  returnType = ATOM;
  } else if (ch == ";") { // comment
  stream.skipToEnd(); // rest of the line is a comment
  returnType = COMMENT;
  } else if (isNumber(ch,stream)){
  returnType = NUMBER;
  } else if (ch == "(" || ch == "[") {
  var keyWord = ''; var indentTemp = stream.column();
  /**
  Either
  (indent-word ..
  (non-indent-word ..
  (;something else, bracket, etc.
  */
 
  while ((letter = stream.eat(tests.keyword_char)) != null) {
  keyWord += letter;
  }
 
  if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
 
  pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  } else { // non-indent word
  // we continue eating the spaces
  stream.eatSpace();
  if (stream.eol() || stream.peek() == ";") {
  // nothing significant after
  // we restart indentation 1 space after
  pushStack(state, indentTemp + 1, ch);
  } else {
  pushStack(state, indentTemp + stream.current().length, ch); // else we match
  }
  }
  stream.backUp(stream.current().length - 1); // undo all the eating
 
  returnType = BRACKET;
  } else if (ch == ")" || ch == "]") {
  returnType = BRACKET;
  if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
  popStack(state);
  }
  } else if ( ch == ":" ) {
  stream.eatWhile(tests.lang_keyword);
  return TAG;
  } else {
  stream.eatWhile(tests.basic);
 
  if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  returnType = BUILTIN;
  } else if ( atoms && atoms.propertyIsEnumerable(stream.current()) ) {
  returnType = ATOM;
  } else returnType = null;
  }
  }
 
  return returnType;
  },
 
  indent: function (state, textAfter) {
  if (state.indentStack == null) return state.indentation;
  return state.indentStack.indent;
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-clojure", "clojure");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Clojure mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="clojure.js"></script>
  <style>.CodeMirror {background: #f8f8f8;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Clojure mode</h1>
  <form><textarea id="code" name="code">
  ; Conway's Game of Life, based on the work of:
  ;; Laurent Petit https://gist.github.com/1200343
  ;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
 
  (ns ^{:doc "Conway's Game of Life."}
  game-of-life)
 
  ;; Core game of life's algorithm functions
 
  (defn neighbours
  "Given a cell's coordinates, returns the coordinates of its neighbours."
  [[x y]]
  (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
  [(+ dx x) (+ dy y)]))
 
  (defn step
  "Given a set of living cells, computes the new set of living cells."
  [cells]
  (set (for [[cell n] (frequencies (mapcat neighbours cells))
  :when (or (= n 3) (and (= n 2) (cells cell)))]
  cell)))
 
  ;; Utility methods for displaying game on a text terminal
 
  (defn print-board
  "Prints a board on *out*, representing a step in the game."
  [board w h]
  (doseq [x (range (inc w)) y (range (inc h))]
  (if (= y 0) (print "\n"))
  (print (if (board [x y]) "[X]" " . "))))
 
  (defn display-grids
  "Prints a squence of boards on *out*, representing several steps."
  [grids w h]
  (doseq [board grids]
  (print-board board w h)
  (print "\n")))
 
  ;; Launches an example board
 
  (def
  ^{:doc "board represents the initial set of living cells"}
  board #{[2 1] [2 2] [2 3]})
 
  (display-grids (take 3 (iterate step board)) 5 5) </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
 
  </body>
  </html>
 
  The MIT License
 
  Copyright (c) 2011 Jeff Pickhardt
  Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  /**
  * Link to the project's GitHub page:
  * https://github.com/pickhardt/coffeescript-codemirror-mode
  */
  CodeMirror.defineMode('coffeescript', function(conf) {
  var ERRORCLASS = 'error';
 
  function wordRegexp(words) {
  return new RegExp("^((" + words.join(")|(") + "))\\b");
  }
 
  var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
  var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
  var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
  var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
  var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
  var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
 
  var wordOperators = wordRegexp(['and', 'or', 'not',
  'is', 'isnt', 'in',
  'instanceof', 'typeof']);
  var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
  'switch', 'try', 'catch', 'finally', 'class'];
  var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
  'do', 'in', 'of', 'new', 'return', 'then',
  'this', 'throw', 'when', 'until'];
 
  var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
 
  indentKeywords = wordRegexp(indentKeywords);
 
 
  var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
  var regexPrefixes = new RegExp("^(/{3}|/)");
  var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
  var constants = wordRegexp(commonConstants);
 
  // Tokenizers
  function tokenBase(stream, state) {
  // Handle scope changes
  if (stream.sol()) {
  var scopeOffset = state.scopes[0].offset;
  if (stream.eatSpace()) {
  var lineOffset = stream.indentation();
  if (lineOffset > scopeOffset) {
  return 'indent';
  } else if (lineOffset < scopeOffset) {
  return 'dedent';
  }
  return null;
  } else {
  if (scopeOffset > 0) {
  dedent(stream, state);
  }
  }
  }
  if (stream.eatSpace()) {
  return null;
  }
 
  var ch = stream.peek();
 
  // Handle comments
  if (ch === '#') {
  stream.skipToEnd();
  return 'comment';
  }
 
  // Handle number literals
  if (stream.match(/^-?[0-9\.]/, false)) {
  var floatLiteral = false;
  // Floats
  if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
  floatLiteral = true;
  }
  if (stream.match(/^-?\d+\.\d*/)) {
  floatLiteral = true;
  }
  if (stream.match(/^-?\.\d+/)) {
  floatLiteral = true;
  }
  if (floatLiteral) {
  return 'number';
  }
  // Integers
  var intLiteral = false;
  // Hex
  if (stream.match(/^-?0x[0-9a-f]+/i)) {
  intLiteral = true;
  }
  // Decimal
  if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
  intLiteral = true;
  }
  // Zero by itself with no other piece of number.
  if (stream.match(/^-?0(?![\dx])/i)) {
  intLiteral = true;
  }
  if (intLiteral) {
  return 'number';
  }
  }
 
  // Handle strings
  if (stream.match(stringPrefixes)) {
  state.tokenize = tokenFactory(stream.current(), 'string');
  return state.tokenize(stream, state);
  }
  // Handle regex literals
  if (stream.match(regexPrefixes)) {
  if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
  state.tokenize = tokenFactory(stream.current(), 'string-2');
  return state.tokenize(stream, state);
  } else {
  stream.backUp(1);
  }
  }
 
  // Handle operators and delimiters
  if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
  return 'punctuation';
  }
  if (stream.match(doubleOperators)
  || stream.match(singleOperators)
  || stream.match(wordOperators)) {
  return 'operator';
  }
  if (stream.match(singleDelimiters)) {
  return 'punctuation';
  }
 
  if (stream.match(constants)) {
  return 'atom';
  }
 
  if (stream.match(keywords)) {
  return 'keyword';
  }
 
  if (stream.match(identifiers)) {
  return 'variable';
  }
 
  // Handle non-detected items
  stream.next();
  return ERRORCLASS;
  }
 
  function tokenFactory(delimiter, outclass) {
  var delim_re = new RegExp(delimiter);
  var singleline = delimiter.length == 1;
 
  return function tokenString(stream, state) {
  while (!stream.eol()) {
  stream.eatWhile(/[^'"\/\\]/);
  if (stream.eat('\\')) {
  stream.next();
  if (singleline && stream.eol()) {
  return outclass;
  }
  } else if (stream.match(delim_re)) {
  state.tokenize = tokenBase;
  return outclass;
  } else {
  stream.eat(/['"\/]/);
  }
  }
  if (singleline) {
  if (conf.mode.singleLineStringErrors) {
  outclass = ERRORCLASS
  } else {
  state.tokenize = tokenBase;
  }
  }
  return outclass;
  };
  }
 
  function indent(stream, state, type) {
  type = type || 'coffee';
  var indentUnit = 0;
  if (type === 'coffee') {
  for (var i = 0; i < state.scopes.length; i++) {
  if (state.scopes[i].type === 'coffee') {
  indentUnit = state.scopes[i].offset + conf.indentUnit;
  break;
  }
  }
  } else {
  indentUnit = stream.column() + stream.current().length;
  }
  state.scopes.unshift({
  offset: indentUnit,
  type: type
  });
  }
 
  function dedent(stream, state) {
  if (state.scopes.length == 1) return;
  if (state.scopes[0].type === 'coffee') {
  var _indent = stream.indentation();
  var _indent_index = -1;
  for (var i = 0; i < state.scopes.length; ++i) {
  if (_indent === state.scopes[i].offset) {
  _indent_index = i;
  break;
  }
  }
  if (_indent_index === -1) {
  return true;
  }
  while (state.scopes[0].offset !== _indent) {
  state.scopes.shift();
  }
  return false
  } else {
  state.scopes.shift();
  return false;
  }
  }
 
  function tokenLexer(stream, state) {
  var style = state.tokenize(stream, state);
  var current = stream.current();
 
  // Handle '.' connected identifiers
  if (current === '.') {
  style = state.tokenize(stream, state);
  current = stream.current();
  if (style === 'variable') {
  return 'variable';
  } else {
  return ERRORCLASS;
  }
  }
 
  // Handle properties
  if (current === '@') {
  style = state.tokenize(stream, state);
  current = stream.current();
  if (style === 'variable') {
  return 'variable-2';
  } else {
  return ERRORCLASS;
  }
  }
 
  // Handle scope changes.
  if (current === 'return') {
  state.dedent += 1;
  }
  if (((current === '->' || current === '=>') &&
  !state.lambda &&
  state.scopes[0].type == 'coffee' &&
  stream.peek() === '')
  || style === 'indent') {
  indent(stream, state);
  }
  var delimiter_index = '[({'.indexOf(current);
  if (delimiter_index !== -1) {
  indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
  }
  if (indentKeywords.exec(current)){
  indent(stream, state);
  }
  if (current == 'then'){
  dedent(stream, state);
  }
 
 
  if (style === 'dedent') {
  if (dedent(stream, state)) {
  return ERRORCLASS;
  }
  }
  delimiter_index = '])}'.indexOf(current);
  if (delimiter_index !== -1) {
  if (dedent(stream, state)) {
  return ERRORCLASS;
  }
  }
  if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
  if (state.scopes.length > 1) state.scopes.shift();
  state.dedent -= 1;
  }
 
  return style;
  }
 
  var external = {
  startState: function(basecolumn) {
  return {
  tokenize: tokenBase,
  scopes: [{offset:basecolumn || 0, type:'coffee'}],
  lastToken: null,
  lambda: false,
  dedent: 0
  };
  },
 
  token: function(stream, state) {
  var style = tokenLexer(stream, state);
 
  state.lastToken = {style:style, content: stream.current()};
 
  if (stream.eol() && stream.lambda) {
  state.lambda = false;
  }
 
  return style;
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != tokenBase) {
  return 0;
  }
 
  return state.scopes[0].offset;
  }
 
  };
  return external;
  });
 
  CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: CoffeeScript mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="coffeescript.js"></script>
  <style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: CoffeeScript mode</h1>
  <form><textarea id="code" name="code">
  # CoffeeScript mode for CodeMirror
  # Copyright (c) 2011 Jeff Pickhardt, released under
  # the MIT License.
  #
  # Modified from the Python CodeMirror mode, which also is
  # under the MIT License Copyright (c) 2010 Timothy Farrell.
  #
  # The following script, Underscore.coffee, is used to
  # demonstrate CoffeeScript mode for CodeMirror.
  #
  # To download CoffeeScript mode for CodeMirror, go to:
  # https://github.com/pickhardt/coffeescript-codemirror-mode
 
  # **Underscore.coffee
  # (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
  # Underscore is freely distributable under the terms of the
  # [MIT license](http://en.wikipedia.org/wiki/MIT_License).
  # Portions of Underscore are inspired by or borrowed from
  # [Prototype.js](http://prototypejs.org/api), Oliver Steele's
  # [Functional](http://osteele.com), and John Resig's
  # [Micro-Templating](http://ejohn.org).
  # For all details and documentation:
  # http://documentcloud.github.com/underscore/
 
 
  # Baseline setup
  # --------------
 
  # Establish the root object, `window` in the browser, or `global` on the server.
  root = this
 
 
  # Save the previous value of the `_` variable.
  previousUnderscore = root._
 
 
  # Establish the object that gets thrown to break out of a loop iteration.
  # `StopIteration` is SOP on Mozilla.
  breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
 
 
  # Helper function to escape **RegExp** contents, because JS doesn't have one.
  escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
 
 
  # Save bytes in the minified (but not gzipped) version:
  ArrayProto = Array.prototype
  ObjProto = Object.prototype
 
 
  # Create quick reference variables for speed access to core prototypes.
  slice = ArrayProto.slice
  unshift = ArrayProto.unshift
  toString = ObjProto.toString
  hasOwnProperty = ObjProto.hasOwnProperty
  propertyIsEnumerable = ObjProto.propertyIsEnumerable
 
 
  # All **ECMA5** native implementations we hope to use are declared here.
  nativeForEach = ArrayProto.forEach
  nativeMap = ArrayProto.map
  nativeReduce = ArrayProto.reduce
  nativeReduceRight = ArrayProto.reduceRight
  nativeFilter = ArrayProto.filter
  nativeEvery = ArrayProto.every
  nativeSome = ArrayProto.some
  nativeIndexOf = ArrayProto.indexOf
  nativeLastIndexOf = ArrayProto.lastIndexOf
  nativeIsArray = Array.isArray
  nativeKeys = Object.keys
 
 
  # Create a safe reference to the Underscore object for use below.
  _ = (obj) -> new wrapper(obj)
 
 
  # Export the Underscore object for **CommonJS**.
  if typeof(exports) != 'undefined' then exports._ = _
 
 
  # Export Underscore to global scope.
  root._ = _
 
 
  # Current version.
  _.VERSION = '1.1.0'
 
 
  # Collection Functions
  # --------------------
 
  # The cornerstone, an **each** implementation.
  # Handles objects implementing **forEach**, arrays, and raw objects.
  _.each = (obj, iterator, context) ->
  try
  if nativeForEach and obj.forEach is nativeForEach
  obj.forEach iterator, context
  else if _.isNumber obj.length
  iterator.call context, obj[i], i, obj for i in [0...obj.length]
  else
  iterator.call context, val, key, obj for own key, val of obj
  catch e
  throw e if e isnt breaker
  obj
 
 
  # Return the results of applying the iterator to each element. Use JavaScript
  # 1.6's version of **map**, if possible.
  _.map = (obj, iterator, context) ->
  return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
  results = []
  _.each obj, (value, index, list) ->
  results.push iterator.call context, value, index, list
  results
 
 
  # **Reduce** builds up a single result from a list of values. Also known as
  # **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
  _.reduce = (obj, iterator, memo, context) ->
  if nativeReduce and obj.reduce is nativeReduce
  iterator = _.bind iterator, context if context
  return obj.reduce iterator, memo
  _.each obj, (value, index, list) ->
  memo = iterator.call context, memo, value, index, list
  memo
 
 
  # The right-associative version of **reduce**, also known as **foldr**. Uses
  # JavaScript 1.8's version of **reduceRight**, if available.
  _.reduceRight = (obj, iterator, memo, context) ->
  if nativeReduceRight and obj.reduceRight is nativeReduceRight
  iterator = _.bind iterator, context if context
  return obj.reduceRight iterator, memo
  reversed = _.clone(_.toArray(obj)).reverse()
  _.reduce reversed, iterator, memo, context
 
 
  # Return the first value which passes a truth test.
  _.detect = (obj, iterator, context) ->
  result = null
  _.each obj, (value, index, list) ->
  if iterator.call context, value, index, list
  result = value
  _.breakLoop()
  result
 
 
  # Return all the elements that pass a truth test. Use JavaScript 1.6's
  # **filter**, if it exists.
  _.filter = (obj, iterator, context) ->
  return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
  results = []
  _.each obj, (value, index, list) ->
  results.push value if iterator.call context, value, index, list
  results
 
 
  # Return all the elements for which a truth test fails.
  _.reject = (obj, iterator, context) ->
  results = []
  _.each obj, (value, index, list) ->
  results.push value if not iterator.call context, value, index, list
  results
 
 
  # Determine whether all of the elements match a truth test. Delegate to
  # JavaScript 1.6's **every**, if it is present.
  _.every = (obj, iterator, context) ->
  iterator ||= _.identity
  return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
  result = true
  _.each obj, (value, index, list) ->
  _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
  result
 
 
  # Determine if at least one element in the object matches a truth test. Use
  # JavaScript 1.6's **some**, if it exists.
  _.some = (obj, iterator, context) ->
  iterator ||= _.identity
  return obj.some iterator, context if nativeSome and obj.some is nativeSome
  result = false
  _.each obj, (value, index, list) ->
  _.breakLoop() if (result = iterator.call(context, value, index, list))
  result
 
 
  # Determine if a given value is included in the array or object,
  # based on `===`.
  _.include = (obj, target) ->
  return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
  return true for own key, val of obj when val is target
  false
 
 
  # Invoke a method with arguments on every item in a collection.
  _.invoke = (obj, method) ->
  args = _.rest arguments, 2
  (if method then val[method] else val).apply(val, args) for val in obj
 
 
  # Convenience version of a common use case of **map**: fetching a property.
  _.pluck = (obj, key) ->
  _.map(obj, (val) -> val[key])
 
 
  # Return the maximum item or (item-based computation).
  _.max = (obj, iterator, context) ->
  return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
  result = computed: -Infinity
  _.each obj, (value, index, list) ->
  computed = if iterator then iterator.call(context, value, index, list) else value
  computed >= result.computed and (result = {value: value, computed: computed})
  result.value
 
 
  # Return the minimum element (or element-based computation).
  _.min = (obj, iterator, context) ->
  return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
  result = computed: Infinity
  _.each obj, (value, index, list) ->
  computed = if iterator then iterator.call(context, value, index, list) else value
  computed < result.computed and (result = {value: value, computed: computed})
  result.value
 
 
  # Sort the object's values by a criterion produced by an iterator.
  _.sortBy = (obj, iterator, context) ->
  _.pluck(((_.map obj, (value, index, list) ->
  {value: value, criteria: iterator.call(context, value, index, list)}
  ).sort((left, right) ->
  a = left.criteria; b = right.criteria
  if a < b then -1 else if a > b then 1 else 0
  )), 'value')
 
 
  # Use a comparator function to figure out at what index an object should
  # be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = (array, obj, iterator) ->
  iterator ||= _.identity
  low = 0
  high = array.length
  while low < high
  mid = (low + high) >> 1
  if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
  low
 
 
  # Convert anything iterable into a real, live array.
  _.toArray = (iterable) ->
  return [] if (!iterable)
  return iterable.toArray() if (iterable.toArray)
  return iterable if (_.isArray(iterable))
  return slice.call(iterable) if (_.isArguments(iterable))
  _.values(iterable)
 
 
  # Return the number of elements in an object.
  _.size = (obj) -> _.toArray(obj).length
 
 
  # Array Functions
  # ---------------
 
  # Get the first element of an array. Passing `n` will return the first N
  # values in the array. Aliased as **head**. The `guard` check allows it to work
  # with **map**.
  _.first = (array, n, guard) ->
  if n and not guard then slice.call(array, 0, n) else array[0]
 
 
  # Returns everything but the first entry of the array. Aliased as **tail**.
  # Especially useful on the arguments object. Passing an `index` will return
  # the rest of the values in the array from that index onward. The `guard`
  # check allows it to work with **map**.
  _.rest = (array, index, guard) ->
  slice.call(array, if _.isUndefined(index) or guard then 1 else index)
 
 
  # Get the last element of an array.
  _.last = (array) -> array[array.length - 1]
 
 
  # Trim out all falsy values from an array.
  _.compact = (array) -> item for item in array when item
 
 
  # Return a completely flattened version of an array.
  _.flatten = (array) ->
  _.reduce array, (memo, value) ->
  return memo.concat(_.flatten(value)) if _.isArray value
  memo.push value
  memo
  , []
 
 
  # Return a version of the array that does not contain the specified value(s).
  _.without = (array) ->
  values = _.rest arguments
  val for val in _.toArray(array) when not _.include values, val
 
 
  # Produce a duplicate-free version of the array. If the array has already
  # been sorted, you have the option of using a faster algorithm.
  _.uniq = (array, isSorted) ->
  memo = []
  for el, i in _.toArray array
  memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
  memo
 
 
  # Produce an array that contains every item shared between all the
  # passed-in arrays.
  _.intersect = (array) ->
  rest = _.rest arguments
  _.select _.uniq(array), (item) ->
  _.all rest, (other) ->
  _.indexOf(other, item) >= 0
 
 
  # Zip together multiple lists into a single array -- elements that share
  # an index go together.
  _.zip = ->
  length = _.max _.pluck arguments, 'length'
  results = new Array length
  for i in [0...length]
  results[i] = _.pluck arguments, String i
  results
 
 
  # If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
  # we need this function. Return the position of the first occurrence of an
  # item in an array, or -1 if the item is not included in the array.
  _.indexOf = (array, item) ->
  return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
  i = 0; l = array.length
  while l - i
  if array[i] is item then return i else i++
  -1
 
 
  # Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
  # if possible.
  _.lastIndexOf = (array, item) ->
  return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
  i = array.length
  while i
  if array[i] is item then return i else i--
  -1
 
 
  # Generate an integer Array containing an arithmetic progression. A port of
  # [the native Python **range** function](http://docs.python.org/library/functions.html#range).
  _.range = (start, stop, step) ->
  a = arguments
  solo = a.length <= 1
  i = start = if solo then 0 else a[0]
  stop = if solo then a[0] else a[1]
  step = a[2] or 1
  len = Math.ceil((stop - start) / step)
  return [] if len <= 0
  range = new Array len
  idx = 0
  loop
  return range if (if step > 0 then i - stop else stop - i) >= 0
  range[idx] = i
  idx++
  i+= step
 
 
  # Function Functions
  # ------------------
 
  # Create a function bound to a given object (assigning `this`, and arguments,
  # optionally). Binding with arguments is also known as **curry**.
  _.bind = (func, obj) ->
  args = _.rest arguments, 2
  -> func.apply obj or root, args.concat arguments
 
 
  # Bind all of an object's methods to that object. Useful for ensuring that
  # all callbacks defined on an object belong to it.
  _.bindAll = (obj) ->
  funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
  _.each funcs, (f) -> obj[f] = _.bind obj[f], obj
  obj
 
 
  # Delays a function for the given number of milliseconds, and then calls
  # it with the arguments supplied.
  _.delay = (func, wait) ->
  args = _.rest arguments, 2
  setTimeout((-> func.apply(func, args)), wait)
 
 
  # Memoize an expensive function by storing its results.
  _.memoize = (func, hasher) ->
  memo = {}
  hasher or= _.identity
  ->
  key = hasher.apply this, arguments
  return memo[key] if key of memo
  memo[key] = func.apply this, arguments
 
 
  # Defers a function, scheduling it to run after the current call stack has
  # cleared.
  _.defer = (func) ->
  _.delay.apply _, [func, 1].concat _.rest arguments
 
 
  # Returns the first function passed as an argument to the second,
  # allowing you to adjust arguments, run code before and after, and
  # conditionally execute the original function.
  _.wrap = (func, wrapper) ->
  -> wrapper.apply wrapper, [func].concat arguments
 
 
  # Returns a function that is the composition of a list of functions, each
  # consuming the return value of the function that follows.
  _.compose = ->
  funcs = arguments
  ->
  args = arguments
  for i in [funcs.length - 1..0] by -1
  args = [funcs[i].apply(this, args)]
  args[0]
 
 
  # Object Functions
  # ----------------
 
  # Retrieve the names of an object's properties.
  _.keys = nativeKeys or (obj) ->
  return _.range 0, obj.length if _.isArray(obj)
  key for key, val of obj
 
 
  # Retrieve the values of an object's properties.
  _.values = (obj) ->
  _.map obj, _.identity
 
 
  # Return a sorted list of the function names available in Underscore.
  _.functions = (obj) ->
  _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
 
 
  # Extend a given object with all of the properties in a source object.
  _.extend = (obj) ->
  for source in _.rest(arguments)
  obj[key] = val for key, val of source
  obj
 
 
  # Create a (shallow-cloned) duplicate of an object.
  _.clone = (obj) ->
  return obj.slice 0 if _.isArray obj
  _.extend {}, obj
 
 
  # Invokes interceptor with the obj, and then returns obj.
  # The primary purpose of this method is to "tap into" a method chain,
  # in order to perform operations on intermediate results within
  the chain.
  _.tap = (obj, interceptor) ->
  interceptor obj
  obj
 
 
  # Perform a deep comparison to check if two objects are equal.
  _.isEqual = (a, b) ->
  # Check object identity.
  return true if a is b
  # Different types?
  atype = typeof(a); btype = typeof(b)
  return false if atype isnt btype
  # Basic equality test (watch out for coercions).
  return true if `a == b`
  # One is falsy and the other truthy.
  return false if (!a and b) or (a and !b)
  # One of them implements an `isEqual()`?
  return a.isEqual(b) if a.isEqual
  # Check dates' integer values.
  return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
  # Both are NaN?
  return false if _.isNaN(a) and _.isNaN(b)
  # Compare regular expressions.
  if _.isRegExp(a) and _.isRegExp(b)
  return a.source is b.source and
  a.global is b.global and
  a.ignoreCase is b.ignoreCase and
  a.multiline is b.multiline
  # If a is not an object by this point, we can't handle it.
  return false if atype isnt 'object'
  # Check for different array lengths before comparing contents.
  return false if a.length and (a.length isnt b.length)
  # Nothing else worked, deep compare the contents.
  aKeys = _.keys(a); bKeys = _.keys(b)
  # Different object sizes?
  return false if aKeys.length isnt bKeys.length
  # Recursive comparison of contents.
  return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
  true
 
 
  # Is a given array or object empty?
  _.isEmpty = (obj) ->
  return obj.length is 0 if _.isArray(obj) or _.isString(obj)
  return false for own key of obj
  true
 
 
  # Is a given value a DOM element?
  _.isElement = (obj) -> obj and obj.nodeType is 1
 
 
  # Is a given value an array?
  _.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
 
 
  # Is a given variable an arguments object?
  _.isArguments = (obj) -> obj and obj.callee
 
 
  # Is the given value a function?
  _.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
 
 
  # Is the given value a string?
  _.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
 
 
  # Is a given value a number?
  _.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
 
 
  # Is a given value a boolean?
  _.isBoolean = (obj) -> obj is true or obj is false
 
 
  # Is a given value a Date?
  _.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
 
 
  # Is the given value a regular expression?
  _.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
 
 
  # Is the given value NaN -- this one is interesting. `NaN != NaN`, and
  # `isNaN(undefined) == true`, so we make sure it's a number first.
  _.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
 
 
  # Is a given value equal to null?
  _.isNull = (obj) -> obj is null
 
 
  # Is a given variable undefined?
  _.isUndefined = (obj) -> typeof obj is 'undefined'
 
 
  # Utility Functions
  # -----------------
 
  # Run Underscore.js in noConflict mode, returning the `_` variable to its
  # previous owner. Returns a reference to the Underscore object.
  _.noConflict = ->
  root._ = previousUnderscore
  this
 
 
  # Keep the identity function around for default iterators.
  _.identity = (value) -> value
 
 
  # Run a function `n` times.
  _.times = (n, iterator, context) ->
  iterator.call context, i for i in [0...n]
 
 
  # Break out of the middle of an iteration.
  _.breakLoop = -> throw breaker
 
 
  # Add your own custom functions to the Underscore object, ensuring that
  # they're correctly added to the OOP wrapper as well.
  _.mixin = (obj) ->
  for name in _.functions(obj)
  addToWrapper name, _[name] = obj[name]
 
 
  # Generate a unique integer id (unique within the entire client session).
  # Useful for temporary DOM ids.
  idCounter = 0
  _.uniqueId = (prefix) ->
  (prefix or '') + idCounter++
 
 
  # By default, Underscore uses **ERB**-style template delimiters, change the
  # following template settings to use alternative delimiters.
  _.templateSettings = {
  start: '<%'
  end: '%>'
  interpolate: /<%=(.+?)%>/g
  }
 
 
  # JavaScript templating a-la **ERB**, pilfered from John Resig's
  # *Secrets of the JavaScript Ninja*, page 83.
  # Single-quote fix from Rick Strahl.
  # With alterations for arbitrary delimiters, and to preserve whitespace.
  _.template = (str, data) ->
  c = _.templateSettings
  endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
  fn = new Function 'obj',
  'var p=[],print=function(){p.push.apply(p,arguments);};' +
  'with(obj||{}){p.push(\'' +
  str.replace(/\r/g, '\\r')
  .replace(/\n/g, '\\n')
  .replace(/\t/g, '\\t')
  .replace(endMatch,"���")
  .split("'").join("\\'")
  .split("���").join("'")
  .replace(c.interpolate, "',$1,'")
  .split(c.start).join("');")
  .split(c.end).join("p.push('") +
  "');}return p.join('');"
  if data then fn(data) else fn
 
 
  # Aliases
  # -------
 
  _.forEach = _.each
  _.foldl = _.inject = _.reduce
  _.foldr = _.reduceRight
  _.select = _.filter
  _.all = _.every
  _.any = _.some
  _.contains = _.include
  _.head = _.first
  _.tail = _.rest
  _.methods = _.functions
 
 
  # Setup the OOP Wrapper
  # ---------------------
 
  # If Underscore is called as a function, it returns a wrapped object that
  # can be used OO-style. This wrapper holds altered versions of all the
  # underscore functions. Wrapped objects may be chained.
  wrapper = (obj) ->
  this._wrapped = obj
  this
 
 
  # Helper function to continue chaining intermediate results.
  result = (obj, chain) ->
  if chain then _(obj).chain() else obj
 
 
  # A method to easily add functions to the OOP wrapper.
  addToWrapper = (name, func) ->
  wrapper.prototype[name] = ->
  args = _.toArray arguments
  unshift.call args, this._wrapped
  result func.apply(_, args), this._chain
 
 
  # Add all ofthe Underscore functions to the wrapper object.
  _.mixin _
 
 
  # Add all mutator Array functions to the wrapper.
  _.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
  method = Array.prototype[name]
  wrapper.prototype[name] = ->
  method.apply(this._wrapped, arguments)
  result(this._wrapped, this._chain)
 
 
  # Add all accessor Array functions to the wrapper.
  _.each ['concat', 'join', 'slice'], (name) ->
  method = Array.prototype[name]
  wrapper.prototype[name] = ->
  result(method.apply(this._wrapped, arguments), this._chain)
 
 
  # Start chaining a wrapped Underscore object.
  wrapper::chain = ->
  this._chain = true
  this
 
 
  # Extracts the result from a wrapped and chained object.
  wrapper::value = -> this._wrapped
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
 
  <p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("css", function(config) {
  var indentUnit = config.indentUnit, type;
  function ret(style, tp) {type = tp; return style;}
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());}
  else if (ch == "/" && stream.eat("*")) {
  state.tokenize = tokenCComment;
  return tokenCComment(stream, state);
  }
  else if (ch == "<" && stream.eat("!")) {
  state.tokenize = tokenSGMLComment;
  return tokenSGMLComment(stream, state);
  }
  else if (ch == "=") ret(null, "compare");
  else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
  else if (ch == "\"" || ch == "'") {
  state.tokenize = tokenString(ch);
  return state.tokenize(stream, state);
  }
  else if (ch == "#") {
  stream.eatWhile(/[\w\\\-]/);
  return ret("atom", "hash");
  }
  else if (ch == "!") {
  stream.match(/^\s*\w*/);
  return ret("keyword", "important");
  }
  else if (/\d/.test(ch)) {
  stream.eatWhile(/[\w.%]/);
  return ret("number", "unit");
  }
  else if (/[,.+>*\/]/.test(ch)) {
  return ret(null, "select-op");
  }
  else if (/[;{}:\[\]]/.test(ch)) {
  return ret(null, ch);
  }
  else {
  stream.eatWhile(/[\w\\\-]/);
  return ret("variable", "variable");
  }
  }
 
  function tokenCComment(stream, state) {
  var maybeEnd = false, ch;
  while ((ch = stream.next()) != null) {
  if (maybeEnd && ch == "/") {
  state.tokenize = tokenBase;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return ret("comment", "comment");
  }
 
  function tokenSGMLComment(stream, state) {
  var dashes = 0, ch;
  while ((ch = stream.next()) != null) {
  if (dashes >= 2 && ch == ">") {
  state.tokenize = tokenBase;
  break;
  }
  dashes = (ch == "-") ? dashes + 1 : 0;
  }
  return ret("comment", "comment");
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  var escaped = false, ch;
  while ((ch = stream.next()) != null) {
  if (ch == quote && !escaped)
  break;
  escaped = !escaped && ch == "\\";
  }
  if (!escaped) state.tokenize = tokenBase;
  return ret("string", "string");
  };
  }
 
  return {
  startState: function(base) {
  return {tokenize: tokenBase,
  baseIndent: base || 0,
  stack: []};
  },
 
  token: function(stream, state) {
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
 
  var context = state.stack[state.stack.length-1];
  if (type == "hash" && context == "rule") style = "atom";
  else if (style == "variable") {
  if (context == "rule") style = "number";
  else if (!context || context == "@media{") style = "tag";
  }
 
  if (context == "rule" && /^[\{\};]$/.test(type))
  state.stack.pop();
  if (type == "{") {
  if (context == "@media") state.stack[state.stack.length-1] = "@media{";
  else state.stack.push("{");
  }
  else if (type == "}") state.stack.pop();
  else if (type == "@media") state.stack.push("@media");
  else if (context == "{" && type != "comment") state.stack.push("rule");
  return style;
  },
 
  indent: function(state, textAfter) {
  var n = state.stack.length;
  if (/^\}/.test(textAfter))
  n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
  return state.baseIndent + n * indentUnit;
  },
 
  electricChars: "}"
  };
  });
 
  CodeMirror.defineMIME("text/css", "css");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: CSS mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="css.js"></script>
  <style>.CodeMirror {background: #f8f8f8;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: CSS mode</h1>
  <form><textarea id="code" name="code">
  /* Some example CSS */
 
  @import url("something.css");
 
  body {
  margin: 0;
  padding: 3em 6em;
  font-family: tahoma, arial, sans-serif;
  color: #000;
  }
 
  #navigation a {
  font-weight: bold;
  text-decoration: none !important;
  }
 
  h1 {
  font-size: 2.5em;
  }
 
  h2 {
  font-size: 1.7em;
  }
 
  h1:before, h2:before {
  content: "::";
  }
 
  code {
  font-family: courier, monospace;
  font-size: 80%;
  color: #418A8A;
  }
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
 
  </body>
  </html>
 
  span.cm-rangeinfo {color: #a0b;}
  span.cm-minus {color: red;}
  span.cm-plus {color: #2b2;}
 
  CodeMirror.defineMode("diff", function() {
  return {
  token: function(stream) {
  var ch = stream.next();
  stream.skipToEnd();
  if (ch == "+") return "plus";
  if (ch == "-") return "minus";
  if (ch == "@") return "rangeinfo";
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-diff", "diff");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Diff mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="diff.js"></script>
  <link rel="stylesheet" href="diff.css">
  <style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Diff mode</h1>
  <form><textarea id="code" name="code">
  diff --git a/index.html b/index.html
  index c1d9156..7764744 100644
  --- a/index.html
  +++ b/index.html
  @@ -95,7 +95,8 @@ StringStream.prototype = {
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  - autoMatchBrackets: true
  + autoMatchBrackets: true,
  + onGutterClick: function(x){console.log(x);}
  });
  </script>
  </body>
  diff --git a/lib/codemirror.js b/lib/codemirror.js
  index 04646a9..9a39cc7 100644
  --- a/lib/codemirror.js
  +++ b/lib/codemirror.js
  @@ -399,10 +399,16 @@ var CodeMirror = (function() {
  }
 
  function onMouseDown(e) {
  - var start = posFromMouse(e), last = start;
  + var start = posFromMouse(e), last = start, target = e.target();
  if (!start) return;
  setCursor(start.line, start.ch, false);
  if (e.button() != 1) return;
  + if (target.parentNode == gutter) {
  + if (options.onGutterClick)
  + options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
  + return;
  + }
  +
  if (!focused) onFocus();
 
  e.stop();
  @@ -808,7 +814,7 @@ var CodeMirror = (function() {
  for (var i = showingFrom; i < showingTo; ++i) {
  var marker = lines[i].gutterMarker;
  if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
  - else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
  + else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
  }
  gutter.style.display = "none"; // TODO test whether this actually helps
  gutter.innerHTML = html.join("");
  @@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
  if (option == "parser") setParser(value);
  else if (option === "lineNumbers") setLineNumbers(value);
  else if (option === "gutter") setGutter(value);
  - else if (option === "readOnly") options.readOnly = value;
  - else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
  - else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
  - else throw new Error("Can't set option " + option);
  + else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
  + else options[option] = value;
  },
  cursorCoords: cursorCoords,
  undo: operation(undo),
  @@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
  replaceRange: operation(replaceRange),
 
  operation: function(f){return operation(f)();},
  - refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
  + refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
  + getInputField: function(){return input;}
  };
  return instance;
  }
  @@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
  readOnly: false,
  onChange: null,
  onCursorActivity: null,
  + onGutterClick: null,
  autoMatchBrackets: false,
  workTime: 200,
  workDelay: 300,
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("gfm", function(config, parserConfig) {
  var mdMode = CodeMirror.getMode(config, "markdown");
  var aliases = {
  html: "htmlmixed",
  js: "javascript",
  json: "application/json",
  c: "text/x-csrc",
  "c++": "text/x-c++src",
  java: "text/x-java",
  csharp: "text/x-csharp",
  "c#": "text/x-csharp",
  };
 
  // make this lazy so that we don't need to load GFM last
  var getMode = (function () {
  var i, modes = {}, mimes = {}, mime;
 
  var list = CodeMirror.listModes();
  for (i = 0; i < list.length; i++) {
  modes[list[i]] = list[i];
  }
  var mimesList = CodeMirror.listMIMEs();
  for (i = 0; i < mimesList.length; i++) {
  mime = mimesList[i].mime;
  mimes[mime] = mimesList[i].mime;
  }
 
  for (var a in aliases) {
  if (aliases[a] in modes || aliases[a] in mimes)
  modes[a] = aliases[a];
  }
 
  return function (lang) {
  return modes[lang] ? CodeMirror.getMode(config, modes[lang]) : null;
  }
  }());
 
  function markdown(stream, state) {
  // intercept fenced code blocks
  if (stream.sol() && stream.match(/^```([\w+#]*)/)) {
  // try switching mode
  state.localMode = getMode(RegExp.$1)
  if (state.localMode)
  state.localState = state.localMode.startState();
 
  state.token = local;
  return 'code';
  }
 
  return mdMode.token(stream, state.mdState);
  }
 
  function local(stream, state) {
  if (stream.sol() && stream.match(/^```/)) {
  state.localMode = state.localState = null;
  state.token = markdown;
  return 'code';
  }
  else if (state.localMode) {
  return state.localMode.token(stream, state.localState);
  } else {
  stream.skipToEnd();
  return 'code';
  }
  }
 
  // custom handleText to prevent emphasis in the middle of a word
  // and add autolinking
  function handleText(stream, mdState) {
  var match;
  if (stream.match(/^\w+:\/\/\S+/)) {
  return 'linkhref';
  }
  if (stream.match(/^[^\[*\\<>` _][^\[*\\<>` ]*[^\[*\\<>` _]/)) {
  return mdMode.getType(mdState);
  }
  if (match = stream.match(/^[^\[*\\<>` ]+/)) {
  var word = match[0];
  if (word[0] === '_' && word[word.length-1] === '_') {
  stream.backUp(word.length);
  return undefined;
  }
  return mdMode.getType(mdState);
  }
  if (stream.eatSpace()) {
  return null;
  }
  }
 
  return {
  startState: function() {
  var mdState = mdMode.startState();
  mdState.text = handleText;
  return {token: markdown, mode: "markdown", mdState: mdState,
  localMode: null, localState: null};
  },
 
  copyState: function(state) {
  return {token: state.token, mode: state.mode, mdState: CodeMirror.copyState(mdMode, state.mdState),
  localMode: state.localMode,
  localState: state.localMode ? CodeMirror.copyState(state.localMode, state.localState) : null};
  },
 
  token: function(stream, state) {
  return state.token(stream, state);
  }
  }
  });
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: GFM mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="../xml/xml.js"></script>
  <script src="../markdown/markdown.js"></script>
  <script src="gfm.js"></script>
  <script src="../javascript/javascript.js"></script>
  <link rel="stylesheet" href="../markdown/markdown.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: GFM mode</h1>
 
  <!-- source: http://daringfireball.net/projects/markdown/basics.text -->
  <form><textarea id="code" name="code">
  Github Flavored Markdown
  ========================
 
  Everything from markdown plus GFM features:
 
  ## Fenced code blocks
 
  ```javascript
  for (var i = 0; i &lt; items.length; i++) {
  console.log(items[i], i); // log them
  }
  ```
 
  See http://github.github.com/github-flavored-markdown/
 
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: 'gfm',
  lineNumbers: true,
  matchBrackets: true,
  theme: "default"
  });
  </script>
 
  </body>
  </html>
 
  CodeMirror.defineMode("groovy", function(config, parserConfig) {
  function words(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
  var keywords = words(
  "abstract as assert boolean break byte case catch char class const continue def default " +
  "do double else enum extends final finally float for goto if implements import in " +
  "instanceof int interface long native new package private protected public return " +
  "short static strictfp super switch synchronized threadsafe throw throws transient " +
  "try void volatile while");
  var blockKeywords = words("catch class do else finally for if switch try while enum interface def");
  var atoms = words("null true false this");
 
  var curPunc;
  function tokenBase(stream, state) {
  var ch = stream.next();
  if (ch == '"' || ch == "'") {
  return startString(ch, stream, state);
  }
  if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
  curPunc = ch;
  return null
  }
  if (/\d/.test(ch)) {
  stream.eatWhile(/[\w\.]/);
  if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); }
  return "number";
  }
  if (ch == "/") {
  if (stream.eat("*")) {
  state.tokenize.push(tokenComment);
  return tokenComment(stream, state);
  }
  if (stream.eat("/")) {
  stream.skipToEnd();
  return "comment";
  }
  if (expectExpression(state.lastToken)) {
  return startString(ch, stream, state);
  }
  }
  if (ch == "-" && stream.eat(">")) {
  curPunc = "->";
  return null;
  }
  if (/[+\-*&%=<>!?|\/~]/.test(ch)) {
  stream.eatWhile(/[+\-*&%=<>|~]/);
  return "operator";
  }
  stream.eatWhile(/[\w\$_]/);
  if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; }
  if (state.lastToken == ".") return "property";
  if (stream.eat(":")) { curPunc = "proplabel"; return "property"; }
  var cur = stream.current();
  if (atoms.propertyIsEnumerable(cur)) { return "atom"; }
  if (keywords.propertyIsEnumerable(cur)) {
  if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
  return "keyword";
  }
  return "word";
  }
  tokenBase.isBase = true;
 
  function startString(quote, stream, state) {
  var tripleQuoted = false;
  if (quote != "/" && stream.eat(quote)) {
  if (stream.eat(quote)) tripleQuoted = true;
  else return "string";
  }
  function t(stream, state) {
  var escaped = false, next, end = !tripleQuoted;
  while ((next = stream.next()) != null) {
  if (next == quote && !escaped) {
  if (!tripleQuoted) { break; }
  if (stream.match(quote + quote)) { end = true; break; }
  }
  if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
  state.tokenize.push(tokenBaseUntilBrace());
  return "string";
  }
  escaped = !escaped && next == "\\";
  }
  if (end) state.tokenize.pop();
  return "string";
  }
  state.tokenize.push(t);
  return t(stream, state);
  }
 
  function tokenBaseUntilBrace() {
  var depth = 1;
  function t(stream, state) {
  if (stream.peek() == "}") {
  depth--;
  if (depth == 0) {
  state.tokenize.pop();
  return state.tokenize[state.tokenize.length-1](stream, state);
  }
  } else if (stream.peek() == "{") {
  depth++;
  }
  return tokenBase(stream, state);
  }
  t.isBase = true;
  return t;
  }
 
  function tokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize.pop();
  break;
  }
  maybeEnd = (ch == "*");
  }
  return "comment";
  }
 
  function expectExpression(last) {
  return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
  last == "newstatement" || last == "keyword" || last == "proplabel";
  }
 
  function Context(indented, column, type, align, prev) {
  this.indented = indented;
  this.column = column;
  this.type = type;
  this.align = align;
  this.prev = prev;
  }
  function pushContext(state, col, type) {
  return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
  var t = state.context.type;
  if (t == ")" || t == "]" || t == "}")
  state.indented = state.context.indented;
  return state.context = state.context.prev;
  }
 
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: [tokenBase],
  context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
  indented: 0,
  startOfLine: true,
  lastToken: null
  };
  },
 
  token: function(stream, state) {
  var ctx = state.context;
  if (stream.sol()) {
  if (ctx.align == null) ctx.align = false;
  state.indented = stream.indentation();
  state.startOfLine = true;
  // Automatic semicolon insertion
  if (ctx.type == "statement" && !expectExpression(state.lastToken)) {
  popContext(state); ctx = state.context;
  }
  }
  if (stream.eatSpace()) return null;
  curPunc = null;
  var style = state.tokenize[state.tokenize.length-1](stream, state);
  if (style == "comment") return style;
  if (ctx.align == null) ctx.align = true;
 
  if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
  // Handle indentation for {x -> \n ... }
  else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
  popContext(state);
  state.context.align = false;
  }
  else if (curPunc == "{") pushContext(state, stream.column(), "}");
  else if (curPunc == "[") pushContext(state, stream.column(), "]");
  else if (curPunc == "(") pushContext(state, stream.column(), ")");
  else if (curPunc == "}") {
  while (ctx.type == "statement") ctx = popContext(state);
  if (ctx.type == "}") ctx = popContext(state);
  while (ctx.type == "statement") ctx = popContext(state);
  }
  else if (curPunc == ctx.type) popContext(state);
  else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
  pushContext(state, stream.column(), "statement");
  state.startOfLine = false;
  state.lastToken = curPunc || style;
  return style;
  },
 
  indent: function(state, textAfter) {
  if (!state.tokenize[state.tokenize.length-1].isBase) return 0;
  var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
  if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev;
  var closing = firstChar == ctx.type;
  if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
  else if (ctx.align) return ctx.column + (closing ? 0 : 1);
  else return ctx.indented + (closing ? 0 : config.indentUnit);
  },
 
  electricChars: "{}"
  };
  });
 
  CodeMirror.defineMIME("text/x-groovy", "groovy");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Groovy mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="groovy.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
  </head>
  <body>
  <h1>CodeMirror: Groovy mode</h1>
 
  <form><textarea id="code" name="code">
  //Pattern for groovy script
  def p = ~/.*\.groovy/
  new File( 'd:\\scripts' ).eachFileMatch(p) {f ->
  // imports list
  def imports = []
  f.eachLine {
  // condition to detect an import instruction
  ln -> if ( ln =~ '^import .*' ) {
  imports << "${ln - 'import '}"
  }
  }
  // print thmen
  if ( ! imports.empty ) {
  println f
  imports.each{ println " $it" }
  }
  }
 
  /* Coin changer demo code from http://groovy.codehaus.org */
 
  enum UsCoin {
  quarter(25), dime(10), nickel(5), penny(1)
  UsCoin(v) { value = v }
  final value
  }
 
  enum OzzieCoin {
  fifty(50), twenty(20), ten(10), five(5)
  OzzieCoin(v) { value = v }
  final value
  }
 
  def plural(word, count) {
  if (count == 1) return word
  word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
  }
 
  def change(currency, amount) {
  currency.values().inject([]){ list, coin ->
  int count = amount / coin.value
  amount = amount % coin.value
  list += "$count ${plural(coin.toString(), count)}"
  }
  }
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "text/x-groovy"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p>
  </body>
  </html>
 
  CodeMirror.defineMode("haskell", function(cmCfg, modeCfg) {
 
  function switchState(source, setState, f) {
  setState(f);
  return f(source, setState);
  }
 
  // These should all be Unicode extended, as per the Haskell 2010 report
  var smallRE = /[a-z_]/;
  var largeRE = /[A-Z]/;
  var digitRE = /[0-9]/;
  var hexitRE = /[0-9A-Fa-f]/;
  var octitRE = /[0-7]/;
  var idRE = /[a-z_A-Z0-9']/;
  var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
  var specialRE = /[(),;[\]`{}]/;
  var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
 
  function normal(source, setState) {
  if (source.eatWhile(whiteCharRE)) {
  return null;
  }
 
  var ch = source.next();
  if (specialRE.test(ch)) {
  if (ch == '{' && source.eat('-')) {
  var t = "comment";
  if (source.eat('#')) {
  t = "meta";
  }
  return switchState(source, setState, ncomment(t, 1));
  }
  return null;
  }
 
  if (ch == '\'') {
  if (source.eat('\\')) {
  source.next(); // should handle other escapes here
  }
  else {
  source.next();
  }
  if (source.eat('\'')) {
  return "string";
  }
  return "error";
  }
 
  if (ch == '"') {
  return switchState(source, setState, stringLiteral);
  }
 
  if (largeRE.test(ch)) {
  source.eatWhile(idRE);
  if (source.eat('.')) {
  return "qualifier";
  }
  return "variable-2";
  }
 
  if (smallRE.test(ch)) {
  source.eatWhile(idRE);
  return "variable";
  }
 
  if (digitRE.test(ch)) {
  if (ch == '0') {
  if (source.eat(/[xX]/)) {
  source.eatWhile(hexitRE); // should require at least 1
  return "integer";
  }
  if (source.eat(/[oO]/)) {
  source.eatWhile(octitRE); // should require at least 1
  return "number";
  }
  }
  source.eatWhile(digitRE);
  var t = "number";
  if (source.eat('.')) {
  t = "number";
  source.eatWhile(digitRE); // should require at least 1
  }
  if (source.eat(/[eE]/)) {
  t = "number";
  source.eat(/[-+]/);
  source.eatWhile(digitRE); // should require at least 1
  }
  return t;
  }
 
  if (symbolRE.test(ch)) {
  if (ch == '-' && source.eat(/-/)) {
  source.eatWhile(/-/);
  if (!source.eat(symbolRE)) {
  source.skipToEnd();
  return "comment";
  }
  }
  var t = "variable";
  if (ch == ':') {
  t = "variable-2";
  }
  source.eatWhile(symbolRE);
  return t;
  }
 
  return "error";
  }
 
  function ncomment(type, nest) {
  if (nest == 0) {
  return normal;
  }
  return function(source, setState) {
  var currNest = nest;
  while (!source.eol()) {
  var ch = source.next();
  if (ch == '{' && source.eat('-')) {
  ++currNest;
  }
  else if (ch == '-' && source.eat('}')) {
  --currNest;
  if (currNest == 0) {
  setState(normal);
  return type;
  }
  }
  }
  setState(ncomment(type, currNest));
  return type;
  }
  }
 
  function stringLiteral(source, setState) {
  while (!source.eol()) {
  var ch = source.next();
  if (ch == '"') {
  setState(normal);
  return "string";
  }
  if (ch == '\\') {
  if (source.eol() || source.eat(whiteCharRE)) {
  setState(stringGap);
  return "string";
  }
  if (source.eat('&')) {
  }
  else {
  source.next(); // should handle other escapes here
  }
  }
  }
  setState(normal);
  return "error";
  }
 
  function stringGap(source, setState) {
  if (source.eat('\\')) {
  return switchState(source, setState, stringLiteral);
  }
  source.next();
  setState(normal);
  return "error";
  }
 
 
  var wellKnownWords = (function() {
  var wkw = {};
  function setType(t) {
  return function () {
  for (var i = 0; i < arguments.length; i++)
  wkw[arguments[i]] = t;
  }
  }
 
  setType("keyword")(
  "case", "class", "data", "default", "deriving", "do", "else", "foreign",
  "if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
  "module", "newtype", "of", "then", "type", "where", "_");
 
  setType("keyword")(
  "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");
 
  setType("builtin")(
  "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
  "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");
 
  setType("builtin")(
  "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
  "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
  "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
  "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
  "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
  "String", "True");
 
  setType("builtin")(
  "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
  "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
  "compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
  "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
  "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
  "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
  "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
  "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
  "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
  "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
  "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
  "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
  "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
  "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
  "otherwise", "pi", "pred", "print", "product", "properFraction",
  "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
  "readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
  "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
  "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
  "sequence", "sequence_", "show", "showChar", "showList", "showParen",
  "showString", "shows", "showsPrec", "significand", "signum", "sin",
  "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
  "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
  "toRational", "truncate", "uncurry", "undefined", "unlines", "until",
  "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
  "zip3", "zipWith", "zipWith3");
 
  return wkw;
  })();
 
 
 
  return {
  startState: function () { return { f: normal }; },
  copyState: function (s) { return { f: s.f }; },
 
  token: function(stream, state) {
  var t = state.f(stream, function(s) { state.f = s; });
  var w = stream.current();
  return (w in wellKnownWords) ? wellKnownWords[w] : t;
  }
  };
 
  });
 
  CodeMirror.defineMIME("text/x-haskell", "haskell");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Haskell mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="haskell.js"></script>
  <link rel="stylesheet" href="../../theme/elegant.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Haskell mode</h1>
 
  <form><textarea id="code" name="code">
  module UniquePerms (
  uniquePerms
  )
  where
 
  -- | Find all unique permutations of a list where there might be duplicates.
  uniquePerms :: (Eq a) => [a] -> [[a]]
  uniquePerms = permBag . makeBag
 
  -- | An unordered collection where duplicate values are allowed,
  -- but represented with a single value and a count.
  type Bag a = [(a, Int)]
 
  makeBag :: (Eq a) => [a] -> Bag a
  makeBag [] = []
  makeBag (a:as) = mix a $ makeBag as
  where
  mix a [] = [(a,1)]
  mix a (bn@(b,n):bs) | a == b = (b,n+1):bs
  | otherwise = bn : mix a bs
 
  permBag :: Bag a -> [[a]]
  permBag [] = [[]]
  permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
  where
  oneOfEach [] = []
  oneOfEach (an@(a,n):bs) =
  let bs' = if n == 1 then bs else (a,n-1):bs
  in (a,bs') : mapSnd (an:) (oneOfEach bs)
 
  apSnd f (a,b) = (a, f b)
  mapSnd = map . apSnd
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  theme: "elegant"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
 
  //config settings
  var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i,
  scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i;
 
  //inner modes
  var scriptingMode, htmlMixedMode;
 
  //tokenizer when in html mode
  function htmlDispatch(stream, state) {
  if (stream.match(scriptStartRegex, false)) {
  state.token=scriptingDispatch;
  return scriptingMode.token(stream, state.scriptState);
  }
  else
  return htmlMixedMode.token(stream, state.htmlState);
  }
 
  //tokenizer when in scripting mode
  function scriptingDispatch(stream, state) {
  if (stream.match(scriptEndRegex, false)) {
  state.token=htmlDispatch;
  return htmlMixedMode.token(stream, state.htmlState);
  }
  else
  return scriptingMode.token(stream, state.scriptState);
  }
 
 
  return {
  startState: function() {
  scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec);
  htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed");
  return {
  token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch,
  htmlState : htmlMixedMode.startState(),
  scriptState : scriptingMode.startState()
  }
  },
 
  token: function(stream, state) {
  return state.token(stream, state);
  },
 
  indent: function(state, textAfter) {
  if (state.token == htmlDispatch)
  return htmlMixedMode.indent(state.htmlState, textAfter);
  else
  return scriptingMode.indent(state.scriptState, textAfter);
  },
 
  copyState: function(state) {
  return {
  token : state.token,
  htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState),
  scriptState : CodeMirror.copyState(scriptingMode, state.scriptState)
  }
  },
 
 
  electricChars: "/{}:"
  }
  });
 
  CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"});
  CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
  CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"});
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Html Embedded Scripts mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="../xml/xml.js"></script>
  <script src="../javascript/javascript.js"></script>
  <script src="../css/css.js"></script>
  <script src="../htmlmixed/htmlmixed.js"></script>
  <script src="htmlembedded.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Html Embedded Scripts mode</h1>
 
  <form><textarea id="code" name="code">
  <%
  function hello(who) {
  return "Hello " + who;
  }
  %>
  This is an example of EJS (embedded javascript)
  <p>The program says <%= hello("world") %>.</p>
  <script>
  alert("And here is some normal JS code"); // also colored
  </script>
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "application/x-ejs",
  indentUnit: 4,
  indentWithTabs: true,
  enterMode: "keep",
  tabMode: "shift"
  });
  </script>
 
  <p>Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
  JavaScript, CSS and XML.<br />Other dependancies include those of the scriping language chosen.</p>
 
  <p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET),
  <code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)</p>
  </body>
  </html>
 
  CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
  var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
  var jsMode = CodeMirror.getMode(config, "javascript");
  var cssMode = CodeMirror.getMode(config, "css");
 
  function html(stream, state) {
  var style = htmlMode.token(stream, state.htmlState);
  if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
  if (/^script$/i.test(state.htmlState.context.tagName)) {
  state.token = javascript;
  state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
  state.mode = "javascript";
  }
  else if (/^style$/i.test(state.htmlState.context.tagName)) {
  state.token = css;
  state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
  state.mode = "css";
  }
  }
  return style;
  }
  function maybeBackup(stream, pat, style) {
  var cur = stream.current();
  var close = cur.search(pat);
  if (close > -1) stream.backUp(cur.length - close);
  return style;
  }
  function javascript(stream, state) {
  if (stream.match(/^<\/\s*script\s*>/i, false)) {
  state.token = html;
  state.curState = null;
  state.mode = "html";
  return html(stream, state);
  }
  return maybeBackup(stream, /<\/\s*script\s*>/,
  jsMode.token(stream, state.localState));
  }
  function css(stream, state) {
  if (stream.match(/^<\/\s*style\s*>/i, false)) {
  state.token = html;
  state.localState = null;
  state.mode = "html";
  return html(stream, state);
  }
  return maybeBackup(stream, /<\/\s*style\s*>/,
  cssMode.token(stream, state.localState));
  }
 
  return {
  startState: function() {
  var state = htmlMode.startState();
  return {token: html, localState: null, mode: "html", htmlState: state};
  },
 
  copyState: function(state) {
  if (state.localState)
  var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
  return {token: state.token, localState: local, mode: state.mode,
  htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
  },
 
  token: function(stream, state) {
  return state.token(stream, state);
  },
 
  indent: function(state, textAfter) {
  if (state.token == html || /^\s*<\//.test(textAfter))
  return htmlMode.indent(state.htmlState, textAfter);
  else if (state.token == javascript)
  return jsMode.indent(state.localState, textAfter);
  else
  return cssMode.indent(state.localState, textAfter);
  },
 
  compareStates: function(a, b) {
  return htmlMode.compareStates(a.htmlState, b.htmlState);
  },
 
  electricChars: "/{}:"
  }
  });
 
  CodeMirror.defineMIME("text/html", "htmlmixed");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: HTML mixed mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="../xml/xml.js"></script>
  <script src="../javascript/javascript.js"></script>
  <script src="../css/css.js"></script>
  <script src="htmlmixed.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: HTML mixed mode</h1>
  <form><textarea id="code" name="code">
  <html style="color: green">
  <!-- this is a comment -->
  <head>
  <title>Mixed HTML Example</title>
  <style type="text/css">
  h1 {font-family: comic sans; color: #f0f;}
  div {background: yellow !important;}
  body {
  max-width: 50em;
  margin: 1em 2em 1em 5em;
  }
  </style>
  </head>
  <body>
  <h1>Mixed HTML Example</h1>
  <script>
  function jsFunc(arg1, arg2) {
  if (arg1 && arg2) document.body.innerHTML = "achoo";
  }
  </script>
  </body>
  </html>
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
  </script>
 
  <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
 
  <p><strong>MIME types defined:</strong> <code>text/html</code>
  (redefined, only takes effect if you load this parser after the
  XML parser).</p>
 
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: JavaScript mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="javascript.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: JavaScript mode</h1>
 
  <div><textarea id="code" name="code">
  // Demo code (the actual new parser character stream implementation)
 
  function StringStream(string) {
  this.pos = 0;
  this.string = string;
  }
 
  StringStream.prototype = {
  done: function() {return this.pos >= this.string.length;},
  peek: function() {return this.string.charAt(this.pos);},
  next: function() {
  if (this.pos &lt; this.string.length)
  return this.string.charAt(this.pos++);
  },
  eat: function(match) {
  var ch = this.string.charAt(this.pos);
  if (typeof match == "string") var ok = ch == match;
  else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);
  if (ok) {this.pos++; return ch;}
  },
  eatWhile: function(match) {
  var start = this.pos;
  while (this.eat(match));
  if (this.pos > start) return this.string.slice(start, this.pos);
  },
  backUp: function(n) {this.pos -= n;},
  column: function() {return this.pos;},
  eatSpace: function() {
  var start = this.pos;
  while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
  return this.pos - start;
  },
  match: function(pattern, consume, caseInsensitive) {
  if (typeof pattern == "string") {
  function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
  if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
  if (consume !== false) this.pos += str.length;
  return true;
  }
  }
  else {
  var match = this.string.slice(this.pos).match(pattern);
  if (match &amp;&amp; consume !== false) this.pos += match[0].length;
  return match;
  }
  }
  };
  </textarea></div>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true
  });
  </script>
 
  <p>JavaScript mode supports a single configuration
  option, <code>json</code>, which will set the mode to expect JSON
  data rather than a JavaScript program.</p>
 
  <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("javascript", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var jsonMode = parserConfig.json;
 
  // Tokenizer
 
  var keywords = function(){
  function kw(type) {return {type: type, style: "keyword"};}
  var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
  var operator = kw("operator"), atom = {type: "atom", style: "atom"};
  return {
  "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
  "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
  "var": kw("var"), "const": kw("var"), "let": kw("var"),
  "function": kw("function"), "catch": kw("catch"),
  "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
  "in": operator, "typeof": operator, "instanceof": operator,
  "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
  };
  }();
 
  var isOperatorChar = /[+\-*&%=<>!?|]/;
 
  function chain(stream, state, f) {
  state.tokenize = f;
  return f(stream, state);
  }
 
  function nextUntilUnescaped(stream, end) {
  var escaped = false, next;
  while ((next = stream.next()) != null) {
  if (next == end && !escaped)
  return false;
  escaped = !escaped && next == "\\";
  }
  return escaped;
  }
 
  // Used as scratch variables to communicate multiple values without
  // consing up tons of objects.
  var type, content;
  function ret(tp, style, cont) {
  type = tp; content = cont;
  return style;
  }
 
  function jsTokenBase(stream, state) {
  var ch = stream.next();
  if (ch == '"' || ch == "'")
  return chain(stream, state, jsTokenString(ch));
  else if (/[\[\]{}\(\),;\:\.]/.test(ch))
  return ret(ch);
  else if (ch == "0" && stream.eat(/x/i)) {
  stream.eatWhile(/[\da-f]/i);
  return ret("number", "number");
  }
  else if (/\d/.test(ch)) {
  stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
  return ret("number", "number");
  }
  else if (ch == "/") {
  if (stream.eat("*")) {
  return chain(stream, state, jsTokenComment);
  }
  else if (stream.eat("/")) {
  stream.skipToEnd();
  return ret("comment", "comment");
  }
  else if (state.reAllowed) {
  nextUntilUnescaped(stream, "/");
  stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
  return ret("regexp", "string");
  }
  else {
  stream.eatWhile(isOperatorChar);
  return ret("operator", null, stream.current());
  }
  }
  else if (ch == "#") {
  stream.skipToEnd();
  return ret("error", "error");
  }
  else if (isOperatorChar.test(ch)) {
  stream.eatWhile(isOperatorChar);
  return ret("operator", null, stream.current());
  }
  else {
  stream.eatWhile(/[\w\$_]/);
  var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
  return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
  ret("variable", "variable", word);
  }
  }
 
  function jsTokenString(quote) {
  return function(stream, state) {
  if (!nextUntilUnescaped(stream, quote))
  state.tokenize = jsTokenBase;
  return ret("string", "string");
  };
  }
 
  function jsTokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return ret("comment", "comment");
  }
 
  // Parser
 
  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
 
  function JSLexical(indented, column, type, align, prev, info) {
  this.indented = indented;
  this.column = column;
  this.type = type;
  this.prev = prev;
  this.info = info;
  if (align != null) this.align = align;
  }
 
  function inScope(state, varname) {
  for (var v = state.localVars; v; v = v.next)
  if (v.name == varname) return true;
  }
 
  function parseJS(state, style, type, content, stream) {
  var cc = state.cc;
  // Communicate our context to the combinators.
  // (Less wasteful than consing up a hundred closures on every call.)
  cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
 
  if (!state.lexical.hasOwnProperty("align"))
  state.lexical.align = true;
 
  while(true) {
  var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
  if (combinator(type, content)) {
  while(cc.length && cc[cc.length - 1].lex)
  cc.pop()();
  if (cx.marked) return cx.marked;
  if (type == "variable" && inScope(state, content)) return "variable-2";
  return style;
  }
  }
  }
 
  // Combinator utils
 
  var cx = {state: null, column: null, marked: null, cc: null};
  function pass() {
  for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  }
  function cont() {
  pass.apply(null, arguments);
  return true;
  }
  function register(varname) {
  var state = cx.state;
  if (state.context) {
  cx.marked = "def";
  for (var v = state.localVars; v; v = v.next)
  if (v.name == varname) return;
  state.localVars = {name: varname, next: state.localVars};
  }
  }
 
  // Combinators
 
  var defaultVars = {name: "this", next: {name: "arguments"}};
  function pushcontext() {
  if (!cx.state.context) cx.state.localVars = defaultVars;
  cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
  }
  function popcontext() {
  cx.state.localVars = cx.state.context.vars;
  cx.state.context = cx.state.context.prev;
  }
  function pushlex(type, info) {
  var result = function() {
  var state = cx.state;
  state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info)
  };
  result.lex = true;
  return result;
  }
  function poplex() {
  var state = cx.state;
  if (state.lexical.prev) {
  if (state.lexical.type == ")")
  state.indented = state.lexical.indented;
  state.lexical = state.lexical.prev;
  }
  }
  poplex.lex = true;
 
  function expect(wanted) {
  return function expecting(type) {
  if (type == wanted) return cont();
  else if (wanted == ";") return pass();
  else return cont(arguments.callee);
  };
  }
 
  function statement(type) {
  if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
  if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
  if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
  if (type == "{") return cont(pushlex("}"), block, poplex);
  if (type == ";") return cont();
  if (type == "function") return cont(functiondef);
  if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
  poplex, statement, poplex);
  if (type == "variable") return cont(pushlex("stat"), maybelabel);
  if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
  block, poplex, poplex);
  if (type == "case") return cont(expression, expect(":"));
  if (type == "default") return cont(expect(":"));
  if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
  statement, poplex, popcontext);
  return pass(pushlex("stat"), expression, expect(";"), poplex);
  }
  function expression(type) {
  if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
  if (type == "function") return cont(functiondef);
  if (type == "keyword c") return cont(maybeexpression);
  if (type == "(") return cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
  if (type == "operator") return cont(expression);
  if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
  if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
  return cont();
  }
  function maybeexpression(type) {
  if (type.match(/[;\}\)\],]/)) return pass();
  return pass(expression);
  }
 
  function maybeoperator(type, value) {
  if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
  if (type == "operator") return cont(expression);
  if (type == ";") return;
  if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
  if (type == ".") return cont(property, maybeoperator);
  if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
  }
  function maybelabel(type) {
  if (type == ":") return cont(poplex, statement);
  return pass(maybeoperator, expect(";"), poplex);
  }
  function property(type) {
  if (type == "variable") {cx.marked = "property"; return cont();}
  }
  function objprop(type) {
  if (type == "variable") cx.marked = "property";
  if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
  }
  function commasep(what, end) {
  function proceed(type) {
  if (type == ",") return cont(what, proceed);
  if (type == end) return cont();
  return cont(expect(end));
  }
  return function commaSeparated(type) {
  if (type == end) return cont();
  else return pass(what, proceed);
  };
  }
  function block(type) {
  if (type == "}") return cont();
  return pass(statement, block);
  }
  function vardef1(type, value) {
  if (type == "variable"){register(value); return cont(vardef2);}
  return cont();
  }
  function vardef2(type, value) {
  if (value == "=") return cont(expression, vardef2);
  if (type == ",") return cont(vardef1);
  }
  function forspec1(type) {
  if (type == "var") return cont(vardef1, forspec2);
  if (type == ";") return pass(forspec2);
  if (type == "variable") return cont(formaybein);
  return pass(forspec2);
  }
  function formaybein(type, value) {
  if (value == "in") return cont(expression);
  return cont(maybeoperator, forspec2);
  }
  function forspec2(type, value) {
  if (type == ";") return cont(forspec3);
  if (value == "in") return cont(expression);
  return cont(expression, expect(";"), forspec3);
  }
  function forspec3(type) {
  if (type != ")") cont(expression);
  }
  function functiondef(type, value) {
  if (type == "variable") {register(value); return cont(functiondef);}
  if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
  }
  function funarg(type, value) {
  if (type == "variable") {register(value); return cont();}
  }
 
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: jsTokenBase,
  reAllowed: true,
  kwAllowed: true,
  cc: [],
  lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
  localVars: null,
  context: null,
  indented: 0
  };
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  if (!state.lexical.hasOwnProperty("align"))
  state.lexical.align = false;
  state.indented = stream.indentation();
  }
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
  if (type == "comment") return style;
  state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
  state.kwAllowed = type != '.';
  return parseJS(state, style, type, content, stream);
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != jsTokenBase) return 0;
  var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
  type = lexical.type, closing = firstChar == type;
  if (type == "vardef") return lexical.indented + 4;
  else if (type == "form" && firstChar == "{") return lexical.indented;
  else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
  else if (lexical.info == "switch" && !closing)
  return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
  else if (lexical.align) return lexical.column + (closing ? 0 : 1);
  else return lexical.indented + (closing ? 0 : indentUnit);
  },
 
  electricChars: ":{}"
  };
  });
 
  CodeMirror.defineMIME("text/javascript", "javascript");
  CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Jinja2 mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="jinja2.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Jinja2 mode</h1>
  <form><textarea id="code" name="code">
  &lt;html style="color: green"&gt;
  &lt;!-- this is a comment --&gt;
  &lt;head&gt;
  &lt;title&gt;Jinja2 Example&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;ul&gt;
  {# this is a comment #}
  {%- for item in li -%}
  &lt;li&gt;
  {{ item.label }}
  &lt;/li&gt;
  {% endfor -%}
  &lt;/ul&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </textarea></form>
  <script>
  var editor =
  CodeMirror.fromTextArea(document.getElementById("code"), {mode:
  {name: "jinja2", htmlMode: true}});
  </script>
  </body>
  </html>
 
  CodeMirror.defineMode("jinja2", function(config, parserConf) {
  var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
  "loop", "none", "self", "super", "if", "as", "not", "and",
  "else", "import", "with", "without", "context"];
  keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
 
  function tokenBase (stream, state) {
  var ch = stream.next();
  if (ch == "{") {
  if (ch = stream.eat(/\{|%|#/)) {
  stream.eat("-");
  state.tokenize = inTag(ch);
  return "tag";
  }
  }
  }
  function inTag (close) {
  if (close == "{") {
  close = "}";
  }
  return function (stream, state) {
  var ch = stream.next();
  if ((ch == close || (ch == "-" && stream.eat(close)))
  && stream.eat("}")) {
  state.tokenize = tokenBase;
  return "tag";
  }
  if (stream.match(keywords)) {
  return "keyword";
  }
  return close == "#" ? "comment" : "string";
  };
  }
  return {
  startState: function () {
  return {tokenize: tokenBase};
  },
  token: function (stream, state) {
  return state.tokenize(stream, state);
  }
  };
  });
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Lua mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="lua.js"></script>
  <link rel="stylesheet" href="../../theme/neat.css">
  <style>.CodeMirror {border: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Lua mode</h1>
  <form><textarea id="code" name="code">
  --[[
  example useless code to show lua syntax highlighting
  this is multiline comment
  ]]
 
  function blahblahblah(x)
 
  local table = {
  "asd" = 123,
  "x" = 0.34,
  }
  if x ~= 3 then
  print( x )
  elseif x == "string"
  my_custom_function( 0x34 )
  else
  unknown_function( "some string" )
  end
 
  --single line comment
 
  end
 
  function blablabla3()
 
  for k,v in ipairs( table ) do
  --abcde..
  y=[=[
  x=[[
  x is a multi line string
  ]]
  but its definition is iside a highest level string!
  ]=]
  print(" \"\" ")
 
  s = math.sin( x )
  end
 
  end
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  tabMode: "indent",
  matchBrackets: true,
  theme: "neat"
  });
  </script>
 
  <p>Loosely based on Franciszek
  Wawrzak's <a href="http://codemirror.net/1/contrib/lua">CodeMirror
  1 mode</a>. One configuration parameter is
  supported, <code>specials</code>, to which you can provide an
  array of strings to have those identifiers highlighted with
  the <code>lua-special</code> style.</p>
  <p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>
 
  </body>
  </html>
 
  // LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
  // CodeMirror 1 mode.
  // highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
 
  CodeMirror.defineMode("lua", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
 
  function prefixRE(words) {
  return new RegExp("^(?:" + words.join("|") + ")", "i");
  }
  function wordRE(words) {
  return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }
  var specials = wordRE(parserConfig.specials || []);
 
  // long list of standard functions from lua manual
  var builtins = wordRE([
  "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
  "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
  "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
 
  "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
 
  "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
  "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
  "debug.setupvalue","debug.traceback",
 
  "close","flush","lines","read","seek","setvbuf","write",
 
  "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
  "io.stdout","io.tmpfile","io.type","io.write",
 
  "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
  "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
  "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
  "math.sqrt","math.tan","math.tanh",
 
  "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
  "os.time","os.tmpname",
 
  "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
  "package.seeall",
 
  "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
  "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
 
  "table.concat","table.insert","table.maxn","table.remove","table.sort"
  ]);
  var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
  "true","function", "end", "if", "then", "else", "do",
  "while", "repeat", "until", "for", "in", "local" ]);
 
  var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]);
  var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
  var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
 
  function readBracket(stream) {
  var level = 0;
  while (stream.eat("=")) ++level;
  stream.eat("[");
  return level;
  }
 
  function normal(stream, state) {
  var ch = stream.next();
  if (ch == "-" && stream.eat("-")) {
  if (stream.eat("["))
  return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
  stream.skipToEnd();
  return "comment";
  }
  if (ch == "\"" || ch == "'")
  return (state.cur = string(ch))(stream, state);
  if (ch == "[" && /[\[=]/.test(stream.peek()))
  return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
  if (/\d/.test(ch)) {
  stream.eatWhile(/[\w.%]/);
  return "number";
  }
  if (/[\w_]/.test(ch)) {
  stream.eatWhile(/[\w\\\-_.]/);
  return "variable";
  }
  return null;
  }
 
  function bracketed(level, style) {
  return function(stream, state) {
  var curlev = null, ch;
  while ((ch = stream.next()) != null) {
  if (curlev == null) {if (ch == "]") curlev = 0;}
  else if (ch == "=") ++curlev;
  else if (ch == "]" && curlev == level) { state.cur = normal; break; }
  else curlev = null;
  }
  return style;
  };
  }
 
  function string(quote) {
  return function(stream, state) {
  var escaped = false, ch;
  while ((ch = stream.next()) != null) {
  if (ch == quote && !escaped) break;
  escaped = !escaped && ch == "\\";
  }
  if (!escaped) state.cur = normal;
  return "string";
  };
  }
 
  return {
  startState: function(basecol) {
  return {basecol: basecol || 0, indentDepth: 0, cur: normal};
  },
 
  token: function(stream, state) {
  if (stream.eatSpace()) return null;
  var style = state.cur(stream, state);
  var word = stream.current();
  if (style == "variable") {
  if (keywords.test(word)) style = "keyword";
  else if (builtins.test(word)) style = "builtin";
  else if (specials.test(word)) style = "variable-2";
  }
  if ((style != "comment") && (style != "string")){
  if (indentTokens.test(word)) ++state.indentDepth;
  else if (dedentTokens.test(word)) --state.indentDepth;
  }
  return style;
  },
 
  indent: function(state, textAfter) {
  var closing = dedentPartial.test(textAfter);
  return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-lua", "lua");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Markdown mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="../xml/xml.js"></script>
  <script src="markdown.js"></script>
  <link rel="stylesheet" href="markdown.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Markdown mode</h1>
 
  <!-- source: http://daringfireball.net/projects/markdown/basics.text -->
  <form><textarea id="code" name="code">
  Markdown: Basics
  ================
 
  &lt;ul id="ProjectSubmenu"&gt;
  &lt;li&gt;&lt;a href="/projects/markdown/" title="Markdown Project Page"&gt;Main&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a class="selected" title="Markdown Basics"&gt;Basics&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="/projects/markdown/syntax" title="Markdown Syntax Documentation"&gt;Syntax&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="/projects/markdown/license" title="Pricing and License Information"&gt;License&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="/projects/markdown/dingus" title="Online Markdown Web Form"&gt;Dingus&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
 
 
  Getting the Gist of Markdown's Formatting Syntax
  ------------------------------------------------
 
  This page offers a brief overview of what it's like to use Markdown.
  The [syntax page] [s] provides complete, detailed documentation for
  every feature, but Markdown should be very easy to pick up simply by
  looking at a few examples of it in action. The examples on this page
  are written in a before/after style, showing example syntax and the
  HTML output produced by Markdown.
 
  It's also helpful to simply try Markdown out; the [Dingus] [d] is a
  web application that allows you type your own Markdown-formatted text
  and translate it to XHTML.
 
  **Note:** This document is itself written using Markdown; you
  can [see the source for it by adding '.text' to the URL] [src].
 
  [s]: /projects/markdown/syntax "Markdown Syntax"
  [d]: /projects/markdown/dingus "Markdown Dingus"
  [src]: /projects/markdown/basics.text
 
 
  ## Paragraphs, Headers, Blockquotes ##
 
  A paragraph is simply one or more consecutive lines of text, separated
  by one or more blank lines. (A blank line is any line that looks like
  a blank line -- a line containing nothing but spaces or tabs is
  considered blank.) Normal paragraphs should not be indented with
  spaces or tabs.
 
  Markdown offers two styles of headers: *Setext* and *atx*.
  Setext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by
  "underlining" with equal signs (`=`) and hyphens (`-`), respectively.
  To create an atx-style header, you put 1-6 hash marks (`#`) at the
  beginning of the line -- the number of hashes equals the resulting
  HTML header level.
 
  Blockquotes are indicated using email-style '`&gt;`' angle brackets.
 
  Markdown:
 
  A First Level Header
  ====================
 
  A Second Level Header
  ---------------------
 
  Now is the time for all good men to come to
  the aid of their country. This is just a
  regular paragraph.
 
  The quick brown fox jumped over the lazy
  dog's back.
 
  ### Header 3
 
  &gt; This is a blockquote.
  &gt;
  &gt; This is the second paragraph in the blockquote.
  &gt;
  &gt; ## This is an H2 in a blockquote
 
 
  Output:
 
  &lt;h1&gt;A First Level Header&lt;/h1&gt;
 
  &lt;h2&gt;A Second Level Header&lt;/h2&gt;
 
  &lt;p&gt;Now is the time for all good men to come to
  the aid of their country. This is just a
  regular paragraph.&lt;/p&gt;
 
  &lt;p&gt;The quick brown fox jumped over the lazy
  dog's back.&lt;/p&gt;
 
  &lt;h3&gt;Header 3&lt;/h3&gt;
 
  &lt;blockquote&gt;
  &lt;p&gt;This is a blockquote.&lt;/p&gt;
 
  &lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
 
  &lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
  &lt;/blockquote&gt;
 
 
 
  ### Phrase Emphasis ###
 
  Markdown uses asterisks and underscores to indicate spans of emphasis.
 
  Markdown:
 
  Some of these words *are emphasized*.
  Some of these words _are emphasized also_.
 
  Use two asterisks for **strong emphasis**.
  Or, if you prefer, __use two underscores instead__.
 
  Output:
 
  &lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
  Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
 
  &lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
  Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
 
 
 
  ## Lists ##
 
  Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
  `+`, and `-`) as list markers. These three markers are
  interchangable; this:
 
  * Candy.
  * Gum.
  * Booze.
 
  this:
 
  + Candy.
  + Gum.
  + Booze.
 
  and this:
 
  - Candy.
  - Gum.
  - Booze.
 
  all produce the same output:
 
  &lt;ul&gt;
  &lt;li&gt;Candy.&lt;/li&gt;
  &lt;li&gt;Gum.&lt;/li&gt;
  &lt;li&gt;Booze.&lt;/li&gt;
  &lt;/ul&gt;
 
  Ordered (numbered) lists use regular numbers, followed by periods, as
  list markers:
 
  1. Red
  2. Green
  3. Blue
 
  Output:
 
  &lt;ol&gt;
  &lt;li&gt;Red&lt;/li&gt;
  &lt;li&gt;Green&lt;/li&gt;
  &lt;li&gt;Blue&lt;/li&gt;
  &lt;/ol&gt;
 
  If you put blank lines between items, you'll get `&lt;p&gt;` tags for the
  list item text. You can create multi-paragraph list items by indenting
  the paragraphs by 4 spaces or 1 tab:
 
  * A list item.
 
  With multiple paragraphs.
 
  * Another item in the list.
 
  Output:
 
  &lt;ul&gt;
  &lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
  &lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
  &lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
  &lt;/ul&gt;
 
 
 
  ### Links ###
 
  Markdown supports two styles for creating links: *inline* and
  *reference*. With both styles, you use square brackets to delimit the
  text you want to turn into a link.
 
  Inline-style links use parentheses immediately after the link text.
  For example:
 
  This is an [example link](http://example.com/).
 
  Output:
 
  &lt;p&gt;This is an &lt;a href="http://example.com/"&gt;
  example link&lt;/a&gt;.&lt;/p&gt;
 
  Optionally, you may include a title attribute in the parentheses:
 
  This is an [example link](http://example.com/ "With a Title").
 
  Output:
 
  &lt;p&gt;This is an &lt;a href="http://example.com/" title="With a Title"&gt;
  example link&lt;/a&gt;.&lt;/p&gt;
 
  Reference-style links allow you to refer to your links by names, which
  you define elsewhere in your document:
 
  I get 10 times more traffic from [Google][1] than from
  [Yahoo][2] or [MSN][3].
 
  [1]: http://google.com/ "Google"
  [2]: http://search.yahoo.com/ "Yahoo Search"
  [3]: http://search.msn.com/ "MSN Search"
 
  Output:
 
  &lt;p&gt;I get 10 times more traffic from &lt;a href="http://google.com/"
  title="Google"&gt;Google&lt;/a&gt; than from &lt;a href="http://search.yahoo.com/"
  title="Yahoo Search"&gt;Yahoo&lt;/a&gt; or &lt;a href="http://search.msn.com/"
  title="MSN Search"&gt;MSN&lt;/a&gt;.&lt;/p&gt;
 
  The title attribute is optional. Link names may contain letters,
  numbers and spaces, but are *not* case sensitive:
 
  I start my morning with a cup of coffee and
  [The New York Times][NY Times].
 
  [ny times]: http://www.nytimes.com/
 
  Output:
 
  &lt;p&gt;I start my morning with a cup of coffee and
  &lt;a href="http://www.nytimes.com/"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
 
 
  ### Images ###
 
  Image syntax is very much like link syntax.
 
  Inline (titles are optional):
 
  ![alt text](/path/to/img.jpg "Title")
 
  Reference-style:
 
  ![alt text][id]
 
  [id]: /path/to/img.jpg "Title"
 
  Both of the above examples produce the same output:
 
  &lt;img src="/path/to/img.jpg" alt="alt text" title="Title" /&gt;
 
 
 
  ### Code ###
 
  In a regular paragraph, you can create code span by wrapping text in
  backtick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or
  `&gt;`) will automatically be translated into HTML entities. This makes
  it easy to use Markdown to write about HTML example code:
 
  I strongly recommend against using any `&lt;blink&gt;` tags.
 
  I wish SmartyPants used named entities like `&amp;mdash;`
  instead of decimal-encoded entites like `&amp;#8212;`.
 
  Output:
 
  &lt;p&gt;I strongly recommend against using any
  &lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
 
  &lt;p&gt;I wish SmartyPants used named entities like
  &lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
  entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
 
 
  To specify an entire block of pre-formatted code, indent every line of
  the block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,
  and `&gt;` characters will be escaped automatically.
 
  Markdown:
 
  If you want your page to validate under XHTML 1.0 Strict,
  you've got to put paragraph tags in your blockquotes:
 
  &lt;blockquote&gt;
  &lt;p&gt;For example.&lt;/p&gt;
  &lt;/blockquote&gt;
 
  Output:
 
  &lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
  you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
 
  &lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
  &amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
  &amp;lt;/blockquote&amp;gt;
  &lt;/code&gt;&lt;/pre&gt;
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: 'markdown',
  lineNumbers: true,
  matchBrackets: true,
  theme: "default"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
 
  var htmlMode = CodeMirror.getMode(cmCfg, { name: 'xml', htmlMode: true });
 
  var header = 'header'
  , code = 'comment'
  , quote = 'quote'
  , list = 'string'
  , hr = 'hr'
  , linktext = 'link'
  , linkhref = 'string'
  , em = 'em'
  , strong = 'strong'
  , emstrong = 'emstrong';
 
  var hrRE = /^[*-=_]/
  , ulRE = /^[*-+]\s+/
  , olRE = /^[0-9]\.\s+/
  , headerRE = /^(?:\={3,}|-{3,})$/
  , codeRE = /^(k:\t|\s{4,})/
  , textRE = /^[^\[*_\\<>`]+/;
 
  function switchInline(stream, state, f) {
  state.f = state.inline = f;
  return f(stream, state);
  }
 
  function switchBlock(stream, state, f) {
  state.f = state.block = f;
  return f(stream, state);
  }
 
 
  // Blocks
 
  function blockNormal(stream, state) {
  if (stream.match(codeRE)) {
  stream.skipToEnd();
  return code;
  }
 
  if (stream.eatSpace()) {
  return null;
  }
 
  if (stream.peek() === '#' || stream.match(headerRE)) {
  stream.skipToEnd();
  return header;
  }
  if (stream.eat('>')) {
  state.indentation++;
  return quote;
  }
  if (stream.peek() === '[') {
  return switchInline(stream, state, footnoteLink);
  }
  if (hrRE.test(stream.peek())) {
  var re = new RegExp('(?:\s*['+stream.peek()+']){3,}$');
  if (stream.match(re, true)) {
  return hr;
  }
  }
 
  var match;
  if (match = stream.match(ulRE, true) || stream.match(olRE, true)) {
  state.indentation += match[0].length;
  return list;
  }
 
  return switchInline(stream, state, state.inline);
  }
 
  function htmlBlock(stream, state) {
  var style = htmlMode.token(stream, state.htmlState);
  if (style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
  state.f = inlineNormal;
  state.block = blockNormal;
  }
  return style;
  }
 
 
  // Inline
  function getType(state) {
  return state.strong ? (state.em ? emstrong : strong)
  : (state.em ? em : null);
  }
 
  function handleText(stream, state) {
  if (stream.match(textRE, true)) {
  return getType(state);
  }
  return undefined;
  }
 
  function inlineNormal(stream, state) {
  var style = state.text(stream, state)
  if (typeof style !== 'undefined')
  return style;
 
  var ch = stream.next();
 
  if (ch === '\\') {
  stream.next();
  return getType(state);
  }
  if (ch === '`') {
  return switchInline(stream, state, inlineElement(code, '`'));
  }
  if (ch === '[') {
  return switchInline(stream, state, linkText);
  }
  if (ch === '<' && stream.match(/^\w/, false)) {
  stream.backUp(1);
  return switchBlock(stream, state, htmlBlock);
  }
 
  var t = getType(state);
  if (ch === '*' || ch === '_') {
  if (stream.eat(ch)) {
  return (state.strong = !state.strong) ? getType(state) : t;
  }
  return (state.em = !state.em) ? getType(state) : t;
  }
 
  return getType(state);
  }
 
  function linkText(stream, state) {
  while (!stream.eol()) {
  var ch = stream.next();
  if (ch === '\\') stream.next();
  if (ch === ']') {
  state.inline = state.f = linkHref;
  return linktext;
  }
  }
  return linktext;
  }
 
  function linkHref(stream, state) {
  stream.eatSpace();
  var ch = stream.next();
  if (ch === '(' || ch === '[') {
  return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
  }
  return 'error';
  }
 
  function footnoteLink(stream, state) {
  if (stream.match(/^[^\]]*\]:/, true)) {
  state.f = footnoteUrl;
  return linktext;
  }
  return switchInline(stream, state, inlineNormal);
  }
 
  function footnoteUrl(stream, state) {
  stream.eatSpace();
  stream.match(/^[^\s]+/, true);
  state.f = state.inline = inlineNormal;
  return linkhref;
  }
 
  function inlineRE(endChar) {
  if (!inlineRE[endChar]) {
  // match any not-escaped-non-endChar and any escaped char
  // then match endChar or eol
  inlineRE[endChar] = new RegExp('^(?:[^\\\\\\' + endChar + ']|\\\\.)*(?:\\' + endChar + '|$)');
  }
  return inlineRE[endChar];
  }
 
  function inlineElement(type, endChar, next) {
  next = next || inlineNormal;
  return function(stream, state) {
  stream.match(inlineRE(endChar));
  state.inline = state.f = next;
  return type;
  };
  }
 
  return {
  startState: function() {
  return {
  f: blockNormal,
 
  block: blockNormal,
  htmlState: htmlMode.startState(),
  indentation: 0,
 
  inline: inlineNormal,
  text: handleText,
  em: false,
  strong: false
  };
  },
 
  copyState: function(s) {
  return {
  f: s.f,
 
  block: s.block,
  htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
  indentation: s.indentation,
 
  inline: s.inline,
  text: s.text,
  em: s.em,
  strong: s.strong
  };
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  state.f = state.block;
  var previousIndentation = state.indentation
  , currentIndentation = 0;
  while (previousIndentation > 0) {
  if (stream.eat(' ')) {
  previousIndentation--;
  currentIndentation++;
  } else if (previousIndentation >= 4 && stream.eat('\t')) {
  previousIndentation -= 4;
  currentIndentation += 4;
  } else {
  break;
  }
  }
  state.indentation = currentIndentation;
 
  if (currentIndentation > 0) return null;
  }
  return state.f(stream, state);
  },
 
  getType: getType
  };
 
  });
 
  CodeMirror.defineMIME("text/x-markdown", "markdown");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: NTriples mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="ntriples.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">
  .CodeMirror {
  border: 1px solid #eee;
  }
  </style>
  </head>
  <body>
  <h1>CodeMirror: NTriples mode</h1>
  <form>
  <textarea id="ntriples" name="ntriples">
  <http://Sub1> <http://pred1> <http://obj> .
  <http://Sub2> <http://pred2#an2> "literal 1" .
  <http://Sub3#an3> <http://pred3> _:bnode3 .
  _:bnode4 <http://pred4> "literal 2"@lang .
  _:bnode5 <http://pred5> "literal 3"^^<http://type> .
  </textarea>
  </form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("ntriples"), {});
  </script>
  <p><strong>MIME types defined:</strong> <code>text/n-triples</code>.</p>
  </body>
  </html>
 
  /**********************************************************
  * This script provides syntax highlighting support for
  * the Ntriples format.
  * Ntriples format specification:
  * http://www.w3.org/TR/rdf-testcases/#ntriples
  ***********************************************************/
 
  /*
  The following expression defines the defined ASF grammar transitions.
 
  pre_subject ->
  {
  ( writing_subject_uri | writing_bnode_uri )
  -> pre_predicate
  -> writing_predicate_uri
  -> pre_object
  -> writing_object_uri | writing_object_bnode |
  (
  writing_object_literal
  -> writing_literal_lang | writing_literal_type
  )
  -> post_object
  -> BEGIN
  } otherwise {
  -> ERROR
  }
  */
  CodeMirror.defineMode("ntriples", function() {
 
  Location = {
  PRE_SUBJECT : 0,
  WRITING_SUB_URI : 1,
  WRITING_BNODE_URI : 2,
  PRE_PRED : 3,
  WRITING_PRED_URI : 4,
  PRE_OBJ : 5,
  WRITING_OBJ_URI : 6,
  WRITING_OBJ_BNODE : 7,
  WRITING_OBJ_LITERAL : 8,
  WRITING_LIT_LANG : 9,
  WRITING_LIT_TYPE : 10,
  POST_OBJ : 11,
  ERROR : 12
  };
  function transitState(currState, c) {
  var currLocation = currState.location;
  var ret;
 
  // Opening.
  if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;
  else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;
  else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI;
  else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI;
  else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE;
  else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL;
 
  // Closing.
  else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED;
  else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED;
  else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ;
  else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ;
  else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ;
  else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;
  else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;
  else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;
 
  // Closing typed and language literal.
  else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;
  else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;
 
  // Spaces.
  else if( c == ' ' &&
  (
  currLocation == Location.PRE_SUBJECT ||
  currLocation == Location.PRE_PRED ||
  currLocation == Location.PRE_OBJ ||
  currLocation == Location.POST_OBJ
  )
  ) ret = currLocation;
 
  // Reset.
  else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;
 
  // Error
  else ret = Location.ERROR;
 
  currState.location=ret;
  }
 
  untilSpace = function(c) { return c != ' '; };
  untilEndURI = function(c) { return c != '>'; };
  return {
  startState: function() {
  return {
  location : Location.PRE_SUBJECT,
  uris : [],
  anchors : [],
  bnodes : [],
  langs : [],
  types : []
  };
  },
  token: function(stream, state) {
  var ch = stream.next();
  if(ch == '<') {
  transitState(state, ch);
  var parsedURI = '';
  stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );
  state.uris.push(parsedURI);
  if( stream.match('#', false) ) return 'variable';
  stream.next();
  transitState(state, '>');
  return 'variable';
  }
  if(ch == '#') {
  var parsedAnchor = '';
  stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false});
  state.anchors.push(parsedAnchor);
  return 'variable-2';
  }
  if(ch == '>') {
  transitState(state, '>');
  return 'variable';
  }
  if(ch == '_') {
  transitState(state, ch);
  var parsedBNode = '';
  stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});
  state.bnodes.push(parsedBNode);
  stream.next();
  transitState(state, ' ');
  return 'builtin';
  }
  if(ch == '"') {
  transitState(state, ch);
  stream.eatWhile( function(c) { return c != '"'; } );
  stream.next();
  if( stream.peek() != '@' && stream.peek() != '^' ) {
  transitState(state, '"');
  }
  return 'string';
  }
  if( ch == '@' ) {
  transitState(state, '@');
  var parsedLang = '';
  stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});
  state.langs.push(parsedLang);
  stream.next();
  transitState(state, ' ');
  return 'string-2';
  }
  if( ch == '^' ) {
  stream.next();
  transitState(state, '^');
  var parsedType = '';
  stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );
  state.types.push(parsedType);
  stream.next();
  transitState(state, '>');
  return 'variable';
  }
  if( ch == ' ' ) {
  transitState(state, ch);
  }
  if( ch == '.' ) {
  transitState(state, ch);
  }
  }
  };
  });
 
  CodeMirror.defineMIME("text/n-triples", "ntriples");
 
  Copyright (c) 2011 souceLair <support@sourcelair.com>
 
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Pascal mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="pascal.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: Pascal mode</h1>
 
  <div><textarea id="code" name="code">
  (* Example Pascal code *)
 
  while a <> b do writeln('Waiting');
 
  if a > b then
  writeln('Condition met')
  else
  writeln('Condition not met');
 
  for i := 1 to 10 do
  writeln('Iteration: ', i:1);
 
  repeat
  a := a + 1
  until a = 10;
 
  case i of
  0: write('zero');
  1: write('one');
  2: write('two')
  end;
  </textarea></div>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "text/x-pascal"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("pascal", function(config) {
  function words(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
  var keywords = words("and array begin case const div do downto else end file for forward integer " +
  "boolean char function goto if in label mod nil not of or packed procedure " +
  "program record repeat set string then to type until var while with");
  var blockKeywords = words("case do else for if switch while struct then of");
  var atoms = {"null": true};
 
  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
  var curPunc;
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  if (ch == "#" && state.startOfLine) {
  stream.skipToEnd();
  return "meta";
  }
  if (ch == '"' || ch == "'") {
  state.tokenize = tokenString(ch);
  return state.tokenize(stream, state);
  }
  if (ch == "(" && stream.eat("*")) {
  state.tokenize = tokenComment;
  return tokenComment(stream, state);
  }
  if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
  curPunc = ch;
  return null
  }
  if (/\d/.test(ch)) {
  stream.eatWhile(/[\w\.]/);
  return "number";
  }
  if (ch == "/") {
  if (stream.eat("/")) {
  stream.skipToEnd();
  return "comment";
  }
  }
  if (isOperatorChar.test(ch)) {
  stream.eatWhile(isOperatorChar);
  return "operator";
  }
  stream.eatWhile(/[\w\$_]/);
  var cur = stream.current();
  if (keywords.propertyIsEnumerable(cur)) {
  if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
  return "keyword";
  }
  if (atoms.propertyIsEnumerable(cur)) return "atom";
  return "word";
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  var escaped = false, next, end = false;
  while ((next = stream.next()) != null) {
  if (next == quote && !escaped) {end = true; break;}
  escaped = !escaped && next == "\\";
  }
  if (end || !escaped) state.tokenize = null;
  return "string";
  };
  }
 
  function tokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == ")" && maybeEnd) {
  state.tokenize = null;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return "comment";
  }
 
  function Context(indented, column, type, align, prev) {
  this.indented = indented;
  this.column = column;
  this.type = type;
  this.align = align;
  this.prev = prev;
  }
  function pushContext(state, col, type) {
  return state.context = new Context(state.indented, col, type, null, state.context);
  }
  function popContext(state) {
  var t = state.context.type;
  if (t == ")" || t == "]" )
  state.indented = state.context.indented;
  return state.context = state.context.prev;
  }
 
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: null,
  context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
  indented: 0,
  startOfLine: true
  };
  },
 
  token: function(stream, state) {
  var ctx = state.context;
  if (stream.sol()) {
  if (ctx.align == null) ctx.align = false;
  state.indented = stream.indentation();
  state.startOfLine = true;
  }
  if (stream.eatSpace()) return null;
  curPunc = null;
  var style = (state.tokenize || tokenBase)(stream, state);
  if (style == "comment" || style == "meta") return style;
  if (ctx.align == null) ctx.align = true;
 
  if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
  else if (curPunc == "[") pushContext(state, stream.column(), "]");
  else if (curPunc == "(") pushContext(state, stream.column(), ")");
  else if (curPunc == ctx.type) popContext(state);
  else if ( ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
  pushContext(state, stream.column(), "statement");
  state.startOfLine = false;
  return style;
  },
 
  electricChars: "{}"
  };
  });
 
  CodeMirror.defineMIME("text/x-pascal", "pascal");
 
  Copyright (C) 2011 by Sabaca <mail@sabaca.com> under the MIT license.
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Perl mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="perl.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: Perl mode</h1>
 
  <div><textarea id="code" name="code">
  #!/usr/bin/perl
 
  use Something qw(func1 func2);
 
  # strings
  my $s1 = qq'single line';
  our $s2 = q(multi-
  line);
 
  =item Something
  Example.
  =cut
 
  my $html=<<'HTML'
  <html>
  <title>hi!</title>
  </html>
  HTML
 
  print "first,".join(',', 'second', qq~third~);
 
  if($s1 =~ m[(?<!\s)(l.ne)\z]o) {
  $h->{$1}=$$.' predefined variables';
  $s2 =~ s/\-line//ox;
  $s1 =~ s[
  line ]
  [
  block
  ]ox;
  }
 
  1; # numbers and comments
 
  __END__
  something...
 
  </textarea></div>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-perl</code>.</p>
  </body>
  </html>
 
  // CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
  // This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)
  CodeMirror.defineMode("perl",function(config,parserConfig){
  // http://perldoc.perl.org
  var PERL={ // null - magic touch
  // 1 - keyword
  // 2 - def
  // 3 - atom
  // 4 - operator
  // 5 - variable-2 (predefined)
  // [x,y] - x=1,2,3; y=must be defined if x{...}
  // PERL operators
  '->' : 4,
  '++' : 4,
  '--' : 4,
  '**' : 4,
  // ! ~ \ and unary + and -
  '=~' : 4,
  '!~' : 4,
  '*' : 4,
  '/' : 4,
  '%' : 4,
  'x' : 4,
  '+' : 4,
  '-' : 4,
  '.' : 4,
  '<<' : 4,
  '>>' : 4,
  // named unary operators
  '<' : 4,
  '>' : 4,
  '<=' : 4,
  '>=' : 4,
  'lt' : 4,
  'gt' : 4,
  'le' : 4,
  'ge' : 4,
  '==' : 4,
  '!=' : 4,
  '<=>' : 4,
  'eq' : 4,
  'ne' : 4,
  'cmp' : 4,
  '~~' : 4,
  '&' : 4,
  '|' : 4,
  '^' : 4,
  '&&' : 4,
  '||' : 4,
  '//' : 4,
  '..' : 4,
  '...' : 4,
  '?' : 4,
  ':' : 4,
  '=' : 4,
  '+=' : 4,
  '-=' : 4,
  '*=' : 4, // etc. ???
  ',' : 4,
  '=>' : 4,
  '::' : 4,
  // list operators (rightward)
  'not' : 4,
  'and' : 4,
  'or' : 4,
  'xor' : 4,
  // PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
  'BEGIN' : [5,1],
  'END' : [5,1],
  'PRINT' : [5,1],
  'PRINTF' : [5,1],
  'GETC' : [5,1],
  'READ' : [5,1],
  'READLINE' : [5,1],
  'DESTROY' : [5,1],
  'TIE' : [5,1],
  'TIEHANDLE' : [5,1],
  'UNTIE' : [5,1],
  'STDIN' : 5,
  'STDIN_TOP' : 5,
  'STDOUT' : 5,
  'STDOUT_TOP' : 5,
  'STDERR' : 5,
  'STDERR_TOP' : 5,
  '$ARG' : 5,
  '$_' : 5,
  '@ARG' : 5,
  '@_' : 5,
  '$LIST_SEPARATOR' : 5,
  '$"' : 5,
  '$PROCESS_ID' : 5,
  '$PID' : 5,
  '$$' : 5,
  '$REAL_GROUP_ID' : 5,
  '$GID' : 5,
  '$(' : 5,
  '$EFFECTIVE_GROUP_ID' : 5,
  '$EGID' : 5,
  '$)' : 5,
  '$PROGRAM_NAME' : 5,
  '$0' : 5,
  '$SUBSCRIPT_SEPARATOR' : 5,
  '$SUBSEP' : 5,
  '$;' : 5,
  '$REAL_USER_ID' : 5,
  '$UID' : 5,
  '$<' : 5,
  '$EFFECTIVE_USER_ID' : 5,
  '$EUID' : 5,
  '$>' : 5,
  '$a' : 5,
  '$b' : 5,
  '$COMPILING' : 5,
  '$^C' : 5,
  '$DEBUGGING' : 5,
  '$^D' : 5,
  '${^ENCODING}' : 5,
  '$ENV' : 5,
  '%ENV' : 5,
  '$SYSTEM_FD_MAX' : 5,
  '$^F' : 5,
  '@F' : 5,
  '${^GLOBAL_PHASE}' : 5,
  '$^H' : 5,
  '%^H' : 5,
  '@INC' : 5,
  '%INC' : 5,
  '$INPLACE_EDIT' : 5,
  '$^I' : 5,
  '$^M' : 5,
  '$OSNAME' : 5,
  '$^O' : 5,
  '${^OPEN}' : 5,
  '$PERLDB' : 5,
  '$^P' : 5,
  '$SIG' : 5,
  '%SIG' : 5,
  '$BASETIME' : 5,
  '$^T' : 5,
  '${^TAINT}' : 5,
  '${^UNICODE}' : 5,
  '${^UTF8CACHE}' : 5,
  '${^UTF8LOCALE}' : 5,
  '$PERL_VERSION' : 5,
  '$^V' : 5,
  '${^WIN32_SLOPPY_STAT}' : 5,
  '$EXECUTABLE_NAME' : 5,
  '$^X' : 5,
  '$1' : 5, // - regexp $1, $2...
  '$MATCH' : 5,
  '$&' : 5,
  '${^MATCH}' : 5,
  '$PREMATCH' : 5,
  '$`' : 5,
  '${^PREMATCH}' : 5,
  '$POSTMATCH' : 5,
  "$'" : 5,
  '${^POSTMATCH}' : 5,
  '$LAST_PAREN_MATCH' : 5,
  '$+' : 5,
  '$LAST_SUBMATCH_RESULT' : 5,
  '$^N' : 5,
  '@LAST_MATCH_END' : 5,
  '@+' : 5,
  '%LAST_PAREN_MATCH' : 5,
  '%+' : 5,
  '@LAST_MATCH_START' : 5,
  '@-' : 5,
  '%LAST_MATCH_START' : 5,
  '%-' : 5,
  '$LAST_REGEXP_CODE_RESULT' : 5,
  '$^R' : 5,
  '${^RE_DEBUG_FLAGS}' : 5,
  '${^RE_TRIE_MAXBUF}' : 5,
  '$ARGV' : 5,
  '@ARGV' : 5,
  'ARGV' : 5,
  'ARGVOUT' : 5,
  '$OUTPUT_FIELD_SEPARATOR' : 5,
  '$OFS' : 5,
  '$,' : 5,
  '$INPUT_LINE_NUMBER' : 5,
  '$NR' : 5,
  '$.' : 5,
  '$INPUT_RECORD_SEPARATOR' : 5,
  '$RS' : 5,
  '$/' : 5,
  '$OUTPUT_RECORD_SEPARATOR' : 5,
  '$ORS' : 5,
  '$\\' : 5,
  '$OUTPUT_AUTOFLUSH' : 5,
  '$|' : 5,
  '$ACCUMULATOR' : 5,
  '$^A' : 5,
  '$FORMAT_FORMFEED' : 5,
  '$^L' : 5,
  '$FORMAT_PAGE_NUMBER' : 5,
  '$%' : 5,
  '$FORMAT_LINES_LEFT' : 5,
  '$-' : 5,
  '$FORMAT_LINE_BREAK_CHARACTERS' : 5,
  '$:' : 5,
  '$FORMAT_LINES_PER_PAGE' : 5,
  '$=' : 5,
  '$FORMAT_TOP_NAME' : 5,
  '$^' : 5,
  '$FORMAT_NAME' : 5,
  '$~' : 5,
  '${^CHILD_ERROR_NATIVE}' : 5,
  '$EXTENDED_OS_ERROR' : 5,
  '$^E' : 5,
  '$EXCEPTIONS_BEING_CAUGHT' : 5,
  '$^S' : 5,
  '$WARNING' : 5,
  '$^W' : 5,
  '${^WARNING_BITS}' : 5,
  '$OS_ERROR' : 5,
  '$ERRNO' : 5,
  '$!' : 5,
  '%OS_ERROR' : 5,
  '%ERRNO' : 5,
  '%!' : 5,
  '$CHILD_ERROR' : 5,
  '$?' : 5,
  '$EVAL_ERROR' : 5,
  '$@' : 5,
  '$OFMT' : 5,
  '$#' : 5,
  '$*' : 5,
  '$ARRAY_BASE' : 5,
  '$[' : 5,
  '$OLD_PERL_VERSION' : 5,
  '$]' : 5,
  // PERL blocks
  'if' :[1,1],
  elsif :[1,1],
  'else' :[1,1],
  'while' :[1,1],
  unless :[1,1],
  'for' :[1,1],
  foreach :[1,1],
  // PERL functions
  'abs' :1, // - absolute value function
  accept :1, // - accept an incoming socket connect
  alarm :1, // - schedule a SIGALRM
  'atan2' :1, // - arctangent of Y/X in the range -PI to PI
  bind :1, // - binds an address to a socket
  binmode :1, // - prepare binary files for I/O
  bless :1, // - create an object
  bootstrap :1, //
  'break' :1, // - break out of a "given" block
  caller :1, // - get context of the current subroutine call
  chdir :1, // - change your current working directory
  chmod :1, // - changes the permissions on a list of files
  chomp :1, // - remove a trailing record separator from a string
  chop :1, // - remove the last character from a string
  chown :1, // - change the owership on a list of files
  chr :1, // - get character this number represents
  chroot :1, // - make directory new root for path lookups
  close :1, // - close file (or pipe or socket) handle
  closedir :1, // - close directory handle
  connect :1, // - connect to a remote socket
  'continue' :[1,1], // - optional trailing block in a while or foreach
  'cos' :1, // - cosine function
  crypt :1, // - one-way passwd-style encryption
  dbmclose :1, // - breaks binding on a tied dbm file
  dbmopen :1, // - create binding on a tied dbm file
  'default' :1, //
  defined :1, // - test whether a value, variable, or function is defined
  'delete' :1, // - deletes a value from a hash
  die :1, // - raise an exception or bail out
  'do' :1, // - turn a BLOCK into a TERM
  dump :1, // - create an immediate core dump
  each :1, // - retrieve the next key/value pair from a hash
  endgrent :1, // - be done using group file
  endhostent :1, // - be done using hosts file
  endnetent :1, // - be done using networks file
  endprotoent :1, // - be done using protocols file
  endpwent :1, // - be done using passwd file
  endservent :1, // - be done using services file
  eof :1, // - test a filehandle for its end
  'eval' :1, // - catch exceptions or compile and run code
  'exec' :1, // - abandon this program to run another
  exists :1, // - test whether a hash key is present
  exit :1, // - terminate this program
  'exp' :1, // - raise I to a power
  fcntl :1, // - file control system call
  fileno :1, // - return file descriptor from filehandle
  flock :1, // - lock an entire file with an advisory lock
  fork :1, // - create a new process just like this one
  format :1, // - declare a picture format with use by the write() function
  formline :1, // - internal function used for formats
  getc :1, // - get the next character from the filehandle
  getgrent :1, // - get next group record
  getgrgid :1, // - get group record given group user ID
  getgrnam :1, // - get group record given group name
  gethostbyaddr :1, // - get host record given its address
  gethostbyname :1, // - get host record given name
  gethostent :1, // - get next hosts record
  getlogin :1, // - return who logged in at this tty
  getnetbyaddr :1, // - get network record given its address
  getnetbyname :1, // - get networks record given name
  getnetent :1, // - get next networks record
  getpeername :1, // - find the other end of a socket connection
  getpgrp :1, // - get process group
  getppid :1, // - get parent process ID
  getpriority :1, // - get current nice value
  getprotobyname :1, // - get protocol record given name
  getprotobynumber :1, // - get protocol record numeric protocol
  getprotoent :1, // - get next protocols record
  getpwent :1, // - get next passwd record
  getpwnam :1, // - get passwd record given user login name
  getpwuid :1, // - get passwd record given user ID
  getservbyname :1, // - get services record given its name
  getservbyport :1, // - get services record given numeric port
  getservent :1, // - get next services record
  getsockname :1, // - retrieve the sockaddr for a given socket
  getsockopt :1, // - get socket options on a given socket
  given :1, //
  glob :1, // - expand filenames using wildcards
  gmtime :1, // - convert UNIX time into record or string using Greenwich time
  'goto' :1, // - create spaghetti code
  grep :1, // - locate elements in a list test true against a given criterion
  hex :1, // - convert a string to a hexadecimal number
  'import' :1, // - patch a module's namespace into your own
  index :1, // - find a substring within a string
  int :1, // - get the integer portion of a number
  ioctl :1, // - system-dependent device control system call
  'join' :1, // - join a list into a string using a separator
  keys :1, // - retrieve list of indices from a hash
  kill :1, // - send a signal to a process or process group
  last :1, // - exit a block prematurely
  lc :1, // - return lower-case version of a string
  lcfirst :1, // - return a string with just the next letter in lower case
  length :1, // - return the number of bytes in a string
  'link' :1, // - create a hard link in the filesytem
  listen :1, // - register your socket as a server
  local : 2, // - create a temporary value for a global variable (dynamic scoping)
  localtime :1, // - convert UNIX time into record or string using local time
  lock :1, // - get a thread lock on a variable, subroutine, or method
  'log' :1, // - retrieve the natural logarithm for a number
  lstat :1, // - stat a symbolic link
  m :null, // - match a string with a regular expression pattern
  map :1, // - apply a change to a list to get back a new list with the changes
  mkdir :1, // - create a directory
  msgctl :1, // - SysV IPC message control operations
  msgget :1, // - get SysV IPC message queue
  msgrcv :1, // - receive a SysV IPC message from a message queue
  msgsnd :1, // - send a SysV IPC message to a message queue
  my : 2, // - declare and assign a local variable (lexical scoping)
  'new' :1, //
  next :1, // - iterate a block prematurely
  no :1, // - unimport some module symbols or semantics at compile time
  oct :1, // - convert a string to an octal number
  open :1, // - open a file, pipe, or descriptor
  opendir :1, // - open a directory
  ord :1, // - find a character's numeric representation
  our : 2, // - declare and assign a package variable (lexical scoping)
  pack :1, // - convert a list into a binary representation
  'package' :1, // - declare a separate global namespace
  pipe :1, // - open a pair of connected filehandles
  pop :1, // - remove the last element from an array and return it
  pos :1, // - find or set the offset for the last/next m//g search
  print :1, // - output a list to a filehandle
  printf :1, // - output a formatted list to a filehandle
  prototype :1, // - get the prototype (if any) of a subroutine
  push :1, // - append one or more elements to an array
  q :null, // - singly quote a string
  qq :null, // - doubly quote a string
  qr :null, // - Compile pattern
  quotemeta :null, // - quote regular expression magic characters
  qw :null, // - quote a list of words
  qx :null, // - backquote quote a string
  rand :1, // - retrieve the next pseudorandom number
  read :1, // - fixed-length buffered input from a filehandle
  readdir :1, // - get a directory from a directory handle
  readline :1, // - fetch a record from a file
  readlink :1, // - determine where a symbolic link is pointing
  readpipe :1, // - execute a system command and collect standard output
  recv :1, // - receive a message over a Socket
  redo :1, // - start this loop iteration over again
  ref :1, // - find out the type of thing being referenced
  rename :1, // - change a filename
  require :1, // - load in external functions from a library at runtime
  reset :1, // - clear all variables of a given name
  'return' :1, // - get out of a function early
  reverse :1, // - flip a string or a list
  rewinddir :1, // - reset directory handle
  rindex :1, // - right-to-left substring search
  rmdir :1, // - remove a directory
  s :null, // - replace a pattern with a string
  say :1, // - print with newline
  scalar :1, // - force a scalar context
  seek :1, // - reposition file pointer for random-access I/O
  seekdir :1, // - reposition directory pointer
  select :1, // - reset default output or do I/O multiplexing
  semctl :1, // - SysV semaphore control operations
  semget :1, // - get set of SysV semaphores
  semop :1, // - SysV semaphore operations
  send :1, // - send a message over a socket
  setgrent :1, // - prepare group file for use
  sethostent :1, // - prepare hosts file for use
  setnetent :1, // - prepare networks file for use
  setpgrp :1, // - set the process group of a process
  setpriority :1, // - set a process's nice value
  setprotoent :1, // - prepare protocols file for use
  setpwent :1, // - prepare passwd file for use
  setservent :1, // - prepare services file for use
  setsockopt :1, // - set some socket options
  shift :1, // - remove the first element of an array, and return it
  shmctl :1, // - SysV shared memory operations
  shmget :1, // - get SysV shared memory segment identifier
  shmread :1, // - read SysV shared memory
  shmwrite :1, // - write SysV shared memory
  shutdown :1, // - close down just half of a socket connection
  'sin' :1, // - return the sine of a number
  sleep :1, // - block for some number of seconds
  socket :1, // - create a socket
  socketpair :1, // - create a pair of sockets
  'sort' :1, // - sort a list of values
  splice :1, // - add or remove elements anywhere in an array
  'split' :1, // - split up a string using a regexp delimiter
  sprintf :1, // - formatted print into a string
  'sqrt' :1, // - square root function
  srand :1, // - seed the random number generator
  stat :1, // - get a file's status information
  state :1, // - declare and assign a state variable (persistent lexical scoping)
  study :1, // - optimize input data for repeated searches
  'sub' :1, // - declare a subroutine, possibly anonymously
  'substr' :1, // - get or alter a portion of a stirng
  symlink :1, // - create a symbolic link to a file
  syscall :1, // - execute an arbitrary system call
  sysopen :1, // - open a file, pipe, or descriptor
  sysread :1, // - fixed-length unbuffered input from a filehandle
  sysseek :1, // - position I/O pointer on handle used with sysread and syswrite
  system :1, // - run a separate program
  syswrite :1, // - fixed-length unbuffered output to a filehandle
  tell :1, // - get current seekpointer on a filehandle
  telldir :1, // - get current seekpointer on a directory handle
  tie :1, // - bind a variable to an object class
  tied :1, // - get a reference to the object underlying a tied variable
  time :1, // - return number of seconds since 1970
  times :1, // - return elapsed time for self and child processes
  tr :null, // - transliterate a string
  truncate :1, // - shorten a file
  uc :1, // - return upper-case version of a string
  ucfirst :1, // - return a string with just the next letter in upper case
  umask :1, // - set file creation mode mask
  undef :1, // - remove a variable or function definition
  unlink :1, // - remove one link to a file
  unpack :1, // - convert binary structure into normal perl variables
  unshift :1, // - prepend more elements to the beginning of a list
  untie :1, // - break a tie binding to a variable
  use :1, // - load in a module at compile time
  utime :1, // - set a file's last access and modify times
  values :1, // - return a list of the values in a hash
  vec :1, // - test or set particular bits in a string
  wait :1, // - wait for any child process to die
  waitpid :1, // - wait for a particular child process to die
  wantarray :1, // - get void vs scalar vs list context of current subroutine call
  warn :1, // - print debugging info
  when :1, //
  write :1, // - print a picture record
  y :null}; // - transliterate a string
 
  var RXstyle="string-2";
  var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
 
  function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
  state.chain=null; // 12 3tail
  state.style=null;
  state.tail=null;
  state.tokenize=function(stream,state){
  var e=false,c,i=0;
  while(c=stream.next()){
  if(c===chain[i]&&!e){
  if(chain[++i]!==undefined){
  state.chain=chain[i];
  state.style=style;
  state.tail=tail}
  else if(tail)
  stream.eatWhile(tail);
  state.tokenize=tokenPerl;
  return style}
  e=!e&&c=="\\"}
  return style};
  return state.tokenize(stream,state)}
 
  function tokenSOMETHING(stream,state,string){
  state.tokenize=function(stream,state){
  if(stream.string==string)
  state.tokenize=tokenPerl;
  stream.skipToEnd();
  return "string"};
  return state.tokenize(stream,state)}
 
  function tokenPerl(stream,state){
  if(stream.eatSpace())
  return null;
  if(state.chain)
  return tokenChain(stream,state,state.chain,state.style,state.tail);
  if(stream.match(/^\-?[\d\.]/,false))
  if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
  return 'number';
  if(stream.match(/^<<(?=\w)/)){ // NOTE: <<SOMETHING\n...\nSOMETHING\n
  stream.eatWhile(/\w/);
  return tokenSOMETHING(stream,state,stream.current().substr(2))}
  if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n
  return tokenSOMETHING(stream,state,'=cut')}
  var ch=stream.next();
  if(ch=='"'||ch=="'"){ // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
  if(stream.prefix(3)=="<<"+ch){
  var p=stream.pos;
  stream.eatWhile(/\w/);
  var n=stream.current().substr(1);
  if(n&&stream.eat(ch))
  return tokenSOMETHING(stream,state,n);
  stream.pos=p}
  return tokenChain(stream,state,[ch],"string")}
  if(ch=="q"){
  var c=stream.look(-2);
  if(!(c&&/\w/.test(c))){
  c=stream.look(0);
  if(c=="x"){
  c=stream.look(1);
  if(c=="("){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)}
  if(c=="["){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)}
  if(c=="{"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)}
  if(c=="<"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}
  if(/[\^'"!~\/]/.test(c)){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}}
  else if(c=="q"){
  c=stream.look(1);
  if(c=="("){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[")"],"string")}
  if(c=="["){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["]"],"string")}
  if(c=="{"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["}"],"string")}
  if(c=="<"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[">"],"string")}
  if(/[\^'"!~\/]/.test(c)){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[stream.eat(c)],"string")}}
  else if(c=="w"){
  c=stream.look(1);
  if(c=="("){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[")"],"bracket")}
  if(c=="["){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["]"],"bracket")}
  if(c=="{"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["}"],"bracket")}
  if(c=="<"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[">"],"bracket")}
  if(/[\^'"!~\/]/.test(c)){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[stream.eat(c)],"bracket")}}
  else if(c=="r"){
  c=stream.look(1);
  if(c=="("){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)}
  if(c=="["){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)}
  if(c=="{"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)}
  if(c=="<"){
  stream.eatSuffix(2);
  return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}
  if(/[\^'"!~\/]/.test(c)){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}}
  else if(/[\^'"!~\/(\[{<]/.test(c)){
  if(c=="("){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[")"],"string")}
  if(c=="["){
  stream.eatSuffix(1);
  return tokenChain(stream,state,["]"],"string")}
  if(c=="{"){
  stream.eatSuffix(1);
  return tokenChain(stream,state,["}"],"string")}
  if(c=="<"){
  stream.eatSuffix(1);
  return tokenChain(stream,state,[">"],"string")}
  if(/[\^'"!~\/]/.test(c)){
  return tokenChain(stream,state,[stream.eat(c)],"string")}}}}
  if(ch=="m"){
  var c=stream.look(-2);
  if(!(c&&/\w/.test(c))){
  c=stream.eat(/[(\[{<\^'"!~\/]/);
  if(c){
  if(/[\^'"!~\/]/.test(c)){
  return tokenChain(stream,state,[c],RXstyle,RXmodifiers)}
  if(c=="("){
  return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)}
  if(c=="["){
  return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)}
  if(c=="{"){
  return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)}
  if(c=="<"){
  return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}}}}
  if(ch=="s"){
  var c=/[\/>\]})\w]/.test(stream.look(-2));
  if(!c){
  c=stream.eat(/[(\[{<\^'"!~\/]/);
  if(c){
  if(c=="[")
  return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
  if(c=="{")
  return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
  if(c=="<")
  return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
  if(c=="(")
  return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
  return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}
  if(ch=="y"){
  var c=/[\/>\]})\w]/.test(stream.look(-2));
  if(!c){
  c=stream.eat(/[(\[{<\^'"!~\/]/);
  if(c){
  if(c=="[")
  return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
  if(c=="{")
  return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
  if(c=="<")
  return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
  if(c=="(")
  return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
  return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}
  if(ch=="t"){
  var c=/[\/>\]})\w]/.test(stream.look(-2));
  if(!c){
  c=stream.eat("r");if(c){
  c=stream.eat(/[(\[{<\^'"!~\/]/);
  if(c){
  if(c=="[")
  return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
  if(c=="{")
  return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
  if(c=="<")
  return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
  if(c=="(")
  return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
  return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}}
  if(ch=="`"){
  return tokenChain(stream,state,[ch],"variable-2")}
  if(ch=="/"){
  if(!/~\s*$/.test(stream.prefix()))
  return "operator";
  else
  return tokenChain(stream,state,[ch],RXstyle,RXmodifiers)}
  if(ch=="$"){
  var p=stream.pos;
  if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
  return "variable-2";
  else
  stream.pos=p}
  if(/[$@%]/.test(ch)){
  var p=stream.pos;
  if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
  var c=stream.current();
  if(PERL[c])
  return "variable-2"}
  stream.pos=p}
  if(/[$@%&]/.test(ch)){
  if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
  var c=stream.current();
  if(PERL[c])
  return "variable-2";
  else
  return "variable"}}
  if(ch=="#"){
  if(stream.look(-2)!="$"){
  stream.skipToEnd();
  return "comment"}}
  if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
  var p=stream.pos;
  stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
  if(PERL[stream.current()])
  return "operator";
  else
  stream.pos=p}
  if(ch=="_"){
  if(stream.pos==1){
  if(stream.suffix(6)=="_END__"){
  return tokenChain(stream,state,['\0'],"comment")}
  else if(stream.suffix(7)=="_DATA__"){
  return tokenChain(stream,state,['\0'],"variable-2")}
  else if(stream.suffix(7)=="_C__"){
  return tokenChain(stream,state,['\0'],"string")}}}
  if(/\w/.test(ch)){
  var p=stream.pos;
  if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}"))
  return "string";
  else
  stream.pos=p}
  if(/[A-Z]/.test(ch)){
  var l=stream.look(-2);
  var p=stream.pos;
  stream.eatWhile(/[A-Z_]/);
  if(/[\da-z]/.test(stream.look(0))){
  stream.pos=p}
  else{
  var c=PERL[stream.current()];
  if(!c)
  return "meta";
  if(c[1])
  c=c[0];
  if(l!=":"){
  if(c==1)
  return "keyword";
  else if(c==2)
  return "def";
  else if(c==3)
  return "atom";
  else if(c==4)
  return "operator";
  else if(c==5)
  return "variable-2";
  else
  return "meta"}
  else
  return "meta"}}
  if(/[a-zA-Z_]/.test(ch)){
  var l=stream.look(-2);
  stream.eatWhile(/\w/);
  var c=PERL[stream.current()];
  if(!c)
  return "meta";
  if(c[1])
  c=c[0];
  if(l!=":"){
  if(c==1)
  return "keyword";
  else if(c==2)
  return "def";
  else if(c==3)
  return "atom";
  else if(c==4)
  return "operator";
  else if(c==5)
  return "variable-2";
  else
  return "meta"}
  else
  return "meta"}
  return null}
 
  return{
  startState:function(){
  return{
  tokenize:tokenPerl,
  chain:null,
  style:null,
  tail:null}},
  token:function(stream,state){
  return (state.tokenize||tokenPerl)(stream,state)},
  electricChars:"{}"}});
 
  CodeMirror.defineMIME("text/x-perl", "perl");
 
  // it's like "peek", but need for look-ahead or look-behind if index < 0
  CodeMirror.StringStream.prototype.look=function(c){
  return this.string.charAt(this.pos+(c||0))};
 
  // return a part of prefix of current stream from current position
  CodeMirror.StringStream.prototype.prefix=function(c){
  if(c){
  var x=this.pos-c;
  return this.string.substr((x>=0?x:0),c)}
  else{
  return this.string.substr(0,this.pos-1)}};
 
  // return a part of suffix of current stream from current position
  CodeMirror.StringStream.prototype.suffix=function(c){
  var y=this.string.length;
  var x=y-this.pos+1;
  return this.string.substr(this.pos,(c&&c<y?c:x))};
 
  // return a part of suffix of current stream from current position and change current position
  CodeMirror.StringStream.prototype.nsuffix=function(c){
  var p=this.pos;
  var l=c||(this.string.length-this.pos+1);
  this.pos+=l;
  return this.string.substr(p,l)};
 
  // eating and vomiting a part of stream from current position
  CodeMirror.StringStream.prototype.eatSuffix=function(c){
  var x=this.pos+c;
  var y;
  if(x<=0)
  this.pos=0;
  else if(x>=(y=this.string.length-1))
  this.pos=y;
  else
  this.pos=x};
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: PHP mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="../xml/xml.js"></script>
  <script src="../javascript/javascript.js"></script>
  <script src="../css/css.js"></script>
  <script src="../clike/clike.js"></script>
  <script src="php.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: PHP mode</h1>
 
  <form><textarea id="code" name="code">
  <?php
  function hello($who) {
  return "Hello " . $who;
  }
  ?>
  <p>The program says <?= hello("World") ?>.</p>
  <script>
  alert("And here is some JS code"); // also colored
  </script>
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "application/x-httpd-php",
  indentUnit: 4,
  indentWithTabs: true,
  enterMode: "keep",
  tabMode: "shift"
  });
  </script>
 
  <p>Simple HTML/PHP mode based on
  the <a href="../clike/">C-like</a> mode. Depends on XML,
  JavaScript, CSS, and C-like modes.</p>
 
  <p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>
  </body>
  </html>
 
  (function() {
  function keywords(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
  function heredoc(delim) {
  return function(stream, state) {
  if (stream.match(delim)) state.tokenize = null;
  else stream.skipToEnd();
  return "string";
  }
  }
  var phpConfig = {
  name: "clike",
  keywords: keywords("abstract and array as break case catch cfunction class clone const continue declare " +
  "default do else elseif enddeclare endfor endforeach endif endswitch endwhile extends " +
  "final for foreach function global goto if implements interface instanceof namespace " +
  "new or private protected public static switch throw try use var while xor return" +
  "die echo empty exit eval include include_once isset list require require_once print unset"),
  blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
  atoms: keywords("true false null TRUE FALSE NULL"),
  multiLineStrings: true,
  hooks: {
  "$": function(stream, state) {
  stream.eatWhile(/[\w\$_]/);
  return "variable-2";
  },
  "<": function(stream, state) {
  if (stream.match(/<</)) {
  stream.eatWhile(/[\w\.]/);
  state.tokenize = heredoc(stream.current().slice(3));
  return state.tokenize(stream, state);
  }
  return false;
  },
  "#": function(stream, state) {
  stream.skipToEnd();
  return "comment";
  }
  }
  };
 
  CodeMirror.defineMode("php", function(config, parserConfig) {
  var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
  var jsMode = CodeMirror.getMode(config, "javascript");
  var cssMode = CodeMirror.getMode(config, "css");
  var phpMode = CodeMirror.getMode(config, phpConfig);
 
  function dispatch(stream, state) { // TODO open PHP inside text/css
  if (state.curMode == htmlMode) {
  var style = htmlMode.token(stream, state.curState);
  if (style == "meta" && /^<\?/.test(stream.current())) {
  state.curMode = phpMode;
  state.curState = state.php;
  state.curClose = /^\?>/;
  state.mode = 'php';
  }
  else if (style == "tag" && stream.current() == ">" && state.curState.context) {
  if (/^script$/i.test(state.curState.context.tagName)) {
  state.curMode = jsMode;
  state.curState = jsMode.startState(htmlMode.indent(state.curState, ""));
  state.curClose = /^<\/\s*script\s*>/i;
  state.mode = 'javascript';
  }
  else if (/^style$/i.test(state.curState.context.tagName)) {
  state.curMode = cssMode;
  state.curState = cssMode.startState(htmlMode.indent(state.curState, ""));
  state.curClose = /^<\/\s*style\s*>/i;
  state.mode = 'css';
  }
  }
  return style;
  }
  else if (stream.match(state.curClose, false)) {
  state.curMode = htmlMode;
  state.curState = state.html;
  state.curClose = null;
  state.mode = 'html';
  return dispatch(stream, state);
  }
  else return state.curMode.token(stream, state.curState);
  }
 
  return {
  startState: function() {
  var html = htmlMode.startState();
  return {html: html,
  php: phpMode.startState(),
  curMode: parserConfig.startOpen ? phpMode : htmlMode,
  curState: parserConfig.startOpen ? phpMode.startState() : html,
  curClose: parserConfig.startOpen ? /^\?>/ : null,
  mode: parserConfig.startOpen ? 'php' : 'html'}
  },
 
  copyState: function(state) {
  var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
  php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
  if (state.curState == html) cur = htmlNew;
  else if (state.curState == php) cur = phpNew;
  else cur = CodeMirror.copyState(state.curMode, state.curState);
  return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, curClose: state.curClose};
  },
 
  token: dispatch,
 
  indent: function(state, textAfter) {
  if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
  (state.curMode == phpMode && /^\?>/.test(textAfter)))
  return htmlMode.indent(state.html, textAfter);
  return state.curMode.indent(state.curState, textAfter);
  },
 
  electricChars: "/{}:"
  }
  });
  CodeMirror.defineMIME("application/x-httpd-php", "php");
  CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
  CodeMirror.defineMIME("text/x-php", phpConfig);
  })();
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Oracle PL/SQL mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="plsql.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style>.CodeMirror {border: 2px inset #dee;}</style>
  </head>
  <body>
  <h1>CodeMirror: Oracle PL/SQL mode</h1>
 
  <form><textarea id="code" name="code">
  -- Oracle PL/SQL Code Demo
  /*
  based on c-like mode, adapted to PL/SQL by Peter Raganitsch ( http://www.oracle-and-apex.com/ )
  April 2011
  */
  DECLARE
  vIdx NUMBER;
  vString VARCHAR2(100);
  cText CONSTANT VARCHAR2(100) := 'That''s it! Have fun with CodeMirror 2';
  BEGIN
  vIdx := 0;
  --
  FOR rDATA IN
  ( SELECT *
  FROM EMP
  ORDER BY EMPNO
  )
  LOOP
  vIdx := vIdx + 1;
  vString := rDATA.EMPNO || ' - ' || rDATA.ENAME;
  --
  UPDATE EMP
  SET SAL = SAL * 101/100
  WHERE EMPNO = rDATA.EMPNO
  ;
  END LOOP;
  --
  SYS.DBMS_OUTPUT.Put_Line (cText);
  END;
  --
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  indentUnit: 4,
  mode: "text/x-plsql"
  });
  </script>
 
  <p>
  Simple mode that handles Oracle PL/SQL language (and Oracle SQL, of course).
  </p>
 
  <p><strong>MIME type defined:</strong> <code>text/x-plsql</code>
  (PLSQL code)
  </html>
 
  CodeMirror.defineMode("plsql", function(config, parserConfig) {
  var indentUnit = config.indentUnit,
  keywords = parserConfig.keywords,
  functions = parserConfig.functions,
  types = parserConfig.types,
  sqlplus = parserConfig.sqlplus,
  multiLineStrings = parserConfig.multiLineStrings;
  var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
  function chain(stream, state, f) {
  state.tokenize = f;
  return f(stream, state);
  }
 
  var type;
  function ret(tp, style) {
  type = tp;
  return style;
  }
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  // start of string?
  if (ch == '"' || ch == "'")
  return chain(stream, state, tokenString(ch));
  // is it one of the special signs []{}().,;? Seperator?
  else if (/[\[\]{}\(\),;\.]/.test(ch))
  return ret(ch);
  // start of a number value?
  else if (/\d/.test(ch)) {
  stream.eatWhile(/[\w\.]/);
  return ret("number", "number");
  }
  // multi line comment or simple operator?
  else if (ch == "/") {
  if (stream.eat("*")) {
  return chain(stream, state, tokenComment);
  }
  else {
  stream.eatWhile(isOperatorChar);
  return ret("operator", "operator");
  }
  }
  // single line comment or simple operator?
  else if (ch == "-") {
  if (stream.eat("-")) {
  stream.skipToEnd();
  return ret("comment", "comment");
  }
  else {
  stream.eatWhile(isOperatorChar);
  return ret("operator", "operator");
  }
  }
  // pl/sql variable?
  else if (ch == "@" || ch == "$") {
  stream.eatWhile(/[\w\d\$_]/);
  return ret("word", "variable");
  }
  // is it a operator?
  else if (isOperatorChar.test(ch)) {
  stream.eatWhile(isOperatorChar);
  return ret("operator", "operator");
  }
  else {
  // get the whole word
  stream.eatWhile(/[\w\$_]/);
  // is it one of the listed keywords?
  if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword");
  // is it one of the listed functions?
  if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin");
  // is it one of the listed types?
  if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2");
  // is it one of the listed sqlplus keywords?
  if (sqlplus && sqlplus.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3");
  // default: just a "word"
  return ret("word", "plsql-word");
  }
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  var escaped = false, next, end = false;
  while ((next = stream.next()) != null) {
  if (next == quote && !escaped) {end = true; break;}
  escaped = !escaped && next == "\\";
  }
  if (end || !(escaped || multiLineStrings))
  state.tokenize = tokenBase;
  return ret("string", "plsql-string");
  };
  }
 
  function tokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize = tokenBase;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return ret("comment", "plsql-comment");
  }
 
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: tokenBase,
  startOfLine: true
  };
  },
 
  token: function(stream, state) {
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
  return style;
  }
  };
  });
 
  (function() {
  function keywords(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
  var cKeywords = "abort accept access add all alter and any array arraylen as asc assert assign at attributes audit " +
  "authorization avg " +
  "base_table begin between binary_integer body boolean by " +
  "case cast char char_base check close cluster clusters colauth column comment commit compress connect " +
  "connected constant constraint crash create current currval cursor " +
  "data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete " +
  "desc digits dispose distinct do drop " +
  "else elsif enable end entry escape exception exception_init exchange exclusive exists exit external " +
  "fast fetch file for force form from function " +
  "generic goto grant group " +
  "having " +
  "identified if immediate in increment index indexes indicator initial initrans insert interface intersect " +
  "into is " +
  "key " +
  "level library like limited local lock log logging long loop " +
  "master maxextents maxtrans member minextents minus mislabel mode modify multiset " +
  "new next no noaudit nocompress nologging noparallel not nowait number_base " +
  "object of off offline on online only open option or order out " +
  "package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior " +
  "private privileges procedure public " +
  "raise range raw read rebuild record ref references refresh release rename replace resource restrict return " +
  "returning reverse revoke rollback row rowid rowlabel rownum rows run " +
  "savepoint schema segment select separate session set share snapshot some space split sql start statement " +
  "storage subtype successful synonym " +
  "tabauth table tables tablespace task terminate then to trigger truncate type " +
  "union unique unlimited unrecoverable unusable update use using " +
  "validate value values variable view views " +
  "when whenever where while with work";
 
  var cFunctions = "abs acos add_months ascii asin atan atan2 average " +
  "bfilename " +
  "ceil chartorowid chr concat convert cos cosh count " +
  "decode deref dual dump dup_val_on_index " +
  "empty error exp " +
  "false floor found " +
  "glb greatest " +
  "hextoraw " +
  "initcap instr instrb isopen " +
  "last_day least lenght lenghtb ln lower lpad ltrim lub " +
  "make_ref max min mod months_between " +
  "new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower " +
  "nls_sort nls_upper nlssort no_data_found notfound null nvl " +
  "others " +
  "power " +
  "rawtohex reftohex round rowcount rowidtochar rpad rtrim " +
  "sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate " +
  "tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc " +
  "uid upper user userenv " +
  "variance vsize";
 
  var cTypes = "bfile blob " +
  "character clob " +
  "dec " +
  "float " +
  "int integer " +
  "mlslabel " +
  "natural naturaln nchar nclob number numeric nvarchar2 " +
  "real rowtype " +
  "signtype smallint string " +
  "varchar varchar2";
 
  var cSqlplus = "appinfo arraysize autocommit autoprint autorecovery autotrace " +
  "blockterminator break btitle " +
  "cmdsep colsep compatibility compute concat copycommit copytypecheck " +
  "define describe " +
  "echo editfile embedded escape exec execute " +
  "feedback flagger flush " +
  "heading headsep " +
  "instance " +
  "linesize lno loboffset logsource long longchunksize " +
  "markup " +
  "native newpage numformat numwidth " +
  "pagesize pause pno " +
  "recsep recsepchar release repfooter repheader " +
  "serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber " +
  "sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix " +
  "tab term termout time timing trimout trimspool ttitle " +
  "underline " +
  "verify version " +
  "wrap";
 
  CodeMirror.defineMIME("text/x-plsql", {
  name: "plsql",
  keywords: keywords(cKeywords),
  functions: keywords(cFunctions),
  types: keywords(cTypes),
  sqlplus: keywords(cSqlplus)
  });
  }());
 
  The MIT License
 
  Copyright (c) 2010 Timothy Farrell
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Python mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="python.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: Python mode</h1>
 
  <div><textarea id="code" name="code">
  # Literals
  1234
  0.0e101
  .123
  0b01010011100
  0o01234567
  0x0987654321abcdef
  7
  2147483647
  3L
  79228162514264337593543950336L
  0x100000000L
  79228162514264337593543950336
  0xdeadbeef
  3.14j
  10.j
  10j
  .001j
  1e100j
  3.14e-10j
 
 
  # String Literals
  'For\''
  "God\""
  """so loved
  the world"""
  '''that he gave
  his only begotten\' '''
  'that whosoever believeth \
  in him'
  ''
 
  # Identifiers
  __a__
  a.b
  a.b.c
 
  # Operators
  + - * / % & | ^ ~ < >
  == != <= >= <> << >> // **
  and or not in is
 
  # Delimiters
  () [] {} , : ` = ; @ . # Note that @ and . require the proper context.
  += -= *= /= %= &= |= ^=
  //= >>= <<= **=
 
  # Keywords
  as assert break class continue def del elif else except
  finally for from global if import lambda pass raise
  return try while with yield
 
  # Python 2 Keywords (otherwise Identifiers)
  exec print
 
  # Python 3 Keywords (otherwise Identifiers)
  nonlocal
 
  # Types
  bool classmethod complex dict enumerate float frozenset int list object
  property reversed set slice staticmethod str super tuple type
 
  # Python 2 Types (otherwise Identifiers)
  basestring buffer file long unicode xrange
 
  # Python 3 Types (otherwise Identifiers)
  bytearray bytes filter map memoryview open range zip
 
  # Some Example code
  import os
  from package import ParentClass
 
  @nonsenseDecorator
  def doesNothing():
  pass
 
  class ExampleClass(ParentClass):
  @staticmethod
  def example(inputStr):
  a = list(inputStr)
  a.reverse()
  return ''.join(a)
 
  def __init__(self, mixin = 'Hello'):
  self.mixin = mixin
 
  </textarea></div>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: {name: "python",
  version: 2,
  singleLineStringErrors: false},
  lineNumbers: true,
  indentUnit: 4,
  tabMode: "shift",
  matchBrackets: true
  });
  </script>
  <h2>Configuration Options:</h2>
  <ul>
  <li>version - 2/3 - The version of Python to recognize. Default is 2.</li>
  <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
  </ul>
 
  <p><strong>MIME types defined:</strong> <code>text/x-python</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("python", function(conf, parserConf) {
  var ERRORCLASS = 'error';
 
  function wordRegexp(words) {
  return new RegExp("^((" + words.join(")|(") + "))\\b");
  }
 
  var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
  var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
  var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
  var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
  var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
  var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
 
  var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
  var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
  'def', 'del', 'elif', 'else', 'except', 'finally',
  'for', 'from', 'global', 'if', 'import',
  'lambda', 'pass', 'raise', 'return',
  'try', 'while', 'with', 'yield'];
  var commontypes = ['bool', 'classmethod', 'complex', 'dict', 'enumerate',
  'float', 'frozenset', 'int', 'list', 'object',
  'property', 'reversed', 'set', 'slice', 'staticmethod',
  'str', 'super', 'tuple', 'type'];
  var py2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
  'xrange'],
  'keywords': ['exec', 'print']};
  var py3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
  'open', 'range', 'zip'],
  'keywords': ['nonlocal']};
 
  if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
  commonkeywords = commonkeywords.concat(py3.keywords);
  commontypes = commontypes.concat(py3.types);
  var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
  } else {
  commonkeywords = commonkeywords.concat(py2.keywords);
  commontypes = commontypes.concat(py2.types);
  var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
  }
  var keywords = wordRegexp(commonkeywords);
  var types = wordRegexp(commontypes);
 
  var indentInfo = null;
 
  // tokenizers
  function tokenBase(stream, state) {
  // Handle scope changes
  if (stream.sol()) {
  var scopeOffset = state.scopes[0].offset;
  if (stream.eatSpace()) {
  var lineOffset = stream.indentation();
  if (lineOffset > scopeOffset) {
  indentInfo = 'indent';
  } else if (lineOffset < scopeOffset) {
  indentInfo = 'dedent';
  }
  return null;
  } else {
  if (scopeOffset > 0) {
  dedent(stream, state);
  }
  }
  }
  if (stream.eatSpace()) {
  return null;
  }
 
  var ch = stream.peek();
 
  // Handle Comments
  if (ch === '#') {
  stream.skipToEnd();
  return 'comment';
  }
 
  // Handle Number Literals
  if (stream.match(/^[0-9\.]/, false)) {
  var floatLiteral = false;
  // Floats
  if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
  if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
  if (stream.match(/^\.\d+/)) { floatLiteral = true; }
  if (floatLiteral) {
  // Float literals may be "imaginary"
  stream.eat(/J/i);
  return 'number';
  }
  // Integers
  var intLiteral = false;
  // Hex
  if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
  // Binary
  if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
  // Octal
  if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
  // Decimal
  if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
  // Decimal literals may be "imaginary"
  stream.eat(/J/i);
  // TODO - Can you have imaginary longs?
  intLiteral = true;
  }
  // Zero by itself with no other piece of number.
  if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
  if (intLiteral) {
  // Integer literals may be "long"
  stream.eat(/L/i);
  return 'number';
  }
  }
 
  // Handle Strings
  if (stream.match(stringPrefixes)) {
  state.tokenize = tokenStringFactory(stream.current());
  return state.tokenize(stream, state);
  }
 
  // Handle operators and Delimiters
  if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
  return null;
  }
  if (stream.match(doubleOperators)
  || stream.match(singleOperators)
  || stream.match(wordOperators)) {
  return 'operator';
  }
  if (stream.match(singleDelimiters)) {
  return null;
  }
 
  if (stream.match(types)) {
  return 'builtin';
  }
 
  if (stream.match(keywords)) {
  return 'keyword';
  }
 
  if (stream.match(identifiers)) {
  return 'variable';
  }
 
  // Handle non-detected items
  stream.next();
  return ERRORCLASS;
  }
 
  function tokenStringFactory(delimiter) {
  while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
  delimiter = delimiter.substr(1);
  }
  var singleline = delimiter.length == 1;
  var OUTCLASS = 'string';
 
  return function tokenString(stream, state) {
  while (!stream.eol()) {
  stream.eatWhile(/[^'"\\]/);
  if (stream.eat('\\')) {
  stream.next();
  if (singleline && stream.eol()) {
  return OUTCLASS;
  }
  } else if (stream.match(delimiter)) {
  state.tokenize = tokenBase;
  return OUTCLASS;
  } else {
  stream.eat(/['"]/);
  }
  }
  if (singleline) {
  if (parserConf.singleLineStringErrors) {
  return ERRORCLASS;
  } else {
  state.tokenize = tokenBase;
  }
  }
  return OUTCLASS;
  };
  }
 
  function indent(stream, state, type) {
  type = type || 'py';
  var indentUnit = 0;
  if (type === 'py') {
  if (state.scopes[0].type !== 'py') {
  state.scopes[0].offset = stream.indentation();
  return;
  }
  for (var i = 0; i < state.scopes.length; ++i) {
  if (state.scopes[i].type === 'py') {
  indentUnit = state.scopes[i].offset + conf.indentUnit;
  break;
  }
  }
  } else {
  indentUnit = stream.column() + stream.current().length;
  }
  state.scopes.unshift({
  offset: indentUnit,
  type: type
  });
  }
 
  function dedent(stream, state, type) {
  type = type || 'py';
  if (state.scopes.length == 1) return;
  if (state.scopes[0].type === 'py') {
  var _indent = stream.indentation();
  var _indent_index = -1;
  for (var i = 0; i < state.scopes.length; ++i) {
  if (_indent === state.scopes[i].offset) {
  _indent_index = i;
  break;
  }
  }
  if (_indent_index === -1) {
  return true;
  }
  while (state.scopes[0].offset !== _indent) {
  state.scopes.shift();
  }
  return false
  } else {
  if (type === 'py') {
  state.scopes[0].offset = stream.indentation();
  return false;
  } else {
  if (state.scopes[0].type != type) {
  return true;
  }
  state.scopes.shift();
  return false;
  }
  }
  }
 
  function tokenLexer(stream, state) {
  indentInfo = null;
  var style = state.tokenize(stream, state);
  var current = stream.current();
 
  // Handle '.' connected identifiers
  if (current === '.') {
  style = state.tokenize(stream, state);
  current = stream.current();
  if (style === 'variable') {
  return 'variable';
  } else {
  return ERRORCLASS;
  }
  }
 
  // Handle decorators
  if (current === '@') {
  style = state.tokenize(stream, state);
  current = stream.current();
  if (style === 'variable'
  || current === '@staticmethod'
  || current === '@classmethod') {
  return 'meta';
  } else {
  return ERRORCLASS;
  }
  }
 
  // Handle scope changes.
  if (current === 'pass' || current === 'return') {
  state.dedent += 1;
  }
  if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
  || indentInfo === 'indent') {
  indent(stream, state);
  }
  var delimiter_index = '[({'.indexOf(current);
  if (delimiter_index !== -1) {
  indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
  }
  if (indentInfo === 'dedent') {
  if (dedent(stream, state)) {
  return ERRORCLASS;
  }
  }
  delimiter_index = '])}'.indexOf(current);
  if (delimiter_index !== -1) {
  if (dedent(stream, state, current)) {
  return ERRORCLASS;
  }
  }
  if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
  if (state.scopes.length > 1) state.scopes.shift();
  state.dedent -= 1;
  }
 
  return style;
  }
 
  var external = {
  startState: function(basecolumn) {
  return {
  tokenize: tokenBase,
  scopes: [{offset:basecolumn || 0, type:'py'}],
  lastToken: null,
  lambda: false,
  dedent: 0
  };
  },
 
  token: function(stream, state) {
  var style = tokenLexer(stream, state);
 
  state.lastToken = {style:style, content: stream.current()};
 
  if (stream.eol() && stream.lambda) {
  state.lambda = false;
  }
 
  return style;
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != tokenBase) {
  return 0;
  }
 
  return state.scopes[0].offset;
  }
 
  };
  return external;
  });
 
  CodeMirror.defineMIME("text/x-python", "python");
 
  Copyright (c) 2011, Ubalo, Inc.
  All rights reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
  * Neither the name of the Ubalo, Inc nor the names of its
  contributors may be used to endorse or promote products derived
  from this software without specific prior written permission.
 
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: R mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="r.js"></script>
  <style>
  .CodeMirror { border-top: 1px solid silver; border-bottom: 1px solid silver; }
  .cm-s-default span.cm-semi { color: blue; font-weight: bold; }
  .cm-s-default span.cm-dollar { color: orange; font-weight: bold; }
  .cm-s-default span.cm-arrow { color: brown; }
  .cm-s-default span.cm-arg-is { color: brown; }
  </style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: R mode</h1>
  <form><textarea id="code" name="code">
  # Code from http://www.mayin.org/ajayshah/KB/R/
 
  # FIRST LEARN ABOUT LISTS --
  X = list(height=5.4, weight=54)
  print("Use default printing --")
  print(X)
  print("Accessing individual elements --")
  cat("Your height is ", X$height, " and your weight is ", X$weight, "\n")
 
  # FUNCTIONS --
  square <- function(x) {
  return(x*x)
  }
  cat("The square of 3 is ", square(3), "\n")
 
  # default value of the arg is set to 5.
  cube <- function(x=5) {
  return(x*x*x);
  }
  cat("Calling cube with 2 : ", cube(2), "\n") # will give 2^3
  cat("Calling cube : ", cube(), "\n") # will default to 5^3.
 
  # LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
  powers <- function(x) {
  parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
  return(parcel);
  }
 
  X = powers(3);
  print("Showing powers of 3 --"); print(X);
 
  # WRITING THIS COMPACTLY (4 lines instead of 7)
 
  powerful <- function(x) {
  return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
  }
  print("Showing powers of 3 --"); print(powerful(3));
 
  # In R, the last expression in a function is, by default, what is
  # returned. So you could equally just say:
  powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-rsrc</code>.</p>
 
  <p>Development of the CodeMirror R mode was kindly sponsored
  by <a href="http://ubalo.com/">Ubalo</a>, who hold
  the <a href="LICENSE">license</a>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("r", function(config) {
  function wordObj(str) {
  var words = str.split(" "), res = {};
  for (var i = 0; i < words.length; ++i) res[words[i]] = true;
  return res;
  }
  var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
  var builtins = wordObj("list quote bquote eval return call parse deparse");
  var keywords = wordObj("if else repeat while function for in next break");
  var blockkeywords = wordObj("if else repeat while function for");
  var opChars = /[+\-*\/^<>=!&|~$:]/;
  var curPunc;
 
  function tokenBase(stream, state) {
  curPunc = null;
  var ch = stream.next();
  if (ch == "#") {
  stream.skipToEnd();
  return "comment";
  } else if (ch == "0" && stream.eat("x")) {
  stream.eatWhile(/[\da-f]/i);
  return "number";
  } else if (ch == "." && stream.eat(/\d/)) {
  stream.match(/\d*(?:e[+\-]?\d+)?/);
  return "number";
  } else if (/\d/.test(ch)) {
  stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
  return "number";
  } else if (ch == "'" || ch == '"') {
  state.tokenize = tokenString(ch);
  return "string";
  } else if (ch == "." && stream.match(/.[.\d]+/)) {
  return "keyword";
  } else if (/[\w\.]/.test(ch) && ch != "_") {
  stream.eatWhile(/[\w\.]/);
  var word = stream.current();
  if (atoms.propertyIsEnumerable(word)) return "atom";
  if (keywords.propertyIsEnumerable(word)) {
  if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block";
  return "keyword";
  }
  if (builtins.propertyIsEnumerable(word)) return "builtin";
  return "variable";
  } else if (ch == "%") {
  if (stream.skipTo("%")) stream.next();
  return "variable-2";
  } else if (ch == "<" && stream.eat("-")) {
  return "arrow";
  } else if (ch == "=" && state.ctx.argList) {
  return "arg-is";
  } else if (opChars.test(ch)) {
  if (ch == "$") return "dollar";
  stream.eatWhile(opChars);
  return "operator";
  } else if (/[\(\){}\[\];]/.test(ch)) {
  curPunc = ch;
  if (ch == ";") return "semi";
  return null;
  } else {
  return null;
  }
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  if (stream.eat("\\")) {
  var ch = stream.next();
  if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
  else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
  else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
  else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
  else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
  return "string-2";
  } else {
  var next;
  while ((next = stream.next()) != null) {
  if (next == quote) { state.tokenize = tokenBase; break; }
  if (next == "\\") { stream.backUp(1); break; }
  }
  return "string";
  }
  };
  }
 
  function push(state, type, stream) {
  state.ctx = {type: type,
  indent: state.indent,
  align: null,
  column: stream.column(),
  prev: state.ctx};
  }
  function pop(state) {
  state.indent = state.ctx.indent;
  state.ctx = state.ctx.prev;
  }
 
  return {
  startState: function(base) {
  return {tokenize: tokenBase,
  ctx: {type: "top",
  indent: -config.indentUnit,
  align: false},
  indent: 0,
  afterIdent: false};
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  if (state.ctx.align == null) state.ctx.align = false;
  state.indent = stream.indentation();
  }
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
  if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
 
  var ctype = state.ctx.type;
  if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
  if (curPunc == "{") push(state, "}", stream);
  else if (curPunc == "(") {
  push(state, ")", stream);
  if (state.afterIdent) state.ctx.argList = true;
  }
  else if (curPunc == "[") push(state, "]", stream);
  else if (curPunc == "block") push(state, "block", stream);
  else if (curPunc == ctype) pop(state);
  state.afterIdent = style == "variable" || style == "keyword";
  return style;
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != tokenBase) return 0;
  var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
  closing = firstChar == ctx.type;
  if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
  else if (ctx.align) return ctx.column + (closing ? 0 : 1);
  else return ctx.indent + (closing ? 0 : config.indentUnit);
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-rsrc", "r");
 
  CodeMirror.defineMode("changes", function(config, modeConfig) {
  var headerSeperator = /^-+$/;
  var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /;
  var simpleEmail = /^[\w+.-]+@[\w.-]+/;
 
  return {
  token: function(stream) {
  if (stream.sol()) {
  if (stream.match(headerSeperator)) { return 'tag'; }
  if (stream.match(headerLine)) { return 'tag'; }
  }
  if (stream.match(simpleEmail)) { return 'string'; }
  stream.next();
  return null;
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-rpm-changes", "changes");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: RPM changes mode</title>
  <link rel="stylesheet" href="../../../lib/codemirror.css">
  <script src="../../../lib/codemirror.js"></script>
  <script src="changes.js"></script>
  <link rel="stylesheet" href="../../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: RPM changes mode</h1>
 
  <div><textarea id="code" name="code">
  -------------------------------------------------------------------
  Tue Oct 18 13:58:40 UTC 2011 - misterx@example.com
 
  - Update to r60.3
  - Fixes bug in the reflect package
  * disallow Interface method on Value obtained via unexported name
 
  -------------------------------------------------------------------
  Thu Oct 6 08:14:24 UTC 2011 - misterx@example.com
 
  - Update to r60.2
  - Fixes memory leak in certain map types
 
  -------------------------------------------------------------------
  Wed Oct 5 14:34:10 UTC 2011 - misterx@example.com
 
  - Tweaks for gdb debugging
  - go.spec changes:
  - move %go_arch definition to %prep section
  - pass correct location of go specific gdb pretty printer and
  functions to cpp as HOST_EXTRA_CFLAGS macro
  - install go gdb functions & printer
  - gdb-printer.patch
  - patch linker (src/cmd/ld/dwarf.c) to emit correct location of go
  gdb functions and pretty printer
  </textarea></div>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: {name: "changes"},
  lineNumbers: true,
  indentUnit: 4,
  tabMode: "shift",
  matchBrackets: true
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-rpm-changes</code>.</p>
  </body>
  </html>
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: RPM spec mode</title>
  <link rel="stylesheet" href="../../../lib/codemirror.css">
  <script src="../../../lib/codemirror.js"></script>
  <script src="spec.js"></script>
  <link rel="stylesheet" href="spec.css">
  <link rel="stylesheet" href="../../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: RPM spec mode</h1>
 
  <div><textarea id="code" name="code">
  #
  # spec file for package minidlna
  #
  # Copyright (c) 2011, Sascha Peilicke <saschpe@gmx.de>
  #
  # All modifications and additions to the file contributed by third parties
  # remain the property of their copyright owners, unless otherwise agreed
  # upon. The license for this file, and modifications and additions to the
  # file, is the same license as for the pristine package itself (unless the
  # license for the pristine package is not an Open Source License, in which
  # case the license is the MIT License). An "Open Source License" is a
  # license that conforms to the Open Source Definition (Version 1.9)
  # published by the Open Source Initiative.
 
 
  Name: libupnp6
  Version: 1.6.13
  Release: 0
  Summary: Portable Universal Plug and Play (UPnP) SDK
  Group: System/Libraries
  License: BSD-3-Clause
  Url: http://sourceforge.net/projects/pupnp/
  Source0: http://downloads.sourceforge.net/pupnp/libupnp-%{version}.tar.bz2
  BuildRoot: %{_tmppath}/%{name}-%{version}-build
 
  %description
  The portable Universal Plug and Play (UPnP) SDK provides support for building
  UPnP-compliant control points, devices, and bridges on several operating
  systems.
 
  %package -n libupnp-devel
  Summary: Portable Universal Plug and Play (UPnP) SDK
  Group: Development/Libraries/C and C++
  Provides: pkgconfig(libupnp)
  Requires: %{name} = %{version}
 
  %description -n libupnp-devel
  The portable Universal Plug and Play (UPnP) SDK provides support for building
  UPnP-compliant control points, devices, and bridges on several operating
  systems.
 
  %prep
  %setup -n libupnp-%{version}
 
  %build
  %configure --disable-static
  make %{?_smp_mflags}
 
  %install
  %makeinstall
  find %{buildroot} -type f -name '*.la' -exec rm -f {} ';'
 
  %post -p /sbin/ldconfig
 
  %postun -p /sbin/ldconfig
 
  %files
  %defattr(-,root,root,-)
  %doc ChangeLog NEWS README TODO
  %{_libdir}/libixml.so.*
  %{_libdir}/libthreadutil.so.*
  %{_libdir}/libupnp.so.*
 
  %files -n libupnp-devel
  %defattr(-,root,root,-)
  %{_libdir}/pkgconfig/libupnp.pc
  %{_libdir}/libixml.so
  %{_libdir}/libthreadutil.so
  %{_libdir}/libupnp.so
  %{_includedir}/upnp/
 
  %changelog</textarea></div>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: {name: "spec"},
  lineNumbers: true,
  indentUnit: 4,
  matchBrackets: true
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-rpm-spec</code>.</p>
  </body>
  </html>
 
  .cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;}
  .cm-s-default span.cm-macro {color: #b218b2;}
  .cm-s-default span.cm-section {color: green; font-weight: bold;}
  .cm-s-default span.cm-script {color: red;}
  .cm-s-default span.cm-issue {color: yellow;}
 
  // Quick and dirty spec file highlighting
 
  CodeMirror.defineMode("spec", function(config, modeConfig) {
  var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;
 
  var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/;
  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/;
  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
  var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros
 
  return {
  startState: function () {
  return {
  controlFlow: false,
  macroParameters: false,
  section: false,
  };
  },
  token: function (stream, state) {
  var ch = stream.peek();
  if (ch == "#") { stream.skipToEnd(); return "comment"; }
 
  if (stream.sol()) {
  if (stream.match(preamble)) { return "preamble"; }
  if (stream.match(section)) { return "section"; }
  }
 
  if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
  if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'
 
  if (stream.match(control_flow_simple)) { return "keyword"; }
  if (stream.match(control_flow_complex)) {
  state.controlFlow = true;
  return "keyword";
  }
  if (state.controlFlow) {
  if (stream.match(operators)) { return "operator"; }
  if (stream.match(/^(\d+)/)) { return "number"; }
  if (stream.eol()) { state.controlFlow = false; }
  }
 
  if (stream.match(arch)) { return "number"; }
 
  // Macros like '%make_install' or '%attr(0775,root,root)'
  if (stream.match(/^%[\w]+/)) {
  if (stream.match(/^\(/)) { state.macroParameters = true; }
  return "macro";
  }
  if (state.macroParameters) {
  if (stream.match(/^\d+/)) { return "number";}
  if (stream.match(/^\)/)) {
  state.macroParameters = false;
  return "macro";
  }
  }
  if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}'
 
  //TODO: Include bash script sub-parser (CodeMirror supports that)
  stream.next();
  return null;
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-rpm-spec", "spec");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: reStructuredText mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="rst.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: reStructuredText mode</h1>
 
  <form><textarea id="code" name="code">
  .. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt
 
  .. highlightlang:: rest
 
  .. _rst-primer:
 
  reStructuredText Primer
  =======================
 
  This section is a brief introduction to reStructuredText (reST) concepts and
  syntax, intended to provide authors with enough information to author documents
  productively. Since reST was designed to be a simple, unobtrusive markup
  language, this will not take too long.
 
  .. seealso::
 
  The authoritative `reStructuredText User Documentation
  &lt;http://docutils.sourceforge.net/rst.html&gt;`_. The "ref" links in this
  document link to the description of the individual constructs in the reST
  reference.
 
 
  Paragraphs
  ----------
 
  The paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST
  document. Paragraphs are simply chunks of text separated by one or more blank
  lines. As in Python, indentation is significant in reST, so all lines of the
  same paragraph must be left-aligned to the same level of indentation.
 
 
  .. _inlinemarkup:
 
  Inline markup
  -------------
 
  The standard reST inline markup is quite simple: use
 
  * one asterisk: ``*text*`` for emphasis (italics),
  * two asterisks: ``**text**`` for strong emphasis (boldface), and
  * backquotes: ````text```` for code samples.
 
  If asterisks or backquotes appear in running text and could be confused with
  inline markup delimiters, they have to be escaped with a backslash.
 
  Be aware of some restrictions of this markup:
 
  * it may not be nested,
  * content may not start or end with whitespace: ``* text*`` is wrong,
  * it must be separated from surrounding text by non-word characters. Use a
  backslash escaped space to work around that: ``thisis\ *one*\ word``.
 
  These restrictions may be lifted in future versions of the docutils.
 
  reST also allows for custom "interpreted text roles"', which signify that the
  enclosed text should be interpreted in a specific way. Sphinx uses this to
  provide semantic markup and cross-referencing of identifiers, as described in
  the appropriate section. The general syntax is ``:rolename:`content```.
 
  Standard reST provides the following roles:
 
  * :durole:`emphasis` -- alternate spelling for ``*emphasis*``
  * :durole:`strong` -- alternate spelling for ``**strong**``
  * :durole:`literal` -- alternate spelling for ````literal````
  * :durole:`subscript` -- subscript text
  * :durole:`superscript` -- superscript text
  * :durole:`title-reference` -- for titles of books, periodicals, and other
  materials
 
  See :ref:`inline-markup` for roles added by Sphinx.
 
 
  Lists and Quote-like blocks
  ---------------------------
 
  List markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at
  the start of a paragraph and indent properly. The same goes for numbered lists;
  they can also be autonumbered using a ``#`` sign::
 
  * This is a bulleted list.
  * It has two items, the second
  item uses two lines.
 
  1. This is a numbered list.
  2. It has two items too.
 
  #. This is a numbered list.
  #. It has two items too.
 
 
  Nested lists are possible, but be aware that they must be separated from the
  parent list items by blank lines::
 
  * this is
  * a list
 
  * with a nested list
  * and some subitems
 
  * and here the parent list continues
 
  Definition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::
 
  term (up to a line of text)
  Definition of the term, which must be indented
 
  and can even consist of multiple paragraphs
 
  next term
  Description.
 
  Note that the term cannot have more than one line of text.
 
  Quoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting
  them more than the surrounding paragraphs.
 
  Line blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::
 
  | These lines are
  | broken exactly like in
  | the source file.
 
  There are also several more special blocks available:
 
  * field lists (:duref:`ref &lt;field-lists&gt;`)
  * option lists (:duref:`ref &lt;option-lists&gt;`)
  * quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)
  * doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)
 
 
  Source Code
  -----------
 
  Literal code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a
  paragraph with the special marker ``::``. The literal block must be indented
  (and, like all paragraphs, separated from the surrounding ones by blank lines)::
 
  This is a normal text paragraph. The next paragraph is a code sample::
 
  It is not processed in any way, except
  that the indentation is removed.
 
  It can span multiple lines.
 
  This is a normal text paragraph again.
 
  The handling of the ``::`` marker is smart:
 
  * If it occurs as a paragraph of its own, that paragraph is completely left
  out of the document.
  * If it is preceded by whitespace, the marker is removed.
  * If it is preceded by non-whitespace, the marker is replaced by a single
  colon.
 
  That way, the second sentence in the above example's first paragraph would be
  rendered as "The next paragraph is a code sample:".
 
 
  .. _rst-tables:
 
  Tables
  ------
 
  Two forms of tables are supported. For *grid tables* (:duref:`ref
  &lt;grid-tables&gt;`), you have to "paint" the cell grid yourself. They look like
  this::
 
  +------------------------+------------+----------+----------+
  | Header row, column 1 | Header 2 | Header 3 | Header 4 |
  | (header rows optional) | | | |
  +========================+============+==========+==========+
  | body row 1, column 1 | column 2 | column 3 | column 4 |
  +------------------------+------------+----------+----------+
  | body row 2 | ... | ... | |
  +------------------------+------------+----------+----------+
 
  *Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but
  limited: they must contain more than one row, and the first column cannot
  contain multiple lines. They look like this::
 
  ===== ===== =======
  A B A and B
  ===== ===== =======
  False False False
  True False False
  False True False
  True True True
  ===== ===== =======
 
 
  Hyperlinks
  ----------
 
  External links
  ^^^^^^^^^^^^^^
 
  Use ```Link text &lt;http://example.com/&gt;`_`` for inline web links. If the link
  text should be the web address, you don't need special markup at all, the parser
  finds links and mail addresses in ordinary text.
 
  You can also separate the link and the target definition (:duref:`ref
  &lt;hyperlink-targets&gt;`), like this::
 
  This is a paragraph that contains `a link`_.
 
  .. _a link: http://example.com/
 
 
  Internal links
  ^^^^^^^^^^^^^^
 
  Internal linking is done via a special reST role provided by Sphinx, see the
  section on specific markup, :ref:`ref-role`.
 
 
  Sections
  --------
 
  Section headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and
  optionally overlining) the section title with a punctuation character, at least
  as long as the text::
 
  =================
  This is a heading
  =================
 
  Normally, there are no heading levels assigned to certain characters as the
  structure is determined from the succession of headings. However, for the
  Python documentation, this convention is used which you may follow:
 
  * ``#`` with overline, for parts
  * ``*`` with overline, for chapters
  * ``=``, for sections
  * ``-``, for subsections
  * ``^``, for subsubsections
  * ``"``, for paragraphs
 
  Of course, you are free to use your own marker characters (see the reST
  documentation), and use a deeper nesting level, but keep in mind that most
  target formats (HTML, LaTeX) have a limited supported nesting depth.
 
 
  Explicit Markup
  ---------------
 
  "Explicit markup" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for
  most constructs that need special handling, such as footnotes,
  specially-highlighted paragraphs, comments, and generic directives.
 
  An explicit markup block begins with a line starting with ``..`` followed by
  whitespace and is terminated by the next paragraph at the same level of
  indentation. (There needs to be a blank line between explicit markup and normal
  paragraphs. This may all sound a bit complicated, but it is intuitive enough
  when you write it.)
 
 
  .. _directives:
 
  Directives
  ----------
 
  A directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.
  Besides roles, it is one of the extension mechanisms of reST, and Sphinx makes
  heavy use of it.
 
  Docutils supports the following directives:
 
  * Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
  :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
  :dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.
  (Most themes style only "note" and "warning" specially.)
 
  * Images:
 
  - :dudir:`image` (see also Images_ below)
  - :dudir:`figure` (an image with caption and optional legend)
 
  * Additional body elements:
 
  - :dudir:`contents` (a local, i.e. for the current file only, table of
  contents)
  - :dudir:`container` (a container with a custom class, useful to generate an
  outer ``&lt;div&gt;`` in HTML)
  - :dudir:`rubric` (a heading without relation to the document sectioning)
  - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
  - :dudir:`parsed-literal` (literal block that supports inline markup)
  - :dudir:`epigraph` (a block quote with optional attribution line)
  - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
  class attribute)
  - :dudir:`compound` (a compound paragraph)
 
  * Special tables:
 
  - :dudir:`table` (a table with title)
  - :dudir:`csv-table` (a table generated from comma-separated values)
  - :dudir:`list-table` (a table generated from a list of lists)
 
  * Special directives:
 
  - :dudir:`raw` (include raw target-format markup)
  - :dudir:`include` (include reStructuredText from another file)
  -- in Sphinx, when given an absolute include file path, this directive takes
  it as relative to the source directory
  - :dudir:`class` (assign a class attribute to the next element) [1]_
 
  * HTML specifics:
 
  - :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)
  - :dudir:`title` (override document title)
 
  * Influencing markup:
 
  - :dudir:`default-role` (set a new default role)
  - :dudir:`role` (create a new role)
 
  Since these are only per-file, better use Sphinx' facilities for setting the
  :confval:`default_role`.
 
  Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
  :dudir:`footer`.
 
  Directives added by Sphinx are described in :ref:`sphinxmarkup`.
 
  Basically, a directive consists of a name, arguments, options and content. (Keep
  this terminology in mind, it is used in the next chapter describing custom
  directives.) Looking at this example, ::
 
  .. function:: foo(x)
  foo(y, z)
  :module: some.module.name
 
  Return a line of text input from the user.
 
  ``function`` is the directive name. It is given two arguments here, the
  remainder of the first line and the second line, as well as one option
  ``module`` (as you can see, options are given in the lines immediately following
  the arguments and indicated by the colons). Options must be indented to the
  same level as the directive content.
 
  The directive content follows after a blank line and is indented relative to the
  directive start.
 
 
  Images
  ------
 
  reST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::
 
  .. image:: gnu.png
  (options)
 
  When used within Sphinx, the file name given (here ``gnu.png``) must either be
  relative to the source file, or absolute which means that they are relative to
  the top source directory. For example, the file ``sketch/spam.rst`` could refer
  to the image ``images/spam.png`` as ``../images/spam.png`` or
  ``/images/spam.png``.
 
  Sphinx will automatically copy image files over to a subdirectory of the output
  directory on building (e.g. the ``_static`` directory for HTML output.)
 
  Interpretation of image size options (``width`` and ``height``) is as follows:
  if the size has no unit or the unit is pixels, the given size will only be
  respected for output channels that support pixels (i.e. not in LaTeX output).
  Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
 
  Sphinx extends the standard docutils behavior by allowing an asterisk for the
  extension::
 
  .. image:: gnu.*
 
  Sphinx then searches for all images matching the provided pattern and determines
  their type. Each builder then chooses the best image out of these candidates.
  For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`
  and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose
  the former, while the HTML builder would prefer the latter.
 
  .. versionchanged:: 0.4
  Added the support for file names ending in an asterisk.
 
  .. versionchanged:: 0.6
  Image paths can now be absolute.
 
 
  Footnotes
  ---------
 
  For footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote
  location, and add the footnote body at the bottom of the document after a
  "Footnotes" rubric heading, like so::
 
  Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
 
  .. rubric:: Footnotes
 
  .. [#f1] Text of the first footnote.
  .. [#f2] Text of the second footnote.
 
  You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
  footnotes without names (``[#]_``).
 
 
  Citations
  ---------
 
  Standard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the
  additional feature that they are "global", i.e. all citations can be referenced
  from all files. Use them like so::
 
  Lorem ipsum [Ref]_ dolor sit amet.
 
  .. [Ref] Book or article reference, URL or whatever.
 
  Citation usage is similar to footnote usage, but with a label that is not
  numeric or begins with ``#``.
 
 
  Substitutions
  -------------
 
  reST supports "substitutions" (:duref:`ref &lt;substitution-definitions&gt;`), which
  are pieces of text and/or markup referred to in the text by ``|name|``. They
  are defined like footnotes with explicit markup blocks, like this::
 
  .. |name| replace:: replacement *text*
 
  or this::
 
  .. |caution| image:: warning.png
  :alt: Warning!
 
  See the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`
  for details.
 
  If you want to use some substitutions for all documents, put them into
  :confval:`rst_prolog` or put them into a separate file and include it into all
  documents you want to use them in, using the :rst:dir:`include` directive. (Be
  sure to give the include file a file name extension differing from that of other
  source files, to avoid Sphinx finding it as a standalone document.)
 
  Sphinx defines some default substitutions, see :ref:`default-substitutions`.
 
 
  Comments
  --------
 
  Every explicit markup block which isn't a valid markup construct (like the
  footnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`). For
  example::
 
  .. This is a comment.
 
  You can indent text after a comment start to form multiline comments::
 
  ..
  This whole indented block
  is a comment.
 
  Still in the comment.
 
 
  Source encoding
  ---------------
 
  Since the easiest way to include special characters like em dashes or copyright
  signs in reST is to directly write them as Unicode characters, one has to
  specify an encoding. Sphinx assumes source files to be encoded in UTF-8 by
  default; you can change this with the :confval:`source_encoding` config value.
 
 
  Gotchas
  -------
 
  There are some problems one commonly runs into while authoring reST documents:
 
  * **Separation of inline markup:** As said above, inline markup spans must be
  separated from the surrounding text by non-word characters, you have to use a
  backslash-escaped space to get around that. See `the reference
  &lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_
  for the details.
 
  * **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
  possible.
 
 
  .. rubric:: Footnotes
 
  .. [1] When the default domain contains a :rst:dir:`class` directive, this directive
  will be shadowed. Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  });
  </script>
  <p>The reStructuredText mode supports one configuration parameter:</p>
  <dl>
  <dt><code>verbatim (string)</code></dt>
  <dd>A name or MIME type of a mode that will be used for highlighting
  verbatim blocks. By default, reStructuredText mode uses uniform color
  for whole block of verbatim text if no mode is given.</dd>
  </dl>
  <p>If <code>python</code> mode is available,
  it will be used for highlighting blocks containing Python/IPython terminal
  sessions (blocks starting with <code>&gt;&gt;&gt;</code> (for Python) or
  <code>In [num]:</code> (for IPython).
 
  <p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p>
  </body>
  </html>
 
 
  CodeMirror.defineMode('rst', function(config, options) {
  function setState(state, fn, ctx) {
  state.fn = fn;
  setCtx(state, ctx);
  }
 
  function setCtx(state, ctx) {
  state.ctx = ctx || {};
  }
 
  function setNormal(state, ch) {
  if (ch && (typeof ch !== 'string')) {
  var str = ch.current();
  ch = str[str.length-1];
  }
 
  setState(state, normal, {back: ch});
  }
 
  function hasMode(mode) {
  if (mode) {
  var modes = CodeMirror.listModes();
 
  for (var i in modes) {
  if (modes[i] == mode) {
  return true;
  }
  }
  }
 
  return false;
  }
 
  function getMode(mode) {
  if (hasMode(mode)) {
  return CodeMirror.getMode(config, mode);
  } else {
  return null;
  }
  }
 
  var verbatimMode = getMode(options.verbatim);
  var pythonMode = getMode('python');
 
  var reSection = /^[!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
  var reDirective = /^\s*\w([-:.\w]*\w)?::(\s|$)/;
  var reHyperlink = /^\s*_[\w-]+:(\s|$)/;
  var reFootnote = /^\s*\[(\d+|#)\](\s|$)/;
  var reCitation = /^\s*\[[A-Za-z][\w-]*\](\s|$)/;
  var reFootnoteRef = /^\[(\d+|#)\]_/;
  var reCitationRef = /^\[[A-Za-z][\w-]*\]_/;
  var reDirectiveMarker = /^\.\.(\s|$)/;
  var reVerbatimMarker = /^::\s*$/;
  var rePreInline = /^[-\s"([{</:]/;
  var rePostInline = /^[-\s`'")\]}>/:.,;!?\\_]/;
  var reEnumeratedList = /^\s*((\d+|[A-Za-z#])[.)]|\((\d+|[A-Z-a-z#])\))\s/;
  var reBulletedList = /^\s*[-\+\*]\s/;
  var reExamples = /^\s+(>>>|In \[\d+\]:)\s/;
 
  function normal(stream, state) {
  var ch, sol, i;
 
  if (stream.eat(/\\/)) {
  ch = stream.next();
  setNormal(state, ch);
  return null;
  }
 
  sol = stream.sol();
 
  if (sol && (ch = stream.eat(reSection))) {
  for (i = 0; stream.eat(ch); i++);
 
  if (i >= 3 && stream.match(/^\s*$/)) {
  setNormal(state, null);
  return 'header';
  } else {
  stream.backUp(i + 1);
  }
  }
 
  if (sol && stream.match(reDirectiveMarker)) {
  if (!stream.eol()) {
  setState(state, directive);
  }
  return 'meta';
  }
 
  if (stream.match(reVerbatimMarker)) {
  if (!verbatimMode) {
  setState(state, verbatim);
  } else {
  var mode = verbatimMode;
 
  setState(state, verbatim, {
  mode: mode,
  local: mode.startState()
  });
  }
  return 'meta';
  }
 
  if (sol && stream.match(reExamples, false)) {
  if (!pythonMode) {
  setState(state, verbatim);
  return 'meta';
  } else {
  var mode = pythonMode;
 
  setState(state, verbatim, {
  mode: mode,
  local: mode.startState()
  });
 
  return null;
  }
  }
 
  function testBackward(re) {
  return sol || !state.ctx.back || re.test(state.ctx.back);
  }
 
  function testForward(re) {
  return stream.eol() || stream.match(re, false);
  }
 
  function testInline(re) {
  return stream.match(re) && testBackward(/\W/) && testForward(/\W/);
  }
 
  if (testInline(reFootnoteRef)) {
  setNormal(state, stream);
  return 'footnote';
  }
 
  if (testInline(reCitationRef)) {
  setNormal(state, stream);
  return 'citation';
  }
 
  ch = stream.next();
 
  if (testBackward(rePreInline)) {
  if ((ch === ':' || ch === '|') && stream.eat(/\S/)) {
  var token;
 
  if (ch === ':') {
  token = 'builtin';
  } else {
  token = 'atom';
  }
 
  setState(state, inline, {
  ch: ch,
  wide: false,
  prev: null,
  token: token
  });
 
  return token;
  }
 
  if (ch === '*' || ch === '`') {
  var orig = ch,
  wide = false;
 
  ch = stream.next();
 
  if (ch == orig) {
  wide = true;
  ch = stream.next();
  }
 
  if (ch && !/\s/.test(ch)) {
  var token;
 
  if (orig === '*') {
  token = wide ? 'strong' : 'em';
  } else {
  token = wide ? 'string' : 'string-2';
  }
 
  setState(state, inline, {
  ch: orig, // inline() has to know what to search for
  wide: wide, // are we looking for `ch` or `chch`
  prev: null, // terminator must not be preceeded with whitespace
  token: token // I don't want to recompute this all the time
  });
 
  return token;
  }
  }
  }
 
  setNormal(state, ch);
  return null;
  }
 
  function inline(stream, state) {
  var ch = stream.next(),
  token = state.ctx.token;
 
  function finish(ch) {
  state.ctx.prev = ch;
  return token;
  }
 
  if (ch != state.ctx.ch) {
  return finish(ch);
  }
 
  if (/\s/.test(state.ctx.prev)) {
  return finish(ch);
  }
 
  if (state.ctx.wide) {
  ch = stream.next();
 
  if (ch != state.ctx.ch) {
  return finish(ch);
  }
  }
 
  if (!stream.eol() && !rePostInline.test(stream.peek())) {
  if (state.ctx.wide) {
  stream.backUp(1);
  }
 
  return finish(ch);
  }
 
  setState(state, normal);
  setNormal(state, ch);
 
  return token;
  }
 
  function directive(stream, state) {
  var token = null;
 
  if (stream.match(reDirective)) {
  token = 'attribute';
  } else if (stream.match(reHyperlink)) {
  token = 'link';
  } else if (stream.match(reFootnote)) {
  token = 'quote';
  } else if (stream.match(reCitation)) {
  token = 'quote';
  } else {
  stream.eatSpace();
 
  if (stream.eol()) {
  setNormal(state, stream);
  return null;
  } else {
  stream.skipToEnd();
  setState(state, comment);
  return 'comment';
  }
  }
 
  // FIXME this is unreachable
  setState(state, body, {start: true});
  return token;
  }
 
  function body(stream, state) {
  var token = 'body';
 
  if (!state.ctx.start || stream.sol()) {
  return block(stream, state, token);
  }
 
  stream.skipToEnd();
  setCtx(state);
 
  return token;
  }
 
  function comment(stream, state) {
  return block(stream, state, 'comment');
  }
 
  function verbatim(stream, state) {
  if (!verbatimMode) {
  return block(stream, state, 'meta');
  } else {
  if (stream.sol()) {
  if (!stream.eatSpace()) {
  setNormal(state, stream);
  }
 
  return null;
  }
 
  return verbatimMode.token(stream, state.ctx.local);
  }
  }
 
  function block(stream, state, token) {
  if (stream.eol() || stream.eatSpace()) {
  stream.skipToEnd();
  return token;
  } else {
  setNormal(state, stream);
  return null;
  }
  }
 
  return {
  startState: function() {
  return {fn: normal, ctx: {}};
  },
 
  copyState: function(state) {
  return {fn: state.fn, ctx: state.ctx};
  },
 
  token: function(stream, state) {
  var token = state.fn(stream, state);
  return token;
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-rst", "rst");
 
  Copyright (c) 2011, Ubalo, Inc.
  All rights reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
  * Neither the name of the Ubalo, Inc. nor the names of its
  contributors may be used to endorse or promote products derived
  from this software without specific prior written permission.
 
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Ruby mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="ruby.js"></script>
  <style>
  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
  .cm-s-default span.cm-arrow { color: red; }
  </style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Ruby mode</h1>
  <form><textarea id="code" name="code">
  # Code from http://sandbox.mc.edu/~bennet/ruby/code/poly_rb.html
  #
  # This program evaluates polynomials. It first asks for the coefficients
  # of a polynomial, which must be entered on one line, highest-order first.
  # It then requests values of x and will compute the value of the poly for
  # each x. It will repeatly ask for x values, unless you the user enters
  # a blank line. It that case, it will ask for another polynomial. If the
  # user types quit for either input, the program immediately exits.
  #
 
  #
  # Function to evaluate a polynomial at x. The polynomial is given
  # as a list of coefficients, from the greatest to the least.
  def polyval(x, coef)
  sum = 0
  coef = coef.clone # Don't want to destroy the original
  while true
  sum += coef.shift # Add and remove the next coef
  break if coef.empty? # If no more, done entirely.
  sum *= x # This happens the right number of times.
  end
  return sum
  end
 
  #
  # Function to read a line containing a list of integers and return
  # them as an array of integers. If the string conversion fails, it
  # throws TypeError. If the input line is the word 'quit', then it
  # converts it to an end-of-file exception
  def readints(prompt)
  # Read a line
  print prompt
  line = readline.chomp
  raise EOFError.new if line == 'quit' # You can also use a real EOF.
 
  # Go through each item on the line, converting each one and adding it
  # to retval.
  retval = [ ]
  for str in line.split(/\s+/)
  if str =~ /^\-?\d+$/
  retval.push(str.to_i)
  else
  raise TypeError.new
  end
  end
 
  return retval
  end
 
  #
  # Take a coeff and an exponent and return the string representation, ignoring
  # the sign of the coefficient.
  def term_to_str(coef, exp)
  ret = ""
 
  # Show coeff, unless it's 1 or at the right
  coef = coef.abs
  ret = coef.to_s unless coef == 1 && exp > 0
  ret += "x" if exp > 0 # x if exponent not 0
  ret += "^" + exp.to_s if exp > 1 # ^exponent, if > 1.
 
  return ret
  end
 
  #
  # Create a string of the polynomial in sort-of-readable form.
  def polystr(p)
  # Get the exponent of first coefficient, plus 1.
  exp = p.length
 
  # Assign exponents to each term, making pairs of coeff and exponent,
  # Then get rid of the zero terms.
  p = (p.map { |c| exp -= 1; [ c, exp ] }).select { |p| p[0] != 0 }
 
  # If there's nothing left, it's a zero
  return "0" if p.empty?
 
  # *** Now p is a non-empty list of [ coef, exponent ] pairs. ***
 
  # Convert the first term, preceded by a "-" if it's negative.
  result = (if p[0][0] < 0 then "-" else "" end) + term_to_str(*p[0])
 
  # Convert the rest of the terms, in each case adding the appropriate
  # + or - separating them.
  for term in p[1...p.length]
  # Add the separator then the rep. of the term.
  result += (if term[0] < 0 then " - " else " + " end) +
  term_to_str(*term)
  end
 
  return result
  end
 
  #
  # Run until some kind of endfile.
  begin
  # Repeat until an exception or quit gets us out.
  while true
  # Read a poly until it works. An EOF will except out of the
  # program.
  print "\n"
  begin
  poly = readints("Enter a polynomial coefficients: ")
  rescue TypeError
  print "Try again.\n"
  retry
  end
  break if poly.empty?
 
  # Read and evaluate x values until the user types a blank line.
  # Again, an EOF will except out of the pgm.
  while true
  # Request an integer.
  print "Enter x value or blank line: "
  x = readline.chomp
  break if x == ''
  raise EOFError.new if x == 'quit'
 
  # If it looks bad, let's try again.
  if x !~ /^\-?\d+$/
  print "That doesn't look like an integer. Please try again.\n"
  next
  end
 
  # Convert to an integer and print the result.
  x = x.to_i
  print "p(x) = ", polystr(poly), "\n"
  print "p(", x, ") = ", polyval(x, poly), "\n"
  end
  end
  rescue EOFError
  print "\n=== EOF ===\n"
  rescue Interrupt, SignalException
  print "\n=== Interrupted ===\n"
  else
  print "--- Bye ---\n"
  end
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: "text/x-ruby",
  tabMode: "indent",
  matchBrackets: true,
  indentUnit: 4
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-ruby</code>.</p>
 
  <p>Development of the CodeMirror Ruby mode was kindly sponsored
  by <a href="http://ubalo.com/">Ubalo</a>, who hold
  the <a href="LICENSE">license</a>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("ruby", function(config, parserConfig) {
  function wordObj(words) {
  var o = {};
  for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
  return o;
  }
  var keywords = wordObj([
  "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
  "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or",
  "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
  "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc",
  "caller", "lambda", "proc", "public", "protected", "private", "require", "load",
  "require_relative", "extend", "autoload"
  ]);
  var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "module", "then",
  "unless", "catch", "loop", "proc"]);
  var dedentWords = wordObj(["end", "until"]);
  var matching = {"[": "]", "{": "}", "(": ")"};
  var curPunc;
 
  function chain(newtok, stream, state) {
  state.tokenize.push(newtok);
  return newtok(stream, state);
  }
 
  function tokenBase(stream, state) {
  curPunc = null;
  if (stream.sol() && stream.match("=begin") && stream.eol()) {
  state.tokenize.push(readBlockComment);
  return "comment";
  }
  if (stream.eatSpace()) return null;
  var ch = stream.next();
  if (ch == "`" || ch == "'" || ch == '"' || ch == "/") {
  return chain(readQuoted(ch, "string", ch == '"'), stream, state);
  } else if (ch == "%") {
  var style, embed = false;
  if (stream.eat("s")) style = "atom";
  else if (stream.eat(/[WQ]/)) { style = "string"; embed = true; }
  else if (stream.eat(/[wxqr]/)) style = "string";
  var delim = stream.eat(/[^\w\s]/);
  if (!delim) return "operator";
  if (matching.propertyIsEnumerable(delim)) delim = matching[delim];
  return chain(readQuoted(delim, style, embed, true), stream, state);
  } else if (ch == "#") {
  stream.skipToEnd();
  return "comment";
  } else if (ch == "<" && stream.eat("<")) {
  stream.eat("-");
  stream.eat(/[\'\"\`]/);
  var match = stream.match(/^\w+/);
  stream.eat(/[\'\"\`]/);
  if (match) return chain(readHereDoc(match[0]), stream, state);
  return null;
  } else if (ch == "0") {
  if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);
  else if (stream.eat("b")) stream.eatWhile(/[01]/);
  else stream.eatWhile(/[0-7]/);
  return "number";
  } else if (/\d/.test(ch)) {
  stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
  return "number";
  } else if (ch == "?") {
  while (stream.match(/^\\[CM]-/)) {}
  if (stream.eat("\\")) stream.eatWhile(/\w/);
  else stream.next();
  return "string";
  } else if (ch == ":") {
  if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
  if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);
  stream.eatWhile(/[\w\?]/);
  return "atom";
  } else if (ch == "@") {
  stream.eat("@");
  stream.eatWhile(/[\w\?]/);
  return "variable-2";
  } else if (ch == "$") {
  stream.next();
  stream.eatWhile(/[\w\?]/);
  return "variable-3";
  } else if (/\w/.test(ch)) {
  stream.eatWhile(/[\w\?]/);
  if (stream.eat(":")) return "atom";
  return "ident";
  } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
  curPunc = "|";
  return null;
  } else if (/[\(\)\[\]{}\\;]/.test(ch)) {
  curPunc = ch;
  return null;
  } else if (ch == "-" && stream.eat(">")) {
  return "arrow";
  } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
  stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
  return "operator";
  } else {
  return null;
  }
  }
 
  function tokenBaseUntilBrace() {
  var depth = 1;
  return function(stream, state) {
  if (stream.peek() == "}") {
  depth--;
  if (depth == 0) {
  state.tokenize.pop();
  return state.tokenize[state.tokenize.length-1](stream, state);
  }
  } else if (stream.peek() == "{") {
  depth++;
  }
  return tokenBase(stream, state);
  };
  }
  function readQuoted(quote, style, embed, unescaped) {
  return function(stream, state) {
  var escaped = false, ch;
  while ((ch = stream.next()) != null) {
  if (ch == quote && (unescaped || !escaped)) {
  state.tokenize.pop();
  break;
  }
  if (embed && ch == "#" && !escaped && stream.eat("{")) {
  state.tokenize.push(tokenBaseUntilBrace(arguments.callee));
  break;
  }
  escaped = !escaped && ch == "\\";
  }
  return style;
  };
  }
  function readHereDoc(phrase) {
  return function(stream, state) {
  if (stream.match(phrase)) state.tokenize.pop();
  else stream.skipToEnd();
  return "string";
  };
  }
  function readBlockComment(stream, state) {
  if (stream.sol() && stream.match("=end") && stream.eol())
  state.tokenize.pop();
  stream.skipToEnd();
  return "comment";
  }
 
  return {
  startState: function() {
  return {tokenize: [tokenBase],
  indented: 0,
  context: {type: "top", indented: -config.indentUnit},
  continuedLine: false,
  lastTok: null,
  varList: false};
  },
 
  token: function(stream, state) {
  if (stream.sol()) state.indented = stream.indentation();
  var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;
  if (style == "ident") {
  var word = stream.current();
  style = keywords.propertyIsEnumerable(stream.current()) ? "keyword"
  : /^[A-Z]/.test(word) ? "tag"
  : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def"
  : "variable";
  if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";
  else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";
  else if (word == "if" && stream.column() == stream.indentation()) kwtype = "indent";
  }
  if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style;
  if (curPunc == "|") state.varList = !state.varList;
 
  if (kwtype == "indent" || /[\(\[\{]/.test(curPunc))
  state.context = {prev: state.context, type: curPunc || style, indented: state.indented};
  else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev)
  state.context = state.context.prev;
 
  if (stream.eol())
  state.continuedLine = (curPunc == "\\" || style == "operator");
  return style;
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0;
  var firstChar = textAfter && textAfter.charAt(0);
  var ct = state.context;
  var closing = ct.type == matching[firstChar] ||
  ct.type == "keyword" && /^(?:end|until|else|elsif|when)\b/.test(textAfter);
  return ct.indented + (closing ? 0 : config.indentUnit) +
  (state.continuedLine ? config.indentUnit : 0);
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-ruby", "ruby");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Rust mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="rust.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: Rust mode</h1>
 
  <div><textarea id="code" name="code">
  // Demo code.
 
  type foo<T> = int;
  tag bar {
  some(int, foo<float>);
  none;
  }
 
  fn check_crate(x: int) {
  let v = 10;
  alt foo {
  1 to 3 {
  print_foo();
  if x {
  blah() + 10;
  }
  }
  (x, y) { "bye" }
  _ { "hi" }
  }
  }
  </textarea></div>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  tabMode: "indent"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-rustsrc</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("rust", function() {
  var indentUnit = 4, altIndentUnit = 2;
  var valKeywords = {
  "if": "if-style", "while": "if-style", "else": "else-style",
  "do": "else-style", "ret": "else-style", "fail": "else-style",
  "break": "atom", "cont": "atom", "const": "let", "resource": "fn",
  "let": "let", "fn": "fn", "for": "for", "alt": "alt", "obj": "fn",
  "lambda": "fn", "type": "type", "tag": "tag", "mod": "mod",
  "as": "op", "true": "atom", "false": "atom", "assert": "op", "check": "op",
  "claim": "op", "native": "ignore", "unsafe": "ignore", "import": "else-style",
  "export": "else-style", "copy": "op", "log": "op", "log_err": "op",
  "use": "op", "bind": "op"
  };
  var typeKeywords = function() {
  var keywords = {"fn": "fn", "block": "fn", "obj": "obj"};
  var atoms = "bool uint int i8 i16 i32 i64 u8 u16 u32 u64 float f32 f64 str char".split(" ");
  for (var i = 0, e = atoms.length; i < e; ++i) keywords[atoms[i]] = "atom";
  return keywords;
  }();
  var operatorChar = /[+\-*&%=<>!?|\.@]/;
 
  // Tokenizer
 
  // Used as scratch variable to communicate multiple values without
  // consing up tons of objects.
  var tcat, content;
  function r(tc, style) {
  tcat = tc;
  return style;
  }
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  if (ch == '"') {
  state.tokenize = tokenString;
  return state.tokenize(stream, state);
  }
  if (ch == "'") {
  tcat = "atom";
  if (stream.eat("\\")) {
  if (stream.skipTo("'")) { stream.next(); return "string"; }
  else { return "error"; }
  } else {
  stream.next();
  return stream.eat("'") ? "string" : "error";
  }
  }
  if (ch == "/") {
  if (stream.eat("/")) { stream.skipToEnd(); return "comment"; }
  if (stream.eat("*")) {
  state.tokenize = tokenComment(1);
  return state.tokenize(stream, state);
  }
  }
  if (ch == "#") {
  if (stream.eat("[")) { tcat = "open-attr"; return null; }
  stream.eatWhile(/\w/);
  return r("macro", "meta");
  }
  if (ch == ":" && stream.match(":<")) {
  return r("op", null);
  }
  if (ch.match(/\d/) || (ch == "." && stream.eat(/\d/))) {
  var flp = false;
  if (!stream.match(/^x[\da-f]+/i) && !stream.match(/^b[01]+/)) {
  stream.eatWhile(/\d/);
  if (stream.eat(".")) { flp = true; stream.eatWhile(/\d/); }
  if (stream.match(/^e[+\-]?\d+/i)) { flp = true; }
  }
  if (flp) stream.match(/^f(?:32|64)/);
  else stream.match(/^[ui](?:8|16|32|64)/);
  return r("atom", "number");
  }
  if (ch.match(/[()\[\]{}:;,]/)) return r(ch, null);
  if (ch == "-" && stream.eat(">")) return r("->", null);
  if (ch.match(operatorChar)) {
  stream.eatWhile(operatorChar);
  return r("op", null);
  }
  stream.eatWhile(/\w/);
  content = stream.current();
  if (stream.match(/^::\w/)) {
  stream.backUp(1);
  return r("prefix", "variable-2");
  }
  if (state.keywords.propertyIsEnumerable(content))
  return r(state.keywords[content], content.match(/true|false/) ? "atom" : "keyword");
  return r("name", "variable");
  }
 
  function tokenString(stream, state) {
  var ch, escaped = false;
  while (ch = stream.next()) {
  if (ch == '"' && !escaped) {
  state.tokenize = tokenBase;
  return r("atom", "string");
  }
  escaped = !escaped && ch == "\\";
  }
  // Hack to not confuse the parser when a string is split in
  // pieces.
  return r("op", "string");
  }
 
  function tokenComment(depth) {
  return function(stream, state) {
  var lastCh = null, ch;
  while (ch = stream.next()) {
  if (ch == "/" && lastCh == "*") {
  if (depth == 1) {
  state.tokenize = tokenBase;
  break;
  } else {
  state.tokenize = tokenComment(depth - 1);
  return state.tokenize(stream, state);
  }
  }
  if (ch == "*" && lastCh == "/") {
  state.tokenize = tokenComment(depth + 1);
  return state.tokenize(stream, state);
  }
  lastCh = ch;
  }
  return "comment";
  };
  }
 
  // Parser
 
  var cx = {state: null, stream: null, marked: null, cc: null};
  function pass() {
  for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  }
  function cont() {
  pass.apply(null, arguments);
  return true;
  }
 
  function pushlex(type, info) {
  var result = function() {
  var state = cx.state;
  state.lexical = {indented: state.indented, column: cx.stream.column(),
  type: type, prev: state.lexical, info: info};
  };
  result.lex = true;
  return result;
  }
  function poplex() {
  var state = cx.state;
  if (state.lexical.prev) {
  if (state.lexical.type == ")")
  state.indented = state.lexical.indented;
  state.lexical = state.lexical.prev;
  }
  }
  function typecx() { cx.state.keywords = typeKeywords; }
  function valcx() { cx.state.keywords = valKeywords; }
  poplex.lex = typecx.lex = valcx.lex = true;
 
  function commasep(comb, end) {
  function more(type) {
  if (type == ",") return cont(comb, more);
  if (type == end) return cont();
  return cont(more);
  }
  return function(type) {
  if (type == end) return cont();
  return pass(comb, more);
  };
  }
 
  function block(type) {
  if (type == "}") return cont();
  if (type == "let") return cont(pushlex("stat", "let"), letdef1, poplex, block);
  if (type == "fn") return cont(pushlex("stat"), fndef, poplex, block);
  if (type == "type") return cont(pushlex("stat"), tydef, endstatement, poplex, block);
  if (type == "tag") return cont(pushlex("stat"), tagdef, poplex, block);
  if (type == "mod") return cont(pushlex("stat"), mod, poplex, block);
  if (type == "open-attr") return cont(pushlex("]"), commasep(expression, "]"), poplex);
  if (type == "ignore" || type.match(/[\]\);,]/)) return cont(block);
  return pass(pushlex("stat"), expression, poplex, endstatement, block);
  }
  function endstatement(type) {
  if (type == ";") return cont();
  return pass();
  }
  function expression(type) {
  if (type == "atom" || type == "name") return cont(maybeop);
  if (type == "{") return cont(pushlex("}"), exprbrace, poplex);
  if (type.match(/[\[\(]/)) return matchBrackets(type, expression);
  if (type.match(/[\]\)\};,]/)) return pass();
  if (type == "if-style") return cont(expression, expression);
  if (type == "else-style" || type == "op") return cont(expression);
  if (type == "for") return cont(pattern, maybetype, inop, expression, expression);
  if (type == "alt") return cont(expression, altbody);
  if (type == "fn") return cont(fndef);
  if (type == "macro") return cont(macro);
  return cont();
  }
  function maybeop(type) {
  if (content == ".") return cont(maybeprop);
  if (content == "::<"){return cont(typarams, maybeop);}
  if (type == "op" || content == ":") return cont(expression);
  if (type == "(" || type == "[") return matchBrackets(type, expression);
  return pass();
  }
  function maybeprop(type) {
  if (content.match(/^\w+$/)) {cx.marked = "variable"; return cont(maybeop);}
  return pass(expression);
  }
  function exprbrace(type) {
  if (type == "op") {
  if (content == "|") return cont(blockvars, poplex, pushlex("}", "block"), block);
  if (content == "||") return cont(poplex, pushlex("}", "block"), block);
  }
  if (content == "mutable" || (content.match(/^\w+$/) && cx.stream.peek() == ":"
  && !cx.stream.match("::", false)))
  return pass(record_of(expression));
  return pass(block);
  }
  function record_of(comb) {
  function ro(type) {
  if (content == "mutable" || content == "with") {cx.marked = "keyword"; return cont(ro);}
  if (content.match(/^\w*$/)) {cx.marked = "variable"; return cont(ro);}
  if (type == ":") return cont(comb, ro);
  if (type == "}") return cont();
  return cont(ro);
  }
  return ro;
  }
  function blockvars(type) {
  if (type == "name") {cx.marked = "def"; return cont(blockvars);}
  if (type == "op" && content == "|") return cont();
  return cont(blockvars);
  }
 
  function letdef1(type) {
  if (type.match(/[\]\)\};]/)) return cont();
  if (content == "=") return cont(expression, letdef2);
  if (type == ",") return cont(letdef1);
  return pass(pattern, maybetype, letdef1);
  }
  function letdef2(type) {
  if (type.match(/[\]\)\};,]/)) return pass(letdef1);
  else return pass(expression, letdef2);
  }
  function maybetype(type) {
  if (type == ":") return cont(typecx, rtype, valcx);
  return pass();
  }
  function inop(type) {
  if (type == "name" && content == "in") {cx.marked = "keyword"; return cont();}
  return pass();
  }
  function fndef(type) {
  if (type == "name") {cx.marked = "def"; return cont(fndef);}
  if (content == "<") return cont(typarams, fndef);
  if (type == "{") return pass(expression);
  if (type == "(") return cont(pushlex(")"), commasep(argdef, ")"), poplex, fndef);
  if (type == "->") return cont(typecx, rtype, valcx, fndef);
  return cont(fndef);
  }
  function tydef(type) {
  if (type == "name") {cx.marked = "def"; return cont(tydef);}
  if (content == "<") return cont(typarams, tydef);
  if (content == "=") return cont(typecx, rtype, valcx);
  return cont(tydef);
  }
  function tagdef(type) {
  if (type == "name") {cx.marked = "def"; return cont(tagdef);}
  if (content == "<") return cont(typarams, tagdef);
  if (content == "=") return cont(typecx, rtype, valcx, endstatement);
  if (type == "{") return cont(pushlex("}"), typecx, tagblock, valcx, poplex);
  return cont(tagdef);
  }
  function tagblock(type) {
  if (type == "}") return cont();
  if (type == "(") return cont(pushlex(")"), commasep(rtype, ")"), poplex, tagblock);
  if (content.match(/^\w+$/)) cx.marked = "def";
  return cont(tagblock);
  }
  function mod(type) {
  if (type == "name") {cx.marked = "def"; return cont(mod);}
  if (type == "{") return cont(pushlex("}"), block, poplex);
  return pass();
  }
  function typarams(type) {
  if (content == ">") return cont();
  if (content == ",") return cont(typarams);
  return pass(rtype, typarams);
  }
  function argdef(type) {
  if (type == "name") {cx.marked = "def"; return cont(argdef);}
  if (type == ":") return cont(typecx, rtype, valcx);
  return pass();
  }
  function rtype(type) {
  if (type == "name") {cx.marked = "variable-3"; return cont(rtypemaybeparam); }
  if (content == "mutable") {cx.marked = "keyword"; return cont(rtype);}
  if (type == "atom") return cont(rtypemaybeparam);
  if (type == "op" || type == "obj") return cont(rtype);
  if (type == "fn") return cont(fntype);
  if (type == "{") return cont(pushlex("{"), record_of(rtype), poplex);
  return matchBrackets(type, rtype);
  }
  function rtypemaybeparam(type) {
  if (content == "<") return cont(typarams);
  return pass();
  }
  function fntype(type) {
  if (type == "(") return cont(pushlex("("), commasep(rtype, ")"), poplex, fntype);
  if (type == "->") return cont(rtype);
  return pass();
  }
  function pattern(type) {
  if (type == "name") {cx.marked = "def"; return cont(patternmaybeop);}
  if (type == "atom") return cont(patternmaybeop);
  if (type == "op") return cont(pattern);
  if (type.match(/[\]\)\};,]/)) return pass();
  return matchBrackets(type, pattern);
  }
  function patternmaybeop(type) {
  if (type == "op" && content == ".") return cont();
  if (content == "to") {cx.marked = "keyword"; return cont(pattern);}
  else return pass();
  }
  function altbody(type) {
  if (type == "{") return cont(pushlex("}", "alt"), altblock1, poplex);
  return pass();
  }
  function altblock1(type) {
  if (type == "}") return cont();
  if (type == "|") return cont(altblock1);
  if (content == "when") {cx.marked = "keyword"; return cont(expression, altblock2);}
  if (type.match(/[\]\);,]/)) return cont(altblock1);
  return pass(pattern, altblock2);
  }
  function altblock2(type) {
  if (type == "{") return cont(pushlex("}", "alt"), block, poplex, altblock1);
  else return pass(altblock1);
  }
 
  function macro(type) {
  if (type.match(/[\[\(\{]/)) return matchBrackets(type, expression);
  return pass();
  }
  function matchBrackets(type, comb) {
  if (type == "[") return cont(pushlex("]"), commasep(comb, "]"), poplex);
  if (type == "(") return cont(pushlex(")"), commasep(comb, ")"), poplex);
  if (type == "{") return cont(pushlex("}"), commasep(comb, "}"), poplex);
  return cont();
  }
 
  function parse(state, stream, style) {
  var cc = state.cc;
  // Communicate our context to the combinators.
  // (Less wasteful than consing up a hundred closures on every call.)
  cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
 
  while (true) {
  var combinator = cc.length ? cc.pop() : block;
  if (combinator(tcat)) {
  while(cc.length && cc[cc.length - 1].lex)
  cc.pop()();
  return cx.marked || style;
  }
  }
  }
 
  return {
  startState: function() {
  return {
  tokenize: tokenBase,
  cc: [],
  lexical: {indented: -indentUnit, column: 0, type: "top", align: false},
  keywords: valKeywords,
  indented: 0
  };
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  if (!state.lexical.hasOwnProperty("align"))
  state.lexical.align = false;
  state.indented = stream.indentation();
  }
  if (stream.eatSpace()) return null;
  tcat = content = null;
  var style = state.tokenize(stream, state);
  if (style == "comment") return style;
  if (!state.lexical.hasOwnProperty("align"))
  state.lexical.align = true;
  if (tcat == "prefix") return style;
  if (!content) content = stream.current();
  return parse(state, stream, style);
  },
 
  indent: function(state, textAfter) {
  if (state.tokenize != tokenBase) return 0;
  var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
  type = lexical.type, closing = firstChar == type;
  if (type == "stat") return lexical.indented + indentUnit;
  if (lexical.align) return lexical.column + (closing ? 0 : 1);
  return lexical.indented + (closing ? 0 : (lexical.info == "alt" ? altIndentUnit : indentUnit));
  },
 
  electricChars: "{}"
  };
  });
 
  CodeMirror.defineMIME("text/x-rustsrc", "rust");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Scheme mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="scheme.js"></script>
  <style>.CodeMirror {background: #f8f8f8;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Scheme mode</h1>
  <form><textarea id="code" name="code">
  ; See if the input starts with a given symbol.
  (define (match-symbol input pattern)
  (cond ((null? (remain input)) #f)
  ((eqv? (car (remain input)) pattern) (r-cdr input))
  (else #f)))
 
  ; Allow the input to start with one of a list of patterns.
  (define (match-or input pattern)
  (cond ((null? pattern) #f)
  ((match-pattern input (car pattern)))
  (else (match-or input (cdr pattern)))))
 
  ; Allow a sequence of patterns.
  (define (match-seq input pattern)
  (if (null? pattern)
  input
  (let ((match (match-pattern input (car pattern))))
  (if match (match-seq match (cdr pattern)) #f))))
 
  ; Match with the pattern but no problem if it does not match.
  (define (match-opt input pattern)
  (let ((match (match-pattern input (car pattern))))
  (if match match input)))
 
  ; Match anything (other than '()), until pattern is found. The rather
  ; clumsy form of requiring an ending pattern is needed to decide where
  ; the end of the match is. If none is given, this will match the rest
  ; of the sentence.
  (define (match-any input pattern)
  (cond ((null? (remain input)) #f)
  ((null? pattern) (f-cons (remain input) (clear-remain input)))
  (else
  (let ((accum-any (collector)))
  (define (match-pattern-any input pattern)
  (cond ((null? (remain input)) #f)
  (else (accum-any (car (remain input)))
  (cond ((match-pattern (r-cdr input) pattern))
  (else (match-pattern-any (r-cdr input) pattern))))))
  (let ((retval (match-pattern-any input (car pattern))))
  (if retval
  (f-cons (accum-any) retval)
  #f))))))
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-scheme</code>.</p>
 
  </body>
  </html>
 
  /**
  * Author: Koh Zi Han, based on implementation by Koh Zi Chun
  */
  CodeMirror.defineMode("scheme", function (config, mode) {
  var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
  ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD="keyword";
  var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
 
  function makeKeywords(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
 
  var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
  var indentKeys = makeKeywords("define let letrec let* lambda");
 
 
  function stateStack(indent, type, prev) { // represents a state stack object
  this.indent = indent;
  this.type = type;
  this.prev = prev;
  }
 
  function pushStack(state, indent, type) {
  state.indentStack = new stateStack(indent, type, state.indentStack);
  }
 
  function popStack(state) {
  state.indentStack = state.indentStack.prev;
  }
 
  /**
  * Scheme numbers are complicated unfortunately.
  * Checks if we're looking at a number, which might be possibly a fraction.
  * Also checks that it is not part of a longer identifier. Returns true/false accordingly.
  */
  function isNumber(ch, stream){
  if(/[0-9]/.exec(ch) != null){
  stream.eatWhile(/[0-9]/);
  stream.eat(/\//);
  stream.eatWhile(/[0-9]/);
  if (stream.eol() || !(/[a-zA-Z\-\_\/]/.exec(stream.peek()))) return true;
  stream.backUp(stream.current().length - 1); // undo all the eating
  }
  return false;
  }
 
  return {
  startState: function () {
  return {
  indentStack: null,
  indentation: 0,
  mode: false,
  sExprComment: false
  };
  },
 
  token: function (stream, state) {
  if (state.indentStack == null && stream.sol()) {
  // update indentation, but only if indentStack is empty
  state.indentation = stream.indentation();
  }
 
  // skip spaces
  if (stream.eatSpace()) {
  return null;
  }
  var returnType = null;
 
  switch(state.mode){
  case "string": // multi-line string parsing mode
  var next, escaped = false;
  while ((next = stream.next()) != null) {
  if (next == "\"" && !escaped) {
 
  state.mode = false;
  break;
  }
  escaped = !escaped && next == "\\";
  }
  returnType = STRING; // continue on in scheme-string mode
  break;
  case "comment": // comment parsing mode
  var next, maybeEnd = false;
  while ((next = stream.next()) != null) {
  if (next == "#" && maybeEnd) {
 
  state.mode = false;
  break;
  }
  maybeEnd = (next == "|");
  }
  returnType = COMMENT;
  break;
  case "s-expr-comment": // s-expr commenting mode
  state.mode = false;
  if(stream.peek() == "(" || stream.peek() == "["){
  // actually start scheme s-expr commenting mode
  state.sExprComment = 0;
  }else{
  // if not we just comment the entire of the next token
  stream.eatWhile(/[^/s]/); // eat non spaces
  returnType = COMMENT;
  break;
  }
  default: // default parsing mode
  var ch = stream.next();
 
  if (ch == "\"") {
  state.mode = "string";
  returnType = STRING;
 
  } else if (ch == "'") {
  returnType = ATOM;
  } else if (ch == '#') {
  if (stream.eat("|")) { // Multi-line comment
  state.mode = "comment"; // toggle to comment mode
  returnType = COMMENT;
  } else if (stream.eat(/[tf]/)) { // #t/#f (atom)
  returnType = ATOM;
  } else if (stream.eat(';')) { // S-Expr comment
  state.mode = "s-expr-comment";
  returnType = COMMENT;
  }
 
  } else if (ch == ";") { // comment
  stream.skipToEnd(); // rest of the line is a comment
  returnType = COMMENT;
  } else if (ch == "-"){
 
  if(!isNaN(parseInt(stream.peek()))){
  stream.eatWhile(/[\/0-9]/);
  returnType = NUMBER;
  }else{
  returnType = null;
  }
  } else if (isNumber(ch,stream)){
  returnType = NUMBER;
  } else if (ch == "(" || ch == "[") {
  var keyWord = ''; var indentTemp = stream.column();
  /**
  Either
  (indent-word ..
  (non-indent-word ..
  (;something else, bracket, etc.
  */
 
  while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
  keyWord += letter;
  }
 
  if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
 
  pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  } else { // non-indent word
  // we continue eating the spaces
  stream.eatSpace();
  if (stream.eol() || stream.peek() == ";") {
  // nothing significant after
  // we restart indentation 1 space after
  pushStack(state, indentTemp + 1, ch);
  } else {
  pushStack(state, indentTemp + stream.current().length, ch); // else we match
  }
  }
  stream.backUp(stream.current().length - 1); // undo all the eating
 
  if(typeof state.sExprComment == "number") state.sExprComment++;
 
  returnType = BRACKET;
  } else if (ch == ")" || ch == "]") {
  returnType = BRACKET;
  if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
  popStack(state);
 
  if(typeof state.sExprComment == "number"){
  if(--state.sExprComment == 0){
  returnType = COMMENT; // final closing bracket
  state.sExprComment = false; // turn off s-expr commenting mode
  }
  }
  }
  } else {
  stream.eatWhile(/[\w\$_\-]/);
 
  if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  returnType = BUILTIN;
  }else returnType = null;
  }
  }
  return (typeof state.sExprComment == "number") ? COMMENT : returnType;
  },
 
  indent: function (state, textAfter) {
  if (state.indentStack == null) return state.indentation;
  return state.indentStack.indent;
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-scheme", "scheme");
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Smalltalk mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="smalltalk.js"></script>
  <link rel="stylesheet" href="../../doc/docs.css">
  <style>
  .CodeMirror {border: 2px solid #dee; border-right-width: 10px;}
  .CodeMirror-gutter {border: none; background: #dee;}
  .CodeMirror-gutter pre {color: white; font-weight: bold;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Smalltalk mode</h1>
 
  <form><textarea id="code" name="code">
  "
  This is a test of the Smalltalk code
  "
  Seaside.WAComponent subclass: #MyCounter [
  | count |
  MyCounter class &gt;&gt; canBeRoot [ ^true ]
 
  initialize [
  super initialize.
  count := 0.
  ]
  states [ ^{ self } ]
  renderContentOn: html [
  html heading: count.
  html anchor callback: [ count := count + 1 ]; with: '++'.
  html space.
  html anchor callback: [ count := count - 1 ]; with: '--'.
  ]
  ]
 
  MyCounter registerAsApplication: 'mycounter'
  </textarea></form>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  matchBrackets: true,
  mode: "text/x-stsrc",
  indentUnit: 4
  });
  </script>
 
  <p>Simple Smalltalk mode.</p>
 
  <p><strong>MIME types defined:</strong> <code>text/x-stsrc</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode('smalltalk', function(config, modeConfig) {
 
  var specialChars = /[+\-/\\*~<>=@%|&?!.:;^]/;
  var keywords = /true|false|nil|self|super|thisContext/;
 
  var Context = function(tokenizer, parent) {
  this.next = tokenizer;
  this.parent = parent;
  };
 
  var Token = function(name, context, eos) {
  this.name = name;
  this.context = context;
  this.eos = eos;
  };
 
  var State = function() {
  this.context = new Context(next, null);
  this.expectVariable = true;
  this.indentation = 0;
  this.userIndentationDelta = 0;
  };
 
  State.prototype.userIndent = function(indentation) {
  this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0;
  };
 
  var next = function(stream, context, state) {
  var token = new Token(null, context, false);
  var char = stream.next();
 
  if (char === '"') {
  token = nextComment(stream, new Context(nextComment, context));
 
  } else if (char === '\'') {
  token = nextString(stream, new Context(nextString, context));
 
  } else if (char === '#') {
  stream.eatWhile(/[^ .]/);
  token.name = 'string-2';
 
  } else if (char === '$') {
  stream.eatWhile(/[^ ]/);
  token.name = 'string-2';
 
  } else if (char === '|' && state.expectVariable) {
  token.context = new Context(nextTemporaries, context);
 
  } else if (/[\[\]{}()]/.test(char)) {
  token.name = 'bracket';
  token.eos = /[\[{(]/.test(char);
 
  if (char === '[') {
  state.indentation++;
  } else if (char === ']') {
  state.indentation = Math.max(0, state.indentation - 1);
  }
 
  } else if (specialChars.test(char)) {
  stream.eatWhile(specialChars);
  token.name = 'operator';
  token.eos = char !== ';'; // ; cascaded message expression
 
  } else if (/\d/.test(char)) {
  stream.eatWhile(/[\w\d]/);
  token.name = 'number'
 
  } else if (/[\w_]/.test(char)) {
  stream.eatWhile(/[\w\d_]/);
  token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null;
 
  } else {
  token.eos = state.expectVariable;
  }
 
  return token;
  };
 
  var nextComment = function(stream, context) {
  stream.eatWhile(/[^"]/);
  return new Token('comment', stream.eat('"') ? context.parent : context, true);
  };
 
  var nextString = function(stream, context) {
  stream.eatWhile(/[^']/);
  return new Token('string', stream.eat('\'') ? context.parent : context, false);
  };
 
  var nextTemporaries = function(stream, context, state) {
  var token = new Token(null, context, false);
  var char = stream.next();
 
  if (char === '|') {
  token.context = context.parent;
  token.eos = true;
 
  } else {
  stream.eatWhile(/[^|]/);
  token.name = 'variable';
  }
 
  return token;
  }
 
  return {
  startState: function() {
  return new State;
  },
 
  token: function(stream, state) {
  state.userIndent(stream.indentation());
 
  if (stream.eatSpace()) {
  return null;
  }
 
  var token = state.context.next(stream, state.context, state);
  state.context = token.context;
  state.expectVariable = token.eos;
 
  state.lastToken = token;
  return token.name;
  },
 
  blankLine: function(state) {
  state.userIndent(0);
  },
 
  indent: function(state, textAfter) {
  var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta;
  return (state.indentation + i) * config.indentUnit;
  },
 
  electricChars: ']'
  };
 
  });
 
  CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'});
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: SPARQL mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="sparql.js"></script>
  <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: SPARQL mode</h1>
  <form><textarea id="code" name="code">
  PREFIX a: &lt;http://www.w3.org/2000/10/annotation-ns#>
  PREFIX dc: &lt;http://purl.org/dc/elements/1.1/>
  PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/>
 
  # Comment!
 
  SELECT ?given ?family
  WHERE {
  ?annot a:annotates &lt;http://www.w3.org/TR/rdf-sparql-query/> .
  ?annot dc:creator ?c .
  OPTIONAL {?c foaf:given ?given ;
  foaf:family ?family } .
  FILTER isBlank(?c)
  }
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: "application/x-sparql-query",
  tabMode: "indent",
  matchBrackets: true
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>application/x-sparql-query</code>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("sparql", function(config) {
  var indentUnit = config.indentUnit;
  var curPunc;
 
  function wordRegexp(words) {
  return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }
  var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
  "isblank", "isliteral", "union", "a"]);
  var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
  "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
  "graph", "by", "asc", "desc"]);
  var operatorChars = /[*+\-<>=&|]/;
 
  function tokenBase(stream, state) {
  var ch = stream.next();
  curPunc = null;
  if (ch == "$" || ch == "?") {
  stream.match(/^[\w\d]*/);
  return "variable-2";
  }
  else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
  stream.match(/^[^\s\u00a0>]*>?/);
  return "atom";
  }
  else if (ch == "\"" || ch == "'") {
  state.tokenize = tokenLiteral(ch);
  return state.tokenize(stream, state);
  }
  else if (/[{}\(\),\.;\[\]]/.test(ch)) {
  curPunc = ch;
  return null;
  }
  else if (ch == "#") {
  stream.skipToEnd();
  return "comment";
  }
  else if (operatorChars.test(ch)) {
  stream.eatWhile(operatorChars);
  return null;
  }
  else if (ch == ":") {
  stream.eatWhile(/[\w\d\._\-]/);
  return "atom";
  }
  else {
  stream.eatWhile(/[_\w\d]/);
  if (stream.eat(":")) {
  stream.eatWhile(/[\w\d_\-]/);
  return "atom";
  }
  var word = stream.current(), type;
  if (ops.test(word))
  return null;
  else if (keywords.test(word))
  return "keyword";
  else
  return "variable";
  }
  }
 
  function tokenLiteral(quote) {
  return function(stream, state) {
  var escaped = false, ch;
  while ((ch = stream.next()) != null) {
  if (ch == quote && !escaped) {
  state.tokenize = tokenBase;
  break;
  }
  escaped = !escaped && ch == "\\";
  }
  return "string";
  };
  }
 
  function pushContext(state, type, col) {
  state.context = {prev: state.context, indent: state.indent, col: col, type: type};
  }
  function popContext(state) {
  state.indent = state.context.indent;
  state.context = state.context.prev;
  }
 
  return {
  startState: function(base) {
  return {tokenize: tokenBase,
  context: null,
  indent: 0,
  col: 0};
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  if (state.context && state.context.align == null) state.context.align = false;
  state.indent = stream.indentation();
  }
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
 
  if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
  state.context.align = true;
  }
 
  if (curPunc == "(") pushContext(state, ")", stream.column());
  else if (curPunc == "[") pushContext(state, "]", stream.column());
  else if (curPunc == "{") pushContext(state, "}", stream.column());
  else if (/[\]\}\)]/.test(curPunc)) {
  while (state.context && state.context.type == "pattern") popContext(state);
  if (state.context && curPunc == state.context.type) popContext(state);
  }
  else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
  else if (/atom|string|variable/.test(style) && state.context) {
  if (/[\}\]]/.test(state.context.type))
  pushContext(state, "pattern", stream.column());
  else if (state.context.type == "pattern" && !state.context.align) {
  state.context.align = true;
  state.context.col = stream.column();
  }
  }
 
  return style;
  },
 
  indent: function(state, textAfter) {
  var firstChar = textAfter && textAfter.charAt(0);
  var context = state.context;
  if (/[\]\}]/.test(firstChar))
  while (context && context.type == "pattern") context = context.prev;
 
  var closing = context && firstChar == context.type;
  if (!context)
  return 0;
  else if (context.type == "pattern")
  return context.col;
  else if (context.align)
  return context.col + (closing ? 0 : 1);
  else
  return context.indent + (closing ? 0 : indentUnit);
  }
  };
  });
 
  CodeMirror.defineMIME("application/x-sparql-query", "sparql");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: sTeX mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="stex.js"></script>
  <style>.CodeMirror {background: #f8f8f8;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: sTeX mode</h1>
  <form><textarea id="code" name="code">
  \begin{module}[id=bbt-size]
  \importmodule[balanced-binary-trees]{balanced-binary-trees}
  \importmodule[\KWARCslides{dmath/en/cardinality}]{cardinality}
 
  \begin{frame}
  \frametitle{Size Lemma for Balanced Trees}
  \begin{itemize}
  \item
  \begin{assertion}[id=size-lemma,type=lemma]
  Let $G=\tup{V,E}$ be a \termref[cd=binary-trees]{balanced binary tree}
  of \termref[cd=graph-depth,name=vertex-depth]{depth}$n>i$, then the set
  $\defeq{\livar{V}i}{\setst{\inset{v}{V}}{\gdepth{v} = i}}$ of
  \termref[cd=graphs-intro,name=node]{nodes} at
  \termref[cd=graph-depth,name=vertex-depth]{depth} $i$ has
  \termref[cd=cardinality,name=cardinality]{cardinality} $\power2i$.
  \end{assertion}
  \item
  \begin{sproof}[id=size-lemma-pf,proofend=,for=size-lemma]{via induction over the depth $i$.}
  \begin{spfcases}{We have to consider two cases}
  \begin{spfcase}{$i=0$}
  \begin{spfstep}[display=flow]
  then $\livar{V}i=\set{\livar{v}r}$, where $\livar{v}r$ is the root, so
  $\eq{\card{\livar{V}0},\card{\set{\livar{v}r}},1,\power20}$.
  \end{spfstep}
  \end{spfcase}
  \begin{spfcase}{$i>0$}
  \begin{spfstep}[display=flow]
  then $\livar{V}{i-1}$ contains $\power2{i-1}$ vertexes
  \begin{justification}[method=byIH](IH)\end{justification}
  \end{spfstep}
  \begin{spfstep}
  By the \begin{justification}[method=byDef]definition of a binary
  tree\end{justification}, each $\inset{v}{\livar{V}{i-1}}$ is a leaf or has
  two children that are at depth $i$.
  \end{spfstep}
  \begin{spfstep}
  As $G$ is \termref[cd=balanced-binary-trees,name=balanced-binary-tree]{balanced} and $\gdepth{G}=n>i$, $\livar{V}{i-1}$ cannot contain
  leaves.
  \end{spfstep}
  \begin{spfstep}[type=conclusion]
  Thus $\eq{\card{\livar{V}i},{\atimes[cdot]{2,\card{\livar{V}{i-1}}}},{\atimes[cdot]{2,\power2{i-1}}},\power2i}$.
  \end{spfstep}
  \end{spfcase}
  \end{spfcases}
  \end{sproof}
  \item
  \begin{assertion}[id=fbbt,type=corollary]
  A fully balanced tree of depth $d$ has $\power2{d+1}-1$ nodes.
  \end{assertion}
  \item
  \begin{sproof}[for=fbbt,id=fbbt-pf]{}
  \begin{spfstep}
  Let $\defeq{G}{\tup{V,E}}$ be a fully balanced tree
  \end{spfstep}
  \begin{spfstep}
  Then $\card{V}=\Sumfromto{i}1d{\power2i}= \power2{d+1}-1$.
  \end{spfstep}
  \end{sproof}
  \end{itemize}
  \end{frame}
  \begin{note}
  \begin{omtext}[type=conclusion,for=binary-tree]
  This shows that balanced binary trees grow in breadth very quickly, a consequence of
  this is that they are very shallow (and this compute very fast), which is the essence of
  the next result.
  \end{omtext}
  \end{note}
  \end{module}
 
  %%% Local Variables:
  %%% mode: LaTeX
  %%% TeX-master: "all"
  %%% End: \end{document}
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/stex</code>.</p>
 
  </body>
  </html>
 
  /*
  * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
  * Licence: MIT
  */
 
  CodeMirror.defineMode("stex", function(cmCfg, modeCfg)
  {
  function pushCommand(state, command) {
  state.cmdState.push(command);
  }
 
  function peekCommand(state) {
  if (state.cmdState.length>0)
  return state.cmdState[state.cmdState.length-1];
  else
  return null;
  }
 
  function popCommand(state) {
  if (state.cmdState.length>0) {
  var plug = state.cmdState.pop();
  plug.closeBracket();
  }
  }
 
  function applyMostPowerful(state) {
  var context = state.cmdState;
  for (var i = context.length - 1; i >= 0; i--) {
  var plug = context[i];
  if (plug.name=="DEFAULT")
  continue;
  return plug.styleIdentifier();
  }
  return null;
  }
 
  function addPluginPattern(pluginName, cmdStyle, brackets, styles) {
  return function () {
  this.name=pluginName;
  this.bracketNo = 0;
  this.style=cmdStyle;
  this.styles = styles;
  this.brackets = brackets;
 
  this.styleIdentifier = function(content) {
  if (this.bracketNo<=this.styles.length)
  return this.styles[this.bracketNo-1];
  else
  return null;
  };
  this.openBracket = function(content) {
  this.bracketNo++;
  return "bracket";
  };
  this.closeBracket = function(content) {
  };
  }
  }
 
  var plugins = new Array();
 
  plugins["importmodule"] = addPluginPattern("importmodule", "tag", "{[", ["string", "builtin"]);
  plugins["documentclass"] = addPluginPattern("documentclass", "tag", "{[", ["", "atom"]);
  plugins["usepackage"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
  plugins["begin"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
  plugins["end"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
 
  plugins["DEFAULT"] = function () {
  this.name="DEFAULT";
  this.style="tag";
 
  this.styleIdentifier = function(content) {
  };
  this.openBracket = function(content) {
  };
  this.closeBracket = function(content) {
  };
  };
 
  function setState(state, f) {
  state.f = f;
  }
 
  function normal(source, state) {
  if (source.match(/^\\[a-z]+/)) {
  var cmdName = source.current();
  cmdName = cmdName.substr(1, cmdName.length-1);
  var plug = plugins[cmdName];
  if (typeof(plug) == 'undefined') {
  plug = plugins["DEFAULT"];
  }
  plug = new plug();
  pushCommand(state, plug);
  setState(state, beginParams);
  return plug.style;
  }
 
  var ch = source.next();
  if (ch == "%") {
  setState(state, inCComment);
  return "comment";
  }
  else if (ch=='}' || ch==']') {
  plug = peekCommand(state);
  if (plug) {
  plug.closeBracket(ch);
  setState(state, beginParams);
  } else
  return "error";
  return "bracket";
  } else if (ch=='{' || ch=='[') {
  plug = plugins["DEFAULT"];
  plug = new plug();
  pushCommand(state, plug);
  return "bracket";
  }
  else if (/\d/.test(ch)) {
  source.eatWhile(/[\w.%]/);
  return "atom";
  }
  else {
  source.eatWhile(/[\w-_]/);
  return applyMostPowerful(state);
  }
  }
 
  function inCComment(source, state) {
  source.skipToEnd();
  setState(state, normal);
  return "comment";
  }
 
  function beginParams(source, state) {
  var ch = source.peek();
  if (ch == '{' || ch == '[') {
  var lastPlug = peekCommand(state);
  var style = lastPlug.openBracket(ch);
  source.eat(ch);
  setState(state, normal);
  return "bracket";
  }
  if (/[ \t\r]/.test(ch)) {
  source.eat(ch);
  return null;
  }
  setState(state, normal);
  lastPlug = peekCommand(state);
  if (lastPlug) {
  popCommand(state);
  }
  return normal(source, state);
  }
 
  return {
  startState: function() { return { f:normal, cmdState:[] }; },
  copyState: function(s) { return { f: s.f, cmdState: s.cmdState.slice(0, s.cmdState.length) }; },
 
  token: function(stream, state) {
  var t = state.f(stream, state);
  var w = stream.current();
  return t;
  }
  };
  });
 
 
  CodeMirror.defineMIME("text/x-stex", "stex");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: TiddlyWiki mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="tiddlywiki.js"></script>
  <link rel="stylesheet" href="tiddlywiki.css">
  <link rel="stylesheet" href="../../doc/docs.css">
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  </head>
  <body>
  <h1>CodeMirror: TiddlyWiki mode</h1>
 
  <div><textarea id="code" name="code">
  !TiddlyWiki Formatting
  * Rendered versions can be found at: http://www.tiddlywiki.com/#Reference
 
  |!Option|!Syntax|!Output|
  |bold font|{{{''bold''}}}|''bold''|
  |italic type|{{{//italic//}}}|//italic//|
  |underlined text|{{{__underlined__}}}|__underlined__|
  |strikethrough text|{{{--strikethrough--}}}|--strikethrough--|
  |superscript text|{{{^^super^^script}}}|^^super^^script|
  |subscript text|{{{~~sub~~script}}}|~~sub~~script|
  |highlighted text|{{{@@highlighted@@}}}|@@highlighted@@|
  |preformatted text|<html><code>{{{preformatted}}}</code></html>|{{{preformatted}}}|
 
  !Block Elements
  !!Headings
  {{{
  !Heading 1
  !!Heading 2
  !!!Heading 3
  !!!!Heading 4
  !!!!!Heading 5
  }}}
  <<<
 
  !Heading 1
 
  !!Heading 2
 
  !!!Heading 3
 
  !!!!Heading 4
 
  !!!!!Heading 5
  <<<
 
  !!Lists
  {{{
  * unordered list, level 1
  ** unordered list, level 2
  *** unordered list, level 3
 
  # ordered list, level 1
  ## ordered list, level 2
  ### unordered list, level 3
 
  ; definition list, term
  : definition list, description
  }}}
  <<<
  * unordered list, level 1
  ** unordered list, level 2
  *** unordered list, level 3
 
  # ordered list, level 1
  ## ordered list, level 2
  ### unordered list, level 3
 
  ; definition list, term
  : definition list, description
  <<<
 
  !!Blockquotes
  {{{
  > blockquote, level 1
  >> blockquote, level 2
  >>> blockquote, level 3
 
  <<<
  blockquote
  <<<
  }}}
  <<<
  > blockquote, level 1
  >> blockquote, level 2
  >>> blockquote, level 3
 
  > blockquote
  <<<
 
  !!Preformatted Text
  <html><pre>
  {{{
  preformatted (e.g. code)
  }}}
  </pre></html>
  <<<
  {{{
  preformatted (e.g. code)
  }}}
  <<<
 
  !!Code Sections
  {{{
  Text style code
  }}}
 
  //{{{
  JS styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
  //}}}
 
  <!--{{{-->
  XML styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
  <!--}}}-->
 
  !!Tables
  {{{
  |CssClass|k
  |!heading column 1|!heading column 2|
  |row 1, column 1|row 1, column 2|
  |row 2, column 1|row 2, column 2|
  |>|COLSPAN|
  |ROWSPAN| ... |
  |~| ... |
  |CssProperty:value;...| ... |
  |caption|c
  }}}
  ''Annotation:''
  * The {{{>}}} marker creates a "colspan", causing the current cell to merge with the one to the right.
  * The {{{~}}} marker creates a "rowspan", causing the current cell to merge with the one above.
  <<<
  |CssClass|k
  |!heading column 1|!heading column 2|
  |row 1, column 1|row 1, column 2|
  |row 2, column 1|row 2, column 2|
  |>|COLSPAN|
  |ROWSPAN| ... |
  |~| ... |
  |CssProperty:value;...| ... |
  |caption|c
  <<<
  !!Images /% TODO %/
  cf. [[TiddlyWiki.com|http://www.tiddlywiki.com/#EmbeddedImages]]
 
  !Hyperlinks
  * [[WikiWords|WikiWord]] are automatically transformed to hyperlinks to the respective tiddler
  ** the automatic transformation can be suppressed by preceding the respective WikiWord with a tilde ({{{~}}}): {{{~WikiWord}}}
  * [[PrettyLinks]] are enclosed in square brackets and contain the desired tiddler name: {{{[[tiddler name]]}}}
  ** optionally, a custom title or description can be added, separated by a pipe character ({{{|}}}): {{{[[title|target]]}}}<br>'''N.B.:''' In this case, the target can also be any website (i.e. URL).
 
  !Custom Styling
  * {{{@@CssProperty:value;CssProperty:value;...@@}}}<br>''N.B.:'' CSS color definitions should use lowercase letters to prevent the inadvertent creation of WikiWords.
  * <html><code>{{customCssClass{...}}}</code></html>
  * raw HTML can be inserted by enclosing the respective code in HTML tags: {{{<html> ... </html>}}}
 
  !Special Markers
  * {{{<br>}}} forces a manual line break
  * {{{----}}} creates a horizontal ruler
  * [[HTML entities|http://www.tiddlywiki.com/#HtmlEntities]]
  * [[HTML entities local|HtmlEntities]]
  * {{{<<macroName>>}}} calls the respective [[macro|Macros]]
  * To hide text within a tiddler so that it is not displayed, it can be wrapped in {{{/%}}} and {{{%/}}}.<br/>This can be a useful trick for hiding drafts or annotating complex markup.
  * To prevent wiki markup from taking effect for a particular section, that section can be enclosed in three double quotes: e.g. {{{"""WikiWord"""}}}.
  </textarea></div>
 
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: 'tiddlywiki',
  lineNumbers: true,
  enterMode: 'keep',
  matchBrackets: true
  });
  </script>
 
  <p>TiddlyWiki mode supports a single configuration.</p>
 
  <p><strong>MIME types defined:</strong> <code>text/x-tiddlywiki</code>.</p>
  </body>
  </html>
 
  .cm-s-default span.cm-header {color: blue; font-weight:bold;}
  .cm-s-default span.cm-code {color: #a50;}
  .cm-s-default span.cm-code-inline {color: #660;}
 
  .cm-s-default span.cm-quote {color: #555;}
  .cm-s-default span.cm-list {color: #c60;}
  .cm-s-default span.cm-hr {color: #999;}
  .cm-s-default span.cm-em {font-style: italic;}
  .cm-s-default span.cm-strong {font-weight: bold;}
 
  .cm-s-default span.cm-link-external {color: blue;}
  .cm-s-default span.cm-brace {color: #170; font-weight: bold;}
  .cm-s-default span.cm-macro {color: #9E3825;}
  .cm-s-default span.cm-table {color: blue;}
  .cm-s-default span.cm-warning {color: red; font-weight: bold;}
 
  .cm-s-default span.cm-underlined {text-decoration: underline;}
  .cm-s-default span.cm-line-through {text-decoration: line-through;}
 
  .cm-s-default span.cm-comment {color: #666;}
 
 
  /***
  |''Name''|tiddlywiki.js|
  |''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror2|
  |''Author''|PMario|
  |''Version''|0.1.6|
  |''Status''|''beta''|
  |''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]|
  |''Documentation''|http://codemirror.tiddlyspace.com/|
  |''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]|
  |''CoreVersion''|2.5.0|
  |''Requires''|codemirror.js|
  |''Keywords''|syntax highlighting color code mirror codemirror|
  ! Info
  CoreVersion parameter is needed for TiddlyWiki only!
  ***/
  //{{{
  CodeMirror.defineMode("tiddlywiki", function (config, parserConfig) {
  var indentUnit = config.indentUnit;
 
  // Tokenizer
  var textwords = function () {
  function kw(type) {
  return {
  type: type,
  style: "text"
  };
  }
  return {};
  }();
 
  var keywords = function () {
  function kw(type) {
  return { type: type, style: "macro"};
  }
  return {
  "allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'),
  "newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'),
  "permaview": kw('permaview'), "saveChanges": kw('saveChanges'),
  "search": kw('search'), "slider": kw('slider'), "tabs": kw('tabs'),
  "tag": kw('tag'), "tagging": kw('tagging'), "tags": kw('tags'),
  "tiddler": kw('tiddler'), "timeline": kw('timeline'),
  "today": kw('today'), "version": kw('version'), "option": kw('option'),
 
  "with": kw('with'),
  "filter": kw('filter')
  };
  }();
 
  var isSpaceName = /[\w_\-]/i,
  reHR = /^\-\-\-\-+$/,
  reWikiCommentStart = /^\/\*\*\*$/, // /***
  reWikiCommentStop = /^\*\*\*\/$/, // ***/
  reBlockQuote = /^<<<$/,
 
  reJsCodeStart = /^\/\/\{\{\{$/, // //{{{
  reJsCodeStop = /^\/\/\}\}\}$/, // //}}}
  reXmlCodeStart = /^<!--\{\{\{-->$/,
  reXmlCodeStop = /^<!--\}\}\}-->$/,
 
  reCodeBlockStart = /^\{\{\{$/,
  reCodeBlockStop = /^\}\}\}$/,
 
  reCodeStart = /\{\{\{/,
  reUntilCodeStop = /.*?\}\}\}/;
 
  function chain(stream, state, f) {
  state.tokenize = f;
  return f(stream, state);
  }
 
  // used for strings
  function nextUntilUnescaped(stream, end) {
  var escaped = false,
  next;
  while ((next = stream.next()) != null) {
  if (next == end && !escaped) return false;
  escaped = !escaped && next == "\\";
  }
  return escaped;
  }
 
  // Used as scratch variables to communicate multiple values without
  // consing up tons of objects.
  var type, content;
 
  function ret(tp, style, cont) {
  type = tp;
  content = cont;
  return style;
  }
 
  function jsTokenBase(stream, state) {
  var sol = stream.sol(),
  ch, tch;
 
  state.block = false; // indicates the start of a code block.
 
  ch = stream.peek(); // don't eat, to make match simpler
 
  // check start of blocks
  if (sol && /[<\/\*{}\-]/.test(ch)) {
  if (stream.match(reCodeBlockStart)) {
  state.block = true;
  return chain(stream, state, twTokenCode);
  }
  if (stream.match(reBlockQuote)) {
  return ret('quote', 'quote');
  }
  if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) {
  return ret('code', 'code');
  }
  if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) {
  return ret('code', 'code');
  }
  if (stream.match(reHR)) {
  return ret('hr', 'hr');
  }
  } // sol
  var ch = stream.next();
 
  if (sol && /[\/\*!#;:>|]/.test(ch)) {
  if (ch == "!") { // tw header
  stream.skipToEnd();
  return ret("header", "header");
  }
  if (ch == "*") { // tw list
  stream.eatWhile('*');
  return ret("list", "list");
  }
  if (ch == "#") { // tw numbered list
  stream.eatWhile('#');
  return ret("list", "list");
  }
  if (ch == ";") { // tw list
  stream.eatWhile(';');
  return ret("list", "list");
  }
  if (ch == ":") { // tw list
  stream.eatWhile(':');
  return ret("list", "list");
  }
  if (ch == ">") { // single line quote
  stream.eatWhile(">");
  return ret("quote", "quote");
  }
  if (ch == '|') {
  return ret('table', 'table');
  }
  }
 
  if (ch == '{' && stream.match(/\{\{/)) {
  return chain(stream, state, twTokenCode);
  }
 
  // rudimentary html:// file:// link matching. TW knows much more ...
  if (/[hf]/i.test(ch)) {
  if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) {
  return ret("link-external", "link-external");
  }
  }
  // just a little string indicator, don't want to have the whole string covered
  if (ch == '"') {
  return ret('string', 'string');
  }
  if (/[\[\]]/.test(ch)) { // check for [[..]]
  if (stream.peek() == ch) {
  stream.next();
  return ret('brace', 'brace');
  }
  }
  if (ch == "@") { // check for space link. TODO fix @@...@@ highlighting
  stream.eatWhile(isSpaceName);
  return ret("link-external", "link-external");
  }
  if (/\d/.test(ch)) { // numbers
  stream.eatWhile(/\d/);
  return ret("number", "number");
  }
  if (ch == "/") { // tw invisible comment
  if (stream.eat("%")) {
  return chain(stream, state, twTokenComment);
  }
  else if (stream.eat("/")) { //
  return chain(stream, state, twTokenEm);
  }
  }
  if (ch == "_") { // tw underline
  if (stream.eat("_")) {
  return chain(stream, state, twTokenUnderline);
  }
  }
  if (ch == "-") { // tw strikethrough TODO looks ugly .. different handling see below;
  if (stream.eat("-")) {
  return chain(stream, state, twTokenStrike);
  }
  }
  if (ch == "'") { // tw bold
  if (stream.eat("'")) {
  return chain(stream, state, twTokenStrong);
  }
  }
  if (ch == "<") { // tw macro
  if (stream.eat("<")) {
  return chain(stream, state, twTokenMacro);
  }
  }
  else {
  return ret(ch);
  }
 
  stream.eatWhile(/[\w\$_]/);
  var word = stream.current(),
  known = textwords.propertyIsEnumerable(word) && textwords[word];
 
  return known ? ret(known.type, known.style, word) : ret("text", null, word);
 
  } // jsTokenBase()
 
  function twTokenString(quote) {
  return function (stream, state) {
  if (!nextUntilUnescaped(stream, quote)) state.tokenize = jsTokenBase;
  return ret("string", "string");
  };
  }
 
  // tw invisible comment
  function twTokenComment(stream, state) {
  var maybeEnd = false,
  ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "%");
  }
  return ret("comment", "comment");
  }
 
  // tw strong / bold
  function twTokenStrong(stream, state) {
  var maybeEnd = false,
  ch;
  while (ch = stream.next()) {
  if (ch == "'" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "'");
  }
  return ret("text", "strong");
  }
 
  // tw code
  function twTokenCode(stream, state) {
  var ch, sb = state.block;
 
  if (sb && stream.current()) {
  return ret("code", "code");
  }
 
  if (!sb && stream.match(reUntilCodeStop)) {
  state.tokenize = jsTokenBase;
  return ret("code", "code-inline");
  }
 
  if (sb && stream.sol() && stream.match(reCodeBlockStop)) {
  state.tokenize = jsTokenBase;
  return ret("code", "code");
  }
 
  ch = stream.next();
  return (sb) ? ret("code", "code") : ret("code", "code-inline");
  }
 
  // tw em / italic
  function twTokenEm(stream, state) {
  var maybeEnd = false,
  ch;
  while (ch = stream.next()) {
  if (ch == "/" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "/");
  }
  return ret("text", "em");
  }
 
  // tw underlined text
  function twTokenUnderline(stream, state) {
  var maybeEnd = false,
  ch;
  while (ch = stream.next()) {
  if (ch == "_" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "_");
  }
  return ret("text", "underlined");
  }
 
  // tw strike through text looks ugly
  // TODO just strike through the first and last 2 chars if possible.
  function twTokenStrike(stream, state) {
  var maybeEnd = false,
  ch, nr;
 
  while (ch = stream.next()) {
  if (ch == "-" && maybeEnd) {
  state.tokenize = jsTokenBase;
  break;
  }
  maybeEnd = (ch == "-");
  }
  return ret("text", "line-through");
  }
 
  // macro
  function twTokenMacro(stream, state) {
  var ch, tmp, word, known;
 
  if (stream.current() == '<<') {
  return ret('brace', 'macro');
  }
 
  ch = stream.next();
  if (!ch) {
  state.tokenize = jsTokenBase;
  return ret(ch);
  }
  if (ch == ">") {
  if (stream.peek() == '>') {
  stream.next();
  state.tokenize = jsTokenBase;
  return ret("brace", "macro");
  }
  }
 
  stream.eatWhile(/[\w\$_]/);
  word = stream.current();
  known = keywords.propertyIsEnumerable(word) && keywords[word];
 
  if (known) {
  return ret(known.type, known.style, word);
  }
  else {
  return ret("macro", null, word);
  }
  }
 
  // Interface
  return {
  startState: function (basecolumn) {
  return {
  tokenize: jsTokenBase,
  indented: 0,
  level: 0
  };
  },
 
  token: function (stream, state) {
  if (stream.eatSpace()) return null;
  var style = state.tokenize(stream, state);
  return style;
  },
 
  electricChars: ""
  };
  });
 
  CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki");
  //}}}
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Velocity mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="velocity.js"></script>
  <link rel="stylesheet" href="../../theme/night.css">
  <style>.CodeMirror {border: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: Velocity mode</h1>
  <form><textarea id="code" name="code">
  ## Velocity Code Demo
  #*
  based on PL/SQL mode by Peter Raganitsch, adapted to Velocity by Steve O'Hara ( http://www.pivotal-solutions.co.uk )
  August 2011
  *#
 
  #*
  This is a multiline comment.
  This is the second line
  *#
 
  #[[ hello steve
  This has invalid syntax that would normally need "poor man's escaping" like:
 
  #define()
 
  ${blah
  ]]#
 
  #include( "disclaimer.txt" "opinion.txt" )
  #include( $foo $bar )
 
  #parse( "lecorbusier.vm" )
  #parse( $foo )
 
  #evaluate( 'string with VTL #if(true)will be displayed#end' )
 
  #define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!
 
  #foreach( $customer in $customerList )
 
  $foreach.count $customer.Name
 
  #if( $foo == ${bar})
  it's true!
  #break
  #{else}
  it's not!
  #stop
  #end
 
  #if ($foreach.parent.hasNext)
  $velocityCount
  #end
  #end
 
  $someObject.getValues("this is a string split
  across lines")
 
  #macro( tablerows $color $somelist )
  #foreach( $something in $somelist )
  <tr><td bgcolor=$color>$something</td></tr>
  #end
  #end
 
  #tablerows("red" ["dadsdf","dsa"])
 
  Variable reference: #set( $monkey = $bill )
  String literal: #set( $monkey.Friend = 'monica' )
  Property reference: #set( $monkey.Blame = $whitehouse.Leak )
  Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )
  Number literal: #set( $monkey.Number = 123 )
  Range operator: #set( $monkey.Numbers = [1..3] )
  Object list: #set( $monkey.Say = ["Not", $my, "fault"] )
  Object map: #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})
 
  The RHS can also be a simple arithmetic expression, such as:
  Addition: #set( $value = $foo + 1 )
  Subtraction: #set( $value = $bar - 1 )
  Multiplication: #set( $value = $foo * $bar )
  Division: #set( $value = $foo / $bar )
  Remainder: #set( $value = $foo % $bar )
 
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  tabMode: "indent",
  matchBrackets: true,
  theme: "night",
  lineNumbers: true,
  indentUnit: 4,
  mode: "text/velocity"
  });
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("velocity", function(config) {
  function parseWords(str) {
  var obj = {}, words = str.split(" ");
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  return obj;
  }
 
  var indentUnit = config.indentUnit
  var keywords = parseWords("#end #else #break #stop #[[ #]] " +
  "#{end} #{else} #{break} #{stop}");
  var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " +
  "#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}");
  var specials = parseWords("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent $velocityCount");
  var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
  var multiLineStrings =true;
 
  function chain(stream, state, f) {
  state.tokenize = f;
  return f(stream, state);
  }
  function tokenBase(stream, state) {
  var beforeParams = state.beforeParams;
  state.beforeParams = false;
  var ch = stream.next();
  // start of string?
  if ((ch == '"' || ch == "'") && state.inParams)
  return chain(stream, state, tokenString(ch));
  // is it one of the special signs []{}().,;? Seperator?
  else if (/[\[\]{}\(\),;\.]/.test(ch)) {
  if (ch == "(" && beforeParams) state.inParams = true;
  else if (ch == ")") state.inParams = false;
  return null;
  }
  // start of a number value?
  else if (/\d/.test(ch)) {
  stream.eatWhile(/[\w\.]/);
  return "number";
  }
  // multi line comment?
  else if (ch == "#" && stream.eat("*")) {
  return chain(stream, state, tokenComment);
  }
  // unparsed content?
  else if (ch == "#" && stream.match(/ *\[ *\[/)) {
  return chain(stream, state, tokenUnparsed);
  }
  // single line comment?
  else if (ch == "#" && stream.eat("#")) {
  stream.skipToEnd();
  return "comment";
  }
  // variable?
  else if (ch == "$") {
  stream.eatWhile(/[\w\d\$_\.{}]/);
  // is it one of the specials?
  if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
  return "keyword";
  }
  else {
  state.beforeParams = true;
  return "builtin";
  }
  }
  // is it a operator?
  else if (isOperatorChar.test(ch)) {
  stream.eatWhile(isOperatorChar);
  return "operator";
  }
  else {
  // get the whole word
  stream.eatWhile(/[\w\$_{}]/);
  var word = stream.current().toLowerCase();
  // is it one of the listed keywords?
  if (keywords && keywords.propertyIsEnumerable(word))
  return "keyword";
  // is it one of the listed functions?
  if (functions && functions.propertyIsEnumerable(word) ||
  stream.current().match(/^#[a-z0-9_]+ *$/i) && stream.peek()=="(") {
  state.beforeParams = true;
  return "keyword";
  }
  // default: just a "word"
  return null;
  }
  }
 
  function tokenString(quote) {
  return function(stream, state) {
  var escaped = false, next, end = false;
  while ((next = stream.next()) != null) {
  if (next == quote && !escaped) {
  end = true;
  break;
  }
  escaped = !escaped && next == "\\";
  }
  if (end) state.tokenize = tokenBase;
  return "string";
  };
  }
 
  function tokenComment(stream, state) {
  var maybeEnd = false, ch;
  while (ch = stream.next()) {
  if (ch == "#" && maybeEnd) {
  state.tokenize = tokenBase;
  break;
  }
  maybeEnd = (ch == "*");
  }
  return "comment";
  }
 
  function tokenUnparsed(stream, state) {
  var maybeEnd = 0, ch;
  while (ch = stream.next()) {
  if (ch == "#" && maybeEnd == 2) {
  state.tokenize = tokenBase;
  break;
  }
  if (ch == "]")
  maybeEnd++;
  else if (ch != " ")
  maybeEnd = 0;
  }
  return "meta";
  }
  // Interface
 
  return {
  startState: function(basecolumn) {
  return {
  tokenize: tokenBase,
  beforeParams: false,
  inParams: false
  };
  },
 
  token: function(stream, state) {
  if (stream.eatSpace()) return null;
  return state.tokenize(stream, state);
  }
  };
  });
 
  CodeMirror.defineMIME("text/velocity", "velocity");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: XML mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="xml.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: XML mode</h1>
  <form><textarea id="code" name="code">
  &lt;html style="color: green"&gt;
  &lt;!-- this is a comment --&gt;
  &lt;head&gt;
  &lt;title&gt;HTML Example&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
  I mean&amp;quot;&lt;/em&gt;... but might not match your style.
  &lt;/body&gt;
  &lt;/html&gt;
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: {name: "xml", alignCDATA: true},
  lineNumbers: true
  });
  </script>
  <p>The XML mode supports two configuration parameters:</p>
  <dl>
  <dt><code>htmlMode (boolean)</code></dt>
  <dd>This switches the mode to parse HTML instead of XML. This
  means attributes do not have to be quoted, and some elements
  (such as <code>br</code>) do not require a closing tag.</dd>
  <dt><code>alignCDATA (boolean)</code></dt>
  <dd>Setting this to true will force the opening tag of CDATA
  blocks to not be indented.</dd>
  </dl>
 
  <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>
  </body>
  </html>
 
  CodeMirror.defineMode("xml", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var Kludges = parserConfig.htmlMode ? {
  autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
  "meta": true, "col": true, "frame": true, "base": true, "area": true},
  doNotIndent: {"pre": true},
  allowUnquoted: true
  } : {autoSelfClosers: {}, doNotIndent: {}, allowUnquoted: false};
  var alignCDATA = parserConfig.alignCDATA;
 
  // Return variables for tokenizers
  var tagName, type;
 
  function inText(stream, state) {
  function chain(parser) {
  state.tokenize = parser;
  return parser(stream, state);
  }
 
  var ch = stream.next();
  if (ch == "<") {
  if (stream.eat("!")) {
  if (stream.eat("[")) {
  if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  else return null;
  }
  else if (stream.match("--")) return chain(inBlock("comment", "-->"));
  else if (stream.match("DOCTYPE", true, true)) {
  stream.eatWhile(/[\w\._\-]/);
  return chain(doctype(1));
  }
  else return null;
  }
  else if (stream.eat("?")) {
  stream.eatWhile(/[\w\._\-]/);
  state.tokenize = inBlock("meta", "?>");
  return "meta";
  }
  else {
  type = stream.eat("/") ? "closeTag" : "openTag";
  stream.eatSpace();
  tagName = "";
  var c;
  while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
  state.tokenize = inTag;
  return "tag";
  }
  }
  else if (ch == "&") {
  stream.eatWhile(/[^;]/);
  stream.eat(";");
  return "atom";
  }
  else {
  stream.eatWhile(/[^&<]/);
  return null;
  }
  }
 
  function inTag(stream, state) {
  var ch = stream.next();
  if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  state.tokenize = inText;
  type = ch == ">" ? "endTag" : "selfcloseTag";
  return "tag";
  }
  else if (ch == "=") {
  type = "equals";
  return null;
  }
  else if (/[\'\"]/.test(ch)) {
  state.tokenize = inAttribute(ch);
  return state.tokenize(stream, state);
  }
  else {
  stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
  return "word";
  }
  }
 
  function inAttribute(quote) {
  return function(stream, state) {
  while (!stream.eol()) {
  if (stream.next() == quote) {
  state.tokenize = inTag;
  break;
  }
  }
  return "string";
  };
  }
 
  function inBlock(style, terminator) {
  return function(stream, state) {
  while (!stream.eol()) {
  if (stream.match(terminator)) {
  state.tokenize = inText;
  break;
  }
  stream.next();
  }
  return style;
  };
  }
  function doctype(depth) {
  return function(stream, state) {
  var ch;
  while ((ch = stream.next()) != null) {
  if (ch == "<") {
  state.tokenize = doctype(depth + 1);
  return state.tokenize(stream, state);
  } else if (ch == ">") {
  if (depth == 1) {
  state.tokenize = inText;
  break;
  } else {
  state.tokenize = doctype(depth - 1);
  return state.tokenize(stream, state);
  }
  }
  }
  return "meta";
  };
  }
 
  var curState, setStyle;
  function pass() {
  for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
  }
  function cont() {
  pass.apply(null, arguments);
  return true;
  }
 
  function pushContext(tagName, startOfLine) {
  var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
  curState.context = {
  prev: curState.context,
  tagName: tagName,
  indent: curState.indented,
  startOfLine: startOfLine,
  noIndent: noIndent
  };
  }
  function popContext() {
  if (curState.context) curState.context = curState.context.prev;
  }
 
  function element(type) {
  if (type == "openTag") {
  curState.tagName = tagName;
  return cont(attributes, endtag(curState.startOfLine));
  } else if (type == "closeTag") {
  var err = false;
  if (curState.context) {
  err = curState.context.tagName != tagName;
  } else {
  err = true;
  }
  if (err) setStyle = "error";
  return cont(endclosetag(err));
  }
  return cont();
  }
  function endtag(startOfLine) {
  return function(type) {
  if (type == "selfcloseTag" ||
  (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase())))
  return cont();
  if (type == "endTag") {pushContext(curState.tagName, startOfLine); return cont();}
  return cont();
  };
  }
  function endclosetag(err) {
  return function(type) {
  if (err) setStyle = "error";
  if (type == "endTag") { popContext(); return cont(); }
  setStyle = "error";
  return cont(arguments.callee);
  }
  }
 
  function attributes(type) {
  if (type == "word") {setStyle = "attribute"; return cont(attributes);}
  if (type == "equals") return cont(attvalue, attributes);
  if (type == "string") {setStyle = "error"; return cont(attributes);}
  return pass();
  }
  function attvalue(type) {
  if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
  if (type == "string") return cont(attvaluemaybe);
  return pass();
  }
  function attvaluemaybe(type) {
  if (type == "string") return cont(attvaluemaybe);
  else return pass();
  }
 
  return {
  startState: function() {
  return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
  },
 
  token: function(stream, state) {
  if (stream.sol()) {
  state.startOfLine = true;
  state.indented = stream.indentation();
  }
  if (stream.eatSpace()) return null;
 
  setStyle = type = tagName = null;
  var style = state.tokenize(stream, state);
  state.type = type;
  if ((style || type) && style != "comment") {
  curState = state;
  while (true) {
  var comb = state.cc.pop() || element;
  if (comb(type || style)) break;
  }
  }
  state.startOfLine = false;
  return setStyle || style;
  },
 
  indent: function(state, textAfter, fullLine) {
  var context = state.context;
  if ((state.tokenize != inTag && state.tokenize != inText) ||
  context && context.noIndent)
  return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  if (context && /^<\//.test(textAfter))
  context = context.prev;
  while (context && !context.startOfLine)
  context = context.prev;
  if (context) return context.indent + indentUnit;
  else return 0;
  },
 
  compareStates: function(a, b) {
  if (a.indented != b.indented || a.tokenize != b.tokenize) return false;
  for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
  if (!ca || !cb) return ca == cb;
  if (ca.tagName != cb.tagName) return false;
  }
  },
 
  electricChars: "/"
  };
  });
 
  CodeMirror.defineMIME("application/xml", "xml");
  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Pure XML mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="xmlpure.js"></script>
  <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: XML mode</h1>
  <form><textarea id="code" name="code">
  &lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;
 
  &lt;!-- This is the pure XML mode,
  and we're inside a comment! --&gt;
 
  &lt;catalog&gt;
  &lt;books&gt;
  &lt;book id="bk01"&gt;
  &lt;title&gt;Lord of Light&lt;/title&gt;
  &lt;author&gt;Roger Zelazny&lt;/author&gt;
  &lt;year&gt;1967&lt;/year&gt;
  &lt;description&gt;&lt;![CDATA[This is a great book, really!!]]&gt;&lt;/description&gt;
  &lt;/book&gt;
  &lt;/books&gt;
  &lt;/catalog&gt;
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: {name: "xmlpure"}});
  </script>
 
  <p>This is my XML parser, based on the original:</p>
  <ul>
  <li>No html mode - this is pure xml</li>
  <li>Illegal attributes and element names are errors</li>
  <li>Attributes must have a value</li>
  <li>XML declaration supported (e.g.: <b>&lt;?xml version="1.0" encoding="utf-8" standalone="no" ?&gt;</b>)</li>
  <li>CDATA and comment blocks are not indented (except for their start-tag)</li>
  <li>Better handling of errors per line with the state object - provides good infrastructure for extending it</li>
  </ul>
 
  <p>What's missing:</p>
  <ul>
  <li>Make sure only a single root element exists at the document level</li>
  <li>Multi-line attributes should NOT indent</li>
  <li>Start tags are not painted red when they have no matching end tags (is this really wrong?)</li>
  </ul>
 
  <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/xml</code>.</p>
 
  <p><b>@author</b>: Dror BG (<i>deebug.dev[at]gmail.com</i>)<br/>
  <p><b>@date</b>: August, 2011<br/>
  <p><b>@github</b>: <a href='https://github.com/deebugger/CodeMirror2' target='blank'>https://github.com/deebugger/CodeMirror2</a></p>
 
  <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/xml</code>.</p>
  </body>
  </html>
 
  /**
  * xmlpure.js
  *
  * Building upon and improving the CodeMirror 2 XML parser
  * @author: Dror BG (deebug.dev@gmail.com)
  * @date: August, 2011
  */
 
  CodeMirror.defineMode("xmlpure", function(config, parserConfig) {
  // constants
  var STYLE_ERROR = "error";
  var STYLE_INSTRUCTION = "comment";
  var STYLE_COMMENT = "comment";
  var STYLE_ELEMENT_NAME = "tag";
  var STYLE_ATTRIBUTE = "attribute";
  var STYLE_WORD = "string";
  var STYLE_TEXT = "atom";
 
  var TAG_INSTRUCTION = "!instruction";
  var TAG_CDATA = "!cdata";
  var TAG_COMMENT = "!comment";
  var TAG_TEXT = "!text";
 
  var doNotIndent = {
  "!cdata": true,
  "!comment": true,
  "!text": true,
  "!instruction": true
  };
 
  // options
  var indentUnit = config.indentUnit;
 
  ///////////////////////////////////////////////////////////////////////////
  // helper functions
 
  // chain a parser to another parser
  function chain(stream, state, parser) {
  state.tokenize = parser;
  return parser(stream, state);
  }
 
  // parse a block (comment, CDATA or text)
  function inBlock(style, terminator, nextTokenize) {
  return function(stream, state) {
  while (!stream.eol()) {
  if (stream.match(terminator)) {
  popContext(state);
  state.tokenize = nextTokenize;
  break;
  }
  stream.next();
  }
  return style;
  };
  }
 
  // go down a level in the document
  // (hint: look at who calls this function to know what the contexts are)
  function pushContext(state, tagName) {
  var noIndent = doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.doIndent);
  var newContext = {
  tagName: tagName,
  prev: state.context,
  indent: state.context ? state.context.indent + indentUnit : 0,
  lineNumber: state.lineNumber,
  indented: state.indented,
  noIndent: noIndent
  };
  state.context = newContext;
  }
 
  // go up a level in the document
  function popContext(state) {
  if (state.context) {
  var oldContext = state.context;
  state.context = oldContext.prev;
  return oldContext;
  }
 
  // we shouldn't be here - it means we didn't have a context to pop
  return null;
  }
 
  // return true if the current token is seperated from the tokens before it
  // which means either this is the start of the line, or there is at least
  // one space or tab character behind the token
  // otherwise returns false
  function isTokenSeparated(stream) {
  return stream.sol() ||
  stream.string.charAt(stream.start - 1) == " " ||
  stream.string.charAt(stream.start - 1) == "\t";
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // context: document
  //
  // an XML document can contain:
  // - a single declaration (if defined, it must be the very first line)
  // - exactly one root element
  // @todo try to actually limit the number of root elements to 1
  // - zero or more comments
  function parseDocument(stream, state) {
  if(stream.eat("<")) {
  if(stream.eat("?")) {
  // processing instruction
  pushContext(state, TAG_INSTRUCTION);
  state.tokenize = parseProcessingInstructionStartTag;
  return STYLE_INSTRUCTION;
  } else if(stream.match("!--")) {
  // new context: comment
  pushContext(state, TAG_COMMENT);
  return chain(stream, state, inBlock(STYLE_COMMENT, "-->", parseDocument));
  } else if(stream.eatSpace() || stream.eol() ) {
  stream.skipToEnd();
  return STYLE_ERROR;
  } else {
  // element
  state.tokenize = parseElementTagName;
  return STYLE_ELEMENT_NAME;
  }
  }
 
  // error on line
  stream.skipToEnd();
  return STYLE_ERROR;
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // context: XML element start-tag or end-tag
  //
  // - element start-tag can contain attributes
  // - element start-tag may self-close (or start an element block if it doesn't)
  // - element end-tag can contain only the tag name
  function parseElementTagName(stream, state) {
  // get the name of the tag
  var startPos = stream.pos;
  if(stream.match(/^[a-zA-Z_:][-a-zA-Z0-9_:.]*/)) {
  // element start-tag
  var tagName = stream.string.substring(startPos, stream.pos);
  pushContext(state, tagName);
  state.tokenize = parseElement;
  return STYLE_ELEMENT_NAME;
  } else if(stream.match(/^\/[a-zA-Z_:][-a-zA-Z0-9_:.]*( )*>/)) {
  // element end-tag
  var endTagName = stream.string.substring(startPos + 1, stream.pos - 1).trim();
  var oldContext = popContext(state);
  state.tokenize = state.context == null ? parseDocument : parseElementBlock;
  if(oldContext == null || endTagName != oldContext.tagName) {
  // the start and end tag names should match - error
  return STYLE_ERROR;
  }
  return STYLE_ELEMENT_NAME;
  } else {
  // no tag name - error
  state.tokenize = state.context == null ? parseDocument : parseElementBlock;
  stream.eatWhile(/[^>]/);
  stream.eat(">");
  return STYLE_ERROR;
  }
 
  stream.skipToEnd();
  return null;
  }
 
  function parseElement(stream, state) {
  if(stream.match(/^\/>/)) {
  // self-closing tag
  popContext(state);
  state.tokenize = state.context == null ? parseDocument : parseElementBlock;
  return STYLE_ELEMENT_NAME;
  } else if(stream.eat(/^>/)) {
  state.tokenize = parseElementBlock;
  return STYLE_ELEMENT_NAME;
  } else if(isTokenSeparated(stream) && stream.match(/^[a-zA-Z_:][-a-zA-Z0-9_:.]*( )*=/)) {
  // attribute
  state.tokenize = parseAttribute;
  return STYLE_ATTRIBUTE;
  }
 
  // no other options - this is an error
  state.tokenize = state.context == null ? parseDocument : parseDocument;
  stream.eatWhile(/[^>]/);
  stream.eat(">");
  return STYLE_ERROR;
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // context: attribute
  //
  // attribute values may contain everything, except:
  // - the ending quote (with ' or ") - this marks the end of the value
  // - the character "<" - should never appear
  // - ampersand ("&") - unless it starts a reference: a string that ends with a semi-colon (";")
  // ---> note: this parser is lax in what may be put into a reference string,
  // ---> consult http://www.w3.org/TR/REC-xml/#NT-Reference if you want to make it tighter
  function parseAttribute(stream, state) {
  var quote = stream.next();
  if(quote != "\"" && quote != "'") {
  // attribute must be quoted
  stream.skipToEnd();
  state.tokenize = parseElement;
  return STYLE_ERROR;
  }
 
  state.tokParams.quote = quote;
  state.tokenize = parseAttributeValue;
  return STYLE_WORD;
  }
 
  // @todo: find out whether this attribute value spans multiple lines,
  // and if so, push a context for it in order not to indent it
  // (or something of the sort..)
  function parseAttributeValue(stream, state) {
  var ch = "";
  while(!stream.eol()) {
  ch = stream.next();
  if(ch == state.tokParams.quote) {
  // end quote found
  state.tokenize = parseElement;
  return STYLE_WORD;
  } else if(ch == "<") {
  // can't have less-than signs in an attribute value, ever
  stream.skipToEnd()
  state.tokenize = parseElement;
  return STYLE_ERROR;
  } else if(ch == "&") {
  // reference - look for a semi-colon, or return error if none found
  ch = stream.next();
 
  // make sure that semi-colon isn't right after the ampersand
  if(ch == ';') {
  stream.skipToEnd()
  state.tokenize = parseElement;
  return STYLE_ERROR;
  }
 
  // make sure no less-than characters slipped in
  while(!stream.eol() && ch != ";") {
  if(ch == "<") {
  // can't have less-than signs in an attribute value, ever
  stream.skipToEnd()
  state.tokenize = parseElement;
  return STYLE_ERROR;
  }
  ch = stream.next();
  }
  if(stream.eol() && ch != ";") {
  // no ampersand found - error
  stream.skipToEnd();
  state.tokenize = parseElement;
  return STYLE_ERROR;
  }
  }
  }
 
  // attribute value continues to next line
  return STYLE_WORD;
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // context: element block
  //
  // a block can contain:
  // - elements
  // - text
  // - CDATA sections
  // - comments
  function parseElementBlock(stream, state) {
  if(stream.eat("<")) {
  if(stream.match("?")) {
  pushContext(state, TAG_INSTRUCTION);
  state.tokenize = parseProcessingInstructionStartTag;
  return STYLE_INSTRUCTION;
  } else if(stream.match("!--")) {
  // new context: comment
  pushContext(state, TAG_COMMENT);
  return chain(stream, state, inBlock(STYLE_COMMENT, "-->",
  state.context == null ? parseDocument : parseElementBlock));
  } else if(stream.match("![CDATA[")) {
  // new context: CDATA section
  pushContext(state, TAG_CDATA);
  return chain(stream, state, inBlock(STYLE_TEXT, "]]>",
  state.context == null ? parseDocument : parseElementBlock));
  } else if(stream.eatSpace() || stream.eol() ) {
  stream.skipToEnd();
  return STYLE_ERROR;
  } else {
  // element
  state.tokenize = parseElementTagName;
  return STYLE_ELEMENT_NAME;
  }
  } else {
  // new context: text
  pushContext(state, TAG_TEXT);
  state.tokenize = parseText;
  return null;
  }
 
  state.tokenize = state.context == null ? parseDocument : parseElementBlock;
  stream.skipToEnd();
  return null;
  }
 
  function parseText(stream, state) {
  stream.eatWhile(/[^<]/);
  if(!stream.eol()) {
  // we cannot possibly be in the document context,
  // just inside an element block
  popContext(state);
  state.tokenize = parseElementBlock;
  }
  return STYLE_TEXT;
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // context: XML processing instructions
  //
  // XML processing instructions (PIs) allow documents to contain instructions for applications.
  // PI format: <?name data?>
  // - 'name' can be anything other than 'xml' (case-insensitive)
  // - 'data' can be anything which doesn't contain '?>'
  // XML declaration is a special PI (see XML declaration context below)
  function parseProcessingInstructionStartTag(stream, state) {
  if(stream.match("xml", true, true)) {
  // xml declaration
  if(state.lineNumber > 1 || stream.pos > 5) {
  state.tokenize = parseDocument;
  stream.skipToEnd();
  return STYLE_ERROR;
  } else {
  state.tokenize = parseDeclarationVersion;
  return STYLE_INSTRUCTION;
  }
  }
 
  // regular processing instruction
  if(isTokenSeparated(stream) || stream.match("?>")) {
  // we have a space after the start-tag, or nothing but the end-tag
  // either way - error!
  state.tokenize = parseDocument;
  stream.skipToEnd();
  return STYLE_ERROR;
  }
 
  state.tokenize = parseProcessingInstructionBody;
  return STYLE_INSTRUCTION;
  }
 
  function parseProcessingInstructionBody(stream, state) {
  stream.eatWhile(/[^?]/);
  if(stream.eat("?")) {
  if(stream.eat(">")) {
  popContext(state);
  state.tokenize = state.context == null ? parseDocument : parseElementBlock;
  }
  }
  return STYLE_INSTRUCTION;
  }
 
 
  ///////////////////////////////////////////////////////////////////////////
  // context: XML declaration
  //
  // XML declaration is of the following format:
  // <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
  // - must start at the first character of the first line
  // - may span multiple lines
  // - must include 'version'
  // - may include 'encoding' and 'standalone' (in that order after 'version')
  // - attribute names must be lowercase
  // - cannot contain anything else on the line
  function parseDeclarationVersion(stream, state) {
  state.tokenize = parseDeclarationEncoding;
 
  if(isTokenSeparated(stream) && stream.match(/^version( )*=( )*"([a-zA-Z0-9_.:]|\-)+"/)) {
  return STYLE_INSTRUCTION;
  }
  stream.skipToEnd();
  return STYLE_ERROR;
  }
 
  function parseDeclarationEncoding(stream, state) {
  state.tokenize = parseDeclarationStandalone;
 
  if(isTokenSeparated(stream) && stream.match(/^encoding( )*=( )*"[A-Za-z]([A-Za-z0-9._]|\-)*"/)) {
  return STYLE_INSTRUCTION;
  }
  return null;
  }
 
  function parseDeclarationStandalone(stream, state) {
  state.tokenize = parseDeclarationEndTag;
 
  if(isTokenSeparated(stream) && stream.match(/^standalone( )*=( )*"(yes|no)"/)) {
  return STYLE_INSTRUCTION;
  }
  return null;
  }
 
  function parseDeclarationEndTag(stream, state) {
  state.tokenize = parseDocument;
 
  if(stream.match("?>") && stream.eol()) {
  popContext(state);
  return STYLE_INSTRUCTION;
  }
  stream.skipToEnd();
  return STYLE_ERROR;
  }
 
  ///////////////////////////////////////////////////////////////////////////
  // returned object
  return {
  electricChars: "/[",
 
  startState: function() {
  return {
  tokenize: parseDocument,
  tokParams: {},
  lineNumber: 0,
  lineError: false,
  context: null,
  indented: 0
  };
  },
 
  token: function(stream, state) {
  if(stream.sol()) {
  // initialize a new line
  state.lineNumber++;
  state.lineError = false;
  state.indented = stream.indentation();
  }
 
  // eat all (the spaces) you can
  if(stream.eatSpace()) return null;
 
  // run the current tokenize function, according to the state
  var style = state.tokenize(stream, state);
 
  // is there an error somewhere in the line?
  state.lineError = (state.lineError || style == "error");
 
  return style;
  },
 
  blankLine: function(state) {
  // blank lines are lines too!
  state.lineNumber++;
  state.lineError = false;
  },
 
  indent: function(state, textAfter) {
  if(state.context) {
  if(state.context.noIndent == true) {
  // do not indent - no return value at all
  return;
  }
  if(textAfter.match(/^<\/.*/)) {
  // end-tag - indent back to last context
  return state.context.indent;
  }
  if(textAfter.match(/^<!\[CDATA\[/)) {
  // a stand-alone CDATA start-tag - indent back to column 0
  return 0;
  }
  // indent to last context + regular indent unit
  return state.context.indent + indentUnit;
  }
  return 0;
  },
 
  compareStates: function(a, b) {
  if (a.indented != b.indented) return false;
  for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
  if (!ca || !cb) return ca == cb;
  if (ca.tagName != cb.tagName) return false;
  }
  }
  };
  });
 
  CodeMirror.defineMIME("application/xml", "purexml");
  CodeMirror.defineMIME("text/xml", "purexml");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: YAML mode</title>
  <link rel="stylesheet" href="../../lib/codemirror.css">
  <script src="../../lib/codemirror.js"></script>
  <script src="yaml.js"></script>
  <style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
  <link rel="stylesheet" href="../../doc/docs.css">
  </head>
  <body>
  <h1>CodeMirror: YAML mode</h1>
  <form><textarea id="code" name="code">
  --- # Favorite movies
  - Casablanca
  - North by Northwest
  - The Man Who Wasn't There
  --- # Shopping list
  [milk, pumpkin pie, eggs, juice]
  --- # Indented Blocks, common in YAML data files, use indentation and new lines to separate the key: value pairs
  name: John Smith
  age: 33
  --- # Inline Blocks, common in YAML data streams, use commas to separate the key: value pairs between braces
  {name: John Smith, age: 33}
  ---
  receipt: Oz-Ware Purchase Invoice
  date: 2007-08-06
  customer:
  given: Dorothy
  family: Gale
 
  items:
  - part_no: A4786
  descrip: Water Bucket (Filled)
  price: 1.47
  quantity: 4
 
  - part_no: E1628
  descrip: High Heeled "Ruby" Slippers
  size: 8
  price: 100.27
  quantity: 1
 
  bill-to: &id001
  street: |
  123 Tornado Alley
  Suite 16
  city: East Centerville
  state: KS
 
  ship-to: *id001
 
  specialDelivery: >
  Follow the Yellow Brick
  Road to the Emerald City.
  Pay no attention to the
  man behind the curtain.
  ...
  </textarea></form>
  <script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  </script>
 
  <p><strong>MIME types defined:</strong> <code>text/x-yaml</code>.</p>
 
  </body>
  </html>
 
  CodeMirror.defineMode("yaml", function() {
 
  var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
  var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
 
  return {
  token: function(stream, state) {
  var ch = stream.peek();
  var esc = state.escaped;
  state.escaped = false;
  /* comments */
  if (ch == "#") { stream.skipToEnd(); return "comment"; }
  if (state.literal && stream.indentation() > state.keyCol) {
  stream.skipToEnd(); return "string";
  } else if (state.literal) { state.literal = false; }
  if (stream.sol()) {
  state.keyCol = 0;
  state.pair = false;
  state.pairStart = false;
  /* document start */
  if(stream.match(/---/)) { return "def"; }
  /* document end */
  if (stream.match(/\.\.\./)) { return "def"; }
  /* array list item */
  if (stream.match(/\s*-\s+/)) { return 'meta'; }
  }
  /* pairs (associative arrays) -> key */
  if (!state.pair && stream.match(/^\s*([a-z0-9\._-])+(?=\s*:)/i)) {
  state.pair = true;
  state.keyCol = stream.indentation();
  return "atom";
  }
  if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
 
  /* inline pairs/lists */
  if (stream.match(/^(\{|\}|\[|\])/)) {
  if (ch == '{')
  state.inlinePairs++;
  else if (ch == '}')
  state.inlinePairs--;
  else if (ch == '[')
  state.inlineList++;
  else
  state.inlineList--;
  return 'meta';
  }
 
  /* list seperator */
  if (state.inlineList > 0 && !esc && ch == ',') {
  stream.next();
  return 'meta';
  }
  /* pairs seperator */
  if (state.inlinePairs > 0 && !esc && ch == ',') {
  state.keyCol = 0;
  state.pair = false;
  state.pairStart = false;
  stream.next();
  return 'meta';
  }
 
  /* start of value of a pair */
  if (state.pairStart) {
  /* block literals */
  if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; };
  /* references */
  if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; }
  /* numbers */
  if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; }
  if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; }
  /* keywords */
  if (stream.match(keywordRegex)) { return 'keyword'; }
  }
 
  /* nothing found, continue */
  state.pairStart = false;
  state.escaped = (ch == '\\');
  stream.next();
  return null;
  },
  startState: function() {
  return {
  pair: false,
  pairStart: false,
  keyCol: 0,
  inlinePairs: 0,
  inlineList: 0,
  literal: false,
  escaped: false
  };
  }
  };
  });
 
  CodeMirror.defineMIME("text/x-yaml", "yaml");
 
  <!doctype html>
  <html>
  <head>
  <title>CodeMirror: Test Suite</title>
  <link rel="stylesheet" href="../lib/codemirror.css">
  <script src="../lib/codemirror.js"></script>
  <script src="../mode/javascript/javascript.js"></script>
 
  <style type="text/css">
  .ok {color: #0e0;}
  .failure {color: #e00;}
  .error {color: #c90;}
  </style>
  </head>
  <body>
  <h1>CodeMirror: Test Suite</h1>
 
  <p>A limited set of programmatic sanity tests for CodeMirror.</p>
 
  <pre id=output></pre>
 
  <div style="visibility: hidden" id=testground>
  <form><textarea id="code" name="code"></textarea><input type=submit value=ok name=submit></form>
  </div>
 
  <script src="test.js"></script>
  </body>
  </html>
 
  var tests = [];
 
  test("fromTextArea", function() {
  var te = document.getElementById("code");
  te.value = "CONTENT";
  var cm = CodeMirror.fromTextArea(te);
  is(!te.offsetHeight);
  eq(cm.getValue(), "CONTENT");
  cm.setValue("foo\nbar");
  eq(cm.getValue(), "foo\nbar");
  cm.save();
  is(/^foo\r?\nbar$/.test(te.value));
  cm.setValue("xxx");
  cm.toTextArea();
  is(te.offsetHeight);
  eq(te.value, "xxx");
  });
 
  testCM("getRange", function(cm) {
  eq(cm.getLine(0), "1234");
  eq(cm.getLine(1), "5678");
  eq(cm.getLine(2), null);
  eq(cm.getLine(-1), null);
  eq(cm.getRange({line: 0, ch: 0}, {line: 0, ch: 3}), "123");
  eq(cm.getRange({line: 0, ch: -1}, {line: 0, ch: 200}), "1234");
  eq(cm.getRange({line: 0, ch: 2}, {line: 1, ch: 2}), "34\n56");
  eq(cm.getRange({line: 1, ch: 2}, {line: 100, ch: 0}), "78");
  }, {value: "1234\n5678"});
 
  testCM("replaceRange", function(cm) {
  eq(cm.getValue(), "");
  cm.replaceRange("foo\n", {line: 0, ch: 0});
  eq(cm.getValue(), "foo\n");
  cm.replaceRange("a\nb", {line: 0, ch: 1});
  eq(cm.getValue(), "fa\nboo\n");
  eq(cm.lineCount(), 3);
  cm.replaceRange("xyzzy", {line: 0, ch: 0}, {line: 1, ch: 1});
  eq(cm.getValue(), "xyzzyoo\n");
  cm.replaceRange("abc", {line: 0, ch: 0}, {line: 10, ch: 0});
  eq(cm.getValue(), "abc");
  eq(cm.lineCount(), 1);
  });
 
  testCM("selection", function(cm) {
  cm.setSelection({line: 0, ch: 4}, {line: 2, ch: 2});
  is(cm.somethingSelected());
  eq(cm.getSelection(), "11\n222222\n33");
  eqPos(cm.getCursor(false), {line: 2, ch: 2});
  eqPos(cm.getCursor(true), {line: 0, ch: 4});
  cm.setSelection({line: 1, ch: 0});
  is(!cm.somethingSelected());
  eq(cm.getSelection(), "");
  eqPos(cm.getCursor(true), {line: 1, ch: 0});
  cm.replaceSelection("abc");
  eq(cm.getSelection(), "abc");
  eq(cm.getValue(), "111111\nabc222222\n333333");
  cm.replaceSelection("def", "end");
  eq(cm.getSelection(), "");
  eqPos(cm.getCursor(true), {line: 1, ch: 3});
  cm.setCursor({line: 2, ch: 1});
  eqPos(cm.getCursor(true), {line: 2, ch: 1});
  cm.setCursor(1, 2);
  eqPos(cm.getCursor(true), {line: 1, ch: 2});
  }, {value: "111111\n222222\n333333"});
 
  testCM("lines", function(cm) {
  eq(cm.getLine(0), "111111");
  eq(cm.getLine(1), "222222");
  eq(cm.getLine(-1), null);
  cm.removeLine(1);
  cm.setLine(1, "abc");
  eq(cm.getValue(), "111111\nabc");
  }, {value: "111111\n222222\n333333"});
 
  testCM("indent", function(cm) {
  cm.indentLine(1);
  eq(cm.getLine(1), " blah();");
  cm.setOption("indentUnit", 8);
  cm.indentLine(1);
  eq(cm.getLine(1), "\tblah();");
  }, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8});
 
  test("defaults", function() {
  var olddefaults = CodeMirror.defaults, defs = CodeMirror.defaults = {};
  for (var opt in olddefaults) defs[opt] = olddefaults[opt];
  defs.indentUnit = 5;
  defs.value = "uu";
  defs.enterMode = "keep";
  defs.tabindex = 55;
  var place = document.getElementById("testground"), cm = CodeMirror(place);
  try {
  eq(cm.getOption("indentUnit"), 5);
  cm.setOption("indentUnit", 10);
  eq(defs.indentUnit, 5);
  eq(cm.getValue(), "uu");
  eq(cm.getOption("enterMode"), "keep");
  eq(cm.getInputField().tabIndex, 55);
  }
  finally {
  CodeMirror.defaults = olddefaults;
  place.removeChild(cm.getWrapperElement());
  }
  });
 
  testCM("lineInfo", function(cm) {
  eq(cm.lineInfo(-1), null);
  var lh = cm.setMarker(1, "FOO", "bar");
  var info = cm.lineInfo(1);
  eq(info.text, "222222");
  eq(info.markerText, "FOO");
  eq(info.markerClass, "bar");
  eq(info.line, 1);
  eq(cm.lineInfo(2).markerText, null);
  cm.clearMarker(lh);
  eq(cm.lineInfo(1).markerText, null);
  }, {value: "111111\n222222\n333333"});
 
  testCM("coords", function(cm) {
  var scroller = cm.getWrapperElement().getElementsByClassName("CodeMirror-scroll")[0];
  scroller.style.height = "100px";
  var content = [];
  for (var i = 0; i < 200; ++i) content.push("------------------------------" + i);
  cm.setValue(content.join("\n"));
  var top = cm.charCoords({line: 0, ch: 0});
  var bot = cm.charCoords({line: 200, ch: 30});
  is(top.x < bot.x);
  is(top.y < bot.y);
  is(top.y < top.yBot);
  scroller.scrollTop = 100;
  cm.refresh();
  var top2 = cm.charCoords({line: 0, ch: 0});
  is(top.y > top2.y);
  eq(top.x, top2.x);
  });
 
  testCM("coordsChar", function(cm) {
  var content = [];
  for (var i = 0; i < 70; ++i) content.push("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  cm.setValue(content.join("\n"));
  for (var x = 0; x < 35; x += 2) {
  for (var y = 0; y < 70; y += 5) {
  cm.setCursor(y, x);
  var pos = cm.coordsChar(cm.charCoords({line: y, ch: x}));
  eq(pos.line, y);
  eq(pos.ch, x);
  }
  }
  });
 
  testCM("posFromIndex", function(cm) {
  cm.setValue(
  "This function should\n" +
  "convert a zero based index\n" +
  "to line and ch."
  );
 
  var examples = [
  { index: -1, line: 0, ch: 0 }, // <- Tests clipping
  { index: 0, line: 0, ch: 0 },
  { index: 10, line: 0, ch: 10 },
  { index: 39, line: 1, ch: 18 },
  { index: 55, line: 2, ch: 7 },
  { index: 63, line: 2, ch: 15 },
  { index: 64, line: 2, ch: 15 } // <- Tests clipping
  ];
 
  for (var i = 0; i < examples.length; i++) {
  var example = examples[i];
  var pos = cm.posFromIndex(example.index);
  eq(pos.line, example.line);
  eq(pos.ch, example.ch);
  if (example.index >= 0 && example.index < 64)
  eq(cm.indexFromPos(pos), example.index);
  }
  });
 
  testCM("undo", function(cm) {
  cm.setLine(0, "def");
  eq(cm.historySize().undo, 1);
  cm.undo();
  eq(cm.getValue(), "abc");
  eq(cm.historySize().undo, 0);
  eq(cm.historySize().redo, 1);
  cm.redo();
  eq(cm.getValue(), "def");
  eq(cm.historySize().undo, 1);
  eq(cm.historySize().redo, 0);
  cm.setValue("1\n\n\n2");
  cm.clearHistory();
  eq(cm.historySize().undo, 0);
  for (var i = 0; i < 20; ++i) {
  cm.replaceRange("a", {line: 0, ch: 0});
  cm.replaceRange("b", {line: 3, ch: 0});
  }
  eq(cm.historySize().undo, 40);
  for (var i = 0; i < 38; ++i) cm.undo();
  eq(cm.historySize().undo, 2);
  eq(cm.historySize().redo, 38);
  eq(cm.getValue(), "a1\n\n\nb2");
  cm.setOption("undoDepth", 10);
  for (var i = 0; i < 20; ++i) {
  cm.replaceRange("a", {line: 0, ch: 0});
  cm.replaceRange("b", {line: 3, ch: 0});
  }
  eq(cm.historySize().undo, 10);
  }, {value: "abc"});
 
  testCM("undoMultiLine", function(cm) {
  cm.replaceRange("x", {line:0, ch: 0});
  cm.replaceRange("y", {line:1, ch: 0});
  cm.undo();
  eq(cm.getValue(), "abc\ndef\nghi");
  cm.replaceRange("y", {line:1, ch: 0});
  cm.replaceRange("x", {line:0, ch: 0});
  cm.undo();
  eq(cm.getValue(), "abc\ndef\nghi");
  cm.replaceRange("y", {line:2, ch: 0});
  cm.replaceRange("x", {line:1, ch: 0});
  cm.replaceRange("z", {line:2, ch: 0});
  cm.undo();
  eq(cm.getValue(), "abc\ndef\nghi");
  }, {value: "abc\ndef\nghi"});
 
  testCM("markTextSingleLine", function(cm) {
  forEach([{a: 0, b: 1, c: "", f: 2, t: 5},
  {a: 0, b: 4, c: "", f: 0, t: 2},
  {a: 1, b: 2, c: "x", f: 3, t: 6},
  {a: 4, b: 5, c: "", f: 3, t: 5},
  {a: 4, b: 5, c: "xx", f: 3, t: 7},
  {a: 2, b: 5, c: "", f: 2, t: 3},
  {a: 2, b: 5, c: "abcd", f: 6, t: 7},
  {a: 2, b: 6, c: "x", f: null, t: null},
  {a: 3, b: 6, c: "", f: null, t: null},
  {a: 0, b: 9, c: "hallo", f: null, t: null},
  {a: 4, b: 6, c: "x", f: 3, t: 4},
  {a: 4, b: 8, c: "", f: 3, t: 4},
  {a: 6, b: 6, c: "a", f: 3, t: 6},
  {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) {
  cm.setValue("1234567890");
  var r = cm.markText({line: 0, ch: 3}, {line: 0, ch: 6}, "foo");
  cm.replaceRange(test.c, {line: 0, ch: test.a}, {line: 0, ch: test.b});
  var f = r.find();
  eq(f.from && f.from.ch, test.f); eq(f.to && f.to.ch, test.t);
  });
  });
 
  testCM("markTextMultiLine", function(cm) {
  function p(v) { return v && {line: v[0], ch: v[1]}; }
  forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]},
  {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]},
  {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]},
  {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]},
  {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]},
  {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]},
  {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]},
  {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null},
  {a: [0, 0], b: [2, 10], c: "x", f: null, t: null},
  {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]},
  {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]},
  {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]},
  {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]},
  {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) {
  cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n");
  var r = cm.markText({line: 0, ch: 5}, {line: 2, ch: 5}, "foo");
  cm.replaceRange(test.c, p(test.a), p(test.b));
  var f = r.find();
  eqPos(f.from, p(test.f)); eqPos(f.to, p(test.t));
  });
  });
 
  testCM("bookmark", function(cm) {
  function p(v) { return v && {line: v[0], ch: v[1]}; }
  forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]},
  {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]},
  {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]},
  {a: [1, 4], b: [1, 6], c: "", d: null},
  {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]},
  {a: [1, 6], b: [1, 8], c: "", d: [1, 5]},
  {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]}], function(test) {
  cm.setValue("1234567890\n1234567890\n1234567890");
  var b = cm.setBookmark({line: 1, ch: 5});
  cm.replaceRange(test.c, p(test.a), p(test.b));
  eqPos(b.find(), p(test.d));
  });
  });
 
  // Scaffolding
 
  function htmlEscape(str) {
  return str.replace(/[<&]/g, function(str) {return str == "&" ? "&amp;" : "&lt;";});
  }
  function forEach(arr, f) {
  for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
  }
 
  function Failure(why) {this.message = why;}
 
  function test(name, run) {tests.push({name: name, func: run});}
  function testCM(name, run, opts) {
  test(name, function() {
  var place = document.getElementById("testground"), cm = CodeMirror(place, opts);
  try {run(cm);}
  finally {place.removeChild(cm.getWrapperElement());}
  });
  }
 
  function runTests() {
  var failures = [], run = 0;
  for (var i = 0; i < tests.length; ++i) {
  var test = tests[i];
  try {test.func();}
  catch(e) {
  if (e instanceof Failure)
  failures.push({type: "failure", test: test.name, text: e.message});
  else
  failures.push({type: "error", test: test.name, text: e.toString()});
  }
  run++;
  }
  var html = [run + " tests run."];
  if (failures.length)
  forEach(failures, function(fail) {
  html.push(fail.test + ': <span class="' + fail.type + '">' + htmlEscape(fail.text) + "</span>");
  });
  else html.push('<span class="ok">All passed.</span>');
  document.getElementById("output").innerHTML = html.join("\n");
  }
 
  function eq(a, b, msg) {
  if (a != b) throw new Failure(a + " != " + b + (msg ? " (" + msg + ")" : ""));
  }
  function eqPos(a, b, msg) {
  if (a == b) return;
  if (a == null || b == null) throw new Failure("comparing point to null");
  eq(a.line, b.line, msg);
  eq(a.ch, b.ch, msg);
  }
  function is(a, msg) {
  if (!a) throw new Failure("assertion failed" + (msg ? " (" + msg + ")" : ""));
  }
 
  window.onload = runTests;
 
  .cm-s-cobalt { background: #002240; color: white; }
  .cm-s-cobalt span.CodeMirror-selected { background: #b36539 !important; }
  .cm-s-cobalt .CodeMirror-gutter { background: #002240; border-right: 1px solid #aaa; }
  .cm-s-cobalt .CodeMirror-gutter-text { color: #d0d0d0; }
  .cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; }
 
  .cm-s-cobalt span.cm-comment { color: #08f; }
  .cm-s-cobalt span.cm-atom { color: #845dc4; }
  .cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; }
  .cm-s-cobalt span.cm-keyword { color: #ffee80; }
  .cm-s-cobalt span.cm-string { color: #3ad900; }
  .cm-s-cobalt span.cm-meta { color: #ff9d00; }
  .cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; }
  .cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; }
  .cm-s-cobalt span.cm-error { color: #9d1e15; }
  .cm-s-cobalt span.cm-bracket { color: #d8d8d8; }
  .cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; }
  .cm-s-cobalt span.cm-link { color: #845dc4; }
 
  .cm-s-eclipse span.cm-meta {color: #FF1717;}
  .cm-s-eclipse span.cm-keyword { font-weight: bold; color: #7F0055; }
  .cm-s-eclipse span.cm-atom {color: #219;}
  .cm-s-eclipse span.cm-number {color: #164;}
  .cm-s-eclipse span.cm-def {color: #00f;}
  .cm-s-eclipse span.cm-variable {color: black;}
  .cm-s-eclipse span.cm-variable-2 {color: #0000C0;}
  .cm-s-eclipse span.cm-variable-3 {color: #0000C0;}
  .cm-s-eclipse span.cm-property {color: black;}
  .cm-s-eclipse span.cm-operator {color: black;}
  .cm-s-eclipse span.cm-comment {color: #3F7F5F;}
  .cm-s-eclipse span.cm-string {color: #2A00FF;}
  .cm-s-eclipse span.cm-string-2 {color: #f50;}
  .cm-s-eclipse span.cm-error {color: #f00;}
  .cm-s-eclipse span.cm-qualifier {color: #555;}
  .cm-s-eclipse span.cm-builtin {color: #30a;}
  .cm-s-eclipse span.cm-bracket {color: #cc7;}
  .cm-s-eclipse span.cm-tag {color: #170;}
  .cm-s-eclipse span.cm-attribute {color: #00c;}
  .cm-s-eclipse span.cm-link {color: #219;}
 
  .cm-s-eclipse .CodeMirror-matchingbracket {
  border:1px solid grey;
  color:black !important;;
  }
 
  .cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;}
  .cm-s-elegant span.cm-comment {color: #262;font-style: italic;}
  .cm-s-elegant span.cm-meta {color: #555;font-style: italic;}
  .cm-s-elegant span.cm-variable {color: black;}
  .cm-s-elegant span.cm-variable-2 {color: #b11;}
  .cm-s-elegant span.cm-qualifier {color: #555;}
  .cm-s-elegant span.cm-keyword {color: #730;}
  .cm-s-elegant span.cm-builtin {color: #30a;}
  .cm-s-elegant span.cm-error {background-color: #fdd;}
  .cm-s-elegant span.cm-link {color: #762;}
 
  /* Based on Sublime Text's Monokai theme */
 
  .cm-s-monokai {background: #272822; color: #f8f8f2;}
  .cm-s-monokai span.CodeMirror-selected {background: #ffe792 !important;}
  .cm-s-monokai .CodeMirror-gutter {background: #272822; border-right: 0px;}
  .cm-s-monokai .CodeMirror-gutter-text {color: #d0d0d0;}
  .cm-s-monokai .CodeMirror-cursor {border-left: 1px solid #f8f8f0 !important;}
 
  .cm-s-monokai span.cm-comment {color: #75715e;}
  .cm-s-monokai span.cm-atom {color: #ae81ff;}
  .cm-s-monokai span.cm-number {color: #ae81ff;}
 
  .cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute {color: #a6e22e;}
  .cm-s-monokai span.cm-keyword {color: #f92672;}
  .cm-s-monokai span.cm-string {color: #e6db74;}
 
  .cm-s-monokai span.cm-variable {color: #a6e22e;}
  .cm-s-monokai span.cm-variable-2 {color: #9effff;}
  .cm-s-monokai span.cm-def {color: #fd971f;}
  .cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;}
  .cm-s-monokai span.cm-bracket {color: #f8f8f2;}
  .cm-s-monokai span.cm-tag {color: #f92672;}
  .cm-s-monokai span.cm-link {color: #ae81ff;}
 
  .cm-s-monokai .CodeMirror-matchingbracket {
  text-decoration: underline;
  color: white !important;
  }
 
  .cm-s-neat span.cm-comment { color: #a86; }
  .cm-s-neat span.cm-keyword { font-weight: bold; color: blue; }
  .cm-s-neat span.cm-string { color: #a22; }
  .cm-s-neat span.cm-builtin { font-weight: bold; color: #077; }
  .cm-s-neat span.cm-special { font-weight: bold; color: #0aa; }
  .cm-s-neat span.cm-variable { color: black; }
  .cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
  .cm-s-neat span.cm-meta {color: #555;}
  .cm-s-neat span.cm-link { color: #3a3; }
 
  /* Loosely based on the Midnight Textmate theme */
 
  .cm-s-night { background: #0a001f; color: #f8f8f8; }
  .cm-s-night span.CodeMirror-selected { background: #a8f !important; }
  .cm-s-night .CodeMirror-gutter { background: #0a001f; border-right: 1px solid #aaa; }
  .cm-s-night .CodeMirror-gutter-text { color: #f8f8f8; }
  .cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; }
 
  .cm-s-night span.cm-comment { color: #6900a1; }
  .cm-s-night span.cm-atom { color: #845dc4; }
  .cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }
  .cm-s-night span.cm-keyword { color: #599eff; }
  .cm-s-night span.cm-string { color: #37f14a; }
  .cm-s-night span.cm-meta { color: #7678e2; }
  .cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }
  .cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; }
  .cm-s-night span.cm-error { color: #9d1e15; }
  .cm-s-night span.cm-bracket { color: #8da6ce; }
  .cm-s-night span.cm-comment { color: #6900a1; }
  .cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }
  .cm-s-night span.cm-link { color: #845dc4; }
 
  .cm-s-rubyblue { font:13px/1.4em Trebuchet, Verdana, sans-serif; } /* - customized editor font - */
 
  .cm-s-rubyblue { background: #112435; color: white; }
  .cm-s-rubyblue span.CodeMirror-selected { background: #0000FF !important; }
  .cm-s-rubyblue .CodeMirror-gutter { background: #1F4661; border-right: 7px solid #3E7087; min-width:2.5em; }
  .cm-s-rubyblue .CodeMirror-gutter-text { color: white; }
  .cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white !important; }
 
  .cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; }
  .cm-s-rubyblue span.cm-atom { color: #F4C20B; }
  .cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; }
  .cm-s-rubyblue span.cm-keyword { color: #F0F; }
  .cm-s-rubyblue span.cm-string { color: #F08047; }
  .cm-s-rubyblue span.cm-meta { color: #F0F; }
  .cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; }
  .cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def { color: white; }
  .cm-s-rubyblue span.cm-error { color: #AF2018; }
  .cm-s-rubyblue span.cm-bracket { color: #F0F; }
  .cm-s-rubyblue span.cm-link { color: #F4C20B; }
  .cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; }
  .cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; }
 
  /*! jQuery v1.7.1 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 cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},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){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.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:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},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){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\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),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},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){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!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;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","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=bv.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(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.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(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$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)));return c}),c.documentElement.currentStyle&&(bB=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)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,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)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).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||bO.test(this.nodeName)||bI.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(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\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:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},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:bZ(bT),ajaxTransport:bZ(bU),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?cb(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=cc(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=bH.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(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.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]!=="*"?", "+bX+"; 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=b$(bU,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)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.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(ce,l),b.url===j&&(e&&(k=k.replace(ce,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 cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,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,cf&&delete ch[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),m.text=h.responseText;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=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
  /*
  * jQuery hashchange event - v1.3 - 7/21/2010
  * http://benalman.com/projects/jquery-hashchange-plugin/
  *
  * Copyright (c) 2010 "Cowboy" Ben Alman
  * Dual licensed under the MIT and GPL licenses.
  * http://benalman.com/about/license/
  */
  (function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
  // seedrandom.js version 2.0.
  // Author: David Bau 4/2/2011
  //
  // Defines a method Math.seedrandom() that, when called, substitutes
  // an explicitly seeded RC4-based algorithm for Math.random(). Also
  // supports automatic seeding from local or network sources of entropy.
  //
  // Usage:
  //
  // <script src=http://davidbau.com/encode/seedrandom-min.js></script>
  //
  // Math.seedrandom('yipee'); Sets Math.random to a function that is
  // initialized using the given explicit seed.
  //
  // Math.seedrandom(); Sets Math.random to a function that is
  // seeded using the current time, dom state,
  // and other accumulated local entropy.
  // The generated seed string is returned.
  //
  // Math.seedrandom('yowza', true);
  // Seeds using the given explicit seed mixed
  // together with accumulated entropy.
  //
  // <script src="http://bit.ly/srandom-512"></script>
  // Seeds using physical random bits downloaded
  // from random.org.
  //
  // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
  // </script> Seeds using urandom bits from call.jsonlib.com,
  // which is faster than random.org.
  //
  // Examples:
  //
  // Math.seedrandom("hello"); // Use "hello" as the seed.
  // document.write(Math.random()); // Always 0.5463663768140734
  // document.write(Math.random()); // Always 0.43973793770592234
  // var rng1 = Math.random; // Remember the current prng.
  //
  // var autoseed = Math.seedrandom(); // New prng with an automatic seed.
  // document.write(Math.random()); // Pretty much unpredictable.
  //
  // Math.random = rng1; // Continue "hello" prng sequence.
  // document.write(Math.random()); // Always 0.554769432473455
  //
  // Math.seedrandom(autoseed); // Restart at the previous seed.
  // document.write(Math.random()); // Repeat the 'unpredictable' value.
  //
  // Notes:
  //
  // Each time seedrandom('arg') is called, entropy from the passed seed
  // is accumulated in a pool to help generate future seeds for the
  // zero-argument form of Math.seedrandom, so entropy can be injected over
  // time by calling seedrandom with explicit data repeatedly.
  //
  // On speed - This javascript implementation of Math.random() is about
  // 3-10x slower than the built-in Math.random() because it is not native
  // code, but this is typically fast enough anyway. Seeding is more expensive,
  // especially if you use auto-seeding. Some details (timings on Chrome 4):
  //
  // Our Math.random() - avg less than 0.002 milliseconds per call
  // seedrandom('explicit') - avg less than 0.5 milliseconds per call
  // seedrandom('explicit', true) - avg less than 2 milliseconds per call
  // seedrandom() - avg about 38 milliseconds per call
  //
  // LICENSE (BSD):
  //
  // Copyright 2010 David Bau, all rights reserved.
  //
  // Redistribution and use in source and binary forms, with or without
  // modification, are permitted provided that the following conditions are met:
  //
  // 1. Redistributions of source code must retain the above copyright
  // notice, this list of conditions and the following disclaimer.
  //
  // 2. Redistributions in binary form must reproduce the above copyright
  // notice, this list of conditions and the following disclaimer in the
  // documentation and/or other materials provided with the distribution.
  //
  // 3. Neither the name of this module nor the names of its contributors may
  // be used to endorse or promote products derived from this software
  // without specific prior written permission.
  //
  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  //
  /**
  * All code is in an anonymous closure to keep the global namespace clean.
  *
  * @param {number=} overflow
  * @param {number=} startdenom
  */
  (function (pool, math, width, chunks, significance, overflow, startdenom) {
 
 
  //
  // seedrandom()
  // This is the seedrandom function described above.
  //
  math['seedrandom'] = function seedrandom(seed, use_entropy) {
  var key = [];
  var arc4;
 
  // Flatten the seed string or build one from local entropy if needed.
  seed = mixkey(flatten(
  use_entropy ? [seed, pool] :
  arguments.length ? seed :
  [new Date().getTime(), pool, window], 3), key);
 
  // Use the seed to initialize an ARC4 generator.
  arc4 = new ARC4(key);
 
  // Mix the randomness into accumulated entropy.
  mixkey(arc4.S, pool);
 
  // Override Math.random
 
  // This function returns a random double in [0, 1) that contains
  // randomness in every bit of the mantissa of the IEEE 754 value.
 
  math['random'] = function random() { // Closure to return a random double:
  var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
  var d = startdenom; // and denominator d = 2 ^ 48.
  var x = 0; // and no 'extra last byte'.
  while (n < significance) { // Fill up all significant digits by
  n = (n + x) * width; // shifting numerator and
  d *= width; // denominator and generating a
  x = arc4.g(1); // new least-significant-byte.
  }
  while (n >= overflow) { // To avoid rounding up, before adding
  n /= 2; // last byte, shift everything
  d /= 2; // right using integer math until
  x >>>= 1; // we have exactly the desired bits.
  }
  return (n + x) / d; // Form the number within [0, 1).
  };
 
  // Return the seed that was used
  return seed;
  };
 
  //
  // ARC4
  //
  // An ARC4 implementation. The constructor takes a key in the form of
  // an array of at most (width) integers that should be 0 <= x < (width).
  //
  // The g(count) method returns a pseudorandom integer that concatenates
  // the next (count) outputs from ARC4. Its return value is a number x
  // that is in the range 0 <= x < (width ^ count).
  //
  /** @constructor */
  function ARC4(key) {
  var t, u, me = this, keylen = key.length;
  var i = 0, j = me.i = me.j = me.m = 0;
  me.S = [];
  me.c = [];
 
  // The empty key [] is treated as [0].
  if (!keylen) { key = [keylen++]; }
 
  // Set up S using the standard key scheduling algorithm.
  while (i < width) { me.S[i] = i++; }
  for (i = 0; i < width; i++) {
  t = me.S[i];
  j = lowbits(j + t + key[i % keylen]);
  u = me.S[j];
  me.S[i] = u;
  me.S[j] = t;
  }
 
  // The "g" method returns the next (count) outputs as one number.
  me.g = function getnext(count) {
  var s = me.S;
  var i = lowbits(me.i + 1); var t = s[i];
  var j = lowbits(me.j + t); var u = s[j];
  s[i] = u;
  s[j] = t;
  var r = s[lowbits(t + u)];
  while (--count) {
  i = lowbits(i + 1); t = s[i];
  j = lowbits(j + t); u = s[j];
  s[i] = u;
  s[j] = t;
  r = r * width + s[lowbits(t + u)];
  }
  me.i = i;
  me.j = j;
  return r;
  };
  // For robust unpredictability discard an initial batch of values.
  // See http://www.rsa.com/rsalabs/node.asp?id=2009
  me.g(width);
  }
 
  //
  // flatten()
  // Converts an object tree to nested arrays of strings.
  //
  /** @param {Object=} result
  * @param {string=} prop
  * @param {string=} typ */
  function flatten(obj, depth, result, prop, typ) {
  result = [];
  typ = typeof(obj);
  if (depth && typ == 'object') {
  for (prop in obj) {
  if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
  try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  }
  }
  }
  return (result.length ? result : obj + (typ != 'string' ? '\0' : ''));
  }
 
  //
  // mixkey()
  // Mixes a string seed into a key that is an array of integers, and
  // returns a shortened string seed that is equivalent to the result key.
  //
  /** @param {number=} smear
  * @param {number=} j */
  function mixkey(seed, key, smear, j) {
  seed += ''; // Ensure the seed is a string
  smear = 0;
  for (j = 0; j < seed.length; j++) {
  key[lowbits(j)] =
  lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
  }
  seed = '';
  for (j in key) { seed += String.fromCharCode(key[j]); }
  return seed;
  }
 
  //
  // lowbits()
  // A quick "n mod width" for width a power of 2.
  //
  function lowbits(n) { return n & (width - 1); }
 
  //
  // The following constants are related to IEEE 754 limits.
  //
  startdenom = math.pow(width, chunks);
  significance = math.pow(2, significance);
  overflow = significance * 2;
 
  //
  // When seedrandom.js is loaded, we immediately mix a few bits
  // from the built-in RNG into the entropy pool. Because we do
  // not want to intefere with determinstic PRNG state later,
  // seedrandom will not call math.random on its own again after
  // initialization.
  //
  mixkey(math.random(), pool);
 
  // End anonymous scope, and pass initial values.
  })(
  [], // pool: entropy pool starts empty
  Math, // math: package containing random, pow, and seedrandom
  256, // width: each RC4 output is 0 <= x < 256
  6, // chunks: at least six RC4 outputs for each double
  52 // significance: there are 52 significant digits in a double
  );
 
  <?php
 
  class CSVParser {
  var $fp = null;
  var $delimiter = null;
  var $enclosure = null;
 
  function __construct($file, $delimiter = ',', $enclosure = '"'){
  $this->fp = fopen($file, 'r');
  $this->delimiter = $delimiter;
  $this->enclosure = $enclosure;
  }
 
  function __destruct(){
  fclose($this->fp);
  }
 
  function getFlotrData($lines_count = 1000000){
  $data = array();
  $ticks = array();
 
  $this->nextLine();
  $x = 0;
  while(($line = $this->nextLine()) && $lines_count--){
  $d = array($x);
  $i = 1;
  while ($i < 5 && $value = $line[$i++]) {
  $d[] = floatval($value);
  }
  $data[] = $d;
  $ticks[] = array($x, $line[0]);
 
  $x++;
  }
  return array('ticks' => $ticks, 'data' => $data);
  }
 
  function reset(){
  rewind($this->fp);
  }
 
  function nextLine(){
  return fgetcsv($this->fp, null, $this->delimiter, $this->enclosure);
  }
  }
 
  $parser = new CSVParser('http://ichart.finance.yahoo.com/table.csv?s=AAPL&a=00&b=1&c=1999&d=11&e=31&f=2020&g=m&ignore=.csv');
 
  echo json_encode($parser->getFlotrData(30));
 
  ?>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: Basic Watermark Example</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
 
  <script type="text/javascript" src="../../flotr/prototype/lib/prototype.js"></script>
  <script type="text/javascript" src="examples.js"></script>
 
  <!--[if IE]>
  <script type="text/javascript" src="../../flotr/prototype/lib/excanvas.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/lib/base64.js"></script>
  <![endif]-->
  <script type="text/javascript" src="../../flotr/prototype/lib/canvas2image.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/lib/canvastext.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/flotr.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="container" style="width:600px;height:300px;"></div>
  <h2>Example</h2>
  <p>This example shows a basic Flotr graph with a watermark image.</p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  /**
  * Wait till dom's finished loading.
  */
  document.observe('dom:loaded', function () {
  /**
  * Fill series d1 and d2.
  */
  var d1 = [];
  for (var i = 0; i < 14; i += 0.5)
  d1.push([i, Math.sin(i)]);
 
  var d2 = [
  [0, 3],
  [4, 8],
  [8, 5],
  [9, 13]
  ];
 
  /**
  * Draw the graph.
  */
  var f = Flotr.draw($('container'), [d1, d2], {
  grid: {
  /**
  * The watermark can be added in two ways:
  */
  //backgroundImage: 'images/butterfly.jpg'
  /**
  * However, if you need positioning and/or transparancy, use:
  */
  backgroundImage: {
  left: 60,
  src: 'images/butterfly.jpg',
  alpha: 0.3
  },
  }
  });
  });
  </script>
 
  <!-- analytics -->
  </body>
  </html>
 
 Binary files /dev/null and b/js/flotr2/examples/old_examples/blank.cur differ
  // Gets the value from a group of radio buttons
  function getV(nl) {
  var v = null;
  _.each(nl, function(e) {
  if (e.checked) {
  v = e.value;
  return;
  }
  });
  return v;
  }
 
  (function(){
  var view = document.getElementById('code-view');
  if (view) {
  var code = document.body.getElementsByTagName('script')[0].innerHTML.replace(/\n\t\t\t/g, '\n');
  if (view.outerHTML)
  view.outerHTML = '<pre id="code-view"><code class="javascript">' + code + '</code></pre>';
  else
  view.innerHTML = code;
  }
 
  document.getElementById('wrapper').getElementsByTagName('h1')[0].innerHTML =
  document.getElementsByTagName('title')[0].innerHTML;
  })();
 
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: Extending Flotr</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="container" style="width:600px;height:300px;"></div>
  <h2>Flotr Structure</h2>
  <p>This example shows you how to extend Flotr. But before you begin, it's important to know how Flotr is structured.
  Flotr consists of two important parts. The first one is the Flotr object. This object acts like a namespace for
  all utility functions, just to be sure it doesn't collide with the environment. </p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  // @TODO fix it
  function example(){
 
  var MyGraph = Class.create(Flotr.Graph, {
  drawCount: 0,
  drawSeries: function($super, series){
  this.drawCount++;
  $super(series);
  }
  });
 
  /**
  * Fill series d1 and d2.
  */
  var d1 = [];
  for(var i = 0; i < 14; i += 0.5)
  d1.push([i, Math.sin(i)]);
 
  var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];
 
  /**
  * Draw the graph.
  */
  var f = Flotr.draw($('container'), [ d1, d2 ], null, MyGraph);
 
  alert('Draw count: '+f.drawCount);
  };
  </script>
 
  <!-- analytics -->
  </body>
  <script type="text/javascript" src="includes.js"></script>
  </html>
 
  yepnope([
  // Libs
  '../lib/bean-min.js',
  '../lib/underscore-min.js',
  {
  test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
  // Load for IE < 9
  yep : [
  '../lib/excanvas.js',
  '../lib/base64.js'
  ]
  },
  '../lib/canvas2image.js',
  '../lib/canvastext.js',
 
  // Examples
  'examples.js',
 
  // Flotr
  '../js/Flotr.js',
  '../js/Flotr.defaultOptions.js',
  '../js/Flotr.Color.js',
  '../js/Flotr.Date.js',
  '../js/Flotr.DOM.js',
  '../js/Flotr.EventAdapter.js',
  '../js/Flotr.Graph.js',
  '../js/Flotr.Axis.js',
  '../js/Flotr.Series.js',
  '../js/types/lines.js',
  '../js/types/bars.js',
  '../js/types/points.js',
  '../js/types/pie.js',
  '../js/types/candles.js',
  '../js/types/markers.js',
  '../js/types/radar.js',
  '../js/types/bubbles.js',
  '../js/plugins/selection.js',
  '../js/plugins/spreadsheet.js',
  '../js/plugins/hit.js',
  '../js/plugins/crosshair.js',
  '../js/plugins/labels.js',
  '../js/plugins/legend.js',
  '../js/plugins/titles.js',
  '../js/types/gantt.js',
  { complete : example }
  ]);
 
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr Example Index Page</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1>Flotr for Prototype.js Example Index</h1>
  <p>
  This is the <a href="http://www.solutoire.com/flotr">Flotr</a> for <a href="http://www.prototypejs.org/" target="_blank">Prototype.js</a> example index page. Here you can find links to various Flotr examples.
  Each example emphasizes a certain feature, but I think it's useful to read and understand all of the examples,
  even if they're of no use to you. Just to get a better understanding of Flotr.
  </p>
 
  <ul>
  <li><a href="basic.html">Basic Example</a></li>
  <li><a href="basic-axis.html">Basic Axis Example</a></li>
  <li><a href="basic-bar.html">Basic Bar Example</a></li>
  <li><a href="basic-stacked-bars.html">Basic Stacked Bars Example</a></li>
  <li><a href="basic-pie.html">Basic Pie Example</a></li>
  <li><a href="basic-radar.html">Basic Radar Example</a></li>
  <li><a href="basic-bubble.html">Basic Bubble Example</a></li>
  <li><a href="basic-candlesticks.html">Basic Candle sticks Example</a></li>
  <li><a href="basic-legend.html">Basic Legend Example</a></li>
  <li><a href="mouse-tracking.html">Mouse Tracking Support Example</a></li>
  <li><a href="mouse-zoom.html">Mouse Zoom Support Example</a></li>
  <li><a href="mouse-zoom-preview.html">Mouse Zoom with Preview Example</a></li>
  <li><a href="mouse-drag.html">Mouse Drag Support Example</a></li>
  <li><a href="basic-time.html">Basic Time Example</a></li>
  <li><a href="negative.html">Negative Value Support Example</a></li>
  <!-- <li><a href="extending-flotr.html">Extending Flotr Example</a></li> -->
  <li><a href="click-event.html">Click Event Hook Example</a></li>
  <!--
  <li><a href="json-real-data.html">JSON Request on Real Data Example</a></li>
  <li><a href="json-data.html">JSON Request Data Example</a></li>
  -->
  <li><a href="image-download.html">Download Image Example</a></li>
  <li><a href="data-download.html">Download CSV Example</a></li>
  <li><a href="advanced-titles.html">Advanced Titles Example</a></li>
  <li><a href="color-gradients.html">Color Gradients Example</a></li>
  </ul>
 
  <!-- <p>If you want to play more, go the playground <a href="../../playground/index.html" title="Flotr Playground">Flotr Playground</a>.</p> -->
  <p>Can't find what you're looking for? Check out the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation">Flotr Documentation</a>.</p>
 
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
 
  <!-- ad -->
 
  <!-- analytics -->
 
  </div>
  </body>
  </html>
 
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: JSON Data Example</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="container" style="display:none;width:600px;height:300px;"></div>
  <button disabled="disabled" id="json-btn">Request JSON</button>
  <h2>Example</h2>
  <p>
  This example shows you how to use JSON data with Flotr. The canvas container is hidden when the page is
  loaded. By pressing the button a GET request is send to <a href="json.txt">json.txt</a>.
  This returns a JSON string with data for three series. When the returned json is a valid object, the
  canvas container is shown and the graph is rendered with <code>Flotr.draw()</code>. Here's the requested json:
  </p>
  <pre><code class="javascript">{
  series:[{
  data:[[0,1],[1,4],[2,3],[3,6],[4,4.5]],
  points:{show:true},
  lines:{show:true}
  },
  [[0,0.5],[1,0.6],[2,1.8],[3,0.9],[4,2]],
  [[0,1.5],[1,2],[2,4.5],[3,3.5],[4,5.5]]
  ],
  options:{
  mouse:{track:true},
  xaxis:{noTicks:10, tickDecimals:1}
  }
  }</code></pre>
  <p>
  Let me give you one advise about JSON. To make sure you receive the data in the right format, use the Firefox extension <a href="http://www.getfirebug.com" title="Firebug Javascript Debug Extension">Firebug</a>
  to <code>console.log</code> (print) the response. With Firebug you can examine the Ajax request and it's response.
  Also, it's worth reading <a href="http://prototypejs.org/learn/json">Introduction to JSON</a> on PrototypeJS.org.
  </p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  function example(){
  var f = null,
  button = $('json-btn');
  button.disabled = false;
  button.observe('click', function(){
  /**
  * The json.txt contains a valid json string. Imagine this string
  * is generated by some server-side script.
  */
  new Ajax.Request('json.txt', {
  method:'get',
  onSuccess: function(transport){
  /**
  * Parse (eval) the JSON from the server.
  */
  var json = transport.responseText.evalJSON();
 
  if(json.series && json.options){
  /**
  * The json is valid! Display the canvas container.
  */
  $('container').show();
 
  /**
  * Draw the graph using the JSON data. Of course the
  * options are optional.
  */
  f = Flotr.draw($('container'), json.series, json.options);
  }
 
  }
  });
  });
  }
  </script>
 
  <!-- analytics -->
 
  </body>
  <script type="text/javascript" src="includes.js"></script>
  </html>
 
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: JSON on Real Data Example</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="container" style="width:600px;height:300px;"></div>
  <h2>Example</h2>
  <p>
  This example shows you how to use JSON data with Flotr. The canvas container is hidden when the page is
  loaded. By pressing the button a GET request is send to <a href="json.txt">json.txt</a>.
  This returns a JSON string with data for three series. When the returned json is a valid object, the
  canvas container is shown and the graph is rendered with <code>Flotr.draw()</code>. Here's the requested json:
  </p>
  <p>
  Let me give you one advise about JSON. To make sure you receive the data in the right format, use the Firefox extension <a href="http://www.getfirebug.com" title="Firebug Javascript Debug Extension">Firebug</a>
  to <code>console.log</code> (print) the response. With Firebug you can examine the Ajax request and it's response.
  Also, it's worth reading <a href="http://prototypejs.org/learn/json">Introduction to JSON</a> on PrototypeJS.org.
  </p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  var f = null;
  function example(){
  /**
  * The ajax-financial-data.php retrieves data drom the Yahoo Ichart application.
  */
  new Ajax.Request('ajax-financial-data.php', {
  method:'get',
  onSuccess: function(transport){
  /**
  * Parse (eval) the JSON from the server.
  */
  var json = transport.responseText.evalJSON();
 
  if(json.data && json.ticks){
  var options = {
  title: "Apple Inc. real time quotes",
  xaxis: {ticks: json.ticks, labelsAngle: 45},
  candles: {show: true, candleWidth: 0.6},
  HtmlText: false
  };
 
  /**
  * Draw the graph using the JSON data. Of course the
  * options are optional.
  */
  f = Flotr.draw($('container'), [json.data], options);
  }
  else {
  $('container').update('The data could not be retrieved. Check if your server can access yahoo.com and has PHP and the php_json extension.')
  }
  }
  });
  };
  </script>
 
  <!-- analytics -->
 
  </body>
  <script type="text/javascript" src="includes.js"></script>
  </html>
 
  {
  series:[{
  data:[[0,1],[1,4],[2,3],[3,6],[4,4.5]],
  points:{show:true},
  lines:{show:true}
  },
  [[0,0.5],[1,0.6],[2,1.8],[3,0.9],[4,2]],
  [[0,1.5],[1,2],[2,4.5],[3,3.5],[4,5.5]]
  ],
  options:{
  mouse:{track:true},
  xaxis:{noTicks:10, tickDecimals:1}
  }
  }
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: Logarithmic Scale Example</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
 
  <script type="text/javascript" src="../../flotr/prototype/lib/prototype.js"></script>
  <script type="text/javascript" src="examples.js"></script>
 
  <!--[if IE]>
  <script type="text/javascript" src="../../flotr/prototype/lib/excanvas.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/lib/base64.js"></script>
  <![endif]-->
  <script type="text/javascript" src="../../flotr/prototype/lib/canvas2image.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/lib/canvastext.js"></script>
  <script type="text/javascript" src="../../flotr/prototype/flotr.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="container" style="width:600px;height:600px;"></div>
  <h2>Example</h2>
  <p>This graph shows how logarithmic scale is handled</p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  window.onload= function(){
  var d1 = [];
 
  var i;
  for(i = -10; i <= 10; i += 0.1){
  d1.push([i, Math.exp(i)]);
  }
 
  /**
  * Draw the graph.
  */
  var f = Flotr.draw(
  $('container'),[
  {data:d1, label:'exp(x)'}
  ],{
  yaxis:{
  ticks: [10e-5, 10e-4, 10e-3, 10e-2, 10e-1, 10e0, 10e1, 10e2, 10e3, 10e4, 10e5],
  scaling:'logarithmic',
  //base: 0.5,
  min: 10e-6,
  max: 10e6
  },
  spreadsheet:{
  show: true
  },
  mouse: {track: true}
  });
  }
  </script>
 
  <!-- analytics -->
 
  </body>
  </html>
 
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr: Mouse Zoom With Preview Example</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  </head>
  <body>
 
  <!-- ad -->
 
  <div id="wrapper">
  <h1></h1>
  <div id="overview" style="width:200px;height:100px;float:right;"></div>
  <div id="container" style="width:500px;height:250px;"></div>
  <h2>Example</h2>
  <p>This example show an enhancement of the mouse-zoom example. It displays an overview of the graph. By selecting an area in the graph or in the overview, the graph is zoomed. Read more about the <a href="http://www.solutoire.com/flotr/docs/eventhooks/" title="Flotr Event Hooks">event hooks</a>.</p>
  <p>Finished? Go to the example <a href="index.html" title="Flotr Example Index Page">index page</a>, play with the <a href="../../playground/index.html" title="Flotr playground">playground</a> or read the <a href="http://www.solutoire.com/flotr/docs/" title="Flotr Documentation Pages">Flotr Documentation Pages</a>.</p>
  <p><button id="reset-btn">Reset</button></p>
  <h2>The Code</h2>
  <pre id="code-view"><code class="javascript"></code></pre>
  <div id="footer">Copyright &copy; 2008 Bas Wenneker, <a href="http://www.solutoire.com">solutoire.com</a></div>
  </div>
 
  <!-- ad -->
 
  <script type="text/javascript">
  function example(){
 
  var container = document.getElementById('container'),
  overviewContainer = document.getElementById('overview');
 
  /**
  * Fill series d1 and d2.
  */
  var d1 = [];
  var d2 = [];
  var d3 = [];
  for(var i = 0; i < 40; i += 0.5){
  d1.push([i, Math.sin(i)+3*Math.cos(i)]);
  d2.push([i, Math.pow(1.1, i)]);
  d3.push([i, 40 - i+Math.random()*10]);
  }
 
  /**
  * Global options object.
  */
  var options = {
  selection: { mode:'xy', fps:30 }
  };
 
  // setup overview
  var overviewOptions = {
  lines: { show: true, lineWidth: 1 },
  shadowSize: 0,
  grid: { color: '#999', outlineWidth: 1 },
  selection: { mode: 'xy' }
  };
 
  /**
  * Function displays a graph in the 'container' element, extending
  * the global options object with the optionally passed options.
  */
  function drawGraph(opts){
  /**
  * Clone the options, so the 'options' variable always keeps intact.
  */
  var o = _.extend(_.clone(options), opts || {});
  /**
  * Return a new graph.
  */
  return Flotr.draw(
  container,
  [ d1, d2, d3 ],
  o
  );
  }
 
  /**
  * Function displays a graph in the 'overview' element.
  */
  function drawOverview(){
  return Flotr.draw(
  overviewContainer,
  [ d1, d2, d3 ],
  overviewOptions
  );
  }
 
  /**
  * Actually draw the graphs.
  */
  var f = drawGraph();
  var overview = drawOverview();
 
  /**
  * Hook into the 'flotr:select' event.
  */
  Flotr.EventAdapter.observe(container, 'flotr:select', function(area){
  /**
  * Do the zooming.
  */
  f = drawGraph({
  xaxis: {min:area.x1, max:area.x2},
  yaxis: {min:area.y1, max:area.y2}
  });
 
  // don't fire event on the overview to prevent eternal loop
  overview.setSelection(area, true);
  });
 
  /**
  * Hook into the 'flotr:select' event from overview.
  */
  Flotr.EventAdapter.observe(overview, 'flotr:select', function(evt){
  f.setSelection(evt.memo[0]);
  });
 
  /**
  * Observe click event on the reset-btn. Reset the graph when clicked.
  * The drawGraph function wrapped in another function otherwise it get's
  * an Event object passed as first argument, while it expects an options
  * object.
  */
  document.getElementById('reset-btn').onclick = function(){
  drawGraph();
  drawOverview();
  };
  };
  </script>
 
  <!-- analytics -->
 
  </body>
  <script type="text/javascript" src="includes.js"></script>
  </html>
 
  body{
  font-family:Arial,Helvetica,sans-serif;
  font-size: 12px;
  }
 
  #wrapper{
  width: 700px;
  margin: 50px auto;
  }
 
  a:link, a:visited{
  color: #004892;
  font-weight: bold;
  text-decoration: none;
  }
 
  a:visited{
  color: #1763b5;
  }
 
  a:focus, a:hover, a:active{
  color: #3c85d4;
  background-color: #b6d9ff;
  }
 
  h1, h2, h3 {
  font-family:Georgia,"Times New Roman",Times,serif;
  font-style:italic;
  font-weight:normal;
  letter-spacing:-1px;
  font-size: 1.5em;
  color: #050404;
  }
 
  h2{
  font-size: 1.4em;
  }
 
  p{
  margin: 10px;
  }
 
  code {
  background: #b6d9ff;
  font-size: 0.9em;
  color: #004892;
  }
 
  pre{
  border: 4px solid #B6D9FF;
  background:#d2e8ff;
  color: #004892;
  padding: 15px;
  margin:5px 0;
  }
 
  pre code{
  background-color: transparent;
  display:block;
  line-height:16px;
  overflow-x: auto;
  overflow-y: hidden;
  white-space:pre;
  padding:0 5px;
  }
 
  #footer{
  margin: 30px 0;
  text-align:center;
  }
 
  iframe {
  border:3px solid #B6D9FF;
  }
 
  .ad{
  width: 740px;
  margin: 10px auto;
  }
 
  .flotr-datagrid-container {
  border: 1px solid #999;
  border-bottom: none;
  background: #fff;
  }
  .flotr-datagrid {
  border-collapse: collapse;
  border-spacing: 0;
  }
  .flotr-datagrid td, .flotr-datagrid th {
  border: 1px solid #ccc;
  padding: 1px 3px;
  min-width: 2em;
  }
  .flotr-datagrid tr:hover, .flotr-datagrid col.hover {
  background: #f3f3f3;
  }
  .flotr-datagrid tr:hover th, .flotr-datagrid th.hover {
  background: #999;
  color: #fff;
  }
  .flotr-datagrid th {
  text-align: left;
  background: #e3e3e3;
  border: 2px outset #fff;
  }
  .flotr-datagrid-toolbar {
  padding: 1px;
  border-bottom: 1px solid #ccc;
  background: #f9f9f9;
  }
  .flotr-datagrid td:hover {
  background: #ccc;
  }
  .flotr-datagrid .first-row th {
  text-align: center;
  }
  .flotr-canvas {
  margin-bottom: -3px;
  padding-bottom: 1px;
  }
  .flotr-tabs-group {
  border-top: 1px solid #999;
  }
  .flotr-tab {
  border: 1px solid #666;
  border-top: none;
  margin: 0 3px;
  padding: 1px 4px;
  cursor: pointer;
  -moz-border-radius: 0 0 4px 4px;
  -webkit-border-bottom-left-radius: 4px;
  -webkit-border-bottom-right-radius: 4px;
  border-radius: 0 0 4px 4px;
  opacity: 0.5;
  -moz-opacity: 0.5;
  }
  .flotr-tab.selected {
  background: #ddd;
  opacity: 1;
  -moz-opacity: 1;
  }
  .flotr-tab:hover {
  background: #ccc;
  }
  <!DOCTYPE html>
  <html>
 
  <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Flotr Example Index Page</title>
  <link rel="stylesheet" href="examples.css" type="text/css" />
  <link rel="stylesheet" href="lib/google-code-prettify/prettify.css" type="text/css" />
  </head>
 
  <body>
 
  <div id="body-container">
 
  <div id="content-container">
  <div id="content">
 
  <h2>Examples:</h2>
  <div id="examples"></div>
  <div id="example-highlight"></div>
 
  <div id="example">
  <h3 id="example-label">Example:</h3>
  <div id="example-graph"></div>
  <div id="example-description"></div>
 
  <div id="example-profile-container">
  <h3>Profile:</h3>
  <div id="example-profile"></div>
  </div>
 
  <div id="example-source-container">
  <h3>Source:</h3>
  <div id="example-source"></div>
  <textarea id="example-editor"></textarea>
  <div id="example-buttons">
  <button id="example-run">Run</button>
  <button id="example-edit">Edit</button>
  </div>
  </div>
  </div>
 
  </div>
  </div>
 
  </div>
 
 
 
  </body>
 
  <script>
  Flotr = {};
  Flotr.ExamplesCallback = function () {
  Profile = new Flotr.Profile();
  };
  </script>
 
  <script type="text/javascript" src="../lib/yepnope.js"></script>
  <script type="text/javascript" src="js/includes.dev.js"></script>
 
  </html>
 
  (function (root, factory) {
  if (typeof define === 'function' && define.amd) {
  // AMD. Register as an anonymous module.
  define(['bean', 'underscore'], function (bean, _) {
  // Also create a global in case some scripts
  // that are loaded still are looking for
  // a global even when an AMD loader is in use.
  return (root.Flotr = factory(bean, _));
  });
  } else {
  // Browser globals
  root.Flotr = factory(root.bean, root._);
  }
  }(this, function (bean, _) {
 
  /**
  * Flotr2 (c) 2012 Carl Sutherland
  * MIT License
  * Special thanks to:
  * Flotr: http://code.google.com/p/flotr/ (fork)
  * Flot: https://github.com/flot/flot (original fork)
  */
  (function () {
 
  var
  global = this,
  previousFlotr = this.Flotr,
  Flotr;
 
  Flotr = {
  _: _,
  bean: bean,
  isIphone: /iphone/i.test(navigator.userAgent),
  isIE: (navigator.appVersion.indexOf("MSIE") != -1 ? parseFloat(navigator.appVersion.split("MSIE")[1]) : false),
 
  /**
  * An object of the registered graph types. Use Flotr.addType(type, object)
  * to add your own type.
  */
  graphTypes: {},
 
  /**
  * The list of the registered plugins
  */
  plugins: {},
 
  /**
  * Can be used to add your own chart type.
  * @param {String} name - Type of chart, like 'pies', 'bars' etc.
  * @param {String} graphType - The object containing the basic drawing functions (draw, etc)
  */
  addType: function(name, graphType){
  Flotr.graphTypes[name] = graphType;
  Flotr.defaultOptions[name] = graphType.options || {};
  Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
  },
 
  /**
  * Can be used to add a plugin
  * @param {String} name - The name of the plugin
  * @param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
  */
  addPlugin: function(name, plugin){
  Flotr.plugins[name] = plugin;
  Flotr.defaultOptions[name] = plugin.options || {};
  },
 
  /**
  * Draws the graph. This function is here for backwards compatibility with Flotr version 0.1.0alpha.
  * You could also draw graphs by directly calling Flotr.Graph(element, data, options).
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  * @param {Class} _GraphKlass_ - (optional) Class to pass the arguments to, defaults to Flotr.Graph
  * @return {Object} returns a new graph object and of course draws the graph.
  */
  draw: function(el, data, options, GraphKlass){
  GraphKlass = GraphKlass || Flotr.Graph;
  return new GraphKlass(el, data, options);
  },
 
  /**
  * Recursively merges two objects.
  * @param {Object} src - source object (likely the object with the least properties)
  * @param {Object} dest - destination object (optional, object with the most properties)
  * @return {Object} recursively merged Object
  * @TODO See if we can't remove this.
  */
  merge: function(src, dest){
  var i, v, result = dest || {};
 
  for (i in src) {
  v = src[i];
  if (v && typeof(v) === 'object') {
  if (v.constructor === Array) {
  result[i] = this._.clone(v);
  } else if (v.constructor !== RegExp && !this._.isElement(v)) {
  result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
  } else {
  result[i] = v;
  }
  } else {
  result[i] = v;
  }
  }
 
  return result;
  },
 
  /**
  * Recursively clones an object.
  * @param {Object} object - The object to clone
  * @return {Object} the clone
  * @TODO See if we can't remove this.
  */
  clone: function(object){
  return Flotr.merge(object, {});
  },
 
  /**
  * Function calculates the ticksize and returns it.
  * @param {Integer} noTicks - number of ticks
  * @param {Integer} min - lower bound integer value for the current axis
  * @param {Integer} max - upper bound integer value for the current axis
  * @param {Integer} decimals - number of decimals for the ticks
  * @return {Integer} returns the ticksize in pixels
  */
  getTickSize: function(noTicks, min, max, decimals){
  var delta = (max - min) / noTicks,
  magn = Flotr.getMagnitude(delta),
  tickSize = 10,
  norm = delta / magn; // Norm is between 1.0 and 10.0.
 
  if(norm < 1.5) tickSize = 1;
  else if(norm < 2.25) tickSize = 2;
  else if(norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
  else if(norm < 7.5) tickSize = 5;
 
  return tickSize * magn;
  },
 
  /**
  * Default tick formatter.
  * @param {String, Integer} val - tick value integer
  * @param {Object} axisOpts - the axis' options
  * @return {String} formatted tick string
  */
  defaultTickFormatter: function(val, axisOpts){
  return val+'';
  },
 
  /**
  * Formats the mouse tracker values.
  * @param {Object} obj - Track value Object {x:..,y:..}
  * @return {String} Formatted track string
  */
  defaultTrackFormatter: function(obj){
  return '('+obj.x+', '+obj.y+')';
  },
 
  /**
  * Utility function to convert file size values in bytes to kB, MB, ...
  * @param value {Number} - The value to convert
  * @param precision {Number} - The number of digits after the comma (default: 2)
  * @param base {Number} - The base (default: 1000)
  */
  engineeringNotation: function(value, precision, base){
  var sizes = ['Y','Z','E','P','T','G','M','k',''],
  fractionSizes = ['y','z','a','f','p','n','µ','m',''],
  total = sizes.length;
 
  base = base || 1000;
  precision = Math.pow(10, precision || 2);
 
  if (value === 0) return 0;
 
  if (value > 1) {
  while (total-- && (value >= base)) value /= base;
  }
  else {
  sizes = fractionSizes;
  total = sizes.length;
  while (total-- && (value < 1)) value *= base;
  }
 
  return (Math.round(value * precision) / precision) + sizes[total];
  },
 
  /**
  * Returns the magnitude of the input value.
  * @param {Integer, Float} x - integer or float value
  * @return {Integer, Float} returns the magnitude of the input value
  */
  getMagnitude: function(x){
  return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
  },
  toPixel: function(val){
  return Math.floor(val)+0.5;//((val-Math.round(val) < 0.4) ? (Math.floor(val)-0.5) : val);
  },
  toRad: function(angle){
  return -angle * (Math.PI/180);
  },
  floorInBase: function(n, base) {
  return base * Math.floor(n / base);
  },
  drawText: function(ctx, text, x, y, style) {
  if (!ctx.fillText) {
  ctx.drawText(text, x, y, style);
  return;
  }
 
  style = this._.extend({
  size: Flotr.defaultOptions.fontSize,
  color: '#000000',
  textAlign: 'left',
  textBaseline: 'bottom',
  weight: 1,
  angle: 0
  }, style);
 
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(style.angle);
  ctx.fillStyle = style.color;
  ctx.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  ctx.textAlign = style.textAlign;
  ctx.textBaseline = style.textBaseline;
  ctx.fillText(text, 0, 0);
  ctx.restore();
  },
  getBestTextAlign: function(angle, style) {
  style = style || {textAlign: 'center', textBaseline: 'middle'};
  angle += Flotr.getTextAngleFromAlign(style);
 
  if (Math.abs(Math.cos(angle)) > 10e-3)
  style.textAlign = (Math.cos(angle) > 0 ? 'right' : 'left');
 
  if (Math.abs(Math.sin(angle)) > 10e-3)
  style.textBaseline = (Math.sin(angle) > 0 ? 'top' : 'bottom');
 
  return style;
  },
  alignTable: {
  'right middle' : 0,
  'right top' : Math.PI/4,
  'center top' : Math.PI/2,
  'left top' : 3*(Math.PI/4),
  'left middle' : Math.PI,
  'left bottom' : -3*(Math.PI/4),
  'center bottom': -Math.PI/2,
  'right bottom' : -Math.PI/4,
  'center middle': 0
  },
  getTextAngleFromAlign: function(style) {
  return Flotr.alignTable[style.textAlign+' '+style.textBaseline] || 0;
  },
  noConflict : function () {
  global.Flotr = previousFlotr;
  return this;
  }
  };
 
  global.Flotr = Flotr;
 
  })();
 
  /**
  * Flotr Defaults
  */
  Flotr.defaultOptions = {
  colors: ['#00A8F0', '#C0D800', '#CB4B4B', '#4DA74D', '#9440ED'], //=> The default colorscheme. When there are > 5 series, additional colors are generated.
  ieBackgroundColor: '#FFFFFF', // Background color for excanvas clipping
  title: null, // => The graph's title
  subtitle: null, // => The graph's subtitle
  shadowSize: 4, // => size of the 'fake' shadow
  defaultType: null, // => default series type
  HtmlText: true, // => wether to draw the text using HTML or on the canvas
  fontColor: '#545454', // => default font color
  fontSize: 7.5, // => canvas' text font size
  resolution: 1, // => resolution of the graph, to have printer-friendly graphs !
  parseFloat: true, // => whether to preprocess data for floats (ie. if input is string)
  preventDefault: true, // => preventDefault by default for mobile events. Turn off to enable scroll.
  xaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 0, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => color of the ticks
  mode: 'normal', // => can be 'time' or 'normal'
  timeFormat: null,
  timeMode:'UTC', // => For UTC time ('local' for local time).
  timeUnit:'millisecond',// => Unit for time (millisecond, second, minute, hour, day, month, year)
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  x2axis: {},
  yaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 90, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => The color of the ticks
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  y2axis: {
  titleAngle: 270
  },
  grid: {
  color: '#545454', // => primary color used for outline and labels
  backgroundColor: null, // => null for transparent, else color
  backgroundImage: null, // => background image. String or object with src, left and top
  watermarkAlpha: 0.4, // =>
  tickColor: '#DDDDDD', // => color used for the ticks
  labelMargin: 3, // => margin in pixels
  verticalLines: true, // => whether to show gridlines in vertical direction
  minorVerticalLines: null, // => whether to show gridlines for minor ticks in vertical dir.
  horizontalLines: true, // => whether to show gridlines in horizontal direction
  minorHorizontalLines: null, // => whether to show gridlines for minor ticks in horizontal dir.
  outlineWidth: 1, // => width of the grid outline/border in pixels
  outline : 'nsew', // => walls of the outline to display
  circular: false // => if set to true, the grid will be circular, must be used when radars are drawn
  },
  mouse: {
  track: false, // => true to track the mouse, no tracking otherwise
  trackAll: false,
  position: 'se', // => position of the value box (default south-east)
  relative: false, // => next to the mouse cursor
  trackFormatter: Flotr.defaultTrackFormatter, // => formats the values in the value box
  margin: 5, // => margin in pixels of the valuebox
  lineColor: '#FF3F19', // => line color of points that are drawn when mouse comes near a value of a series
  trackDecimals: 1, // => decimals for the track values
  sensibility: 2, // => the lower this number, the more precise you have to aim to show a value
  trackY: true, // => whether or not to track the mouse in the y axis
  radius: 3, // => radius of the track point
  fillColor: null, // => color to fill our select bar with only applies to bar and similar graphs (only bars for now)
  fillOpacity: 0.4 // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  }
  };
 
  /**
  * Flotr Color
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  // Constructor
  function Color (r, g, b, a) {
  this.rgba = ['r','g','b','a'];
  var x = 4;
  while(-1<--x){
  this[this.rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
  }
  this.normalize();
  }
 
  // Constants
  var COLOR_NAMES = {
  aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],
  brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],
  darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],
  darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],
  darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],
  khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],
  lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],
  maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],
  violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]
  };
 
  Color.prototype = {
  scale: function(rf, gf, bf, af){
  var x = 4;
  while (-1 < --x) {
  if (!_.isUndefined(arguments[x])) this[this.rgba[x]] *= arguments[x];
  }
  return this.normalize();
  },
  alpha: function(alpha) {
  if (!_.isUndefined(alpha) && !_.isNull(alpha)) {
  this.a = alpha;
  }
  return this.normalize();
  },
  clone: function(){
  return new Color(this.r, this.b, this.g, this.a);
  },
  limit: function(val,minVal,maxVal){
  return Math.max(Math.min(val, maxVal), minVal);
  },
  normalize: function(){
  var limit = this.limit;
  this.r = limit(parseInt(this.r, 10), 0, 255);
  this.g = limit(parseInt(this.g, 10), 0, 255);
  this.b = limit(parseInt(this.b, 10), 0, 255);
  this.a = limit(this.a, 0, 1);
  return this;
  },
  distance: function(color){
  if (!color) return;
  color = new Color.parse(color);
  var dist = 0, x = 3;
  while(-1<--x){
  dist += Math.abs(this[this.rgba[x]] - color[this.rgba[x]]);
  }
  return dist;
  },
  toString: function(){
  return (this.a >= 1.0) ? 'rgb('+[this.r,this.g,this.b].join(',')+')' : 'rgba('+[this.r,this.g,this.b,this.a].join(',')+')';
  },
  contrast: function () {
  var
  test = 1 - ( 0.299 * this.r + 0.587 * this.g + 0.114 * this.b) / 255;
  return (test < 0.5 ? '#000000' : '#ffffff');
  }
  };
 
  _.extend(Color, {
  /**
  * Parses a color string and returns a corresponding Color.
  * The different tests are in order of probability to improve speed.
  * @param {String, Color} str - string thats representing a color
  * @return {Color} returns a Color object or false
  */
  parse: function(color){
  if (color instanceof Color) return color;
 
  var result;
 
  // #a0b1c2
  if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)))
  return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
 
  // rgb(num,num,num)
  if((result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
 
  // #fff
  if((result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)))
  return new Color(parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16));
 
  // rgba(num,num,num,num)
  if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
 
  // rgb(num%,num%,num%)
  if((result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);
 
  // rgba(num%,num%,num%,num)
  if((result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));
 
  // Otherwise, we're most likely dealing with a named color.
  var name = (color+'').replace(/^\s*([\S\s]*?)\s*$/, '$1').toLowerCase();
  if(name == 'transparent'){
  return new Color(255, 255, 255, 0);
  }
  return (result = COLOR_NAMES[name]) ? new Color(result[0], result[1], result[2]) : new Color(0, 0, 0, 0);
  },
 
  /**
  * Process color and options into color style.
  */
  processColor: function(color, options) {
 
  var opacity = options.opacity;
  if (!color) return 'rgba(0, 0, 0, 0)';
  if (color instanceof Color) return color.alpha(opacity).toString();
  if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
 
  var grad = color.colors ? color : {colors: color};
 
  if (!options.ctx) {
  if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
  return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
  }
  grad = _.extend({start: 'top', end: 'bottom'}, grad);
 
  if (/top/i.test(grad.start)) options.x1 = 0;
  if (/left/i.test(grad.start)) options.y1 = 0;
  if (/bottom/i.test(grad.end)) options.x2 = 0;
  if (/right/i.test(grad.end)) options.y2 = 0;
 
  var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
  for (i = 0; i < grad.colors.length; i++) {
  c = grad.colors[i];
  if (_.isArray(c)) {
  stop = c[0];
  c = c[1];
  }
  else stop = i / (grad.colors.length-1);
  gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
  }
  return gradient;
  }
  });
 
  Flotr.Color = Color;
 
  })();
 
  /**
  * Flotr Date
  */
  Flotr.Date = {
 
  set : function (date, name, mode, value) {
  mode = mode || 'UTC';
  name = 'set' + (mode === 'UTC' ? 'UTC' : '') + name;
  date[name](value);
  },
 
  get : function (date, name, mode) {
  mode = mode || 'UTC';
  name = 'get' + (mode === 'UTC' ? 'UTC' : '') + name;
  return date[name]();
  },
 
  format: function(d, format, mode) {
  if (!d) return;
 
  // We should maybe use an "official" date format spec, like PHP date() or ColdFusion
  // http://fr.php.net/manual/en/function.date.php
  // http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_c-d_29.html
  var
  get = this.get,
  tokens = {
  h: get(d, 'Hours', mode).toString(),
  H: leftPad(get(d, 'Hours', mode)),
  M: leftPad(get(d, 'Minutes', mode)),
  S: leftPad(get(d, 'Seconds', mode)),
  s: get(d, 'Milliseconds', mode),
  d: get(d, 'Date', mode).toString(),
  m: (get(d, 'Month', mode) + 1).toString(),
  y: get(d, 'FullYear', mode).toString(),
  b: Flotr.Date.monthNames[get(d, 'Month', mode)]
  };
 
  function leftPad(n){
  n += '';
  return n.length == 1 ? "0" + n : n;
  }
 
  var r = [], c,
  escape = false;
 
  for (var i = 0; i < format.length; ++i) {
  c = format.charAt(i);
 
  if (escape) {
  r.push(tokens[c] || c);
  escape = false;
  }
  else if (c == "%")
  escape = true;
  else
  r.push(c);
  }
  return r.join('');
  },
  getFormat: function(time, span) {
  var tu = Flotr.Date.timeUnits;
  if (time < tu.second) return "%h:%M:%S.%s";
  else if (time < tu.minute) return "%h:%M:%S";
  else if (time < tu.day) return (span < 2 * tu.day) ? "%h:%M" : "%b %d %h:%M";
  else if (time < tu.month) return "%b %d";
  else if (time < tu.year) return (span < tu.year) ? "%b" : "%b %y";
  else return "%y";
  },
  formatter: function (v, axis) {
  var
  options = axis.options,
  scale = Flotr.Date.timeUnits[options.timeUnit],
  d = new Date(v * scale);
 
  // first check global format
  if (axis.options.timeFormat)
  return Flotr.Date.format(d, options.timeFormat, options.timeMode);
 
  var span = (axis.max - axis.min) * scale,
  t = axis.tickSize * Flotr.Date.timeUnits[axis.tickUnit];
 
  return Flotr.Date.format(d, Flotr.Date.getFormat(t, span), options.timeMode);
  },
  generator: function(axis) {
 
  var
  set = this.set,
  get = this.get,
  timeUnits = this.timeUnits,
  spec = this.spec,
  options = axis.options,
  mode = options.timeMode,
  scale = timeUnits[options.timeUnit],
  min = axis.min * scale,
  max = axis.max * scale,
  delta = (max - min) / options.noTicks,
  ticks = [],
  tickSize = axis.tickSize,
  tickUnit,
  formatter, i;
 
  // Use custom formatter or time tick formatter
  formatter = (options.tickFormatter === Flotr.defaultTickFormatter ?
  this.formatter : options.tickFormatter
  );
 
  for (i = 0; i < spec.length - 1; ++i) {
  var d = spec[i][0] * timeUnits[spec[i][1]];
  if (delta < (d + spec[i+1][0] * timeUnits[spec[i+1][1]]) / 2 && d >= tickSize)
  break;
  }
  tickSize = spec[i][0];
  tickUnit = spec[i][1];
 
  // special-case the possibility of several years
  if (tickUnit == "year") {
  tickSize = Flotr.getTickSize(options.noTicks*timeUnits.year, min, max, 0);
 
  // Fix for 0.5 year case
  if (tickSize == 0.5) {
  tickUnit = "month";
  tickSize = 6;
  }
  }
 
  axis.tickUnit = tickUnit;
  axis.tickSize = tickSize;
 
  var step = tickSize * timeUnits[tickUnit];
  d = new Date(min);
 
  function setTick (name) {
  set(d, name, mode, Flotr.floorInBase(
  get(d, name, mode), tickSize
  ));
  }
 
  switch (tickUnit) {
  case "millisecond": setTick('Milliseconds'); break;
  case "second": setTick('Seconds'); break;
  case "minute": setTick('Minutes'); break;
  case "hour": setTick('Hours'); break;
  case "month": setTick('Month'); break;
  case "year": setTick('FullYear'); break;
  }
 
  // reset smaller components
  if (step >= timeUnits.second) set(d, 'Milliseconds', mode, 0);
  if (step >= timeUnits.minute) set(d, 'Seconds', mode, 0);
  if (step >= timeUnits.hour) set(d, 'Minutes', mode, 0);
  if (step >= timeUnits.day) set(d, 'Hours', mode, 0);
  if (step >= timeUnits.day * 4) set(d, 'Date', mode, 1);
  if (step >= timeUnits.year) set(d, 'Month', mode, 0);
 
  var carry = 0, v = NaN, prev;
  do {
  prev = v;
  v = d.getTime();
  ticks.push({ v: v / scale, label: formatter(v / scale, axis) });
  if (tickUnit == "month") {
  if (tickSize < 1) {
  /* a bit complicated - we'll divide the month up but we need to take care of fractions
  so we don't end up in the middle of a day */
  set(d, 'Date', mode, 1);
  var start = d.getTime();
  set(d, 'Month', mode, get(d, 'Month', mode) + 1);
  var end = d.getTime();
  d.setTime(v + carry * timeUnits.hour + (end - start) * tickSize);
  carry = get(d, 'Hours', mode);
  set(d, 'Hours', mode, 0);
  }
  else
  set(d, 'Month', mode, get(d, 'Month', mode) + tickSize);
  }
  else if (tickUnit == "year") {
  set(d, 'FullYear', mode, get(d, 'FullYear', mode) + tickSize);
  }
  else
  d.setTime(v + step);
 
  } while (v < max && v != prev);
 
  return ticks;
  },
  timeUnits: {
  millisecond: 1,
  second: 1000,
  minute: 1000 * 60,
  hour: 1000 * 60 * 60,
  day: 1000 * 60 * 60 * 24,
  month: 1000 * 60 * 60 * 24 * 30,
  year: 1000 * 60 * 60 * 24 * 365.2425
  },
  // the allowed tick sizes, after 1 year we use an integer algorithm
  spec: [
  [1, "millisecond"], [20, "millisecond"], [50, "millisecond"], [100, "millisecond"], [200, "millisecond"], [500, "millisecond"],
  [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"],
  [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"],
  [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"],
  [1, "day"], [2, "day"], [3, "day"],
  [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"],
  [1, "year"]
  ],
  monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  };
 
  (function () {
 
  var _ = Flotr._;
 
  Flotr.DOM = {
  addClass: function(element, name){
  var classList = (element.className ? element.className : '');
  if (_.include(classList.split(/\s+/g), name)) return;
  element.className = (classList ? classList + ' ' : '') + name;
  },
  /**
  * Create an element.
  */
  create: function(tag){
  return document.createElement(tag);
  },
  node: function(html) {
  var div = Flotr.DOM.create('div'), n;
  div.innerHTML = html;
  n = div.children[0];
  div.innerHTML = '';
  return n;
  },
  /**
  * Remove all children.
  */
  empty: function(element){
  element.innerHTML = '';
  /*
  if (!element) return;
  _.each(element.childNodes, function (e) {
  Flotr.DOM.empty(e);
  element.removeChild(e);
  });
  */
  },
  hide: function(element){
  Flotr.DOM.setStyles(element, {display:'none'});
  },
  /**
  * Insert a child.
  * @param {Element} element
  * @param {Element|String} Element or string to be appended.
  */
  insert: function(element, child){
  if(_.isString(child))
  element.innerHTML += child;
  else if (_.isElement(child))
  element.appendChild(child);
  },
  // @TODO find xbrowser implementation
  opacity: function(element, opacity) {
  element.style.opacity = opacity;
  },
  position: function(element, p){
  if (!element.offsetParent)
  return {left: (element.offsetLeft || 0), top: (element.offsetTop || 0)};
 
  p = this.position(element.offsetParent);
  p.left += element.offsetLeft;
  p.top += element.offsetTop;
  return p;
  },
  removeClass: function(element, name) {
  var classList = (element.className ? element.className : '');
  element.className = _.filter(classList.split(/\s+/g), function (c) {
  if (c != name) return true; }
  ).join(' ');
  },
  setStyles: function(element, o) {
  _.each(o, function (value, key) {
  element.style[key] = value;
  });
  },
  show: function(element){
  Flotr.DOM.setStyles(element, {display:''});
  },
  /**
  * Return element size.
  */
  size: function(element){
  return {
  height : element.offsetHeight,
  width : element.offsetWidth };
  }
  };
 
  })();
 
  /**
  * Flotr Event Adapter
  */
  (function () {
  var
  F = Flotr,
  bean = F.bean;
  F.EventAdapter = {
  observe: function(object, name, callback) {
  bean.add(object, name, callback);
  return this;
  },
  fire: function(object, name, args) {
  bean.fire(object, name, args);
  if (typeof(Prototype) != 'undefined')
  Event.fire(object, name, args);
  // @TODO Someone who uses mootools, add mootools adapter for existing applciations.
  return this;
  },
  stopObserving: function(object, name, callback) {
  bean.remove(object, name, callback);
  return this;
  },
  eventPointer: function(e) {
  if (!F._.isUndefined(e.touches) && e.touches.length > 0) {
  return {
  x : e.touches[0].pageX,
  y : e.touches[0].pageY
  };
  } else if (!F._.isUndefined(e.changedTouches) && e.changedTouches.length > 0) {
  return {
  x : e.changedTouches[0].pageX,
  y : e.changedTouches[0].pageY
  };
  } else if (e.pageX || e.pageY) {
  return {
  x : e.pageX,
  y : e.pageY
  };
  } else if (e.clientX || e.clientY) {
  var
  d = document,
  b = d.body,
  de = d.documentElement;
  return {
  x: e.clientX + b.scrollLeft + de.scrollLeft,
  y: e.clientY + b.scrollTop + de.scrollTop
  };
  }
  }
  };
  })();
 
  /**
  * Text Utilities
  */
  (function () {
 
  var
  F = Flotr,
  D = F.DOM,
  _ = F._,
 
  Text = function (o) {
  this.o = o;
  };
 
  Text.prototype = {
 
  dimensions : function (text, canvasStyle, htmlStyle, className) {
 
  if (!text) return { width : 0, height : 0 };
 
  return (this.o.html) ?
  this.html(text, this.o.element, htmlStyle, className) :
  this.canvas(text, canvasStyle);
  },
 
  canvas : function (text, style) {
 
  if (!this.o.textEnabled) return;
  style = style || {};
 
  var
  metrics = this.measureText(text, style),
  width = metrics.width,
  height = style.size || F.defaultOptions.fontSize,
  angle = style.angle || 0,
  cosAngle = Math.cos(angle),
  sinAngle = Math.sin(angle),
  widthPadding = 2,
  heightPadding = 6,
  bounds;
 
  bounds = {
  width: Math.abs(cosAngle * width) + Math.abs(sinAngle * height) + widthPadding,
  height: Math.abs(sinAngle * width) + Math.abs(cosAngle * height) + heightPadding
  };
 
  return bounds;
  },
 
  html : function (text, element, style, className) {
 
  var div = D.create('div');
 
  D.setStyles(div, { 'position' : 'absolute', 'top' : '-10000px' });
  D.insert(div, '<div style="'+style+'" class="'+className+' flotr-dummy-div">' + text + '</div>');
  D.insert(this.o.element, div);
 
  return D.size(div);
  },
 
  measureText : function (text, style) {
 
  var
  context = this.o.ctx,
  metrics;
 
  if (!context.fillText || (F.isIphone && context.measure)) {
  return { width : context.measure(text, style)};
  }
 
  style = _.extend({
  size: F.defaultOptions.fontSize,
  weight: 1,
  angle: 0
  }, style);
 
  context.save();
  context.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  metrics = context.measureText(text);
  context.restore();
 
  return metrics;
  }
  };
 
  Flotr.Text = Text;
 
  })();
 
  /**
  * Flotr Graph class that plots a graph on creation.
  */
  (function () {
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._,
  flotr = Flotr;
  /**
  * Flotr Graph constructor.
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  */
  Graph = function(el, data, options){
  // Let's see if we can get away with out this [JS]
  // try {
  this._setEl(el);
  this._initMembers();
  this._initPlugins();
 
  E.fire(this.el, 'flotr:beforeinit', [this]);
 
  this.data = data;
  this.series = flotr.Series.getSeries(data);
  this._initOptions(options);
  this._initGraphTypes();
  this._initCanvas();
  this._text = new flotr.Text({
  element : this.el,
  ctx : this.ctx,
  html : this.options.HtmlText,
  textEnabled : this.textEnabled
  });
  E.fire(this.el, 'flotr:afterconstruct', [this]);
  this._initEvents();
 
  this.findDataRanges();
  this.calculateSpacing();
 
  this.draw(_.bind(function() {
  E.fire(this.el, 'flotr:afterinit', [this]);
  }, this));
  /*
  try {
  } catch (e) {
  try {
  console.error(e);
  } catch (e2) {}
  }*/
  };
 
  function observe (object, name, callback) {
  E.observe.apply(this, arguments);
  this._handles.push(arguments);
  return this;
  }
 
  Graph.prototype = {
 
  destroy: function () {
  E.fire(this.el, 'flotr:destroy');
  _.each(this._handles, function (handle) {
  E.stopObserving.apply(this, handle);
  });
  this._handles = [];
  this.el.graph = null;
  },
 
  observe : observe,
 
  /**
  * @deprecated
  */
  _observe : observe,
 
  processColor: function(color, options){
  var o = { x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx };
  _.extend(o, options);
  return flotr.Color.processColor(color, o);
  },
  /**
  * Function determines the min and max values for the xaxis and yaxis.
  *
  * TODO logarithmic range validation (consideration of 0)
  */
  findDataRanges: function(){
  var a = this.axes,
  xaxis, yaxis, range;
 
  _.each(this.series, function (series) {
  range = series.getRange();
  if (range) {
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
  xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
  yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
  yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
  xaxis.used = (xaxis.used || range.xused);
  yaxis.used = (yaxis.used || range.yused);
  }
  }, this);
 
  // Check for empty data, no data case (none used)
  if (!a.x.used && !a.x2.used) a.x.used = true;
  if (!a.y.used && !a.y2.used) a.y.used = true;
 
  _.each(a, function (axis) {
  axis.calculateRange();
  });
 
  var
  types = _.keys(flotr.graphTypes),
  drawn = false;
 
  _.each(this.series, function (series) {
  if (series.hide) return;
  _.each(types, function (type) {
  if (series[type] && series[type].show) {
  this.extendRange(type, series);
  drawn = true;
  }
  }, this);
  if (!drawn) {
  this.extendRange(this.options.defaultType, series);
  }
  }, this);
  },
 
  extendRange : function (type, series) {
  if (this[type].extendRange) this[type].extendRange(series, series.data, series[type], this[type]);
  if (this[type].extendYRange) this[type].extendYRange(series.yaxis, series.data, series[type], this[type]);
  if (this[type].extendXRange) this[type].extendXRange(series.xaxis, series.data, series[type], this[type]);
  },
 
  /**
  * Calculates axis label sizes.
  */
  calculateSpacing: function(){
 
  var a = this.axes,
  options = this.options,
  series = this.series,
  margin = options.grid.labelMargin,
  T = this._text,
  x = a.x,
  x2 = a.x2,
  y = a.y,
  y2 = a.y2,
  maxOutset = options.grid.outlineWidth,
  i, j, l, dim;
 
  // TODO post refactor, fix this
  _.each(a, function (axis) {
  axis.calculateTicks();
  axis.calculateTextDimensions(T, options);
  });
 
  // Title height
  dim = T.dimensions(
  options.title,
  {size: options.fontSize*1.5},
  'font-size:1em;font-weight:bold;',
  'flotr-title'
  );
  this.titleHeight = dim.height;
 
  // Subtitle height
  dim = T.dimensions(
  options.subtitle,
  {size: options.fontSize},
  'font-size:smaller;',
  'flotr-subtitle'
  );
  this.subtitleHeight = dim.height;
 
  for(j = 0; j < options.length; ++j){
  if (series[j].points.show){
  maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
  }
  }
 
  var p = this.plotOffset;
  if (x.options.margin === false) {
  p.bottom = 0;
  p.top = 0;
  } else {
  p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ? (x.maxLabel.height + margin) : 0)) +
  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;
 
  p.top += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
  }
  if (y.options.margin === false) {
  p.left = 0;
  p.right = 0;
  } else {
  p.left += (options.grid.circular ? 0 : (y.used && y.options.showLabels ? (y.maxLabel.width + margin) : 0)) +
  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;
 
  p.right += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
  }
 
  p.top = Math.floor(p.top); // In order the outline not to be blured
 
  this.plotWidth = this.canvasWidth - p.left - p.right;
  this.plotHeight = this.canvasHeight - p.bottom - p.top;
 
  // TODO post refactor, fix this
  x.length = x2.length = this.plotWidth;
  y.length = y2.length = this.plotHeight;
  y.offset = y2.offset = this.plotHeight;
  x.setScale();
  x2.setScale();
  y.setScale();
  y2.setScale();
  },
  /**
  * Draws grid, labels, series and outline.
  */
  draw: function(after) {
 
  var
  context = this.ctx,
  i;
 
  E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
 
  if (this.series.length) {
 
  context.save();
  context.translate(this.plotOffset.left, this.plotOffset.top);
 
  for (i = 0; i < this.series.length; i++) {
  if (!this.series[i].hide) this.drawSeries(this.series[i]);
  }
 
  context.restore();
  this.clip();
  }
 
  E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
  if (after) after();
  },
  /**
  * Actually draws the graph.
  * @param {Object} series - series to draw
  */
  drawSeries: function(series){
 
  function drawChart (series, typeKey) {
  var options = this.getOptions(series, typeKey);
  this[typeKey].draw(options);
  }
 
  var drawn = false;
  series = series || this.series;
 
  _.each(flotr.graphTypes, function (type, typeKey) {
  if (series[typeKey] && series[typeKey].show && this[typeKey]) {
  drawn = true;
  drawChart.call(this, series, typeKey);
  }
  }, this);
 
  if (!drawn) drawChart.call(this, series, this.options.defaultType);
  },
 
  getOptions : function (series, typeKey) {
  var
  type = series[typeKey],
  graphType = this[typeKey],
  xaxis = series.xaxis,
  yaxis = series.yaxis,
  options = {
  context : this.ctx,
  width : this.plotWidth,
  height : this.plotHeight,
  fontSize : this.options.fontSize,
  fontColor : this.options.fontColor,
  textEnabled : this.textEnabled,
  htmlText : this.options.HtmlText,
  text : this._text, // TODO Is this necessary?
  element : this.el,
  data : series.data,
  color : series.color,
  shadowSize : series.shadowSize,
  xScale : xaxis.d2p,
  yScale : yaxis.d2p,
  xInverse : xaxis.p2d,
  yInverse : yaxis.p2d
  };
 
  options = flotr.merge(type, options);
 
  // Fill
  options.fillStyle = this.processColor(
  type.fillColor || series.color,
  {opacity: type.fillOpacity}
  );
 
  return options;
  },
  /**
  * Calculates the coordinates from a mouse event object.
  * @param {Event} event - Mouse Event object.
  * @return {Object} Object with coordinates of the mouse.
  */
  getEventPosition: function (e){
 
  var
  d = document,
  b = d.body,
  de = d.documentElement,
  axes = this.axes,
  plotOffset = this.plotOffset,
  lastMousePos = this.lastMousePos,
  pointer = E.eventPointer(e),
  dx = pointer.x - lastMousePos.pageX,
  dy = pointer.y - lastMousePos.pageY,
  r, rx, ry;
 
  if ('ontouchstart' in this.el) {
  r = D.position(this.overlay);
  rx = pointer.x - r.left - plotOffset.left;
  ry = pointer.y - r.top - plotOffset.top;
  } else {
  r = this.overlay.getBoundingClientRect();
  rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
  ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
  }
 
  return {
  x: axes.x.p2d(rx),
  x2: axes.x2.p2d(rx),
  y: axes.y.p2d(ry),
  y2: axes.y2.p2d(ry),
  relX: rx,
  relY: ry,
  dX: dx,
  dY: dy,
  absX: pointer.x,
  absY: pointer.y,
  pageX: pointer.x,
  pageY: pointer.y
  };
  },
  /**
  * Observes the 'click' event and fires the 'flotr:click' event.
  * @param {Event} event - 'click' Event object.
  */
  clickHandler: function(event){
  if(this.ignoreClick){
  this.ignoreClick = false;
  return this.ignoreClick;
  }
  E.fire(this.el, 'flotr:click', [this.getEventPosition(event), this]);
  },
  /**
  * Observes mouse movement over the graph area. Fires the 'flotr:mousemove' event.
  * @param {Event} event - 'mousemove' Event object.
  */
  mouseMoveHandler: function(event){
  if (this.mouseDownMoveHandler) return;
  var pos = this.getEventPosition(event);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  },
  /**
  * Observes the 'mousedown' event.
  * @param {Event} event - 'mousedown' Event object.
  */
  mouseDownHandler: function (event){
 
  /*
  // @TODO Context menu?
  if(event.isRightClick()) {
  event.stop();
 
  var overlay = this.overlay;
  overlay.hide();
 
  function cancelContextMenu () {
  overlay.show();
  E.stopObserving(document, 'mousemove', cancelContextMenu);
  }
  E.observe(document, 'mousemove', cancelContextMenu);
  return;
  }
  */
 
  if (this.mouseUpHandler) return;
  this.mouseUpHandler = _.bind(function (e) {
  E.stopObserving(document, 'mouseup', this.mouseUpHandler);
  E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
  this.mouseDownMoveHandler = null;
  this.mouseUpHandler = null;
  // @TODO why?
  //e.stop();
  E.fire(this.el, 'flotr:mouseup', [e, this]);
  }, this);
  this.mouseDownMoveHandler = _.bind(function (e) {
  var pos = this.getEventPosition(e);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  }, this);
  E.observe(document, 'mouseup', this.mouseUpHandler);
  E.observe(document, 'mousemove', this.mouseDownMoveHandler);
  E.fire(this.el, 'flotr:mousedown', [event, this]);
  this.ignoreClick = false;
  },
  drawTooltip: function(content, x, y, options) {
  var mt = this.getMouseTrack(),
  style = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;',
  p = options.position,
  m = options.margin,
  plotOffset = this.plotOffset;
 
  if(x !== null && y !== null){
  if (!options.relative) { // absolute to the canvas
  if(p.charAt(0) == 'n') style += 'top:' + (m + plotOffset.top) + 'px;bottom:auto;';
  else if(p.charAt(0) == 's') style += 'bottom:' + (m + plotOffset.bottom) + 'px;top:auto;';
  if(p.charAt(1) == 'e') style += 'right:' + (m + plotOffset.right) + 'px;left:auto;';
  else if(p.charAt(1) == 'w') style += 'left:' + (m + plotOffset.left) + 'px;right:auto;';
  }
  else { // relative to the mouse
  if(p.charAt(0) == 'n') style += 'bottom:' + (m - plotOffset.top - y + this.canvasHeight) + 'px;top:auto;';
  else if(p.charAt(0) == 's') style += 'top:' + (m + plotOffset.top + y) + 'px;bottom:auto;';
  if(p.charAt(1) == 'e') style += 'left:' + (m + plotOffset.left + x) + 'px;right:auto;';
  else if(p.charAt(1) == 'w') style += 'right:' + (m - plotOffset.left - x + this.canvasWidth) + 'px;left:auto;';
  }
 
  mt.style.cssText = style;
  D.empty(mt);
  D.insert(mt, content);
  D.show(mt);
  }
  else {
  D.hide(mt);
  }
  },
 
  clip: function (ctx) {
 
  var
  o = this.plotOffset,
  w = this.canvasWidth,
  h = this.canvasHeight;
 
  ctx = ctx || this.ctx;
 
  if (flotr.isIE && flotr.isIE < 9) {
  // Clipping for excanvas :-(
  ctx.save();
  ctx.fillStyle = this.processColor(this.options.ieBackgroundColor);
  ctx.fillRect(0, 0, w, o.top);
  ctx.fillRect(0, 0, o.left, h);
  ctx.fillRect(0, h - o.bottom, w, o.bottom);
  ctx.fillRect(w - o.right, 0, o.right,h);
  ctx.restore();
  } else {
  ctx.clearRect(0, 0, w, o.top);
  ctx.clearRect(0, 0, o.left, h);
  ctx.clearRect(0, h - o.bottom, w, o.bottom);
  ctx.clearRect(w - o.right, 0, o.right,h);
  }
  },
 
  _initMembers: function() {
  this._handles = [];
  this.lastMousePos = {pageX: null, pageY: null };
  this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
  this.ignoreClick = true;
  this.prevHit = null;
  },
 
  _initGraphTypes: function() {
  _.each(flotr.graphTypes, function(handler, graphType){
  this[graphType] = flotr.clone(handler);
  }, this);
  },
 
  _initEvents: function () {
 
  var
  el = this.el,
  touchendHandler, movement, touchend;
 
  if ('ontouchstart' in el) {
 
  touchendHandler = _.bind(function (e) {
  touchend = true;
  E.stopObserving(document, 'touchend', touchendHandler);
  E.fire(el, 'flotr:mouseup', [event, this]);
  this.multitouches = null;
 
  if (!movement) {
  this.clickHandler(e);
  }
  }, this);
 
  this.observe(this.overlay, 'touchstart', _.bind(function (e) {
  movement = false;
  touchend = false;
  this.ignoreClick = false;
 
  if (e.touches && e.touches.length > 1) {
  this.multitouches = e.touches;
  }
 
  E.fire(el, 'flotr:mousedown', [event, this]);
  this.observe(document, 'touchend', touchendHandler);
  }, this));
 
  this.observe(this.overlay, 'touchmove', _.bind(function (e) {
 
  var pos = this.getEventPosition(e);
 
  if (this.options.preventDefault) {
  e.preventDefault();
  }
 
  movement = true;
 
  if (this.multitouches || (e.touches && e.touches.length > 1)) {
  this.multitouches = e.touches;
  } else {
  if (!touchend) {
  E.fire(el, 'flotr:mousemove', [event, pos, this]);
  }
  }
  this.lastMousePos = pos;
  }, this));
 
  } else {
  this.
  observe(this.overlay, 'mousedown', _.bind(this.mouseDownHandler, this)).
  observe(el, 'mousemove', _.bind(this.mouseMoveHandler, this)).
  observe(this.overlay, 'click', _.bind(this.clickHandler, this)).
  observe(el, 'mouseout', function () {
  E.fire(el, 'flotr:mouseout');
  });
  }
  },
 
  /**
  * Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
  * of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
  * are created, the elements are inserted into the container element.
  */
  _initCanvas: function(){
  var el = this.el,
  o = this.options,
  children = el.children,
  removedChildren = [],
  child, i,
  size, style;
 
  // Empty the el
  for (i = children.length; i--;) {
  child = children[i];
  if (!this.canvas && child.className === 'flotr-canvas') {
  this.canvas = child;
  } else if (!this.overlay && child.className === 'flotr-overlay') {
  this.overlay = child;
  } else {
  removedChildren.push(child);
  }
  }
  for (i = removedChildren.length; i--;) {
  el.removeChild(removedChildren[i]);
  }
 
  D.setStyles(el, {position: 'relative'}); // For positioning labels and overlay.
  size = {};
  size.width = el.clientWidth;
  size.height = el.clientHeight;
 
  if(size.width <= 0 || size.height <= 0 || o.resolution <= 0){
  throw 'Invalid dimensions for plot, width = ' + size.width + ', height = ' + size.height + ', resolution = ' + o.resolution;
  }
 
  // Main canvas for drawing graph types
  this.canvas = getCanvas(this.canvas, 'canvas');
  // Overlay canvas for interactive features
  this.overlay = getCanvas(this.overlay, 'overlay');
  this.ctx = getContext(this.canvas);
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this.octx = getContext(this.overlay);
  this.octx.clearRect(0, 0, this.overlay.width, this.overlay.height);
  this.canvasHeight = size.height;
  this.canvasWidth = size.width;
  this.textEnabled = !!this.ctx.drawText || !!this.ctx.fillText; // Enable text functions
 
  function getCanvas(canvas, name){
  if(!canvas){
  canvas = D.create('canvas');
  if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
  FlashCanvas.initElement(canvas);
  }
  canvas.className = 'flotr-'+name;
  canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
  D.insert(el, canvas);
  }
  _.each(size, function(size, attribute){
  D.show(canvas);
  if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
  return;
  }
  canvas.setAttribute(attribute, size * o.resolution);
  canvas.style[attribute] = size + 'px';
  });
  canvas.context_ = null; // Reset the ExCanvas context
  return canvas;
  }
 
  function getContext(canvas){
  if(window.G_vmlCanvasManager) window.G_vmlCanvasManager.initElement(canvas); // For ExCanvas
  var context = canvas.getContext('2d');
  if(!window.G_vmlCanvasManager) context.scale(o.resolution, o.resolution);
  return context;
  }
  },
 
  _initPlugins: function(){
  // TODO Should be moved to flotr and mixed in.
  _.each(flotr.plugins, function(plugin, name){
  _.each(plugin.callbacks, function(fn, c){
  this.observe(this.el, c, _.bind(fn, this));
  }, this);
  this[name] = flotr.clone(plugin);
  _.each(this[name], function(fn, p){
  if (_.isFunction(fn))
  this[name][p] = _.bind(fn, this);
  }, this);
  }, this);
  },
 
  /**
  * Sets options and initializes some variables and color specific values, used by the constructor.
  * @param {Object} opts - options object
  */
  _initOptions: function(opts){
  var options = flotr.clone(flotr.defaultOptions);
  options.x2axis = _.extend(_.clone(options.xaxis), options.x2axis);
  options.y2axis = _.extend(_.clone(options.yaxis), options.y2axis);
  this.options = flotr.merge(opts || {}, options);
 
  if (this.options.grid.minorVerticalLines === null &&
  this.options.xaxis.scaling === 'logarithmic') {
  this.options.grid.minorVerticalLines = true;
  }
  if (this.options.grid.minorHorizontalLines === null &&
  this.options.yaxis.scaling === 'logarithmic') {
  this.options.grid.minorHorizontalLines = true;
  }
 
  E.fire(this.el, 'flotr:afterinitoptions', [this]);
 
  this.axes = flotr.Axis.getAxes(this.options);
 
  // Initialize some variables used throughout this function.
  var assignedColors = [],
  colors = [],
  ln = this.series.length,
  neededColors = this.series.length,
  oc = this.options.colors,
  usedColors = [],
  variation = 0,
  c, i, j, s;
 
  // Collect user-defined colors from series.
  for(i = neededColors - 1; i > -1; --i){
  c = this.series[i].color;
  if(c){
  --neededColors;
  if(_.isNumber(c)) assignedColors.push(c);
  else usedColors.push(flotr.Color.parse(c));
  }
  }
 
  // Calculate the number of colors that need to be generated.
  for(i = assignedColors.length - 1; i > -1; --i)
  neededColors = Math.max(neededColors, assignedColors[i] + 1);
 
  // Generate needed number of colors.
  for(i = 0; colors.length < neededColors;){
  c = (oc.length == i) ? new flotr.Color(100, 100, 100) : flotr.Color.parse(oc[i]);
 
  // Make sure each serie gets a different color.
  var sign = variation % 2 == 1 ? -1 : 1,
  factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
  c.scale(factor, factor, factor);
 
  /**
  * @todo if we're getting too close to something else, we should probably skip this one
  */
  colors.push(c);
 
  if(++i >= oc.length){
  i = 0;
  ++variation;
  }
  }
 
  // Fill the options with the generated colors.
  for(i = 0, j = 0; i < ln; ++i){
  s = this.series[i];
 
  // Assign the color.
  if (!s.color){
  s.color = colors[j++].toString();
  }else if(_.isNumber(s.color)){
  s.color = colors[s.color].toString();
  }
 
  // Every series needs an axis
  if (!s.xaxis) s.xaxis = this.axes.x;
  if (s.xaxis == 1) s.xaxis = this.axes.x;
  else if (s.xaxis == 2) s.xaxis = this.axes.x2;
 
  if (!s.yaxis) s.yaxis = this.axes.y;
  if (s.yaxis == 1) s.yaxis = this.axes.y;
  else if (s.yaxis == 2) s.yaxis = this.axes.y2;
 
  // Apply missing options to the series.
  for (var t in flotr.graphTypes){
  s[t] = _.extend(_.clone(this.options[t]), s[t]);
  }
  s.mouse = _.extend(_.clone(this.options.mouse), s.mouse);
 
  if (_.isUndefined(s.shadowSize)) s.shadowSize = this.options.shadowSize;
  }
  },
 
  _setEl: function(el) {
  if (!el) throw 'The target container doesn\'t exist';
  else if (el.graph instanceof Graph) el.graph.destroy();
  else if (!el.clientWidth) throw 'The target container must be visible';
 
  el.graph = this;
  this.el = el;
  }
  };
 
  Flotr.Graph = Graph;
 
  })();
 
  /**
  * Flotr Axis Library
  */
 
  (function () {
 
  var
  _ = Flotr._,
  LOGARITHMIC = 'logarithmic';
 
  function Axis (o) {
 
  this.orientation = 1;
  this.offset = 0;
  this.datamin = Number.MAX_VALUE;
  this.datamax = -Number.MAX_VALUE;
 
  _.extend(this, o);
  }
 
 
  // Prototype
  Axis.prototype = {
 
  setScale : function () {
  var
  length = this.length,
  max = this.max,
  min = this.min,
  offset = this.offset,
  orientation = this.orientation,
  options = this.options,
  logarithmic = options.scaling === LOGARITHMIC,
  scale;
 
  if (logarithmic) {
  scale = length / (log(max, options.base) - log(min, options.base));
  } else {
  scale = length / (max - min);
  }
  this.scale = scale;
 
  // Logarithmic?
  if (logarithmic) {
  this.d2p = function (dataValue) {
  return offset + orientation * (log(dataValue, options.base) - log(min, options.base)) * scale;
  }
  this.p2d = function (pointValue) {
  return exp((offset + orientation * pointValue) / scale + log(min, options.base), options.base);
  }
  } else {
  this.d2p = function (dataValue) {
  return offset + orientation * (dataValue - min) * scale;
  }
  this.p2d = function (pointValue) {
  return (offset + orientation * pointValue) / scale + min;
  }
  }
  },
 
  calculateTicks : function () {
  var options = this.options;
 
  this.ticks = [];
  this.minorTicks = [];
 
  // User Ticks
  if(options.ticks){
  this._cleanUserTicks(options.ticks, this.ticks);
  this._cleanUserTicks(options.minorTicks || [], this.minorTicks);
  }
  else {
  if (options.mode == 'time') {
  this._calculateTimeTicks();
  } else if (options.scaling === 'logarithmic') {
  this._calculateLogTicks();
  } else {
  this._calculateTicks();
  }
  }
 
  // Ticks to strings
  _.each(this.ticks, function (tick) { tick.label += ''; });
  _.each(this.minorTicks, function (tick) { tick.label += ''; });
  },
 
  /**
  * Calculates the range of an axis to apply autoscaling.
  */
  calculateRange: function () {
 
  if (!this.used) return;
 
  var axis = this,
  o = axis.options,
  min = o.min !== null ? o.min : axis.datamin,
  max = o.max !== null ? o.max : axis.datamax,
  margin = o.autoscaleMargin;
 
  if (o.scaling == 'logarithmic') {
  if (min <= 0) min = axis.datamin;
 
  // Let it widen later on
  if (max <= 0) max = min;
  }
 
  if (max == min) {
  var widen = max ? 0.01 : 1.00;
  if (o.min === null) min -= widen;
  if (o.max === null) max += widen;
  }
 
  if (o.scaling === 'logarithmic') {
  if (min < 0) min = max / o.base; // Could be the result of widening
 
  var maxexp = Math.log(max);
  if (o.base != Math.E) maxexp /= Math.log(o.base);
  maxexp = Math.ceil(maxexp);
 
  var minexp = Math.log(min);
  if (o.base != Math.E) minexp /= Math.log(o.base);
  minexp = Math.ceil(minexp);
 
  axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
 
  // Try to determine a suitable amount of miniticks based on the length of a decade
  if (o.minorTickFreq === null) {
  if (maxexp - minexp > 10)
  o.minorTickFreq = 0;
  else if (maxexp - minexp > 5)
  o.minorTickFreq = 2;
  else
  o.minorTickFreq = 5;
  }
  } else {
  axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
  }
 
  axis.min = min;
  axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
 
  // Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
  if(o.min === null && o.autoscale){
  axis.min -= axis.tickSize * margin;
  // Make sure we don't go below zero if all values are positive.
  if(axis.min < 0 && axis.datamin >= 0) axis.min = 0;
  axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
  }
 
  if(o.max === null && o.autoscale){
  axis.max += axis.tickSize * margin;
  if(axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
  axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
  }
 
  if (axis.min == axis.max) axis.max = axis.min + 1;
  },
 
  calculateTextDimensions : function (T, options) {
 
  var maxLabel = '',
  length,
  i;
 
  if (this.options.showLabels) {
  for (i = 0; i < this.ticks.length; ++i) {
  length = this.ticks[i].label.length;
  if (length > maxLabel.length){
  maxLabel = this.ticks[i].label;
  }
  }
  }
 
  this.maxLabel = T.dimensions(
  maxLabel,
  {size:options.fontSize, angle: Flotr.toRad(this.options.labelsAngle)},
  'font-size:smaller;',
  'flotr-grid-label'
  );
 
  this.titleSize = T.dimensions(
  this.options.title,
  {size:options.fontSize*1.2, angle: Flotr.toRad(this.options.titleAngle)},
  'font-weight:bold;',
  'flotr-axis-title'
  );
  },
 
  _cleanUserTicks : function (ticks, axisTicks) {
 
  var axis = this, options = this.options,
  v, i, label, tick;
 
  if(_.isFunction(ticks)) ticks = ticks({min : axis.min, max : axis.max});
 
  for(i = 0; i < ticks.length; ++i){
  tick = ticks[i];
  if(typeof(tick) === 'object'){
  v = tick[0];
  label = (tick.length > 1) ? tick[1] : options.tickFormatter(v, {min : axis.min, max : axis.max});
  } else {
  v = tick;
  label = options.tickFormatter(v, {min : this.min, max : this.max});
  }
  axisTicks[i] = { v: v, label: label };
  }
  },
 
  _calculateTimeTicks : function () {
  this.ticks = Flotr.Date.generator(this);
  },
 
  _calculateLogTicks : function () {
 
  var axis = this,
  o = axis.options,
  v,
  decadeStart;
 
  var max = Math.log(axis.max);
  if (o.base != Math.E) max /= Math.log(o.base);
  max = Math.ceil(max);
 
  var min = Math.log(axis.min);
  if (o.base != Math.E) min /= Math.log(o.base);
  min = Math.ceil(min);
 
  for (i = min; i < max; i += axis.tickSize) {
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  // Next decade begins here:
  var decadeEnd = decadeStart * ((o.base == Math.E) ? Math.exp(axis.tickSize) : Math.pow(o.base, axis.tickSize));
  var stepSize = (decadeEnd - decadeStart) / o.minorTickFreq;
 
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  for (v = decadeStart + stepSize; v < decadeEnd; v += stepSize)
  axis.minorTicks.push({v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max})});
  }
 
  // Always show the value at the would-be start of next decade (end of this decade)
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  },
 
  _calculateTicks : function () {
 
  var axis = this,
  o = axis.options,
  tickSize = axis.tickSize,
  min = axis.min,
  max = axis.max,
  start = tickSize * Math.ceil(min / tickSize), // Round to nearest multiple of tick size.
  decimals,
  minorTickSize,
  v, v2,
  i, j;
 
  if (o.minorTickFreq)
  minorTickSize = tickSize / o.minorTickFreq;
 
  // Then store all possible ticks.
  for (i = 0; (v = v2 = start + i * tickSize) <= max; ++i){
 
  // Round (this is always needed to fix numerical instability).
  decimals = o.tickDecimals;
  if (decimals === null) decimals = 1 - Math.floor(Math.log(tickSize) / Math.LN10);
  if (decimals < 0) decimals = 0;
 
  v = v.toFixed(decimals);
  axis.ticks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
 
  if (o.minorTickFreq) {
  for (j = 0; j < o.minorTickFreq && (i * tickSize + j * minorTickSize) < max; ++j) {
  v = v2 + j * minorTickSize;
  axis.minorTicks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
  }
  }
  }
 
  }
  };
 
 
  // Static Methods
  _.extend(Axis, {
  getAxes : function (options) {
  return {
  x: new Axis({options: options.xaxis, n: 1, length: this.plotWidth}),
  x2: new Axis({options: options.x2axis, n: 2, length: this.plotWidth}),
  y: new Axis({options: options.yaxis, n: 1, length: this.plotHeight, offset: this.plotHeight, orientation: -1}),
  y2: new Axis({options: options.y2axis, n: 2, length: this.plotHeight, offset: this.plotHeight, orientation: -1})
  };
  }
  });
 
 
  // Helper Methods
 
 
  function log (value, base) {
  value = Math.log(Math.max(value, Number.MIN_VALUE));
  if (base !== Math.E)
  value /= Math.log(base);
  return value;
  }
 
  function exp (value, base) {
  return (base === Math.E) ? Math.exp(value) : Math.pow(base, value);
  }
 
  Flotr.Axis = Axis;
 
  })();
 
  /**
  * Flotr Series Library
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  function Series (o) {
  _.extend(this, o);
  }
 
  Series.prototype = {
 
  getRange: function () {
 
  var
  data = this.data,
  length = data.length,
  xmin = Number.MAX_VALUE,
  ymin = Number.MAX_VALUE,
  xmax = -Number.MAX_VALUE,
  ymax = -Number.MAX_VALUE,
  xused = false,
  yused = false,
  x, y, i;
 
  if (length < 0 || this.hide) return false;
 
  for (i = 0; i < length; i++) {
  x = data[i][0];
  y = data[i][1];
  if (x !== null) {
  if (x < xmin) { xmin = x; xused = true; }
  if (x > xmax) { xmax = x; xused = true; }
  }
  if (y !== null) {
  if (y < ymin) { ymin = y; yused = true; }
  if (y > ymax) { ymax = y; yused = true; }
  }
  }
 
  return {
  xmin : xmin,
  xmax : xmax,
  ymin : ymin,
  ymax : ymax,
  xused : xused,
  yused : yused
  };
  }
  };
 
  _.extend(Series, {
  /**
  * Collects dataseries from input and parses the series into the right format. It returns an Array
  * of Objects each having at least the 'data' key set.
  * @param {Array, Object} data - Object or array of dataseries
  * @return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
  */
  getSeries: function(data){
  return _.map(data, function(s){
  var series;
  if (s.data) {
  series = new Series();
  _.extend(series, s);
  } else {
  series = new Series({data:s});
  }
  return series;
  });
  }
  });
 
  Flotr.Series = Series;
 
  })();
 
  /** Lines **/
  Flotr.addType('lines', {
  options: {
  show: false, // => setting to true will show lines, false will hide
  lineWidth: 2, // => line width in pixels
  fill: false, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillBorder: false, // => draw a border around the fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  steps: false, // => draw steps
  stacked: false // => setting to true will show stacked lines, false will show normal lines
  },
 
  stack : {
  values : []
  },
 
  /**
  * Draws lines series in the canvas element.
  * @param {Object} options
  */
  draw : function (options) {
 
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  offset;
 
  context.save();
  context.lineJoin = 'round';
 
  if (shadowSize) {
 
  context.lineWidth = shadowSize / 2;
  offset = lineWidth / 2 + context.lineWidth / 2;
 
  // @TODO do this instead with a linear gradient
  context.strokeStyle = "rgba(0,0,0,0.1)";
  this.plot(options, offset + shadowSize / 2, false);
 
  context.strokeStyle = "rgba(0,0,0,0.2)";
  this.plot(options, offset, false);
  }
 
  context.lineWidth = lineWidth;
  context.strokeStyle = options.color;
 
  this.plot(options, 0, true);
 
  context.restore();
  },
 
  plot : function (options, shadowOffset, incStack) {
 
  var
  context = options.context,
  width = options.width,
  height = options.height,
  xScale = options.xScale,
  yScale = options.yScale,
  data = options.data,
  stack = options.stacked ? this.stack : false,
  length = data.length - 1,
  prevx = null,
  prevy = null,
  zero = yScale(0),
  start = null,
  x1, x2, y1, y2, stack1, stack2, i;
 
  if (length < 1) return;
 
  context.beginPath();
 
  for (i = 0; i < length; ++i) {
 
  // To allow empty values
  if (data[i][1] === null || data[i+1][1] === null) {
  if (options.fill) {
  if (i > 0 && data[i][1]) {
  context.stroke();
  fill();
  start = null;
  context.closePath();
  context.beginPath();
  }
  }
  continue;
  }
 
  // Zero is infinity for log scales
  // TODO handle zero for logarithmic
  // if (xa.options.scaling === 'logarithmic' && (data[i][0] <= 0 || data[i+1][0] <= 0)) continue;
  // if (ya.options.scaling === 'logarithmic' && (data[i][1] <= 0 || data[i+1][1] <= 0)) continue;
 
  x1 = xScale(data[i][0]);
  x2 = xScale(data[i+1][0]);
 
  if (start === null) start = data[i];
 
  if (stack) {
 
  stack1 = stack.values[data[i][0]] || 0;
  stack2 = stack.values[data[i+1][0]] || stack.values[data[i][0]] || 0;
 
  y1 = yScale(data[i][1] + stack1);
  y2 = yScale(data[i+1][1] + stack2);
 
  if(incStack){
  stack.values[data[i][0]] = data[i][1]+stack1;
 
  if(i == length-1)
  stack.values[data[i+1][0]] = data[i+1][1]+stack2;
  }
  }
  else{
  y1 = yScale(data[i][1]);
  y2 = yScale(data[i+1][1]);
  }
 
  if (
  (y1 > height && y2 > height) ||
  (y1 < 0 && y2 < 0) ||
  (x1 < 0 && x2 < 0) ||
  (x1 > width && x2 > width)
  ) continue;
 
  if((prevx != x1) || (prevy != y1 + shadowOffset))
  context.moveTo(x1, y1 + shadowOffset);
 
  prevx = x2;
  prevy = y2 + shadowOffset;
  if (options.steps) {
  context.lineTo(prevx + shadowOffset / 2, y1 + shadowOffset);
  context.lineTo(prevx + shadowOffset / 2, prevy);
  } else {
  context.lineTo(prevx, prevy);
  }
  }
 
  if (!options.fill || options.fill && !options.fillBorder) context.stroke();
 
  fill();
 
  function fill () {
  // TODO stacked lines
  if(!shadowOffset && options.fill && start){
  x1 = xScale(start[0]);
  context.fillStyle = options.fillStyle;
  context.lineTo(x2, zero);
  context.lineTo(x1, zero);
  context.lineTo(x1, yScale(start[1]));
  context.fill();
  if (options.fillBorder) {
  context.stroke();
  }
  }
  }
 
  context.closePath();
  },
 
  // Perform any pre-render precalculations (this should be run on data first)
  // - Pie chart total for calculating measures
  // - Stacks for lines and bars
  // precalculate : function () {
  // }
  //
  //
  // Get any bounds after pre calculation (axis can fetch this if does not have explicit min/max)
  // getBounds : function () {
  // }
  // getMin : function () {
  // }
  // getMax : function () {
  // }
  //
  //
  // Padding around rendered elements
  // getPadding : function () {
  // }
 
  extendYRange : function (axis, data, options, lines) {
 
  var o = axis.options;
 
  // If stacked and auto-min
  if (options.stacked && ((!o.max && o.max !== 0) || (!o.min && o.min !== 0))) {
 
  var
  newmax = axis.max,
  newmin = axis.min,
  positiveSums = lines.positiveSums || {},
  negativeSums = lines.negativeSums || {},
  x, j;
 
  for (j = 0; j < data.length; j++) {
 
  x = data[j][0] + '';
 
  // Positive
  if (data[j][1] > 0) {
  positiveSums[x] = (positiveSums[x] || 0) + data[j][1];
  newmax = Math.max(newmax, positiveSums[x]);
  }
 
  // Negative
  else {
  negativeSums[x] = (negativeSums[x] || 0) + data[j][1];
  newmin = Math.min(newmin, negativeSums[x]);
  }
  }
 
  lines.negativeSums = negativeSums;
  lines.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  if (options.steps) {
 
  this.hit = function (options) {
  var
  data = options.data,
  args = options.args,
  yScale = options.yScale,
  mouse = args[0],
  length = data.length,
  n = args[1],
  x = options.xInverse(mouse.relX),
  relY = mouse.relY,
  i;
 
  for (i = 0; i < length - 1; i++) {
  if (x >= data[i][0] && x <= data[i+1][0]) {
  if (Math.abs(yScale(data[i][1]) - relY) < 8) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  break;
  }
  }
  };
 
  this.drawHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x2, y);
  context.stroke();
  context.closePath();
  context.restore();
  }
  };
 
  this.clearHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  width = options.lineWidth,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.clearRect(x - width, y - width, x2 - x + 2 * width, 2 * width);
  }
  };
  }
  }
 
  });
 
  /** Bars **/
  Flotr.addType('bars', {
 
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  horizontal: false, // => horizontal bars (x and y inverted)
  stacked: false, // => stacked bar charts
  centered: true, // => center the bars to their x axis value
  topPadding: 0.1, // => top padding in percent
  grouped: false // => groups bars together which share x value, hit not supported.
  },
 
  stack : {
  positive : [],
  negative : [],
  _positive : [], // Shadow
  _negative : [] // Shadow
  },
 
  draw : function (options) {
  var
  context = options.context;
 
  this.current += 1;
 
  context.save();
  context.lineJoin = 'miter';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  shadowSize = options.shadowSize,
  i, geometry, left, top, width, height;
 
  if (data.length < 1) return;
 
  this.translate(context, options.horizontal);
 
  for (i = 0; i < data.length; i++) {
 
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (geometry === null) continue;
 
  left = geometry.left;
  top = geometry.top;
  width = geometry.width;
  height = geometry.height;
 
  if (options.fill) context.fillRect(left, top, width, height);
  if (shadowSize) {
  context.save();
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top + shadowSize, width, height);
  context.restore();
  }
  if (options.lineWidth) {
  context.strokeRect(left, top, width, height);
  }
  }
  },
 
  translate : function (context, horizontal) {
  if (horizontal) {
  context.rotate(-Math.PI / 2);
  context.scale(-1, 1);
  }
  },
 
  getBarGeometry : function (x, y, options) {
 
  var
  horizontal = options.horizontal,
  barWidth = options.barWidth,
  centered = options.centered,
  stack = options.stacked ? this.stack : false,
  lineWidth = options.lineWidth,
  bisection = centered ? barWidth / 2 : 0,
  xScale = horizontal ? options.yScale : options.xScale,
  yScale = horizontal ? options.xScale : options.yScale,
  xValue = horizontal ? y : x,
  yValue = horizontal ? x : y,
  stackOffset = 0,
  stackValue, left, right, top, bottom;
 
  if (options.grouped) {
  this.current / this.groups;
  xValue = xValue - bisection;
  barWidth = barWidth / this.groups;
  bisection = barWidth / 2;
  xValue = xValue + barWidth * this.current - bisection;
  }
 
  // Stacked bars
  if (stack) {
  stackValue = yValue > 0 ? stack.positive : stack.negative;
  stackOffset = stackValue[xValue] || stackOffset;
  stackValue[xValue] = stackOffset + yValue;
  }
 
  left = xScale(xValue - bisection);
  right = xScale(xValue + barWidth - bisection);
  top = yScale(yValue + stackOffset);
  bottom = yScale(stackOffset);
 
  // TODO for test passing... probably looks better without this
  if (bottom < 0) bottom = 0;
 
  // TODO Skipping...
  // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;
 
  return (x === null || y === null) ? null : {
  x : xValue,
  y : yValue,
  xScale : xScale,
  yScale : yScale,
  top : top,
  left : Math.min(left, right) - lineWidth / 2,
  width : Math.abs(right - left) - lineWidth,
  height : bottom - top
  };
  },
 
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  x = options.xInverse(mouse.relX),
  y = options.yInverse(mouse.relY),
  hitGeometry = this.getBarGeometry(x, y, options),
  width = hitGeometry.width / 2,
  left = hitGeometry.left,
  height = hitGeometry.y,
  geometry, i;
 
  for (i = data.length; i--;) {
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (
  // Height:
  (
  // Positive Bars:
  (height > 0 && height < geometry.y) ||
  // Negative Bars:
  (height < 0 && height > geometry.y)
  ) &&
  // Width:
  (Math.abs(left - geometry.left) < width)
  ) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  }
  },
 
  drawHit : function (options) {
  // TODO hits for stacked bars; implement using calculateStack option?
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  top = geometry.top,
  width = geometry.width,
  height = geometry.height;
 
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  this.translate(context, options.horizontal);
 
  // Draw highlight
  context.beginPath();
  context.moveTo(left, top + height);
  context.lineTo(left, top);
  context.lineTo(left + width, top);
  context.lineTo(left + width, top + height);
  if (options.fill) {
  context.fillStyle = options.fillStyle;
  context.fill();
  }
  context.stroke();
  context.closePath();
 
  context.restore();
  },
 
  clearHit: function (options) {
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  width = geometry.width,
  top = geometry.top,
  height = geometry.height,
  lineWidth = 2 * options.lineWidth;
 
  context.save();
  this.translate(context, options.horizontal);
  context.clearRect(
  left - lineWidth,
  Math.min(top, top + height) - lineWidth,
  width + 2 * lineWidth,
  Math.abs(height) + 2 * lineWidth
  );
  context.restore();
  },
 
  extendXRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  this.groups = (this.groups + 1) || 1;
  this.current = 0;
  },
 
  extendYRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {
 
  var
  max = axis.options.max;
 
  if (_.isNumber(max) || _.isString(max)) return;
 
  var
  newmin = axis.min,
  newmax = axis.max,
  horizontal = options.horizontal,
  orientation = axis.orientation,
  positiveSums = this.positiveSums || {},
  negativeSums = this.negativeSums || {},
  value, datum, index, j;
 
  // Sides of bars
  if ((orientation == 1 && !horizontal) || (orientation == -1 && horizontal)) {
  if (options.centered) {
  newmax = Math.max(axis.datamax + options.barWidth, newmax);
  newmin = Math.min(axis.datamin - options.barWidth, newmin);
  }
  }
 
  if (options.stacked &&
  ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal))){
 
  for (j = data.length; j--;) {
  value = data[j][(orientation == 1 ? 1 : 0)]+'';
  datum = data[j][(orientation == 1 ? 0 : 1)];
 
  // Positive
  if (datum > 0) {
  positiveSums[value] = (positiveSums[value] || 0) + datum;
  newmax = Math.max(newmax, positiveSums[value]);
  }
 
  // Negative
  else {
  negativeSums[value] = (negativeSums[value] || 0) + datum;
  newmin = Math.min(newmin, negativeSums[value]);
  }
  }
  }
 
  // End of bars
  if ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal)) {
  if (options.topPadding && (axis.max === axis.datamax || (options.stacked && this.stackMax !== newmax))) {
  newmax += options.topPadding * (newmax - newmin);
  }
  }
 
  this.stackMin = newmin;
  this.stackMax = newmax;
  this.negativeSums = negativeSums;
  this.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  });
 
  /** Bubbles **/
  Flotr.addType('bubbles', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  baseRadius: 2 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.lineWidth = options.lineWidth;
 
  // Shadows
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
 
  var
  data = options.data,
  context = options.context,
  geometry,
  i, x, y, z;
 
  offset = offset || 0;
 
  for (i = 0; i < data.length; ++i){
 
  geometry = this.getGeometry(data[i], options);
 
  context.beginPath();
  context.arc(geometry.x + offset, geometry.y + offset, geometry.z, 0, 2 * Math.PI, true);
  context.stroke();
  if (options.fill) context.fill();
  context.closePath();
  }
  },
  getGeometry : function (point, options) {
  return {
  x : options.xScale(point[0]),
  y : options.yScale(point[1]),
  z : point[2] * options.baseRadius
  };
  },
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  relX = mouse.relX,
  relY = mouse.relY,
  distance,
  geometry,
  dx, dy;
 
  n.best = n.best || Number.MAX_VALUE;
 
  for (i = data.length; i--;) {
  geometry = this.getGeometry(data[i], options);
 
  dx = geometry.x - relX;
  dy = geometry.y - relY;
  distance = Math.sqrt(dx * dx + dy * dy);
 
  if (distance < geometry.z && geometry.z < n.best) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  n.best = geometry.z;
  }
  }
  },
  drawHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options);
 
  context.save();
  context.lineWidth = options.lineWidth;
  context.fillStyle = options.fillStyle;
  context.strokeStyle = options.color;
  context.beginPath();
  context.arc(geometry.x, geometry.y, geometry.z, 0, 2 * Math.PI, true);
  context.fill();
  context.stroke();
  context.closePath();
  context.restore();
  },
  clearHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options),
  offset = geometry.z + options.lineWidth;
 
  context.save();
  context.clearRect(
  geometry.x - offset,
  geometry.y - offset,
  2 * offset,
  2 * offset
  );
  context.restore();
  }
  // TODO Add a hit calculation method (like pie)
  });
 
  /** Candles **/
  Flotr.addType('candles', {
  options: {
  show: false, // => setting to true will show candle sticks, false will hide
  lineWidth: 1, // => in pixels
  wickLineWidth: 1, // => in pixels
  candleWidth: 0.6, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  upFillColor: '#00A8F0',// => up sticks fill color
  downFillColor: '#CB4B4B',// => down sticks fill color
  fillOpacity: 0.5, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  // TODO Test this barcharts option.
  barcharts: false // => draw as barcharts (not standard bars but financial barcharts)
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineCap = 'butt';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.wickLineWidth || options.lineWidth;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  width = options.candleWidth / 2,
  shadowSize = options.shadowSize,
  lineWidth = options.lineWidth,
  wickLineWidth = options.wickLineWidth,
  pixelOffset = (wickLineWidth % 2) / 2,
  color,
  datum, x, y,
  open, high, low, close,
  left, right, bottom, top, bottom2, top2,
  i;
 
  if (data.length < 1) return;
 
  for (i = 0; i < data.length; i++) {
  datum = data[i];
  x = datum[0];
  open = datum[1];
  high = datum[2];
  low = datum[3];
  close = datum[4];
  left = xScale(x - width);
  right = xScale(x + width);
  bottom = yScale(low);
  top = yScale(high);
  bottom2 = yScale(Math.min(open, close));
  top2 = yScale(Math.max(open, close));
 
  /*
  // TODO skipping
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
  */
 
  color = options[open > close ? 'downFillColor' : 'upFillColor'];
 
  // Fill the candle.
  // TODO Test the barcharts option
  if (options.fill && !options.barcharts) {
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top2 + shadowSize, right - left, bottom2 - top2);
  context.save();
  context.globalAlpha = options.fillOpacity;
  context.fillStyle = color;
  context.fillRect(left, top2 + lineWidth, right - left, bottom2 - top2);
  context.restore();
  }
 
  // Draw candle outline/border, high, low.
  if (lineWidth || wickLineWidth) {
 
  x = Math.floor((left + right) / 2) + pixelOffset;
 
  context.strokeStyle = color;
  context.beginPath();
 
  // TODO Again with the bartcharts
  if (options.barcharts) {
 
  context.moveTo(x, Math.floor(top + width));
  context.lineTo(x, Math.floor(bottom + width));
 
  y = Math.floor(open + width) + 0.5;
  context.moveTo(Math.floor(left) + pixelOffset, y);
  context.lineTo(x, y);
 
  y = Math.floor(close + width) + 0.5;
  context.moveTo(Math.floor(right) + pixelOffset, y);
  context.lineTo(x, y);
  } else {
  context.strokeRect(left, top2 + lineWidth, right - left, bottom2 - top2);
 
  context.moveTo(x, Math.floor(top2 + lineWidth));
  context.lineTo(x, Math.floor(top + lineWidth));
  context.moveTo(x, Math.floor(bottom2 + lineWidth));
  context.lineTo(x, Math.floor(bottom + lineWidth));
  }
 
  context.closePath();
  context.stroke();
  }
  }
  },
  extendXRange: function (axis, data, options) {
  if (axis.options.max === null) {
  axis.max = Math.max(axis.datamax + 0.5, axis.max);
  axis.min = Math.min(axis.datamin - 0.5, axis.min);
  }
  }
  });
 
  /** Gantt
  * Base on data in form [s,y,d] where:
  * y - executor or simply y value
  * s - task start value
  * d - task duration
  * **/
  Flotr.addType('gantt', {
  options: {
  show: false, // => setting to true will show gantt, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  centered: true // => center the bars to their x axis value
  },
  /**
  * Draws gantt series in the canvas element.
  * @param {Object} series - Series with options.gantt.show = true.
  */
  draw: function(series) {
  var ctx = this.ctx,
  bw = series.gantt.barWidth,
  lw = Math.min(series.gantt.lineWidth, bw);
 
  ctx.save();
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
  ctx.lineJoin = 'miter';
 
  /**
  * @todo linewidth not interpreted the right way.
  */
  ctx.lineWidth = lw;
  ctx.strokeStyle = series.color;
 
  ctx.save();
  this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
  ctx.restore();
 
  if(series.gantt.fill){
  var color = series.gantt.fillColor || series.color;
  ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
  }
 
  this.gantt.plot(series, bw, 0, series.gantt.fill);
  ctx.restore();
  },
  plot: function(series, barWidth, offset, fill){
  var data = series.data;
  if(data.length < 1) return;
 
  var xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx, i;
 
  for(i = 0; i < data.length; i++){
  var y = data[i][0],
  s = data[i][1],
  d = data[i][2],
  drawLeft = true, drawTop = true, drawRight = true;
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min){
  left = xa.min;
  drawLeft = false;
  }
 
  if(right > xa.max){
  right = xa.max;
  if (xa.lastSerie != series)
  drawTop = false;
  }
 
  if(bottom < ya.min)
  bottom = ya.min;
 
  if(top > ya.max){
  top = ya.max;
  if (ya.lastSerie != series)
  drawTop = false;
  }
 
  /**
  * Fill the bar.
  */
  if(fill){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
  ctx.lineTo(xa.d2p(left), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(bottom) + offset);
  ctx.fill();
  ctx.closePath();
  }
 
  /**
  * Draw bar outline/border.
  */
  if(series.gantt.lineWidth && (drawLeft || drawRight || drawTop)){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
 
  ctx[drawLeft ?'lineTo':'moveTo'](xa.d2p(left), ya.d2p(top) + offset);
  ctx[drawTop ?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(top) + offset);
  ctx[drawRight?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(bottom) + offset);
 
  ctx.stroke();
  ctx.closePath();
  }
  }
  },
  plotShadows: function(series, barWidth, offset){
  var data = series.data;
  if(data.length < 1) return;
 
  var i, y, s, d,
  xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx,
  sw = this.options.shadowSize;
 
  for(i = 0; i < data.length; i++){
  y = data[i][0];
  s = data[i][1];
  d = data[i][2];
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min) left = xa.min;
  if(right > xa.max) right = xa.max;
  if(bottom < ya.min) bottom = ya.min;
  if(top > ya.max) top = ya.max;
 
  var width = xa.d2p(right)-xa.d2p(left)-((xa.d2p(right)+sw <= this.plotWidth) ? 0 : sw);
  var height = ya.d2p(bottom)-ya.d2p(top)-((ya.d2p(bottom)+sw <= this.plotHeight) ? 0 : sw );
 
  ctx.fillStyle = 'rgba(0,0,0,0.05)';
  ctx.fillRect(Math.min(xa.d2p(left)+sw, this.plotWidth), Math.min(ya.d2p(top)+sw, this.plotHeight), width, height);
  }
  },
  extendXRange: function(axis) {
  if(axis.options.max === null){
  var newmin = axis.min,
  newmax = axis.max,
  i, j, x, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if(g.show && s.xaxis == axis) {
  for (j = 0; j < s.data.length; j++) {
  if (g.show) {
  y = s.data[j][0]+'';
  stackedSumsPos[y] = Math.max((stackedSumsPos[y] || 0), s.data[j][1]+s.data[j][2]);
  lastSerie = s;
  }
  }
  for (j in stackedSumsPos) {
  newmax = Math.max(stackedSumsPos[j], newmax);
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  }
  },
  extendYRange: function(axis){
  if(axis.options.max === null){
  var newmax = Number.MIN_VALUE,
  newmin = Number.MAX_VALUE,
  i, j, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if (g.show && !s.hide && s.yaxis == axis) {
  var datamax = Number.MIN_VALUE, datamin = Number.MAX_VALUE;
  for(j=0; j < s.data.length; j++){
  datamax = Math.max(datamax,s.data[j][0]);
  datamin = Math.min(datamin,s.data[j][0]);
  }
 
  if (g.centered) {
  newmax = Math.max(datamax + 0.5, newmax);
  newmin = Math.min(datamin - 0.5, newmin);
  }
  else {
  newmax = Math.max(datamax + 1, newmax);
  newmin = Math.min(datamin, newmin);
  }
  // For normal horizontal bars
  if (g.barWidth + datamax > newmax){
  newmax = axis.max + g.barWidth;
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  axis.tickSize = Flotr.getTickSize(axis.options.noTicks, newmin, newmax, axis.options.tickDecimals);
  }
  }
  });
 
  /** Markers **/
  /**
  * Formats the marker labels.
  * @param {Object} obj - Marker value Object {x:..,y:..}
  * @return {String} Formatted marker string
  */
  (function () {
 
  Flotr.defaultMarkerFormatter = function(obj){
  return (Math.round(obj.y*100)/100)+'';
  };
 
  Flotr.addType('markers', {
  options: {
  show: false, // => setting to true will show markers, false will hide
  lineWidth: 1, // => line width of the rectangle around the marker
  color: '#000000', // => text color
  fill: false, // => fill or not the marekers' rectangles
  fillColor: "#FFFFFF", // => fill color
  fillOpacity: 0.4, // => fill opacity
  stroke: false, // => draw the rectangle around the markers
  position: 'ct', // => the markers position (vertical align: b, m, t, horizontal align: l, c, r)
  verticalMargin: 0, // => the margin between the point and the text.
  labelFormatter: Flotr.defaultMarkerFormatter,
  fontSize: Flotr.defaultOptions.fontSize,
  stacked: false, // => true if markers should be stacked
  stackingType: 'b', // => define staching behavior, (b- bars like, a - area like) (see Issue 125 for details)
  horizontal: false // => true if markers should be horizontal (For now only in a case on horizontal stacked bars, stacks should be calculated horizontaly)
  },
 
  // TODO test stacked markers.
  stack : {
  positive : [],
  negative : [],
  values : []
  },
 
  draw : function (options) {
 
  var
  data = options.data,
  context = options.context,
  stack = options.stacked ? options.stack : false,
  stackType = options.stackingType,
  stackOffsetNeg,
  stackOffsetPos,
  stackOffset,
  i, x, y, label;
 
  context.save();
  context.lineJoin = 'round';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = 'rgba(0,0,0,0.5)';
  context.fillStyle = options.fillStyle;
 
  function stackPos (a, b) {
  stackOffsetPos = stack.negative[a] || 0;
  stackOffsetNeg = stack.positive[a] || 0;
  if (b > 0) {
  stack.positive[a] = stackOffsetPos + b;
  return stackOffsetPos + b;
  } else {
  stack.negative[a] = stackOffsetNeg + b;
  return stackOffsetNeg + b;
  }
  }
 
  for (i = 0; i < data.length; ++i) {
 
  x = data[i][0];
  y = data[i][1];
 
  if (stack) {
  if (stackType == 'b') {
  if (options.horizontal) y = stackPos(y, x);
  else x = stackPos(x, y);
  } else if (stackType == 'a') {
  stackOffset = stack.values[x] || 0;
  stack.values[x] = stackOffset + y;
  y = stackOffset + y;
  }
  }
 
  label = options.labelFormatter({x: x, y: y, index: i, data : data});
  this.plot(options.xScale(x), options.yScale(y), label, options);
  }
  context.restore();
  },
  plot: function(x, y, label, options) {
  var context = options.context;
  if (isImage(label) && !label.complete) {
  throw 'Marker image not loaded.';
  } else {
  this._plot(x, y, label, options);
  }
  },
 
  _plot: function(x, y, label, options) {
  var context = options.context,
  margin = 2,
  left = x,
  top = y,
  dim;
 
  if (isImage(label))
  dim = {height : label.height, width: label.width};
  else
  dim = options.text.canvas(label);
 
  dim.width = Math.floor(dim.width+margin*2);
  dim.height = Math.floor(dim.height+margin*2);
 
  if (options.position.indexOf('c') != -1) left -= dim.width/2 + margin;
  else if (options.position.indexOf('l') != -1) left -= dim.width;
 
  if (options.position.indexOf('m') != -1) top -= dim.height/2 + margin;
  else if (options.position.indexOf('t') != -1) top -= dim.height + options.verticalMargin;
  else top += options.verticalMargin;
 
  left = Math.floor(left)+0.5;
  top = Math.floor(top)+0.5;
 
  if(options.fill)
  context.fillRect(left, top, dim.width, dim.height);
 
  if(options.stroke)
  context.strokeRect(left, top, dim.width, dim.height);
 
  if (isImage(label))
  context.drawImage(label, left+margin, top+margin);
  else
  Flotr.drawText(context, label, left+margin, top+margin, {textBaseline: 'top', textAlign: 'left', size: options.fontSize, color: options.color});
  }
  });
 
  function isImage (i) {
  return typeof i === 'object' && i.constructor && (Image ? true : i.constructor === Image);
  }
 
  })();
 
  /**
  * Pie
  *
  * Formats the pies labels.
  * @param {Object} slice - Slice object
  * @return {String} Formatted pie label string
  */
  (function () {
 
  var
  _ = Flotr._;
 
  Flotr.defaultPieLabelFormatter = function (total, value) {
  return (100 * value / total).toFixed(2)+'%';
  };
 
  Flotr.addType('pie', {
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 1, // => in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.6, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  explode: 6, // => the number of pixels the splices will be far from the center
  sizeRatio: 0.6, // => the size ratio of the pie relative to the plot
  startAngle: Math.PI/4, // => the first slice start angle
  labelFormatter: Flotr.defaultPieLabelFormatter,
  pie3D: false, // => whether to draw the pie in 3 dimenstions or not (ineffective)
  pie3DviewAngle: (Math.PI/2 * 0.8),
  pie3DspliceThickness: 20,
  epsilon: 0.1 // => how close do you have to get to hit empty slice
  },
 
  draw : function (options) {
 
  // TODO 3D charts what?
 
  var
  data = options.data,
  context = options.context,
  canvas = context.canvas,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  sizeRatio = options.sizeRatio,
  height = options.height,
  width = options.width,
  explode = options.explode,
  color = options.color,
  fill = options.fill,
  fillStyle = options.fillStyle,
  radius = Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  value = data[0][1],
  html = [],
  vScale = 1,//Math.cos(series.pie.viewAngle);
  measure = Math.PI * 2 * value / this.total,
  startAngle = this.startAngle || (2 * Math.PI * options.startAngle), // TODO: this initial startAngle is already in radians (fixing will be test-unstable)
  endAngle = startAngle + measure,
  bisection = startAngle + measure / 2,
  label = options.labelFormatter(this.total, value),
  //plotTickness = Math.sin(series.pie.viewAngle)*series.pie.spliceThickness / vScale;
  explodeCoeff = explode + radius + 4,
  distX = Math.cos(bisection) * explodeCoeff,
  distY = Math.sin(bisection) * explodeCoeff,
  textAlign = distX < 0 ? 'right' : 'left',
  textBaseline = distY > 0 ? 'top' : 'bottom',
  style,
  x, y;
 
  context.save();
  context.translate(width / 2, height / 2);
  context.scale(1, vScale);
 
  x = Math.cos(bisection) * explode;
  y = Math.sin(bisection) * explode;
 
  // Shadows
  if (shadowSize > 0) {
  this.plotSlice(x + shadowSize, y + shadowSize, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = 'rgba(0,0,0,0.1)';
  context.fill();
  }
  }
 
  this.plotSlice(x, y, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = fillStyle;
  context.fill();
  }
  context.lineWidth = lineWidth;
  context.strokeStyle = color;
  context.stroke();
 
  style = {
  size : options.fontSize * 1.2,
  color : options.fontColor,
  weight : 1.5
  };
 
  if (label) {
  if (options.htmlText || !options.textEnabled) {
  divStyle = 'position:absolute;' + textBaseline + ':' + (height / 2 + (textBaseline === 'top' ? distY : -distY)) + 'px;';
  divStyle += textAlign + ':' + (width / 2 + (textAlign === 'right' ? -distX : distX)) + 'px;';
  html.push('<div style="', divStyle, '" class="flotr-grid-label">', label, '</div>');
  }
  else {
  style.textAlign = textAlign;
  style.textBaseline = textBaseline;
  Flotr.drawText(context, label, distX, distY, style);
  }
  }
 
  if (options.htmlText || !options.textEnabled) {
  var div = Flotr.DOM.node('<div style="color:' + options.fontColor + '" class="flotr-labels"></div>');
  Flotr.DOM.insert(div, html.join(''));
  Flotr.DOM.insert(options.element, div);
  }
 
  context.restore();
 
  // New start angle
  this.startAngle = endAngle;
  this.slices = this.slices || [];
  this.slices.push({
  radius : Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  x : x,
  y : y,
  explode : explode,
  start : startAngle,
  end : endAngle
  });
  },
  plotSlice : function (x, y, radius, startAngle, endAngle, context) {
  context.beginPath();
  context.moveTo(x, y);
  context.arc(x, y, radius, startAngle, endAngle, false);
  context.lineTo(x, y);
  context.closePath();
  },
  hit : function (options) {
 
  var
  data = options.data[0],
  args = options.args,
  index = options.index,
  mouse = args[0],
  n = args[1],
  slice = this.slices[index],
  x = mouse.relX - options.width / 2,
  y = mouse.relY - options.height / 2,
  r = Math.sqrt(x * x + y * y),
  theta = Math.atan(y / x),
  circle = Math.PI * 2,
  explode = slice.explode || options.explode,
  start = slice.start % circle,
  end = slice.end % circle,
  epsilon = options.epsilon;
 
  if (x < 0) {
  theta += Math.PI;
  } else if (x > 0 && y < 0) {
  theta += circle;
  }
 
  if (r < slice.radius + explode && r > explode) {
  if (
  (theta > start && theta < end) || // Normal Slice
  (start > end && (theta < end || theta > start)) || // First slice
  // TODO: Document the two cases at the end:
  (start === end && ((slice.start === slice.end && Math.abs(theta - start) < epsilon) || (slice.start !== slice.end && Math.abs(theta-start) > epsilon)))
  ) {
 
  // TODO Decouple this from hit plugin (chart shouldn't know what n means)
  n.x = data[0];
  n.y = data[1];
  n.sAngle = start;
  n.eAngle = end;
  n.index = 0;
  n.seriesIndex = index;
  n.fraction = data[1] / this.total;
  }
  }
  },
  drawHit: function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex];
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  this.plotSlice(slice.x, slice.y, slice.radius, slice.start, slice.end, context);
  context.stroke();
  context.restore();
  },
  clearHit : function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex],
  padding = 2 * options.lineWidth,
  radius = slice.radius + padding;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.clearRect(
  slice.x - radius,
  slice.y - radius,
  2 * radius + padding,
  2 * radius + padding
  );
  context.restore();
  },
  extendYRange : function (axis, data) {
  this.total = (this.total || 0) + data[0][1];
  }
  });
  })();
 
  /** Points **/
  Flotr.addType('points', {
  options: {
  show: false, // => setting to true will show points, false will hide
  radius: 3, // => point radius (pixels)
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the points with a color, false for (transparent) no fill
  fillColor: '#FFFFFF', // => fill color. Null to use series color.
  fillOpacity: 1, // => opacity of color inside the points
  hitRadius: null // => override for points hit radius
  },
 
  draw : function (options) {
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize;
 
  context.save();
 
  if (shadowSize > 0) {
  context.lineWidth = shadowSize / 2;
 
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 2 + context.lineWidth / 2);
 
  context.strokeStyle = 'rgba(0,0,0,0.2)';
  this.plot(options, context.lineWidth / 2);
  }
 
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
  context.restore();
  },
 
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  i, x, y;
 
  for (i = data.length - 1; i > -1; --i) {
  y = data[i][1];
  if (y === null) continue;
 
  x = xScale(data[i][0]);
  y = yScale(y);
 
  if (x < 0 || x > options.width || y < 0 || y > options.height) continue;
 
  context.beginPath();
  if (offset) {
  context.arc(x, y + offset, options.radius, 0, Math.PI, false);
  } else {
  context.arc(x, y, options.radius, 0, 2 * Math.PI, true);
  if (options.fill) context.fill();
  }
  context.stroke();
  context.closePath();
  }
  }
  });
 
  /** Radar **/
  Flotr.addType('radar', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  radiusRatio: 0.90 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.lineWidth = options.lineWidth;
 
  // Shadow
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  radius = Math.min(options.height, options.width) * options.radiusRatio / 2,
  step = 2 * Math.PI / data.length,
  angle = -Math.PI / 2,
  i, ratio;
 
  offset = offset || 0;
 
  context.beginPath();
  for (i = 0; i < data.length; ++i) {
  ratio = data[i][1] / this.max;
 
  context[i === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(i * step + angle) * radius * ratio + offset,
  Math.sin(i * step + angle) * radius * ratio + offset
  );
  }
  context.closePath();
  if (options.fill) context.fill();
  context.stroke();
  },
  extendYRange : function (axis, data) {
  this.max = Math.max(axis.max, this.max || -Number.MAX_VALUE);
  }
  });
 
  Flotr.addType('timeline', {
  options: {
  show: false,
  lineWidth: 1,
  barWidth: 0.2,
  fill: true,
  fillColor: null,
  fillOpacity: 0.4,
  centered: true
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  barWidth = options.barWidth,
  lineWidth = options.lineWidth,
  i;
 
  Flotr._.each(data, function (timeline) {
 
  var
  x = timeline[0],
  y = timeline[1],
  w = timeline[2],
  h = barWidth,
 
  xt = Math.ceil(xScale(x)),
  wt = Math.ceil(xScale(x + w)) - xt,
  yt = Math.round(yScale(y)),
  ht = Math.round(yScale(y - h)) - yt,
 
  x0 = xt - lineWidth / 2,
  y0 = Math.round(yt - ht / 2) - lineWidth / 2;
 
  context.strokeRect(x0, y0, wt, ht);
  context.fillRect(x0, y0, wt, ht);
 
  });
  },
 
  extendRange : function (series) {
 
  var
  data = series.data,
  xa = series.xaxis,
  ya = series.yaxis,
  w = series.timeline.barWidth;
 
  if (xa.options.min === null)
  xa.min = xa.datamin - w / 2;
 
  if (xa.options.max === null) {
 
  var
  max = xa.max;
 
  Flotr._.each(data, function (timeline) {
  max = Math.max(max, timeline[0] + timeline[2]);
  }, this);
 
  xa.max = max + w / 2;
  }
 
  if (ya.options.min === null)
  ya.min = ya.datamin - w;
  if (ya.options.min === null)
  ya.max = ya.datamax + w;
  }
 
  });
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('crosshair', {
  options: {
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#FF0000', // => crosshair color
  hideCursor: true // => hide the cursor when the crosshair is shown
  },
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  if (this.options.crosshair.mode) {
  this.crosshair.clearCrosshair();
  this.crosshair.drawCrosshair(pos);
  }
  }
  },
  /**
  * Draws the selection box.
  */
  drawCrosshair: function(pos) {
  var octx = this.octx,
  options = this.options.crosshair,
  plotOffset = this.plotOffset,
  x = plotOffset.left + Math.round(pos.relX) + 0.5,
  y = plotOffset.top + Math.round(pos.relY) + 0.5;
 
  if (pos.relX < 0 || pos.relY < 0 || pos.relX > this.plotWidth || pos.relY > this.plotHeight) {
  this.el.style.cursor = null;
  D.removeClass(this.el, 'flotr-crosshair');
  return;
  }
 
  if (options.hideCursor) {
  this.el.style.cursor = 'none';
  D.addClass(this.el, 'flotr-crosshair');
  }
 
  octx.save();
  octx.strokeStyle = options.color;
  octx.lineWidth = 1;
  octx.beginPath();
 
  if (options.mode.indexOf('x') != -1) {
  octx.moveTo(x, plotOffset.top);
  octx.lineTo(x, plotOffset.top + this.plotHeight);
  }
 
  if (options.mode.indexOf('y') != -1) {
  octx.moveTo(plotOffset.left, y);
  octx.lineTo(plotOffset.left + this.plotWidth, y);
  }
 
  octx.stroke();
  octx.restore();
  },
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearCrosshair: function() {
 
  var
  plotOffset = this.plotOffset,
  position = this.lastMousePos,
  context = this.octx;
 
  if (position) {
  context.clearRect(
  Math.round(position.relX) + plotOffset.left,
  plotOffset.top,
  1,
  this.plotHeight + 1
  );
  context.clearRect(
  plotOffset.left,
  Math.round(position.relY) + plotOffset.top,
  this.plotWidth + 1,
  1
  );
  }
  }
  });
  })();
 
  (function() {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  function getImage (type, canvas, width, height) {
 
  // TODO add scaling for w / h
  var
  mime = 'image/'+type,
  data = canvas.toDataURL(mime),
  image = new Image();
  image.src = data;
  return image;
  }
 
  Flotr.addPlugin('download', {
 
  saveImage: function (type, width, height, replaceCanvas) {
  var image = null;
  if (Flotr.isIE && Flotr.isIE < 9) {
  image = '<html><body>'+this.canvas.firstChild.innerHTML+'</body></html>';
  return window.open().document.write(image);
  }
 
  if (type !== 'jpeg' && type !== 'png') return;
 
  image = getImage(type, this.canvas, width, height);
 
  if (_.isElement(image) && replaceCanvas) {
  this.download.restoreCanvas();
  D.hide(this.canvas);
  D.hide(this.overlay);
  D.setStyles({position: 'absolute'});
  D.insert(this.el, image);
  this.saveImageElement = image;
  } else {
  return window.open(image.src);
  }
  },
 
  restoreCanvas: function() {
  D.show(this.canvas);
  D.show(this.overlay);
  if (this.saveImageElement) this.el.removeChild(this.saveImageElement);
  this.saveImageElement = null;
  }
  });
 
  })();
 
  (function () {
 
  var E = Flotr.EventAdapter,
  _ = Flotr._;
 
  Flotr.addPlugin('graphGrid', {
 
  callbacks: {
  'flotr:beforedraw' : function () {
  this.graphGrid.drawGrid();
  },
  'flotr:afterdraw' : function () {
  this.graphGrid.drawOutline();
  }
  },
 
  drawGrid: function(){
 
  var
  ctx = this.ctx,
  options = this.options,
  grid = options.grid,
  verticalLines = grid.verticalLines,
  horizontalLines = grid.horizontalLines,
  minorVerticalLines = grid.minorVerticalLines,
  minorHorizontalLines = grid.minorHorizontalLines,
  plotHeight = this.plotHeight,
  plotWidth = this.plotWidth,
  a, v, i, j;
 
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:beforegrid', [this.axes.x, this.axes.y, options, this]);
  }
  ctx.save();
  ctx.lineWidth = 1;
  ctx.strokeStyle = grid.tickColor;
 
  function circularHorizontalTicks (ticks) {
  for(i = 0; i < ticks.length; ++i){
  var ratio = ticks[i].v / a.max;
  for(j = 0; j <= sides; ++j){
  ctx[j === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(j*coeff+angle)*radius*ratio,
  Math.sin(j*coeff+angle)*radius*ratio
  );
  }
  }
  }
  function drawGridLines (ticks, callback) {
  _.each(_.pluck(ticks, 'v'), function(v){
  // Don't show lines on upper and lower bounds.
  if ((v <= a.min || v >= a.max) ||
  (v == a.min || v == a.max) && grid.outlineWidth)
  return;
  callback(Math.floor(a.d2p(v)) + ctx.lineWidth/2);
  });
  }
  function drawVerticalLines (x) {
  ctx.moveTo(x, 0);
  ctx.lineTo(x, plotHeight);
  }
  function drawHorizontalLines (y) {
  ctx.moveTo(0, y);
  ctx.lineTo(plotWidth, y);
  }
 
  if (grid.circular) {
  ctx.translate(this.plotOffset.left+plotWidth/2, this.plotOffset.top+plotHeight/2);
  var radius = Math.min(plotHeight, plotWidth)*options.radar.radiusRatio/2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw grid lines in vertical direction.
  ctx.beginPath();
 
  a = this.axes.y;
 
  if(horizontalLines){
  circularHorizontalTicks(a.ticks);
  }
  if(minorHorizontalLines){
  circularHorizontalTicks(a.minorTicks);
  }
 
  if(verticalLines){
  _.times(sides, function(i){
  ctx.moveTo(0, 0);
  ctx.lineTo(Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  });
  }
  ctx.stroke();
  }
  else {
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
 
  // Draw grid background, if present in options.
  if(grid.backgroundColor){
  ctx.fillStyle = this.processColor(grid.backgroundColor, {x1: 0, y1: 0, x2: plotWidth, y2: plotHeight});
  ctx.fillRect(0, 0, plotWidth, plotHeight);
  }
 
  ctx.beginPath();
 
  a = this.axes.x;
  if (verticalLines) drawGridLines(a.ticks, drawVerticalLines);
  if (minorVerticalLines) drawGridLines(a.minorTicks, drawVerticalLines);
 
  a = this.axes.y;
  if (horizontalLines) drawGridLines(a.ticks, drawHorizontalLines);
  if (minorHorizontalLines) drawGridLines(a.minorTicks, drawHorizontalLines);
 
  ctx.stroke();
  }
 
  ctx.restore();
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:aftergrid', [this.axes.x, this.axes.y, options, this]);
  }
  },
 
  drawOutline: function(){
  var
  that = this,
  options = that.options,
  grid = options.grid,
  outline = grid.outline,
  ctx = that.ctx,
  backgroundImage = grid.backgroundImage,
  plotOffset = that.plotOffset,
  leftOffset = plotOffset.left,
  topOffset = plotOffset.top,
  plotWidth = that.plotWidth,
  plotHeight = that.plotHeight,
  v, img, src, left, top, globalAlpha;
 
  if (!grid.outlineWidth) return;
 
  ctx.save();
 
  if (grid.circular) {
  ctx.translate(leftOffset + plotWidth / 2, topOffset + plotHeight / 2);
  var radius = Math.min(plotHeight, plotWidth) * options.radar.radiusRatio / 2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw axis/grid border.
  ctx.beginPath();
  ctx.lineWidth = grid.outlineWidth;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'round';
 
  for(i = 0; i <= sides; ++i){
  ctx[i === 0 ? 'moveTo' : 'lineTo'](Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  }
  //ctx.arc(0, 0, radius, 0, Math.PI*2, true);
 
  ctx.stroke();
  }
  else {
  ctx.translate(leftOffset, topOffset);
 
  // Draw axis/grid border.
  var lw = grid.outlineWidth,
  orig = 0.5-lw+((lw+1)%2/2),
  lineTo = 'lineTo',
  moveTo = 'moveTo';
  ctx.lineWidth = lw;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'miter';
  ctx.beginPath();
  ctx.moveTo(orig, orig);
  plotWidth = plotWidth - (lw / 2) % 1;
  plotHeight = plotHeight + lw / 2;
  ctx[outline.indexOf('n') !== -1 ? lineTo : moveTo](plotWidth, orig);
  ctx[outline.indexOf('e') !== -1 ? lineTo : moveTo](plotWidth, plotHeight);
  ctx[outline.indexOf('s') !== -1 ? lineTo : moveTo](orig, plotHeight);
  ctx[outline.indexOf('w') !== -1 ? lineTo : moveTo](orig, orig);
  ctx.stroke();
  ctx.closePath();
  }
 
  ctx.restore();
 
  if (backgroundImage) {
 
  src = backgroundImage.src || backgroundImage;
  left = (parseInt(backgroundImage.left, 10) || 0) + plotOffset.left;
  top = (parseInt(backgroundImage.top, 10) || 0) + plotOffset.top;
  img = new Image();
 
  img.onload = function() {
  ctx.save();
  if (backgroundImage.alpha) ctx.globalAlpha = backgroundImage.alpha;
  ctx.globalCompositeOperation = 'destination-over';
  ctx.drawImage(img, 0, 0, img.width, img.height, left, top, plotWidth, plotHeight);
  ctx.restore();
  };
 
  img.src = src;
  }
  }
  });
 
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._,
  flotr = Flotr,
  S_MOUSETRACK = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;';
 
  Flotr.addPlugin('hit', {
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  this.hit.track(pos);
  },
  'flotr:click': function(pos) {
  var
  hit = this.hit.track(pos);
  _.defaults(pos, hit);
  },
  'flotr:mouseout': function() {
  this.hit.clearHit();
  },
  'flotr:destroy': function() {
  this.mouseTrack = null;
  }
  },
  track : function (pos) {
  if (this.options.mouse.track || _.any(this.series, function(s){return s.mouse && s.mouse.track;})) {
  return this.hit.hit(pos);
  }
  },
  /**
  * Try a method on a graph type. If the method exists, execute it.
  * @param {Object} series
  * @param {String} method Method name.
  * @param {Array} args Arguments applied to method.
  * @return executed successfully or failed.
  */
  executeOnType: function(s, method, args){
  var
  success = false,
  options;
 
  if (!_.isArray(s)) s = [s];
 
  function e(s, index) {
  _.each(_.keys(flotr.graphTypes), function (type) {
  if (s[type] && s[type].show && this[type][method]) {
  options = this.getOptions(s, type);
 
  options.fill = !!s.mouse.fillColor;
  options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  options.color = s.mouse.lineColor;
  options.context = this.octx;
  options.index = index;
 
  if (args) options.args = args;
  this[type][method].call(this[type], options);
  success = true;
  }
  }, this);
  }
  _.each(s, e, this);
 
  return success;
  },
  /**
  * Updates the mouse tracking point on the overlay.
  */
  drawHit: function(n){
  var octx = this.octx,
  s = n.series;
 
  if (s.mouse.lineColor) {
  octx.save();
  octx.lineWidth = (s.points ? s.points.lineWidth : 1);
  octx.strokeStyle = s.mouse.lineColor;
  octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  octx.translate(this.plotOffset.left, this.plotOffset.top);
 
  if (!this.hit.executeOnType(s, 'drawHit', n)) {
  var
  xa = n.xaxis,
  ya = n.yaxis;
 
  octx.beginPath();
  // TODO fix this (points) should move to general testable graph mixin
  octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.hitRadius || s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
  octx.fill();
  octx.stroke();
  octx.closePath();
  }
  octx.restore();
  this.clip(octx);
  }
  this.prevHit = n;
  },
  /**
  * Removes the mouse tracking point from the overlay.
  */
  clearHit: function(){
  var prev = this.prevHit,
  octx = this.octx,
  plotOffset = this.plotOffset;
  octx.save();
  octx.translate(plotOffset.left, plotOffset.top);
  if (prev) {
  if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
  // TODO fix this (points) should move to general testable graph mixin
  var
  s = prev.series,
  lw = (s.points ? s.points.lineWidth : 1);
  offset = (s.points.hitRadius || s.points.radius || s.mouse.radius) + lw;
  octx.clearRect(
  prev.xaxis.d2p(prev.x) - offset,
  prev.yaxis.d2p(prev.y) - offset,
  offset*2,
  offset*2
  );
  }
  D.hide(this.mouseTrack);
  this.prevHit = null;
  }
  octx.restore();
  },
  /**
  * Retrieves the nearest data point from the mouse cursor. If it's within
  * a certain range, draw a point on the overlay canvas and display the x and y
  * value of the data.
  * @param {Object} mouse - Object that holds the relative x and y coordinates of the cursor.
  */
  hit : function (mouse) {
 
  var
  options = this.options,
  prevHit = this.prevHit,
  closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n;
 
  if (this.series.length === 0) return;
 
  // Nearest data element.
  // dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
  // xaxis, yaxis, series, index, seriesIndex
  n = {
  relX : mouse.relX,
  relY : mouse.relY,
  absX : mouse.absX,
  absY : mouse.absY
  };
 
  if (options.mouse.trackY &&
  !options.mouse.trackAll &&
  this.hit.executeOnType(this.series, 'hit', [mouse, n]) &&
  !_.isUndefined(n.seriesIndex))
  {
  series = this.series[n.seriesIndex];
  n.series = series;
  n.mouse = series.mouse;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  } else {
 
  closest = this.hit.closest(mouse);
 
  if (closest) {
 
  closest = options.mouse.trackY ? closest.point : closest.x;
  seriesIndex = closest.seriesIndex;
  series = this.series[seriesIndex];
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  sensibility = 2 * series.mouse.sensibility;
 
  if
  (options.mouse.trackAll ||
  (closest.distanceX < sensibility / xaxis.scale &&
  (!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale)))
  {
  n.series = series;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  n.mouse = series.mouse;
  n.x = closest.x;
  n.y = closest.y;
  n.dist = closest.distance;
  n.index = closest.dataIndex;
  n.seriesIndex = seriesIndex;
  }
  }
  }
 
  if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
  this.hit.clearHit();
  if (n.series && n.mouse && n.mouse.track) {
  this.hit.drawMouseTrack(n);
  this.hit.drawHit(n);
  Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
  }
  }
 
  return n;
  },
 
  closest : function (mouse) {
 
  var
  series = this.series,
  options = this.options,
  relX = mouse.relX,
  relY = mouse.relY,
  compare = Number.MAX_VALUE,
  compareX = Number.MAX_VALUE,
  closest = {},
  closestX = {},
  check = false,
  serie, data,
  distance, distanceX, distanceY,
  mouseX, mouseY,
  x, y, i, j;
 
  function setClosest (o) {
  o.distance = distance;
  o.distanceX = distanceX;
  o.distanceY = distanceY;
  o.seriesIndex = i;
  o.dataIndex = j;
  o.x = x;
  o.y = y;
  check = true;
  }
 
  for (i = 0; i < series.length; i++) {
 
  serie = series[i];
  data = serie.data;
  mouseX = serie.xaxis.p2d(relX);
  mouseY = serie.yaxis.p2d(relY);
 
  for (j = data.length; j--;) {
 
  x = data[j][0];
  y = data[j][1];
 
  if (x === null || y === null) continue;
 
  // don't check if the point isn't visible in the current range
  if (x < serie.xaxis.min || x > serie.xaxis.max) continue;
 
  distanceX = Math.abs(x - mouseX);
  distanceY = Math.abs(y - mouseY);
 
  // Skip square root for speed
  distance = distanceX * distanceX + distanceY * distanceY;
 
  if (distance < compare) {
  compare = distance;
  setClosest(closest);
  }
 
  if (distanceX < compareX) {
  compareX = distanceX;
  setClosest(closestX);
  }
  }
  }
 
  return check ? {
  point : closest,
  x : closestX
  } : false;
  },
 
  drawMouseTrack : function (n) {
 
  var
  pos = '',
  s = n.series,
  p = n.mouse.position,
  m = n.mouse.margin,
  x = n.x,
  y = n.y,
  elStyle = S_MOUSETRACK,
  mouseTrack = this.mouseTrack,
  plotOffset = this.plotOffset,
  left = plotOffset.left,
  right = plotOffset.right,
  bottom = plotOffset.bottom,
  top = plotOffset.top,
  decimals = n.mouse.trackDecimals,
  options = this.options;
 
  // Create
  if (!mouseTrack) {
  mouseTrack = D.node('<div class="flotr-mouse-value"></div>');
  this.mouseTrack = mouseTrack;
  D.insert(this.el, mouseTrack);
  }
 
  if (!n.mouse.relative) { // absolute to the canvas
 
  if (p.charAt(0) == 'n') pos += 'top:' + (m + top) + 'px;bottom:auto;';
  else if (p.charAt(0) == 's') pos += 'bottom:' + (m + bottom) + 'px;top:auto;';
  if (p.charAt(1) == 'e') pos += 'right:' + (m + right) + 'px;left:auto;';
  else if (p.charAt(1) == 'w') pos += 'left:' + (m + left) + 'px;right:auto;';
 
  // Pie
  } else if (s.pie && s.pie.show) {
  var center = {
  x: (this.plotWidth)/2,
  y: (this.plotHeight)/2
  },
  radius = (Math.min(this.canvasWidth, this.canvasHeight) * s.pie.sizeRatio) / 2,
  bisection = n.sAngle<n.eAngle ? (n.sAngle + n.eAngle) / 2: (n.sAngle + n.eAngle + 2* Math.PI) / 2;
 
  pos += 'bottom:' + (m - top - center.y - Math.sin(bisection) * radius/2 + this.canvasHeight) + 'px;top:auto;';
  pos += 'left:' + (m + left + center.x + Math.cos(bisection) * radius/2) + 'px;right:auto;';
 
  // Default
  } else {
  if (/n/.test(p)) pos += 'bottom:' + (m - top - n.yaxis.d2p(n.y) + this.canvasHeight) + 'px;top:auto;';
  else pos += 'top:' + (m + top + n.yaxis.d2p(n.y)) + 'px;bottom:auto;';
  if (/w/.test(p)) pos += 'right:' + (m - left - n.xaxis.d2p(n.x) + this.canvasWidth) + 'px;left:auto;';
  else pos += 'left:' + (m + left + n.xaxis.d2p(n.x)) + 'px;right:auto;';
  }
 
  elStyle += pos;
  mouseTrack.style.cssText = elStyle;
  if (!decimals || decimals < 0) decimals = 0;
 
  if (x && x.toFixed) x = x.toFixed(decimals);
 
  if (y && y.toFixed) y = y.toFixed(decimals);
 
  mouseTrack.innerHTML = n.mouse.trackFormatter({
  x: x ,
  y: y,
  series: n.series,
  index: n.index,
  nearest: n,
  fraction: n.fraction
  });
 
  D.show(mouseTrack);
 
  if (n.mouse.relative) {
  if (!/[ew]/.test(p)) {
  // Center Horizontally
  mouseTrack.style.left =
  (left + n.xaxis.d2p(n.x) - D.size(mouseTrack).width / 2) + 'px';
  } else
  if (!/[ns]/.test(p)) {
  // Center Vertically
  mouseTrack.style.top =
  (top + n.yaxis.d2p(n.y) - D.size(mouseTrack).height / 2) + 'px';
  }
  }
  }
 
  });
  })();
 
  /**
  * Selection Handles Plugin
  *
  *
  * Options
  * show - True enables the handles plugin.
  * drag - Left and Right drag handles
  * scroll - Scrolling handle
  */
  (function () {
 
  function isLeftClick (e, type) {
  return (e.which ? (e.which === 1) : (e.button === 0 || e.button === 1));
  }
 
  function boundX(x, graph) {
  return Math.min(Math.max(0, x), graph.plotWidth - 1);
  }
 
  function boundY(y, graph) {
  return Math.min(Math.max(0, y), graph.plotHeight);
  }
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._;
 
 
  Flotr.addPlugin('selection', {
 
  options: {
  pinchOnly: null, // Only select on pinch
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#B6D9FF', // => selection box color
  fps: 20 // => frames-per-second
  },
 
  callbacks: {
  'flotr:mouseup' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (selection.interval) clearInterval(selection.interval);
 
  if (this.multitouches) {
  selection.updateSelection();
  } else
  if (!options.pinchOnly) {
  selection.setSelectionPos(selection.selection.second, pointer);
  }
  selection.clearSelection();
 
  if(selection.selecting && selection.selectionIsSane()){
  selection.drawSelection();
  selection.fireSelectEvent();
  this.ignoreClick = true;
  }
  },
  'flotr:mousedown' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (!options.mode || (!isLeftClick(event) && _.isUndefined(event.touches))) return;
  if (!options.pinchOnly) selection.setSelectionPos(selection.selection.first, pointer);
  if (selection.interval) clearInterval(selection.interval);
 
  this.lastMousePos.pageX = null;
  selection.selecting = false;
  selection.interval = setInterval(
  _.bind(selection.updateSelection, this),
  1000 / options.fps
  );
  },
  'flotr:destroy' : function (event) {
  clearInterval(this.selection.interval);
  }
  },
 
  // TODO This isn't used. Maybe it belongs in the draw area and fire select event methods?
  getArea: function() {
 
  var
  s = this.selection.selection,
  a = this.axes,
  first = s.first,
  second = s.second,
  x1, x2, y1, y2;
 
  x1 = a.x.p2d(s.first.x);
  x2 = a.x.p2d(s.second.x);
  y1 = a.y.p2d(s.first.y);
  y2 = a.y.p2d(s.second.y);
 
  return {
  x1 : Math.min(x1, x2),
  y1 : Math.min(y1, y2),
  x2 : Math.max(x1, x2),
  y2 : Math.max(y1, y2),
  xfirst : x1,
  xsecond : x2,
  yfirst : y1,
  ysecond : y2
  };
  },
 
  selection: {first: {x: -1, y: -1}, second: {x: -1, y: -1}},
  prevSelection: null,
  interval: null,
 
  /**
  * Fires the 'flotr:select' event when the user made a selection.
  */
  fireSelectEvent: function(name){
  var
  area = this.selection.getArea();
  name = name || 'select';
  area.selection = this.selection.selection;
  E.fire(this.el, 'flotr:'+name, [area, this]);
  },
 
  /**
  * Allows the user the manually select an area.
  * @param {Object} area - Object with coordinates to select.
  */
  setSelection: function(area, preventEvent){
  var options = this.options,
  xa = this.axes.x,
  ya = this.axes.y,
  vertScale = ya.scale,
  hozScale = xa.scale,
  selX = options.selection.mode.indexOf('x') != -1,
  selY = options.selection.mode.indexOf('y') != -1,
  s = this.selection.selection;
 
  this.selection.clearSelection();
 
  s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
  s.second.y = boundY((selX && !selY) ? this.plotHeight - 1: (ya.max - area.y2) * vertScale, this);
  s.first.x = boundX((selY && !selX) ? 0 : (area.x1 - xa.min) * hozScale, this);
  s.second.x = boundX((selY && !selX) ? this.plotWidth : (area.x2 - xa.min) * hozScale, this);
 
  this.selection.drawSelection();
  if (!preventEvent)
  this.selection.fireSelectEvent();
  },
 
  /**
  * Calculates the position of the selection.
  * @param {Object} pos - Position object.
  * @param {Event} event - Event object.
  */
  setSelectionPos: function(pos, pointer) {
  var mode = this.options.selection.mode,
  selection = this.selection.selection;
 
  if(mode.indexOf('x') == -1) {
  pos.x = (pos == selection.first) ? 0 : this.plotWidth;
  }else{
  pos.x = boundX(pointer.relX, this);
  }
 
  if (mode.indexOf('y') == -1) {
  pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
  }else{
  pos.y = boundY(pointer.relY, this);
  }
  },
  /**
  * Draws the selection box.
  */
  drawSelection: function() {
 
  this.selection.fireSelectEvent('selecting');
 
  var s = this.selection.selection,
  octx = this.octx,
  options = this.options,
  plotOffset = this.plotOffset,
  prevSelection = this.selection.prevSelection;
 
  if (prevSelection &&
  s.first.x == prevSelection.first.x &&
  s.first.y == prevSelection.first.y &&
  s.second.x == prevSelection.second.x &&
  s.second.y == prevSelection.second.y) {
  return;
  }
 
  octx.save();
  octx.strokeStyle = this.processColor(options.selection.color, {opacity: 0.8});
  octx.lineWidth = 1;
  octx.lineJoin = 'miter';
  octx.fillStyle = this.processColor(options.selection.color, {opacity: 0.4});
 
  this.selection.prevSelection = {
  first: { x: s.first.x, y: s.first.y },
  second: { x: s.second.x, y: s.second.y }
  };
 
  var x = Math.min(s.first.x, s.second.x),
  y = Math.min(s.first.y, s.second.y),
  w = Math.abs(s.second.x - s.first.x),
  h = Math.abs(s.second.y - s.first.y);
 
  octx.fillRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.strokeRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.restore();
  },
 
  /**
  * Updates (draws) the selection box.
  */
  updateSelection: function(){
  if (!this.lastMousePos.pageX) return;
 
  this.selection.selecting = true;
 
  if (this.multitouches) {
  this.selection.setSelectionPos(this.selection.selection.first, this.getEventPosition(this.multitouches[0]));
  this.selection.setSelectionPos(this.selection.selection.second, this.getEventPosition(this.multitouches[1]));
  } else
  if (this.options.selection.pinchOnly) {
  return;
  } else {
  this.selection.setSelectionPos(this.selection.selection.second, this.lastMousePos);
  }
 
  this.selection.clearSelection();
 
  if(this.selection.selectionIsSane()) {
  this.selection.drawSelection();
  }
  },
 
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearSelection: function() {
  if (!this.selection.prevSelection) return;
 
  var prevSelection = this.selection.prevSelection,
  lw = 1,
  plotOffset = this.plotOffset,
  x = Math.min(prevSelection.first.x, prevSelection.second.x),
  y = Math.min(prevSelection.first.y, prevSelection.second.y),
  w = Math.abs(prevSelection.second.x - prevSelection.first.x),
  h = Math.abs(prevSelection.second.y - prevSelection.first.y);
 
  this.octx.clearRect(x + plotOffset.left - lw + 0.5,
  y + plotOffset.top - lw,
  w + 2 * lw + 0.5,
  h + 2 * lw + 0.5);
 
  this.selection.prevSelection = null;
  },
  /**
  * Determines whether or not the selection is sane and should be drawn.
  * @return {Boolean} - True when sane, false otherwise.
  */
  selectionIsSane: function(){
  var s = this.selection.selection;
  return Math.abs(s.second.x - s.first.x) >= 5 ||
  Math.abs(s.second.y - s.first.y) >= 5;
  }
 
  });
 
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('labels', {
 
  callbacks : {
  'flotr:afterdraw' : function () {
  this.labels.draw();
  }
  },
 
  draw: function(){
  // Construct fixed width label boxes, which can be styled easily.
  var
  axis, tick, left, top, xBoxWidth,
  radius, sides, coeff, angle,
  div, i, html = '',
  noLabels = 0,
  options = this.options,
  ctx = this.ctx,
  a = this.axes,
  style = { size: options.fontSize };
 
  for (i = 0; i < a.x.ticks.length; ++i){
  if (a.x.ticks[i].label) { ++noLabels; }
  }
  xBoxWidth = this.plotWidth / noLabels;
 
  if (options.grid.circular) {
  ctx.save();
  ctx.translate(this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top + this.plotHeight / 2);
 
  radius = this.plotHeight * options.radar.radiusRatio / 2 + options.fontSize;
  sides = this.axes.x.ticks.length;
  coeff = 2 * (Math.PI / sides);
  angle = -Math.PI / 2;
 
  drawLabelCircular(this, a.x, false);
  drawLabelCircular(this, a.x, true);
  drawLabelCircular(this, a.y, false);
  drawLabelCircular(this, a.y, true);
  ctx.restore();
  }
 
  if (!options.HtmlText && this.textEnabled) {
  drawLabelNoHtmlText(this, a.x, 'center', 'top');
  drawLabelNoHtmlText(this, a.x2, 'center', 'bottom');
  drawLabelNoHtmlText(this, a.y, 'right', 'middle');
  drawLabelNoHtmlText(this, a.y2, 'left', 'middle');
 
  } else if ((
  a.x.options.showLabels ||
  a.x2.options.showLabels ||
  a.y.options.showLabels ||
  a.y2.options.showLabels) &&
  !options.grid.circular
  ) {
 
  html = '';
 
  drawLabelHtml(this, a.x);
  drawLabelHtml(this, a.x2);
  drawLabelHtml(this, a.y);
  drawLabelHtml(this, a.y2);
 
  ctx.stroke();
  ctx.restore();
  div = D.create('div');
  D.setStyles(div, {
  fontSize: 'smaller',
  color: options.grid.color
  });
  div.className = 'flotr-labels';
  D.insert(this.el, div);
  D.insert(div, html);
  }
 
  function drawLabelCircular (graph, axis, minorTicks) {
  var
  ticks = minorTicks ? axis.minorTicks : axis.ticks,
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  angle : Flotr.toRad(axis.options.labelsAngle),
  textBaseline : 'middle'
  };
 
  for (i = 0; i < ticks.length &&
  (minorTicks ? axis.options.showMinorLabels : axis.options.showLabels); ++i){
  tick = ticks[i];
  tick.label += '';
  if (!tick.label || !tick.label.length) { continue; }
 
  x = Math.cos(i * coeff + angle) * radius;
  y = Math.sin(i * coeff + angle) * radius;
 
  style.textAlign = isX ? (Math.abs(x) < 0.1 ? 'center' : (x < 0 ? 'right' : 'left')) : 'left';
 
  Flotr.drawText(
  ctx, tick.label,
  isX ? x : 3,
  isX ? y : -(axis.ticks[i].v / axis.max) * (radius - options.fontSize),
  style
  );
  }
  }
 
  function drawLabelNoHtmlText (graph, axis, textAlign, textBaseline) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  textAlign : textAlign,
  textBaseline : textBaseline,
  angle : Flotr.toRad(axis.options.labelsAngle)
  };
  style = Flotr.getBestTextAlign(style.angle, style);
 
  for (i = 0; i < axis.ticks.length && continueShowingLabels(axis); ++i) {
 
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length) { continue; }
 
  offset = axis.d2p(tick.v);
  if (offset < 0 ||
  offset > (isX ? graph.plotWidth : graph.plotHeight)) { continue; }
 
  Flotr.drawText(
  ctx, tick.label,
  leftOffset(graph, isX, isFirst, offset),
  topOffset(graph, isX, isFirst, offset),
  style
  );
 
  // Only draw on axis y2
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = style.color;
  ctx.beginPath();
  ctx.moveTo(graph.plotOffset.left + graph.plotWidth - 8, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.lineTo(graph.plotOffset.left + graph.plotWidth, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.stroke();
  ctx.restore();
  }
  }
 
  function continueShowingLabels (axis) {
  return axis.options.showLabels && axis.used;
  }
  function leftOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.left +
  (isX ? offset :
  (isFirst ?
  -options.grid.labelMargin :
  options.grid.labelMargin + graph.plotWidth));
  }
  function topOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.top +
  (isX ? options.grid.labelMargin : offset) +
  ((isX && isFirst) ? graph.plotHeight : 0);
  }
  }
 
  function drawLabelHtml (graph, axis) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  name = '',
  left, style, top,
  offset = graph.plotOffset;
 
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = axis.options.color || options.grid.color;
  ctx.beginPath();
  }
 
  if (axis.options.showLabels && (isFirst ? true : axis.used)) {
  for (i = 0; i < axis.ticks.length; ++i) {
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) < 0) ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) > (isX ? graph.canvasWidth : graph.canvasHeight))) {
  continue;
  }
  top = offset.top +
  (isX ?
  ((isFirst ? 1 : -1 ) * (graph.plotHeight + options.grid.labelMargin)) :
  axis.d2p(tick.v) - axis.maxLabel.height / 2);
  left = isX ? (offset.left + axis.d2p(tick.v) - xBoxWidth / 2) : 0;
 
  name = '';
  if (i === 0) {
  name = ' first';
  } else if (i === axis.ticks.length - 1) {
  name = ' last';
  }
  name += isX ? ' flotr-grid-label-x' : ' flotr-grid-label-y';
 
  html += [
  '<div style="position:absolute; text-align:' + (isX ? 'center' : 'right') + '; ',
  'top:' + top + 'px; ',
  ((!isX && !isFirst) ? 'right:' : 'left:') + left + 'px; ',
  'width:' + (isX ? xBoxWidth : ((isFirst ? offset.left : offset.right) - options.grid.labelMargin)) + 'px; ',
  axis.options.color ? ('color:' + axis.options.color + '; ') : ' ',
  '" class="flotr-grid-label' + name + '">' + tick.label + '</div>'
  ].join(' ');
 
  if (!isX && !isFirst) {
  ctx.moveTo(offset.left + graph.plotWidth - 8, offset.top + axis.d2p(tick.v));
  ctx.lineTo(offset.left + graph.plotWidth, offset.top + axis.d2p(tick.v));
  }
  }
  }
  }
  }
 
  });
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('legend', {
  options: {
  show: true, // => setting to true will show the legend, hide otherwise
  noColumns: 1, // => number of colums in legend table // @todo: doesn't work for HtmlText = false
  labelFormatter: function(v){return v;}, // => fn: string -> string
  labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
  labelBoxWidth: 14,
  labelBoxHeight: 10,
  labelBoxMargin: 5,
  container: null, // => container (as jQuery object) to put legend in, null means default on top of graph
  position: 'nw', // => position of default legend container within plot
  margin: 5, // => distance from grid edge to default legend container within plot
  backgroundColor: '#F0F0F0', // => Legend background color.
  backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
  'flotr:afterinit': function() {
  this.legend.insertLegend();
  }
  },
  /**
  * Adds a legend div to the canvas container or draws it on the canvas.
  */
  insertLegend: function(){
 
  if(!this.options.legend.show)
  return;
 
  var series = this.series,
  plotOffset = this.plotOffset,
  options = this.options,
  legend = options.legend,
  fragments = [],
  rowStarted = false,
  ctx = this.ctx,
  itemCount = _.filter(series, function(s) {return (s.label && !s.hide);}).length,
  p = legend.position,
  m = legend.margin,
  opacity = legend.backgroundOpacity,
  i, label, color;
 
  if (itemCount) {
 
  var lbw = legend.labelBoxWidth,
  lbh = legend.labelBoxHeight,
  lbm = legend.labelBoxMargin,
  offsetX = plotOffset.left + m,
  offsetY = plotOffset.top + m,
  labelMaxWidth = 0,
  style = {
  size: options.fontSize*1.1,
  color: options.grid.color
  };
 
  // We calculate the labels' max width
  for(i = series.length - 1; i > -1; --i){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
  labelMaxWidth = Math.max(labelMaxWidth, this._text.measureText(label, style).width);
  }
 
  var legendWidth = Math.round(lbw + lbm*3 + labelMaxWidth),
  legendHeight = Math.round(itemCount*(lbm+lbh) + lbm);
 
  // Default Opacity
  if (!opacity && opacity !== 0) {
  opacity = 0.1;
  }
 
  if (!options.HtmlText && this.textEnabled && !legend.container) {
 
  if(p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
  if(p.charAt(0) == 'c') offsetY = plotOffset.top + (this.plotHeight/2) - (m + (legendHeight/2));
  if(p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);
 
  // Legend box
  color = this.processColor(legend.backgroundColor, { opacity : opacity });
 
  ctx.fillStyle = color;
  ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);
 
  // Legend labels
  var x = offsetX + lbm;
  var y = offsetY + lbm;
  for(i = 0; i < series.length; i++){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
 
  ctx.fillStyle = series[i].color;
  ctx.fillRect(x, y, lbw-1, lbh-1);
 
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.lineWidth = 1;
  ctx.strokeRect(Math.ceil(x)-1.5, Math.ceil(y)-1.5, lbw+2, lbh+2);
 
  // Legend text
  Flotr.drawText(ctx, label, x + lbw + lbm, y + lbh, style);
 
  y += lbh + lbm;
  }
  }
  else {
  for(i = 0; i < series.length; ++i){
  if(!series[i].label || series[i].hide) continue;
 
  if(i % legend.noColumns === 0){
  fragments.push(rowStarted ? '</tr><tr>' : '<tr>');
  rowStarted = true;
  }
 
  var s = series[i],
  boxWidth = legend.labelBoxWidth,
  boxHeight = legend.labelBoxHeight;
 
  label = legend.labelFormatter(s.label);
  color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';
 
  fragments.push(
  '<td class="flotr-legend-color-box">',
  '<div style="border:1px solid ', legend.labelBoxBorderColor, ';padding:1px">',
  '<div style="width:', (boxWidth-1), 'px;height:', (boxHeight-1), 'px;border:1px solid ', series[i].color, '">', // Border
  '<div style="width:', boxWidth, 'px;height:', boxHeight, 'px;', color, '"></div>', // Background
  '</div>',
  '</div>',
  '</td>',
  '<td class="flotr-legend-label">', label, '</td>'
  );
  }
  if(rowStarted) fragments.push('</tr>');
 
  if(fragments.length > 0){
  var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join('') + '</table>';
  if(legend.container){
  D.empty(legend.container);
  D.insert(legend.container, table);
  }
  else {
  var styles = {position: 'absolute', 'zIndex': '2', 'border' : '1px solid ' + legend.labelBoxBorderColor};
 
  if(p.charAt(0) == 'n') { styles.top = (m + plotOffset.top) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 'c') { styles.top = (m + (this.plotHeight - legendHeight) / 2) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 's') { styles.bottom = (m + plotOffset.bottom) + 'px'; styles.top = 'auto'; }
  if(p.charAt(1) == 'e') { styles.right = (m + plotOffset.right) + 'px'; styles.left = 'auto'; }
  else if(p.charAt(1) == 'w') { styles.left = (m + plotOffset.left) + 'px'; styles.right = 'auto'; }
 
  var div = D.create('div'), size;
  div.className = 'flotr-legend';
  D.setStyles(div, styles);
  D.insert(div, table);
  D.insert(this.el, div);
 
  if (!opacity) return;
 
  var c = legend.backgroundColor || options.grid.backgroundColor || '#ffffff';
 
  _.extend(styles, D.size(div), {
  'backgroundColor': c,
  'zIndex' : '',
  'border' : ''
  });
  styles.width += 'px';
  styles.height += 'px';
 
  // Put in the transparent background separately to avoid blended labels and
  div = D.create('div');
  div.className = 'flotr-legend-bg';
  D.setStyles(div, styles);
  D.opacity(div, opacity);
  D.insert(div, ' ');
  D.insert(this.el, div);
  }
  }
  }
  }
  }
  });
  })();
 
  /** Spreadsheet **/
  (function() {
 
  function getRowLabel(value){
  if (this.options.spreadsheet.tickFormatter){
  //TODO maybe pass the xaxis formatter to the custom tick formatter as an opt-out?
  return this.options.spreadsheet.tickFormatter(value);
  }
  else {
  var t = _.find(this.axes.x.ticks, function(t){return t.v == value;});
  if (t) {
  return t.label;
  }
  return value;
  }
  }
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('spreadsheet', {
  options: {
  show: false, // => show the data grid using two tabs
  tabGraphLabel: 'Graph',
  tabDataLabel: 'Data',
  toolbarDownload: 'Download CSV', // @todo: add better language support
  toolbarSelectAll: 'Select all',
  csvFileSeparator: ',',
  decimalSeparator: '.',
  tickFormatter: null,
  initialTab: 'graph'
  },
  /**
  * Builds the tabs in the DOM
  */
  callbacks: {
  'flotr:afterconstruct': function(){
  // @TODO necessary?
  //this.el.select('.flotr-tabs-group,.flotr-datagrid-container').invoke('remove');
 
  if (!this.options.spreadsheet.show) return;
 
  var ss = this.spreadsheet,
  container = D.node('<div class="flotr-tabs-group" style="position:absolute;left:0px;width:'+this.canvasWidth+'px"></div>'),
  graph = D.node('<div style="float:left" class="flotr-tab selected">'+this.options.spreadsheet.tabGraphLabel+'</div>'),
  data = D.node('<div style="float:left" class="flotr-tab">'+this.options.spreadsheet.tabDataLabel+'</div>'),
  offset;
 
  ss.tabsContainer = container;
  ss.tabs = { graph : graph, data : data };
 
  D.insert(container, graph);
  D.insert(container, data);
  D.insert(this.el, container);
 
  offset = D.size(data).height + 2;
  this.plotOffset.bottom += offset;
 
  D.setStyles(container, {top: this.canvasHeight-offset+'px'});
 
  this.
  observe(graph, 'click', function(){ss.showTab('graph');}).
  observe(data, 'click', function(){ss.showTab('data');});
  if (this.options.spreadsheet.initialTab !== 'graph'){
  ss.showTab(this.options.spreadsheet.initialTab);
  }
  }
  },
  /**
  * Builds a matrix of the data to make the correspondance between the x values and the y values :
  * X value => Y values from the axes
  * @return {Array} The data grid
  */
  loadDataGrid: function(){
  if (this.seriesData) return this.seriesData;
 
  var s = this.series,
  rows = {};
 
  /* The data grid is a 2 dimensions array. There is a row for each X value.
  * Each row contains the x value and the corresponding y value for each serie ('undefined' if there isn't one)
  **/
  _.each(s, function(serie, i){
  _.each(serie.data, function (v) {
  var x = v[0],
  y = v[1],
  r = rows[x];
  if (r) {
  r[i+1] = y;
  } else {
  var newRow = [];
  newRow[0] = x;
  newRow[i+1] = y;
  rows[x] = newRow;
  }
  });
  });
 
  // The data grid is sorted by x value
  this.seriesData = _.sortBy(rows, function(row, x){
  return parseInt(x, 10);
  });
  return this.seriesData;
  },
  /**
  * Constructs the data table for the spreadsheet
  * @todo make a spreadsheet manager (Flotr.Spreadsheet)
  * @return {Element} The resulting table element
  */
  constructDataGrid: function(){
  // If the data grid has already been built, nothing to do here
  if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
 
  var s = this.series,
  datagrid = this.spreadsheet.loadDataGrid(),
  colgroup = ['<colgroup><col />'],
  buttonDownload, buttonSelect, t;
 
  // First row : series' labels
  var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
  html.push('<th>&nbsp;</th>');
  _.each(s, function(serie,i){
  html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>');
  colgroup.push('<col />');
  });
  html.push('</tr>');
  // Data rows
  _.each(datagrid, function(row){
  html.push('<tr>');
  _.times(s.length+1, function(i){
  var tag = 'td',
  value = row[i],
  // TODO: do we really want to handle problems with floating point
  // precision here?
  content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : '');
  if (i === 0) {
  tag = 'th';
  var label = getRowLabel.call(this, content);
  if (label) content = label;
  }
 
  html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>');
  }, this);
  html.push('</tr>');
  }, this);
  colgroup.push('</colgroup>');
  t = D.node(html.join(''));
 
  /**
  * @TODO disabled this
  if (!Flotr.isIE || Flotr.isIE == 9) {
  function handleMouseout(){
  t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
  }
  function handleMouseover(e){
  var td = e.element(),
  siblings = td.previousSiblings();
  t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
  t.select('colgroup col')[siblings.length].addClassName('hover');
  }
  _.each(t.select('td'), function(td) {
  Flotr.EventAdapter.
  observe(td, 'mouseover', handleMouseover).
  observe(td, 'mouseout', handleMouseout);
  });
  }
  */
 
  buttonDownload = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarDownload +
  '</button>');
 
  buttonSelect = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarSelectAll+
  '</button>');
 
  this.
  observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
  observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
 
  var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
  D.insert(toolbar, buttonDownload);
  D.insert(toolbar, buttonSelect);
 
  var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2,
  container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+
  this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>');
 
  D.insert(container, toolbar);
  D.insert(container, t);
  D.insert(this.el, container);
  this.spreadsheet.datagrid = t;
  this.spreadsheet.container = container;
 
  return t;
  },
  /**
  * Shows the specified tab, by its name
  * @todo make a tab manager (Flotr.Tabs)
  * @param {String} tabName - The tab name
  */
  showTab: function(tabName){
  if (this.spreadsheet.activeTab === tabName){
  return;
  }
  switch(tabName) {
  case 'graph':
  D.hide(this.spreadsheet.container);
  D.removeClass(this.spreadsheet.tabs.data, 'selected');
  D.addClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  case 'data':
  if (!this.spreadsheet.datagrid)
  this.spreadsheet.constructDataGrid();
  D.show(this.spreadsheet.container);
  D.addClass(this.spreadsheet.tabs.data, 'selected');
  D.removeClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  default:
  throw 'Illegal tab name: ' + tabName;
  }
  this.spreadsheet.activeTab = tabName;
  },
  /**
  * Selects the data table in the DOM for copy/paste
  */
  selectAllData: function(){
  if (this.spreadsheet.tabs) {
  var selection, range, doc, win, node = this.spreadsheet.constructDataGrid();
 
  this.spreadsheet.showTab('data');
 
  // deferred to be able to select the table
  setTimeout(function () {
  if ((doc = node.ownerDocument) && (win = doc.defaultView) &&
  win.getSelection && doc.createRange &&
  (selection = window.getSelection()) &&
  selection.removeAllRanges) {
  range = doc.createRange();
  range.selectNode(node);
  selection.removeAllRanges();
  selection.addRange(range);
  }
  else if (document.body && document.body.createTextRange &&
  (range = document.body.createTextRange())) {
  range.moveToElementText(node);
  range.select();
  }
  }, 0);
  return true;
  }
  else return false;
  },
  /**
  * Converts the data into CSV in order to download a file
  */
  downloadCSV: function(){
  var csv = '',
  series = this.series,
  options = this.options,
  dg = this.spreadsheet.loadDataGrid(),
  separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
 
  if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
  throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
  }
 
  // The first row
  _.each(series, function(serie, i){
  csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
  });
 
  csv += "%0D%0A"; // \r\n
 
  // For each row
  csv += _.reduce(dg, function(memo, row){
  var rowLabel = getRowLabel.call(this, row[0]) || '';
  rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
  var numbers = row.slice(1).join(separator);
  if (options.spreadsheet.decimalSeparator !== '.') {
  numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
  }
  return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
  }, '', this);
 
  if (Flotr.isIE && Flotr.isIE < 9) {
  csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
  window.open().document.write(csv);
  }
  else window.open('data:text/csv,'+csv);
  }
  });
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('titles', {
  callbacks: {
  'flotr:afterdraw': function() {
  this.titles.drawTitles();
  }
  },
  /**
  * Draws the title and the subtitle
  */
  drawTitles : function () {
  var html,
  options = this.options,
  margin = options.grid.labelMargin,
  ctx = this.ctx,
  a = this.axes;
 
  if (!options.HtmlText && this.textEnabled) {
  var style = {
  size: options.fontSize,
  color: options.grid.color,
  textAlign: 'center'
  };
 
  // Add subtitle
  if (options.subtitle){
  Flotr.drawText(
  ctx, options.subtitle,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight + this.subtitleHeight - 2,
  style
  );
  }
 
  style.weight = 1.5;
  style.size *= 1.5;
 
  // Add title
  if (options.title){
  Flotr.drawText(
  ctx, options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight - 2,
  style
  );
  }
 
  style.weight = 1.8;
  style.size *= 0.8;
 
  // Add x axis title
  if (a.x.options.title && a.x.used){
  style.textAlign = a.x.options.titleAlign || 'center';
  style.textBaseline = 'top';
  style.angle = Flotr.toRad(a.x.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top + a.x.maxLabel.height + this.plotHeight + 2 * margin,
  style
  );
  }
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used){
  style.textAlign = a.x2.options.titleAlign || 'center';
  style.textBaseline = 'bottom';
  style.angle = Flotr.toRad(a.x2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x2.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top - a.x2.maxLabel.height - 2 * margin,
  style
  );
  }
 
  // Add y axis title
  if (a.y.options.title && a.y.used){
  style.textAlign = a.y.options.titleAlign || 'right';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y.options.title,
  this.plotOffset.left - a.y.maxLabel.width - 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used){
  style.textAlign = a.y2.options.titleAlign || 'left';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y2.options.title,
  this.plotOffset.left + this.plotWidth + a.y2.maxLabel.width + 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
  }
  else {
  html = [];
 
  // Add title
  if (options.title)
  html.push(
  '<div style="position:absolute;top:0;left:',
  this.plotOffset.left, 'px;font-size:1em;font-weight:bold;text-align:center;width:',
  this.plotWidth,'px;" class="flotr-title">', options.title, '</div>'
  );
 
  // Add subtitle
  if (options.subtitle)
  html.push(
  '<div style="position:absolute;top:', this.titleHeight, 'px;left:',
  this.plotOffset.left, 'px;font-size:smaller;text-align:center;width:',
  this.plotWidth, 'px;" class="flotr-subtitle">', options.subtitle, '</div>'
  );
 
  html.push('</div>');
 
  html.push('<div class="flotr-axis-title" style="font-weight:bold;">');
 
  // Add x axis title
  if (a.x.options.title && a.x.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight + options.grid.labelMargin + a.x.titleSize.height),
  'px;left:', this.plotOffset.left, 'px;width:', this.plotWidth,
  'px;text-align:', a.x.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x1">', a.x.options.title, '</div>'
  );
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used)
  html.push(
  '<div style="position:absolute;top:0;left:', this.plotOffset.left, 'px;width:',
  this.plotWidth, 'px;text-align:', a.x2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x2">', a.x2.options.title, '</div>'
  );
 
  // Add y axis title
  if (a.y.options.title && a.y.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;left:0;text-align:', a.y.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y1">', a.y.options.title, '</div>'
  );
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;right:0;text-align:', a.y2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y2">', a.y2.options.title, '</div>'
  );
 
  html = html.join('');
 
  var div = D.create('div');
  D.setStyles({
  color: options.grid.color
  });
  div.className = 'flotr-titles';
  D.insert(this.el, div);
  D.insert(div, html);
  }
  }
  });
  })();
 
  return Flotr;
 
  }));
 
  (function(){var a=Flotr.EventAdapter,b=Flotr._,c="click",d="example",e="mouseenter",f="mouseleave",g=".",h="flotr-examples",i="flotr-examples-container",j="flotr-examples-reset",k="flotr-examples-thumbs",l="flotr-examples-thumb",m="flotr-examples-collapsed",n="flotr-examples-highlight",o="flotr-examples-large",p="flotr-examples-medium",q="flotr-examples-small",r="flotr-examples-mobile",s='<div class="'+l+'"></div>',t='<div class="'+h+'">'+'<div class="'+j+'">View All</div>'+'<div class="'+k+'"></div>'+'<div class="'+i+'"></div>'+"</div>";Examples=function(a){if(b.isUndefined(Flotr.ExampleList))throw"Flotr.ExampleList not defined.";this.options=a,this.list=Flotr.ExampleList,this.current=null,this.single=!1,this._initNodes(),this._example=new Flotr.Examples.Example({node:this._exampleNode}),this._initExamples()},Examples.prototype={examples:function(){function f(b){var c=$(b.currentTarget),e=c.data("example"),f=b.data.orientation;f^c.hasClass(n)&&(c.toggleClass(n).css(a),d._example.executeCallback(e,c))}var a={cursor:"pointer"},b=this._thumbsNode,c=this.list.get(),d=this,e=["basic","basic-axis","basic-bars","basic-bars-horizontal","basic-bar-stacked","basic-stacked-horizontal","basic-pie","basic-radar","basic-bubble","basic-candle","basic-legend","mouse-tracking","mouse-zoom","mouse-drag","basic-time","negative-values","click-example","download-image","download-data","advanced-titles","color-gradients","basic-timeline","advanced-markers"];(function h(){var a=e.shift(),f=c[a];if(f.type==="profile"||f.type==="test")return;var g=$(s);g.data("example",f),b.append(g),d._example.executeCallback(f,g),g.click(function(){d._loadExample(f)}),e.length&&setTimeout(h,20)})(),b.delegate(g+l,"mouseenter",{orientation:!0},f),b.delegate(g+l,"mouseleave",{orientation:!1},f),$(window).hashchange&&$(window).hashchange(function(){d._loadHash()})},_loadExample:function(a){if(a){if(this._currentExample!==a)this._currentExample=a;else return;window.location.hash="!"+(this.single?"single/":"")+a.key,u||(this._thumbsNode.css({position:"absolute",height:"0px",overflow:"hidden",width:"0px"}),this._resetNode.css({top:"16px"})),this._examplesNode.addClass(m),this._exampleNode.show(),this._example.setExample(a),this._resize(),$(document).scrollTop(0)}},_reset:function(){window.location.hash="",u||this._thumbsNode.css({position:"",height:"",overflow:"",width:""}),this._examplesNode.removeClass(m),this._thumbsNode.height(""),this._exampleNode.hide()},_initNodes:function(){var a=$(this.options.node),b=this,c=$(t);b._resetNode=c.find(g+j),b._exampleNode=c.find(g+i),b._thumbsNode=c.find(g+k),b._examplesNode=c,b._resetNode.click(function(){b._reset()}),a.append(c),this._initResizer()},_initResizer:function(){function e(){var b=c.height()-(a.options.thumbPadding||0),e=c.width(),f;e>1760?(f=o,a._thumbsNode.height(b)):e>1140?(f=p,a._thumbsNode.height(b)):(f=q,a._thumbsNode.height("")),d!==f&&(d&&a._examplesNode.removeClass(d),a._examplesNode.addClass(f),d=f)}var a=this,b=a._examplesNode,c=$(window),d;$(window).resize(e),e(),this._resize=e},_initExamples:function(){var a=window.location.hash,b,c;a=a.substring(2),c=a.split("/"),c.length==1?(this.examples(),a&&this._loadHash()):c[0]=="single"&&(this.single=!0,b=this.list.get(c[1]))},_loadHash:function(){var a=window.location.hash,b;a=a.substring(2),a?(b=this.list.get(a),this._loadExample(b)):this._reset()}};var u=function(){var a=!!(navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPod/i)),b=!!$.browser.mozilla;return!a||b}();Flotr.Examples=Examples})(),function(){var a=Flotr._,b=".",c="flotr-example",d="flotr-example-label",e="flotr-example-title",f="flotr-example-description",g="flotr-example-editor",h="flotr-example-graph",i='<div class="'+c+'">'+'<div class="'+d+" "+e+'"></div>'+'<div class="'+f+'"></div>'+'<div class="'+g+'"></div>'+"</div>",j=function(a){this.options=a,this.example=null,this._initNodes()};j.prototype={setExample:function(a){var b=this.getSource(a),c=this._editorNode;this.example=a,Math.seedrandom(a.key),this._exampleNode.css({display:"block"}),this._titleNode.html(a.name||""),this._markupNode.html(a.description||""),this._editor?this._editor.setExample(b,a.args):this._editor=new Flotr.Examples.Editor(c,{args:a.args,example:b,teardown:function(){Flotr.EventAdapter.stopObserving($(c).find(".render")[0]),$(c).find("canvas").each(function(a,b){Flotr.EventAdapter.stopObserving(b)})}})},getSource:function(a){var b=a.callback.toString();return navigator.userAgent.search(/firefox/i)!==-1&&(b=js_beautify(b)),b},executeCallback:function(b,c){a.isElement(c)||(c=c[0]);var d=b.args?[c].concat(b.args):[c];return Math.seedrandom(b.key),b.callback.apply(this,d)},_initNodes:function(){var a=this.options.node,c=$(i);this._titleNode=c.find(b+e),this._markupNode=c.find(b+f),this._editorNode=c.find(b+g),this._exampleNode=c,a.append(c)}},Flotr.Examples.Example=j}(),function(){function Editor(a,b){function o(){i.hide(),f&&f.call(),m.render({example:d,render:h})}function p(a,b,c){var d=!1,e='<span class="error">Error: </span>',f,g;e+='<span class="message">'+a+"</span>",typeof c!="undefined"&&(e+='<span class="position">',e+='Line <span class="line">'+c+"</span>",console.log(b),b&&(e+=" of ",b==window.location?(e+='<span class="url">script</span>',!d):e+='<span class="url">'+b+"</span>"),e+=".</span>"),i.show(),i.html(e)}var c=b.type||"javascript",d=b.example||"",e=b.noRun||!1,f=b.teardown||!1,g=$(T_CONTROLS),h=$(T_RENDER),i=$(T_ERRORS),j=$(T_SOURCE),k=$(T_EDITOR),l="editor-render-"+COUNT,m,h,n;m=new TYPES[c]({onerror:p});if(!m)throw"Invalid type: API not found for type `"+c+"`.";h.attr("id",l),i.hide(),k.append(h).append(g).append(j).addClass(c).addClass(e?"no-run":""),a=$(a),a.append(k),j.append(i),d=m.example({args:b.args,example:d,render:h}),n=CodeMirror(j[0],{value:d,readOnly:e,lineNumbers:!0,mode:m.codeMirrorType}),e||(g.delegate(".run","click",function(){d=n.getValue(),o()}),o()),window.onerror=function(a,b,c){return p(a,b,c),console.log(a),ONERROR&&$.isFunction(ONERROR)?ONERROR(a,b,c):!1},COUNT++,this.setExample=function(a,b){d=m.example({args:b,example:a,render:h}),n.setValue(d),n.refresh(),o()}}var ONERROR=window.onerror,COUNT=0,TYPES={},T_CONTROLS='<div class="controls"><button class="run btn large primary">Run</button></div>',T_EDITOR='<div class="editor"></div>',T_SOURCE='<div class="source"></div>',T_ERRORS='<div class="errors"></div>',T_RENDER='<div class="render"></div>',T_IFRAME="<iframe></iframe>";TYPES.javascript=function(b){this.onerror=b.onerror},TYPES.javascript.prototype={codeMirrorType:"javascript",example:function(a){var b=a.example,c=a.render,d=$(c).attr("id"),e=a.args?","+a.args.toString():"";return"("+b+')(document.getElementById("'+d+'")'+e+");"},render:function(o){eval(o.example)}},TYPES.html=function(b){this.onerror=b.onerror},TYPES.html.prototype={codeMirrorType:"htmlmixed",example:function(a){return $.trim(a.example)},render:function(a){var b=a.example,c=a.render,d=$(T_IFRAME),e=this,f,g;c.html(d),f=d[0].contentWindow,g=f.document,g.open(),f.onerror=d.onerror=function(){e.onerror.apply(null,arguments)},g.write(b),g.close()}},typeof Flotr.Examples=="undefined"&&(Flotr.Examples={}),Flotr.Examples.Editor=Editor}(),function(){var a=Flotr.DOM,b=Flotr.EventAdapter,c=Flotr._,d="click",e="example-profile",f="examples",g=function(a){if(c.isUndefined(Flotr.ExampleList))throw"Flotr.ExampleList not defined.";this.editMode="off",this.list=Flotr.ExampleList,this.current=null,this.single=!1,this.init()};g.prototype=c.extend({},Flotr.Examples.prototype,{examples:function(){var e=document.getElementById(f),g=a.node("<ul></ul>"),h;c.each(this.list.getType("profile"),function(e){h=a.node("<li>"+e.name+"</li>"),a.insert(g,h),b.observe(h,d,c.bind(function(){this.example(e)},this))},this),a.insert(e,g)},example:function(a){this._renderSource(a),this.profileStart(a),setTimeout(c.bind(function(){this._renderGraph(a),this.profileEnd()},this),50)},profileStart:function(a){var b=document.getElementById(e);this._startTime=new Date,b.innerHTML='<div>Profile started for "'+a.name+'"...</div>'},profileEnd:function(a){var b=document.getElementById(e);profileTime=new Date-this._startTime,this._startTime=null,b.innerHTML+="<div>Profile complete: "+profileTime+"ms<div>"}}),Flotr.Profile=g}()
  (function () {
 
  var ExampleList = function () {
 
  // Map of examples.
  this.examples = {};
 
  };
 
  ExampleList.prototype = {
 
  add : function (example) {
  this.examples[example.key] = example;
  },
 
  get : function (key) {
  return key ? (this.examples[key] || null) : this.examples;
  },
 
  getType : function (type) {
  return Flotr._.select(this.examples, function (example) {
  return (example.type === type);
  });
  }
  }
 
  Flotr.ExampleList = new ExampleList();
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic',
  name : 'Basic',
  callback : basic
  });
 
  function basic (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
  d2 = [], // Second data series
  i, graph;
 
  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  xaxis: {
  minorTickFreq: 4
  },
  grid: {
  minorVerticalLines: true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-stacked',
  name : 'Basic Stacked',
  callback : basic_stacked,
  type : 'test'
  });
 
  function basic_stacked (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 2], [9, 3]], // First data series
  d2 = [[0, 2], [4, 3], [8, 8], [9, 4]], // Second data series
  i, graph;
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  lines: {
  show : true,
  stacked: true
  },
  xaxis: {
  minorTickFreq: 4
  },
  grid: {
  minorVerticalLines: true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-stepped',
  name : 'Basic Stepped',
  callback : basic_stepped,
  type : 'test'
  });
 
  function basic_stepped (container) {
 
  var
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
  d2 = [], // Second data series
  i, graph;
 
  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  lines: {
  steps : true,
  show : true
  },
  xaxis: {
  minorTickFreq: 4
  },
  yaxis: {
  autoscale: true
  },
  grid: {
  minorVerticalLines: true
  },
  mouse : {
  track : true,
  relative : true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-axis',
  name : 'Basic Axis',
  callback : basic_axis
  });
 
  function basic_axis (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [], // Data
  ticks = [[ 0, "Lower"], 10, 20, 30, [40, "Upper"]], // Ticks for the Y-Axis
  graph;
 
  for(var i = 0; i <= 10; i += 0.1){
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if( i.toFixed(1)%1 == 0 ){
  d5.push([i, 2*i]);
  }
  }
 
  d3[30][1] = null;
  d3[31][1] = null;
 
  function ticksFn (n) { return '('+n+')'; }
 
  graph = Flotr.draw(container, [
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3'},
  { data : d3, label : 'y = 5x + 3sin(4x)'},
  { data : d4, label : 'y = x'},
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ], {
  xaxis : {
  noTicks : 7, // Display 7 ticks.
  tickFormatter : ticksFn, // Displays tick values between brackets.
  min : 1, // Part of the series is not displayed.
  max : 7.5 // Part of the series is not displayed.
  },
  yaxis : {
  ticks : ticks, // Set Y-Axis ticks
  max : 40 // Maximum value along Y-Axis
  },
  grid : {
  verticalLines : false,
  backgroundColor : {
  colors : [[0,'#fff'], [1,'#ccc']],
  start : 'top',
  end : 'bottom'
  }
  },
  legend : {
  position : 'nw'
  },
  title : 'Basic Axis example',
  subtitle : 'This is a subtitle'
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bars',
  name : 'Basic Bars',
  callback : basic_bars
  });
 
  Flotr.ExampleList.add({
  key : 'basic-bars-horizontal',
  name : 'Horizontal Bars',
  args : [true],
  callback : basic_bars,
  tolerance : 5
  });
 
  function basic_bars (container, horizontal) {
 
  var
  horizontal = (horizontal ? true : false), // Show horizontal bars
  d1 = [], // First data series
  d2 = [], // Second data series
  point, // Data point variable declaration
  i;
 
  for (i = 0; i < 4; i++) {
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i];
  } else {
  point = [i, Math.ceil(Math.random()*10)];
  }
 
  d1.push(point);
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i+0.5];
  } else {
  point = [i+0.5, Math.ceil(Math.random()*10)];
  }
 
  d2.push(point);
  };
 
  // Draw the graph
  Flotr.draw(
  container,
  [d1, d2],
  {
  bars : {
  show : true,
  horizontal : horizontal,
  shadowSize : 0,
  barWidth : 0.5
  },
  mouse : {
  track : true,
  relative : true
  },
  yaxis : {
  min : 0,
  autoscaleMargin : 1
  }
  }
  );
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bar-stacked',
  name : 'Stacked Bars',
  callback : bars_stacked
  });
 
  Flotr.ExampleList.add({
  key : 'basic-stacked-horizontal',
  name : 'Stacked Horizontal Bars',
  args : [true],
  callback : bars_stacked,
  tolerance : 5
  });
 
  function bars_stacked (container, horizontal) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  graph, i;
 
  for (i = -10; i < 10; i++) {
  if (horizontal) {
  d1.push([Math.random(), i]);
  d2.push([Math.random(), i]);
  d3.push([Math.random(), i]);
  } else {
  d1.push([i, Math.random()]);
  d2.push([i, Math.random()]);
  d3.push([i, Math.random()]);
  }
  }
 
  graph = Flotr.draw(container,[
  { data : d1, label : 'Serie 1' },
  { data : d2, label : 'Serie 2' },
  { data : d3, label : 'Serie 3' }
  ], {
  legend : {
  backgroundColor : '#D2E8FF' // Light blue
  },
  bars : {
  show : true,
  stacked : true,
  horizontal : horizontal,
  barWidth : 0.6,
  lineWidth : 1,
  shadowSize : 0
  },
  grid : {
  verticalLines : horizontal,
  horizontalLines : !horizontal
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-pie',
  name : 'Basic Pie',
  callback : basic_pie
  });
 
  function basic_pie (container) {
 
  var
  d1 = [[0, 4]],
  d2 = [[0, 3]],
  d3 = [[0, 1.03]],
  d4 = [[0, 3.5]],
  graph;
 
  graph = Flotr.draw(container, [
  { data : d1, label : 'Comedy' },
  { data : d2, label : 'Action' },
  { data : d3, label : 'Romance',
  pie : {
  explode : 50
  }
  },
  { data : d4, label : 'Drama' }
  ], {
  HtmlText : false,
  grid : {
  verticalLines : false,
  horizontalLines : false
  },
  xaxis : { showLabels : false },
  yaxis : { showLabels : false },
  pie : {
  show : true,
  explode : 6
  },
  mouse : { track : true },
  legend : {
  position : 'se',
  backgroundColor : '#D2E8FF'
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-radar',
  name : 'Basic Radar',
  callback : basic_radar
  });
 
  function basic_radar (container) {
 
  // Fill series s1 and s2.
  var
  s1 = { label : 'Actual', data : [[0, 3], [1, 8], [2, 5], [3, 5], [4, 3], [5, 9]] },
  s2 = { label : 'Target', data : [[0, 8], [1, 7], [2, 8], [3, 2], [4, 4], [5, 7]] },
  graph, ticks;
 
  // Radar Labels
  ticks = [
  [0, "Statutory"],
  [1, "External"],
  [2, "Videos"],
  [3, "Yippy"],
  [4, "Management"],
  [5, "oops"]
  ];
 
  // Draw the graph.
  graph = Flotr.draw(container, [ s1, s2 ], {
  radar : { show : true},
  grid : { circular : true, minorHorizontalLines : true},
  yaxis : { min : 0, max : 10, minorTickFreq : 2},
  xaxis : { ticks : ticks}
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-bubble',
  name : 'Basic Bubble',
  callback : basic_bubble
  });
 
  function basic_bubble (container) {
 
  var
  d1 = [],
  d2 = [],
  point, graph, i;
 
  for (i = 0; i < 10; i++ ){
  point = [i, Math.ceil(Math.random()*10), Math.ceil(Math.random()*10)];
  d1.push(point);
 
  point = [i, Math.ceil(Math.random()*10), Math.ceil(Math.random()*10)];
  d2.push(point);
  }
 
  // Draw the graph
  graph = Flotr.draw(container, [d1, d2], {
  bubbles : { show : true, baseRadius : 5 },
  xaxis : { min : -4, max : 14 },
  yaxis : { min : -4, max : 14 }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-candle',
  name : 'Basic Candle',
  callback : basic_candle
  });
 
  function basic_candle (container) {
 
  var
  d1 = [],
  price = 3.206,
  graph,
  i, a, b, c;
 
  for (i = 0; i < 50; i++) {
  a = Math.random();
  b = Math.random();
  c = (Math.random() * (a + b)) - b;
  d1.push([i, price, price + a, price - b, price + c]);
  price = price + c;
  }
 
  // Graph
  graph = Flotr.draw(container, [ d1 ], {
  candles : { show : true, candleWidth : 0.6 },
  xaxis : { noTicks : 10 }
  });
  }
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-legend',
  name : 'Basic Legend',
  callback : basic_legend
  });
 
  function basic_legend (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  data,
  graph, i;
 
  // Data Generation
  for (i = 0; i < 15; i += 0.5) {
  d1.push([i, i + Math.sin(i+Math.PI)]);
  d2.push([i, i]);
  d3.push([i, 15-Math.cos(i)]);
  }
 
  data = [
  { data : d1, label :'x + sin(x+&pi;)' },
  { data : d2, label :'x' },
  { data : d3, label :'15 - cos(x)' }
  ];
 
 
  // This function prepend each label with 'y = '
  function labelFn (label) {
  return 'y = ' + label;
  }
 
  // Draw graph
  graph = Flotr.draw(container, data, {
  legend : {
  position : 'se', // Position the legend 'south-east'.
  labelFormatter : labelFn, // Format the labels.
  backgroundColor : '#D2E8FF' // A light blue background color.
  },
  HtmlText : false
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-tracking',
  name : 'Mouse Tracking',
  callback : mouse_tracking
  });
 
  function mouse_tracking (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  graph, i;
 
  for (i = 0; i < 20; i += 0.5) {
  d1.push([i, 2*i]);
  d2.push([i, i*1.5+1.5*Math.sin(i)]);
  d3.push([i, 3*Math.cos(i)+10]);
  }
 
  graph = Flotr.draw(
  container,
  [
  {
  data : d1,
  mouse : { track : false } // Disable mouse tracking for d1
  },
  d2,
  d3
  ],
  {
  mouse : {
  track : true, // Enable mouse tracking
  lineColor : 'purple',
  relative : true,
  position : 'ne',
  sensibility : 1,
  trackDecimals : 2,
  trackFormatter : function (o) { return 'x = ' + o.x +', y = ' + o.y; }
  },
  crosshair : {
  mode : 'xy'
  }
  }
  );
 
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-zoom',
  name : 'Mouse Zoom',
  callback : mouse_zoom,
  description : "<p>Select an area of the graph to zoom. Click to reset the chart.</p>"
  });
 
  function mouse_zoom (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  options,
  graph,
  i;
 
  for (i = 0; i < 40; i += 0.5) {
  d1.push([i, Math.sin(i)+3*Math.cos(i)]);
  d2.push([i, Math.pow(1.1, i)]);
  d3.push([i, 40 - i+Math.random()*10]);
  }
 
  options = {
  selection : { mode : 'x', fps : 30 },
  title : 'Mouse Zoom'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  var o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1, d2, d3 ],
  o
  );
  }
 
  // Actually draw the graph.
  graph = drawGraph();
 
  // Hook into the 'flotr:select' event.
  Flotr.EventAdapter.observe(container, 'flotr:select', function (area) {
 
  // Draw graph with new area
  graph = drawGraph({
  xaxis: {min:area.x1, max:area.x2},
  yaxis: {min:area.y1, max:area.y2}
  });
  });
 
  // When graph is clicked, draw the graph with default area.
  Flotr.EventAdapter.observe(container, 'flotr:click', function () { drawGraph(); });
  };
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'mouse-drag',
  name : 'Mouse Drag',
  callback : mouse_drag
  });
 
  function mouse_drag (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  options,
  graph,
  start,
  i;
 
  for (i = -40; i < 40; i += 0.5) {
  d1.push([i, Math.sin(i)+3*Math.cos(i)]);
  d2.push([i, Math.pow(1.1, i)]);
  d3.push([i, 40 - i+Math.random()*10]);
  }
 
  options = {
  xaxis: {min: 0, max: 20},
  title : 'Mouse Drag'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  var o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1, d2, d3 ],
  o
  );
  }
 
  graph = drawGraph();
 
  function initializeDrag (e) {
  start = graph.getEventPosition(e);
  Flotr.EventAdapter.observe(document, 'mousemove', move);
  Flotr.EventAdapter.observe(document, 'mouseup', stopDrag);
  }
 
  function move (e) {
  var
  end = graph.getEventPosition(e),
  xaxis = graph.axes.x,
  offset = start.x - end.x;
 
  graph = drawGraph({
  xaxis : {
  min : xaxis.min + offset,
  max : xaxis.max + offset
  }
  });
  // @todo: refector initEvents in order not to remove other observed events
  Flotr.EventAdapter.observe(graph.overlay, 'mousedown', initializeDrag);
  }
 
  function stopDrag () {
  Flotr.EventAdapter.stopObserving(document, 'mousemove', move);
  }
 
  Flotr.EventAdapter.observe(graph.overlay, 'mousedown', initializeDrag);
 
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-time',
  name : 'Basic Time',
  callback : basic_time,
  description : "<p>Select an area of the graph to zoom. Click to reset the chart.</p>"
  });
 
  function basic_time (container) {
 
  var
  d1 = [],
  start = new Date("2009/01/01 01:00").getTime(),
  options,
  graph,
  i, x, o;
 
  for (i = 0; i < 100; i++) {
  x = start+(i*1000*3600*24*36.5);
  d1.push([x, i+Math.random()*30+Math.sin(i/20+Math.random()*2)*20+Math.sin(i/10+Math.random())*10]);
  }
 
  options = {
  xaxis : {
  mode : 'time',
  labelsAngle : 45
  },
  selection : {
  mode : 'x'
  },
  HtmlText : false,
  title : 'Time'
  };
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph (opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  container,
  [ d1 ],
  o
  );
  }
 
  graph = drawGraph();
 
  Flotr.EventAdapter.observe(container, 'flotr:select', function(area){
  // Draw selected area
  graph = drawGraph({
  xaxis : { min : area.x1, max : area.x2, mode : 'time', labelsAngle : 45 },
  yaxis : { min : area.y1, max : area.y2 }
  });
  });
 
  // When graph is clicked, draw the graph with default area.
  Flotr.EventAdapter.observe(container, 'flotr:click', function () { graph = drawGraph(); });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'negative-values',
  name : 'Negative Values',
  callback : negative_values
  });
 
  function negative_values (container) {
 
  var
  d0 = [], // Line through y = 0
  d1 = [], // Random data presented as a scatter plot.
  d2 = [], // A regression line for the scatter.
  sx = 0,
  sy = 0,
  sxy = 0,
  sxsq = 0,
  xmean,
  ymean,
  alpha,
  beta,
  n, x, y;
 
  for (n = 0; n < 20; n++){
 
  x = n;
  y = x + Math.random()*8 - 15;
 
  d0.push([x, 0]);
  d1.push([x, y]);
 
  // Computations used for regression line
  sx += x;
  sy += y;
  sxy += x*y;
  sxsq += Math.pow(x,2);
  }
 
  xmean = sx/n;
  ymean = sy/n;
  beta = ((n*sxy) - (sx*sy))/((n*sxsq)-(Math.pow(sx,2)));
  alpha = ymean - (beta * xmean);
 
  // Compute the regression line.
  for (n = 0; n < 20; n++){
  d2.push([n, alpha + beta*n])
  }
 
  // Draw the graph
  graph = Flotr.draw(
  container, [
  { data : d0, shadowSize : 0, color : '#545454' }, // Horizontal
  { data : d1, label : 'y = x + (Math.random() * 8) - 15', points : { show : true } }, // Scatter
  { data : d2, label : 'y = ' + alpha.toFixed(2) + ' + ' + beta.toFixed(2) + '*x' } // Regression
  ],
  {
  legend : { position : 'se', backgroundColor : '#D2E8FF' },
  title : 'Negative Values'
  }
  );
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'click-example',
  name : 'Click Example',
  callback : click_example
  });
 
  function click_example (container) {
 
  var
  d1 = [[0,0]], // Point at origin
  options,
  graph;
 
  options = {
  xaxis: {min: 0, max: 15},
  yaxis: {min: 0, max: 15},
  lines: {show: true},
  points: {show: true},
  mouse: {track:true},
  title: 'Click Example'
  };
 
  graph = Flotr.draw(container, [d1], options);
 
  // Add a point to the series and redraw the graph
  Flotr.EventAdapter.observe(container, 'flotr:click', function(position){
 
  // Add a point to the series at the location of the click
  d1.push([position.x, position.y]);
 
  // Sort the series.
  d1 = d1.sort(function (a, b) { return a[0] - b[0]; });
 
  // Redraw the graph, with the new series.
  graph = Flotr.draw(container, [d1], options);
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'download-image',
  name : 'Download Image',
  callback : download_image,
  description : '' +
  '<form name="image-download" id="image-download" action="" onsubmit="return false">' +
  '<label><input type="radio" name="format" value="png" checked="checked" /> PNG</label>' +
  '<label><input type="radio" name="format" value="jpeg" /> JPEG</label>' +
 
  '<button name="to-image" onclick="CurrentExample(\'to-image\')">To Image</button>' +
  '<button name="download" onclick="CurrentExample(\'download\')">Download</button>' +
  '<button name="reset" onclick="CurrentExample(\'reset\')">Reset</button>' +
  '</form>'
  });
 
  function download_image (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i;
 
  for (i = 0; i <= 10; i += 0.1) {
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if( i.toFixed(1)%1 == 0 ){
  d5.push([i, 2*i]);
  }
  }
 
  // Draw the graph
  graph = Flotr.draw(
  container,[
  {data:d1, label:'y = 4 + x^(1.5)', lines:{fill:true}},
  {data:d2, label:'y = x^3', yaxis:2},
  {data:d3, label:'y = 5x + 3sin(4x)'},
  {data:d4, label:'y = x'},
  {data:d5, label:'y = 2x', lines: {show: true}, points: {show: true}}
  ],{
  title: 'Download Image Example',
  subtitle: 'You can save me as an image',
  xaxis:{
  noTicks: 7, // Display 7 ticks.
  tickFormatter: function(n){ return '('+n+')'; }, // => displays tick values between brackets.
  min: 1, // => part of the series is not displayed.
  max: 7.5, // => part of the series is not displayed.
  labelsAngle: 45,
  title: 'x Axis'
  },
  yaxis:{
  ticks: [[0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max: 40,
  title: 'y = f(x)'
  },
  y2axis:{color:'#FF0000', max: 500, title: 'y = x^3'},
  grid:{
  verticalLines: false,
  backgroundColor: 'white'
  },
  HtmlText: false,
  legend: {
  position: 'nw'
  }
  });
 
  this.CurrentExample = function (operation) {
 
  var
  format = $('#image-download input:radio[name=format]:checked').val();
  if (Flotr.isIE && Flotr.isIE < 9) {
  alert(
  "Your browser doesn't allow you to get a bitmap image from the plot, " +
  "you can only get a VML image that you can use in Microsoft Office.<br />"
  );
  }
 
  if (operation == 'to-image') {
  graph.download.saveImage(format, null, null, true)
  } else if (operation == 'download') {
  graph.download.saveImage(format);
  } else if (operation == 'reset') {
  graph.download.restoreCanvas();
  }
  };
 
  return graph;
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'download-data',
  name : 'Download Data',
  callback : download_data
  });
 
  function download_data (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i,x;
 
  for (i = 0; i <= 100; i += 1) {
  x = i / 10;
  d1.push([x, 4 + Math.pow(x,1.5)]);
  d2.push([x, Math.pow(x,3)]);
  d3.push([x, i*5+3*Math.sin(x*4)]);
  d4.push([x, x]);
  if(x%1 === 0 ){
  d5.push([x, 2*x]);
  }
  }
 
  // Draw the graph.
  graph = Flotr.draw(
  container, [
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3' },
  { data : d3, label : 'y = 5x + 3sin(4x)' },
  { data : d4, label : 'y = x' },
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ],{
  xaxis : {
  noTicks : 7,
  tickFormatter : function (n) { return '('+n+')'; },
  min: 1, // Part of the series is not displayed.
  max: 7.5
  },
  yaxis : {
  ticks : [[ 0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max : 40
  },
  grid : {
  verticalLines : false,
  backgroundColor : 'white'
  },
  legend : {
  position : 'nw'
  },
  spreadsheet : {
  show : true,
  tickFormatter : function (e) { return e+''; }
  }
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'advanced-titles',
  name : 'Advanced Titles',
  callback : advanced_titles
  });
 
  function advanced_titles (container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [],
  graph,
  i;
 
  for (i = 0; i <= 10; i += 0.1) {
  d1.push([i, 4 + Math.pow(i,1.5)]);
  d2.push([i, Math.pow(i,3)]);
  d3.push([i, i*5+3*Math.sin(i*4)]);
  d4.push([i, i]);
  if (i.toFixed(1)%1 == 0) {
  d5.push([i, 2*i]);
  }
  }
 
  // Draw the graph.
  graph = Flotr.draw(
  container,[
  { data : d1, label : 'y = 4 + x^(1.5)', lines : { fill : true } },
  { data : d2, label : 'y = x^3', yaxis : 2 },
  { data : d3, label : 'y = 5x + 3sin(4x)' },
  { data : d4, label : 'y = x' },
  { data : d5, label : 'y = 2x', lines : { show : true }, points : { show : true } }
  ], {
  title : 'Advanced Titles Example',
  subtitle : 'You can save me as an image',
  xaxis : {
  noTicks : 7,
  tickFormatter : function (n) { return '('+n+')'; },
  min : 1,
  max : 7.5,
  labelsAngle : 45,
  title : 'x Axis'
  },
  yaxis : {
  ticks : [[0, "Lower"], 10, 20, 30, [40, "Upper"]],
  max : 40,
  title : 'y = f(x)'
  },
  y2axis : { color : '#FF0000', max : 500, title : 'y = x^3' },
  grid : {
  verticalLines : false,
  backgroundColor : 'white'
  },
  HtmlText : false,
  legend : {
  position : 'nw'
  }
  });
  };
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'color-gradients',
  name : 'Color Gradients',
  callback : color_gradients
  });
 
  function color_gradients (container) {
 
  var
  bars = {
  data: [],
  bars: {
  show: true,
  barWidth: 0.8,
  lineWidth: 0,
  fillColor: {
  colors: ['#CB4B4B', '#fff'],
  start: 'top',
  end: 'bottom'
  },
  fillOpacity: 0.8
  }
  }, markers = {
  data: [],
  markers: {
  show: true,
  position: 'ct'
  }
  }, lines = {
  data: [],
  lines: {
  show: true,
  fillColor: ['#00A8F0', '#fff'],
  fill: true,
  fillOpacity: 1
  }
  },
  point,
  graph,
  i;
 
  for (i = 0; i < 8; i++) {
  point = [i, Math.ceil(Math.random() * 10)];
  bars.data.push(point);
  markers.data.push(point);
  }
 
  for (i = -1; i < 9; i += 0.01){
  lines.data.push([i, i*i/8+2]);
  }
 
  graph = Flotr.draw(
  container,
  [lines, bars, markers], {
  yaxis: {
  min: 0,
  max: 11
  },
  xaxis: {
  min: -0.5,
  max: 7.5
  },
  grid: {
  verticalLines: false,
  backgroundColor: ['#fff', '#ccc']
  }
  }
  );
  };
 
  })();
 
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'profile-bars',
  name : 'Profile Bars',
  type : 'profile',
  callback : profile_bars
  });
 
  /*
  Flotr.ExampleList.add({
  key : 'basic-bars-horizontal',
  name : 'Horizontal Bars',
  args : [true],
  callback : basic_bars
  });
  */
 
  function profile_bars (container, horizontal) {
 
  var
  horizontal = (horizontal ? true : false), // Show horizontal bars
  d1 = [], // First data series
  d2 = [], // Second data series
  point, // Data point variable declaration
  i;
 
  for (i = 0; i < 5000; i++) {
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i];
  } else {
  point = [i, Math.ceil(Math.random()*10)];
  }
 
  d1.push(point);
 
  if (horizontal) {
  point = [Math.ceil(Math.random()*10), i+0.5];
  } else {
  point = [i+0.5, Math.ceil(Math.random()*10)];
  }
 
  d2.push(point);
  };
 
  // Draw the graph
  Flotr.draw(
  container,
  [d1, d2],
  {
  bars : {
  show : true,
  horizontal : horizontal,
  barWidth : 0.5
  },
  mouse : {
  track : true,
  relative : true
  },
  yaxis : {
  min : 0,
  autoscaleMargin : 1
  }
  }
  );
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'basic-timeline',
  name : 'Basic Timeline',
  callback : basic_timeline
  });
 
  function basic_timeline (container) {
 
  var
  d1 = [[1, 4, 5]],
  d2 = [[3.2, 3, 4]],
  d3 = [[1.9, 2, 2], [5, 2, 3.3]],
  d4 = [[1.55, 1, 9]],
  d5 = [[5, 0, 2.3]],
  data = [],
  timeline = { show : true, barWidth : .5 },
  markers = [],
  labels = ['Obama', 'Bush', 'Clinton', 'Palin', 'McCain'],
  i, graph, point;
 
  // Timeline
  Flotr._.each([d1, d2, d3, d4, d5], function (d) {
  data.push({
  data : d,
  timeline : Flotr._.clone(timeline)
  });
  });
 
  // Markers
  Flotr._.each([d1, d2, d3, d4, d5], function (d) {
  point = d[0];
  markers.push([point[0], point[1]]);
  });
  data.push({
  data: markers,
  markers: {
  show: true,
  position: 'rm',
  fontSize: 11,
  labelFormatter : function (o) { return labels[o.index]; }
  }
  });
 
  // Draw Graph
  graph = Flotr.draw(container, data, {
  xaxis: {
  noTicks: 3,
  tickFormatter: function (x) {
  var
  x = parseInt(x),
  months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return months[(x-1)%12];
  }
  },
  yaxis: {
  showLabels : false
  },
  grid: {
  horizontalLines : false
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key : 'advanced-markers',
  name : 'Advanced Markers',
  callback : advanced_markers,
  timeout : 150
  });
 
  function advanced_markers (container) {
 
  var
  xmark = new Image(),
  checkmark = new Image(),
  bars = {
  data: [],
  bars: {
  show: true,
  barWidth: 0.6,
  lineWidth: 0,
  fillOpacity: 0.8
  }
  }, markers = {
  data: [],
  markers: {
  show: true,
  position: 'ct',
  labelFormatter: function (o) {
  return (o.y >= 5) ? checkmark : xmark;
  }
  }
  },
  flotr = Flotr,
  point,
  graph,
  i;
 
 
  for (i = 0; i < 8; i++) {
  point = [i, Math.ceil(Math.random() * 10)];
  bars.data.push(point);
  markers.data.push(point);
  }
 
  var runner = function () {
  if (!xmark.complete || !checkmark.complete) {
  setTimeout(runner, 50);
  return;
  }
 
  graph = flotr.draw(
  container,
  [bars, markers], {
  yaxis: {
  min: 0,
  max: 11
  },
  xaxis: {
  min: -0.5,
  max: 7.5
  },
  grid: {
  verticalLines: false
  }
  }
  );
  }
 
  xmark.onload = runner;
  xmark.src = 'images/xmark.png';
  checkmark.src = 'images/checkmark.png';
  };
 
  })();
 
 
  // Copyright 2006 Google Inc.
  //
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //
  // http://www.apache.org/licenses/LICENSE-2.0
  //
  // Unless required by applicable law or agreed to in writing, software
  // distributed under the License is distributed on an "AS IS" BASIS,
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  // See the License for the specific language governing permissions and
  // limitations under the License.
  // Known Issues:
  //
  // * Patterns only support repeat.
  // * Radial gradient are not implemented. The VML version of these look very
  // different from the canvas one.
  // * Clipping paths are not implemented.
  // * Coordsize. The width and height attribute have higher priority than the
  // width and height style values which isn't correct.
  // * Painting mode isn't implemented.
  // * Canvas width/height should is using content-box by default. IE in
  // Quirks mode will draw the canvas using border-box. Either change your
  // doctype to HTML5
  // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
  // or use Box Sizing Behavior from WebFX
  // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
  // * Non uniform scaling does not correctly scale strokes.
  // * Optimize. There is always room for speed improvements.
  // Only add this code if we do not already have a canvas implementation
 
  document.createElement("canvas").getContext||function(){function j(){return this.context_||(this.context_=new N(this))}function l(a,b,c){var d=k.call(arguments,2);return function(){return a.apply(b,d.concat(k.call(arguments)))}}function m(a){return String(a).replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function n(a,b,c){a.namespaces[b]||a.namespaces.add(b,c,"#default#VML")}function o(a){n(a,"g_vml_","urn:schemas-microsoft-com:vml"),n(a,"g_o_","urn:schemas-microsoft-com:office:office");if(!a.styleSheets.ex_canvas_){var b=a.createStyleSheet();b.owningElement.id="ex_canvas_",b.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}function q(a){var b=a.srcElement;switch(a.propertyName){case"width":b.getContext().clearRect(),b.style.width=b.attributes.width.nodeValue+"px",b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px");break;case"height":b.getContext().clearRect(),b.style.height=b.attributes.height.nodeValue+"px",b.firstChild&&(b.firstChild.style.height=b.clientHeight+"px")}}function r(a){var b=a.srcElement;b.firstChild&&(b.firstChild.style.width=b.clientWidth+"px",b.firstChild.style.height=b.clientHeight+"px")}function v(){return[[1,0,0],[0,1,0],[0,0,1]]}function w(a,b){var c=v();for(var d=0;d<3;d++)for(var e=0;e<3;e++){var f=0;for(var g=0;g<3;g++)f+=a[d][g]*b[g][e];c[d][e]=f}return c}function x(a,b){b.fillStyle=a.fillStyle,b.lineCap=a.lineCap,b.lineJoin=a.lineJoin,b.lineWidth=a.lineWidth,b.miterLimit=a.miterLimit,b.shadowBlur=a.shadowBlur,b.shadowColor=a.shadowColor,b.shadowOffsetX=a.shadowOffsetX,b.shadowOffsetY=a.shadowOffsetY,b.strokeStyle=a.strokeStyle,b.globalAlpha=a.globalAlpha,b.font=a.font,b.textAlign=a.textAlign,b.textBaseline=a.textBaseline,b.arcScaleX_=a.arcScaleX_,b.arcScaleY_=a.arcScaleY_,b.lineScale_=a.lineScale_}function z(a){var b=a.indexOf("(",3),c=a.indexOf(")",b+1),d=a.substring(b+1,c).split(",");if(d.length!=4||a.charAt(3)!="a")d[3]=1;return d}function A(a){return parseFloat(a)/100}function B(a,b,c){return Math.min(c,Math.max(b,a))}function C(a){var b,c,d,e,f,g;e=parseFloat(a[0])/360%360,e<0&&e++,f=B(A(a[1]),0,1),g=B(A(a[2]),0,1);if(f==0)b=c=d=g;else{var h=g<.5?g*(1+f):g+f-g*f,i=2*g-h;b=D(i,h,e+1/3),c=D(i,h,e),d=D(i,h,e-1/3)}return"#"+s[Math.floor(b*255)]+s[Math.floor(c*255)]+s[Math.floor(d*255)]}function D(a,b,c){return c<0&&c++,c>1&&c--,6*c<1?a+(b-a)*6*c:2*c<1?b:3*c<2?a+(b-a)*(2/3-c)*6:a}function F(a){if(a in E)return E[a];var b,c=1;a=String(a);if(a.charAt(0)=="#")b=a;else if(/^rgb/.test(a)){var d=z(a),b="#",e;for(var f=0;f<3;f++)d[f].indexOf("%")!=-1?e=Math.floor(A(d[f])*255):e=+d[f],b+=s[B(e,0,255)];c=+d[3]}else if(/^hsl/.test(a)){var d=z(a);b=C(d),c=d[3]}else b=y[a]||a;return E[a]={color:b,alpha:c}}function I(a){if(H[a])return H[a];var b=document.createElement("div"),c=b.style;try{c.font=a}catch(d){}return H[a]={style:c.fontStyle||G.style,variant:c.fontVariant||G.variant,weight:c.fontWeight||G.weight,size:c.fontSize||G.size,family:c.fontFamily||G.family}}function J(a,b){var c={};for(var d in a)c[d]=a[d];var e=parseFloat(b.currentStyle.fontSize),f=parseFloat(a.size);return typeof a.size=="number"?c.size=a.size:a.size.indexOf("px")!=-1?c.size=f:a.size.indexOf("em")!=-1?c.size=e*f:a.size.indexOf("%")!=-1?c.size=e/100*f:a.size.indexOf("pt")!=-1?c.size=f/.75:c.size=e,c}function K(a){return a.style+" "+a.variant+" "+a.weight+" "+a.size+"px "+a.family}function M(a){return L[a]||"square"}function N(a){this.m_=v(),this.mStack_=[],this.aStack_=[],this.currentPath_=[],this.strokeStyle="#000",this.fillStyle="#000",this.lineWidth=1,this.lineJoin="miter",this.lineCap="butt",this.miterLimit=g*1,this.globalAlpha=1,this.font="10px sans-serif",this.textAlign="left",this.textBaseline="alphabetic",this.canvas=a;var b="width:"+a.clientWidth+"px;height:"+a.clientHeight+"px;overflow:hidden;position:absolute",c=a.ownerDocument.createElement("div");c.style.cssText=b,a.appendChild(c);var d=c.cloneNode(!1);d.style.backgroundColor="red",d.style.filter="alpha(opacity=0)",a.appendChild(d),this.element_=c,this.arcScaleX_=1,this.arcScaleY_=1,this.lineScale_=1}function P(a,b,c,d){a.currentPath_.push({type:"bezierCurveTo",cp1x:b.x,cp1y:b.y,cp2x:c.x,cp2y:c.y,x:d.x,y:d.y}),a.currentX_=d.x,a.currentY_=d.y}function Q(a,b){var c=F(a.strokeStyle),d=c.color,e=c.alpha*a.globalAlpha,f=a.lineScale_*a.lineWidth;f<1&&(e*=f),b.push("<g_vml_:stroke",' opacity="',e,'"',' joinstyle="',a.lineJoin,'"',' miterlimit="',a.miterLimit,'"',' endcap="',M(a.lineCap),'"',' weight="',f,'px"',' color="',d,'" />')}function R(b,c,d,e){var f=b.fillStyle,h=b.arcScaleX_,i=b.arcScaleY_,j=e.x-d.x,k=e.y-d.y;if(f instanceof V){var l=0,m={x:0,y:0},n=0,o=1;if(f.type_=="gradient"){var p=f.x0_/h,q=f.y0_/i,r=f.x1_/h,s=f.y1_/i,t=S(b,p,q),u=S(b,r,s),v=u.x-t.x,w=u.y-t.y;l=Math.atan2(v,w)*180/Math.PI,l<0&&(l+=360),l<1e-6&&(l=0)}else{var t=S(b,f.x0_,f.y0_);m={x:(t.x-d.x)/j,y:(t.y-d.y)/k},j/=h*g,k/=i*g;var x=a.max(j,k);n=2*f.r0_/x,o=2*f.r1_/x-n}var y=f.colors_;y.sort(function(a,b){return a.offset-b.offset});var z=y.length,A=y[0].color,B=y[z-1].color,C=y[0].alpha*b.globalAlpha,D=y[z-1].alpha*b.globalAlpha,E=[];for(var G=0;G<z;G++){var H=y[G];E.push(H.offset*o+n+" "+H.color)}c.push('<g_vml_:fill type="',f.type_,'"',' method="none" focus="100%"',' color="',A,'"',' color2="',B,'"',' colors="',E.join(","),'"',' opacity="',D,'"',' g_o_:opacity2="',C,'"',' angle="',l,'"',' focusposition="',m.x,",",m.y,'" />')}else if(f instanceof W){if(j&&k){var I=-d.x,J=-d.y;c.push("<g_vml_:fill",' position="',I/j*h*h,",",J/k*i*i,'"',' type="tile"',' src="',f.src_,'" />')}}else{var K=F(b.fillStyle),L=K.color,M=K.alpha*b.globalAlpha;c.push('<g_vml_:fill color="',L,'" opacity="',M,'" />')}}function S(a,b,c){var d=a.m_;return{x:g*(b*d[0][0]+c*d[1][0]+d[2][0])-h,y:g*(b*d[0][1]+c*d[1][1]+d[2][1])-h}}function T(a){return isFinite(a[0][0])&&isFinite(a[0][1])&&isFinite(a[1][0])&&isFinite(a[1][1])&&isFinite(a[2][0])&&isFinite(a[2][1])}function U(a,b,c){if(!T(b))return;a.m_=b;if(c){var d=b[0][0]*b[1][1]-b[0][1]*b[1][0];a.lineScale_=f(e(d))}}function V(a){this.type_=a,this.x0_=0,this.y0_=0,this.r0_=0,this.x1_=0,this.y1_=0,this.r1_=0,this.colors_=[]}function W(a,b){Y(a);switch(b){case"repeat":case null:case"":this.repetition_="repeat";break;case"repeat-x":case"repeat-y":case"no-repeat":this.repetition_=b;break;default:X("SYNTAX_ERR")}this.src_=a.src,this.width_=a.width,this.height_=a.height}function X(a){throw new Z(a)}function Y(a){(!a||a.nodeType!=1||a.tagName!="IMG")&&X("TYPE_MISMATCH_ERR"),a.readyState!="complete"&&X("INVALID_STATE_ERR")}function Z(a){this.code=this[a],this.message=a+": DOM Exception "+this.code}var a=Math,b=a.round,c=a.sin,d=a.cos,e=a.abs,f=a.sqrt,g=10,h=g/2,i=+navigator.userAgent.match(/MSIE ([\d.]+)?/)[1],k=Array.prototype.slice;o(document);var p={init:function(a){var b=a||document;b.createElement("canvas"),b.attachEvent("onreadystatechange",l(this.init_,this,b))},init_:function(a){var b=a.getElementsByTagName("canvas");for(var c=0;c<b.length;c++)this.initElement(b[c])},initElement:function(a){if(!a.getContext){a.getContext=j,o(a.ownerDocument),a.innerHTML="",a.attachEvent("onpropertychange",q),a.attachEvent("onresize",r);var b=a.attributes;b.width&&b.width.specified?a.style.width=b.width.nodeValue+"px":a.width=a.clientWidth,b.height&&b.height.specified?a.style.height=b.height.nodeValue+"px":a.height=a.clientHeight}return a}};p.init();var s=[];for(var t=0;t<16;t++)for(var u=0;u<16;u++)s[t*16+u]=t.toString(16)+u.toString(16);var y={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgreen:"#006400",darkgrey:"#A9A9A9",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",grey:"#808080",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgreen:"#90EE90",lightgrey:"#D3D3D3",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",oldlace:"#FDF5E6",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",whitesmoke:"#F5F5F5",yellowgreen:"#9ACD32"},E={},G={style:"normal",variant:"normal",weight:"normal",size:10,family:"sans-serif"},H={},L={butt:"flat",round:"round"},O=N.prototype;O.clearRect=function(){this.textMeasureEl_&&(this.textMeasureEl_.removeNode(!0),this.textMeasureEl_=null),this.element_.innerHTML=""},O.beginPath=function(){this.currentPath_=[]},O.moveTo=function(a,b){var c=S(this,a,b);this.currentPath_.push({type:"moveTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},O.lineTo=function(a,b){var c=S(this,a,b);this.currentPath_.push({type:"lineTo",x:c.x,y:c.y}),this.currentX_=c.x,this.currentY_=c.y},O.bezierCurveTo=function(a,b,c,d,e,f){var g=S(this,e,f),h=S(this,a,b),i=S(this,c,d);P(this,h,i,g)},O.quadraticCurveTo=function(a,b,c,d){var e=S(this,a,b),f=S(this,c,d),g={x:this.currentX_+2/3*(e.x-this.currentX_),y:this.currentY_+2/3*(e.y-this.currentY_)},h={x:g.x+(f.x-this.currentX_)/3,y:g.y+(f.y-this.currentY_)/3};P(this,g,h,f)},O.arc=function(a,b,f,i,j,k){f*=g;var l=k?"at":"wa",m=a+d(i)*f-h,n=b+c(i)*f-h,o=a+d(j)*f-h,p=b+c(j)*f-h;e(m-o)<1e-7&&!k&&(m+=.125),e(n-p)<1e-7&&k&&(n-=.125);var q=S(this,a,b),r=S(this,m,n),s=S(this,o,p);this.currentPath_.push({type:l,x:q.x,y:q.y,radius:f,xStart:r.x,yStart:r.y,xEnd:s.x,yEnd:s.y})},O.rect=function(a,b,c,d){this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath()},O.strokeRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.stroke(),this.currentPath_=e},O.fillRect=function(a,b,c,d){var e=this.currentPath_;this.beginPath(),this.moveTo(a,b),this.lineTo(a+c,b),this.lineTo(a+c,b+d),this.lineTo(a,b+d),this.closePath(),this.fill(),this.currentPath_=e},O.createLinearGradient=function(a,b,c,d){var e=new V("gradient");return e.x0_=a,e.y0_=b,e.x1_=c,e.y1_=d,e},O.createRadialGradient=function(a,b,c,d,e,f){var g=new V("gradientradial");return g.x0_=a,g.y0_=b,g.r0_=c,g.x1_=d,g.y1_=e,g.r1_=f,g},O.drawImage=function(c,d){var e,f,h,i,j,k,l,m,n=c.runtimeStyle.width,o=c.runtimeStyle.height;c.runtimeStyle.width="auto",c.runtimeStyle.height="auto";var p=c.width,q=c.height;c.runtimeStyle.width=n,c.runtimeStyle.height=o;if(arguments.length==3)e=arguments[1],f=arguments[2],j=k=0,l=h=p,m=i=q;else if(arguments.length==5)e=arguments[1],f=arguments[2],h=arguments[3],i=arguments[4],j=k=0,l=p,m=q;else{if(arguments.length!=9)throw Error("Invalid number of arguments");j=arguments[1],k=arguments[2],l=arguments[3],m=arguments[4],e=arguments[5],f=arguments[6],h=arguments[7],i=arguments[8]}var r=S(this,e,f),s=l/2,t=m/2,u=[],v=10,w=10;u.push(" <g_vml_:group",' coordsize="',g*v,",",g*w,'"',' coordorigin="0,0"',' style="width:',v,"px;height:",w,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]||this.m_[1][1]!=1||this.m_[1][0]){var x=[];x.push("M11=",this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",b(r.x/g),",","Dy=",b(r.y/g),"");var y=r,z=S(this,e+h,f),A=S(this,e,f+i),B=S(this,e+h,f+i);y.x=a.max(y.x,z.x,A.x,B.x),y.y=a.max(y.y,z.y,A.y,B.y),u.push("padding:0 ",b(y.x/g),"px ",b(y.y/g),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",x.join(""),", sizingmethod='clip');")}else u.push("top:",b(r.y/g),"px;left:",b(r.x/g),"px;");u.push(' ">','<g_vml_:image src="',c.src,'"',' style="width:',g*h,"px;"," height:",g*i,'px"',' cropleft="',j/p,'"',' croptop="',k/q,'"',' cropright="',(p-j-l)/p,'"',' cropbottom="',(q-k-m)/q,'"'," />","</g_vml_:group>"),this.element_.insertAdjacentHTML("BeforeEnd",u.join(""))},O.stroke=function(a){var c=[],d=!1,e=10,f=10;c.push("<g_vml_:shape",' filled="',!!a,'"',' style="position:absolute;width:',e,"px;height:",f,'px;"',' coordorigin="0,0"',' coordsize="',g*e,",",g*f,'"',' stroked="',!a,'"',' path="');var h=!1,i={x:null,y:null},j={x:null,y:null};for(var k=0;k<this.currentPath_.length;k++){var l=this.currentPath_[k],m;switch(l.type){case"moveTo":m=l,c.push(" m ",b(l.x),",",b(l.y));break;case"lineTo":c.push(" l ",b(l.x),",",b(l.y));break;case"close":c.push(" x "),l=null;break;case"bezierCurveTo":c.push(" c ",b(l.cp1x),",",b(l.cp1y),",",b(l.cp2x),",",b(l.cp2y),",",b(l.x),",",b(l.y));break;case"at":case"wa":c.push(" ",l.type," ",b(l.x-this.arcScaleX_*l.radius),",",b(l.y-this.arcScaleY_*l.radius)," ",b(l.x+this.arcScaleX_*l.radius),",",b(l.y+this.arcScaleY_*l.radius)," ",b(l.xStart),",",b(l.yStart)," ",b(l.xEnd),",",b(l.yEnd))}if(l){if(i.x==null||l.x<i.x)i.x=l.x;if(j.x==null||l.x>j.x)j.x=l.x;if(i.y==null||l.y<i.y)i.y=l.y;if(j.y==null||l.y>j.y)j.y=l.y}}c.push(' ">'),a?R(this,c,i,j):Q(this,c),c.push("</g_vml_:shape>"),this.element_.insertAdjacentHTML("beforeEnd",c.join(""))},O.fill=function(){this.stroke(!0)},O.closePath=function(){this.currentPath_.push({type:"close"})},O.save=function(){var a={};x(this,a),this.aStack_.push(a),this.mStack_.push(this.m_),this.m_=w(v(),this.m_)},O.restore=function(){this.aStack_.length&&(x(this.aStack_.pop(),this),this.m_=this.mStack_.pop())},O.translate=function(a,b){var c=[[1,0,0],[0,1,0],[a,b,1]];U(this,w(c,this.m_),!1)},O.rotate=function(a){var b=d(a),e=c(a),f=[[b,e,0],[-e,b,0],[0,0,1]];U(this,w(f,this.m_),!1)},O.scale=function(a,b){this.arcScaleX_*=a,this.arcScaleY_*=b;var c=[[a,0,0],[0,b,0],[0,0,1]];U(this,w(c,this.m_),!0)},O.transform=function(a,b,c,d,e,f){var g=[[a,b,0],[c,d,0],[e,f,1]];U(this,w(g,this.m_),!0)},O.setTransform=function(a,b,c,d,e,f){var g=[[a,b,0],[c,d,0],[e,f,1]];U(this,g,!0)},O.drawText_=function(a,c,d,e,f){var h=this.m_,i=1e3,j=0,k=i,l={x:0,y:0},n=[],o=J(I(this.font),this.element_),p=K(o),q=this.element_.currentStyle,r=this.textAlign.toLowerCase();switch(r){case"left":case"center":case"right":break;case"end":r=q.direction=="ltr"?"right":"left";break;case"start":r=q.direction=="rtl"?"right":"left";break;default:r="left"}switch(this.textBaseline){case"hanging":case"top":l.y=o.size/1.75;break;case"middle":break;default:case null:case"alphabetic":case"ideographic":case"bottom":l.y=-o.size/2.25}switch(r){case"right":j=i,k=.05;break;case"center":j=k=i/2}var s=S(this,c+l.x,d+l.y);n.push('<g_vml_:line from="',-j,' 0" to="',k,' 0.05" ',' coordsize="100 100" coordorigin="0 0"',' filled="',!f,'" stroked="',!!f,'" style="position:absolute;width:1px;height:1px;">'),f?Q(this,n):R(this,n,{x:-j,y:0},{x:k,y:o.size});var t=h[0][0].toFixed(3)+","+h[1][0].toFixed(3)+","+h[0][1].toFixed(3)+","+h[1][1].toFixed(3)+",0,0",u=b(s.x/g)+","+b(s.y/g);n.push('<g_vml_:skew on="t" matrix="',t,'" ',' offset="',u,'" origin="',j,' 0" />','<g_vml_:path textpathok="true" />','<g_vml_:textpath on="true" string="',m(a),'" style="v-text-align:',r,";font:",m(p),'" /></g_vml_:line>'),this.element_.insertAdjacentHTML("beforeEnd",n.join(""))},O.fillText=function(a,b,c,d){this.drawText_(a,b,c,d,!1)},O.strokeText=function(a,b,c,d){this.drawText_(a,b,c,d,!0)},O.measureText=function(a){if(!this.textMeasureEl_){var b='<span style="position:absolute;top:-20000px;left:0;padding:0;margin:0;border:none;white-space:pre;"></span>';this.element_.insertAdjacentHTML("beforeEnd",b),this.textMeasureEl_=this.element_.lastChild}var c=this.element_.ownerDocument;return this.textMeasureEl_.innerHTML="",this.textMeasureEl_.style.font=this.font,this.textMeasureEl_.appendChild(c.createTextNode(a)),{width:this.textMeasureEl_.offsetWidth}},O.clip=function(){},O.arcTo=function(){},O.createPattern=function(a,b){return new W(a,b)},V.prototype.addColorStop=function(a,b){b=F(b),this.colors_.push({offset:a,color:b.color,alpha:b.alpha})};var $=Z.prototype=new Error;$.INDEX_SIZE_ERR=1,$.DOMSTRING_SIZE_ERR=2,$.HIERARCHY_REQUEST_ERR=3,$.WRONG_DOCUMENT_ERR=4,$.INVALID_CHARACTER_ERR=5,$.NO_DATA_ALLOWED_ERR=6,$.NO_MODIFICATION_ALLOWED_ERR=7,$.NOT_FOUND_ERR=8,$.NOT_SUPPORTED_ERR=9,$.INUSE_ATTRIBUTE_ERR=10,$.INVALID_STATE_ERR=11,$.SYNTAX_ERR=12,$.INVALID_MODIFICATION_ERR=13,$.NAMESPACE_ERR=14,$.INVALID_ACCESS_ERR=15,$.VALIDATION_ERR=16,$.TYPE_MISMATCH_ERR=17,G_vmlCanvasManager=p,CanvasRenderingContext2D=N,CanvasGradient=V,CanvasPattern=W,DOMException=Z}(),function(){function c(b){var c,d,e,f,g,h;e=b.length,d=0,c="";while(d<e){f=b.charCodeAt(d++)&255;if(d==e){c+=a.charAt(f>>2),c+=a.charAt((f&3)<<4),c+="==";break}g=b.charCodeAt(d++);if(d==e){c+=a.charAt(f>>2),c+=a.charAt((f&3)<<4|(g&240)>>4),c+=a.charAt((g&15)<<2),c+="=";break}h=b.charCodeAt(d++),c+=a.charAt(f>>2),c+=a.charAt((f&3)<<4|(g&240)>>4),c+=a.charAt((g&15)<<2|(h&192)>>6),c+=a.charAt(h&63)}return c}function d(a){var c,d,e,f,g,h,i;h=a.length,g=0,i="";while(g<h){do c=b[a.charCodeAt(g++)&255];while(g<h&&c==-1);if(c==-1)break;do d=b[a.charCodeAt(g++)&255];while(g<h&&d==-1);if(d==-1)break;i+=String.fromCharCode(c<<2|(d&48)>>4);do{e=a.charCodeAt(g++)&255;if(e==61)return i;e=b[e]}while(g<h&&e==-1);if(e==-1)break;i+=String.fromCharCode((d&15)<<4|(e&60)>>2);do{f=a.charCodeAt(g++)&255;if(f==61)return i;f=b[f]}while(g<h&&f==-1);if(f==-1)break;i+=String.fromCharCode((e&3)<<6|f)}return i}var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1];window.btoa||(window.btoa=c),window.atob||(window.atob=d)}();var CanvasText={letters:{"\n":{width:-1,points:[]}," ":{width:10,points:[]},"!":{width:10,points:[[5,21],[5,7],null,[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],null,[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],null,[17,25],[10,-7],null,[4,12],[18,12],null,[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],null,[12,25],[12,-4],null,[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],null,[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],null,[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],null,[3,18],[13,12],null,[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],null,[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],null,[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],null,[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],null,[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],null,[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],null,[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],null,[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],null,[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],null,[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],null,[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],null,[9,21],[17,0],null,[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],null,[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],null,[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],null,[4,21],[17,21],null,[4,11],[12,11],null,[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],null,[4,21],[17,21],null,[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],null,[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],null,[18,21],[18,0],null,[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],null,[18,21],[4,7],null,[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],null,[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],null,[4,21],[12,0],null,[20,21],[12,0],null,[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],null,[4,21],[18,0],null,[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],null,[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],null,[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],null,[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],null,[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],null,[12,21],[7,0],null,[12,21],[17,0],null,[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],null,[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],null,[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],null,[3,21],[17,21],null,[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],null,[5,25],[5,-7],null,[4,25],[11,25],null,[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],null,[10,25],[10,-7],null,[3,25],[10,25],null,[3,-7],[10,-7]]},"^":{width:14,points:[[3,10],[8,18],[13,10]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],null,[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],null,[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],null,[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],null,[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],null,[14,14],[4,4],null,[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],null,[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],null,[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],null,[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],null,[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],null,[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],null,[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],null,[11,14],[7,0],null,[11,14],[15,0],null,[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],null,[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],null,[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],null,[3,14],[14,14],null,[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],null,[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],null,[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],null,[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],null,[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],null,[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]},"�":{diacritic:"`",letter:"a"},"�":{diacritic:"�",letter:"a"},"�":{diacritic:"^",letter:"a"},"�":{diacritic:"�",letter:"a"},"�":{diacritic:"~",letter:"a"},"�":{diacritic:"`",letter:"e"},"�":{diacritic:"�",letter:"e"},"�":{diacritic:"^",letter:"e"},"�":{diacritic:"�",letter:"e"},"�":{diacritic:"`",letter:"i"},"�":{diacritic:"�",letter:"i"},"�":{diacritic:"^",letter:"i"},"�":{diacritic:"�",letter:"i"},"�":{diacritic:"`",letter:"o"},"�":{diacritic:"�",letter:"o"},"�":{diacritic:"^",letter:"o"},"�":{diacritic:"�",letter:"o"},"�":{diacritic:"~",letter:"o"},"�":{diacritic:"`",letter:"u"},"�":{diacritic:"�",letter:"u"},"�":{diacritic:"^",letter:"u"},"�":{diacritic:"�",letter:"u"},"�":{diacritic:"�",letter:"y"},"�":{diacritic:"�",letter:"y"},"�":{diacritic:"�",letter:"c"},"�":{diacritic:"~",letter:"n"},"�":{diacritic:"`",letter:"A"},"�":{diacritic:"�",letter:"A"},"�":{diacritic:"^",letter:"A"},"�":{diacritic:"�",letter:"A"},"�":{diacritic:"~",letter:"A"},"�":{diacritic:"`",letter:"E"},"�":{diacritic:"�",letter:"E"},"�":{diacritic:"^",letter:"E"},"�":{diacritic:"�",letter:"E"},"�":{diacritic:"`",letter:"I"},"�":{diacritic:"�",letter:"I"},"�":{diacritic:"^",letter:"I"},"�":{diacritic:"�",letter:"I"},"�":{diacritic:"`",letter:"O"},"�":{diacritic:"�",letter:"O"},"�":{diacritic:"^",letter:"O"},"�":{diacritic:"�",letter:"O"},"�":{diacritic:"~",letter:"O"},"�":{diacritic:"`",letter:"U"},"�":{diacritic:"�",letter:"U"},"�":{diacritic:"^",letter:"U"},"�":{diacritic:"�",letter:"U"},"�":{diacritic:"�",letter:"Y"},"�":{diacritic:"�",letter:"C"},"�":{diacritic:"~",letter:"N"}},specialchars:{pi:{width:19,points:[[6,14],[6,0],null,[14,14],[14,0],null,[2,13],[6,16],[13,13],[17,16]]}},diacritics:{"�":{entity:"cedil",points:[[6,-4],[4,-6],[2,-7],[1,-7]]},"�":{entity:"acute",points:[[8,19],[13,22]]},"`":{entity:"grave",points:[[7,22],[12,19]]},"^":{entity:"circ",points:[[5.5,19],[9.5,23],[12.5,19]]},"�":{entity:"trema",points:[[5,21],[6,20],[7,21],[6,22],[5,21],null,[12,21],[13,20],[14,21],[13,22],[12,21]]},"~":{entity:"tilde",points:[[4,18],[7,22],[10,18],[13,22]]}},style:{size:8,font:null,color:"#000000",weight:1,textAlign:"left",textBaseline:"bottom",adjustAlign:!1,angle:0,tracking:1,boundingBoxColor:"#ff0000",originPointColor:"#000000"},debug:!1,_bufferLexemes:{},extend:function(a,b){for(var c in b){if(c in a)continue;a[c]=b[c]}return a},letter:function(a){return CanvasText.letters[a]},parseLexemes:function(a){if(CanvasText._bufferLexemes[a])return CanvasText._bufferLexemes[a];var b,c,d=a.match(/&[A-Za-z]{2,5};|\s|./g),e=[],f=[];for(b=0;b<d.length;b++){c=d[b];if(c.length==1)f.push(c);else{var g=c.substring(1,c.length-1);CanvasText.specialchars[g]?f.push(g):f=f.concat(c.toArray())}}for(b=0;b<f.length;b++)c=f[b],(c=CanvasText.letters[c]||CanvasText.specialchars[c])&&e.push(c);for(b=0;b<e.length;b++)(e===null||typeof e=="undefined")&&delete e[b];return CanvasText._bufferLexemes[a]=e},ascent:function(a){return a=a||CanvasText.style,a.size||CanvasText.style.size},descent:function(a){return a=a||CanvasText.style,7*(a.size||CanvasText.style.size)/25},measure:function(a,b){if(!a)return;b=b||CanvasText.style;var d,e,f=CanvasText.parseLexemes(a),g=0;for(d=f.length-1;d>-1;--d)c=f[d],e=c.diacritic?CanvasText.letter(c.letter).width:c.width,g+=e*(b.tracking||CanvasText.style.tracking)*(b.size||CanvasText.style.size)/25;return g},getDimensions:function(a,b){b=b||CanvasText.style;var c=CanvasText.measure(a,b),d=b.size||CanvasText.style.size,e=b.angle||CanvasText.style.angle;return b.angle==0?{width:c,height:d}:{width:Math.abs(Math.cos(e)*c)+Math.abs(Math.sin(e)*d),height:Math.abs(Math.sin(e)*c)+Math.abs(Math.cos(e)*d)}},drawPoints:function(a,b,c,d,e,f){var g,h,i=!0,j=0;f=f||{x:0,y:0},a.beginPath();for(g=0;g<b.length;g++){h=b[g];if(!h){i=!0;continue}i?(a.moveTo(c+h[0]*e+f.x,d-h[1]*e+f.y),i=!1):a.lineTo(c+h[0]*e+f.x,d-h[1]*e+f.y)}a.stroke(),a.closePath()},draw:function(a,b,c,d){if(!a)return;CanvasText.extend(d,CanvasText.style);var e,f,g=0,h=d.size/25,i=0,j=0,k=CanvasText.parseLexemes(a),l={x:0,y:0},m=CanvasText.measure(a,d),n;d.adjustAlign&&(n=CanvasText.getBestAlign(d.angle,d),CanvasText.extend(d,n));switch(d.textAlign){case"left":break;case"center":l.x=-m/2;break;case"right":l.x=-m}switch(d.textBaseline){case"bottom":break;case"middle":l.y=d.size/2;break;case"top":l.y=d.size}this.save(),this.translate(b,c),this.rotate(d.angle),this.lineCap="round",this.lineWidth=2*h*(d.weight||CanvasText.style.weight),this.strokeStyle=d.color||CanvasText.style.color;for(e=0;e<k.length;e++){f=k[e];if(f.width==-1){i=0,j=d.size*1.4;continue}var o=f.points,p=f.width;if(f.diacritic){var q=CanvasText.diacritics[f.diacritic],r=CanvasText.letter(f.letter);CanvasText.drawPoints(this,q.points,i,j-(f.letter.toUpperCase()==f.letter?3:0),h,l),o=r.points,p=r.width}CanvasText.drawPoints(this,o,i,j,h,l),CanvasText.debug&&(this.save(),this.lineJoin="miter",this.lineWidth=.5,this.strokeStyle=d.boundingBoxColor||CanvasText.style.boundingBoxColor,this.strokeRect(i+l.x,j+l.y,p*h,-d.size),this.fillStyle=d.originPointColor||CanvasText.style.originPointColor,this.beginPath(),this.arc(0,0,1.5,0,Math.PI*2,!0),this.fill(),this.closePath(),this.restore()),i+=p*h*(d.tracking||CanvasText.style.tracking)}return this.restore(),g}};CanvasText.proto=window.CanvasRenderingContext2D?window.CanvasRenderingContext2D.prototype:document.createElement("canvas").getContext("2d").__proto__,CanvasText.proto&&(CanvasText.proto.drawText=CanvasText.draw,CanvasText.proto.measure=CanvasText.measure,CanvasText.proto.getTextBounds=CanvasText.getDimensions,CanvasText.proto.fontAscent=CanvasText.ascent,CanvasText.proto.fontDescent=CanvasText.descent)
  /*!
  * bean.js - copyright Jacob Thornton 2011
  * https://github.com/fat/bean
  * MIT License
  * special thanks to:
  * dean edwards: http://dean.edwards.name/
  * dperini: https://github.com/dperini/nwevents
  * the entire mootools team: github.com/mootools/mootools-core
  */
  /*global module:true, define:true*/
  !function (name, context, definition) {
  if (typeof module !== 'undefined') module.exports = definition(name, context);
  else if (typeof define === 'function' && typeof define.amd === 'object') define(definition);
  else context[name] = definition(name, context);
  }('bean', this, function (name, context) {
  var win = window
  , old = context[name]
  , overOut = /over|out/
  , namespaceRegex = /[^\.]*(?=\..*)\.|.*/
  , nameRegex = /\..*/
  , addEvent = 'addEventListener'
  , attachEvent = 'attachEvent'
  , removeEvent = 'removeEventListener'
  , detachEvent = 'detachEvent'
  , doc = document || {}
  , root = doc.documentElement || {}
  , W3C_MODEL = root[addEvent]
  , eventSupport = W3C_MODEL ? addEvent : attachEvent
  , slice = Array.prototype.slice
  , mouseTypeRegex = /click|mouse|menu|drag|drop/i
  , touchTypeRegex = /^touch|^gesture/i
  , ONE = { one: 1 } // singleton for quick matching making add() do one()
 
  , nativeEvents = (function (hash, events, i) {
  for (i = 0; i < events.length; i++)
  hash[events[i]] = 1
  return hash
  })({}, (
  'click dblclick mouseup mousedown contextmenu ' + // mouse buttons
  'mousewheel DOMMouseScroll ' + // mouse wheel
  'mouseover mouseout mousemove selectstart selectend ' + // mouse movement
  'keydown keypress keyup ' + // keyboard
  'orientationchange ' + // mobile
  'focus blur change reset select submit ' + // form elements
  'load unload beforeunload resize move DOMContentLoaded readystatechange ' + // window
  'error abort scroll ' + // misc
  (W3C_MODEL ? // element.fireEvent('onXYZ'... is not forgiving if we try to fire an event
  // that doesn't actually exist, so make sure we only do these on newer browsers
  'show ' + // mouse buttons
  'input invalid ' + // form elements
  'touchstart touchmove touchend touchcancel ' + // touch
  'gesturestart gesturechange gestureend ' + // gesture
  'message readystatechange pageshow pagehide popstate ' + // window
  'hashchange offline online ' + // window
  'afterprint beforeprint ' + // printing
  'dragstart dragenter dragover dragleave drag drop dragend ' + // dnd
  'loadstart progress suspend emptied stalled loadmetadata ' + // media
  'loadeddata canplay canplaythrough playing waiting seeking ' + // media
  'seeked ended durationchange timeupdate play pause ratechange ' + // media
  'volumechange cuechange ' + // media
  'checking noupdate downloading cached updateready obsolete ' + // appcache
  '' : '')
  ).split(' ')
  )
 
  , customEvents = (function () {
  function isDescendant(parent, node) {
  while ((node = node.parentNode) !== null) {
  if (node === parent) return true
  }
  return false
  }
 
  function check(event) {
  var related = event.relatedTarget
  if (!related) return related === null
  return (related !== this && related.prefix !== 'xul' && !/document/.test(this.toString()) && !isDescendant(this, related))
  }
 
  return {
  mouseenter: { base: 'mouseover', condition: check }
  , mouseleave: { base: 'mouseout', condition: check }
  , mousewheel: { base: /Firefox/.test(navigator.userAgent) ? 'DOMMouseScroll' : 'mousewheel' }
  }
  })()
 
  , fixEvent = (function () {
  var commonProps = 'altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which'.split(' ')
  , mouseProps = commonProps.concat('button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement'.split(' '))
  , keyProps = commonProps.concat('char charCode key keyCode'.split(' '))
  , touchProps = commonProps.concat('touches targetTouches changedTouches scale rotation'.split(' '))
  , preventDefault = 'preventDefault'
  , createPreventDefault = function (event) {
  return function () {
  if (event[preventDefault])
  event[preventDefault]()
  else
  event.returnValue = false
  }
  }
  , stopPropagation = 'stopPropagation'
  , createStopPropagation = function (event) {
  return function () {
  if (event[stopPropagation])
  event[stopPropagation]()
  else
  event.cancelBubble = true
  }
  }
  , createStop = function (synEvent) {
  return function () {
  synEvent[preventDefault]()
  synEvent[stopPropagation]()
  synEvent.stopped = true
  }
  }
  , copyProps = function (event, result, props) {
  var i, p
  for (i = props.length; i--;) {
  p = props[i]
  if (!(p in result) && p in event) result[p] = event[p]
  }
  }
 
  return function (event, isNative) {
  var result = { originalEvent: event, isNative: isNative }
  if (!event)
  return result
 
  var props
  , type = event.type
  , target = event.target || event.srcElement
 
  result[preventDefault] = createPreventDefault(event)
  result[stopPropagation] = createStopPropagation(event)
  result.stop = createStop(result)
  result.target = target && target.nodeType === 3 ? target.parentNode : target
 
  if (isNative) { // we only need basic augmentation on custom events, the rest is too expensive
  if (type.indexOf('key') !== -1) {
  props = keyProps
  result.keyCode = event.which || event.keyCode
  } else if (mouseTypeRegex.test(type)) {
  props = mouseProps
  result.rightClick = event.which === 3 || event.button === 2
  result.pos = { x: 0, y: 0 }
  if (event.pageX || event.pageY) {
  result.clientX = event.pageX
  result.clientY = event.pageY
  } else if (event.clientX || event.clientY) {
  result.clientX = event.clientX + doc.body.scrollLeft + root.scrollLeft
  result.clientY = event.clientY + doc.body.scrollTop + root.scrollTop
  }
  if (overOut.test(type))
  result.relatedTarget = event.relatedTarget || event[(type === 'mouseover' ? 'from' : 'to') + 'Element']
  } else if (touchTypeRegex.test(type)) {
  props = touchProps
  }
  copyProps(event, result, props || commonProps)
  }
  return result
  }
  })()
 
  // if we're in old IE we can't do onpropertychange on doc or win so we use doc.documentElement for both
  , targetElement = function (element, isNative) {
  return !W3C_MODEL && !isNative && (element === doc || element === win) ? root : element
  }
 
  // we use one of these per listener, of any type
  , RegEntry = (function () {
  function entry(element, type, handler, original, namespaces) {
  this.element = element
  this.type = type
  this.handler = handler
  this.original = original
  this.namespaces = namespaces
  this.custom = customEvents[type]
  this.isNative = nativeEvents[type] && element[eventSupport]
  this.eventType = W3C_MODEL || this.isNative ? type : 'propertychange'
  this.customType = !W3C_MODEL && !this.isNative && type
  this.target = targetElement(element, this.isNative)
  this.eventSupport = this.target[eventSupport]
  }
 
  entry.prototype = {
  // given a list of namespaces, is our entry in any of them?
  inNamespaces: function (checkNamespaces) {
  var i, j
  if (!checkNamespaces)
  return true
  if (!this.namespaces)
  return false
  for (i = checkNamespaces.length; i--;) {
  for (j = this.namespaces.length; j--;) {
  if (checkNamespaces[i] === this.namespaces[j])
  return true
  }
  }
  return false
  }
 
  // match by element, original fn (opt), handler fn (opt)
  , matches: function (checkElement, checkOriginal, checkHandler) {
  return this.element === checkElement &&
  (!checkOriginal || this.original === checkOriginal) &&
  (!checkHandler || this.handler === checkHandler)
  }
  }
 
  return entry
  })()
 
  , registry = (function () {
  // our map stores arrays by event type, just because it's better than storing
  // everything in a single array. uses '$' as a prefix for the keys for safety
  var map = {}
 
  // generic functional search of our registry for matching listeners,
  // `fn` returns false to break out of the loop
  , forAll = function (element, type, original, handler, fn) {
  if (!type || type === '*') {
  // search the whole registry
  for (var t in map) {
  if (t.charAt(0) === '$')
  forAll(element, t.substr(1), original, handler, fn)
  }
  } else {
  var i = 0, l, list = map['$' + type], all = element === '*'
  if (!list)
  return
  for (l = list.length; i < l; i++) {
  if (all || list[i].matches(element, original, handler))
  if (!fn(list[i], list, i, type))
  return
  }
  }
  }
 
  , has = function (element, type, original) {
  // we're not using forAll here simply because it's a bit slower and this
  // needs to be fast
  var i, list = map['$' + type]
  if (list) {
  for (i = list.length; i--;) {
  if (list[i].matches(element, original, null))
  return true
  }
  }
  return false
  }
 
  , get = function (element, type, original) {
  var entries = []
  forAll(element, type, original, null, function (entry) { return entries.push(entry) })
  return entries
  }
 
  , put = function (entry) {
  (map['$' + entry.type] || (map['$' + entry.type] = [])).push(entry)
  return entry
  }
 
  , del = function (entry) {
  forAll(entry.element, entry.type, null, entry.handler, function (entry, list, i) {
  list.splice(i, 1)
  if (list.length === 0)
  delete map['$' + entry.type]
  return false
  })
  }
 
  // dump all entries, used for onunload
  , entries = function () {
  var t, entries = []
  for (t in map) {
  if (t.charAt(0) === '$')
  entries = entries.concat(map[t])
  }
  return entries
  }
 
  return { has: has, get: get, put: put, del: del, entries: entries }
  })()
 
  // add and remove listeners to DOM elements
  , listener = W3C_MODEL ? function (element, type, fn, add) {
  element[add ? addEvent : removeEvent](type, fn, false)
  } : function (element, type, fn, add, custom) {
  if (custom && add && element['_on' + custom] === null)
  element['_on' + custom] = 0
  element[add ? attachEvent : detachEvent]('on' + type, fn)
  }
 
  , nativeHandler = function (element, fn, args) {
  return function (event) {
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, true)
  return fn.apply(element, [event].concat(args))
  }
  }
 
  , customHandler = function (element, fn, type, condition, args, isNative) {
  return function (event) {
  if (condition ? condition.apply(this, arguments) : W3C_MODEL ? true : event && event.propertyName === '_on' + type || !event) {
  if (event)
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, isNative)
  fn.apply(element, event && (!args || args.length === 0) ? arguments : slice.call(arguments, event ? 0 : 1).concat(args))
  }
  }
  }
 
  , once = function (rm, element, type, fn, originalFn) {
  // wrap the handler in a handler that does a remove as well
  return function () {
  rm(element, type, originalFn)
  fn.apply(this, arguments)
  }
  }
 
  , removeListener = function (element, orgType, handler, namespaces) {
  var i, l, entry
  , type = (orgType && orgType.replace(nameRegex, ''))
  , handlers = registry.get(element, type, handler)
 
  for (i = 0, l = handlers.length; i < l; i++) {
  if (handlers[i].inNamespaces(namespaces)) {
  if ((entry = handlers[i]).eventSupport)
  listener(entry.target, entry.eventType, entry.handler, false, entry.type)
  // TODO: this is problematic, we have a registry.get() and registry.del() that
  // both do registry searches so we waste cycles doing this. Needs to be rolled into
  // a single registry.forAll(fn) that removes while finding, but the catch is that
  // we'll be splicing the arrays that we're iterating over. Needs extra tests to
  // make sure we don't screw it up. @rvagg
  registry.del(entry)
  }
  }
  }
 
  , addListener = function (element, orgType, fn, originalFn, args) {
  var entry
  , type = orgType.replace(nameRegex, '')
  , namespaces = orgType.replace(namespaceRegex, '').split('.')
 
  if (registry.has(element, type, fn))
  return element // no dupe
  if (type === 'unload')
  fn = once(removeListener, element, type, fn, originalFn) // self clean-up
  if (customEvents[type]) {
  if (customEvents[type].condition)
  fn = customHandler(element, fn, type, customEvents[type].condition, true)
  type = customEvents[type].base || type
  }
  entry = registry.put(new RegEntry(element, type, fn, originalFn, namespaces[0] && namespaces))
  entry.handler = entry.isNative ?
  nativeHandler(element, entry.handler, args) :
  customHandler(element, entry.handler, type, false, args, false)
  if (entry.eventSupport)
  listener(entry.target, entry.eventType, entry.handler, true, entry.customType)
  }
 
  , del = function (selector, fn, $) {
  return function (e) {
  var target, i, array = typeof selector === 'string' ? $(selector, this) : selector
  for (target = e.target; target && target !== this; target = target.parentNode) {
  for (i = array.length; i--;) {
  if (array[i] === target) {
  return fn.apply(target, arguments)
  }
  }
  }
  }
  }
 
  , remove = function (element, typeSpec, fn) {
  var k, m, type, namespaces, i
  , rm = removeListener
  , isString = typeSpec && typeof typeSpec === 'string'
 
  if (isString && typeSpec.indexOf(' ') > 0) {
  // remove(el, 't1 t2 t3', fn) or remove(el, 't1 t2 t3')
  typeSpec = typeSpec.split(' ')
  for (i = typeSpec.length; i--;)
  remove(element, typeSpec[i], fn)
  return element
  }
  type = isString && typeSpec.replace(nameRegex, '')
  if (type && customEvents[type])
  type = customEvents[type].type
  if (!typeSpec || isString) {
  // remove(el) or remove(el, t1.ns) or remove(el, .ns) or remove(el, .ns1.ns2.ns3)
  if (namespaces = isString && typeSpec.replace(namespaceRegex, ''))
  namespaces = namespaces.split('.')
  rm(element, type, fn, namespaces)
  } else if (typeof typeSpec === 'function') {
  // remove(el, fn)
  rm(element, null, typeSpec)
  } else {
  // remove(el, { t1: fn1, t2, fn2 })
  for (k in typeSpec) {
  if (typeSpec.hasOwnProperty(k))
  remove(element, k, typeSpec[k])
  }
  }
  return element
  }
 
  , add = function (element, events, fn, delfn, $) {
  var type, types, i, args
  , originalFn = fn
  , isDel = fn && typeof fn === 'string'
 
  if (events && !fn && typeof events === 'object') {
  for (type in events) {
  if (events.hasOwnProperty(type))
  add.apply(this, [ element, type, events[type] ])
  }
  } else {
  args = arguments.length > 3 ? slice.call(arguments, 3) : []
  types = (isDel ? fn : events).split(' ')
  isDel && (fn = del(events, (originalFn = delfn), $)) && (args = slice.call(args, 1))
  // special case for one()
  this === ONE && (fn = once(remove, element, events, fn, originalFn))
  for (i = types.length; i--;) addListener(element, types[i], fn, originalFn, args)
  }
  return element
  }
 
  , one = function () {
  return add.apply(ONE, arguments)
  }
 
  , fireListener = W3C_MODEL ? function (isNative, type, element) {
  var evt = doc.createEvent(isNative ? 'HTMLEvents' : 'UIEvents')
  evt[isNative ? 'initEvent' : 'initUIEvent'](type, true, true, win, 1)
  element.dispatchEvent(evt)
  } : function (isNative, type, element) {
  element = targetElement(element, isNative)
  // if not-native then we're using onpropertychange so we just increment a custom property
  isNative ? element.fireEvent('on' + type, doc.createEventObject()) : element['_on' + type]++
  }
 
  , fire = function (element, type, args) {
  var i, j, l, names, handlers
  , types = type.split(' ')
 
  for (i = types.length; i--;) {
  type = types[i].replace(nameRegex, '')
  if (names = types[i].replace(namespaceRegex, ''))
  names = names.split('.')
  if (!names && !args && element[eventSupport]) {
  fireListener(nativeEvents[type], type, element)
  } else {
  // non-native event, either because of a namespace, arguments or a non DOM element
  // iterate over all listeners and manually 'fire'
  handlers = registry.get(element, type)
  args = [false].concat(args)
  for (j = 0, l = handlers.length; j < l; j++) {
  if (handlers[j].inNamespaces(names))
  handlers[j].handler.apply(element, args)
  }
  }
  }
  return element
  }
 
  , clone = function (element, from, type) {
  var i = 0
  , handlers = registry.get(from, type)
  , l = handlers.length
 
  for (;i < l; i++)
  handlers[i].original && add(element, handlers[i].type, handlers[i].original)
  return element
  }
 
  , bean = {
  add: add
  , one: one
  , remove: remove
  , clone: clone
  , fire: fire
  , noConflict: function () {
  context[name] = old
  return this
  }
  }
 
  if (win[attachEvent]) {
  // for IE, clean up on unload to avoid leaks
  var cleanup = function () {
  var i, entries = registry.entries()
  for (i in entries) {
  if (entries[i].type && entries[i].type !== 'unload')
  remove(entries[i].element, entries[i].type)
  }
  win[detachEvent]('onunload', cleanup)
  win.CollectGarbage && win.CollectGarbage()
  }
  win[attachEvent]('onunload', cleanup)
  }
 
  return bean
  });
  // Underscore.js 1.1.7
  // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
  // Underscore is freely distributable under the MIT license.
  // Portions of Underscore are inspired or borrowed from Prototype,
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
  // For all details and documentation:
  // http://documentcloud.github.com/underscore
 
  (function() {
 
  // Baseline setup
  // --------------
 
  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;
 
  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;
 
  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};
 
  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
 
  // Create quick reference variables for speed access to core prototypes.
  var slice = ArrayProto.slice,
  unshift = ArrayProto.unshift,
  toString = ObjProto.toString,
  hasOwnProperty = ObjProto.hasOwnProperty;
 
  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
  nativeForEach = ArrayProto.forEach,
  nativeMap = ArrayProto.map,
  nativeReduce = ArrayProto.reduce,
  nativeReduceRight = ArrayProto.reduceRight,
  nativeFilter = ArrayProto.filter,
  nativeEvery = ArrayProto.every,
  nativeSome = ArrayProto.some,
  nativeIndexOf = ArrayProto.indexOf,
  nativeLastIndexOf = ArrayProto.lastIndexOf,
  nativeIsArray = Array.isArray,
  nativeKeys = Object.keys,
  nativeBind = FuncProto.bind;
 
  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) { return new wrapper(obj); };
 
  // Export the Underscore object for **CommonJS**, with backwards-compatibility
  // for the old `require()` API. If we're not in CommonJS, add `_` to the
  // global object.
  if (typeof module !== 'undefined' && module.exports) {
  module.exports = _;
  _._ = _;
  } else {
  // Exported as a string, for Closure Compiler "advanced" mode.
  root['_'] = _;
  }
 
  // Current version.
  _.VERSION = '1.1.7';
 
  // Collection Functions
  // --------------------
 
  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
  if (obj == null) return;
  if (nativeForEach && obj.forEach === nativeForEach) {
  obj.forEach(iterator, context);
  } else if (obj.length === +obj.length) {
  for (var i = 0, l = obj.length; i < l; i++) {
  if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
  }
  } else {
  for (var key in obj) {
  if (hasOwnProperty.call(obj, key)) {
  if (iterator.call(context, obj[key], key, obj) === breaker) return;
  }
  }
  }
  };
 
  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  each(obj, function(value, index, list) {
  results[results.length] = iterator.call(context, value, index, list);
  });
  return results;
  };
 
  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  var initial = memo !== void 0;
  if (obj == null) obj = [];
  if (nativeReduce && obj.reduce === nativeReduce) {
  if (context) iterator = _.bind(iterator, context);
  return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  }
  each(obj, function(value, index, list) {
  if (!initial) {
  memo = value;
  initial = true;
  } else {
  memo = iterator.call(context, memo, value, index, list);
  }
  });
  if (!initial) throw new TypeError("Reduce of empty array with no initial value");
  return memo;
  };
 
  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  if (obj == null) obj = [];
  if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  if (context) iterator = _.bind(iterator, context);
  return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  }
  var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
  return _.reduce(reversed, iterator, memo, context);
  };
 
  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
  var result;
  any(obj, function(value, index, list) {
  if (iterator.call(context, value, index, list)) {
  result = value;
  return true;
  }
  });
  return result;
  };
 
  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  each(obj, function(value, index, list) {
  if (iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  each(obj, function(value, index, list) {
  if (!iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
  var result = true;
  if (obj == null) return result;
  if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  each(obj, function(value, index, list) {
  if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  });
  return result;
  };
 
  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
  iterator = iterator || _.identity;
  var result = false;
  if (obj == null) return result;
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  each(obj, function(value, index, list) {
  if (result |= iterator.call(context, value, index, list)) return breaker;
  });
  return !!result;
  };
 
  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function(obj, target) {
  var found = false;
  if (obj == null) return found;
  if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  any(obj, function(value) {
  if (found = value === target) return true;
  });
  return found;
  };
 
  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
  var args = slice.call(arguments, 2);
  return _.map(obj, function(value) {
  return (method.call ? method || value : value[method]).apply(value, args);
  });
  };
 
  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
  return _.map(obj, function(value){ return value[key]; });
  };
 
  // Return the maximum element or (element-based computation).
  _.max = function(obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  var result = {computed : -Infinity};
  each(obj, function(value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed >= result.computed && (result = {value : value, computed : computed});
  });
  return result.value;
  };
 
  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  var result = {computed : Infinity};
  each(obj, function(value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed < result.computed && (result = {value : value, computed : computed});
  });
  return result.value;
  };
 
  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, iterator, context) {
  return _.pluck(_.map(obj, function(value, index, list) {
  return {
  value : value,
  criteria : iterator.call(context, value, index, list)
  };
  }).sort(function(left, right) {
  var a = left.criteria, b = right.criteria;
  return a < b ? -1 : a > b ? 1 : 0;
  }), 'value');
  };
 
  // Groups the object's values by a criterion produced by an iterator
  _.groupBy = function(obj, iterator) {
  var result = {};
  each(obj, function(value, index) {
  var key = iterator(value, index);
  (result[key] || (result[key] = [])).push(value);
  });
  return result;
  };
 
  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator) {
  iterator || (iterator = _.identity);
  var low = 0, high = array.length;
  while (low < high) {
  var mid = (low + high) >> 1;
  iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  }
  return low;
  };
 
  // Safely convert anything iterable into a real, live array.
  _.toArray = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  if (_.isArray(iterable)) return slice.call(iterable);
  if (_.isArguments(iterable)) return slice.call(iterable);
  return _.values(iterable);
  };
 
  // Return the number of elements in an object.
  _.size = function(obj) {
  return _.toArray(obj).length;
  };
 
  // Array Functions
  // ---------------
 
  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head`. The **guard** check allows it to work
  // with `_.map`.
  _.first = _.head = function(array, n, guard) {
  return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };
 
  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function(array, index, guard) {
  return slice.call(array, (index == null) || guard ? 1 : index);
  };
 
  // Get the last element of an array.
  _.last = function(array) {
  return array[array.length - 1];
  };
 
  // Trim out all falsy values from an array.
  _.compact = function(array) {
  return _.filter(array, function(value){ return !!value; });
  };
 
  // Return a completely flattened version of an array.
  _.flatten = function(array) {
  return _.reduce(array, function(memo, value) {
  if (_.isArray(value)) return memo.concat(_.flatten(value));
  memo[memo.length] = value;
  return memo;
  }, []);
  };
 
  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
  return _.difference(array, slice.call(arguments, 1));
  };
 
  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted) {
  return _.reduce(array, function(memo, el, i) {
  if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
  return memo;
  }, []);
  };
 
  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
  return _.uniq(_.flatten(arguments));
  };
 
  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function(array) {
  var rest = slice.call(arguments, 1);
  return _.filter(_.uniq(array), function(item) {
  return _.every(rest, function(other) {
  return _.indexOf(other, item) >= 0;
  });
  });
  };
 
  // Take the difference between one array and another.
  // Only the elements present in just the first array will remain.
  _.difference = function(array, other) {
  return _.filter(array, function(value){ return !_.include(other, value); });
  };
 
  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
  var args = slice.call(arguments);
  var length = _.max(_.pluck(args, 'length'));
  var results = new Array(length);
  for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  return results;
  };
 
  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
  if (array == null) return -1;
  var i, l;
  if (isSorted) {
  i = _.sortedIndex(array, item);
  return array[i] === item ? i : -1;
  }
  if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
  for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
  return -1;
  };
 
 
  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item) {
  if (array == null) return -1;
  if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
  var i = array.length;
  while (i--) if (array[i] === item) return i;
  return -1;
  };
 
  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
  if (arguments.length <= 1) {
  stop = start || 0;
  start = 0;
  }
  step = arguments[2] || 1;
 
  var len = Math.max(Math.ceil((stop - start) / step), 0);
  var idx = 0;
  var range = new Array(len);
 
  while(idx < len) {
  range[idx++] = start;
  start += step;
  }
 
  return range;
  };
 
  // Function (ahem) Functions
  // ------------------
 
  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function(func, obj) {
  if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  var args = slice.call(arguments, 2);
  return function() {
  return func.apply(obj, args.concat(slice.call(arguments)));
  };
  };
 
  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
  var funcs = slice.call(arguments, 1);
  if (funcs.length == 0) funcs = _.functions(obj);
  each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  return obj;
  };
 
  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
  var memo = {};
  hasher || (hasher = _.identity);
  return function() {
  var key = hasher.apply(this, arguments);
  return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  };
  };
 
  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
  var args = slice.call(arguments, 2);
  return setTimeout(function(){ return func.apply(func, args); }, wait);
  };
 
  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
  return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };
 
  // Internal function used to implement `_.throttle` and `_.debounce`.
  var limit = function(func, wait, debounce) {
  var timeout;
  return function() {
  var context = this, args = arguments;
  var throttler = function() {
  timeout = null;
  func.apply(context, args);
  };
  if (debounce) clearTimeout(timeout);
  if (debounce || !timeout) timeout = setTimeout(throttler, wait);
  };
  };
 
  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
  return limit(func, wait, false);
  };
 
  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds.
  _.debounce = function(func, wait) {
  return limit(func, wait, true);
  };
 
  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
  var ran = false, memo;
  return function() {
  if (ran) return memo;
  ran = true;
  return memo = func.apply(this, arguments);
  };
  };
 
  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
  return function() {
  var args = [func].concat(slice.call(arguments));
  return wrapper.apply(this, args);
  };
  };
 
  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
  var funcs = slice.call(arguments);
  return function() {
  var args = slice.call(arguments);
  for (var i = funcs.length - 1; i >= 0; i--) {
  args = [funcs[i].apply(this, args)];
  }
  return args[0];
  };
  };
 
  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
  return function() {
  if (--times < 1) { return func.apply(this, arguments); }
  };
  };
 
 
  // Object Functions
  // ----------------
 
  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
  if (obj !== Object(obj)) throw new TypeError('Invalid object');
  var keys = [];
  for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
  return keys;
  };
 
  // Retrieve the values of an object's properties.
  _.values = function(obj) {
  return _.map(obj, _.identity);
  };
 
  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
  var names = [];
  for (var key in obj) {
  if (_.isFunction(obj[key])) names.push(key);
  }
  return names.sort();
  };
 
  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
  each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
  if (source[prop] !== void 0) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Fill in a given object with default properties.
  _.defaults = function(obj) {
  each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
  if (obj[prop] == null) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };
 
  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
  interceptor(obj);
  return obj;
  };
 
  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
  // Check object identity.
  if (a === b) return true;
  // Different types?
  var atype = typeof(a), btype = typeof(b);
  if (atype != btype) return false;
  // Basic equality test (watch out for coercions).
  if (a == b) return true;
  // One is falsy and the other truthy.
  if ((!a && b) || (a && !b)) return false;
  // Unwrap any wrapped objects.
  if (a._chain) a = a._wrapped;
  if (b._chain) b = b._wrapped;
  // One of them implements an isEqual()?
  if (a.isEqual) return a.isEqual(b);
  if (b.isEqual) return b.isEqual(a);
  // Check dates' integer values.
  if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
  // Both are NaN?
  if (_.isNaN(a) && _.isNaN(b)) return false;
  // Compare regular expressions.
  if (_.isRegExp(a) && _.isRegExp(b))
  return a.source === b.source &&
  a.global === b.global &&
  a.ignoreCase === b.ignoreCase &&
  a.multiline === b.multiline;
  // If a is not an object by this point, we can't handle it.
  if (atype !== 'object') return false;
  // Check for different array lengths before comparing contents.
  if (a.length && (a.length !== b.length)) return false;
  // Nothing else worked, deep compare the contents.
  var aKeys = _.keys(a), bKeys = _.keys(b);
  // Different object sizes?
  if (aKeys.length != bKeys.length) return false;
  // Recursive comparison of contents.
  for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
  return true;
  };
 
  // Is a given array or object empty?
  _.isEmpty = function(obj) {
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
  return true;
  };
 
  // Is a given value a DOM element?
  _.isElement = function(obj) {
  return !!(obj && obj.nodeType == 1);
  };
 
  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
  return toString.call(obj) === '[object Array]';
  };
 
  // Is a given variable an object?
  _.isObject = function(obj) {
  return obj === Object(obj);
  };
 
  // Is a given variable an arguments object?
  _.isArguments = function(obj) {
  return !!(obj && hasOwnProperty.call(obj, 'callee'));
  };
 
  // Is a given value a function?
  _.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
  };
 
  // Is a given value a string?
  _.isString = function(obj) {
  return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
  };
 
  // Is a given value a number?
  _.isNumber = function(obj) {
  return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
  };
 
  // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
  // that does not equal itself.
  _.isNaN = function(obj) {
  return obj !== obj;
  };
 
  // Is a given value a boolean?
  _.isBoolean = function(obj) {
  return obj === true || obj === false;
  };
 
  // Is a given value a date?
  _.isDate = function(obj) {
  return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
  };
 
  // Is the given value a regular expression?
  _.isRegExp = function(obj) {
  return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };
 
  // Is a given value equal to null?
  _.isNull = function(obj) {
  return obj === null;
  };
 
  // Is a given variable undefined?
  _.isUndefined = function(obj) {
  return obj === void 0;
  };
 
  // Utility Functions
  // -----------------
 
  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
  root._ = previousUnderscore;
  return this;
  };
 
  // Keep the identity function around for default iterators.
  _.identity = function(value) {
  return value;
  };
 
  // Run a function **n** times.
  _.times = function (n, iterator, context) {
  for (var i = 0; i < n; i++) iterator.call(context, i);
  };
 
  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function(obj) {
  each(_.functions(obj), function(name){
  addToWrapper(name, _[name] = obj[name]);
  });
  };
 
  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
  var id = idCounter++;
  return prefix ? prefix + id : id;
  };
 
  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
  evaluate : /<%([\s\S]+?)%>/g,
  interpolate : /<%=([\s\S]+?)%>/g
  };
 
  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(str, data) {
  var c = _.templateSettings;
  var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
  'with(obj||{}){__p.push(\'' +
  str.replace(/\\/g, '\\\\')
  .replace(/'/g, "\\'")
  .replace(c.interpolate, function(match, code) {
  return "'," + code.replace(/\\'/g, "'") + ",'";
  })
  .replace(c.evaluate || null, function(match, code) {
  return "');" + code.replace(/\\'/g, "'")
  .replace(/[\r\n\t]/g, ' ') + "__p.push('";
  })
  .replace(/\r/g, '\\r')
  .replace(/\n/g, '\\n')
  .replace(/\t/g, '\\t')
  + "');}return __p.join('');";
  var func = new Function('obj', tmpl);
  return data ? func(data) : func;
  };
 
  // The OOP Wrapper
  // ---------------
 
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function(obj) { this._wrapped = obj; };
 
  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;
 
  // Helper function to continue chaining intermediate results.
  var result = function(obj, chain) {
  return chain ? _(obj).chain() : obj;
  };
 
  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function(name, func) {
  wrapper.prototype[name] = function() {
  var args = slice.call(arguments);
  unshift.call(args, this._wrapped);
  return result(func.apply(_, args), this._chain);
  };
  };
 
  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);
 
  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function() {
  method.apply(this._wrapped, arguments);
  return result(this._wrapped, this._chain);
  };
  });
 
  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function() {
  return result(method.apply(this._wrapped, arguments), this._chain);
  };
  });
 
  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function() {
  this._chain = true;
  return this;
  };
 
  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function() {
  return this._wrapped;
  };
 
  })();
  /**
  * Flotr2 (c) 2012 Carl Sutherland
  * MIT License
  * Special thanks to:
  * Flotr: http://code.google.com/p/flotr/ (fork)
  * Flot: https://github.com/flot/flot (original fork)
  */
  (function () {
 
  var
  global = this,
  previousFlotr = this.Flotr,
  Flotr;
 
  Flotr = {
  _: _,
  bean: bean,
  isIphone: /iphone/i.test(navigator.userAgent),
  isIE: (navigator.appVersion.indexOf("MSIE") != -1 ? parseFloat(navigator.appVersion.split("MSIE")[1]) : false),
 
  /**
  * An object of the registered graph types. Use Flotr.addType(type, object)
  * to add your own type.
  */
  graphTypes: {},
 
  /**
  * The list of the registered plugins
  */
  plugins: {},
 
  /**
  * Can be used to add your own chart type.
  * @param {String} name - Type of chart, like 'pies', 'bars' etc.
  * @param {String} graphType - The object containing the basic drawing functions (draw, etc)
  */
  addType: function(name, graphType){
  Flotr.graphTypes[name] = graphType;
  Flotr.defaultOptions[name] = graphType.options || {};
  Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
  },
 
  /**
  * Can be used to add a plugin
  * @param {String} name - The name of the plugin
  * @param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
  */
  addPlugin: function(name, plugin){
  Flotr.plugins[name] = plugin;
  Flotr.defaultOptions[name] = plugin.options || {};
  },
 
  /**
  * Draws the graph. This function is here for backwards compatibility with Flotr version 0.1.0alpha.
  * You could also draw graphs by directly calling Flotr.Graph(element, data, options).
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  * @param {Class} _GraphKlass_ - (optional) Class to pass the arguments to, defaults to Flotr.Graph
  * @return {Object} returns a new graph object and of course draws the graph.
  */
  draw: function(el, data, options, GraphKlass){
  GraphKlass = GraphKlass || Flotr.Graph;
  return new GraphKlass(el, data, options);
  },
 
  /**
  * Recursively merges two objects.
  * @param {Object} src - source object (likely the object with the least properties)
  * @param {Object} dest - destination object (optional, object with the most properties)
  * @return {Object} recursively merged Object
  * @TODO See if we can't remove this.
  */
  merge: function(src, dest){
  var i, v, result = dest || {};
 
  for (i in src) {
  v = src[i];
  if (v && typeof(v) === 'object') {
  if (v.constructor === Array) {
  result[i] = this._.clone(v);
  } else if (
  v.constructor !== RegExp &&
  !this._.isElement(v) &&
  !v.jquery
  ) {
  result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
  } else {
  result[i] = v;
  }
  } else {
  result[i] = v;
  }
  }
 
  return result;
  },
 
  /**
  * Recursively clones an object.
  * @param {Object} object - The object to clone
  * @return {Object} the clone
  * @TODO See if we can't remove this.
  */
  clone: function(object){
  return Flotr.merge(object, {});
  },
 
  /**
  * Function calculates the ticksize and returns it.
  * @param {Integer} noTicks - number of ticks
  * @param {Integer} min - lower bound integer value for the current axis
  * @param {Integer} max - upper bound integer value for the current axis
  * @param {Integer} decimals - number of decimals for the ticks
  * @return {Integer} returns the ticksize in pixels
  */
  getTickSize: function(noTicks, min, max, decimals){
  var delta = (max - min) / noTicks,
  magn = Flotr.getMagnitude(delta),
  tickSize = 10,
  norm = delta / magn; // Norm is between 1.0 and 10.0.
 
  if(norm < 1.5) tickSize = 1;
  else if(norm < 2.25) tickSize = 2;
  else if(norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
  else if(norm < 7.5) tickSize = 5;
 
  return tickSize * magn;
  },
 
  /**
  * Default tick formatter.
  * @param {String, Integer} val - tick value integer
  * @param {Object} axisOpts - the axis' options
  * @return {String} formatted tick string
  */
  defaultTickFormatter: function(val, axisOpts){
  return val+'';
  },
 
  /**
  * Formats the mouse tracker values.
  * @param {Object} obj - Track value Object {x:..,y:..}
  * @return {String} Formatted track string
  */
  defaultTrackFormatter: function(obj){
  return '('+obj.x+', '+obj.y+')';
  },
 
  /**
  * Utility function to convert file size values in bytes to kB, MB, ...
  * @param value {Number} - The value to convert
  * @param precision {Number} - The number of digits after the comma (default: 2)
  * @param base {Number} - The base (default: 1000)
  */
  engineeringNotation: function(value, precision, base){
  var sizes = ['Y','Z','E','P','T','G','M','k',''],
  fractionSizes = ['y','z','a','f','p','n','µ','m',''],
  total = sizes.length;
 
  base = base || 1000;
  precision = Math.pow(10, precision || 2);
 
  if (value === 0) return 0;
 
  if (value > 1) {
  while (total-- && (value >= base)) value /= base;
  }
  else {
  sizes = fractionSizes;
  total = sizes.length;
  while (total-- && (value < 1)) value *= base;
  }
 
  return (Math.round(value * precision) / precision) + sizes[total];
  },
 
  /**
  * Returns the magnitude of the input value.
  * @param {Integer, Float} x - integer or float value
  * @return {Integer, Float} returns the magnitude of the input value
  */
  getMagnitude: function(x){
  return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
  },
  toPixel: function(val){
  return Math.floor(val)+0.5;//((val-Math.round(val) < 0.4) ? (Math.floor(val)-0.5) : val);
  },
  toRad: function(angle){
  return -angle * (Math.PI/180);
  },
  floorInBase: function(n, base) {
  return base * Math.floor(n / base);
  },
  drawText: function(ctx, text, x, y, style) {
  if (!ctx.fillText) {
  ctx.drawText(text, x, y, style);
  return;
  }
 
  style = this._.extend({
  size: Flotr.defaultOptions.fontSize,
  color: '#000000',
  textAlign: 'left',
  textBaseline: 'bottom',
  weight: 1,
  angle: 0
  }, style);
 
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(style.angle);
  ctx.fillStyle = style.color;
  ctx.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  ctx.textAlign = style.textAlign;
  ctx.textBaseline = style.textBaseline;
  ctx.fillText(text, 0, 0);
  ctx.restore();
  },
  getBestTextAlign: function(angle, style) {
  style = style || {textAlign: 'center', textBaseline: 'middle'};
  angle += Flotr.getTextAngleFromAlign(style);
 
  if (Math.abs(Math.cos(angle)) > 10e-3)
  style.textAlign = (Math.cos(angle) > 0 ? 'right' : 'left');
 
  if (Math.abs(Math.sin(angle)) > 10e-3)
  style.textBaseline = (Math.sin(angle) > 0 ? 'top' : 'bottom');
 
  return style;
  },
  alignTable: {
  'right middle' : 0,
  'right top' : Math.PI/4,
  'center top' : Math.PI/2,
  'left top' : 3*(Math.PI/4),
  'left middle' : Math.PI,
  'left bottom' : -3*(Math.PI/4),
  'center bottom': -Math.PI/2,
  'right bottom' : -Math.PI/4,
  'center middle': 0
  },
  getTextAngleFromAlign: function(style) {
  return Flotr.alignTable[style.textAlign+' '+style.textBaseline] || 0;
  },
  noConflict : function () {
  global.Flotr = previousFlotr;
  return this;
  }
  };
 
  global.Flotr = Flotr;
 
  })();
 
  /**
  * Flotr Defaults
  */
  Flotr.defaultOptions = {
  colors: ['#00A8F0', '#C0D800', '#CB4B4B', '#4DA74D', '#9440ED'], //=> The default colorscheme. When there are > 5 series, additional colors are generated.
  ieBackgroundColor: '#FFFFFF', // Background color for excanvas clipping
  title: null, // => The graph's title
  subtitle: null, // => The graph's subtitle
  shadowSize: 4, // => size of the 'fake' shadow
  defaultType: null, // => default series type
  HtmlText: true, // => wether to draw the text using HTML or on the canvas
  fontColor: '#545454', // => default font color
  fontSize: 7.5, // => canvas' text font size
  resolution: 1, // => resolution of the graph, to have printer-friendly graphs !
  parseFloat: true, // => whether to preprocess data for floats (ie. if input is string)
  preventDefault: true, // => preventDefault by default for mobile events. Turn off to enable scroll.
  xaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 0, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => color of the ticks
  mode: 'normal', // => can be 'time' or 'normal'
  timeFormat: null,
  timeMode:'UTC', // => For UTC time ('local' for local time).
  timeUnit:'millisecond',// => Unit for time (millisecond, second, minute, hour, day, month, year)
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  x2axis: {},
  yaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 90, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => The color of the ticks
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  y2axis: {
  titleAngle: 270
  },
  grid: {
  color: '#545454', // => primary color used for outline and labels
  backgroundColor: null, // => null for transparent, else color
  backgroundImage: null, // => background image. String or object with src, left and top
  watermarkAlpha: 0.4, // =>
  tickColor: '#DDDDDD', // => color used for the ticks
  labelMargin: 3, // => margin in pixels
  verticalLines: true, // => whether to show gridlines in vertical direction
  minorVerticalLines: null, // => whether to show gridlines for minor ticks in vertical dir.
  horizontalLines: true, // => whether to show gridlines in horizontal direction
  minorHorizontalLines: null, // => whether to show gridlines for minor ticks in horizontal dir.
  outlineWidth: 1, // => width of the grid outline/border in pixels
  outline : 'nsew', // => walls of the outline to display
  circular: false // => if set to true, the grid will be circular, must be used when radars are drawn
  },
  mouse: {
  track: false, // => true to track the mouse, no tracking otherwise
  trackAll: false,
  position: 'se', // => position of the value box (default south-east)
  relative: false, // => next to the mouse cursor
  trackFormatter: Flotr.defaultTrackFormatter, // => formats the values in the value box
  margin: 5, // => margin in pixels of the valuebox
  lineColor: '#FF3F19', // => line color of points that are drawn when mouse comes near a value of a series
  trackDecimals: 1, // => decimals for the track values
  sensibility: 2, // => the lower this number, the more precise you have to aim to show a value
  trackY: true, // => whether or not to track the mouse in the y axis
  radius: 3, // => radius of the track point
  fillColor: null, // => color to fill our select bar with only applies to bar and similar graphs (only bars for now)
  fillOpacity: 0.4 // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  }
  };
 
  /**
  * Flotr Color
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  // Constructor
  function Color (r, g, b, a) {
  this.rgba = ['r','g','b','a'];
  var x = 4;
  while(-1<--x){
  this[this.rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
  }
  this.normalize();
  }
 
  // Constants
  var COLOR_NAMES = {
  aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],
  brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],
  darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],
  darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],
  darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],
  khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],
  lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],
  maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],
  violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]
  };
 
  Color.prototype = {
  scale: function(rf, gf, bf, af){
  var x = 4;
  while (-1 < --x) {
  if (!_.isUndefined(arguments[x])) this[this.rgba[x]] *= arguments[x];
  }
  return this.normalize();
  },
  alpha: function(alpha) {
  if (!_.isUndefined(alpha) && !_.isNull(alpha)) {
  this.a = alpha;
  }
  return this.normalize();
  },
  clone: function(){
  return new Color(this.r, this.b, this.g, this.a);
  },
  limit: function(val,minVal,maxVal){
  return Math.max(Math.min(val, maxVal), minVal);
  },
  normalize: function(){
  var limit = this.limit;
  this.r = limit(parseInt(this.r, 10), 0, 255);
  this.g = limit(parseInt(this.g, 10), 0, 255);
  this.b = limit(parseInt(this.b, 10), 0, 255);
  this.a = limit(this.a, 0, 1);
  return this;
  },
  distance: function(color){
  if (!color) return;
  color = new Color.parse(color);
  var dist = 0, x = 3;
  while(-1<--x){
  dist += Math.abs(this[this.rgba[x]] - color[this.rgba[x]]);
  }
  return dist;
  },
  toString: function(){
  return (this.a >= 1.0) ? 'rgb('+[this.r,this.g,this.b].join(',')+')' : 'rgba('+[this.r,this.g,this.b,this.a].join(',')+')';
  },
  contrast: function () {
  var
  test = 1 - ( 0.299 * this.r + 0.587 * this.g + 0.114 * this.b) / 255;
  return (test < 0.5 ? '#000000' : '#ffffff');
  }
  };
 
  _.extend(Color, {
  /**
  * Parses a color string and returns a corresponding Color.
  * The different tests are in order of probability to improve speed.
  * @param {String, Color} str - string thats representing a color
  * @return {Color} returns a Color object or false
  */
  parse: function(color){
  if (color instanceof Color) return color;
 
  var result;
 
  // #a0b1c2
  if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)))
  return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
 
  // rgb(num,num,num)
  if((result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
 
  // #fff
  if((result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)))
  return new Color(parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16));
 
  // rgba(num,num,num,num)
  if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
 
  // rgb(num%,num%,num%)
  if((result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);
 
  // rgba(num%,num%,num%,num)
  if((result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));
 
  // Otherwise, we're most likely dealing with a named color.
  var name = (color+'').replace(/^\s*([\S\s]*?)\s*$/, '$1').toLowerCase();
  if(name == 'transparent'){
  return new Color(255, 255, 255, 0);
  }
  return (result = COLOR_NAMES[name]) ? new Color(result[0], result[1], result[2]) : new Color(0, 0, 0, 0);
  },
 
  /**
  * Process color and options into color style.
  */
  processColor: function(color, options) {
 
  var opacity = options.opacity;
  if (!color) return 'rgba(0, 0, 0, 0)';
  if (color instanceof Color) return color.alpha(opacity).toString();
  if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
 
  var grad = color.colors ? color : {colors: color};
 
  if (!options.ctx) {
  if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
  return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
  }
  grad = _.extend({start: 'top', end: 'bottom'}, grad);
 
  if (/top/i.test(grad.start)) options.x1 = 0;
  if (/left/i.test(grad.start)) options.y1 = 0;
  if (/bottom/i.test(grad.end)) options.x2 = 0;
  if (/right/i.test(grad.end)) options.y2 = 0;
 
  var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
  for (i = 0; i < grad.colors.length; i++) {
  c = grad.colors[i];
  if (_.isArray(c)) {
  stop = c[0];
  c = c[1];
  }
  else stop = i / (grad.colors.length-1);
  gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
  }
  return gradient;
  }
  });
 
  Flotr.Color = Color;
 
  })();
 
  /**
  * Flotr Date
  */
  Flotr.Date = {
 
  set : function (date, name, mode, value) {
  mode = mode || 'UTC';
  name = 'set' + (mode === 'UTC' ? 'UTC' : '') + name;
  date[name](value);
  },
 
  get : function (date, name, mode) {
  mode = mode || 'UTC';
  name = 'get' + (mode === 'UTC' ? 'UTC' : '') + name;
  return date[name]();
  },
 
  format: function(d, format, mode) {
  if (!d) return;
 
  // We should maybe use an "official" date format spec, like PHP date() or ColdFusion
  // http://fr.php.net/manual/en/function.date.php
  // http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_c-d_29.html
  var
  get = this.get,
  tokens = {
  h: get(d, 'Hours', mode).toString(),
  H: leftPad(get(d, 'Hours', mode)),
  M: leftPad(get(d, 'Minutes', mode)),
  S: leftPad(get(d, 'Seconds', mode)),
  s: get(d, 'Milliseconds', mode),
  d: get(d, 'Date', mode).toString(),
  m: (get(d, 'Month', mode) + 1).toString(),
  y: get(d, 'FullYear', mode).toString(),
  b: Flotr.Date.monthNames[get(d, 'Month', mode)]
  };
 
  function leftPad(n){
  n += '';
  return n.length == 1 ? "0" + n : n;
  }
 
  var r = [], c,
  escape = false;
 
  for (var i = 0; i < format.length; ++i) {
  c = format.charAt(i);
 
  if (escape) {
  r.push(tokens[c] || c);
  escape = false;
  }
  else if (c == "%")
  escape = true;
  else
  r.push(c);
  }
  return r.join('');
  },
  getFormat: function(time, span) {
  var tu = Flotr.Date.timeUnits;
  if (time < tu.second) return "%h:%M:%S.%s";
  else if (time < tu.minute) return "%h:%M:%S";
  else if (time < tu.day) return (span < 2 * tu.day) ? "%h:%M" : "%b %d %h:%M";
  else if (time < tu.month) return "%b %d";
  else if (time < tu.year) return (span < tu.year) ? "%b" : "%b %y";
  else return "%y";
  },
  formatter: function (v, axis) {
  var
  options = axis.options,
  scale = Flotr.Date.timeUnits[options.timeUnit],
  d = new Date(v * scale);
 
  // first check global format
  if (axis.options.timeFormat)
  return Flotr.Date.format(d, options.timeFormat, options.timeMode);
 
  var span = (axis.max - axis.min) * scale,
  t = axis.tickSize * Flotr.Date.timeUnits[axis.tickUnit];
 
  return Flotr.Date.format(d, Flotr.Date.getFormat(t, span), options.timeMode);
  },
  generator: function(axis) {
 
  var
  set = this.set,
  get = this.get,
  timeUnits = this.timeUnits,
  spec = this.spec,
  options = axis.options,
  mode = options.timeMode,
  scale = timeUnits[options.timeUnit],
  min = axis.min * scale,
  max = axis.max * scale,
  delta = (max - min) / options.noTicks,
  ticks = [],
  tickSize = axis.tickSize,
  tickUnit,
  formatter, i;
 
  // Use custom formatter or time tick formatter
  formatter = (options.tickFormatter === Flotr.defaultTickFormatter ?
  this.formatter : options.tickFormatter
  );
 
  for (i = 0; i < spec.length - 1; ++i) {
  var d = spec[i][0] * timeUnits[spec[i][1]];
  if (delta < (d + spec[i+1][0] * timeUnits[spec[i+1][1]]) / 2 && d >= tickSize)
  break;
  }
  tickSize = spec[i][0];
  tickUnit = spec[i][1];
 
  // special-case the possibility of several years
  if (tickUnit == "year") {
  tickSize = Flotr.getTickSize(options.noTicks*timeUnits.year, min, max, 0);
 
  // Fix for 0.5 year case
  if (tickSize == 0.5) {
  tickUnit = "month";
  tickSize = 6;
  }
  }
 
  axis.tickUnit = tickUnit;
  axis.tickSize = tickSize;
 
  var step = tickSize * timeUnits[tickUnit];
  d = new Date(min);
 
  function setTick (name) {
  set(d, name, mode, Flotr.floorInBase(
  get(d, name, mode), tickSize
  ));
  }
 
  switch (tickUnit) {
  case "millisecond": setTick('Milliseconds'); break;
  case "second": setTick('Seconds'); break;
  case "minute": setTick('Minutes'); break;
  case "hour": setTick('Hours'); break;
  case "month": setTick('Month'); break;
  case "year": setTick('FullYear'); break;
  }
 
  // reset smaller components
  if (step >= timeUnits.second) set(d, 'Milliseconds', mode, 0);
  if (step >= timeUnits.minute) set(d, 'Seconds', mode, 0);
  if (step >= timeUnits.hour) set(d, 'Minutes', mode, 0);
  if (step >= timeUnits.day) set(d, 'Hours', mode, 0);
  if (step >= timeUnits.day * 4) set(d, 'Date', mode, 1);
  if (step >= timeUnits.year) set(d, 'Month', mode, 0);
 
  var carry = 0, v = NaN, prev;
  do {
  prev = v;
  v = d.getTime();
  ticks.push({ v: v / scale, label: formatter(v / scale, axis) });
  if (tickUnit == "month") {
  if (tickSize < 1) {
  /* a bit complicated - we'll divide the month up but we need to take care of fractions
  so we don't end up in the middle of a day */
  set(d, 'Date', mode, 1);
  var start = d.getTime();
  set(d, 'Month', mode, get(d, 'Month', mode) + 1);
  var end = d.getTime();
  d.setTime(v + carry * timeUnits.hour + (end - start) * tickSize);
  carry = get(d, 'Hours', mode);
  set(d, 'Hours', mode, 0);
  }
  else
  set(d, 'Month', mode, get(d, 'Month', mode) + tickSize);
  }
  else if (tickUnit == "year") {
  set(d, 'FullYear', mode, get(d, 'FullYear', mode) + tickSize);
  }
  else
  d.setTime(v + step);
 
  } while (v < max && v != prev);
 
  return ticks;
  },
  timeUnits: {
  millisecond: 1,
  second: 1000,
  minute: 1000 * 60,
  hour: 1000 * 60 * 60,
  day: 1000 * 60 * 60 * 24,
  month: 1000 * 60 * 60 * 24 * 30,
  year: 1000 * 60 * 60 * 24 * 365.2425
  },
  // the allowed tick sizes, after 1 year we use an integer algorithm
  spec: [
  [1, "millisecond"], [20, "millisecond"], [50, "millisecond"], [100, "millisecond"], [200, "millisecond"], [500, "millisecond"],
  [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"],
  [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"],
  [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"],
  [1, "day"], [2, "day"], [3, "day"],
  [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"],
  [1, "year"]
  ],
  monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  };
 
  (function () {
 
  var _ = Flotr._;
 
  function getEl (el) {
  return (el && el.jquery) ? el[0] : el;
  }
 
  Flotr.DOM = {
  addClass: function(element, name){
  element = getEl(element);
  var classList = (element.className ? element.className : '');
  if (_.include(classList.split(/\s+/g), name)) return;
  element.className = (classList ? classList + ' ' : '') + name;
  },
  /**
  * Create an element.
  */
  create: function(tag){
  return document.createElement(tag);
  },
  node: function(html) {
  var div = Flotr.DOM.create('div'), n;
  div.innerHTML = html;
  n = div.children[0];
  div.innerHTML = '';
  return n;
  },
  /**
  * Remove all children.
  */
  empty: function(element){
  element = getEl(element);
  element.innerHTML = '';
  /*
  if (!element) return;
  _.each(element.childNodes, function (e) {
  Flotr.DOM.empty(e);
  element.removeChild(e);
  });
  */
  },
  remove: function (element) {
  element = getEl(element);
  element.parentNode.removeChild(element);
  },
  hide: function(element){
  element = getEl(element);
  Flotr.DOM.setStyles(element, {display:'none'});
  },
  /**
  * Insert a child.
  * @param {Element} element
  * @param {Element|String} Element or string to be appended.
  */
  insert: function(element, child){
  element = getEl(element);
  if(_.isString(child))
  element.innerHTML += child;
  else if (_.isElement(child))
  element.appendChild(child);
  },
  // @TODO find xbrowser implementation
  opacity: function(element, opacity) {
  element = getEl(element);
  element.style.opacity = opacity;
  },
  position: function(element, p){
  element = getEl(element);
  if (!element.offsetParent)
  return {left: (element.offsetLeft || 0), top: (element.offsetTop || 0)};
 
  p = this.position(element.offsetParent);
  p.left += element.offsetLeft;
  p.top += element.offsetTop;
  return p;
  },
  removeClass: function(element, name) {
  var classList = (element.className ? element.className : '');
  element = getEl(element);
  element.className = _.filter(classList.split(/\s+/g), function (c) {
  if (c != name) return true; }
  ).join(' ');
  },
  setStyles: function(element, o) {
  element = getEl(element);
  _.each(o, function (value, key) {
  element.style[key] = value;
  });
  },
  show: function(element){
  element = getEl(element);
  Flotr.DOM.setStyles(element, {display:''});
  },
  /**
  * Return element size.
  */
  size: function(element){
  element = getEl(element);
  return {
  height : element.offsetHeight,
  width : element.offsetWidth };
  }
  };
 
  })();
 
  /**
  * Flotr Event Adapter
  */
  (function () {
  var
  F = Flotr,
  bean = F.bean;
  F.EventAdapter = {
  observe: function(object, name, callback) {
  bean.add(object, name, callback);
  return this;
  },
  fire: function(object, name, args) {
  bean.fire(object, name, args);
  if (typeof(Prototype) != 'undefined')
  Event.fire(object, name, args);
  // @TODO Someone who uses mootools, add mootools adapter for existing applciations.
  return this;
  },
  stopObserving: function(object, name, callback) {
  bean.remove(object, name, callback);
  return this;
  },
  eventPointer: function(e) {
  if (!F._.isUndefined(e.touches) && e.touches.length > 0) {
  return {
  x : e.touches[0].pageX,
  y : e.touches[0].pageY
  };
  } else if (!F._.isUndefined(e.changedTouches) && e.changedTouches.length > 0) {
  return {
  x : e.changedTouches[0].pageX,
  y : e.changedTouches[0].pageY
  };
  } else if (e.pageX || e.pageY) {
  return {
  x : e.pageX,
  y : e.pageY
  };
  } else if (e.clientX || e.clientY) {
  var
  d = document,
  b = d.body,
  de = d.documentElement;
  return {
  x: e.clientX + b.scrollLeft + de.scrollLeft,
  y: e.clientY + b.scrollTop + de.scrollTop
  };
  }
  }
  };
  })();
 
  /**
  * Text Utilities
  */
  (function () {
 
  var
  F = Flotr,
  D = F.DOM,
  _ = F._,
 
  Text = function (o) {
  this.o = o;
  };
 
  Text.prototype = {
 
  dimensions : function (text, canvasStyle, htmlStyle, className) {
 
  if (!text) return { width : 0, height : 0 };
 
  return (this.o.html) ?
  this.html(text, this.o.element, htmlStyle, className) :
  this.canvas(text, canvasStyle);
  },
 
  canvas : function (text, style) {
 
  if (!this.o.textEnabled) return;
  style = style || {};
 
  var
  metrics = this.measureText(text, style),
  width = metrics.width,
  height = style.size || F.defaultOptions.fontSize,
  angle = style.angle || 0,
  cosAngle = Math.cos(angle),
  sinAngle = Math.sin(angle),
  widthPadding = 2,
  heightPadding = 6,
  bounds;
 
  bounds = {
  width: Math.abs(cosAngle * width) + Math.abs(sinAngle * height) + widthPadding,
  height: Math.abs(sinAngle * width) + Math.abs(cosAngle * height) + heightPadding
  };
 
  return bounds;
  },
 
  html : function (text, element, style, className) {
 
  var div = D.create('div');
 
  D.setStyles(div, { 'position' : 'absolute', 'top' : '-10000px' });
  D.insert(div, '<div style="'+style+'" class="'+className+' flotr-dummy-div">' + text + '</div>');
  D.insert(this.o.element, div);
 
  return D.size(div);
  },
 
  measureText : function (text, style) {
 
  var
  context = this.o.ctx,
  metrics;
 
  if (!context.fillText || (F.isIphone && context.measure)) {
  return { width : context.measure(text, style)};
  }
 
  style = _.extend({
  size: F.defaultOptions.fontSize,
  weight: 1,
  angle: 0
  }, style);
 
  context.save();
  context.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  metrics = context.measureText(text);
  context.restore();
 
  return metrics;
  }
  };
 
  Flotr.Text = Text;
 
  })();
 
  /**
  * Flotr Graph class that plots a graph on creation.
  */
  (function () {
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._,
  flotr = Flotr;
  /**
  * Flotr Graph constructor.
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  */
  Graph = function(el, data, options){
  // Let's see if we can get away with out this [JS]
  // try {
  this._setEl(el);
  this._initMembers();
  this._initPlugins();
 
  E.fire(this.el, 'flotr:beforeinit', [this]);
 
  this.data = data;
  this.series = flotr.Series.getSeries(data);
  this._initOptions(options);
  this._initGraphTypes();
  this._initCanvas();
  this._text = new flotr.Text({
  element : this.el,
  ctx : this.ctx,
  html : this.options.HtmlText,
  textEnabled : this.textEnabled
  });
  E.fire(this.el, 'flotr:afterconstruct', [this]);
  this._initEvents();
 
  this.findDataRanges();
  this.calculateSpacing();
 
  this.draw(_.bind(function() {
  E.fire(this.el, 'flotr:afterinit', [this]);
  }, this));
  /*
  try {
  } catch (e) {
  try {
  console.error(e);
  } catch (e2) {}
  }*/
  };
 
  function observe (object, name, callback) {
  E.observe.apply(this, arguments);
  this._handles.push(arguments);
  return this;
  }
 
  Graph.prototype = {
 
  destroy: function () {
  E.fire(this.el, 'flotr:destroy');
  _.each(this._handles, function (handle) {
  E.stopObserving.apply(this, handle);
  });
  this._handles = [];
  this.el.graph = null;
  },
 
  observe : observe,
 
  /**
  * @deprecated
  */
  _observe : observe,
 
  processColor: function(color, options){
  var o = { x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx };
  _.extend(o, options);
  return flotr.Color.processColor(color, o);
  },
  /**
  * Function determines the min and max values for the xaxis and yaxis.
  *
  * TODO logarithmic range validation (consideration of 0)
  */
  findDataRanges: function(){
  var a = this.axes,
  xaxis, yaxis, range;
 
  _.each(this.series, function (series) {
  range = series.getRange();
  if (range) {
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
  xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
  yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
  yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
  xaxis.used = (xaxis.used || range.xused);
  yaxis.used = (yaxis.used || range.yused);
  }
  }, this);
 
  // Check for empty data, no data case (none used)
  if (!a.x.used && !a.x2.used) a.x.used = true;
  if (!a.y.used && !a.y2.used) a.y.used = true;
 
  _.each(a, function (axis) {
  axis.calculateRange();
  });
 
  var
  types = _.keys(flotr.graphTypes),
  drawn = false;
 
  _.each(this.series, function (series) {
  if (series.hide) return;
  _.each(types, function (type) {
  if (series[type] && series[type].show) {
  this.extendRange(type, series);
  drawn = true;
  }
  }, this);
  if (!drawn) {
  this.extendRange(this.options.defaultType, series);
  }
  }, this);
  },
 
  extendRange : function (type, series) {
  if (this[type].extendRange) this[type].extendRange(series, series.data, series[type], this[type]);
  if (this[type].extendYRange) this[type].extendYRange(series.yaxis, series.data, series[type], this[type]);
  if (this[type].extendXRange) this[type].extendXRange(series.xaxis, series.data, series[type], this[type]);
  },
 
  /**
  * Calculates axis label sizes.
  */
  calculateSpacing: function(){
 
  var a = this.axes,
  options = this.options,
  series = this.series,
  margin = options.grid.labelMargin,
  T = this._text,
  x = a.x,
  x2 = a.x2,
  y = a.y,
  y2 = a.y2,
  maxOutset = options.grid.outlineWidth,
  i, j, l, dim;
 
  // TODO post refactor, fix this
  _.each(a, function (axis) {
  axis.calculateTicks();
  axis.calculateTextDimensions(T, options);
  });
 
  // Title height
  dim = T.dimensions(
  options.title,
  {size: options.fontSize*1.5},
  'font-size:1em;font-weight:bold;',
  'flotr-title'
  );
  this.titleHeight = dim.height;
 
  // Subtitle height
  dim = T.dimensions(
  options.subtitle,
  {size: options.fontSize},
  'font-size:smaller;',
  'flotr-subtitle'
  );
  this.subtitleHeight = dim.height;
 
  for(j = 0; j < options.length; ++j){
  if (series[j].points.show){
  maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
  }
  }
 
  var p = this.plotOffset;
  if (x.options.margin === false) {
  p.bottom = 0;
  p.top = 0;
  } else {
  p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ? (x.maxLabel.height + margin) : 0)) +
  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;
 
  p.top += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
  }
  if (y.options.margin === false) {
  p.left = 0;
  p.right = 0;
  } else {
  p.left += (options.grid.circular ? 0 : (y.used && y.options.showLabels ? (y.maxLabel.width + margin) : 0)) +
  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;
 
  p.right += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
  }
 
  p.top = Math.floor(p.top); // In order the outline not to be blured
 
  this.plotWidth = this.canvasWidth - p.left - p.right;
  this.plotHeight = this.canvasHeight - p.bottom - p.top;
 
  // TODO post refactor, fix this
  x.length = x2.length = this.plotWidth;
  y.length = y2.length = this.plotHeight;
  y.offset = y2.offset = this.plotHeight;
  x.setScale();
  x2.setScale();
  y.setScale();
  y2.setScale();
  },
  /**
  * Draws grid, labels, series and outline.
  */
  draw: function(after) {
 
  var
  context = this.ctx,
  i;
 
  E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
 
  if (this.series.length) {
 
  context.save();
  context.translate(this.plotOffset.left, this.plotOffset.top);
 
  for (i = 0; i < this.series.length; i++) {
  if (!this.series[i].hide) this.drawSeries(this.series[i]);
  }
 
  context.restore();
  this.clip();
  }
 
  E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
  if (after) after();
  },
  /**
  * Actually draws the graph.
  * @param {Object} series - series to draw
  */
  drawSeries: function(series){
 
  function drawChart (series, typeKey) {
  var options = this.getOptions(series, typeKey);
  this[typeKey].draw(options);
  }
 
  var drawn = false;
  series = series || this.series;
 
  _.each(flotr.graphTypes, function (type, typeKey) {
  if (series[typeKey] && series[typeKey].show && this[typeKey]) {
  drawn = true;
  drawChart.call(this, series, typeKey);
  }
  }, this);
 
  if (!drawn) drawChart.call(this, series, this.options.defaultType);
  },
 
  getOptions : function (series, typeKey) {
  var
  type = series[typeKey],
  graphType = this[typeKey],
  xaxis = series.xaxis,
  yaxis = series.yaxis,
  options = {
  context : this.ctx,
  width : this.plotWidth,
  height : this.plotHeight,
  fontSize : this.options.fontSize,
  fontColor : this.options.fontColor,
  textEnabled : this.textEnabled,
  htmlText : this.options.HtmlText,
  text : this._text, // TODO Is this necessary?
  element : this.el,
  data : series.data,
  color : series.color,
  shadowSize : series.shadowSize,
  xScale : xaxis.d2p,
  yScale : yaxis.d2p,
  xInverse : xaxis.p2d,
  yInverse : yaxis.p2d
  };
 
  options = flotr.merge(type, options);
 
  // Fill
  options.fillStyle = this.processColor(
  type.fillColor || series.color,
  {opacity: type.fillOpacity}
  );
 
  return options;
  },
  /**
  * Calculates the coordinates from a mouse event object.
  * @param {Event} event - Mouse Event object.
  * @return {Object} Object with coordinates of the mouse.
  */
  getEventPosition: function (e){
 
  var
  d = document,
  b = d.body,
  de = d.documentElement,
  axes = this.axes,
  plotOffset = this.plotOffset,
  lastMousePos = this.lastMousePos,
  pointer = E.eventPointer(e),
  dx = pointer.x - lastMousePos.pageX,
  dy = pointer.y - lastMousePos.pageY,
  r, rx, ry;
 
  if ('ontouchstart' in this.el) {
  r = D.position(this.overlay);
  rx = pointer.x - r.left - plotOffset.left;
  ry = pointer.y - r.top - plotOffset.top;
  } else {
  r = this.overlay.getBoundingClientRect();
  rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
  ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
  }
 
  return {
  x: axes.x.p2d(rx),
  x2: axes.x2.p2d(rx),
  y: axes.y.p2d(ry),
  y2: axes.y2.p2d(ry),
  relX: rx,
  relY: ry,
  dX: dx,
  dY: dy,
  absX: pointer.x,
  absY: pointer.y,
  pageX: pointer.x,
  pageY: pointer.y
  };
  },
  /**
  * Observes the 'click' event and fires the 'flotr:click' event.
  * @param {Event} event - 'click' Event object.
  */
  clickHandler: function(event){
  if(this.ignoreClick){
  this.ignoreClick = false;
  return this.ignoreClick;
  }
  E.fire(this.el, 'flotr:click', [this.getEventPosition(event), this]);
  },
  /**
  * Observes mouse movement over the graph area. Fires the 'flotr:mousemove' event.
  * @param {Event} event - 'mousemove' Event object.
  */
  mouseMoveHandler: function(event){
  if (this.mouseDownMoveHandler) return;
  var pos = this.getEventPosition(event);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  },
  /**
  * Observes the 'mousedown' event.
  * @param {Event} event - 'mousedown' Event object.
  */
  mouseDownHandler: function (event){
 
  /*
  // @TODO Context menu?
  if(event.isRightClick()) {
  event.stop();
 
  var overlay = this.overlay;
  overlay.hide();
 
  function cancelContextMenu () {
  overlay.show();
  E.stopObserving(document, 'mousemove', cancelContextMenu);
  }
  E.observe(document, 'mousemove', cancelContextMenu);
  return;
  }
  */
 
  if (this.mouseUpHandler) return;
  this.mouseUpHandler = _.bind(function (e) {
  E.stopObserving(document, 'mouseup', this.mouseUpHandler);
  E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
  this.mouseDownMoveHandler = null;
  this.mouseUpHandler = null;
  // @TODO why?
  //e.stop();
  E.fire(this.el, 'flotr:mouseup', [e, this]);
  }, this);
  this.mouseDownMoveHandler = _.bind(function (e) {
  var pos = this.getEventPosition(e);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  }, this);
  E.observe(document, 'mouseup', this.mouseUpHandler);
  E.observe(document, 'mousemove', this.mouseDownMoveHandler);
  E.fire(this.el, 'flotr:mousedown', [event, this]);
  this.ignoreClick = false;
  },
  drawTooltip: function(content, x, y, options) {
  var mt = this.getMouseTrack(),
  style = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;',
  p = options.position,
  m = options.margin,
  plotOffset = this.plotOffset;
 
  if(x !== null && y !== null){
  if (!options.relative) { // absolute to the canvas
  if(p.charAt(0) == 'n') style += 'top:' + (m + plotOffset.top) + 'px;bottom:auto;';
  else if(p.charAt(0) == 's') style += 'bottom:' + (m + plotOffset.bottom) + 'px;top:auto;';
  if(p.charAt(1) == 'e') style += 'right:' + (m + plotOffset.right) + 'px;left:auto;';
  else if(p.charAt(1) == 'w') style += 'left:' + (m + plotOffset.left) + 'px;right:auto;';
  }
  else { // relative to the mouse
  if(p.charAt(0) == 'n') style += 'bottom:' + (m - plotOffset.top - y + this.canvasHeight) + 'px;top:auto;';
  else if(p.charAt(0) == 's') style += 'top:' + (m + plotOffset.top + y) + 'px;bottom:auto;';
  if(p.charAt(1) == 'e') style += 'left:' + (m + plotOffset.left + x) + 'px;right:auto;';
  else if(p.charAt(1) == 'w') style += 'right:' + (m - plotOffset.left - x + this.canvasWidth) + 'px;left:auto;';
  }
 
  mt.style.cssText = style;
  D.empty(mt);
  D.insert(mt, content);
  D.show(mt);
  }
  else {
  D.hide(mt);
  }
  },
 
  clip: function (ctx) {
 
  var
  o = this.plotOffset,
  w = this.canvasWidth,
  h = this.canvasHeight;
 
  ctx = ctx || this.ctx;
 
  if (flotr.isIE && flotr.isIE < 9) {
  // Clipping for excanvas :-(
  ctx.save();
  ctx.fillStyle = this.processColor(this.options.ieBackgroundColor);
  ctx.fillRect(0, 0, w, o.top);
  ctx.fillRect(0, 0, o.left, h);
  ctx.fillRect(0, h - o.bottom, w, o.bottom);
  ctx.fillRect(w - o.right, 0, o.right,h);
  ctx.restore();
  } else {
  ctx.clearRect(0, 0, w, o.top);
  ctx.clearRect(0, 0, o.left, h);
  ctx.clearRect(0, h - o.bottom, w, o.bottom);
  ctx.clearRect(w - o.right, 0, o.right,h);
  }
  },
 
  _initMembers: function() {
  this._handles = [];
  this.lastMousePos = {pageX: null, pageY: null };
  this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
  this.ignoreClick = true;
  this.prevHit = null;
  },
 
  _initGraphTypes: function() {
  _.each(flotr.graphTypes, function(handler, graphType){
  this[graphType] = flotr.clone(handler);
  }, this);
  },
 
  _initEvents: function () {
 
  var
  el = this.el,
  touchendHandler, movement, touchend;
 
  if ('ontouchstart' in el) {
 
  touchendHandler = _.bind(function (e) {
  touchend = true;
  E.stopObserving(document, 'touchend', touchendHandler);
  E.fire(el, 'flotr:mouseup', [event, this]);
  this.multitouches = null;
 
  if (!movement) {
  this.clickHandler(e);
  }
  }, this);
 
  this.observe(this.overlay, 'touchstart', _.bind(function (e) {
  movement = false;
  touchend = false;
  this.ignoreClick = false;
 
  if (e.touches && e.touches.length > 1) {
  this.multitouches = e.touches;
  }
 
  E.fire(el, 'flotr:mousedown', [event, this]);
  this.observe(document, 'touchend', touchendHandler);
  }, this));
 
  this.observe(this.overlay, 'touchmove', _.bind(function (e) {
 
  var pos = this.getEventPosition(e);
 
  if (this.options.preventDefault) {
  e.preventDefault();
  }
 
  movement = true;
 
  if (this.multitouches || (e.touches && e.touches.length > 1)) {
  this.multitouches = e.touches;
  } else {
  if (!touchend) {
  E.fire(el, 'flotr:mousemove', [event, pos, this]);
  }
  }
  this.lastMousePos = pos;
  }, this));
 
  } else {
  this.
  observe(this.overlay, 'mousedown', _.bind(this.mouseDownHandler, this)).
  observe(el, 'mousemove', _.bind(this.mouseMoveHandler, this)).
  observe(this.overlay, 'click', _.bind(this.clickHandler, this)).
  observe(el, 'mouseout', function () {
  E.fire(el, 'flotr:mouseout');
  });
  }
  },
 
  /**
  * Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
  * of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
  * are created, the elements are inserted into the container element.
  */
  _initCanvas: function(){
  var el = this.el,
  o = this.options,
  children = el.children,
  removedChildren = [],
  child, i,
  size, style;
 
  // Empty the el
  for (i = children.length; i--;) {
  child = children[i];
  if (!this.canvas && child.className === 'flotr-canvas') {
  this.canvas = child;
  } else if (!this.overlay && child.className === 'flotr-overlay') {
  this.overlay = child;
  } else {
  removedChildren.push(child);
  }
  }
  for (i = removedChildren.length; i--;) {
  el.removeChild(removedChildren[i]);
  }
 
  D.setStyles(el, {position: 'relative'}); // For positioning labels and overlay.
  size = {};
  size.width = el.clientWidth;
  size.height = el.clientHeight;
 
  if(size.width <= 0 || size.height <= 0 || o.resolution <= 0){
  throw 'Invalid dimensions for plot, width = ' + size.width + ', height = ' + size.height + ', resolution = ' + o.resolution;
  }
 
  // Main canvas for drawing graph types
  this.canvas = getCanvas(this.canvas, 'canvas');
  // Overlay canvas for interactive features
  this.overlay = getCanvas(this.overlay, 'overlay');
  this.ctx = getContext(this.canvas);
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this.octx = getContext(this.overlay);
  this.octx.clearRect(0, 0, this.overlay.width, this.overlay.height);
  this.canvasHeight = size.height;
  this.canvasWidth = size.width;
  this.textEnabled = !!this.ctx.drawText || !!this.ctx.fillText; // Enable text functions
 
  function getCanvas(canvas, name){
  if(!canvas){
  canvas = D.create('canvas');
  if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
  FlashCanvas.initElement(canvas);
  }
  canvas.className = 'flotr-'+name;
  canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
  D.insert(el, canvas);
  }
  _.each(size, function(size, attribute){
  D.show(canvas);
  if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
  return;
  }
  canvas.setAttribute(attribute, size * o.resolution);
  canvas.style[attribute] = size + 'px';
  });
  canvas.context_ = null; // Reset the ExCanvas context
  return canvas;
  }
 
  function getContext(canvas){
  if(window.G_vmlCanvasManager) window.G_vmlCanvasManager.initElement(canvas); // For ExCanvas
  var context = canvas.getContext('2d');
  if(!window.G_vmlCanvasManager) context.scale(o.resolution, o.resolution);
  return context;
  }
  },
 
  _initPlugins: function(){
  // TODO Should be moved to flotr and mixed in.
  _.each(flotr.plugins, function(plugin, name){
  _.each(plugin.callbacks, function(fn, c){
  this.observe(this.el, c, _.bind(fn, this));
  }, this);
  this[name] = flotr.clone(plugin);
  _.each(this[name], function(fn, p){
  if (_.isFunction(fn))
  this[name][p] = _.bind(fn, this);
  }, this);
  }, this);
  },
 
  /**
  * Sets options and initializes some variables and color specific values, used by the constructor.
  * @param {Object} opts - options object
  */
  _initOptions: function(opts){
  var options = flotr.clone(flotr.defaultOptions);
  options.x2axis = _.extend(_.clone(options.xaxis), options.x2axis);
  options.y2axis = _.extend(_.clone(options.yaxis), options.y2axis);
  this.options = flotr.merge(opts || {}, options);
 
  if (this.options.grid.minorVerticalLines === null &&
  this.options.xaxis.scaling === 'logarithmic') {
  this.options.grid.minorVerticalLines = true;
  }
  if (this.options.grid.minorHorizontalLines === null &&
  this.options.yaxis.scaling === 'logarithmic') {
  this.options.grid.minorHorizontalLines = true;
  }
 
  E.fire(this.el, 'flotr:afterinitoptions', [this]);
 
  this.axes = flotr.Axis.getAxes(this.options);
 
  // Initialize some variables used throughout this function.
  var assignedColors = [],
  colors = [],
  ln = this.series.length,
  neededColors = this.series.length,
  oc = this.options.colors,
  usedColors = [],
  variation = 0,
  c, i, j, s;
 
  // Collect user-defined colors from series.
  for(i = neededColors - 1; i > -1; --i){
  c = this.series[i].color;
  if(c){
  --neededColors;
  if(_.isNumber(c)) assignedColors.push(c);
  else usedColors.push(flotr.Color.parse(c));
  }
  }
 
  // Calculate the number of colors that need to be generated.
  for(i = assignedColors.length - 1; i > -1; --i)
  neededColors = Math.max(neededColors, assignedColors[i] + 1);
 
  // Generate needed number of colors.
  for(i = 0; colors.length < neededColors;){
  c = (oc.length == i) ? new flotr.Color(100, 100, 100) : flotr.Color.parse(oc[i]);
 
  // Make sure each serie gets a different color.
  var sign = variation % 2 == 1 ? -1 : 1,
  factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
  c.scale(factor, factor, factor);
 
  /**
  * @todo if we're getting too close to something else, we should probably skip this one
  */
  colors.push(c);
 
  if(++i >= oc.length){
  i = 0;
  ++variation;
  }
  }
 
  // Fill the options with the generated colors.
  for(i = 0, j = 0; i < ln; ++i){
  s = this.series[i];
 
  // Assign the color.
  if (!s.color){
  s.color = colors[j++].toString();
  }else if(_.isNumber(s.color)){
  s.color = colors[s.color].toString();
  }
 
  // Every series needs an axis
  if (!s.xaxis) s.xaxis = this.axes.x;
  if (s.xaxis == 1) s.xaxis = this.axes.x;
  else if (s.xaxis == 2) s.xaxis = this.axes.x2;
 
  if (!s.yaxis) s.yaxis = this.axes.y;
  if (s.yaxis == 1) s.yaxis = this.axes.y;
  else if (s.yaxis == 2) s.yaxis = this.axes.y2;
 
  // Apply missing options to the series.
  for (var t in flotr.graphTypes){
  s[t] = _.extend(_.clone(this.options[t]), s[t]);
  }
  s.mouse = _.extend(_.clone(this.options.mouse), s.mouse);
 
  if (_.isUndefined(s.shadowSize)) s.shadowSize = this.options.shadowSize;
  }
  },
 
  _setEl: function(el) {
  if (!el) throw 'The target container doesn\'t exist';
  else if (el.graph instanceof Graph) el.graph.destroy();
  else if (!el.clientWidth) throw 'The target container must be visible';
 
  el.graph = this;
  this.el = el;
  }
  };
 
  Flotr.Graph = Graph;
 
  })();
 
  /**
  * Flotr Axis Library
  */
 
  (function () {
 
  var
  _ = Flotr._,
  LOGARITHMIC = 'logarithmic';
 
  function Axis (o) {
 
  this.orientation = 1;
  this.offset = 0;
  this.datamin = Number.MAX_VALUE;
  this.datamax = -Number.MAX_VALUE;
 
  _.extend(this, o);
  }
 
 
  // Prototype
  Axis.prototype = {
 
  setScale : function () {
  var
  length = this.length,
  max = this.max,
  min = this.min,
  offset = this.offset,
  orientation = this.orientation,
  options = this.options,
  logarithmic = options.scaling === LOGARITHMIC,
  scale;
 
  if (logarithmic) {
  scale = length / (log(max, options.base) - log(min, options.base));
  } else {
  scale = length / (max - min);
  }
  this.scale = scale;
 
  // Logarithmic?
  if (logarithmic) {
  this.d2p = function (dataValue) {
  return offset + orientation * (log(dataValue, options.base) - log(min, options.base)) * scale;
  };
  this.p2d = function (pointValue) {
  return exp((offset + orientation * pointValue) / scale + log(min, options.base), options.base);
  };
  } else {
  this.d2p = function (dataValue) {
  return offset + orientation * (dataValue - min) * scale;
  };
  this.p2d = function (pointValue) {
  return (offset + orientation * pointValue) / scale + min;
  };
  }
  },
 
  calculateTicks : function () {
  var options = this.options;
 
  this.ticks = [];
  this.minorTicks = [];
 
  // User Ticks
  if(options.ticks){
  this._cleanUserTicks(options.ticks, this.ticks);
  this._cleanUserTicks(options.minorTicks || [], this.minorTicks);
  }
  else {
  if (options.mode == 'time') {
  this._calculateTimeTicks();
  } else if (options.scaling === 'logarithmic') {
  this._calculateLogTicks();
  } else {
  this._calculateTicks();
  }
  }
 
  // Ticks to strings
  _.each(this.ticks, function (tick) { tick.label += ''; });
  _.each(this.minorTicks, function (tick) { tick.label += ''; });
  },
 
  /**
  * Calculates the range of an axis to apply autoscaling.
  */
  calculateRange: function () {
 
  if (!this.used) return;
 
  var axis = this,
  o = axis.options,
  min = o.min !== null ? o.min : axis.datamin,
  max = o.max !== null ? o.max : axis.datamax,
  margin = o.autoscaleMargin;
 
  if (o.scaling == 'logarithmic') {
  if (min <= 0) min = axis.datamin;
 
  // Let it widen later on
  if (max <= 0) max = min;
  }
 
  if (max == min) {
  var widen = max ? 0.01 : 1.00;
  if (o.min === null) min -= widen;
  if (o.max === null) max += widen;
  }
 
  if (o.scaling === 'logarithmic') {
  if (min < 0) min = max / o.base; // Could be the result of widening
 
  var maxexp = Math.log(max);
  if (o.base != Math.E) maxexp /= Math.log(o.base);
  maxexp = Math.ceil(maxexp);
 
  var minexp = Math.log(min);
  if (o.base != Math.E) minexp /= Math.log(o.base);
  minexp = Math.ceil(minexp);
 
  axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
 
  // Try to determine a suitable amount of miniticks based on the length of a decade
  if (o.minorTickFreq === null) {
  if (maxexp - minexp > 10)
  o.minorTickFreq = 0;
  else if (maxexp - minexp > 5)
  o.minorTickFreq = 2;
  else
  o.minorTickFreq = 5;
  }
  } else {
  axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
  }
 
  axis.min = min;
  axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
 
  // Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
  if(o.min === null && o.autoscale){
  axis.min -= axis.tickSize * margin;
  // Make sure we don't go below zero if all values are positive.
  if(axis.min < 0 && axis.datamin >= 0) axis.min = 0;
  axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
  }
 
  if(o.max === null && o.autoscale){
  axis.max += axis.tickSize * margin;
  if(axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
  axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
  }
 
  if (axis.min == axis.max) axis.max = axis.min + 1;
  },
 
  calculateTextDimensions : function (T, options) {
 
  var maxLabel = '',
  length,
  i;
 
  if (this.options.showLabels) {
  for (i = 0; i < this.ticks.length; ++i) {
  length = this.ticks[i].label.length;
  if (length > maxLabel.length){
  maxLabel = this.ticks[i].label;
  }
  }
  }
 
  this.maxLabel = T.dimensions(
  maxLabel,
  {size:options.fontSize, angle: Flotr.toRad(this.options.labelsAngle)},
  'font-size:smaller;',
  'flotr-grid-label'
  );
 
  this.titleSize = T.dimensions(
  this.options.title,
  {size:options.fontSize*1.2, angle: Flotr.toRad(this.options.titleAngle)},
  'font-weight:bold;',
  'flotr-axis-title'
  );
  },
 
  _cleanUserTicks : function (ticks, axisTicks) {
 
  var axis = this, options = this.options,
  v, i, label, tick;
 
  if(_.isFunction(ticks)) ticks = ticks({min : axis.min, max : axis.max});
 
  for(i = 0; i < ticks.length; ++i){
  tick = ticks[i];
  if(typeof(tick) === 'object'){
  v = tick[0];
  label = (tick.length > 1) ? tick[1] : options.tickFormatter(v, {min : axis.min, max : axis.max});
  } else {
  v = tick;
  label = options.tickFormatter(v, {min : this.min, max : this.max});
  }
  axisTicks[i] = { v: v, label: label };
  }
  },
 
  _calculateTimeTicks : function () {
  this.ticks = Flotr.Date.generator(this);
  },
 
  _calculateLogTicks : function () {
 
  var axis = this,
  o = axis.options,
  v,
  decadeStart;
 
  var max = Math.log(axis.max);
  if (o.base != Math.E) max /= Math.log(o.base);
  max = Math.ceil(max);
 
  var min = Math.log(axis.min);
  if (o.base != Math.E) min /= Math.log(o.base);
  min = Math.ceil(min);
 
  for (i = min; i < max; i += axis.tickSize) {
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  // Next decade begins here:
  var decadeEnd = decadeStart * ((o.base == Math.E) ? Math.exp(axis.tickSize) : Math.pow(o.base, axis.tickSize));
  var stepSize = (decadeEnd - decadeStart) / o.minorTickFreq;
 
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  for (v = decadeStart + stepSize; v < decadeEnd; v += stepSize)
  axis.minorTicks.push({v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max})});
  }
 
  // Always show the value at the would-be start of next decade (end of this decade)
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  },
 
  _calculateTicks : function () {
 
  var axis = this,
  o = axis.options,
  tickSize = axis.tickSize,
  min = axis.min,
  max = axis.max,
  start = tickSize * Math.ceil(min / tickSize), // Round to nearest multiple of tick size.
  decimals,
  minorTickSize,
  v, v2,
  i, j;
 
  if (o.minorTickFreq)
  minorTickSize = tickSize / o.minorTickFreq;
 
  // Then store all possible ticks.
  for (i = 0; (v = v2 = start + i * tickSize) <= max; ++i){
 
  // Round (this is always needed to fix numerical instability).
  decimals = o.tickDecimals;
  if (decimals === null) decimals = 1 - Math.floor(Math.log(tickSize) / Math.LN10);
  if (decimals < 0) decimals = 0;
 
  v = v.toFixed(decimals);
  axis.ticks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
 
  if (o.minorTickFreq) {
  for (j = 0; j < o.minorTickFreq && (i * tickSize + j * minorTickSize) < max; ++j) {
  v = v2 + j * minorTickSize;
  axis.minorTicks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
  }
  }
  }
 
  }
  };
 
 
  // Static Methods
  _.extend(Axis, {
  getAxes : function (options) {
  return {
  x: new Axis({options: options.xaxis, n: 1, length: this.plotWidth}),
  x2: new Axis({options: options.x2axis, n: 2, length: this.plotWidth}),
  y: new Axis({options: options.yaxis, n: 1, length: this.plotHeight, offset: this.plotHeight, orientation: -1}),
  y2: new Axis({options: options.y2axis, n: 2, length: this.plotHeight, offset: this.plotHeight, orientation: -1})
  };
  }
  });
 
 
  // Helper Methods
 
 
  function log (value, base) {
  value = Math.log(Math.max(value, Number.MIN_VALUE));
  if (base !== Math.E)
  value /= Math.log(base);
  return value;
  }
 
  function exp (value, base) {
  return (base === Math.E) ? Math.exp(value) : Math.pow(base, value);
  }
 
  Flotr.Axis = Axis;
 
  })();
 
  /**
  * Flotr Series Library
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  function Series (o) {
  _.extend(this, o);
  }
 
  Series.prototype = {
 
  getRange: function () {
 
  var
  data = this.data,
  length = data.length,
  xmin = Number.MAX_VALUE,
  ymin = Number.MAX_VALUE,
  xmax = -Number.MAX_VALUE,
  ymax = -Number.MAX_VALUE,
  xused = false,
  yused = false,
  x, y, i;
 
  if (length < 0 || this.hide) return false;
 
  for (i = 0; i < length; i++) {
  x = data[i][0];
  y = data[i][1];
  if (x !== null) {
  if (x < xmin) { xmin = x; xused = true; }
  if (x > xmax) { xmax = x; xused = true; }
  }
  if (y !== null) {
  if (y < ymin) { ymin = y; yused = true; }
  if (y > ymax) { ymax = y; yused = true; }
  }
  }
 
  return {
  xmin : xmin,
  xmax : xmax,
  ymin : ymin,
  ymax : ymax,
  xused : xused,
  yused : yused
  };
  }
  };
 
  _.extend(Series, {
  /**
  * Collects dataseries from input and parses the series into the right format. It returns an Array
  * of Objects each having at least the 'data' key set.
  * @param {Array, Object} data - Object or array of dataseries
  * @return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
  */
  getSeries: function(data){
  return _.map(data, function(s){
  var series;
  if (s.data) {
  series = new Series();
  _.extend(series, s);
  } else {
  series = new Series({data:s});
  }
  return series;
  });
  }
  });
 
  Flotr.Series = Series;
 
  })();
 
  /** Lines **/
  Flotr.addType('lines', {
  options: {
  show: false, // => setting to true will show lines, false will hide
  lineWidth: 2, // => line width in pixels
  fill: false, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillBorder: false, // => draw a border around the fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  steps: false, // => draw steps
  stacked: false // => setting to true will show stacked lines, false will show normal lines
  },
 
  stack : {
  values : []
  },
 
  /**
  * Draws lines series in the canvas element.
  * @param {Object} options
  */
  draw : function (options) {
 
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  offset;
 
  context.save();
  context.lineJoin = 'round';
 
  if (shadowSize) {
 
  context.lineWidth = shadowSize / 2;
  offset = lineWidth / 2 + context.lineWidth / 2;
 
  // @TODO do this instead with a linear gradient
  context.strokeStyle = "rgba(0,0,0,0.1)";
  this.plot(options, offset + shadowSize / 2, false);
 
  context.strokeStyle = "rgba(0,0,0,0.2)";
  this.plot(options, offset, false);
  }
 
  context.lineWidth = lineWidth;
  context.strokeStyle = options.color;
 
  this.plot(options, 0, true);
 
  context.restore();
  },
 
  plot : function (options, shadowOffset, incStack) {
 
  var
  context = options.context,
  width = options.width,
  height = options.height,
  xScale = options.xScale,
  yScale = options.yScale,
  data = options.data,
  stack = options.stacked ? this.stack : false,
  length = data.length - 1,
  prevx = null,
  prevy = null,
  zero = yScale(0),
  start = null,
  x1, x2, y1, y2, stack1, stack2, i;
 
  if (length < 1) return;
 
  context.beginPath();
 
  for (i = 0; i < length; ++i) {
 
  // To allow empty values
  if (data[i][1] === null || data[i+1][1] === null) {
  if (options.fill) {
  if (i > 0 && data[i][1]) {
  context.stroke();
  fill();
  start = null;
  context.closePath();
  context.beginPath();
  }
  }
  continue;
  }
 
  // Zero is infinity for log scales
  // TODO handle zero for logarithmic
  // if (xa.options.scaling === 'logarithmic' && (data[i][0] <= 0 || data[i+1][0] <= 0)) continue;
  // if (ya.options.scaling === 'logarithmic' && (data[i][1] <= 0 || data[i+1][1] <= 0)) continue;
 
  x1 = xScale(data[i][0]);
  x2 = xScale(data[i+1][0]);
 
  if (start === null) start = data[i];
 
  if (stack) {
 
  stack1 = stack.values[data[i][0]] || 0;
  stack2 = stack.values[data[i+1][0]] || stack.values[data[i][0]] || 0;
 
  y1 = yScale(data[i][1] + stack1);
  y2 = yScale(data[i+1][1] + stack2);
 
  if(incStack){
  stack.values[data[i][0]] = data[i][1]+stack1;
 
  if(i == length-1)
  stack.values[data[i+1][0]] = data[i+1][1]+stack2;
  }
  }
  else{
  y1 = yScale(data[i][1]);
  y2 = yScale(data[i+1][1]);
  }
 
  if (
  (y1 > height && y2 > height) ||
  (y1 < 0 && y2 < 0) ||
  (x1 < 0 && x2 < 0) ||
  (x1 > width && x2 > width)
  ) continue;
 
  if((prevx != x1) || (prevy != y1 + shadowOffset))
  context.moveTo(x1, y1 + shadowOffset);
 
  prevx = x2;
  prevy = y2 + shadowOffset;
  if (options.steps) {
  context.lineTo(prevx + shadowOffset / 2, y1 + shadowOffset);
  context.lineTo(prevx + shadowOffset / 2, prevy);
  } else {
  context.lineTo(prevx, prevy);
  }
  }
 
  if (!options.fill || options.fill && !options.fillBorder) context.stroke();
 
  fill();
 
  function fill () {
  // TODO stacked lines
  if(!shadowOffset && options.fill && start){
  x1 = xScale(start[0]);
  context.fillStyle = options.fillStyle;
  context.lineTo(x2, zero);
  context.lineTo(x1, zero);
  context.lineTo(x1, yScale(start[1]));
  context.fill();
  if (options.fillBorder) {
  context.stroke();
  }
  }
  }
 
  context.closePath();
  },
 
  // Perform any pre-render precalculations (this should be run on data first)
  // - Pie chart total for calculating measures
  // - Stacks for lines and bars
  // precalculate : function () {
  // }
  //
  //
  // Get any bounds after pre calculation (axis can fetch this if does not have explicit min/max)
  // getBounds : function () {
  // }
  // getMin : function () {
  // }
  // getMax : function () {
  // }
  //
  //
  // Padding around rendered elements
  // getPadding : function () {
  // }
 
  extendYRange : function (axis, data, options, lines) {
 
  var o = axis.options;
 
  // If stacked and auto-min
  if (options.stacked && ((!o.max && o.max !== 0) || (!o.min && o.min !== 0))) {
 
  var
  newmax = axis.max,
  newmin = axis.min,
  positiveSums = lines.positiveSums || {},
  negativeSums = lines.negativeSums || {},
  x, j;
 
  for (j = 0; j < data.length; j++) {
 
  x = data[j][0] + '';
 
  // Positive
  if (data[j][1] > 0) {
  positiveSums[x] = (positiveSums[x] || 0) + data[j][1];
  newmax = Math.max(newmax, positiveSums[x]);
  }
 
  // Negative
  else {
  negativeSums[x] = (negativeSums[x] || 0) + data[j][1];
  newmin = Math.min(newmin, negativeSums[x]);
  }
  }
 
  lines.negativeSums = negativeSums;
  lines.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  if (options.steps) {
 
  this.hit = function (options) {
  var
  data = options.data,
  args = options.args,
  yScale = options.yScale,
  mouse = args[0],
  length = data.length,
  n = args[1],
  x = options.xInverse(mouse.relX),
  relY = mouse.relY,
  i;
 
  for (i = 0; i < length - 1; i++) {
  if (x >= data[i][0] && x <= data[i+1][0]) {
  if (Math.abs(yScale(data[i][1]) - relY) < 8) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  break;
  }
  }
  };
 
  this.drawHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x2, y);
  context.stroke();
  context.closePath();
  context.restore();
  }
  };
 
  this.clearHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  width = options.lineWidth,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.clearRect(x - width, y - width, x2 - x + 2 * width, 2 * width);
  }
  };
  }
  }
 
  });
 
  /** Bars **/
  Flotr.addType('bars', {
 
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  horizontal: false, // => horizontal bars (x and y inverted)
  stacked: false, // => stacked bar charts
  centered: true, // => center the bars to their x axis value
  topPadding: 0.1, // => top padding in percent
  grouped: false // => groups bars together which share x value, hit not supported.
  },
 
  stack : {
  positive : [],
  negative : [],
  _positive : [], // Shadow
  _negative : [] // Shadow
  },
 
  draw : function (options) {
  var
  context = options.context;
 
  this.current += 1;
 
  context.save();
  context.lineJoin = 'miter';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  shadowSize = options.shadowSize,
  i, geometry, left, top, width, height;
 
  if (data.length < 1) return;
 
  this.translate(context, options.horizontal);
 
  for (i = 0; i < data.length; i++) {
 
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (geometry === null) continue;
 
  left = geometry.left;
  top = geometry.top;
  width = geometry.width;
  height = geometry.height;
 
  if (options.fill) context.fillRect(left, top, width, height);
  if (shadowSize) {
  context.save();
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top + shadowSize, width, height);
  context.restore();
  }
  if (options.lineWidth) {
  context.strokeRect(left, top, width, height);
  }
  }
  },
 
  translate : function (context, horizontal) {
  if (horizontal) {
  context.rotate(-Math.PI / 2);
  context.scale(-1, 1);
  }
  },
 
  getBarGeometry : function (x, y, options) {
 
  var
  horizontal = options.horizontal,
  barWidth = options.barWidth,
  centered = options.centered,
  stack = options.stacked ? this.stack : false,
  lineWidth = options.lineWidth,
  bisection = centered ? barWidth / 2 : 0,
  xScale = horizontal ? options.yScale : options.xScale,
  yScale = horizontal ? options.xScale : options.yScale,
  xValue = horizontal ? y : x,
  yValue = horizontal ? x : y,
  stackOffset = 0,
  stackValue, left, right, top, bottom;
 
  if (options.grouped) {
  this.current / this.groups;
  xValue = xValue - bisection;
  barWidth = barWidth / this.groups;
  bisection = barWidth / 2;
  xValue = xValue + barWidth * this.current - bisection;
  }
 
  // Stacked bars
  if (stack) {
  stackValue = yValue > 0 ? stack.positive : stack.negative;
  stackOffset = stackValue[xValue] || stackOffset;
  stackValue[xValue] = stackOffset + yValue;
  }
 
  left = xScale(xValue - bisection);
  right = xScale(xValue + barWidth - bisection);
  top = yScale(yValue + stackOffset);
  bottom = yScale(stackOffset);
 
  // TODO for test passing... probably looks better without this
  if (bottom < 0) bottom = 0;
 
  // TODO Skipping...
  // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;
 
  return (x === null || y === null) ? null : {
  x : xValue,
  y : yValue,
  xScale : xScale,
  yScale : yScale,
  top : top,
  left : Math.min(left, right) - lineWidth / 2,
  width : Math.abs(right - left) - lineWidth,
  height : bottom - top
  };
  },
 
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  x = options.xInverse(mouse.relX),
  y = options.yInverse(mouse.relY),
  hitGeometry = this.getBarGeometry(x, y, options),
  width = hitGeometry.width / 2,
  left = hitGeometry.left,
  height = hitGeometry.y,
  geometry, i;
 
  for (i = data.length; i--;) {
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (
  // Height:
  (
  // Positive Bars:
  (height > 0 && height < geometry.y) ||
  // Negative Bars:
  (height < 0 && height > geometry.y)
  ) &&
  // Width:
  (Math.abs(left - geometry.left) < width)
  ) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  }
  },
 
  drawHit : function (options) {
  // TODO hits for stacked bars; implement using calculateStack option?
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  top = geometry.top,
  width = geometry.width,
  height = geometry.height;
 
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  this.translate(context, options.horizontal);
 
  // Draw highlight
  context.beginPath();
  context.moveTo(left, top + height);
  context.lineTo(left, top);
  context.lineTo(left + width, top);
  context.lineTo(left + width, top + height);
  if (options.fill) {
  context.fillStyle = options.fillStyle;
  context.fill();
  }
  context.stroke();
  context.closePath();
 
  context.restore();
  },
 
  clearHit: function (options) {
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  width = geometry.width,
  top = geometry.top,
  height = geometry.height,
  lineWidth = 2 * options.lineWidth;
 
  context.save();
  this.translate(context, options.horizontal);
  context.clearRect(
  left - lineWidth,
  Math.min(top, top + height) - lineWidth,
  width + 2 * lineWidth,
  Math.abs(height) + 2 * lineWidth
  );
  context.restore();
  },
 
  extendXRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  this.groups = (this.groups + 1) || 1;
  this.current = 0;
  },
 
  extendYRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {
 
  var
  max = axis.options.max;
 
  if (_.isNumber(max) || _.isString(max)) return;
 
  var
  newmin = axis.min,
  newmax = axis.max,
  horizontal = options.horizontal,
  orientation = axis.orientation,
  positiveSums = this.positiveSums || {},
  negativeSums = this.negativeSums || {},
  value, datum, index, j;
 
  // Sides of bars
  if ((orientation == 1 && !horizontal) || (orientation == -1 && horizontal)) {
  if (options.centered) {
  newmax = Math.max(axis.datamax + options.barWidth, newmax);
  newmin = Math.min(axis.datamin - options.barWidth, newmin);
  }
  }
 
  if (options.stacked &&
  ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal))){
 
  for (j = data.length; j--;) {
  value = data[j][(orientation == 1 ? 1 : 0)]+'';
  datum = data[j][(orientation == 1 ? 0 : 1)];
 
  // Positive
  if (datum > 0) {
  positiveSums[value] = (positiveSums[value] || 0) + datum;
  newmax = Math.max(newmax, positiveSums[value]);
  }
 
  // Negative
  else {
  negativeSums[value] = (negativeSums[value] || 0) + datum;
  newmin = Math.min(newmin, negativeSums[value]);
  }
  }
  }
 
  // End of bars
  if ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal)) {
  if (options.topPadding && (axis.max === axis.datamax || (options.stacked && this.stackMax !== newmax))) {
  newmax += options.topPadding * (newmax - newmin);
  }
  }
 
  this.stackMin = newmin;
  this.stackMax = newmax;
  this.negativeSums = negativeSums;
  this.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  });
 
  /** Bubbles **/
  Flotr.addType('bubbles', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  baseRadius: 2 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.lineWidth = options.lineWidth;
 
  // Shadows
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
 
  var
  data = options.data,
  context = options.context,
  geometry,
  i, x, y, z;
 
  offset = offset || 0;
 
  for (i = 0; i < data.length; ++i){
 
  geometry = this.getGeometry(data[i], options);
 
  context.beginPath();
  context.arc(geometry.x + offset, geometry.y + offset, geometry.z, 0, 2 * Math.PI, true);
  context.stroke();
  if (options.fill) context.fill();
  context.closePath();
  }
  },
  getGeometry : function (point, options) {
  return {
  x : options.xScale(point[0]),
  y : options.yScale(point[1]),
  z : point[2] * options.baseRadius
  };
  },
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  relX = mouse.relX,
  relY = mouse.relY,
  distance,
  geometry,
  dx, dy;
 
  n.best = n.best || Number.MAX_VALUE;
 
  for (i = data.length; i--;) {
  geometry = this.getGeometry(data[i], options);
 
  dx = geometry.x - relX;
  dy = geometry.y - relY;
  distance = Math.sqrt(dx * dx + dy * dy);
 
  if (distance < geometry.z && geometry.z < n.best) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  n.best = geometry.z;
  }
  }
  },
  drawHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options);
 
  context.save();
  context.lineWidth = options.lineWidth;
  context.fillStyle = options.fillStyle;
  context.strokeStyle = options.color;
  context.beginPath();
  context.arc(geometry.x, geometry.y, geometry.z, 0, 2 * Math.PI, true);
  context.fill();
  context.stroke();
  context.closePath();
  context.restore();
  },
  clearHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options),
  offset = geometry.z + options.lineWidth;
 
  context.save();
  context.clearRect(
  geometry.x - offset,
  geometry.y - offset,
  2 * offset,
  2 * offset
  );
  context.restore();
  }
  // TODO Add a hit calculation method (like pie)
  });
 
  /** Candles **/
  Flotr.addType('candles', {
  options: {
  show: false, // => setting to true will show candle sticks, false will hide
  lineWidth: 1, // => in pixels
  wickLineWidth: 1, // => in pixels
  candleWidth: 0.6, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  upFillColor: '#00A8F0',// => up sticks fill color
  downFillColor: '#CB4B4B',// => down sticks fill color
  fillOpacity: 0.5, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  // TODO Test this barcharts option.
  barcharts: false // => draw as barcharts (not standard bars but financial barcharts)
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineCap = 'butt';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.wickLineWidth || options.lineWidth;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  width = options.candleWidth / 2,
  shadowSize = options.shadowSize,
  lineWidth = options.lineWidth,
  wickLineWidth = options.wickLineWidth,
  pixelOffset = (wickLineWidth % 2) / 2,
  color,
  datum, x, y,
  open, high, low, close,
  left, right, bottom, top, bottom2, top2,
  i;
 
  if (data.length < 1) return;
 
  for (i = 0; i < data.length; i++) {
  datum = data[i];
  x = datum[0];
  open = datum[1];
  high = datum[2];
  low = datum[3];
  close = datum[4];
  left = xScale(x - width);
  right = xScale(x + width);
  bottom = yScale(low);
  top = yScale(high);
  bottom2 = yScale(Math.min(open, close));
  top2 = yScale(Math.max(open, close));
 
  /*
  // TODO skipping
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
  */
 
  color = options[open > close ? 'downFillColor' : 'upFillColor'];
 
  // Fill the candle.
  // TODO Test the barcharts option
  if (options.fill && !options.barcharts) {
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top2 + shadowSize, right - left, bottom2 - top2);
  context.save();
  context.globalAlpha = options.fillOpacity;
  context.fillStyle = color;
  context.fillRect(left, top2 + lineWidth, right - left, bottom2 - top2);
  context.restore();
  }
 
  // Draw candle outline/border, high, low.
  if (lineWidth || wickLineWidth) {
 
  x = Math.floor((left + right) / 2) + pixelOffset;
 
  context.strokeStyle = color;
  context.beginPath();
 
  // TODO Again with the bartcharts
  if (options.barcharts) {
 
  context.moveTo(x, Math.floor(top + width));
  context.lineTo(x, Math.floor(bottom + width));
 
  y = Math.floor(open + width) + 0.5;
  context.moveTo(Math.floor(left) + pixelOffset, y);
  context.lineTo(x, y);
 
  y = Math.floor(close + width) + 0.5;
  context.moveTo(Math.floor(right) + pixelOffset, y);
  context.lineTo(x, y);
  } else {
  context.strokeRect(left, top2 + lineWidth, right - left, bottom2 - top2);
 
  context.moveTo(x, Math.floor(top2 + lineWidth));
  context.lineTo(x, Math.floor(top + lineWidth));
  context.moveTo(x, Math.floor(bottom2 + lineWidth));
  context.lineTo(x, Math.floor(bottom + lineWidth));
  }
 
  context.closePath();
  context.stroke();
  }
  }
  },
  extendXRange: function (axis, data, options) {
  if (axis.options.max === null) {
  axis.max = Math.max(axis.datamax + 0.5, axis.max);
  axis.min = Math.min(axis.datamin - 0.5, axis.min);
  }
  }
  });
 
  /** Gantt
  * Base on data in form [s,y,d] where:
  * y - executor or simply y value
  * s - task start value
  * d - task duration
  * **/
  Flotr.addType('gantt', {
  options: {
  show: false, // => setting to true will show gantt, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  centered: true // => center the bars to their x axis value
  },
  /**
  * Draws gantt series in the canvas element.
  * @param {Object} series - Series with options.gantt.show = true.
  */
  draw: function(series) {
  var ctx = this.ctx,
  bw = series.gantt.barWidth,
  lw = Math.min(series.gantt.lineWidth, bw);
 
  ctx.save();
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
  ctx.lineJoin = 'miter';
 
  /**
  * @todo linewidth not interpreted the right way.
  */
  ctx.lineWidth = lw;
  ctx.strokeStyle = series.color;
 
  ctx.save();
  this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
  ctx.restore();
 
  if(series.gantt.fill){
  var color = series.gantt.fillColor || series.color;
  ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
  }
 
  this.gantt.plot(series, bw, 0, series.gantt.fill);
  ctx.restore();
  },
  plot: function(series, barWidth, offset, fill){
  var data = series.data;
  if(data.length < 1) return;
 
  var xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx, i;
 
  for(i = 0; i < data.length; i++){
  var y = data[i][0],
  s = data[i][1],
  d = data[i][2],
  drawLeft = true, drawTop = true, drawRight = true;
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min){
  left = xa.min;
  drawLeft = false;
  }
 
  if(right > xa.max){
  right = xa.max;
  if (xa.lastSerie != series)
  drawTop = false;
  }
 
  if(bottom < ya.min)
  bottom = ya.min;
 
  if(top > ya.max){
  top = ya.max;
  if (ya.lastSerie != series)
  drawTop = false;
  }
 
  /**
  * Fill the bar.
  */
  if(fill){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
  ctx.lineTo(xa.d2p(left), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(bottom) + offset);
  ctx.fill();
  ctx.closePath();
  }
 
  /**
  * Draw bar outline/border.
  */
  if(series.gantt.lineWidth && (drawLeft || drawRight || drawTop)){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
 
  ctx[drawLeft ?'lineTo':'moveTo'](xa.d2p(left), ya.d2p(top) + offset);
  ctx[drawTop ?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(top) + offset);
  ctx[drawRight?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(bottom) + offset);
 
  ctx.stroke();
  ctx.closePath();
  }
  }
  },
  plotShadows: function(series, barWidth, offset){
  var data = series.data;
  if(data.length < 1) return;
 
  var i, y, s, d,
  xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx,
  sw = this.options.shadowSize;
 
  for(i = 0; i < data.length; i++){
  y = data[i][0];
  s = data[i][1];
  d = data[i][2];
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min) left = xa.min;
  if(right > xa.max) right = xa.max;
  if(bottom < ya.min) bottom = ya.min;
  if(top > ya.max) top = ya.max;
 
  var width = xa.d2p(right)-xa.d2p(left)-((xa.d2p(right)+sw <= this.plotWidth) ? 0 : sw);
  var height = ya.d2p(bottom)-ya.d2p(top)-((ya.d2p(bottom)+sw <= this.plotHeight) ? 0 : sw );
 
  ctx.fillStyle = 'rgba(0,0,0,0.05)';
  ctx.fillRect(Math.min(xa.d2p(left)+sw, this.plotWidth), Math.min(ya.d2p(top)+sw, this.plotHeight), width, height);
  }
  },
  extendXRange: function(axis) {
  if(axis.options.max === null){
  var newmin = axis.min,
  newmax = axis.max,
  i, j, x, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if(g.show && s.xaxis == axis) {
  for (j = 0; j < s.data.length; j++) {
  if (g.show) {
  y = s.data[j][0]+'';
  stackedSumsPos[y] = Math.max((stackedSumsPos[y] || 0), s.data[j][1]+s.data[j][2]);
  lastSerie = s;
  }
  }
  for (j in stackedSumsPos) {
  newmax = Math.max(stackedSumsPos[j], newmax);
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  }
  },
  extendYRange: function(axis){
  if(axis.options.max === null){
  var newmax = Number.MIN_VALUE,
  newmin = Number.MAX_VALUE,
  i, j, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if (g.show && !s.hide && s.yaxis == axis) {
  var datamax = Number.MIN_VALUE, datamin = Number.MAX_VALUE;
  for(j=0; j < s.data.length; j++){
  datamax = Math.max(datamax,s.data[j][0]);
  datamin = Math.min(datamin,s.data[j][0]);
  }
 
  if (g.centered) {
  newmax = Math.max(datamax + 0.5, newmax);
  newmin = Math.min(datamin - 0.5, newmin);
  }
  else {
  newmax = Math.max(datamax + 1, newmax);
  newmin = Math.min(datamin, newmin);
  }
  // For normal horizontal bars
  if (g.barWidth + datamax > newmax){
  newmax = axis.max + g.barWidth;
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  axis.tickSize = Flotr.getTickSize(axis.options.noTicks, newmin, newmax, axis.options.tickDecimals);
  }
  }
  });
 
  /** Markers **/
  /**
  * Formats the marker labels.
  * @param {Object} obj - Marker value Object {x:..,y:..}
  * @return {String} Formatted marker string
  */
  (function () {
 
  Flotr.defaultMarkerFormatter = function(obj){
  return (Math.round(obj.y*100)/100)+'';
  };
 
  Flotr.addType('markers', {
  options: {
  show: false, // => setting to true will show markers, false will hide
  lineWidth: 1, // => line width of the rectangle around the marker
  color: '#000000', // => text color
  fill: false, // => fill or not the marekers' rectangles
  fillColor: "#FFFFFF", // => fill color
  fillOpacity: 0.4, // => fill opacity
  stroke: false, // => draw the rectangle around the markers
  position: 'ct', // => the markers position (vertical align: b, m, t, horizontal align: l, c, r)
  verticalMargin: 0, // => the margin between the point and the text.
  labelFormatter: Flotr.defaultMarkerFormatter,
  fontSize: Flotr.defaultOptions.fontSize,
  stacked: false, // => true if markers should be stacked
  stackingType: 'b', // => define staching behavior, (b- bars like, a - area like) (see Issue 125 for details)
  horizontal: false // => true if markers should be horizontal (For now only in a case on horizontal stacked bars, stacks should be calculated horizontaly)
  },
 
  // TODO test stacked markers.
  stack : {
  positive : [],
  negative : [],
  values : []
  },
 
  draw : function (options) {
 
  var
  data = options.data,
  context = options.context,
  stack = options.stacked ? options.stack : false,
  stackType = options.stackingType,
  stackOffsetNeg,
  stackOffsetPos,
  stackOffset,
  i, x, y, label;
 
  context.save();
  context.lineJoin = 'round';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = 'rgba(0,0,0,0.5)';
  context.fillStyle = options.fillStyle;
 
  function stackPos (a, b) {
  stackOffsetPos = stack.negative[a] || 0;
  stackOffsetNeg = stack.positive[a] || 0;
  if (b > 0) {
  stack.positive[a] = stackOffsetPos + b;
  return stackOffsetPos + b;
  } else {
  stack.negative[a] = stackOffsetNeg + b;
  return stackOffsetNeg + b;
  }
  }
 
  for (i = 0; i < data.length; ++i) {
 
  x = data[i][0];
  y = data[i][1];
 
  if (stack) {
  if (stackType == 'b') {
  if (options.horizontal) y = stackPos(y, x);
  else x = stackPos(x, y);
  } else if (stackType == 'a') {
  stackOffset = stack.values[x] || 0;
  stack.values[x] = stackOffset + y;
  y = stackOffset + y;
  }
  }
 
  label = options.labelFormatter({x: x, y: y, index: i, data : data});
  this.plot(options.xScale(x), options.yScale(y), label, options);
  }
  context.restore();
  },
  plot: function(x, y, label, options) {
  var context = options.context;
  if (isImage(label) && !label.complete) {
  throw 'Marker image not loaded.';
  } else {
  this._plot(x, y, label, options);
  }
  },
 
  _plot: function(x, y, label, options) {
  var context = options.context,
  margin = 2,
  left = x,
  top = y,
  dim;
 
  if (isImage(label))
  dim = {height : label.height, width: label.width};
  else
  dim = options.text.canvas(label);
 
  dim.width = Math.floor(dim.width+margin*2);
  dim.height = Math.floor(dim.height+margin*2);
 
  if (options.position.indexOf('c') != -1) left -= dim.width/2 + margin;
  else if (options.position.indexOf('l') != -1) left -= dim.width;
 
  if (options.position.indexOf('m') != -1) top -= dim.height/2 + margin;
  else if (options.position.indexOf('t') != -1) top -= dim.height + options.verticalMargin;
  else top += options.verticalMargin;
 
  left = Math.floor(left)+0.5;
  top = Math.floor(top)+0.5;
 
  if(options.fill)
  context.fillRect(left, top, dim.width, dim.height);
 
  if(options.stroke)
  context.strokeRect(left, top, dim.width, dim.height);
 
  if (isImage(label))
  context.drawImage(label, left+margin, top+margin);
  else
  Flotr.drawText(context, label, left+margin, top+margin, {textBaseline: 'top', textAlign: 'left', size: options.fontSize, color: options.color});
  }
  });
 
  function isImage (i) {
  return typeof i === 'object' && i.constructor && (Image ? true : i.constructor === Image);
  }
 
  })();
 
  /**
  * Pie
  *
  * Formats the pies labels.
  * @param {Object} slice - Slice object
  * @return {String} Formatted pie label string
  */
  (function () {
 
  var
  _ = Flotr._;
 
  Flotr.defaultPieLabelFormatter = function (total, value) {
  return (100 * value / total).toFixed(2)+'%';
  };
 
  Flotr.addType('pie', {
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 1, // => in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.6, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  explode: 6, // => the number of pixels the splices will be far from the center
  sizeRatio: 0.6, // => the size ratio of the pie relative to the plot
  startAngle: Math.PI/4, // => the first slice start angle
  labelFormatter: Flotr.defaultPieLabelFormatter,
  pie3D: false, // => whether to draw the pie in 3 dimenstions or not (ineffective)
  pie3DviewAngle: (Math.PI/2 * 0.8),
  pie3DspliceThickness: 20,
  epsilon: 0.1 // => how close do you have to get to hit empty slice
  },
 
  draw : function (options) {
 
  // TODO 3D charts what?
 
  var
  data = options.data,
  context = options.context,
  canvas = context.canvas,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  sizeRatio = options.sizeRatio,
  height = options.height,
  width = options.width,
  explode = options.explode,
  color = options.color,
  fill = options.fill,
  fillStyle = options.fillStyle,
  radius = Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  value = data[0][1],
  html = [],
  vScale = 1,//Math.cos(series.pie.viewAngle);
  measure = Math.PI * 2 * value / this.total,
  startAngle = this.startAngle || (2 * Math.PI * options.startAngle), // TODO: this initial startAngle is already in radians (fixing will be test-unstable)
  endAngle = startAngle + measure,
  bisection = startAngle + measure / 2,
  label = options.labelFormatter(this.total, value),
  //plotTickness = Math.sin(series.pie.viewAngle)*series.pie.spliceThickness / vScale;
  explodeCoeff = explode + radius + 4,
  distX = Math.cos(bisection) * explodeCoeff,
  distY = Math.sin(bisection) * explodeCoeff,
  textAlign = distX < 0 ? 'right' : 'left',
  textBaseline = distY > 0 ? 'top' : 'bottom',
  style,
  x, y;
 
  context.save();
  context.translate(width / 2, height / 2);
  context.scale(1, vScale);
 
  x = Math.cos(bisection) * explode;
  y = Math.sin(bisection) * explode;
 
  // Shadows
  if (shadowSize > 0) {
  this.plotSlice(x + shadowSize, y + shadowSize, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = 'rgba(0,0,0,0.1)';
  context.fill();
  }
  }
 
  this.plotSlice(x, y, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = fillStyle;
  context.fill();
  }
  context.lineWidth = lineWidth;
  context.strokeStyle = color;
  context.stroke();
 
  style = {
  size : options.fontSize * 1.2,
  color : options.fontColor,
  weight : 1.5
  };
 
  if (label) {
  if (options.htmlText || !options.textEnabled) {
  divStyle = 'position:absolute;' + textBaseline + ':' + (height / 2 + (textBaseline === 'top' ? distY : -distY)) + 'px;';
  divStyle += textAlign + ':' + (width / 2 + (textAlign === 'right' ? -distX : distX)) + 'px;';
  html.push('<div style="', divStyle, '" class="flotr-grid-label">', label, '</div>');
  }
  else {
  style.textAlign = textAlign;
  style.textBaseline = textBaseline;
  Flotr.drawText(context, label, distX, distY, style);
  }
  }
 
  if (options.htmlText || !options.textEnabled) {
  var div = Flotr.DOM.node('<div style="color:' + options.fontColor + '" class="flotr-labels"></div>');
  Flotr.DOM.insert(div, html.join(''));
  Flotr.DOM.insert(options.element, div);
  }
 
  context.restore();
 
  // New start angle
  this.startAngle = endAngle;
  this.slices = this.slices || [];
  this.slices.push({
  radius : Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  x : x,
  y : y,
  explode : explode,
  start : startAngle,
  end : endAngle
  });
  },
  plotSlice : function (x, y, radius, startAngle, endAngle, context) {
  context.beginPath();
  context.moveTo(x, y);
  context.arc(x, y, radius, startAngle, endAngle, false);
  context.lineTo(x, y);
  context.closePath();
  },
  hit : function (options) {
 
  var
  data = options.data[0],
  args = options.args,
  index = options.index,
  mouse = args[0],
  n = args[1],
  slice = this.slices[index],
  x = mouse.relX - options.width / 2,
  y = mouse.relY - options.height / 2,
  r = Math.sqrt(x * x + y * y),
  theta = Math.atan(y / x),
  circle = Math.PI * 2,
  explode = slice.explode || options.explode,
  start = slice.start % circle,
  end = slice.end % circle,
  epsilon = options.epsilon;
 
  if (x < 0) {
  theta += Math.PI;
  } else if (x > 0 && y < 0) {
  theta += circle;
  }
 
  if (r < slice.radius + explode && r > explode) {
  if (
  (theta > start && theta < end) || // Normal Slice
  (start > end && (theta < end || theta > start)) || // First slice
  // TODO: Document the two cases at the end:
  (start === end && ((slice.start === slice.end && Math.abs(theta - start) < epsilon) || (slice.start !== slice.end && Math.abs(theta-start) > epsilon)))
  ) {
 
  // TODO Decouple this from hit plugin (chart shouldn't know what n means)
  n.x = data[0];
  n.y = data[1];
  n.sAngle = start;
  n.eAngle = end;
  n.index = 0;
  n.seriesIndex = index;
  n.fraction = data[1] / this.total;
  }
  }
  },
  drawHit: function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex];
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  this.plotSlice(slice.x, slice.y, slice.radius, slice.start, slice.end, context);
  context.stroke();
  context.restore();
  },
  clearHit : function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex],
  padding = 2 * options.lineWidth,
  radius = slice.radius + padding;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.clearRect(
  slice.x - radius,
  slice.y - radius,
  2 * radius + padding,
  2 * radius + padding
  );
  context.restore();
  },
  extendYRange : function (axis, data) {
  this.total = (this.total || 0) + data[0][1];
  }
  });
  })();
 
  /** Points **/
  Flotr.addType('points', {
  options: {
  show: false, // => setting to true will show points, false will hide
  radius: 3, // => point radius (pixels)
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the points with a color, false for (transparent) no fill
  fillColor: '#FFFFFF', // => fill color. Null to use series color.
  fillOpacity: 1, // => opacity of color inside the points
  hitRadius: null // => override for points hit radius
  },
 
  draw : function (options) {
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize;
 
  context.save();
 
  if (shadowSize > 0) {
  context.lineWidth = shadowSize / 2;
 
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 2 + context.lineWidth / 2);
 
  context.strokeStyle = 'rgba(0,0,0,0.2)';
  this.plot(options, context.lineWidth / 2);
  }
 
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
  context.restore();
  },
 
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  i, x, y;
 
  for (i = data.length - 1; i > -1; --i) {
  y = data[i][1];
  if (y === null) continue;
 
  x = xScale(data[i][0]);
  y = yScale(y);
 
  if (x < 0 || x > options.width || y < 0 || y > options.height) continue;
 
  context.beginPath();
  if (offset) {
  context.arc(x, y + offset, options.radius, 0, Math.PI, false);
  } else {
  context.arc(x, y, options.radius, 0, 2 * Math.PI, true);
  if (options.fill) context.fill();
  }
  context.stroke();
  context.closePath();
  }
  }
  });
 
  /** Radar **/
  Flotr.addType('radar', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  radiusRatio: 0.90 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.lineWidth = options.lineWidth;
 
  // Shadow
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  radius = Math.min(options.height, options.width) * options.radiusRatio / 2,
  step = 2 * Math.PI / data.length,
  angle = -Math.PI / 2,
  i, ratio;
 
  offset = offset || 0;
 
  context.beginPath();
  for (i = 0; i < data.length; ++i) {
  ratio = data[i][1] / this.max;
 
  context[i === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(i * step + angle) * radius * ratio + offset,
  Math.sin(i * step + angle) * radius * ratio + offset
  );
  }
  context.closePath();
  if (options.fill) context.fill();
  context.stroke();
  },
  extendYRange : function (axis, data) {
  this.max = Math.max(axis.max, this.max || -Number.MAX_VALUE);
  }
  });
 
  Flotr.addType('timeline', {
  options: {
  show: false,
  lineWidth: 1,
  barWidth: 0.2,
  fill: true,
  fillColor: null,
  fillOpacity: 0.4,
  centered: true
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  barWidth = options.barWidth,
  lineWidth = options.lineWidth,
  i;
 
  Flotr._.each(data, function (timeline) {
 
  var
  x = timeline[0],
  y = timeline[1],
  w = timeline[2],
  h = barWidth,
 
  xt = Math.ceil(xScale(x)),
  wt = Math.ceil(xScale(x + w)) - xt,
  yt = Math.round(yScale(y)),
  ht = Math.round(yScale(y - h)) - yt,
 
  x0 = xt - lineWidth / 2,
  y0 = Math.round(yt - ht / 2) - lineWidth / 2;
 
  context.strokeRect(x0, y0, wt, ht);
  context.fillRect(x0, y0, wt, ht);
 
  });
  },
 
  extendRange : function (series) {
 
  var
  data = series.data,
  xa = series.xaxis,
  ya = series.yaxis,
  w = series.timeline.barWidth;
 
  if (xa.options.min === null)
  xa.min = xa.datamin - w / 2;
 
  if (xa.options.max === null) {
 
  var
  max = xa.max;
 
  Flotr._.each(data, function (timeline) {
  max = Math.max(max, timeline[0] + timeline[2]);
  }, this);
 
  xa.max = max + w / 2;
  }
 
  if (ya.options.min === null)
  ya.min = ya.datamin - w;
  if (ya.options.min === null)
  ya.max = ya.datamax + w;
  }
 
  });
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('crosshair', {
  options: {
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#FF0000', // => crosshair color
  hideCursor: true // => hide the cursor when the crosshair is shown
  },
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  if (this.options.crosshair.mode) {
  this.crosshair.clearCrosshair();
  this.crosshair.drawCrosshair(pos);
  }
  }
  },
  /**
  * Draws the selection box.
  */
  drawCrosshair: function(pos) {
  var octx = this.octx,
  options = this.options.crosshair,
  plotOffset = this.plotOffset,
  x = plotOffset.left + Math.round(pos.relX) + 0.5,
  y = plotOffset.top + Math.round(pos.relY) + 0.5;
 
  if (pos.relX < 0 || pos.relY < 0 || pos.relX > this.plotWidth || pos.relY > this.plotHeight) {
  this.el.style.cursor = null;
  D.removeClass(this.el, 'flotr-crosshair');
  return;
  }
 
  if (options.hideCursor) {
  this.el.style.cursor = 'none';
  D.addClass(this.el, 'flotr-crosshair');
  }
 
  octx.save();
  octx.strokeStyle = options.color;
  octx.lineWidth = 1;
  octx.beginPath();
 
  if (options.mode.indexOf('x') != -1) {
  octx.moveTo(x, plotOffset.top);
  octx.lineTo(x, plotOffset.top + this.plotHeight);
  }
 
  if (options.mode.indexOf('y') != -1) {
  octx.moveTo(plotOffset.left, y);
  octx.lineTo(plotOffset.left + this.plotWidth, y);
  }
 
  octx.stroke();
  octx.restore();
  },
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearCrosshair: function() {
 
  var
  plotOffset = this.plotOffset,
  position = this.lastMousePos,
  context = this.octx;
 
  if (position) {
  context.clearRect(
  Math.round(position.relX) + plotOffset.left,
  plotOffset.top,
  1,
  this.plotHeight + 1
  );
  context.clearRect(
  plotOffset.left,
  Math.round(position.relY) + plotOffset.top,
  this.plotWidth + 1,
  1
  );
  }
  }
  });
  })();
 
  (function() {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  function getImage (type, canvas, width, height) {
 
  // TODO add scaling for w / h
  var
  mime = 'image/'+type,
  data = canvas.toDataURL(mime),
  image = new Image();
  image.src = data;
  return image;
  }
 
  Flotr.addPlugin('download', {
 
  saveImage: function (type, width, height, replaceCanvas) {
  var image = null;
  if (Flotr.isIE && Flotr.isIE < 9) {
  image = '<html><body>'+this.canvas.firstChild.innerHTML+'</body></html>';
  return window.open().document.write(image);
  }
 
  if (type !== 'jpeg' && type !== 'png') return;
 
  image = getImage(type, this.canvas, width, height);
 
  if (_.isElement(image) && replaceCanvas) {
  this.download.restoreCanvas();
  D.hide(this.canvas);
  D.hide(this.overlay);
  D.setStyles({position: 'absolute'});
  D.insert(this.el, image);
  this.saveImageElement = image;
  } else {
  return window.open(image.src);
  }
  },
 
  restoreCanvas: function() {
  D.show(this.canvas);
  D.show(this.overlay);
  if (this.saveImageElement) this.el.removeChild(this.saveImageElement);
  this.saveImageElement = null;
  }
  });
 
  })();
 
  (function () {
 
  var E = Flotr.EventAdapter,
  _ = Flotr._;
 
  Flotr.addPlugin('graphGrid', {
 
  callbacks: {
  'flotr:beforedraw' : function () {
  this.graphGrid.drawGrid();
  },
  'flotr:afterdraw' : function () {
  this.graphGrid.drawOutline();
  }
  },
 
  drawGrid: function(){
 
  var
  ctx = this.ctx,
  options = this.options,
  grid = options.grid,
  verticalLines = grid.verticalLines,
  horizontalLines = grid.horizontalLines,
  minorVerticalLines = grid.minorVerticalLines,
  minorHorizontalLines = grid.minorHorizontalLines,
  plotHeight = this.plotHeight,
  plotWidth = this.plotWidth,
  a, v, i, j;
 
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:beforegrid', [this.axes.x, this.axes.y, options, this]);
  }
  ctx.save();
  ctx.lineWidth = 1;
  ctx.strokeStyle = grid.tickColor;
 
  function circularHorizontalTicks (ticks) {
  for(i = 0; i < ticks.length; ++i){
  var ratio = ticks[i].v / a.max;
  for(j = 0; j <= sides; ++j){
  ctx[j === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(j*coeff+angle)*radius*ratio,
  Math.sin(j*coeff+angle)*radius*ratio
  );
  }
  }
  }
  function drawGridLines (ticks, callback) {
  _.each(_.pluck(ticks, 'v'), function(v){
  // Don't show lines on upper and lower bounds.
  if ((v <= a.min || v >= a.max) ||
  (v == a.min || v == a.max) && grid.outlineWidth)
  return;
  callback(Math.floor(a.d2p(v)) + ctx.lineWidth/2);
  });
  }
  function drawVerticalLines (x) {
  ctx.moveTo(x, 0);
  ctx.lineTo(x, plotHeight);
  }
  function drawHorizontalLines (y) {
  ctx.moveTo(0, y);
  ctx.lineTo(plotWidth, y);
  }
 
  if (grid.circular) {
  ctx.translate(this.plotOffset.left+plotWidth/2, this.plotOffset.top+plotHeight/2);
  var radius = Math.min(plotHeight, plotWidth)*options.radar.radiusRatio/2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw grid lines in vertical direction.
  ctx.beginPath();
 
  a = this.axes.y;
 
  if(horizontalLines){
  circularHorizontalTicks(a.ticks);
  }
  if(minorHorizontalLines){
  circularHorizontalTicks(a.minorTicks);
  }
 
  if(verticalLines){
  _.times(sides, function(i){
  ctx.moveTo(0, 0);
  ctx.lineTo(Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  });
  }
  ctx.stroke();
  }
  else {
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
 
  // Draw grid background, if present in options.
  if(grid.backgroundColor){
  ctx.fillStyle = this.processColor(grid.backgroundColor, {x1: 0, y1: 0, x2: plotWidth, y2: plotHeight});
  ctx.fillRect(0, 0, plotWidth, plotHeight);
  }
 
  ctx.beginPath();
 
  a = this.axes.x;
  if (verticalLines) drawGridLines(a.ticks, drawVerticalLines);
  if (minorVerticalLines) drawGridLines(a.minorTicks, drawVerticalLines);
 
  a = this.axes.y;
  if (horizontalLines) drawGridLines(a.ticks, drawHorizontalLines);
  if (minorHorizontalLines) drawGridLines(a.minorTicks, drawHorizontalLines);
 
  ctx.stroke();
  }
 
  ctx.restore();
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:aftergrid', [this.axes.x, this.axes.y, options, this]);
  }
  },
 
  drawOutline: function(){
  var
  that = this,
  options = that.options,
  grid = options.grid,
  outline = grid.outline,
  ctx = that.ctx,
  backgroundImage = grid.backgroundImage,
  plotOffset = that.plotOffset,
  leftOffset = plotOffset.left,
  topOffset = plotOffset.top,
  plotWidth = that.plotWidth,
  plotHeight = that.plotHeight,
  v, img, src, left, top, globalAlpha;
 
  if (!grid.outlineWidth) return;
 
  ctx.save();
 
  if (grid.circular) {
  ctx.translate(leftOffset + plotWidth / 2, topOffset + plotHeight / 2);
  var radius = Math.min(plotHeight, plotWidth) * options.radar.radiusRatio / 2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw axis/grid border.
  ctx.beginPath();
  ctx.lineWidth = grid.outlineWidth;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'round';
 
  for(i = 0; i <= sides; ++i){
  ctx[i === 0 ? 'moveTo' : 'lineTo'](Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  }
  //ctx.arc(0, 0, radius, 0, Math.PI*2, true);
 
  ctx.stroke();
  }
  else {
  ctx.translate(leftOffset, topOffset);
 
  // Draw axis/grid border.
  var lw = grid.outlineWidth,
  orig = 0.5-lw+((lw+1)%2/2),
  lineTo = 'lineTo',
  moveTo = 'moveTo';
  ctx.lineWidth = lw;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'miter';
  ctx.beginPath();
  ctx.moveTo(orig, orig);
  plotWidth = plotWidth - (lw / 2) % 1;
  plotHeight = plotHeight + lw / 2;
  ctx[outline.indexOf('n') !== -1 ? lineTo : moveTo](plotWidth, orig);
  ctx[outline.indexOf('e') !== -1 ? lineTo : moveTo](plotWidth, plotHeight);
  ctx[outline.indexOf('s') !== -1 ? lineTo : moveTo](orig, plotHeight);
  ctx[outline.indexOf('w') !== -1 ? lineTo : moveTo](orig, orig);
  ctx.stroke();
  ctx.closePath();
  }
 
  ctx.restore();
 
  if (backgroundImage) {
 
  src = backgroundImage.src || backgroundImage;
  left = (parseInt(backgroundImage.left, 10) || 0) + plotOffset.left;
  top = (parseInt(backgroundImage.top, 10) || 0) + plotOffset.top;
  img = new Image();
 
  img.onload = function() {
  ctx.save();
  if (backgroundImage.alpha) ctx.globalAlpha = backgroundImage.alpha;
  ctx.globalCompositeOperation = 'destination-over';
  ctx.drawImage(img, 0, 0, img.width, img.height, left, top, plotWidth, plotHeight);
  ctx.restore();
  };
 
  img.src = src;
  }
  }
  });
 
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._,
  flotr = Flotr,
  S_MOUSETRACK = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;';
 
  Flotr.addPlugin('hit', {
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  this.hit.track(pos);
  },
  'flotr:click': function(pos) {
  var
  hit = this.hit.track(pos);
  _.defaults(pos, hit);
  },
  'flotr:mouseout': function() {
  this.hit.clearHit();
  },
  'flotr:destroy': function() {
  this.mouseTrack = null;
  }
  },
  track : function (pos) {
  if (this.options.mouse.track || _.any(this.series, function(s){return s.mouse && s.mouse.track;})) {
  return this.hit.hit(pos);
  }
  },
  /**
  * Try a method on a graph type. If the method exists, execute it.
  * @param {Object} series
  * @param {String} method Method name.
  * @param {Array} args Arguments applied to method.
  * @return executed successfully or failed.
  */
  executeOnType: function(s, method, args){
  var
  success = false,
  options;
 
  if (!_.isArray(s)) s = [s];
 
  function e(s, index) {
  _.each(_.keys(flotr.graphTypes), function (type) {
  if (s[type] && s[type].show && this[type][method]) {
  options = this.getOptions(s, type);
 
  options.fill = !!s.mouse.fillColor;
  options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  options.color = s.mouse.lineColor;
  options.context = this.octx;
  options.index = index;
 
  if (args) options.args = args;
  this[type][method].call(this[type], options);
  success = true;
  }
  }, this);
  }
  _.each(s, e, this);
 
  return success;
  },
  /**
  * Updates the mouse tracking point on the overlay.
  */
  drawHit: function(n){
  var octx = this.octx,
  s = n.series;
 
  if (s.mouse.lineColor) {
  octx.save();
  octx.lineWidth = (s.points ? s.points.lineWidth : 1);
  octx.strokeStyle = s.mouse.lineColor;
  octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  octx.translate(this.plotOffset.left, this.plotOffset.top);
 
  if (!this.hit.executeOnType(s, 'drawHit', n)) {
  var
  xa = n.xaxis,
  ya = n.yaxis;
 
  octx.beginPath();
  // TODO fix this (points) should move to general testable graph mixin
  octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.hitRadius || s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
  octx.fill();
  octx.stroke();
  octx.closePath();
  }
  octx.restore();
  this.clip(octx);
  }
  this.prevHit = n;
  },
  /**
  * Removes the mouse tracking point from the overlay.
  */
  clearHit: function(){
  var prev = this.prevHit,
  octx = this.octx,
  plotOffset = this.plotOffset;
  octx.save();
  octx.translate(plotOffset.left, plotOffset.top);
  if (prev) {
  if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
  // TODO fix this (points) should move to general testable graph mixin
  var
  s = prev.series,
  lw = (s.points ? s.points.lineWidth : 1);
  offset = (s.points.hitRadius || s.points.radius || s.mouse.radius) + lw;
  octx.clearRect(
  prev.xaxis.d2p(prev.x) - offset,
  prev.yaxis.d2p(prev.y) - offset,
  offset*2,
  offset*2
  );
  }
  D.hide(this.mouseTrack);
  this.prevHit = null;
  }
  octx.restore();
  },
  /**
  * Retrieves the nearest data point from the mouse cursor. If it's within
  * a certain range, draw a point on the overlay canvas and display the x and y
  * value of the data.
  * @param {Object} mouse - Object that holds the relative x and y coordinates of the cursor.
  */
  hit : function (mouse) {
 
  var
  options = this.options,
  prevHit = this.prevHit,
  closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n;
 
  if (this.series.length === 0) return;
 
  // Nearest data element.
  // dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
  // xaxis, yaxis, series, index, seriesIndex
  n = {
  relX : mouse.relX,
  relY : mouse.relY,
  absX : mouse.absX,
  absY : mouse.absY
  };
 
  if (options.mouse.trackY &&
  !options.mouse.trackAll &&
  this.hit.executeOnType(this.series, 'hit', [mouse, n]) &&
  !_.isUndefined(n.seriesIndex))
  {
  series = this.series[n.seriesIndex];
  n.series = series;
  n.mouse = series.mouse;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  } else {
 
  closest = this.hit.closest(mouse);
 
  if (closest) {
 
  closest = options.mouse.trackY ? closest.point : closest.x;
  seriesIndex = closest.seriesIndex;
  series = this.series[seriesIndex];
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  sensibility = 2 * series.mouse.sensibility;
 
  if
  (options.mouse.trackAll ||
  (closest.distanceX < sensibility / xaxis.scale &&
  (!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale)))
  {
  n.series = series;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  n.mouse = series.mouse;
  n.x = closest.x;
  n.y = closest.y;
  n.dist = closest.distance;
  n.index = closest.dataIndex;
  n.seriesIndex = seriesIndex;
  }
  }
  }
 
  if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
  this.hit.clearHit();
  if (n.series && n.mouse && n.mouse.track) {
  this.hit.drawMouseTrack(n);
  this.hit.drawHit(n);
  Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
  }
  }
 
  return n;
  },
 
  closest : function (mouse) {
 
  var
  series = this.series,
  options = this.options,
  relX = mouse.relX,
  relY = mouse.relY,
  compare = Number.MAX_VALUE,
  compareX = Number.MAX_VALUE,
  closest = {},
  closestX = {},
  check = false,
  serie, data,
  distance, distanceX, distanceY,
  mouseX, mouseY,
  x, y, i, j;
 
  function setClosest (o) {
  o.distance = distance;
  o.distanceX = distanceX;
  o.distanceY = distanceY;
  o.seriesIndex = i;
  o.dataIndex = j;
  o.x = x;
  o.y = y;
  check = true;
  }
 
  for (i = 0; i < series.length; i++) {
 
  serie = series[i];
  data = serie.data;
  mouseX = serie.xaxis.p2d(relX);
  mouseY = serie.yaxis.p2d(relY);
 
  for (j = data.length; j--;) {
 
  x = data[j][0];
  y = data[j][1];
 
  if (x === null || y === null) continue;
 
  // don't check if the point isn't visible in the current range
  if (x < serie.xaxis.min || x > serie.xaxis.max) continue;
 
  distanceX = Math.abs(x - mouseX);
  distanceY = Math.abs(y - mouseY);
 
  // Skip square root for speed
  distance = distanceX * distanceX + distanceY * distanceY;
 
  if (distance < compare) {
  compare = distance;
  setClosest(closest);
  }
 
  if (distanceX < compareX) {
  compareX = distanceX;
  setClosest(closestX);
  }
  }
  }
 
  return check ? {
  point : closest,
  x : closestX
  } : false;
  },
 
  drawMouseTrack : function (n) {
 
  var
  pos = '',
  s = n.series,
  p = n.mouse.position,
  m = n.mouse.margin,
  x = n.x,
  y = n.y,
  elStyle = S_MOUSETRACK,
  mouseTrack = this.mouseTrack,
  plotOffset = this.plotOffset,
  left = plotOffset.left,
  right = plotOffset.right,
  bottom = plotOffset.bottom,
  top = plotOffset.top,
  decimals = n.mouse.trackDecimals,
  options = this.options;
 
  // Create
  if (!mouseTrack) {
  mouseTrack = D.node('<div class="flotr-mouse-value"></div>');
  this.mouseTrack = mouseTrack;
  D.insert(this.el, mouseTrack);
  }
 
  if (!n.mouse.relative) { // absolute to the canvas
 
  if (p.charAt(0) == 'n') pos += 'top:' + (m + top) + 'px;bottom:auto;';
  else if (p.charAt(0) == 's') pos += 'bottom:' + (m + bottom) + 'px;top:auto;';
  if (p.charAt(1) == 'e') pos += 'right:' + (m + right) + 'px;left:auto;';
  else if (p.charAt(1) == 'w') pos += 'left:' + (m + left) + 'px;right:auto;';
 
  // Pie
  } else if (s.pie && s.pie.show) {
  var center = {
  x: (this.plotWidth)/2,
  y: (this.plotHeight)/2
  },
  radius = (Math.min(this.canvasWidth, this.canvasHeight) * s.pie.sizeRatio) / 2,
  bisection = n.sAngle<n.eAngle ? (n.sAngle + n.eAngle) / 2: (n.sAngle + n.eAngle + 2* Math.PI) / 2;
 
  pos += 'bottom:' + (m - top - center.y - Math.sin(bisection) * radius/2 + this.canvasHeight) + 'px;top:auto;';
  pos += 'left:' + (m + left + center.x + Math.cos(bisection) * radius/2) + 'px;right:auto;';
 
  // Default
  } else {
  if (/n/.test(p)) pos += 'bottom:' + (m - top - n.yaxis.d2p(n.y) + this.canvasHeight) + 'px;top:auto;';
  else pos += 'top:' + (m + top + n.yaxis.d2p(n.y)) + 'px;bottom:auto;';
  if (/w/.test(p)) pos += 'right:' + (m - left - n.xaxis.d2p(n.x) + this.canvasWidth) + 'px;left:auto;';
  else pos += 'left:' + (m + left + n.xaxis.d2p(n.x)) + 'px;right:auto;';
  }
 
  elStyle += pos;
  mouseTrack.style.cssText = elStyle;
  if (!decimals || decimals < 0) decimals = 0;
 
  if (x && x.toFixed) x = x.toFixed(decimals);
 
  if (y && y.toFixed) y = y.toFixed(decimals);
 
  mouseTrack.innerHTML = n.mouse.trackFormatter({
  x: x ,
  y: y,
  series: n.series,
  index: n.index,
  nearest: n,
  fraction: n.fraction
  });
 
  D.show(mouseTrack);
 
  if (n.mouse.relative) {
  if (!/[ew]/.test(p)) {
  // Center Horizontally
  mouseTrack.style.left =
  (left + n.xaxis.d2p(n.x) - D.size(mouseTrack).width / 2) + 'px';
  } else
  if (!/[ns]/.test(p)) {
  // Center Vertically
  mouseTrack.style.top =
  (top + n.yaxis.d2p(n.y) - D.size(mouseTrack).height / 2) + 'px';
  }
  }
  }
 
  });
  })();
 
  /**
  * Selection Handles Plugin
  *
  *
  * Options
  * show - True enables the handles plugin.
  * drag - Left and Right drag handles
  * scroll - Scrolling handle
  */
  (function () {
 
  function isLeftClick (e, type) {
  return (e.which ? (e.which === 1) : (e.button === 0 || e.button === 1));
  }
 
  function boundX(x, graph) {
  return Math.min(Math.max(0, x), graph.plotWidth - 1);
  }
 
  function boundY(y, graph) {
  return Math.min(Math.max(0, y), graph.plotHeight);
  }
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._;
 
 
  Flotr.addPlugin('selection', {
 
  options: {
  pinchOnly: null, // Only select on pinch
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#B6D9FF', // => selection box color
  fps: 20 // => frames-per-second
  },
 
  callbacks: {
  'flotr:mouseup' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (selection.interval) clearInterval(selection.interval);
 
  if (this.multitouches) {
  selection.updateSelection();
  } else
  if (!options.pinchOnly) {
  selection.setSelectionPos(selection.selection.second, pointer);
  }
  selection.clearSelection();
 
  if(selection.selecting && selection.selectionIsSane()){
  selection.drawSelection();
  selection.fireSelectEvent();
  this.ignoreClick = true;
  }
  },
  'flotr:mousedown' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (!options.mode || (!isLeftClick(event) && _.isUndefined(event.touches))) return;
  if (!options.pinchOnly) selection.setSelectionPos(selection.selection.first, pointer);
  if (selection.interval) clearInterval(selection.interval);
 
  this.lastMousePos.pageX = null;
  selection.selecting = false;
  selection.interval = setInterval(
  _.bind(selection.updateSelection, this),
  1000 / options.fps
  );
  },
  'flotr:destroy' : function (event) {
  clearInterval(this.selection.interval);
  }
  },
 
  // TODO This isn't used. Maybe it belongs in the draw area and fire select event methods?
  getArea: function() {
 
  var
  s = this.selection.selection,
  a = this.axes,
  first = s.first,
  second = s.second,
  x1, x2, y1, y2;
 
  x1 = a.x.p2d(s.first.x);
  x2 = a.x.p2d(s.second.x);
  y1 = a.y.p2d(s.first.y);
  y2 = a.y.p2d(s.second.y);
 
  return {
  x1 : Math.min(x1, x2),
  y1 : Math.min(y1, y2),
  x2 : Math.max(x1, x2),
  y2 : Math.max(y1, y2),
  xfirst : x1,
  xsecond : x2,
  yfirst : y1,
  ysecond : y2
  };
  },
 
  selection: {first: {x: -1, y: -1}, second: {x: -1, y: -1}},
  prevSelection: null,
  interval: null,
 
  /**
  * Fires the 'flotr:select' event when the user made a selection.
  */
  fireSelectEvent: function(name){
  var
  area = this.selection.getArea();
  name = name || 'select';
  area.selection = this.selection.selection;
  E.fire(this.el, 'flotr:'+name, [area, this]);
  },
 
  /**
  * Allows the user the manually select an area.
  * @param {Object} area - Object with coordinates to select.
  */
  setSelection: function(area, preventEvent){
  var options = this.options,
  xa = this.axes.x,
  ya = this.axes.y,
  vertScale = ya.scale,
  hozScale = xa.scale,
  selX = options.selection.mode.indexOf('x') != -1,
  selY = options.selection.mode.indexOf('y') != -1,
  s = this.selection.selection;
 
  this.selection.clearSelection();
 
  s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
  s.second.y = boundY((selX && !selY) ? this.plotHeight - 1: (ya.max - area.y2) * vertScale, this);
  s.first.x = boundX((selY && !selX) ? 0 : (area.x1 - xa.min) * hozScale, this);
  s.second.x = boundX((selY && !selX) ? this.plotWidth : (area.x2 - xa.min) * hozScale, this);
 
  this.selection.drawSelection();
  if (!preventEvent)
  this.selection.fireSelectEvent();
  },
 
  /**
  * Calculates the position of the selection.
  * @param {Object} pos - Position object.
  * @param {Event} event - Event object.
  */
  setSelectionPos: function(pos, pointer) {
  var mode = this.options.selection.mode,
  selection = this.selection.selection;
 
  if(mode.indexOf('x') == -1) {
  pos.x = (pos == selection.first) ? 0 : this.plotWidth;
  }else{
  pos.x = boundX(pointer.relX, this);
  }
 
  if (mode.indexOf('y') == -1) {
  pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
  }else{
  pos.y = boundY(pointer.relY, this);
  }
  },
  /**
  * Draws the selection box.
  */
  drawSelection: function() {
 
  this.selection.fireSelectEvent('selecting');
 
  var s = this.selection.selection,
  octx = this.octx,
  options = this.options,
  plotOffset = this.plotOffset,
  prevSelection = this.selection.prevSelection;
 
  if (prevSelection &&
  s.first.x == prevSelection.first.x &&
  s.first.y == prevSelection.first.y &&
  s.second.x == prevSelection.second.x &&
  s.second.y == prevSelection.second.y) {
  return;
  }
 
  octx.save();
  octx.strokeStyle = this.processColor(options.selection.color, {opacity: 0.8});
  octx.lineWidth = 1;
  octx.lineJoin = 'miter';
  octx.fillStyle = this.processColor(options.selection.color, {opacity: 0.4});
 
  this.selection.prevSelection = {
  first: { x: s.first.x, y: s.first.y },
  second: { x: s.second.x, y: s.second.y }
  };
 
  var x = Math.min(s.first.x, s.second.x),
  y = Math.min(s.first.y, s.second.y),
  w = Math.abs(s.second.x - s.first.x),
  h = Math.abs(s.second.y - s.first.y);
 
  octx.fillRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.strokeRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.restore();
  },
 
  /**
  * Updates (draws) the selection box.
  */
  updateSelection: function(){
  if (!this.lastMousePos.pageX) return;
 
  this.selection.selecting = true;
 
  if (this.multitouches) {
  this.selection.setSelectionPos(this.selection.selection.first, this.getEventPosition(this.multitouches[0]));
  this.selection.setSelectionPos(this.selection.selection.second, this.getEventPosition(this.multitouches[1]));
  } else
  if (this.options.selection.pinchOnly) {
  return;
  } else {
  this.selection.setSelectionPos(this.selection.selection.second, this.lastMousePos);
  }
 
  this.selection.clearSelection();
 
  if(this.selection.selectionIsSane()) {
  this.selection.drawSelection();
  }
  },
 
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearSelection: function() {
  if (!this.selection.prevSelection) return;
 
  var prevSelection = this.selection.prevSelection,
  lw = 1,
  plotOffset = this.plotOffset,
  x = Math.min(prevSelection.first.x, prevSelection.second.x),
  y = Math.min(prevSelection.first.y, prevSelection.second.y),
  w = Math.abs(prevSelection.second.x - prevSelection.first.x),
  h = Math.abs(prevSelection.second.y - prevSelection.first.y);
 
  this.octx.clearRect(x + plotOffset.left - lw + 0.5,
  y + plotOffset.top - lw,
  w + 2 * lw + 0.5,
  h + 2 * lw + 0.5);
 
  this.selection.prevSelection = null;
  },
  /**
  * Determines whether or not the selection is sane and should be drawn.
  * @return {Boolean} - True when sane, false otherwise.
  */
  selectionIsSane: function(){
  var s = this.selection.selection;
  return Math.abs(s.second.x - s.first.x) >= 5 ||
  Math.abs(s.second.y - s.first.y) >= 5;
  }
 
  });
 
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('labels', {
 
  callbacks : {
  'flotr:afterdraw' : function () {
  this.labels.draw();
  }
  },
 
  draw: function(){
  // Construct fixed width label boxes, which can be styled easily.
  var
  axis, tick, left, top, xBoxWidth,
  radius, sides, coeff, angle,
  div, i, html = '',
  noLabels = 0,
  options = this.options,
  ctx = this.ctx,
  a = this.axes,
  style = { size: options.fontSize };
 
  for (i = 0; i < a.x.ticks.length; ++i){
  if (a.x.ticks[i].label) { ++noLabels; }
  }
  xBoxWidth = this.plotWidth / noLabels;
 
  if (options.grid.circular) {
  ctx.save();
  ctx.translate(this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top + this.plotHeight / 2);
 
  radius = this.plotHeight * options.radar.radiusRatio / 2 + options.fontSize;
  sides = this.axes.x.ticks.length;
  coeff = 2 * (Math.PI / sides);
  angle = -Math.PI / 2;
 
  drawLabelCircular(this, a.x, false);
  drawLabelCircular(this, a.x, true);
  drawLabelCircular(this, a.y, false);
  drawLabelCircular(this, a.y, true);
  ctx.restore();
  }
 
  if (!options.HtmlText && this.textEnabled) {
  drawLabelNoHtmlText(this, a.x, 'center', 'top');
  drawLabelNoHtmlText(this, a.x2, 'center', 'bottom');
  drawLabelNoHtmlText(this, a.y, 'right', 'middle');
  drawLabelNoHtmlText(this, a.y2, 'left', 'middle');
 
  } else if ((
  a.x.options.showLabels ||
  a.x2.options.showLabels ||
  a.y.options.showLabels ||
  a.y2.options.showLabels) &&
  !options.grid.circular
  ) {
 
  html = '';
 
  drawLabelHtml(this, a.x);
  drawLabelHtml(this, a.x2);
  drawLabelHtml(this, a.y);
  drawLabelHtml(this, a.y2);
 
  ctx.stroke();
  ctx.restore();
  div = D.create('div');
  D.setStyles(div, {
  fontSize: 'smaller',
  color: options.grid.color
  });
  div.className = 'flotr-labels';
  D.insert(this.el, div);
  D.insert(div, html);
  }
 
  function drawLabelCircular (graph, axis, minorTicks) {
  var
  ticks = minorTicks ? axis.minorTicks : axis.ticks,
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  angle : Flotr.toRad(axis.options.labelsAngle),
  textBaseline : 'middle'
  };
 
  for (i = 0; i < ticks.length &&
  (minorTicks ? axis.options.showMinorLabels : axis.options.showLabels); ++i){
  tick = ticks[i];
  tick.label += '';
  if (!tick.label || !tick.label.length) { continue; }
 
  x = Math.cos(i * coeff + angle) * radius;
  y = Math.sin(i * coeff + angle) * radius;
 
  style.textAlign = isX ? (Math.abs(x) < 0.1 ? 'center' : (x < 0 ? 'right' : 'left')) : 'left';
 
  Flotr.drawText(
  ctx, tick.label,
  isX ? x : 3,
  isX ? y : -(axis.ticks[i].v / axis.max) * (radius - options.fontSize),
  style
  );
  }
  }
 
  function drawLabelNoHtmlText (graph, axis, textAlign, textBaseline) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  textAlign : textAlign,
  textBaseline : textBaseline,
  angle : Flotr.toRad(axis.options.labelsAngle)
  };
  style = Flotr.getBestTextAlign(style.angle, style);
 
  for (i = 0; i < axis.ticks.length && continueShowingLabels(axis); ++i) {
 
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length) { continue; }
 
  offset = axis.d2p(tick.v);
  if (offset < 0 ||
  offset > (isX ? graph.plotWidth : graph.plotHeight)) { continue; }
 
  Flotr.drawText(
  ctx, tick.label,
  leftOffset(graph, isX, isFirst, offset),
  topOffset(graph, isX, isFirst, offset),
  style
  );
 
  // Only draw on axis y2
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = style.color;
  ctx.beginPath();
  ctx.moveTo(graph.plotOffset.left + graph.plotWidth - 8, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.lineTo(graph.plotOffset.left + graph.plotWidth, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.stroke();
  ctx.restore();
  }
  }
 
  function continueShowingLabels (axis) {
  return axis.options.showLabels && axis.used;
  }
  function leftOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.left +
  (isX ? offset :
  (isFirst ?
  -options.grid.labelMargin :
  options.grid.labelMargin + graph.plotWidth));
  }
  function topOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.top +
  (isX ? options.grid.labelMargin : offset) +
  ((isX && isFirst) ? graph.plotHeight : 0);
  }
  }
 
  function drawLabelHtml (graph, axis) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  name = '',
  left, style, top,
  offset = graph.plotOffset;
 
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = axis.options.color || options.grid.color;
  ctx.beginPath();
  }
 
  if (axis.options.showLabels && (isFirst ? true : axis.used)) {
  for (i = 0; i < axis.ticks.length; ++i) {
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) < 0) ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) > (isX ? graph.canvasWidth : graph.canvasHeight))) {
  continue;
  }
  top = offset.top +
  (isX ?
  ((isFirst ? 1 : -1 ) * (graph.plotHeight + options.grid.labelMargin)) :
  axis.d2p(tick.v) - axis.maxLabel.height / 2);
  left = isX ? (offset.left + axis.d2p(tick.v) - xBoxWidth / 2) : 0;
 
  name = '';
  if (i === 0) {
  name = ' first';
  } else if (i === axis.ticks.length - 1) {
  name = ' last';
  }
  name += isX ? ' flotr-grid-label-x' : ' flotr-grid-label-y';
 
  html += [
  '<div style="position:absolute; text-align:' + (isX ? 'center' : 'right') + '; ',
  'top:' + top + 'px; ',
  ((!isX && !isFirst) ? 'right:' : 'left:') + left + 'px; ',
  'width:' + (isX ? xBoxWidth : ((isFirst ? offset.left : offset.right) - options.grid.labelMargin)) + 'px; ',
  axis.options.color ? ('color:' + axis.options.color + '; ') : ' ',
  '" class="flotr-grid-label' + name + '">' + tick.label + '</div>'
  ].join(' ');
 
  if (!isX && !isFirst) {
  ctx.moveTo(offset.left + graph.plotWidth - 8, offset.top + axis.d2p(tick.v));
  ctx.lineTo(offset.left + graph.plotWidth, offset.top + axis.d2p(tick.v));
  }
  }
  }
  }
  }
 
  });
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('legend', {
  options: {
  show: true, // => setting to true will show the legend, hide otherwise
  noColumns: 1, // => number of colums in legend table // @todo: doesn't work for HtmlText = false
  labelFormatter: function(v){return v;}, // => fn: string -> string
  labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
  labelBoxWidth: 14,
  labelBoxHeight: 10,
  labelBoxMargin: 5,
  container: null, // => container (as jQuery object) to put legend in, null means default on top of graph
  position: 'nw', // => position of default legend container within plot
  margin: 5, // => distance from grid edge to default legend container within plot
  backgroundColor: '#F0F0F0', // => Legend background color.
  backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
  'flotr:afterinit': function() {
  this.legend.insertLegend();
  },
  'flotr:destroy': function() {
  var markup = this.legend.markup;
  if (markup) {
  this.legend.markup = null;
  D.remove(markup);
  }
  }
  },
  /**
  * Adds a legend div to the canvas container or draws it on the canvas.
  */
  insertLegend: function(){
 
  if(!this.options.legend.show)
  return;
 
  var series = this.series,
  plotOffset = this.plotOffset,
  options = this.options,
  legend = options.legend,
  fragments = [],
  rowStarted = false,
  ctx = this.ctx,
  itemCount = _.filter(series, function(s) {return (s.label && !s.hide);}).length,
  p = legend.position,
  m = legend.margin,
  opacity = legend.backgroundOpacity,
  i, label, color;
 
  if (itemCount) {
 
  var lbw = legend.labelBoxWidth,
  lbh = legend.labelBoxHeight,
  lbm = legend.labelBoxMargin,
  offsetX = plotOffset.left + m,
  offsetY = plotOffset.top + m,
  labelMaxWidth = 0,
  style = {
  size: options.fontSize*1.1,
  color: options.grid.color
  };
 
  // We calculate the labels' max width
  for(i = series.length - 1; i > -1; --i){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
  labelMaxWidth = Math.max(labelMaxWidth, this._text.measureText(label, style).width);
  }
 
  var legendWidth = Math.round(lbw + lbm*3 + labelMaxWidth),
  legendHeight = Math.round(itemCount*(lbm+lbh) + lbm);
 
  // Default Opacity
  if (!opacity && opacity !== 0) {
  opacity = 0.1;
  }
 
  if (!options.HtmlText && this.textEnabled && !legend.container) {
 
  if(p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
  if(p.charAt(0) == 'c') offsetY = plotOffset.top + (this.plotHeight/2) - (m + (legendHeight/2));
  if(p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);
 
  // Legend box
  color = this.processColor(legend.backgroundColor, { opacity : opacity });
 
  ctx.fillStyle = color;
  ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);
 
  // Legend labels
  var x = offsetX + lbm;
  var y = offsetY + lbm;
  for(i = 0; i < series.length; i++){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
 
  ctx.fillStyle = series[i].color;
  ctx.fillRect(x, y, lbw-1, lbh-1);
 
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.lineWidth = 1;
  ctx.strokeRect(Math.ceil(x)-1.5, Math.ceil(y)-1.5, lbw+2, lbh+2);
 
  // Legend text
  Flotr.drawText(ctx, label, x + lbw + lbm, y + lbh, style);
 
  y += lbh + lbm;
  }
  }
  else {
  for(i = 0; i < series.length; ++i){
  if(!series[i].label || series[i].hide) continue;
 
  if(i % legend.noColumns === 0){
  fragments.push(rowStarted ? '</tr><tr>' : '<tr>');
  rowStarted = true;
  }
 
  var s = series[i],
  boxWidth = legend.labelBoxWidth,
  boxHeight = legend.labelBoxHeight;
 
  label = legend.labelFormatter(s.label);
  color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';
 
  fragments.push(
  '<td class="flotr-legend-color-box">',
  '<div style="border:1px solid ', legend.labelBoxBorderColor, ';padding:1px">',
  '<div style="width:', (boxWidth-1), 'px;height:', (boxHeight-1), 'px;border:1px solid ', series[i].color, '">', // Border
  '<div style="width:', boxWidth, 'px;height:', boxHeight, 'px;', color, '"></div>', // Background
  '</div>',
  '</div>',
  '</td>',
  '<td class="flotr-legend-label">', label, '</td>'
  );
  }
  if(rowStarted) fragments.push('</tr>');
 
  if(fragments.length > 0){
  var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join('') + '</table>';
  if(legend.container){
  table = D.node(table);
  this.legend.markup = table;
  D.insert(legend.container, table);
  }
  else {
  var styles = {position: 'absolute', 'zIndex': '2', 'border' : '1px solid ' + legend.labelBoxBorderColor};
 
  if(p.charAt(0) == 'n') { styles.top = (m + plotOffset.top) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 'c') { styles.top = (m + (this.plotHeight - legendHeight) / 2) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 's') { styles.bottom = (m + plotOffset.bottom) + 'px'; styles.top = 'auto'; }
  if(p.charAt(1) == 'e') { styles.right = (m + plotOffset.right) + 'px'; styles.left = 'auto'; }
  else if(p.charAt(1) == 'w') { styles.left = (m + plotOffset.left) + 'px'; styles.right = 'auto'; }
 
  var div = D.create('div'), size;
  div.className = 'flotr-legend';
  D.setStyles(div, styles);
  D.insert(div, table);
  D.insert(this.el, div);
 
  if (!opacity) return;
 
  var c = legend.backgroundColor || options.grid.backgroundColor || '#ffffff';
 
  _.extend(styles, D.size(div), {
  'backgroundColor': c,
  'zIndex' : '',
  'border' : ''
  });
  styles.width += 'px';
  styles.height += 'px';
 
  // Put in the transparent background separately to avoid blended labels and
  div = D.create('div');
  div.className = 'flotr-legend-bg';
  D.setStyles(div, styles);
  D.opacity(div, opacity);
  D.insert(div, ' ');
  D.insert(this.el, div);
  }
  }
  }
  }
  }
  });
  })();
 
  /** Spreadsheet **/
  (function() {
 
  function getRowLabel(value){
  if (this.options.spreadsheet.tickFormatter){
  //TODO maybe pass the xaxis formatter to the custom tick formatter as an opt-out?
  return this.options.spreadsheet.tickFormatter(value);
  }
  else {
  var t = _.find(this.axes.x.ticks, function(t){return t.v == value;});
  if (t) {
  return t.label;
  }
  return value;
  }
  }
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('spreadsheet', {
  options: {
  show: false, // => show the data grid using two tabs
  tabGraphLabel: 'Graph',
  tabDataLabel: 'Data',
  toolbarDownload: 'Download CSV', // @todo: add better language support
  toolbarSelectAll: 'Select all',
  csvFileSeparator: ',',
  decimalSeparator: '.',
  tickFormatter: null,
  initialTab: 'graph'
  },
  /**
  * Builds the tabs in the DOM
  */
  callbacks: {
  'flotr:afterconstruct': function(){
  // @TODO necessary?
  //this.el.select('.flotr-tabs-group,.flotr-datagrid-container').invoke('remove');
 
  if (!this.options.spreadsheet.show) return;
 
  var ss = this.spreadsheet,
  container = D.node('<div class="flotr-tabs-group" style="position:absolute;left:0px;width:'+this.canvasWidth+'px"></div>'),
  graph = D.node('<div style="float:left" class="flotr-tab selected">'+this.options.spreadsheet.tabGraphLabel+'</div>'),
  data = D.node('<div style="float:left" class="flotr-tab">'+this.options.spreadsheet.tabDataLabel+'</div>'),
  offset;
 
  ss.tabsContainer = container;
  ss.tabs = { graph : graph, data : data };
 
  D.insert(container, graph);
  D.insert(container, data);
  D.insert(this.el, container);
 
  offset = D.size(data).height + 2;
  this.plotOffset.bottom += offset;
 
  D.setStyles(container, {top: this.canvasHeight-offset+'px'});
 
  this.
  observe(graph, 'click', function(){ss.showTab('graph');}).
  observe(data, 'click', function(){ss.showTab('data');});
  if (this.options.spreadsheet.initialTab !== 'graph'){
  ss.showTab(this.options.spreadsheet.initialTab);
  }
  }
  },
  /**
  * Builds a matrix of the data to make the correspondance between the x values and the y values :
  * X value => Y values from the axes
  * @return {Array} The data grid
  */
  loadDataGrid: function(){
  if (this.seriesData) return this.seriesData;
 
  var s = this.series,
  rows = {};
 
  /* The data grid is a 2 dimensions array. There is a row for each X value.
  * Each row contains the x value and the corresponding y value for each serie ('undefined' if there isn't one)
  **/
  _.each(s, function(serie, i){
  _.each(serie.data, function (v) {
  var x = v[0],
  y = v[1],
  r = rows[x];
  if (r) {
  r[i+1] = y;
  } else {
  var newRow = [];
  newRow[0] = x;
  newRow[i+1] = y;
  rows[x] = newRow;
  }
  });
  });
 
  // The data grid is sorted by x value
  this.seriesData = _.sortBy(rows, function(row, x){
  return parseInt(x, 10);
  });
  return this.seriesData;
  },
  /**
  * Constructs the data table for the spreadsheet
  * @todo make a spreadsheet manager (Flotr.Spreadsheet)
  * @return {Element} The resulting table element
  */
  constructDataGrid: function(){
  // If the data grid has already been built, nothing to do here
  if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
 
  var s = this.series,
  datagrid = this.spreadsheet.loadDataGrid(),
  colgroup = ['<colgroup><col />'],
  buttonDownload, buttonSelect, t;
 
  // First row : series' labels
  var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
  html.push('<th>&nbsp;</th>');
  _.each(s, function(serie,i){
  html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>');
  colgroup.push('<col />');
  });
  html.push('</tr>');
  // Data rows
  _.each(datagrid, function(row){
  html.push('<tr>');
  _.times(s.length+1, function(i){
  var tag = 'td',
  value = row[i],
  // TODO: do we really want to handle problems with floating point
  // precision here?
  content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : '');
  if (i === 0) {
  tag = 'th';
  var label = getRowLabel.call(this, content);
  if (label) content = label;
  }
 
  html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>');
  }, this);
  html.push('</tr>');
  }, this);
  colgroup.push('</colgroup>');
  t = D.node(html.join(''));
 
  /**
  * @TODO disabled this
  if (!Flotr.isIE || Flotr.isIE == 9) {
  function handleMouseout(){
  t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
  }
  function handleMouseover(e){
  var td = e.element(),
  siblings = td.previousSiblings();
  t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
  t.select('colgroup col')[siblings.length].addClassName('hover');
  }
  _.each(t.select('td'), function(td) {
  Flotr.EventAdapter.
  observe(td, 'mouseover', handleMouseover).
  observe(td, 'mouseout', handleMouseout);
  });
  }
  */
 
  buttonDownload = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarDownload +
  '</button>');
 
  buttonSelect = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarSelectAll+
  '</button>');
 
  this.
  observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
  observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
 
  var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
  D.insert(toolbar, buttonDownload);
  D.insert(toolbar, buttonSelect);
 
  var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2,
  container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+
  this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>');
 
  D.insert(container, toolbar);
  D.insert(container, t);
  D.insert(this.el, container);
  this.spreadsheet.datagrid = t;
  this.spreadsheet.container = container;
 
  return t;
  },
  /**
  * Shows the specified tab, by its name
  * @todo make a tab manager (Flotr.Tabs)
  * @param {String} tabName - The tab name
  */
  showTab: function(tabName){
  if (this.spreadsheet.activeTab === tabName){
  return;
  }
  switch(tabName) {
  case 'graph':
  D.hide(this.spreadsheet.container);
  D.removeClass(this.spreadsheet.tabs.data, 'selected');
  D.addClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  case 'data':
  if (!this.spreadsheet.datagrid)
  this.spreadsheet.constructDataGrid();
  D.show(this.spreadsheet.container);
  D.addClass(this.spreadsheet.tabs.data, 'selected');
  D.removeClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  default:
  throw 'Illegal tab name: ' + tabName;
  }
  this.spreadsheet.activeTab = tabName;
  },
  /**
  * Selects the data table in the DOM for copy/paste
  */
  selectAllData: function(){
  if (this.spreadsheet.tabs) {
  var selection, range, doc, win, node = this.spreadsheet.constructDataGrid();
 
  this.spreadsheet.showTab('data');
 
  // deferred to be able to select the table
  setTimeout(function () {
  if ((doc = node.ownerDocument) && (win = doc.defaultView) &&
  win.getSelection && doc.createRange &&
  (selection = window.getSelection()) &&
  selection.removeAllRanges) {
  range = doc.createRange();
  range.selectNode(node);
  selection.removeAllRanges();
  selection.addRange(range);
  }
  else if (document.body && document.body.createTextRange &&
  (range = document.body.createTextRange())) {
  range.moveToElementText(node);
  range.select();
  }
  }, 0);
  return true;
  }
  else return false;
  },
  /**
  * Converts the data into CSV in order to download a file
  */
  downloadCSV: function(){
  var csv = '',
  series = this.series,
  options = this.options,
  dg = this.spreadsheet.loadDataGrid(),
  separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
 
  if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
  throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
  }
 
  // The first row
  _.each(series, function(serie, i){
  csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
  });
 
  csv += "%0D%0A"; // \r\n
 
  // For each row
  csv += _.reduce(dg, function(memo, row){
  var rowLabel = getRowLabel.call(this, row[0]) || '';
  rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
  var numbers = row.slice(1).join(separator);
  if (options.spreadsheet.decimalSeparator !== '.') {
  numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
  }
  return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
  }, '', this);
 
  if (Flotr.isIE && Flotr.isIE < 9) {
  csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
  window.open().document.write(csv);
  }
  else window.open('data:text/csv,'+csv);
  }
  });
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('titles', {
  callbacks: {
  'flotr:afterdraw': function() {
  this.titles.drawTitles();
  }
  },
  /**
  * Draws the title and the subtitle
  */
  drawTitles : function () {
  var html,
  options = this.options,
  margin = options.grid.labelMargin,
  ctx = this.ctx,
  a = this.axes;
 
  if (!options.HtmlText && this.textEnabled) {
  var style = {
  size: options.fontSize,
  color: options.grid.color,
  textAlign: 'center'
  };
 
  // Add subtitle
  if (options.subtitle){
  Flotr.drawText(
  ctx, options.subtitle,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight + this.subtitleHeight - 2,
  style
  );
  }
 
  style.weight = 1.5;
  style.size *= 1.5;
 
  // Add title
  if (options.title){
  Flotr.drawText(
  ctx, options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight - 2,
  style
  );
  }
 
  style.weight = 1.8;
  style.size *= 0.8;
 
  // Add x axis title
  if (a.x.options.title && a.x.used){
  style.textAlign = a.x.options.titleAlign || 'center';
  style.textBaseline = 'top';
  style.angle = Flotr.toRad(a.x.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top + a.x.maxLabel.height + this.plotHeight + 2 * margin,
  style
  );
  }
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used){
  style.textAlign = a.x2.options.titleAlign || 'center';
  style.textBaseline = 'bottom';
  style.angle = Flotr.toRad(a.x2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x2.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top - a.x2.maxLabel.height - 2 * margin,
  style
  );
  }
 
  // Add y axis title
  if (a.y.options.title && a.y.used){
  style.textAlign = a.y.options.titleAlign || 'right';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y.options.title,
  this.plotOffset.left - a.y.maxLabel.width - 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used){
  style.textAlign = a.y2.options.titleAlign || 'left';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y2.options.title,
  this.plotOffset.left + this.plotWidth + a.y2.maxLabel.width + 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
  }
  else {
  html = [];
 
  // Add title
  if (options.title)
  html.push(
  '<div style="position:absolute;top:0;left:',
  this.plotOffset.left, 'px;font-size:1em;font-weight:bold;text-align:center;width:',
  this.plotWidth,'px;" class="flotr-title">', options.title, '</div>'
  );
 
  // Add subtitle
  if (options.subtitle)
  html.push(
  '<div style="position:absolute;top:', this.titleHeight, 'px;left:',
  this.plotOffset.left, 'px;font-size:smaller;text-align:center;width:',
  this.plotWidth, 'px;" class="flotr-subtitle">', options.subtitle, '</div>'
  );
 
  html.push('</div>');
 
  html.push('<div class="flotr-axis-title" style="font-weight:bold;">');
 
  // Add x axis title
  if (a.x.options.title && a.x.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight + options.grid.labelMargin + a.x.titleSize.height),
  'px;left:', this.plotOffset.left, 'px;width:', this.plotWidth,
  'px;text-align:', a.x.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x1">', a.x.options.title, '</div>'
  );
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used)
  html.push(
  '<div style="position:absolute;top:0;left:', this.plotOffset.left, 'px;width:',
  this.plotWidth, 'px;text-align:', a.x2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x2">', a.x2.options.title, '</div>'
  );
 
  // Add y axis title
  if (a.y.options.title && a.y.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;left:0;text-align:', a.y.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y1">', a.y.options.title, '</div>'
  );
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;right:0;text-align:', a.y2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y2">', a.y2.options.title, '</div>'
  );
 
  html = html.join('');
 
  var div = D.create('div');
  D.setStyles({
  color: options.grid.color
  });
  div.className = 'flotr-titles';
  D.insert(this.el, div);
  D.insert(div, html);
  }
  }
  });
  })();
 
  /*!
  * bean.js - copyright Jacob Thornton 2011
  * https://github.com/fat/bean
  * MIT License
  * special thanks to:
  * dean edwards: http://dean.edwards.name/
  * dperini: https://github.com/dperini/nwevents
  * the entire mootools team: github.com/mootools/mootools-core
  *//*global module:true, define:true*/
  !function(a,b,c){typeof module!="undefined"?module.exports=c(a,b):typeof define=="function"&&typeof define.amd=="object"?define(c):b[a]=c(a,b)}("bean",this,function(a,b){var c=window,d=b[a],e=/over|out/,f=/[^\.]*(?=\..*)\.|.*/,g=/\..*/,h="addEventListener",i="attachEvent",j="removeEventListener",k="detachEvent",l=document||{},m=l.documentElement||{},n=m[h],o=n?h:i,p=Array.prototype.slice,q=/click|mouse|menu|drag|drop/i,r=/^touch|^gesture/i,s={one:1},t=function(a,b,c){for(c=0;c<b.length;c++)a[b[c]]=1;return a}({},("click dblclick mouseup mousedown contextmenu mousewheel DOMMouseScroll mouseover mouseout mousemove selectstart selectend keydown keypress keyup orientationchange focus blur change reset select submit load unload beforeunload resize move DOMContentLoaded readystatechange error abort scroll "+(n?"show input invalid touchstart touchmove touchend touchcancel gesturestart gesturechange gestureend message readystatechange pageshow pagehide popstate hashchange offline online afterprint beforeprint dragstart dragenter dragover dragleave drag drop dragend loadstart progress suspend emptied stalled loadmetadata loadeddata canplay canplaythrough playing waiting seeking seeked ended durationchange timeupdate play pause ratechange volumechange cuechange checking noupdate downloading cached updateready obsolete ":"")).split(" ")),u=function(){function a(a,b){while((b=b.parentNode)!==null)if(b===a)return!0;return!1}function b(b){var c=b.relatedTarget;return c?c!==this&&c.prefix!=="xul"&&!/document/.test(this.toString())&&!a(this,c):c===null}return{mouseenter:{base:"mouseover",condition:b},mouseleave:{base:"mouseout",condition:b},mousewheel:{base:/Firefox/.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel"}}}(),v=function(){var a="altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which".split(" "),b=a.concat("button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" ")),c=a.concat("char charCode key keyCode".split(" ")),d=a.concat("touches targetTouches changedTouches scale rotation".split(" ")),f="preventDefault",g=function(a){return function(){a[f]?a[f]():a.returnValue=!1}},h="stopPropagation",i=function(a){return function(){a[h]?a[h]():a.cancelBubble=!0}},j=function(a){return function(){a[f](),a[h](),a.stopped=!0}},k=function(a,b,c){var d,e;for(d=c.length;d--;)e=c[d],!(e in b)&&e in a&&(b[e]=a[e])};return function(n,o){var p={originalEvent:n,isNative:o};if(!n)return p;var s,t=n.type,u=n.target||n.srcElement;p[f]=g(n),p[h]=i(n),p.stop=j(p),p.target=u&&u.nodeType===3?u.parentNode:u;if(o){if(t.indexOf("key")!==-1)s=c,p.keyCode=n.which||n.keyCode;else if(q.test(t)){s=b,p.rightClick=n.which===3||n.button===2,p.pos={x:0,y:0};if(n.pageX||n.pageY)p.clientX=n.pageX,p.clientY=n.pageY;else if(n.clientX||n.clientY)p.clientX=n.clientX+l.body.scrollLeft+m.scrollLeft,p.clientY=n.clientY+l.body.scrollTop+m.scrollTop;e.test(t)&&(p.relatedTarget=n.relatedTarget||n[(t==="mouseover"?"from":"to")+"Element"])}else r.test(t)&&(s=d);k(n,p,s||a)}return p}}(),w=function(a,b){return!n&&!b&&(a===l||a===c)?m:a},x=function(){function a(a,b,c,d,e){this.element=a,this.type=b,this.handler=c,this.original=d,this.namespaces=e,this.custom=u[b],this.isNative=t[b]&&a[o],this.eventType=n||this.isNative?b:"propertychange",this.customType=!n&&!this.isNative&&b,this.target=w(a,this.isNative),this.eventSupport=this.target[o]}return a.prototype={inNamespaces:function(a){var b,c;if(!a)return!0;if(!this.namespaces)return!1;for(b=a.length;b--;)for(c=this.namespaces.length;c--;)if(a[b]===this.namespaces[c])return!0;return!1},matches:function(a,b,c){return this.element===a&&(!b||this.original===b)&&(!c||this.handler===c)}},a}(),y=function(){var a={},b=function(c,d,e,f,g){if(!d||d==="*")for(var h in a)h.charAt(0)==="$"&&b(c,h.substr(1),e,f,g);else{var i=0,j,k=a["$"+d],l=c==="*";if(!k)return;for(j=k.length;i<j;i++)if(l||k[i].matches(c,e,f))if(!g(k[i],k,i,d))return}},c=function(b,c,d){var e,f=a["$"+c];if(f)for(e=f.length;e--;)if(f[e].matches(b,d,null))return!0;return!1},d=function(a,c,d){var e=[];return b(a,c,d,null,function(a){return e.push(a)}),e},e=function(b){return(a["$"+b.type]||(a["$"+b.type]=[])).push(b),b},f=function(c){b(c.element,c.type,null,c.handler,function(b,c,d){return c.splice(d,1),c.length===0&&delete a["$"+b.type],!1})},g=function(){var b,c=[];for(b in a)b.charAt(0)==="$"&&(c=c.concat(a[b]));return c};return{has:c,get:d,put:e,del:f,entries:g}}(),z=n?function(a,b,c,d){a[d?h:j](b,c,!1)}:function(a,b,c,d,e){e&&d&&a["_on"+e]===null&&(a["_on"+e]=0),a[d?i:k]("on"+b,c)},A=function(a,b,d){return function(e){return e=v(e||((this.ownerDocument||this.document||this).parentWindow||c).event,!0),b.apply(a,[e].concat(d))}},B=function(a,b,d,e,f,g){return function(h){if(e?e.apply(this,arguments):n?!0:h&&h.propertyName==="_on"+d||!h)h&&(h=v(h||((this.ownerDocument||this.document||this).parentWindow||c).event,g)),b.apply(a,h&&(!f||f.length===0)?arguments:p.call(arguments,h?0:1).concat(f))}},C=function(a,b,c,d,e){return function(){a(b,c,e),d.apply(this,arguments)}},D=function(a,b,c,d){var e,f,h,i=b&&b.replace(g,""),j=y.get(a,i,c);for(e=0,f=j.length;e<f;e++)j[e].inNamespaces(d)&&((h=j[e]).eventSupport&&z(h.target,h.eventType,h.handler,!1,h.type),y.del(h))},E=function(a,b,c,d,e){var h,i=b.replace(g,""),j=b.replace(f,"").split(".");if(y.has(a,i,c))return a;i==="unload"&&(c=C(D,a,i,c,d)),u[i]&&(u[i].condition&&(c=B(a,c,i,u[i].condition,!0)),i=u[i].base||i),h=y.put(new x(a,i,c,d,j[0]&&j)),h.handler=h.isNative?A(a,h.handler,e):B(a,h.handler,i,!1,e,!1),h.eventSupport&&z(h.target,h.eventType,h.handler,!0,h.customType)},F=function(a,b,c){return function(d){var e,f,g=typeof a=="string"?c(a,this):a;for(e=d.target;e&&e!==this;e=e.parentNode)for(f=g.length;f--;)if(g[f]===e)return b.apply(e,arguments)}},G=function(a,b,c){var d,e,h,i,j,k=D,l=b&&typeof b=="string";if(l&&b.indexOf(" ")>0){b=b.split(" ");for(j=b.length;j--;)G(a,b[j],c);return a}h=l&&b.replace(g,""),h&&u[h]&&(h=u[h].type);if(!b||l){if(i=l&&b.replace(f,""))i=i.split(".");k(a,h,c,i)}else if(typeof b=="function")k(a,null,b);else for(d in b)b.hasOwnProperty(d)&&G(a,d,b[d]);return a},H=function(a,b,c,d,e){var f,g,h,i,j=c,k=c&&typeof c=="string";if(b&&!c&&typeof b=="object")for(f in b)b.hasOwnProperty(f)&&H.apply(this,[a,f,b[f]]);else{i=arguments.length>3?p.call(arguments,3):[],g=(k?c:b).split(" "),k&&(c=F(b,j=d,e))&&(i=p.call(i,1)),this===s&&(c=C(G,a,b,c,j));for(h=g.length;h--;)E(a,g[h],c,j,i)}return a},I=function(){return H.apply(s,arguments)},J=n?function(a,b,d){var e=l.createEvent(a?"HTMLEvents":"UIEvents");e[a?"initEvent":"initUIEvent"](b,!0,!0,c,1),d.dispatchEvent(e)}:function(a,b,c){c=w(c,a),a?c.fireEvent("on"+b,l.createEventObject()):c["_on"+b]++},K=function(a,b,c){var d,e,h,i,j,k=b.split(" ");for(d=k.length;d--;){b=k[d].replace(g,"");if(i=k[d].replace(f,""))i=i.split(".");if(!i&&!c&&a[o])J(t[b],b,a);else{j=y.get(a,b),c=[!1].concat(c);for(e=0,h=j.length;e<h;e++)j[e].inNamespaces(i)&&j[e].handler.apply(a,c)}}return a},L=function(a,b,c){var d=0,e=y.get(b,c),f=e.length;for(;d<f;d++)e[d].original&&H(a,e[d].type,e[d].original);return a},M={add:H,one:I,remove:G,clone:L,fire:K,noConflict:function(){return b[a]=d,this}};if(c[i]){var N=function(){var a,b=y.entries();for(a in b)b[a].type&&b[a].type!=="unload"&&G(b[a].element,b[a].type);c[k]("onunload",N),c.CollectGarbage&&c.CollectGarbage()};c[i]("onunload",N)}return M});
  // Underscore.js 1.1.7
  // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
  // Underscore is freely distributable under the MIT license.
  // Portions of Underscore are inspired or borrowed from Prototype,
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
  // For all details and documentation:
  // http://documentcloud.github.com/underscore
 
  (function(){var a=this,b=a._,c={},d=Array.prototype,e=Object.prototype,f=Function.prototype,g=d.slice,h=d.unshift,i=e.toString,j=e.hasOwnProperty,k=d.forEach,l=d.map,m=d.reduce,n=d.reduceRight,o=d.filter,p=d.every,q=d.some,r=d.indexOf,s=d.lastIndexOf,t=Array.isArray,u=Object.keys,v=f.bind,w=function(a){return new B(a)};typeof module!="undefined"&&module.exports?(module.exports=w,w._=w):a._=w,w.VERSION="1.1.7";var x=w.each=w.forEach=function(a,b,d){if(a==null)return;if(k&&a.forEach===k)a.forEach(b,d);else if(a.length===+a.length){for(var e=0,f=a.length;e<f;e++)if(e in a&&b.call(d,a[e],e,a)===c)return}else for(var g in a)if(j.call(a,g)&&b.call(d,a[g],g,a)===c)return};w.map=function(a,b,c){var d=[];return a==null?d:l&&a.map===l?a.map(b,c):(x(a,function(a,e,f){d[d.length]=b.call(c,a,e,f)}),d)},w.reduce=w.foldl=w.inject=function(a,b,c,d){var e=c!==void 0;a==null&&(a=[]);if(m&&a.reduce===m)return d&&(b=w.bind(b,d)),e?a.reduce(b,c):a.reduce(b);x(a,function(a,f,g){e?c=b.call(d,c,a,f,g):(c=a,e=!0)});if(!e)throw new TypeError("Reduce of empty array with no initial value");return c},w.reduceRight=w.foldr=function(a,b,c,d){a==null&&(a=[]);if(n&&a.reduceRight===n)return d&&(b=w.bind(b,d)),c!==void 0?a.reduceRight(b,c):a.reduceRight(b);var e=(w.isArray(a)?a.slice():w.toArray(a)).reverse();return w.reduce(e,b,c,d)},w.find=w.detect=function(a,b,c){var d;return y(a,function(a,e,f){if(b.call(c,a,e,f))return d=a,!0}),d},w.filter=w.select=function(a,b,c){var d=[];return a==null?d:o&&a.filter===o?a.filter(b,c):(x(a,function(a,e,f){b.call(c,a,e,f)&&(d[d.length]=a)}),d)},w.reject=function(a,b,c){var d=[];return a==null?d:(x(a,function(a,e,f){b.call(c,a,e,f)||(d[d.length]=a)}),d)},w.every=w.all=function(a,b,d){var e=!0;return a==null?e:p&&a.every===p?a.every(b,d):(x(a,function(a,f,g){if(!(e=e&&b.call(d,a,f,g)))return c}),e)};var y=w.some=w.any=function(a,b,d){b=b||w.identity;var e=!1;return a==null?e:q&&a.some===q?a.some(b,d):(x(a,function(a,f,g){if(e|=b.call(d,a,f,g))return c}),!!e)};w.include=w.contains=function(a,b){var c=!1;return a==null?c:r&&a.indexOf===r?a.indexOf(b)!=-1:(y(a,function(a){if(c=a===b)return!0}),c)},w.invoke=function(a,b){var c=g.call(arguments,2);return w.map(a,function(a){return(b.call?b||a:a[b]).apply(a,c)})},w.pluck=function(a,b){return w.map(a,function(a){return a[b]})},w.max=function(a,b,c){if(!b&&w.isArray(a))return Math.max.apply(Math,a);var d={computed:-Infinity};return x(a,function(a,e,f){var g=b?b.call(c,a,e,f):a;g>=d.computed&&(d={value:a,computed:g})}),d.value},w.min=function(a,b,c){if(!b&&w.isArray(a))return Math.min.apply(Math,a);var d={computed:Infinity};return x(a,function(a,e,f){var g=b?b.call(c,a,e,f):a;g<d.computed&&(d={value:a,computed:g})}),d.value},w.sortBy=function(a,b,c){return w.pluck(w.map(a,function(a,d,e){return{value:a,criteria:b.call(c,a,d,e)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")},w.groupBy=function(a,b){var c={};return x(a,function(a,d){var e=b(a,d);(c[e]||(c[e]=[])).push(a)}),c},w.sortedIndex=function(a,b,c){c||(c=w.identity);var d=0,e=a.length;while(d<e){var f=d+e>>1;c(a[f])<c(b)?d=f+1:e=f}return d},w.toArray=function(a){return a?a.toArray?a.toArray():w.isArray(a)?g.call(a):w.isArguments(a)?g.call(a):w.values(a):[]},w.size=function(a){return w.toArray(a).length},w.first=w.head=function(a,b,c){return b!=null&&!c?g.call(a,0,b):a[0]},w.rest=w.tail=function(a,b,c){return g.call(a,b==null||c?1:b)},w.last=function(a){return a[a.length-1]},w.compact=function(a){return w.filter(a,function(a){return!!a})},w.flatten=function(a){return w.reduce(a,function(a,b){return w.isArray(b)?a.concat(w.flatten(b)):(a[a.length]=b,a)},[])},w.without=function(a){return w.difference(a,g.call(arguments,1))},w.uniq=w.unique=function(a,b){return w.reduce(a,function(a,c,d){if(0==d||(b===!0?w.last(a)!=c:!w.include(a,c)))a[a.length]=c;return a},[])},w.union=function(){return w.uniq(w.flatten(arguments))},w.intersection=w.intersect=function(a){var b=g.call(arguments,1);return w.filter(w.uniq(a),function(a){return w.every(b,function(b){return w.indexOf(b,a)>=0})})},w.difference=function(a,b){return w.filter(a,function(a){return!w.include(b,a)})},w.zip=function(){var a=g.call(arguments),b=w.max(w.pluck(a,"length")),c=new Array(b);for(var d=0;d<b;d++)c[d]=w.pluck(a,""+d);return c},w.indexOf=function(a,b,c){if(a==null)return-1;var d,e;if(c)return d=w.sortedIndex(a,b),a[d]===b?d:-1;if(r&&a.indexOf===r)return a.indexOf(b);for(d=0,e=a.length;d<e;d++)if(a[d]===b)return d;return-1},w.lastIndexOf=function(a,b){if(a==null)return-1;if(s&&a.lastIndexOf===s)return a.lastIndexOf(b);var c=a.length;while(c--)if(a[c]===b)return c;return-1},w.range=function(a,b,c){arguments.length<=1&&(b=a||0,a=0),c=arguments[2]||1;var d=Math.max(Math.ceil((b-a)/c),0),e=0,f=new Array(d);while(e<d)f[e++]=a,a+=c;return f},w.bind=function(a,b){if(a.bind===v&&v)return v.apply(a,g.call(arguments,1));var c=g.call(arguments,2);return function(){return a.apply(b,c.concat(g.call(arguments)))}},w.bindAll=function(a){var b=g.call(arguments,1);return b.length==0&&(b=w.functions(a)),x(b,function(b){a[b]=w.bind(a[b],a)}),a},w.memoize=function(a,b){var c={};return b||(b=w.identity),function(){var d=b.apply(this,arguments);return j.call(c,d)?c[d]:c[d]=a.apply(this,arguments)}},w.delay=function(a,b){var c=g.call(arguments,2);return setTimeout(function(){return a.apply(a,c)},b)},w.defer=function(a){return w.delay.apply(w,[a,1].concat(g.call(arguments,1)))};var z=function(a,b,c){var d;return function(){var e=this,f=arguments,g=function(){d=null,a.apply(e,f)};c&&clearTimeout(d);if(c||!d)d=setTimeout(g,b)}};w.throttle=function(a,b){return z(a,b,!1)},w.debounce=function(a,b){return z(a,b,!0)},w.once=function(a){var b=!1,c;return function(){return b?c:(b=!0,c=a.apply(this,arguments))}},w.wrap=function(a,b){return function(){var c=[a].concat(g.call(arguments));return b.apply(this,c)}},w.compose=function(){var a=g.call(arguments);return function(){var b=g.call(arguments);for(var c=a.length-1;c>=0;c--)b=[a[c].apply(this,b)];return b[0]}},w.after=function(a,b){return function(){if(--a<1)return b.apply(this,arguments)}},w.keys=u||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var b=[];for(var c in a)j.call(a,c)&&(b[b.length]=c);return b},w.values=function(a){return w.map(a,w.identity)},w.functions=w.methods=function(a){var b=[];for(var c in a)w.isFunction(a[c])&&b.push(c);return b.sort()},w.extend=function(a){return x(g.call(arguments,1),function(b){for(var c in b)b[c]!==void 0&&(a[c]=b[c])}),a},w.defaults=function(a){return x(g.call(arguments,1),function(b){for(var c in b)a[c]==null&&(a[c]=b[c])}),a},w.clone=function(a){return w.isArray(a)?a.slice():w.extend({},a)},w.tap=function(a,b){return b(a),a},w.isEqual=function(a,b){if(a===b)return!0;var c=typeof a,d=typeof b;if(c!=d)return!1;if(a==b)return!0;if(!a&&b||a&&!b)return!1;a._chain&&(a=a._wrapped),b._chain&&(b=b._wrapped);if(a.isEqual)return a.isEqual(b);if(b.isEqual)return b.isEqual(a);if(w.isDate(a)&&w.isDate(b))return a.getTime()===b.getTime();if(w.isNaN(a)&&w.isNaN(b))return!1;if(w.isRegExp(a)&&w.isRegExp(b))return a.source===b.source&&a.global===b.global&&a.ignoreCase===b.ignoreCase&&a.multiline===b.multiline;if(c!=="object")return!1;if(a.length&&a.length!==b.length)return!1;var e=w.keys(a),f=w.keys(b);if(e.length!=f.length)return!1;for(var g in a)if(!(g in b)||!w.isEqual(a[g],b[g]))return!1;return!0},w.isEmpty=function(a){if(w.isArray(a)||w.isString(a))return a.length===0;for(var b in a)if(j.call(a,b))return!1;return!0},w.isElement=function(a){return!!a&&a.nodeType==1},w.isArray=t||function(a){return i.call(a)==="[object Array]"},w.isObject=function(a){return a===Object(a)},w.isArguments=function(a){return!!a&&!!j.call(a,"callee")},w.isFunction=function(a){return!!(a&&a.constructor&&a.call&&a.apply)},w.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)},w.isNumber=function(a){return!!(a===0||a&&a.toExponential&&a.toFixed)},w.isNaN=function(a){return a!==a},w.isBoolean=function(a){return a===!0||a===!1},w.isDate=function(a){return!!(a&&a.getTimezoneOffset&&a.setUTCFullYear)},w.isRegExp=function(a){return!(!(a&&a.test&&a.exec)||!a.ignoreCase&&a.ignoreCase!==!1)},w.isNull=function(a){return a===null},w.isUndefined=function(a){return a===void 0},w.noConflict=function(){return a._=b,this},w.identity=function(a){return a},w.times=function(a,b,c){for(var d=0;d<a;d++)b.call(c,d)},w.mixin=function(a){x(w.functions(a),function(b){D(b,w[b]=a[b])})};var A=0;w.uniqueId=function(a){var b=A++;return a?a+b:b},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g},w.template=function(a,b){var c=w.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(c.interpolate,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(c.evaluate||null,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ")+"__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj",d);return b?e(b):e};var B=function(a){this._wrapped=a};w.prototype=B.prototype;var C=function(a,b){return b?w(a).chain():a},D=function(a,b){B.prototype[a]=function(){var a=g.call(arguments);return h.call(a,this._wrapped),C(b.apply(w,a),this._chain)}};w.mixin(w),x(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var b=d[a];B.prototype[a]=function(){return b.apply(this._wrapped,arguments),C(this._wrapped,this._chain)}}),x(["concat","join","slice"],function(a){var b=d[a];B.prototype[a]=function(){return C(b.apply(this._wrapped,arguments),this._chain)}}),B.prototype.chain=function(){return this._chain=!0,this},B.prototype.value=function(){return this._wrapped}})();
  /**
  * Flotr2 (c) 2012 Carl Sutherland
  * MIT License
  * Special thanks to:
  * Flotr: http://code.google.com/p/flotr/ (fork)
  * Flot: https://github.com/flot/flot (original fork)
  */
  (function(){var a=this,b=this.Flotr,c;c={_:_,bean:bean,isIphone:/iphone/i.test(navigator.userAgent),isIE:navigator.appVersion.indexOf("MSIE")!=-1?parseFloat(navigator.appVersion.split("MSIE")[1]):!1,graphTypes:{},plugins:{},addType:function(a,b){c.graphTypes[a]=b,c.defaultOptions[a]=b.options||{},c.defaultOptions.defaultType=c.defaultOptions.defaultType||a},addPlugin:function(a,b){c.plugins[a]=b,c.defaultOptions[a]=b.options||{}},draw:function(a,b,d,e){return e=e||c.Graph,new e(a,b,d)},merge:function(a,b){var d,e,f=b||{};for(d in a)e=a[d],e&&typeof e=="object"?e.constructor===Array?f[d]=this._.clone(e):e.constructor!==RegExp&&!this._.isElement(e)&&!e.jquery?f[d]=c.merge(e,b?b[d]:undefined):f[d]=e:f[d]=e;return f},clone:function(a){return c.merge(a,{})},getTickSize:function(a,b,d,e){var f=(d-b)/a,g=c.getMagnitude(f),h=10,i=f/g;return i<1.5?h=1:i<2.25?h=2:i<3?h=e===0?2:2.5:i<7.5&&(h=5),h*g},defaultTickFormatter:function(a,b){return a+""},defaultTrackFormatter:function(a){return"("+a.x+", "+a.y+")"},engineeringNotation:function(a,b,c){var d=["Y","Z","E","P","T","G","M","k",""],e=["y","z","a","f","p","n","µ","m",""],f=d.length;c=c||1e3,b=Math.pow(10,b||2);if(a===0)return 0;if(a>1)while(f--&&a>=c)a/=c;else{d=e,f=d.length;while(f--&&a<1)a*=c}return Math.round(a*b)/b+d[f]},getMagnitude:function(a){return Math.pow(10,Math.floor(Math.log(a)/Math.LN10))},toPixel:function(a){return Math.floor(a)+.5},toRad:function(a){return-a*(Math.PI/180)},floorInBase:function(a,b){return b*Math.floor(a/b)},drawText:function(a,b,d,e,f){if(!a.fillText){a.drawText(b,d,e,f);return}f=this._.extend({size:c.defaultOptions.fontSize,color:"#000000",textAlign:"left",textBaseline:"bottom",weight:1,angle:0},f),a.save(),a.translate(d,e),a.rotate(f.angle),a.fillStyle=f.color,a.font=(f.weight>1?"bold ":"")+f.size*1.3+"px sans-serif",a.textAlign=f.textAlign,a.textBaseline=f.textBaseline,a.fillText(b,0,0),a.restore()},getBestTextAlign:function(a,b){return b=b||{textAlign:"center",textBaseline:"middle"},a+=c.getTextAngleFromAlign(b),Math.abs(Math.cos(a))>.01&&(b.textAlign=Math.cos(a)>0?"right":"left"),Math.abs(Math.sin(a))>.01&&(b.textBaseline=Math.sin(a)>0?"top":"bottom"),b},alignTable:{"right middle":0,"right top":Math.PI/4,"center top":Math.PI/2,"left top":3*(Math.PI/4),"left middle":Math.PI,"left bottom":-3*(Math.PI/4),"center bottom":-Math.PI/2,"right bottom":-Math.PI/4,"center middle":0},getTextAngleFromAlign:function(a){return c.alignTable[a.textAlign+" "+a.textBaseline]||0},noConflict:function(){return a.Flotr=b,this}},a.Flotr=c})(),Flotr.defaultOptions={colors:["#00A8F0","#C0D800","#CB4B4B","#4DA74D","#9440ED"],ieBackgroundColor:"#FFFFFF",title:null,subtitle:null,shadowSize:4,defaultType:null,HtmlText:!0,fontColor:"#545454",fontSize:7.5,resolution:1,parseFloat:!0,preventDefault:!0,xaxis:{ticks:null,minorTicks:null,showLabels:!0,showMinorLabels:!1,labelsAngle:0,title:null,titleAngle:0,noTicks:5,minorTickFreq:null,tickFormatter:Flotr.defaultTickFormatter,tickDecimals:null,min:null,max:null,autoscale:!1,autoscaleMargin:0,color:null,mode:"normal",timeFormat:null,timeMode:"UTC",timeUnit:"millisecond",scaling:"linear",base:Math.E,titleAlign:"center",margin:!0},x2axis:{},yaxis:{ticks:null,minorTicks:null,showLabels:!0,showMinorLabels:!1,labelsAngle:0,title:null,titleAngle:90,noTicks:5,minorTickFreq:null,tickFormatter:Flotr.defaultTickFormatter,tickDecimals:null,min:null,max:null,autoscale:!1,autoscaleMargin:0,color:null,scaling:"linear",base:Math.E,titleAlign:"center",margin:!0},y2axis:{titleAngle:270},grid:{color:"#545454",backgroundColor:null,backgroundImage:null,watermarkAlpha:.4,tickColor:"#DDDDDD",labelMargin:3,verticalLines:!0,minorVerticalLines:null,horizontalLines:!0,minorHorizontalLines:null,outlineWidth:1,outline:"nsew",circular:!1},mouse:{track:!1,trackAll:!1,position:"se",relative:!1,trackFormatter:Flotr.defaultTrackFormatter,margin:5,lineColor:"#FF3F19",trackDecimals:1,sensibility:2,trackY:!0,radius:3,fillColor:null,fillOpacity:.4}},function(){function b(a,b,c,d){this.rgba=["r","g","b","a"];var e=4;while(-1<--e)this[this.rgba[e]]=arguments[e]||(e==3?1:0);this.normalize()}var a=Flotr._,c={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]};b.prototype={scale:function(b,c,d,e){var f=4;while(-1<--f)a.isUndefined(arguments[f])||(this[this.rgba[f]]*=arguments[f]);return this.normalize()},alpha:function(b){return!a.isUndefined(b)&&!a.isNull(b)&&(this.a=b),this.normalize()},clone:function(){return new b(this.r,this.b,this.g,this.a)},limit:function(a,b,c){return Math.max(Math.min(a,c),b)},normalize:function(){var a=this.limit;return this.r=a(parseInt(this.r,10),0,255),this.g=a(parseInt(this.g,10),0,255),this.b=a(parseInt(this.b,10),0,255),this.a=a(this.a,0,1),this},distance:function(a){if(!a)return;a=new b.parse(a);var c=0,d=3;while(-1<--d)c+=Math.abs(this[this.rgba[d]]-a[this.rgba[d]]);return c},toString:function(){return this.a>=1?"rgb("+[this.r,this.g,this.b].join(",")+")":"rgba("+[this.r,this.g,this.b,this.a].join(",")+")"},contrast:function(){var a=1-(.299*this.r+.587*this.g+.114*this.b)/255;return a<.5?"#000000":"#ffffff"}},a.extend(b,{parse:function(a){if(a instanceof b)return a;var d;if(d=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(a))return new b(parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16));if(d=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))return new b(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10));if(d=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(a))return new b(parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16));if(d=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(a))return new b(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10),parseFloat(d[4]));if(d=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(a))return new b(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55);if(d=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(a))return new b(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55,parseFloat(d[4]));var e=(a+"").replace(/^\s*([\S\s]*?)\s*$/,"$1").toLowerCase();return e=="transparent"?new b(255,255,255,0):(d=c[e])?new b(d[0],d[1],d[2]):new b(0,0,0,0)},processColor:function(c,d){var e=d.opacity;if(!c)return"rgba(0, 0, 0, 0)";if(c instanceof b)return c.alpha(e).toString();if(a.isString(c))return b.parse(c).alpha(e).toString();var f=c.colors?c:{colors:c};if(!d.ctx)return a.isArray(f.colors)?b.parse(a.isArray(f.colors[0])?f.colors[0][1]:f.colors[0]).alpha(e).toString():"rgba(0, 0, 0, 0)";f=a.extend({start:"top",end:"bottom"},f),/top/i.test(f.start)&&(d.x1=0),/left/i.test(f.start)&&(d.y1=0),/bottom/i.test(f.end)&&(d.x2=0),/right/i.test(f.end)&&(d.y2=0);var g,h,i,j=d.ctx.createLinearGradient(d.x1,d.y1,d.x2,d.y2);for(g=0;g<f.colors.length;g++)h=f.colors[g],a.isArray(h)?(i=h[0],h=h[1]):i=g/(f.colors.length-1),j.addColorStop(i,b.parse(h).alpha(e));return j}}),Flotr.Color=b}(),Flotr.Date={set:function(a,b,c,d){c=c||"UTC",b="set"+(c==="UTC"?"UTC":"")+b,a[b](d)},get:function(a,b,c){return c=c||"UTC",b="get"+(c==="UTC"?"UTC":"")+b,a[b]()},format:function(a,b,c){function f(a){return a+="",a.length==1?"0"+a:a}if(!a)return;var d=this.get,e={h:d(a,"Hours",c).toString(),H:f(d(a,"Hours",c)),M:f(d(a,"Minutes",c)),S:f(d(a,"Seconds",c)),s:d(a,"Milliseconds",c),d:d(a,"Date",c).toString(),m:(d(a,"Month",c)+1).toString(),y:d(a,"FullYear",c).toString(),b:Flotr.Date.monthNames[d(a,"Month",c)]},g=[],h,i=!1;for(var j=0;j<b.length;++j)h=b.charAt(j),i?(g.push(e[h]||h),i=!1):h=="%"?i=!0:g.push(h);return g.join("")},getFormat:function(a,b){var c=Flotr.Date.timeUnits;return a<c.second?"%h:%M:%S.%s":a<c.minute?"%h:%M:%S":a<c.day?b<2*c.day?"%h:%M":"%b %d %h:%M":a<c.month?"%b %d":a<c.year?b<c.year?"%b":"%b %y":"%y"},formatter:function(a,b){var c=b.options,d=Flotr.Date.timeUnits[c.timeUnit],e=new Date(a*d);if(b.options.timeFormat)return Flotr.Date.format(e,c.timeFormat,c.timeMode);var f=(b.max-b.min)*d,g=b.tickSize*Flotr.Date.timeUnits[b.tickUnit];return Flotr.Date.format(e,Flotr.Date.getFormat(g,f),c.timeMode)},generator:function(a){function s(a){b(q,a,g,Flotr.floorInBase(c(q,a,g),m))}var b=this.set,c=this.get,d=this.timeUnits,e=this.spec,f=a.options,g=f.timeMode,h=d[f.timeUnit],i=a.min*h,j=a.max*h,k=(j-i)/f.noTicks,l=[],m=a.tickSize,n,o,p;o=f.tickFormatter===Flotr.defaultTickFormatter?this.formatter:f.tickFormatter;for(p=0;p<e.length-1;++p){var q=e[p][0]*d[e[p][1]];if(k<(q+e[p+1][0]*d[e[p+1][1]])/2&&q>=m)break}m=e[p][0],n=e[p][1],n=="year"&&(m=Flotr.getTickSize(f.noTicks*d.year,i,j,0),m==.5&&(n="month",m=6)),a.tickUnit=n,a.tickSize=m;var r=m*d[n];q=new Date(i);switch(n){case"millisecond":s("Milliseconds");break;case"second":s("Seconds");break;case"minute":s("Minutes");break;case"hour":s("Hours");break;case"month":s("Month");break;case"year":s("FullYear")}r>=d.second&&b(q,"Milliseconds",g,0),r>=d.minute&&b(q,"Seconds",g,0),r>=d.hour&&b(q,"Minutes",g,0),r>=d.day&&b(q,"Hours",g,0),r>=d.day*4&&b(q,"Date",g,1),r>=d.year&&b(q,"Month",g,0);var t=0,u=NaN,v;do{v=u,u=q.getTime(),l.push({v:u/h,label:o(u/h,a)});if(n=="month")if(m<1){b(q,"Date",g,1);var w=q.getTime();b(q,"Month",g,c(q,"Month",g)+1);var x=q.getTime();q.setTime(u+t*d.hour+(x-w)*m),t=c(q,"Hours",g),b(q,"Hours",g,0)}else b(q,"Month",g,c(q,"Month",g)+m);else n=="year"?b(q,"FullYear",g,c(q,"FullYear",g)+m):q.setTime(u+r)}while(u<j&&u!=v);return l},timeUnits:{millisecond:1,second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31556952e3},spec:[[1,"millisecond"],[20,"millisecond"],[50,"millisecond"],[100,"millisecond"],[200,"millisecond"],[500,"millisecond"],[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[.25,"month"],[.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},function(){function b(a){return a&&a.jquery?a[0]:a}var a=Flotr._;Flotr.DOM={addClass:function(c,d){c=b(c);var e=c.className?c.className:"";if(a.include(e.split(/\s+/g),d))return;c.className=(e?e+" ":"")+d},create:function(a){return document.createElement(a)},node:function(a){var b=Flotr.DOM.create("div"),c;return b.innerHTML=a,c=b.children[0],b.innerHTML="",c},empty:function(a){a=b(a),a.innerHTML=""},remove:function(a){a=b(a),a.parentNode.removeChild(a)},hide:function(a){a=b(a),Flotr.DOM.setStyles(a,{display:"none"})},insert:function(c,d){c=b(c),a.isString(d)?c.innerHTML+=d:a.isElement(d)&&c.appendChild(d)},opacity:function(a,c){a=b(a),a.style.opacity=c},position:function(a,c){return a=b(a),a.offsetParent?(c=this.position(a.offsetParent),c.left+=a.offsetLeft,c.top+=a.offsetTop,c):{left:a.offsetLeft||0,top:a.offsetTop||0}},removeClass:function(c,d){var e=c.className?c.className:"";c=b(c),c.className=a.filter(e.split(/\s+/g),function(a){if(a!=d)return!0}).join(" ")},setStyles:function(c,d){c=b(c),a.each(d,function(a,b){c.style[b]=a})},show:function(a){a=b(a),Flotr.DOM.setStyles(a,{display:""})},size:function(a){return a=b(a),{height:a.offsetHeight,width:a.offsetWidth}}}}(),function(){var a=Flotr,b=a.bean;a.EventAdapter={observe:function(a,c,d){return b.add(a,c,d),this},fire:function(a,c,d){return b.fire(a,c,d),typeof Prototype!="undefined"&&Event.fire(a,c,d),this},stopObserving:function(a,c,d){return b.remove(a,c,d),this},eventPointer:function(b){if(!a._.isUndefined(b.touches)&&b.touches.length>0)return{x:b.touches[0].pageX,y:b.touches[0].pageY};if(!a._.isUndefined(b.changedTouches)&&b.changedTouches.length>0)return{x:b.changedTouches[0].pageX,y:b.changedTouches[0].pageY};if(b.pageX||b.pageY)return{x:b.pageX,y:b.pageY};if(b.clientX||b.clientY){var c=document,d=c.body,e=c.documentElement;return{x:b.clientX+d.scrollLeft+e.scrollLeft,y:b.clientY+d.scrollTop+e.scrollTop}}}}}(),function(){var a=Flotr,b=a.DOM,c=a._,d=function(a){this.o=a};d.prototype={dimensions:function(a,b,c,d){return a?this.o.html?this.html(a,this.o.element,c,d):this.canvas(a,b):{width:0,height:0}},canvas:function(b,c){if(!this.o.textEnabled)return;c=c||{};var d=this.measureText(b,c),e=d.width,f=c.size||a.defaultOptions.fontSize,g=c.angle||0,h=Math.cos(g),i=Math.sin(g),j=2,k=6,l;return l={width:Math.abs(h*e)+Math.abs(i*f)+j,height:Math.abs(i*e)+Math.abs(h*f)+k},l},html:function(a,c,d,e){var f=b.create("div");return b.setStyles(f,{position:"absolute",top:"-10000px"}),b.insert(f,'<div style="'+d+'" class="'+e+' flotr-dummy-div">'+a+"</div>"),b.insert(this.o.element,f),b.size(f)},measureText:function(b,d){var e=this.o.ctx,f;return!e.fillText||a.isIphone&&e.measure?{width:e.measure(b,d)}:(d=c.extend({size:a.defaultOptions.fontSize,weight:1,angle:0},d),e.save(),e.font=(d.weight>1?"bold ":"")+d.size*1.3+"px sans-serif",f=e.measureText(b),e.restore(),f)}},Flotr.Text=d}(),function(){function e(a,c,d){return b.observe.apply(this,arguments),this._handles.push(arguments),this}var a=Flotr.DOM,b=Flotr.EventAdapter,c=Flotr._,d=Flotr;Graph=function(a,e,f){this._setEl(a),this._initMembers(),this._initPlugins(),b.fire(this.el,"flotr:beforeinit",[this]),this.data=e,this.series=d.Series.getSeries(e),this._initOptions(f),this._initGraphTypes(),this._initCanvas(),this._text=new d.Text({element:this.el,ctx:this.ctx,html:this.options.HtmlText,textEnabled:this.textEnabled}),b.fire(this.el,"flotr:afterconstruct",[this]),this._initEvents(),this.findDataRanges(),this.calculateSpacing(),this.draw(c.bind(function(){b.fire(this.el,"flotr:afterinit",[this])},this))},Graph.prototype={destroy:function(){b.fire(this.el,"flotr:destroy"),c.each(this._handles,function(a){b.stopObserving.apply(this,a)}),this._handles=[],this.el.graph=null},observe:e,_observe:e,processColor:function(a,b){var e={x1:0,y1:0,x2:this.plotWidth,y2:this.plotHeight,opacity:1,ctx:this.ctx};return c.extend(e,b),d.Color.processColor(a,e)},findDataRanges:function(){var a=this.axes,b,e,f;c.each(this.series,function(a){f=a.getRange(),f&&(b=a.xaxis,e=a.yaxis,b.datamin=Math.min(f.xmin,b.datamin),b.datamax=Math.max(f.xmax,b.datamax),e.datamin=Math.min(f.ymin,e.datamin),e.datamax=Math.max(f.ymax,e.datamax),b.used=b.used||f.xused,e.used=e.used||f.yused)},this),!a.x.used&&!a.x2.used&&(a.x.used=!0),!a.y.used&&!a.y2.used&&(a.y.used=!0),c.each(a,function(a){a.calculateRange()});var g=c.keys(d.graphTypes),h=!1;c.each(this.series,function(a){if(a.hide)return;c.each(g,function(b){a[b]&&a[b].show&&(this.extendRange(b,a),h=!0)},this),h||this.extendRange(this.options.defaultType,a)},this)},extendRange:function(a,b){this[a].extendRange&&this[a].extendRange(b,b.data,b[a],this[a]),this[a].extendYRange&&this[a].extendYRange(b.yaxis,b.data,b[a],this[a]),this[a].extendXRange&&this[a].extendXRange(b.xaxis,b.data,b[a],this[a])},calculateSpacing:function(){var a=this.axes,b=this.options,d=this.series,e=b.grid.labelMargin,f=this._text,g=a.x,h=a.x2,i=a.y,j=a.y2,k=b.grid.outlineWidth,l,m,n,o;c.each(a,function(a){a.calculateTicks(),a.calculateTextDimensions(f,b)}),o=f.dimensions(b.title,{size:b.fontSize*1.5},"font-size:1em;font-weight:bold;","flotr-title"),this.titleHeight=o.height,o=f.dimensions(b.subtitle,{size:b.fontSize},"font-size:smaller;","flotr-subtitle"),this.subtitleHeight=o.height;for(m=0;m<b.length;++m)d[m].points.show&&(k=Math.max(k,d[m].points.radius+d[m].points.lineWidth/2));var p=this.plotOffset;g.options.margin===!1?(p.bottom=0,p.top=0):(p.bottom+=(b.grid.circular?0:g.used&&g.options.showLabels?g.maxLabel.height+e:0)+(g.used&&g.options.title?g.titleSize.height+e:0)+k,p.top+=(b.grid.circular?0:h.used&&h.options.showLabels?h.maxLabel.height+e:0)+(h.used&&h.options.title?h.titleSize.height+e:0)+this.subtitleHeight+this.titleHeight+k),i.options.margin===!1?(p.left=0,p.right=0):(p.left+=(b.grid.circular?0:i.used&&i.options.showLabels?i.maxLabel.width+e:0)+(i.used&&i.options.title?i.titleSize.width+e:0)+k,p.right+=(b.grid.circular?0:j.used&&j.options.showLabels?j.maxLabel.width+e:0)+(j.used&&j.options.title?j.titleSize.width+e:0)+k),p.top=Math.floor(p.top),this.plotWidth=this.canvasWidth-p.left-p.right,this.plotHeight=this.canvasHeight-p.bottom-p.top,g.length=h.length=this.plotWidth,i.length=j.length=this.plotHeight,i.offset=j.offset=this.plotHeight,g.setScale(),h.setScale(),i.setScale(),j.setScale()},draw:function(a){var c=this.ctx,d;b.fire(this.el,"flotr:beforedraw",[this.series,this]);if(this.series.length){c.save(),c.translate(this.plotOffset.left,this.plotOffset.top);for(d=0;d<this.series.length;d++)this.series[d].hide||this.drawSeries(this.series[d]);c.restore(),this.clip()}b.fire(this.el,"flotr:afterdraw",[this.series,this]),a&&a()},drawSeries:function(a){function b(a,b){var c=this.getOptions(a,b);this[b].draw(c)}var e=!1;a=a||this.series,c.each(d.graphTypes,function(c,d){a[d]&&a[d].show&&this[d]&&(e=!0,b.call(this,a,d))},this),e||b.call(this,a,this.options.defaultType)},getOptions:function(a,b){var c=a[b],e=this[b],f=a.xaxis,g=a.yaxis,h={context:this.ctx,width:this.plotWidth,height:this.plotHeight,fontSize:this.options.fontSize,fontColor:this.options.fontColor,textEnabled:this.textEnabled,htmlText:this.options.HtmlText,text:this._text,element:this.el,data:a.data,color:a.color,shadowSize:a.shadowSize,xScale:f.d2p,yScale:g.d2p,xInverse:f.p2d,yInverse:g.p2d};return h=d.merge(c,h),h.fillStyle=this.processColor(c.fillColor||a.color,{opacity:c.fillOpacity}),h},getEventPosition:function(c){var d=document,e=d.body,f=d.documentElement,g=this.axes,h=this.plotOffset,i=this.lastMousePos,j=b.eventPointer(c),k=j.x-i.pageX,l=j.y-i.pageY,m,n,o;return"ontouchstart"in this.el?(m=a.position(this.overlay),n=j.x-m.left-h.left,o=j.y-m.top-h.top):(m=this.overlay.getBoundingClientRect(),n=c.clientX-m.left-h.left-e.scrollLeft-f.scrollLeft,o=c.clientY-m.top-h.top-e.scrollTop-f.scrollTop),{x:g.x.p2d(n),x2:g.x2.p2d(n),y:g.y.p2d(o),y2:g.y2.p2d(o),relX:n,relY:o,dX:k,dY:l,absX:j.x,absY:j.y,pageX:j.x,pageY:j.y}},clickHandler:function(a){if(this.ignoreClick)return this.ignoreClick=!1,this.ignoreClick;b.fire(this.el,"flotr:click",[this.getEventPosition(a),this])},mouseMoveHandler:function(a){if(this.mouseDownMoveHandler)return;var c=this.getEventPosition(a);b.fire(this.el,"flotr:mousemove",[a,c,this]),this.lastMousePos=c},mouseDownHandler:function(a){if(this.mouseUpHandler)return;this.mouseUpHandler=c.bind(function(a){b.stopObserving(document,"mouseup",this.mouseUpHandler),b.stopObserving(document,"mousemove",this.mouseDownMoveHandler),this.mouseDownMoveHandler=null,this.mouseUpHandler=null,b.fire(this.el,"flotr:mouseup",[a,this])},this),this.mouseDownMoveHandler=c.bind(function(c){var d=this.getEventPosition(c);b.fire(this.el,"flotr:mousemove",[a,d,this]),this.lastMousePos=d},this),b.observe(document,"mouseup",this.mouseUpHandler),b.observe(document,"mousemove",this.mouseDownMoveHandler),b.fire(this.el,"flotr:mousedown",[a,this]),this.ignoreClick=!1},drawTooltip:function(b,c,d,e){var f=this.getMouseTrack(),g="opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;",h=e.position,i=e.margin,j=this.plotOffset;c!==null&&d!==null?(e.relative?(h.charAt(0)=="n"?g+="bottom:"+(i-j.top-d+this.canvasHeight)+"px;top:auto;":h.charAt(0)=="s"&&(g+="top:"+(i+j.top+d)+"px;bottom:auto;"),h.charAt(1)=="e"?g+="left:"+(i+j.left+c)+"px;right:auto;":h.charAt(1)=="w"&&(g+="right:"+(i-j.left-c+this.canvasWidth)+"px;left:auto;")):(h.charAt(0)=="n"?g+="top:"+(i+j.top)+"px;bottom:auto;":h.charAt(0)=="s"&&(g+="bottom:"+(i+j.bottom)+"px;top:auto;"),h.charAt(1)=="e"?g+="right:"+(i+j.right)+"px;left:auto;":h.charAt(1)=="w"&&(g+="left:"+(i+j.left)+"px;right:auto;")),f.style.cssText=g,a.empty(f),a.insert(f,b),a.show(f)):a.hide(f)},clip:function(a){var b=this.plotOffset,c=this.canvasWidth,e=this.canvasHeight;a=a||this.ctx,d.isIE&&d.isIE<9?(a.save(),a.fillStyle=this.processColor(this.options.ieBackgroundColor),a.fillRect(0,0,c,b.top),a.fillRect(0,0,b.left,e),a.fillRect(0,e-b.bottom,c,b.bottom),a.fillRect(c-b.right,0,b.right,e),a.restore()):(a.clearRect(0,0,c,b.top),a.clearRect(0,0,b.left,e),a.clearRect(0,e-b.bottom,c,b.bottom),a.clearRect(c-b.right,0,b.right,e))},_initMembers:function(){this._handles=[],this.lastMousePos={pageX:null,pageY:null},this.plotOffset={left:0,right:0,top:0,bottom:0},this.ignoreClick=!0,this.prevHit=null},_initGraphTypes:function(){c.each(d.graphTypes,function(a,b){this[b]=d.clone(a)},this)},_initEvents:function(){var a=this.el,d,e,f;"ontouchstart"in a?(d=c.bind(function(c){f=!0,b.stopObserving(document,"touchend",d),b.fire(a,"flotr:mouseup",[event,this]),this.multitouches=null,e||this.clickHandler(c)},this),this.observe(this.overlay,"touchstart",c.bind(function(c){e=!1,f=!1,this.ignoreClick=!1,c.touches&&c.touches.length>1&&(this.multitouches=c.touches),b.fire(a,"flotr:mousedown",[event,this]),this.observe(document,"touchend",d)},this)),this.observe(this.overlay,"touchmove",c.bind(function(c){var d=this.getEventPosition(c);this.options.preventDefault&&c.preventDefault(),e=!0,this.multitouches||c.touches&&c.touches.length>1?this.multitouches=c.touches:f||b.fire(a,"flotr:mousemove",[event,d,this]),this.lastMousePos=d},this))):this.observe(this.overlay,"mousedown",c.bind(this.mouseDownHandler,this)).observe(a,"mousemove",c.bind(this.mouseMoveHandler,this)).observe(this.overlay,"click",c.bind(this.clickHandler,this)).observe(a,"mouseout",function(){b.fire(a,"flotr:mouseout")})},_initCanvas:function(){function k(e,f){return e||(e=a.create("canvas"),typeof FlashCanvas!="undefined"&&typeof e.getContext=="function"&&FlashCanvas.initElement(e),e.className="flotr-"+f,e.style.cssText="position:absolute;left:0px;top:0px;",a.insert(b,e)),c.each(i,function(b,c){a.show(e);if(f=="canvas"&&e.getAttribute(c)===b)return;e.setAttribute(c,b*d.resolution),e.style[c]=b+"px"}),e.context_=null,e}function l(a){window.G_vmlCanvasManager&&window.G_vmlCanvasManager.initElement(a);var b=a.getContext("2d");return window.G_vmlCanvasManager||b.scale(d.resolution,d.resolution),b}var b=this.el,d=this.options,e=b.children,f=[],g,h,i,j;for(h=e.length;h--;)g=e[h],!this.canvas&&g.className==="flotr-canvas"?this.canvas=g:!this.overlay&&g.className==="flotr-overlay"?this.overlay=g:f.push(g);for(h=f.length;h--;)b.removeChild(f[h]);a.setStyles(b,{position:"relative"}),i={},i.width=b.clientWidth,i.height=b.clientHeight;if(i.width<=0||i.height<=0||d.resolution<=0)throw"Invalid dimensions for plot, width = "+i.width+", height = "+i.height+", resolution = "+d.resolution;this.canvas=k(this.canvas,"canvas"),this.overlay=k(this.overlay,"overlay"),this.ctx=l(this.canvas),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.octx=l(this.overlay),this.octx.clearRect(0,0,this.overlay.width,this.overlay.height),this.canvasHeight=i.height,this.canvasWidth=i.width,this.textEnabled=!!this.ctx.drawText||!!this.ctx.fillText},_initPlugins:function(){c.each(d.plugins,function(a,b){c.each(a.callbacks,function(a,b){this.observe(this.el,b,c.bind(a,this))},this),this[b]=d.clone(a),c.each(this[b],function(a,d){c.isFunction(a)&&(this[b][d]=c.bind(a,this))},this)},this)},_initOptions:function(a){var e=d.clone(d.defaultOptions);e.x2axis=c.extend(c.clone(e.xaxis),e.x2axis),e.y2axis=c.extend(c.clone(e.yaxis),e.y2axis),this.options=d.merge(a||{},e),this.options.grid.minorVerticalLines===null&&this.options.xaxis.scaling==="logarithmic"&&(this.options.grid.minorVerticalLines=!0),this.options.grid.minorHorizontalLines===null&&this.options.yaxis.scaling==="logarithmic"&&(this.options.grid.minorHorizontalLines=!0),b.fire(this.el,"flotr:afterinitoptions",[this]),this.axes=d.Axis.getAxes(this.options);var f=[],g=[],h=this.series.length,i=this.series.length,j=this.options.colors,k=[],l=0,m,n,o,p;for(n=i-1;n>-1;--n)m=this.series[n].color,m&&(--i,c.isNumber(m)?f.push(m):k.push(d.Color.parse(m)));for(n=f.length-1;n>-1;--n)i=Math.max(i,f[n]+1);for(n=0;g.length<i;){m=j.length==n?new d.Color(100,100,100):d.Color.parse(j[n]);var q=l%2==1?-1:1,r=1+q*Math.ceil(l/2)*.2;m.scale(r,r,r),g.push(m),++n>=j.length&&(n=0,++l)}for(n=0,o=0;n<h;++n){p=this.series[n],p.color?c.isNumber(p.color)&&(p.color=g[p.color].toString()):p.color=g[o++].toString(),p.xaxis||(p.xaxis=this.axes.x),p.xaxis==1?p.xaxis=this.axes.x:p.xaxis==2&&(p.xaxis=this.axes.x2),p.yaxis||(p.yaxis=this.axes.y),p.yaxis==1?p.yaxis=this.axes.y:p.yaxis==2&&(p.yaxis=this.axes.y2);for(var s in d.graphTypes)p[s]=c.extend(c.clone(this.options[s]),p[s]);p.mouse=c.extend(c.clone(this.options.mouse),p.mouse),c.isUndefined(p.shadowSize)&&(p.shadowSize=this.options.shadowSize)}},_setEl:function(a){if(!a)throw"The target container doesn't exist";if(a.graph instanceof Graph)a.graph.destroy();else if(!a.clientWidth)throw"The target container must be visible";a.graph=this,this.el=a}},Flotr.Graph=Graph}(),function(){function c(b){this.orientation=1,this.offset=0,this.datamin=Number.MAX_VALUE,this.datamax=-Number.MAX_VALUE,a.extend(this,b)}function d(a,b){return a=Math.log(Math.max(a,Number.MIN_VALUE)),b!==Math.E&&(a/=Math.log(b)),a}function e(a,b){return b===Math.E?Math.exp(a):Math.pow(b,a)}var a=Flotr._,b="logarithmic";c.prototype={setScale:function(){var a=this.length,c=this.max,f=this.min,g=this.offset,h=this.orientation,i=this.options,j=i.scaling===b,k;j?k=a/(d(c,i.base)-d(f,i.base)):k=a/(c-f),this.scale=k,j?(this.d2p=function(a){return g+h*(d(a,i.base)-d(f,i.base))*k},this.p2d=function(a){return e((g+h*a)/k+d(f,i.base),i.base)}):(this.d2p=function(a){return g+h*(a-f)*k},this.p2d=function(a){return(g+h*a)/k+f})},calculateTicks:function(){var b=this.options;this.ticks=[],this.minorTicks=[],b.ticks?(this._cleanUserTicks(b.ticks,this.ticks),this._cleanUserTicks(b.minorTicks||[],this.minorTicks)):b.mode=="time"?this._calculateTimeTicks():b.scaling==="logarithmic"?this._calculateLogTicks():this._calculateTicks(),a.each(this.ticks,function(a){a.label+=""}),a.each(this.minorTicks,function(a){a.label+=""})},calculateRange:function(){if(!this.used)return;var a=this,b=a.options,c=b.min!==null?b.min:a.datamin,d=b.max!==null?b.max:a.datamax,e=b.autoscaleMargin;b.scaling=="logarithmic"&&(c<=0&&(c=a.datamin),d<=0&&(d=c));if(d==c){var f=d?.01:1;b.min===null&&(c-=f),b.max===null&&(d+=f)}if(b.scaling==="logarithmic"){c<0&&(c=d/b.base);var g=Math.log(d);b.base!=Math.E&&(g/=Math.log(b.base)),g=Math.ceil(g);var h=Math.log(c);b.base!=Math.E&&(h/=Math.log(b.base)),h=Math.ceil(h),a.tickSize=Flotr.getTickSize(b.noTicks,h,g,b.tickDecimals===null?0:b.tickDecimals),b.minorTickFreq===null&&(g-h>10?b.minorTickFreq=0:g-h>5?b.minorTickFreq=2:b.minorTickFreq=5)}else a.tickSize=Flotr.getTickSize(b.noTicks,c,d,b.tickDecimals);a.min=c,a.max=d,b.min===null&&b.autoscale&&(a.min-=a.tickSize*e,a.min<0&&a.datamin>=0&&(a.min=0),a.min=a.tickSize*Math.floor(a.min/a.tickSize)),b.max===null&&b.autoscale&&(a.max+=a.tickSize*e,a.max>0&&a.datamax<=0&&a.datamax!=a.datamin&&(a.max=0),a.max=a.tickSize*Math.ceil(a.max/a.tickSize)),a.min==a.max&&(a.max=a.min+1)},calculateTextDimensions:function(a,b){var c="",d,e;if(this.options.showLabels)for(e=0;e<this.ticks.length;++e)d=this.ticks[e].label.length,d>c.length&&(c=this.ticks[e].label);this.maxLabel=a.dimensions(c,{size:b.fontSize,angle:Flotr.toRad(this.options.labelsAngle)},"font-size:smaller;","flotr-grid-label"),this.titleSize=a.dimensions(this.options.title,{size:b.fontSize*1.2,angle:Flotr.toRad(this.options.titleAngle)},"font-weight:bold;","flotr-axis-title")},_cleanUserTicks:function(b,c){var d=this,e=this.options,f,g,h,i;a.isFunction(b)&&(b=b({min:d.min,max:d.max}));for(g=0;g<b.length;++g)i=b[g],typeof i=="object"?(f=i[0],h=i.length>1?i[1]:e.tickFormatter(f,{min:d.min,max:d.max})):(f=i,h=e.tickFormatter(f,{min:this.min,max:this.max})),c[g]={v:f,label:h}},_calculateTimeTicks:function(){this.ticks=Flotr.Date.generator(this)},_calculateLogTicks:function(){var a=this,b=a.options,c,d,e=Math.log(a.max);b.base!=Math.E&&(e/=Math.log(b.base)),e=Math.ceil(e);var f=Math.log(a.min);b.base!=Math.E&&(f/=Math.log(b.base)),f=Math.ceil(f);for(i=f;i<e;i+=a.tickSize){d=b.base==Math.E?Math.exp(i):Math.pow(b.base,i);var g=d*(b.base==Math.E?Math.exp(a.tickSize):Math.pow(b.base,a.tickSize)),h=(g-d)/b.minorTickFreq;a.ticks.push({v:d,label:b.tickFormatter(d,{min:a.min,max:a.max})});for(c=d+h;c<g;c+=h)a.minorTicks.push({v:c,label:b.tickFormatter(c,{min:a.min,max:a.max})})}d=b.base==Math.E?Math.exp(i):Math.pow(b.base,i),a.ticks.push({v:d,label:b.tickFormatter(d,{min:a.min,max:a.max})})},_calculateTicks:function(){var a=this,b=a.options,c=a.tickSize,d=a.min,e=a.max,f=c*Math.ceil(d/c),g,h,i,j,k,l;b.minorTickFreq&&(h=c/b.minorTickFreq);for(k=0;(i=j=f+k*c)<=e;++k){g=b.tickDecimals,g===null&&(g=1-Math.floor(Math.log(c)/Math.LN10)),g<0&&(g=0),i=i.toFixed(g),a.ticks.push({v:i,label:b.tickFormatter(i,{min:a.min,max:a.max})});if(b.minorTickFreq)for(l=0;l<b.minorTickFreq&&k*c+l*h<e;++l)i=j+l*h,a.minorTicks.push({v:i,label:b.tickFormatter(i,{min:a.min,max:a.max})})}}},a.extend(c,{getAxes:function(a){return{x:new c({options:a.xaxis,n:1,length:this.plotWidth}),x2:new c({options:a.x2axis,n:2,length:this.plotWidth}),y:new c({options:a.yaxis,n:1,length:this.plotHeight,offset:this.plotHeight,orientation:-1}),y2:new c({options:a.y2axis,n:2,length:this.plotHeight,offset:this.plotHeight,orientation:-1})}}}),Flotr.Axis=c}(),function(){function b(b){a.extend(this,b)}var a=Flotr._;b.prototype={getRange:function(){var a=this.data,b=a.length,c=Number.MAX_VALUE,d=Number.MAX_VALUE,e=-Number.MAX_VALUE,f=-Number.MAX_VALUE,g=!1,h=!1,i,j,k;if(b<0||this.hide)return!1;for(k=0;k<b;k++)i=a[k][0],j=a[k][1],i!==null&&(i<c&&(c=i,g=!0),i>e&&(e=i,g=!0)),j!==null&&(j<d&&(d=j,h=!0),j>f&&(f=j,h=!0));return{xmin:c,xmax:e,ymin:d,ymax:f,xused:g,yused:h}}},a.extend(b,{getSeries:function(c){return a.map(c,function(c){var d;return c.data?(d=new b,a.extend(d,c)):d=new b({data:c}),d})}}),Flotr.Series=b}(),Flotr.addType("lines",{options:{show:!1,lineWidth:2,fill:!1,fillBorder:!1,fillColor:null,fillOpacity:.4,steps:!1,stacked:!1},stack:{values:[]},draw:function(a){var b=a.context,c=a.lineWidth,d=a.shadowSize,e;b.save(),b.lineJoin="round",d&&(b.lineWidth=d/2,e=c/2+b.lineWidth/2,b.strokeStyle="rgba(0,0,0,0.1)",this.plot(a,e+d/2,!1),b.strokeStyle="rgba(0,0,0,0.2)",this.plot(a,e,!1)),b.lineWidth=c,b.strokeStyle=a.color,this.plot(a,0,!0),b.restore()},plot:function(a,b,c){function w(){!b&&a.fill&&o&&(p=g(o[0]),d.fillStyle=a.fillStyle,d.lineTo(q,n),d.lineTo(p,n),d.lineTo(p,h(o[1])),d.fill(),a.fillBorder&&d.stroke())}var d=a.context,e=a.width,f=a.height,g=a.xScale,h=a.yScale,i=a.data,j=a.stacked?this.stack:!1,k=i.length-1,l=null,m=null,n=h(0),o=null,p,q,r,s,t,u,v;if(k<1)return;d.beginPath();for(v=0;v<k;++v){if(i[v][1]===null||i[v+1][1]===null){a.fill&&v>0&&i[v][1]&&(d.stroke(),w(),o=null,d.closePath(),d.beginPath());continue}p=g(i[v][0]),q=g(i[v+1][0]),o===null&&(o=i[v]),j?(t=j.values[i[v][0]]||0,u=j.values[i[v+1][0]]||j.values[i[v][0]]||0,r=h(i[v][1]+t),s=h(i[v+1][1]+u),c&&(j.values[i[v][0]]=i[v][1]+t,v==k-1&&(j.values[i[v+1][0]]=i[v+1][1]+u))):(r=h(i[v][1]),s=h(i[v+1][1]));if(r>f&&s>f||r<0&&s<0||p<0&&q<0||p>e&&q>e)continue;(l!=p||m!=r+b)&&d.moveTo(p,r+b),l=q,m=s+b,a.steps?(d.lineTo(l+b/2,r+b),d.lineTo(l+b/2,m)):d.lineTo(l,m)}(!a.fill||a.fill&&!a.fillBorder)&&d.stroke(),w(),d.closePath()},extendYRange:function(a,b,c,d){var e=a.options;if(c.stacked&&(!e.max&&e.max!==0||!e.min&&e.min!==0)){var f=a.max,g=a.min,h=d.positiveSums||{},i=d.negativeSums||{},j,k;for(k=0;k<b.length;k++)j=b[k][0]+"",b[k][1]>0?(h[j]=(h[j]||0)+b[k][1],f=Math.max(f,h[j])):(i[j]=(i[j]||0)+b[k][1],g=Math.min(g,i[j]));d.negativeSums=i,d.positiveSums=h,a.max=f,a.min=g}c.steps&&(this.hit=function(a){var b=a.data,c=a.args,d=a.yScale,e=c[0],f=b.length,g=c[1],h=a.xInverse(e.relX),i=e.relY,j;for(j=0;j<f-1;j++)if(h>=b[j][0]&&h<=b[j+1][0]){Math.abs(d(b[j][1])-i)<8&&(g.x=b[j][0],g.y=b[j][1],g.index=j,g.seriesIndex=a.index);break}},this.drawHit=function(a){var b=a.context,c=a.args,d=a.data,e=a.xScale,f=c.index,g=e(c.x),h=a.yScale(c.y),i;d.length-1>f&&(i=a.xScale(d[f+1][0]),b.save(),b.strokeStyle=a.color,b.lineWidth=a.lineWidth,b.beginPath(),b.moveTo(g,h),b.lineTo(i,h),b.stroke(),b.closePath(),b.restore())},this.clearHit=function(a){var b=a.context,c=a.args,d=a.data,e=a.xScale,f=a.lineWidth,g=c.index,h=e(c.x),i=a.yScale(c.y),j;d.length-1>g&&(j=a.xScale(d[g+1][0]),b.clearRect(h-f,i-f,j-h+2*f,2*f))})}}),Flotr.addType("bars",{options:{show:!1,lineWidth:2,barWidth:1,fill:!0,fillColor:null,fillOpacity:.4,horizontal:!1,stacked:!1,centered:!0,topPadding:.1,grouped:!1},stack:{positive:[],negative:[],_positive:[],_negative:[]},draw:function(a){var b=a.context;this.current+=1,b.save(),b.lineJoin="miter",b.lineWidth=a.lineWidth,b.strokeStyle=a.color,a.fill&&(b.fillStyle=a.fillStyle),this.plot(a),b.restore()},plot:function(a){var b=a.data,c=a.context,d=a.shadowSize,e,f,g,h,i,j;if(b.length<1)return;this.translate(c,a.horizontal);for(e=0;e<b.length;e++){f=this.getBarGeometry(b[e][0],b[e][1],a);if(f===null)continue;g=f.left,h=f.top,i=f.width,j=f.height,a.fill&&c.fillRect(g,h,i,j),d&&(c.save(),c.fillStyle="rgba(0,0,0,0.05)",c.fillRect(g+d,h+d,i,j),c.restore()),a.lineWidth&&c.strokeRect(g,h,i,j)}},translate:function(a,b){b&&(a.rotate(-Math.PI/2),a.scale(-1,1))},getBarGeometry:function(a,b,c){var d=c.horizontal,e=c.barWidth,f=c.centered,g=c.stacked?this.stack:!1,h=c.lineWidth,i=f?e/2:0,j=d?c.yScale:c.xScale,k=d?c.xScale:c.yScale,l=d?b:a,m=d?a:b,n=0,o,p,q,r,s;return c.grouped&&(this.current/this.groups,l-=i,e/=this.groups,i=e/2,l=l+e*this.current-i),g&&(o=m>0?g.positive:g.negative,n=o[l]||n,o[l]=n+m),p=j(l-i),q=j(l+e-i),r=k(m+n),s=k(n),s<0&&(s=0),a===null||b===null?null:{x:l,y:m,xScale:j,yScale:k,top:r,left:Math.min(p,q)-h/2,width:Math.abs(q-p)-h,height:s-r}},hit:function(a){var b=a.data,c=a.args,d=c[0],e=c[1],f=a.xInverse(d.relX),g=a.yInverse(d.relY),h=this.getBarGeometry(f,g,a),i=h.width/2,j=h.left,k=h.y,l,m;for(m=b.length;m--;)l=this.getBarGeometry(b[m][0],b[m][1],a),(k>0&&k<l.y||k<0&&k>l.y)&&Math.abs(j-l.left)<i&&(e.x=b[m][0],e.y=b[m][1],e.index=m,e.seriesIndex=a.index)},drawHit:function(a){var b=a.context,c=a.args,d=this.getBarGeometry(c.x,c.y,a),e=d.left,f=d.top,g=d.width,h=d.height;b.save(),b.strokeStyle=a.color,b.lineWidth=a.lineWidth,this.translate(b,a.horizontal),b.beginPath(),b.moveTo(e,f+h),b.lineTo(e,f),b.lineTo(e+g,f),b.lineTo(e+g,f+h),a.fill&&(b.fillStyle=a.fillStyle,b.fill()),b.stroke(),b.closePath(),b.restore()},clearHit:function(a){var b=a.context,c=a.args,d=this.getBarGeometry(c.x,c.y,a),e=d.left,f=d.width,g=d.top,h=d.height,i=2*a.lineWidth;b.save(),this.translate(b,a.horizontal),b.clearRect(e-i,Math.min(g,g+h)-i,f+2*i,Math.abs(h)+2*i),b.restore()},extendXRange:function(a,b,c,d){this._extendRange(a,b,c,d),this.groups=this.groups+1||1,this.current=0},extendYRange:function(a,b,c,d){this._extendRange(a,b,c,d)},_extendRange:function(a,b,c,d){var e=a.options.max;if(_.isNumber(e)||_.isString(e))return;var f=a.min,g=a.max,h=c.horizontal,i=a.orientation,j=this.positiveSums||{},k=this.negativeSums||{},l,m,n,o;(i==1&&!h||i==-1&&h)&&c.centered&&(g=Math.max(a.datamax+c.barWidth,g),f=Math.min(a.datamin-c.barWidth,f));if(c.stacked&&(i==1&&h||i==-1&&!h))for(o=b.length;o--;)l=b[o][i==1?1:0]+"",m=b[o][i==1?0:1],m>0?(j[l]=(j[l]||0)+m,g=Math.max(g,j[l])):(k[l]=(k[l]||0)+m,f=Math.min(f,k[l]));(i==1&&h||i==-1&&!h)&&c.topPadding&&(a.max===a.datamax||c.stacked&&this.stackMax!==g)&&(g+=c.topPadding*(g-f)),this.stackMin=f,this.stackMax=g,this.negativeSums=k,this.positiveSums=j,a.max=g,a.min=f}}),Flotr.addType("bubbles",{options:{show:!1,lineWidth:2,fill:!0,fillOpacity:.4,baseRadius:2},draw:function(a){var b=a.context,c=a.shadowSize;b.save(),b.lineWidth=a.lineWidth,b.fillStyle="rgba(0,0,0,0.05)",b.strokeStyle="rgba(0,0,0,0.05)",this.plot(a,c/2),b.strokeStyle="rgba(0,0,0,0.1)",this.plot(a,c/4),b.strokeStyle=a.color,b.fillStyle=a.fillStyle,this.plot(a),b.restore()},plot:function(a,b){var c=a.data,d=a.context,e,f,g,h,i;b=b||0;for(f=0;f<c.length;++f)e=this.getGeometry(c[f],a),d.beginPath(),d.arc(e.x+b,e.y+b,e.z,0,2*Math.PI,!0),d.stroke(),a.fill&&d.fill(),d.closePath()},getGeometry:function(a,b){return{x:b.xScale(a[0]),y:b.yScale(a[1]),z:a[2]*b.baseRadius}},hit:function(a){var b=a.data,c=a.args,d=c[0],e=c[1],f=d.relX,g=d.relY,h,j,k,l;e.best=e.best||Number.MAX_VALUE;for(i=b.length;i--;)j=this.getGeometry(b[i],a),k=j.x-f,l=j.y-g,h=Math.sqrt(k*k+l*l),h<j.z&&j.z<e.best&&(e.x=b[i][0],e.y=b[i][1],e.index=i,e.seriesIndex=a.index,e.best=j.z)},drawHit:function(a){var b=a.context,c=this.getGeometry(a.data[a.args.index],a);b.save(),b.lineWidth=a.lineWidth,b.fillStyle=a.fillStyle,b.strokeStyle=a.color,b.beginPath(),b.arc(c.x,c.y,c.z,0,2*Math.PI,!0),b.fill(),b.stroke(),b.closePath(),b.restore()},clearHit:function(a){var b=a.context,c=this.getGeometry(a.data[a.args.index],a),d=c.z+a.lineWidth;b.save(),b.clearRect(c.x-d,c.y-d,2*d,2*d),b.restore()}}),Flotr.addType("candles",{options:{show:!1,lineWidth:1,wickLineWidth:1,candleWidth:.6,fill:!0,upFillColor:"#00A8F0",downFillColor:"#CB4B4B",fillOpacity:.5,barcharts:!1},draw:function(a){var b=a.context;b.save(),b.lineJoin="miter",b.lineCap="butt",b.lineWidth=a.wickLineWidth||a.lineWidth,this.plot(a),b.restore()},plot:function(a){var b=a.data,c=a.context,d=a.xScale,e=a.yScale,f=a.candleWidth/2,g=a.shadowSize,h=a.lineWidth,i=a.wickLineWidth,j=i%2/2,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y;if(b.length<1)return;for(y=0;y<b.length;y++){l=b[y],m=l[0],o=l[1],p=l[2],q=l[3],r=l[4],s=d(m-f),t=d(m+f),u=e(q),v=e(p),w=e(Math.min(o,r)),x=e(Math.max(o,r)),k=a[o>r?"downFillColor":"upFillColor"],a.fill&&!a.barcharts&&(c.fillStyle="rgba(0,0,0,0.05)",c.fillRect(s+g,x+g,t-s,w-x),c.save(),c.globalAlpha=a.fillOpacity,c.fillStyle=k,c.fillRect(s,x+h,t-s,w-x),c.restore());if(h||i)m=Math.floor((s+t)/2)+j,c.strokeStyle=k,c.beginPath(),a.barcharts?(c.moveTo(m,Math.floor(v+f)),c.lineTo(m,Math.floor(u+f)),n=Math.floor(o+f)+.5,c.moveTo(Math.floor(s)+j,n),c.lineTo(m,n),n=Math.floor(r+f)+.5,c.moveTo(Math.floor(t)+j,n),c.lineTo(m,n)):(c.strokeRect(s,x+h,t-s,w-x),c.moveTo(m,Math.floor(x+h)),c.lineTo(m,Math.floor(v+h)),c.moveTo(m,Math.floor(w+h)),c.lineTo(m,Math.floor(u+h))),c.closePath(),c.stroke()}},extendXRange:function(a,b,c){a.options.max===null&&(a.max=Math.max(a.datamax+.5,a.max),a.min=Math.min(a.datamin-.5,a.min))}}),Flotr.addType("gantt",{options:{show:!1,lineWidth:2,barWidth:1,fill:!0,fillColor:null,fillOpacity:.4,centered:!0},draw:function(a){var b=this.ctx,c=a.gantt.barWidth,d=Math.min(a.gantt.lineWidth,c);b.save(),b.translate(this.plotOffset.left,this.plotOffset.top),b.lineJoin="miter",b.lineWidth=d,b.strokeStyle=a.color,b.save(),this.gantt.plotShadows(a,c,0,a.gantt.fill),b.restore();if(a.gantt.fill){var e=a.gantt.fillColor||a.color;b.fillStyle=this.processColor(e,{opacity:a.gantt.fillOpacity})}this.gantt.plot(a,c,0,a.gantt.fill),b.restore()},plot:function(a,b,c,d){var e=a.data;if(e.length<1)return;var f=a.xaxis,g=a.yaxis,h=this.ctx,i;for(i=0;i<e.length;i++){var j=e[i][0],k=e[i][1],l=e[i][2],m=!0,n=!0,o=!0;if(k===null||l===null)continue;var p=k,q=k+l,r=j-(a.gantt.centered?b/2:0),s=j+b-(a.gantt.centered?b/2:0);if(q<f.min||p>f.max||s<g.min||r>g.max)continue;p<f.min&&(p=f.min,m=!1),q>f.max&&(q=f.max,f.lastSerie!=a&&(n=!1)),r<g.min&&(r=g.min),s>g.max&&(s=g.max,g.lastSerie!=a&&(n=!1)),d&&(h.beginPath(),h.moveTo(f.d2p(p),g.d2p(r)+c),h.lineTo(f.d2p(p),g.d2p(s)+c),h.lineTo(f.d2p(q),g.d2p(s)+c),h.lineTo(f.d2p(q),g.d2p(r)+c),h.fill(),h.closePath()),a.gantt.lineWidth&&(m||o||n)&&(h.beginPath(),h.moveTo(f.d2p(p),g.d2p(r)+c),h[m?"lineTo":"moveTo"](f.d2p(p),g.d2p(s)+c),h[n?"lineTo":"moveTo"](f.d2p(q),g.d2p(s)+c),h[o?"lineTo":"moveTo"](f.d2p(q),g.d2p(r)+c),h.stroke(),h.closePath())}},plotShadows:function(a,b,c){var d=a.data;if(d.length<1)return;var e,f,g,h,i=a.xaxis,j=a.yaxis,k=this.ctx,l=this.options.shadowSize;for(e=0;e<d.length;e++){f=d[e][0],g=d[e][1],h=d[e][2];if(g===null||h===null)continue;var m=g,n=g+h,o=f-(a.gantt.centered?b/2:0),p=f+b-(a.gantt.centered?b/2:0);if(n<i.min||m>i.max||p<j.min||o>j.max)continue;m<i.min&&(m=i.min),n>i.max&&(n=i.max),o<j.min&&(o=j.min),p>j.max&&(p=j.max);var q=i.d2p(n)-i.d2p(m)-(i.d2p(n)+l<=this.plotWidth?0:l),r=j.d2p(o)-j.d2p(p)-(j.d2p(o)+l<=this.plotHeight?0:l);k.fillStyle="rgba(0,0,0,0.05)",k.fillRect(Math.min(i.d2p(m)+l,this.plotWidth),Math.min(j.d2p(p)+l,this.plotHeight),q,r)}},extendXRange:function(a){if(a.options.max===null){var b=a.min,c=a.max,d,e,f,g,h,i={},j={},k=null;for(d=0;d<this.series.length;++d){g=this.series[d],h=g.gantt;if(h.show&&g.xaxis==a){for(e=0;e<g.data.length;e++)h.show&&(y=g.data[e][0]+"",i[y]=Math.max(i[y]||0,g.data[e][1]+g.data[e][2]),k=g);for(e in i)c=Math.max(i[e],c)}}a.lastSerie=k,a.max=c,a.min=b}},extendYRange:function(a){if(a.options.max===null){var b=Number.MIN_VALUE,c=Number.MAX_VALUE,d,e,f,g,h={},i={},j=null;for(d=0;d<this.series.length;++d){f=this.series[d],g=f.gantt;if(g.show&&!f.hide&&f.yaxis==a){var k=Number.MIN_VALUE,l=Number.MAX_VALUE;for(e=0;e<f.data.length;e++)k=Math.max(k,f.data[e][0]),l=Math.min(l,f.data[e][0]);g.centered?(b=Math.max(k+.5,b),c=Math.min(l-.5,c)):(b=Math.max(k+1,b),c=Math.min(l,c)),g.barWidth+k>b&&(b=a.max+g.barWidth)}}a.lastSerie=j,a.max=b,a.min=c,a.tickSize=Flotr.getTickSize(a.options.noTicks,c,b,a.options.tickDecimals)}}}),function(){function a(a){return typeof a=="object"&&a.constructor&&(Image?!0:a.constructor===Image)}Flotr.defaultMarkerFormatter=function(a){return Math.round(a.y*100)/100+""},Flotr.addType("markers",{options:{show:!1,lineWidth:1,color:"#000000",fill:!1,fillColor:"#FFFFFF",fillOpacity:.4,stroke:!1,position:"ct",verticalMargin:0,labelFormatter:Flotr.defaultMarkerFormatter,fontSize:Flotr.defaultOptions.fontSize,stacked:!1,stackingType:"b",horizontal:!1},stack:{positive:[],negative:[],values:[]},draw:function(a){function m(a,b){return g=d.negative[a]||0,f=d.positive[a]||0,b>0?(d.positive[a]=g+b,g+b):(d.negative[a]=f+b,f+b)}var b=a.data,c=a.context,d=a.stacked?a.stack:!1,e=a.stackingType,f,g,h,i,j,k,l;c.save(),c.lineJoin="round",c.lineWidth=a.lineWidth,c.strokeStyle="rgba(0,0,0,0.5)",c.fillStyle=a.fillStyle;for(i=0;i<b.length;++i)j=b[i][0],k=b[i][1],d&&(e=="b"?a.horizontal?k=m(k,j):j=m(j,k):e=="a"&&(h=d.values[j]||0,d.values[j]=h+k,k=h+k)),l=a.labelFormatter({x:j,y:k,index:i,data:b}),this.plot(a.xScale(j),a.yScale(k),l,a);c.restore()},plot:function(b,c,d,e){var f=e.context;if(a(d)&&!d.complete)throw"Marker image not loaded.";this._plot(b,c,d,e)},_plot:function(b,c,d,e){var f=e.context,g=2,h=b,i=c,j;a(d)?j={height:d.height,width:d.width}:j=e.text.canvas(d),j.width=Math.floor(j.width+g*2),j.height=Math.floor(j.height+g*2),e.position.indexOf("c")!=-1?h-=j.width/2+g:e.position.indexOf("l")!=-1&&(h-=j.width),e.position.indexOf("m")!=-1?i-=j.height/2+g:e.position.indexOf("t")!=-1?i-=j.height+e.verticalMargin:i+=e.verticalMargin,h=Math.floor(h)+.5,i=Math.floor(i)+.5,e.fill&&f.fillRect(h,i,j.width,j.height),e.stroke&&f.strokeRect(h,i,j.width,j.height),a(d)?f.drawImage(d,h+g,i+g):Flotr.drawText(f,d,h+g,i+g,{textBaseline:"top",textAlign:"left",size:e.fontSize,color:e.color})}})}(),function(){var a=Flotr._;Flotr.defaultPieLabelFormatter=function(a,b){return(100*b/a).toFixed(2)+"%"},Flotr.addType("pie",{options:{show:!1,lineWidth:1,fill:!0,fillColor:null,fillOpacity:.6,explode:6,sizeRatio:.6,startAngle:Math.PI/4,labelFormatter:Flotr.defaultPieLabelFormatter,pie3D:!1,pie3DviewAngle:Math.PI/2*.8,pie3DspliceThickness:20,epsilon:.1},draw:function(a){var b=a.data,c=a.context,d=c.canvas,e=a.lineWidth,f=a.shadowSize,g=a.sizeRatio,h=a.height,i=a.width,j=a.explode,k=a.color,l=a.fill,m=a.fillStyle,n=Math.min(d.width,d.height)*g/2,o=b[0][1],p=[],q=1,r=Math.PI*2*o/this.total,s=this.startAngle||2*Math.PI*a.startAngle,t=s+r,u=s+r/2,v=a.labelFormatter(this.total,o),w=j+n+4,x=Math.cos(u)*w,y=Math.sin(u)*w,z=x<0?"right":"left",A=y>0?"top":"bottom",B,C,D;c.save(),c.translate(i/2,h/2),c.scale(1,q),C=Math.cos(u)*j,D=Math.sin(u)*j,f>0&&(this.plotSlice(C+f,D+f,n,s,t,c),l&&(c.fillStyle="rgba(0,0,0,0.1)",c.fill())),this.plotSlice(C,D,n,s,t,c),l&&(c.fillStyle=m,c.fill()),c.lineWidth=e,c.strokeStyle=k,c.stroke(),B={size:a.fontSize*1.2,color:a.fontColor,weight:1.5},v&&(a.htmlText||!a.textEnabled?(divStyle="position:absolute;"+A+":"+(h/2+(A==="top"?y:-y))+"px;",divStyle+=z+":"+(i/2+(z==="right"?-x:x))+"px;",p.push('<div style="',divStyle,'" class="flotr-grid-label">',v,"</div>")):(B.textAlign=z,B.textBaseline=A,Flotr.drawText(c,v,x,y,B)));if(a.htmlText||!a.textEnabled){var E=Flotr.DOM.node('<div style="color:'+a.fontColor+'" class="flotr-labels"></div>');Flotr.DOM.insert(E,p.join("")),Flotr.DOM.insert(a.element,E)}c.restore(),this.startAngle=t,this.slices=this.slices||[],this.slices.push({radius:Math.min(d.width,d.height)*g/2,x:C,y:D,explode:j,start:s,end:t})},plotSlice:function(a,b,c,d,e,f){f.beginPath(),f.moveTo(a,b),f.arc(a,b,c,d,e,!1),f.lineTo(a,b),f.closePath()},hit:function(a){var b=a.data[0],c=a.args,d=a.index,e=c[0],f=c[1],g=this.slices[d],h=e.relX-a.width/2,i=e.relY-a.height/2,j=Math.sqrt(h*h+i*i),k=Math.atan(i/h),l=Math.PI*2,m=g.explode||a.explode,n=g.start%l,o=g.end%l,p=a.epsilon;h<0?k+=Math.PI:h>0&&i<0&&(k+=l),j<g.radius+m&&j>m&&(k>n&&k<o||n>o&&(k<o||k>n)||n===o&&(g.start===g.end&&Math.abs(k-n)<p||g.start!==g.end&&Math.abs(k-n)>p))&&(f.x=b[0],f.y=b[1],f.sAngle=n,f.eAngle=o,f.index=0,f.seriesIndex=d,f.fraction=b[1]/this.total)},drawHit:function(a){var b=a.context,c=this.slices[a.args.seriesIndex];b.save(),b.translate(a.width/2,a.height/2),this.plotSlice(c.x,c.y,c.radius,c.start,c.end,b),b.stroke(),b.restore()},clearHit:function(a){var b=a.context,c=this.slices[a.args.seriesIndex],d=2*a.lineWidth,e=c.radius+d;b.save(),b.translate(a.width/2,a.height/2),b.clearRect(c.x-e,c.y-e,2*e+d,2*e+d),b.restore()},extendYRange:function(a,b){this.total=(this.total||0)+b[0][1]}})}(),Flotr.addType("points",{options:{show:!1,radius:3,lineWidth:2,fill:!0,fillColor:"#FFFFFF",fillOpacity:1,hitRadius:null},draw:function(a){var b=a.context,c=a.lineWidth,d=a.shadowSize;b.save(),d>0&&(b.lineWidth=d/2,b.strokeStyle="rgba(0,0,0,0.1)",this.plot(a,d/2+b.lineWidth/2),b.strokeStyle="rgba(0,0,0,0.2)",this.plot(a,b.lineWidth/2)),b.lineWidth=a.lineWidth,b.strokeStyle=a.color,a.fill&&(b.fillStyle=a.fillStyle),this.plot(a),b.restore()},plot:function(a,b){var c=a.data,d=a.context,e=a.xScale,f=a.yScale,g,h,i;for(g=c.length-1;g>-1;--g){i=c[g][1];if(i===null)continue;h=e(c[g][0]),i=f(i);if(h<0||h>a.width||i<0||i>a.height)continue;d.beginPath(),b?d.arc(h,i+b,a.radius,0,Math.PI,!1):(d.arc(h,i,a.radius,0,2*Math.PI,!0),a.fill&&d.fill()),d.stroke(),d.closePath()}}}),Flotr.addType("radar",{options:{show:!1,lineWidth:2,fill:!0,fillOpacity:.4,radiusRatio:.9},draw:function(a){var b=a.context,c=a.shadowSize;b.save(),b.translate(a.width/2,a.height/2),b.lineWidth=a.lineWidth,b.fillStyle="rgba(0,0,0,0.05)",b.strokeStyle="rgba(0,0,0,0.05)",this.plot(a,c/2),b.strokeStyle="rgba(0,0,0,0.1)",this.plot(a,c/4),b.strokeStyle=a.color,b.fillStyle=a.fillStyle,this.plot(a),b.restore()},plot:function(a,b){var c=a.data,d=a.context,e=Math.min(a.height,a.width)*a.radiusRatio/2,f=2*Math.PI/c.length,g=-Math.PI/2,h,i;b=b||0,d.beginPath();for(h=0;h<c.length;++h)i=c[h][1]/this.max,d[h===0?"moveTo":"lineTo"](Math.cos(h*f+g)*e*i+b,Math.sin(h*f+g)*e*i+b);d.closePath(),a.fill&&d.fill(),d.stroke()},extendYRange:function(a,b){this.max=Math.max(a.max,this.max||-Number.MAX_VALUE)}}),Flotr.addType("timeline",{options:{show:!1,lineWidth:1,barWidth:.2,fill:!0,fillColor:null,fillOpacity:.4,centered:!0},draw:function(a){var b=a.context;b.save(),b.lineJoin="miter",b.lineWidth=a.lineWidth,b.strokeStyle=a.color,b.fillStyle=a.fillStyle,this.plot(a),b.restore()},plot:function(a){var b=a.data,c=a.context,d=a.xScale,e=a.yScale,f=a.barWidth,g=a.lineWidth,h;Flotr._.each(b,function(a){var b=a[0],h=a[1],i=a[2],j=f,k=Math.ceil(d(b)),l=Math.ceil(d(b+i))-k,m=Math.round(e(h)),n=Math.round(e(h-j))-m,o=k-g/2,p=Math.round(m-n/2)-g/2;c.strokeRect(o,p,l,n),c.fillRect(o,p,l,n)})},extendRange:function(a){var b=a.data,c=a.xaxis,d=a.yaxis,e=a.timeline.barWidth;c.options.min===null&&(c.min=c.datamin-e/2);if(c.options.max===null){var f=c.max;Flotr._.each(b,function(a){f=Math.max(f,a[0]+a[2])},this),c.max=f+e/2}d.options.min===null&&(d.min=d.datamin-e),d.options.min===null&&(d.max=d.datamax+e)}}),function(){var a=Flotr.DOM;Flotr.addPlugin("crosshair",{options:{mode:null,color:"#FF0000",hideCursor:!0},callbacks:{"flotr:mousemove":function(a,b){this.options.crosshair.mode&&(this.crosshair.clearCrosshair(),this.crosshair.drawCrosshair(b))}},drawCrosshair:function(b){var c=this.octx,d=this.options.crosshair,e=this.plotOffset,f=e.left+Math.round(b.relX)+.5,g=e.top+Math.round(b.relY)+.5;if(b.relX<0||b.relY<0||b.relX>this.plotWidth||b.relY>this.plotHeight){this.el.style.cursor=null,a.removeClass(this.el,"flotr-crosshair");return}d.hideCursor&&(this.el.style.cursor="none",a.addClass(this.el,"flotr-crosshair")),c.save(),c.strokeStyle=d.color,c.lineWidth=1,c.beginPath(),d.mode.indexOf("x")!=-1&&(c.moveTo(f,e.top),c.lineTo(f,e.top+this.plotHeight)),d.mode.indexOf("y")!=-1&&(c.moveTo(e.left,g),c.lineTo(e.left+this.plotWidth,g)),c.stroke(),c.restore()},clearCrosshair:function(){var a=this.plotOffset,b=this.lastMousePos,c=this.octx;b&&(c.clearRect(Math.round(b.relX)+a.left,a.top,1,this.plotHeight+1),c.clearRect(a.left,Math.round(b.relY)+a.top,this.plotWidth+1,1))}})}(),function(){function c(a,b,c,d){var e="image/"+a,f=b.toDataURL(e),g=new Image;return g.src=f,g}var a=Flotr.DOM,b=Flotr._;Flotr.addPlugin("download",{saveImage:function(d,e,f,g){var h=null;if(Flotr.isIE&&Flotr.isIE<9)return h="<html><body>"+this.canvas.firstChild.innerHTML+"</body></html>",window.open().document.write(h);if(d!=="jpeg"&&d!=="png")return;h=c(d,this.canvas,e,f);if(!b.isElement(h)||!g)return window.open(h.src);this.download.restoreCanvas(),a.hide(this.canvas),a.hide(this.overlay),a.setStyles({position:"absolute"}),a.insert(this.el,h),this.saveImageElement=h},restoreCanvas:function(){a.show(this.canvas),a.show(this.overlay),this.saveImageElement&&this.el.removeChild(this.saveImageElement),this.saveImageElement=null}})}(),function(){var a=Flotr.EventAdapter,b=Flotr._;Flotr.addPlugin("graphGrid",{callbacks:{"flotr:beforedraw":function(){this.graphGrid.drawGrid()},"flotr:afterdraw":function(){this.graphGrid.drawOutline()}},drawGrid:function(){function p(a){for(n=0;n<a.length;++n){var b=a[n].v/l.max;for(o=0;o<=u;++o)c[o===0?"moveTo":"lineTo"](Math.cos(o*v+w)*t*b,Math.sin(o*v+w)*t*b)}}function q(a,d){b.each(b.pluck(a,"v"),function(a){if(a<=l.min||a>=l.max||(a==l.min||a==l.max)&&e.outlineWidth)return;d(Math.floor(l.d2p(a))+c.lineWidth/2)})}function r(a){c.moveTo(a,0),c.lineTo(a,j)}function s(a){c.moveTo(0,a),c.lineTo(k,a)}var c=this.ctx,d=this.options,e=d.grid,f=e.verticalLines,g=e.horizontalLines,h=e.minorVerticalLines,i=e.minorHorizontalLines,j=this.plotHeight,k=this.plotWidth,l,m,n,o;(f||h||g||i)&&a.fire(this.el,"flotr:beforegrid",[this.axes.x,this.axes.y,d,this]),c.save(),c.lineWidth=1,c.strokeStyle=e.tickColor;if(e.circular){c.translate(this.plotOffset.left+k/2,this.plotOffset.top+j/2);var t=Math.min(j,k)*d.radar.radiusRatio/2,u=this.axes.x.ticks.length,v=2*(Math.PI/u),w=-Math.PI/2;c.beginPath(),l=this.axes.y,g&&p(l.ticks),i&&p(l.minorTicks),f&&b.times(u,function(a){c.moveTo(0,0),c.lineTo(Math.cos(a*v+w)*t,Math.sin(a*v+w)*t)}),c.stroke()}else c.translate(this.plotOffset.left,this.plotOffset.top),e.backgroundColor&&(c.fillStyle=this.processColor(e.backgroundColor,{x1:0,y1:0,x2:k,y2:j}),c.fillRect(0,0,k,j)),c.beginPath(),l=this.axes.x,f&&q(l.ticks,r),h&&q(l.minorTicks,r),l=this.axes.y,g&&q(l.ticks,s),i&&q(l.minorTicks,s),c.stroke();c.restore(),(f||h||g||i)&&a.fire(this.el,"flotr:aftergrid",[this.axes.x,this.axes.y,d,this])},drawOutline:function(){var a=this,b=a.options,c=b.grid,d=c.outline,e=a.ctx,f=c.backgroundImage,g=a.plotOffset,h=g.left,j=g.top,k=a.plotWidth,l=a.plotHeight,m,n,o,p,q,r;if(!c.outlineWidth)return;e.save();if(c.circular){e.translate(h+k/2,j+l/2);var s=Math.min(l,k)*b.radar.radiusRatio/2,t=this.axes.x.ticks.length,u=2*(Math.PI/t),v=-Math.PI/2;e.beginPath(),e.lineWidth=c.outlineWidth,e.strokeStyle=c.color,e.lineJoin="round";for(i=0;i<=t;++i)e[i===0?"moveTo":"lineTo"](Math.cos(i*u+v)*s,Math.sin(i*u+v)*s);e.stroke()}else{e.translate(h,j);var w=c.outlineWidth,x=.5-w+(w+1)%2/2,y="lineTo",z="moveTo";e.lineWidth=w,e.strokeStyle=c.color,e.lineJoin="miter",e.beginPath(),e.moveTo(x,x),k-=w/2%1,l+=w/2,e[d.indexOf("n")!==-1?y:z](k,x),e[d.indexOf("e")!==-1?y:z](k,l),e[d.indexOf("s")!==-1?y:z](x,l),e[d.indexOf("w")!==-1?y:z](x,x),e.stroke(),e.closePath()}e.restore(),f&&(o=f.src||f,p=(parseInt(f.left,10)||0)+g.left,q=(parseInt(f.top,10)||0)+g.top,n=new Image,n.onload=function(){e.save(),f.alpha&&(e.globalAlpha=f.alpha),e.globalCompositeOperation="destination-over",e.drawImage(n,0,0,n.width,n.height,p,q,k,l),e.restore()},n.src=o)}})}(),function(){var a=Flotr.DOM,b=Flotr._,c=Flotr,d="opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;";Flotr.addPlugin("hit",{callbacks:{"flotr:mousemove":function(a,b){this.hit.track(b)},"flotr:click":function(a){var c=this.hit.track(a);b.defaults(a,c)},"flotr:mouseout":function(){this.hit.clearHit()},"flotr:destroy":function(){this.mouseTrack=null}},track:function(a){if(this.options.mouse.track||b.any(this.series,function(a){return a.mouse&&a.mouse.track}))return this.hit.hit(a)},executeOnType:function(a,d,e){function h(a,h){b.each(b.keys(c.graphTypes),function(b){a[b]&&a[b].show&&this[b][d]&&(g=this.getOptions(a,b),g.fill=!!a.mouse.fillColor,g.fillStyle=this.processColor(a.mouse.fillColor||"#ffffff",{opacity:a.mouse.fillOpacity}),g.color=a.mouse.lineColor,g.context=this.octx,g.index=h,e&&(g.args=e),this[b][d].call(this[b],g),f=!0)},this)}var f=!1,g;return b.isArray(a)||(a=[a]),b.each(a,h,this),f},drawHit:function(a){var b=this.octx,c=a.series;if(c.mouse.lineColor){b.save(),b.lineWidth=c.points?c.points.lineWidth:1,b.strokeStyle=c.mouse.lineColor,b.fillStyle=this.processColor(c.mouse.fillColor||"#ffffff",{opacity:c.mouse.fillOpacity}),b.translate(this.plotOffset.left,this.plotOffset.top);if(!this.hit.executeOnType(c,"drawHit",a)){var d=a.xaxis,e=a.yaxis;b.beginPath(),b.arc(d.d2p(a.x),e.d2p(a.y),c.points.hitRadius||c.points.radius||c.mouse.radius,0,2*Math.PI,!0),b.fill(),b.stroke(),b.closePath()}b.restore(),this.clip(b)}this.prevHit=a},clearHit:function(){var b=this.prevHit,c=this.octx,d=this.plotOffset;c.save(),c.translate(d.left,d.top);if(b){if(!this.hit.executeOnType(b.series,"clearHit",this.prevHit)){var e=b.series,f=e.points?e.points.lineWidth:1;offset=(e.points.hitRadius||e.points.radius||e.mouse.radius)+f,c.clearRect(b.xaxis.d2p(b.x)-offset,b.yaxis.d2p(b.y)-offset,offset*2,offset*2)}a.hide(this.mouseTrack),this.prevHit=null}c.restore()},hit:function(a){var c=this.options,d=this.prevHit,e,f,g,h,i,j,k,l,m;if(this.series.length===0)return;m={relX:a.relX,relY:a.relY,absX:a.absX,absY:a.absY};if(c.mouse.trackY&&!c.mouse.trackAll&&this.hit.executeOnType(this.series,"hit",[a,m])&&!b.isUndefined(m.seriesIndex))i=this.series[m.seriesIndex],m.series=i,m.mouse=i.mouse,m.xaxis=i.xaxis,m.yaxis=i.yaxis;else{e=this.hit.closest(a);if(e){e=c.mouse.trackY?e.point:e.x,h=e.seriesIndex,i=this.series[h],k=i.xaxis,l=i.yaxis,f=2*i.mouse.sensibility;if(c.mouse.trackAll||e.distanceX<f/k.scale&&(!c.mouse.trackY||e.distanceY<f/l.scale))m.series=i,m.xaxis=i.xaxis,m.yaxis=i.yaxis,m.mouse=i.mouse,m.x=e.x,m.y=e.y,m.dist=e.distance,m.index=e.dataIndex,m.seriesIndex=h}}if(!d||d.index!==m.index||d.seriesIndex!==m.seriesIndex)this.hit.clearHit(),m.series&&m.mouse&&m.mouse.track&&(this.hit.drawMouseTrack(m),this.hit.drawHit(m),Flotr.EventAdapter.fire(this.el,"flotr:hit",[m,this]));return m},closest:function(a){function v(a){a.distance=m,a.distanceX=n,a.distanceY=o,a.seriesIndex=t,a.dataIndex=u,a.x=r,a.y=s,j=!0}var b=this.series,c=this.options,d=a.relX,e=a.relY,f=Number.MAX_VALUE,g=Number.MAX_VALUE,h={},i={},j=!1,k,l,m,n,o,p,q,r,s,t,u;for(t=0;t<b.length;t++){k=b[t],l=k.data,p=k.xaxis.p2d(d),q=k.yaxis.p2d(e);for(u=l.length;u--;){r=l[u][0],s=l[u][1];if(r===null||s===null)continue;if(r<k.xaxis.min||r>k.xaxis.max)continue;n=Math.abs(r-p),o=Math.abs(s-q),m=n*n+o*o,m<f&&(f=m,v(h)),n<g&&(g=n,v(i))}}return j?{point:h,x:i}:!1},drawMouseTrack:function(b){var c="",e=b.series,f=b.mouse.position,g=b.mouse.margin,h=b.x,i=b.y,j=d,k=this.mouseTrack,l=this.plotOffset,m=l.left,n=l.right,o=l.bottom,p=l.top,q=b.mouse.trackDecimals,r=this.options;k||(k=a.node('<div class="flotr-mouse-value"></div>'),this.mouseTrack=k,a.insert(this.el,k));if(!b.mouse.relative)f.charAt(0)=="n"?c+="top:"+(g+p)+"px;bottom:auto;":f.charAt(0)=="s"&&(c+="bottom:"+(g+o)+"px;top:auto;"),f.charAt(1)=="e"?c+="right:"+(g+n)+"px;left:auto;":f.charAt(1)=="w"&&(c+="left:"+(g+m)+"px;right:auto;");else if(e.pie&&e.pie.show){var s={x:this.plotWidth/2,y:this.plotHeight/2},t=Math.min(this.canvasWidth,this.canvasHeight)*e.pie.sizeRatio/2,u=b.sAngle<b.eAngle?(b.sAngle+b.eAngle)/2:(b.sAngle+b.eAngle+2*Math.PI)/2;c+="bottom:"+(g-p-s.y-Math.sin(u)*t/2+this.canvasHeight)+"px;top:auto;",c+="left:"+(g+m+s.x+Math.cos(u)*t/2)+"px;right:auto;"}else/n/.test(f)?c+="bottom:"+(g-p-b.yaxis.d2p(b.y)+this.canvasHeight)+"px;top:auto;":c+="top:"+(g+p+b.yaxis.d2p(b.y))+"px;bottom:auto;",/w/.test(f)?c+="right:"+(g-m-b.xaxis.d2p(b.x)+this.canvasWidth)+"px;left:auto;":c+="left:"+(g+m+b.xaxis.d2p(b.x))+"px;right:auto;";j+=c,k.style.cssText=j;if(!q||q<0)q=0;h&&h.toFixed&&(h=h.toFixed(q)),i&&i.toFixed&&(i=i.toFixed(q)),k.innerHTML=b.mouse.trackFormatter({x:h,y:i,series:b.series,index:b.index,nearest:b,fraction:b.fraction}),a.show(k),b.mouse.relative&&(/[ew]/.test(f)?/[ns]/.test(f)||(k.style.top=p+b.yaxis.d2p(b.y)-a.size(k).height/2+"px"):k.style.left=m+b.xaxis.d2p(b.x)-a.size(k).width/2+"px")}})}(),function(){function a(a,b){return a.which?a.which===1:a.button===0||a.button===1}function b(a,b){return Math.min(Math.max(0,a),b.plotWidth-1)}function c(a,b){return Math.min(Math.max(0,a),b.plotHeight)}var d=Flotr.DOM,e=Flotr.EventAdapter,f=Flotr._;Flotr.addPlugin("selection",{options:{pinchOnly:null,mode:null,color:"#B6D9FF",fps:20},callbacks:{"flotr:mouseup":function(a){var b=this.options.selection,c=this.selection,d=this.getEventPosition(a);if(!b||!b.mode)return;c.interval&&clearInterval(c.interval),this.multitouches?c.updateSelection():b.pinchOnly||c.setSelectionPos(c.selection.second,d),c.clearSelection(),c.selecting&&c.selectionIsSane()&&(c.drawSelection(),c.fireSelectEvent(),this.ignoreClick=!0)},"flotr:mousedown":function(b){var c=this.options.selection,d=this.selection,e=this.getEventPosition(b);if(!c||!c.mode)return;if(!c.mode||!a(b)&&f.isUndefined(b.touches))return;c.pinchOnly||d.setSelectionPos(d.selection.first,e),d.interval&&clearInterval(d.interval),this.lastMousePos.pageX=null,d.selecting=!1,d.interval=setInterval(f.bind(d.updateSelection,this),1e3/c.fps)},"flotr:destroy":function(a){clearInterval(this.selection.interval)}},getArea:function(){var a=this.selection.selection,b=this.axes,c=a.first,d=a.second,e,f,g,h;return e=b.x.p2d(a.first.x),f=b.x.p2d(a.second.x),g=b.y.p2d(a.first.y),h=b.y.p2d(a.second.y),{x1:Math.min(e,f),y1:Math.min(g,h),x2:Math.max(e,f),y2:Math.max(g,h),xfirst:e,xsecond:f,yfirst:g,ysecond:h}},selection:{first:{x:-1,y:-1},second:{x:-1,y:-1}},prevSelection:null,interval:null,fireSelectEvent:function(a){var b=this.selection.getArea();a=a||"select",b.selection=this.selection.selection,e.fire(this.el,"flotr:"+a,[b,this])},setSelection:function(a,d){var e=this.options,f=this.axes.x,g=this.axes.y,h=g.scale,i=f.scale,j=e.selection.mode.indexOf("x")!=-1,k=e.selection.mode.indexOf("y")!=-1,l=this.selection.selection;this.selection.clearSelection(),l.first.y=c(j&&!k?0:(g.max-a.y1)*h,this),l.second.y=c(j&&!k?this.plotHeight-1:(g.max-a.y2)*h,this),l.first.x=b(k&&!j?0:(a.x1-f.min)*i,this),l.second.x=b(k&&!j?this.plotWidth:(a.x2-f.min)*i,this),this.selection.drawSelection(),d||this.selection.fireSelectEvent()},setSelectionPos:function(a,d){var e=this.options.selection.mode,f=this.selection.selection;e.indexOf("x")==-1?a.x=a==f.first?0:this.plotWidth:a.x=b(d.relX,this),e.indexOf("y")==-1?a.y=a==f.first?0:this.plotHeight-1:a.y=c(d.relY,this)},drawSelection:function(){this.selection.fireSelectEvent("selecting");var a=this.selection.selection,b=this.octx,c=this.options,d=this.plotOffset,e=this.selection.prevSelection;if(e&&a.first.x==e.first.x&&a.first.y==e.first.y&&a.second.x==e.second.x&&a.second.y==e.second.y)return;b.save(),b.strokeStyle=this.processColor(c.selection.color,{opacity:.8}),b.lineWidth=1,b.lineJoin="miter",b.fillStyle=this.processColor(c.selection.color,{opacity:.4}),this.selection.prevSelection={first:{x:a.first.x,y:a.first.y},second:{x:a.second.x,y:a.second.y}};var f=Math.min(a.first.x,a.second.x),g=Math.min(a.first.y,a.second.y),h=Math.abs(a.second.x-a.first.x),i=Math.abs(a.second.y-a.first.y);b.fillRect(f+d.left+.5,g+d.top+.5,h,i),b.strokeRect(f+d.left+.5,g+d.top+.5,h,i),b.restore()},updateSelection:function(){if(!this.lastMousePos.pageX)return;this.selection.selecting=!0;if(this.multitouches)this.selection.setSelectionPos(this.selection.selection.first,this.getEventPosition(this.multitouches[0])),this.selection.setSelectionPos(this.selection.selection.second,this.getEventPosition(this.multitouches[1]));else{if(this.options.selection.pinchOnly)return;this.selection.setSelectionPos(this.selection.selection.second,this.lastMousePos)}this.selection.clearSelection(),this.selection.selectionIsSane()&&this.selection.drawSelection()},clearSelection:function(){if(!this.selection.prevSelection)return;var a=this.selection.prevSelection,b=1,c=this.plotOffset,d=Math.min(a.first.x,a.second.x),e=Math.min(a.first.y,a.second.y),f=Math.abs(a.second.x-a.first.x),g=Math.abs(a.second.y-a.first.y);this.octx.clearRect(d+c.left-b+.5,e+c.top-b,f+2*b+.5,g+2*b+.5),this.selection.prevSelection=null},selectionIsSane:function(){var a=this.selection.selection;return Math.abs(a.second.x-a.first.x)>=5||Math.abs(a.second.y-a.first.y)>=5}})}(),function(){var a=Flotr.DOM;Flotr.addPlugin("labels",{callbacks:{"flotr:afterdraw":function(){this.labels.draw()}},draw:function(){function s(a,b,d){var e=d?b.minorTicks:b.ticks,f=b.orientation===1,h=b.n===1,k,m;k={color:b.options.color||o.grid.color,angle:Flotr.toRad(b.options.labelsAngle),textBaseline:"middle"};for(l=0;l<e.length&&(d?b.options.showMinorLabels:b.options.showLabels);++l){c=e[l],c.label+="";if(!c.label||!c.label.length)continue;x=Math.cos(l*i+j)*g,y=Math.sin(l*i+j)*g,k.textAlign=f?Math.abs(x)<.1?"center":x<0?"right":"left":"left",Flotr.drawText(p,c.label,f?x:3,f?y:-(b.ticks[l].v/b.max)*(g-o.fontSize),k)}}function t(a,b,d,e){function j(a){return a.options.showLabels&&a.used}function k(a,b,c,d){return a.plotOffset.left+(b?d:c?-o.grid.labelMargin:o.grid.labelMargin+a.plotWidth)}function m(a,b,c,d){return a.plotOffset.top+(b?o.grid.labelMargin:d)+(b&&c?a.plotHeight:0)}var f=b.orientation===1,g=b.n===1,h,i;h={color:b.options.color||o.grid.color,textAlign:d,textBaseline:e,angle:Flotr.toRad(b.options.labelsAngle)},h=Flotr.getBestTextAlign(h.angle,h);for(l=0;l<b.ticks.length&&j(b);++l){c=b.ticks[l];if(!c.label||!c.label.length)continue;i=b.d2p(c.v);if(i<0||i>(f?a.plotWidth:a.plotHeight))continue;Flotr.drawText(p,c.label,k(a,f,g,i),m(a,f,g,i),h),!f&&!g&&(p.save(),p.strokeStyle=h.color,p.beginPath(),p.moveTo(a.plotOffset.left+a.plotWidth-8,a.plotOffset.top+b.d2p(c.v)),p.lineTo(a.plotOffset.left+a.plotWidth,a.plotOffset.top+b.d2p(c.v)),p.stroke(),p.restore())}}function u(a,b){var d=b.orientation===1,e=b.n===1,g="",h,i,j,k=a.plotOffset;!d&&!e&&(p.save(),p.strokeStyle=b.options.color||o.grid.color,p.beginPath());if(b.options.showLabels&&(e?!0:b.used))for(l=0;l<b.ticks.length;++l){c=b.ticks[l];if(!c.label||!c.label.length||(d?k.left:k.top)+b.d2p(c.v)<0||(d?k.left:k.top)+b.d2p(c.v)>(d?a.canvasWidth:a.canvasHeight))continue;j=k.top+(d?(e?1:-1)*(a.plotHeight+o.grid.labelMargin):b.d2p(c.v)-b.maxLabel.height/2),h=d?k.left+b.d2p(c.v)-f/2:0,g="",l===0?g=" first":l===b.ticks.length-1&&(g=" last"),g+=d?" flotr-grid-label-x":" flotr-grid-label-y",m+=['<div style="position:absolute; text-align:'+(d?"center":"right")+"; ","top:"+j+"px; ",(!d&&!e?"right:":"left:")+h+"px; ","width:"+(d?f:(e?k.left:k.right)-o.grid.labelMargin)+"px; ",b.options.color?"color:"+b.options.color+"; ":" ",'" class="flotr-grid-label'+g+'">'+c.label+"</div>"].join(" "),!d&&!e&&(p.moveTo(k.left+a.plotWidth-8,k.top+b.d2p(c.v)),p.lineTo(k.left+a.plotWidth,k.top+b.d2p(c.v)))}}var b,c,d,e,f,g,h,i,j,k,l,m="",n=0,o=this.options,p=this.ctx,q=this.axes,r={size:o.fontSize};for(l=0;l<q.x.ticks.length;++l)q.x.ticks[l].label&&++n;f=this.plotWidth/n,o.grid.circular&&(p.save(),p.translate(this.plotOffset.left+this.plotWidth/2,this.plotOffset.top+this.plotHeight/2),g=this.plotHeight*o.radar.radiusRatio/2+o.fontSize,h=this.axes.x.ticks.length,i=2*(Math.PI/h),j=-Math.PI/2,s(this,q.x,!1),s(this,q.x,!0),s(this,q.y,!1),s(this,q.y,!0),p.restore()),!o.HtmlText&&this.textEnabled?(t(this,q.x,"center","top"),t(this,q.x2,"center","bottom"),t(this,q.y,"right","middle"),t(this,q.y2,"left","middle")):(q.x.options.showLabels||q.x2.options.showLabels||q.y.options.showLabels||q.y2.options.showLabels)&&!o.grid.circular&&(m="",u(this,q.x),u(this,q.x2),u(this,q.y),u(this,q.y2),p.stroke(),p.restore(),k=a.create("div"),a.setStyles(k,{fontSize:"smaller",color:o.grid.color}),k.className="flotr-labels",a.insert(this.el,k),a.insert(k,m))}})}(),function(){var a=Flotr.DOM,b=Flotr._;Flotr.addPlugin("legend",{options:{show:!0,noColumns:1,labelFormatter:function(a){return a},labelBoxBorderColor:"#CCCCCC",labelBoxWidth:14,labelBoxHeight:10,labelBoxMargin:5,container:null,position:"nw",margin:5,backgroundColor:"#F0F0F0",backgroundOpacity:.85},callbacks:{"flotr:afterinit":function(){this.legend.insertLegend()},"flotr:destroy":function(){var b=this.legend.markup;b&&(this.legend.markup=null,a.remove(b))}},insertLegend:function(){if(!this.options.legend.show)return;var c=this.series,d=this.plotOffset,e=this.options,f=e.legend,g=[],h=!1,i=this.ctx,j=b.filter(c,function(a){return a.label&&!a.hide}).length,k=f.position,l=f.margin,m=f.backgroundOpacity,n,o,p;if(j){var q=f.labelBoxWidth,r=f.labelBoxHeight,s=f.labelBoxMargin,t=d.left+l,u=d.top+l,v=0,w={size:e.fontSize*1.1,color:e.grid.color};for(n=c.length-1;n>-1;--n){if(!c[n].label||c[n].hide)continue;o=f.labelFormatter(c[n].label),v=Math.max(v,this._text.measureText(o,w).width)}var x=Math.round(q+s*3+v),y=Math.round(j*(s+r)+s);!m&&m!==0&&(m=.1);if(!e.HtmlText&&this.textEnabled&&!f.container){k.charAt(0)=="s"&&(u=d.top+this.plotHeight-(l+y)),k.charAt(0)=="c"&&(u=d.top+this.plotHeight/2-(l+y/2)),k.charAt(1)=="e"&&(t=d.left+this.plotWidth-(l+x)),p=this.processColor(f.backgroundColor,{opacity:m}),i.fillStyle=p,i.fillRect(t,u,x,y),i.strokeStyle=f.labelBoxBorderColor,i.strokeRect(Flotr.toPixel(t),Flotr.toPixel(u),x,y);var z=t+s,A=u+s;for(n=0;n<c.length;n++){if(!c[n].label||c[n].hide)continue;o=f.labelFormatter(c[n].label),i.fillStyle=c[n].color,i.fillRect(z,A,q-1,r-1),i.strokeStyle=f.labelBoxBorderColor,i.lineWidth=1,i.strokeRect(Math.ceil(z)-1.5,Math.ceil(A)-1.5,q+2,r+2),Flotr.drawText(i,o,z+q+s,A+r,w),A+=r+s}}else{for(n=0;n<c.length;++n){if(!c[n].label||c[n].hide)continue;n%f.noColumns===0&&(g.push(h?"</tr><tr>":"<tr>"),h=!0);var B=c[n],C=f.labelBoxWidth,E=f.labelBoxHeight;o=f.labelFormatter(B.label),p="background-color:"+(B.bars&&B.bars.show&&B.bars.fillColor&&B.bars.fill?B.bars.fillColor:B.color)+";",g.push('<td class="flotr-legend-color-box">','<div style="border:1px solid ',f.labelBoxBorderColor,';padding:1px">','<div style="width:',C-1,"px;height:",E-1,"px;border:1px solid ",c[n].color,'">','<div style="width:',C,"px;height:",E,"px;",p,'"></div>',"</div>","</div>","</td>",'<td class="flotr-legend-label">',o,"</td>")}h&&g.push("</tr>");if(g.length>0){var F='<table style="font-size:smaller;color:'+e.grid.color+'">'+g.join("")+"</table>";if(f.container)F=a.node(F),this.legend.markup=F,a.insert(f.container,F);else{var G={position:"absolute",zIndex:"2",border:"1px solid "+f.labelBoxBorderColor};k.charAt(0)=="n"?(G.top=l+d.top+"px",G.bottom="auto"):k.charAt(0)=="c"?(G.top=l+(this.plotHeight-y)/2+"px",G.bottom="auto"):k.charAt(0)=="s"&&(G.bottom=l+d.bottom+"px",G.top="auto"),k.charAt(1)=="e"?(G.right=l+d.right+"px",G.left="auto"):k.charAt(1)=="w"&&(G.left=l+d.left+"px",G.right="auto");var H=a.create("div"),I;H.className="flotr-legend",a.setStyles(H,G),a.insert(H,F),a.insert(this.el,H);if(!m)return;var J=f.backgroundColor||e.grid.backgroundColor||"#ffffff";b.extend(G,a.size(H),{backgroundColor:J,zIndex:"",border:""}),G.width+="px",G.height+="px",H=a.create("div"),H.className="flotr-legend-bg",a.setStyles(H,G),a.opacity(H,m),a.insert(H," "),a.insert(this.el,H)}}}}}})}(),function(){function a(a){if(this.options.spreadsheet.tickFormatter)return this.options.spreadsheet.tickFormatter(a);var b=c.find(this.axes.x.ticks,function(b){return b.v==a});return b?b.label:a}var b=Flotr.DOM,c=Flotr._;Flotr.addPlugin("spreadsheet",{options:{show:!1,tabGraphLabel:"Graph",tabDataLabel:"Data",toolbarDownload:"Download CSV",toolbarSelectAll:"Select all",csvFileSeparator:",",decimalSeparator:".",tickFormatter:null,initialTab:"graph"},callbacks:{"flotr:afterconstruct":function(){if(!this.options.spreadsheet.show)return;var a=this.spreadsheet,c=b.node('<div class="flotr-tabs-group" style="position:absolute;left:0px;width:'+this.canvasWidth+'px"></div>'),d=b.node('<div style="float:left" class="flotr-tab selected">'+this.options.spreadsheet.tabGraphLabel+"</div>"),e=b.node('<div style="float:left" class="flotr-tab">'+this.options.spreadsheet.tabDataLabel+"</div>"),f;a.tabsContainer=c,a.tabs={graph:d,data:e},b.insert(c,d),b.insert(c,e),b.insert(this.el,c),f=b.size(e).height+2,this.plotOffset.bottom+=f,b.setStyles(c,{top:this.canvasHeight-f+"px"}),this.observe(d,"click",function(){a.showTab("graph")}).observe(e,"click",function(){a.showTab("data")}),this.options.spreadsheet.initialTab!=="graph"&&a.showTab(this.options.spreadsheet.initialTab)}},loadDataGrid:function(){if(this.seriesData)return this.seriesData;var a=this.series,b={};return c.each(a,function(a,d){c.each(a.data,function(a){var c=a[0],e=a[1],f=b[c];if(f)f[d+1]=e;else{var g=[];g[0]=c,g[d+1]=e,b[c]=g}})}),this.seriesData=c.sortBy(b,function(a,b){return parseInt(b,10)}),this.seriesData},constructDataGrid:function(){if(this.spreadsheet.datagrid)return this.spreadsheet.datagrid;var d=this.series,e=this.spreadsheet.loadDataGrid(),f=["<colgroup><col />"],g,h,i,j=['<table class="flotr-datagrid"><tr class="first-row">'];j.push("<th>&nbsp;</th>"),c.each(d,function(a,b){j.push('<th scope="col">'+(a.label||String.fromCharCode(65+b))+"</th>"),f.push("<col />")}),j.push("</tr>"),c.each(e,function(b){j.push("<tr>"),c.times(d.length+1,function(d){var e="td",f=b[d],g=c.isUndefined(f)?"":Math.round(f*1e5)/1e5;if(d===0){e="th";var h=a.call(this,g);h&&(g=h)}j.push("<"+e+(e=="th"?' scope="row"':"")+">"+g+"</"+e+">")},this),j.push("</tr>")},this),f.push("</colgroup>"),i=b.node(j.join("")),g=b.node('<button type="button" class="flotr-datagrid-toolbar-button">'+this.options.spreadsheet.toolbarDownload+"</button>"),h=b.node('<button type="button" class="flotr-datagrid-toolbar-button">'+this.options.spreadsheet.toolbarSelectAll+"</button>"),this.observe(g,"click",c.bind(this.spreadsheet.downloadCSV,this)).observe(h,"click",c.bind(this.spreadsheet.selectAllData,this));var k=b.node('<div class="flotr-datagrid-toolbar"></div>');b.insert(k,g),b.insert(k,h);var l=this.canvasHeight-b.size(this.spreadsheet.tabsContainer).height-2,m=b.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+this.canvasWidth+"px;height:"+l+'px;overflow:auto;z-index:10"></div>');return b.insert(m,k),b.insert(m,i),b.insert(this.el,m),this.spreadsheet.datagrid=i,this.spreadsheet.container=m,i},showTab:function(a){if(this.spreadsheet.activeTab===a)return;switch(a){case"graph":b.hide(this.spreadsheet.container),b.removeClass(this.spreadsheet.tabs.data,"selected"),b.addClass(this.spreadsheet.tabs.graph,"selected");break;case"data":this.spreadsheet.datagrid||this.spreadsheet.constructDataGrid(),b.show(this.spreadsheet.container),b.addClass(this.spreadsheet.tabs.data,"selected"),b.removeClass(this.spreadsheet.tabs.graph,"selected");break;default:throw"Illegal tab name: "+a}this.spreadsheet.activeTab=a},selectAllData:function(){if(this.spreadsheet.tabs){var a,b,c,d,e=this.spreadsheet.constructDataGrid();return this.spreadsheet.showTab("data"),setTimeout(function(){(c=e.ownerDocument)&&(d=c.defaultView)&&d.getSelection&&c.createRange&&(a=window.getSelection())&&a.removeAllRanges?(b=c.createRange(),b.selectNode(e),a.removeAllRanges(),a.addRange(b)):document.body&&document.body.createTextRange&&(b=document.body.createTextRange())&&(b.moveToElementText(e),b.select())},0),!0}return!1},downloadCSV:function(){var b="",d=this.series,e=this.options,f=this.spreadsheet.loadDataGrid(),g=encodeURIComponent(e.spreadsheet.csvFileSeparator);if(e.spreadsheet.decimalSeparator===e.spreadsheet.csvFileSeparator)throw"The decimal separator is the same as the column separator ("+e.spreadsheet.decimalSeparator+")";c.each(d,function(a,c){b+=g+'"'+(a.label||String.fromCharCode(65+c)).replace(/\"/g,'\\"')+'"'}),b+="%0D%0A",b+=c.reduce(f,function(b,c){var d=a.call(this,c[0])||"";d='"'+(d+"").replace(/\"/g,'\\"')+'"';var f=c.slice(1).join(g);return e.spreadsheet.decimalSeparator!=="."&&(f=f.replace(/\./g,e.spreadsheet.decimalSeparator)),b+d+g+f+"%0D%0A"},"",this),Flotr.isIE&&Flotr.isIE<9?(b=b.replace(new RegExp(g,"g"),decodeURIComponent(g)).replace(/%0A/g,"\n").replace(/%0D/g,"\r"),window.open().document.write(b)):window.open("data:text/csv,"+b)}})}(),function(){var a=Flotr.DOM;Flotr.addPlugin("titles",{callbacks:{"flotr:afterdraw":function(){this.titles.drawTitles()}},drawTitles:function(){var b,c=this.options,d=c.grid.labelMargin,e=this.ctx,f=this.axes;if(!c.HtmlText&&this.textEnabled){var g={size:c.fontSize,color:c.grid.color,textAlign:"center"};c.subtitle&&Flotr.drawText(e,c.subtitle,this.plotOffset.left+this.plotWidth/2,this.titleHeight+this.subtitleHeight-2,g),g.weight=1.5,g.size*=1.5,c.title&&Flotr.drawText(e,c.title,this.plotOffset.left+this.plotWidth/2,this.titleHeight-2,g),g.weight=1.8,g.size*=.8,f.x.options.title&&f.x.used&&(g.textAlign=f.x.options.titleAlign||"center",g.textBaseline="top",g.angle=Flotr.toRad(f.x.options.titleAngle),g=Flotr.getBestTextAlign(g.angle,g),Flotr.drawText(e,f.x.options.title,this.plotOffset.left+this.plotWidth/2,this.plotOffset.top+f.x.maxLabel.height+this.plotHeight+2*d,g)),f.x2.options.title&&f.x2.used&&(g.textAlign=f.x2.options.titleAlign||"center",g.textBaseline="bottom",g.angle=Flotr.toRad(f.x2.options.titleAngle),g=Flotr.getBestTextAlign(g.angle,g),Flotr.drawText(e,f.x2.options.title,this.plotOffset.left+this.plotWidth/2,this.plotOffset.top-f.x2.maxLabel.height-2*d,g)),f.y.options.title&&f.y.used&&(g.textAlign=f.y.options.titleAlign||"right",g.textBaseline="middle",g.angle=Flotr.toRad(f.y.options.titleAngle),g=Flotr.getBestTextAlign(g.angle,g),Flotr.drawText(e,f.y.options.title,this.plotOffset.left-f.y.maxLabel.width-2*d,this.plotOffset.top+this.plotHeight/2,g)),f.y2.options.title&&f.y2.used&&(g.textAlign=f.y2.options.titleAlign||"left",g.textBaseline="middle",g.angle=Flotr.toRad(f.y2.options.titleAngle),g=Flotr.getBestTextAlign(g.angle,g),Flotr.drawText(e,f.y2.options.title,this.plotOffset.left+this.plotWidth+f.y2.maxLabel.width+2*d,this.plotOffset.top+this.plotHeight/2,g))}else{b=[],c.title&&b.push('<div style="position:absolute;top:0;left:',this.plotOffset.left,"px;font-size:1em;font-weight:bold;text-align:center;width:",this.plotWidth,'px;" class="flotr-title">',c.title,"</div>"),c.subtitle&&b.push('<div style="position:absolute;top:',this.titleHeight,"px;left:",this.plotOffset.left,"px;font-size:smaller;text-align:center;width:",this.plotWidth,'px;" class="flotr-subtitle">',c.subtitle,"</div>"),b.push("</div>"),b.push('<div class="flotr-axis-title" style="font-weight:bold;">'),f.x.options.title&&f.x.used&&b.push('<div style="position:absolute;top:',this.plotOffset.top+this.plotHeight+c.grid.labelMargin+f.x.titleSize.height,"px;left:",this.plotOffset.left,"px;width:",this.plotWidth,"px;text-align:",f.x.options.titleAlign,';" class="flotr-axis-title flotr-axis-title-x1">',f.x.options.title,"</div>"),f.x2.options.title&&f.x2.used&&b.push('<div style="position:absolute;top:0;left:',this.plotOffset.left,"px;width:",this.plotWidth,"px;text-align:",f.x2.options.titleAlign,';" class="flotr-axis-title flotr-axis-title-x2">',f.x2.options.title,"</div>"),f.y.options.title&&f.y.used&&b.push('<div style="position:absolute;top:',this.plotOffset.top+this.plotHeight/2-f.y.titleSize.height/2,"px;left:0;text-align:",f.y.options.titleAlign,';" class="flotr-axis-title flotr-axis-title-y1">',f.y.options.title,"</div>"),f.y2.options.title&&f.y2.used&&b.push('<div style="position:absolute;top:',this.plotOffset.top+this.plotHeight/2-f.y.titleSize.height/2,"px;right:0;text-align:",f.y2.options.titleAlign,';" class="flotr-axis-title flotr-axis-title-y2">',f.y2.options.title,"</div>"),b=b.join("");var h=a.create("div");a.setStyles({color:c.grid.color}),h.className="flotr-titles",a.insert(this.el,h),a.insert(h,b)}}})}();
 
  /**
  * Flotr Axis Library
  */
 
  (function () {
 
  var
  _ = Flotr._,
  LOGARITHMIC = 'logarithmic';
 
  function Axis (o) {
 
  this.orientation = 1;
  this.offset = 0;
  this.datamin = Number.MAX_VALUE;
  this.datamax = -Number.MAX_VALUE;
 
  _.extend(this, o);
  }
 
 
  // Prototype
  Axis.prototype = {
 
  setScale : function () {
  var
  length = this.length,
  max = this.max,
  min = this.min,
  offset = this.offset,
  orientation = this.orientation,
  options = this.options,
  logarithmic = options.scaling === LOGARITHMIC,
  scale;
 
  if (logarithmic) {
  scale = length / (log(max, options.base) - log(min, options.base));
  } else {
  scale = length / (max - min);
  }
  this.scale = scale;
 
  // Logarithmic?
  if (logarithmic) {
  this.d2p = function (dataValue) {
  return offset + orientation * (log(dataValue, options.base) - log(min, options.base)) * scale;
  };
  this.p2d = function (pointValue) {
  return exp((offset + orientation * pointValue) / scale + log(min, options.base), options.base);
  };
  } else {
  this.d2p = function (dataValue) {
  return offset + orientation * (dataValue - min) * scale;
  };
  this.p2d = function (pointValue) {
  return (offset + orientation * pointValue) / scale + min;
  };
  }
  },
 
  calculateTicks : function () {
  var options = this.options;
 
  this.ticks = [];
  this.minorTicks = [];
 
  // User Ticks
  if(options.ticks){
  this._cleanUserTicks(options.ticks, this.ticks);
  this._cleanUserTicks(options.minorTicks || [], this.minorTicks);
  }
  else {
  if (options.mode == 'time') {
  this._calculateTimeTicks();
  } else if (options.scaling === 'logarithmic') {
  this._calculateLogTicks();
  } else {
  this._calculateTicks();
  }
  }
 
  // Ticks to strings
  _.each(this.ticks, function (tick) { tick.label += ''; });
  _.each(this.minorTicks, function (tick) { tick.label += ''; });
  },
 
  /**
  * Calculates the range of an axis to apply autoscaling.
  */
  calculateRange: function () {
 
  if (!this.used) return;
 
  var axis = this,
  o = axis.options,
  min = o.min !== null ? o.min : axis.datamin,
  max = o.max !== null ? o.max : axis.datamax,
  margin = o.autoscaleMargin;
 
  if (o.scaling == 'logarithmic') {
  if (min <= 0) min = axis.datamin;
 
  // Let it widen later on
  if (max <= 0) max = min;
  }
 
  if (max == min) {
  var widen = max ? 0.01 : 1.00;
  if (o.min === null) min -= widen;
  if (o.max === null) max += widen;
  }
 
  if (o.scaling === 'logarithmic') {
  if (min < 0) min = max / o.base; // Could be the result of widening
 
  var maxexp = Math.log(max);
  if (o.base != Math.E) maxexp /= Math.log(o.base);
  maxexp = Math.ceil(maxexp);
 
  var minexp = Math.log(min);
  if (o.base != Math.E) minexp /= Math.log(o.base);
  minexp = Math.ceil(minexp);
 
  axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
 
  // Try to determine a suitable amount of miniticks based on the length of a decade
  if (o.minorTickFreq === null) {
  if (maxexp - minexp > 10)
  o.minorTickFreq = 0;
  else if (maxexp - minexp > 5)
  o.minorTickFreq = 2;
  else
  o.minorTickFreq = 5;
  }
  } else {
  axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
  }
 
  axis.min = min;
  axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
 
  // Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
  if(o.min === null && o.autoscale){
  axis.min -= axis.tickSize * margin;
  // Make sure we don't go below zero if all values are positive.
  if(axis.min < 0 && axis.datamin >= 0) axis.min = 0;
  axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
  }
 
  if(o.max === null && o.autoscale){
  axis.max += axis.tickSize * margin;
  if(axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
  axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
  }
 
  if (axis.min == axis.max) axis.max = axis.min + 1;
  },
 
  calculateTextDimensions : function (T, options) {
 
  var maxLabel = '',
  length,
  i;
 
  if (this.options.showLabels) {
  for (i = 0; i < this.ticks.length; ++i) {
  length = this.ticks[i].label.length;
  if (length > maxLabel.length){
  maxLabel = this.ticks[i].label;
  }
  }
  }
 
  this.maxLabel = T.dimensions(
  maxLabel,
  {size:options.fontSize, angle: Flotr.toRad(this.options.labelsAngle)},
  'font-size:smaller;',
  'flotr-grid-label'
  );
 
  this.titleSize = T.dimensions(
  this.options.title,
  {size:options.fontSize*1.2, angle: Flotr.toRad(this.options.titleAngle)},
  'font-weight:bold;',
  'flotr-axis-title'
  );
  },
 
  _cleanUserTicks : function (ticks, axisTicks) {
 
  var axis = this, options = this.options,
  v, i, label, tick;
 
  if(_.isFunction(ticks)) ticks = ticks({min : axis.min, max : axis.max});
 
  for(i = 0; i < ticks.length; ++i){
  tick = ticks[i];
  if(typeof(tick) === 'object'){
  v = tick[0];
  label = (tick.length > 1) ? tick[1] : options.tickFormatter(v, {min : axis.min, max : axis.max});
  } else {
  v = tick;
  label = options.tickFormatter(v, {min : this.min, max : this.max});
  }
  axisTicks[i] = { v: v, label: label };
  }
  },
 
  _calculateTimeTicks : function () {
  this.ticks = Flotr.Date.generator(this);
  },
 
  _calculateLogTicks : function () {
 
  var axis = this,
  o = axis.options,
  v,
  decadeStart;
 
  var max = Math.log(axis.max);
  if (o.base != Math.E) max /= Math.log(o.base);
  max = Math.ceil(max);
 
  var min = Math.log(axis.min);
  if (o.base != Math.E) min /= Math.log(o.base);
  min = Math.ceil(min);
 
  for (i = min; i < max; i += axis.tickSize) {
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  // Next decade begins here:
  var decadeEnd = decadeStart * ((o.base == Math.E) ? Math.exp(axis.tickSize) : Math.pow(o.base, axis.tickSize));
  var stepSize = (decadeEnd - decadeStart) / o.minorTickFreq;
 
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  for (v = decadeStart + stepSize; v < decadeEnd; v += stepSize)
  axis.minorTicks.push({v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max})});
  }
 
  // Always show the value at the would-be start of next decade (end of this decade)
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min : axis.min, max : axis.max})});
  },
 
  _calculateTicks : function () {
 
  var axis = this,
  o = axis.options,
  tickSize = axis.tickSize,
  min = axis.min,
  max = axis.max,
  start = tickSize * Math.ceil(min / tickSize), // Round to nearest multiple of tick size.
  decimals,
  minorTickSize,
  v, v2,
  i, j;
 
  if (o.minorTickFreq)
  minorTickSize = tickSize / o.minorTickFreq;
 
  // Then store all possible ticks.
  for (i = 0; (v = v2 = start + i * tickSize) <= max; ++i){
 
  // Round (this is always needed to fix numerical instability).
  decimals = o.tickDecimals;
  if (decimals === null) decimals = 1 - Math.floor(Math.log(tickSize) / Math.LN10);
  if (decimals < 0) decimals = 0;
 
  v = v.toFixed(decimals);
  axis.ticks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
 
  if (o.minorTickFreq) {
  for (j = 0; j < o.minorTickFreq && (i * tickSize + j * minorTickSize) < max; ++j) {
  v = v2 + j * minorTickSize;
  axis.minorTicks.push({ v: v, label: o.tickFormatter(v, {min : axis.min, max : axis.max}) });
  }
  }
  }
 
  }
  };
 
 
  // Static Methods
  _.extend(Axis, {
  getAxes : function (options) {
  return {
  x: new Axis({options: options.xaxis, n: 1, length: this.plotWidth}),
  x2: new Axis({options: options.x2axis, n: 2, length: this.plotWidth}),
  y: new Axis({options: options.yaxis, n: 1, length: this.plotHeight, offset: this.plotHeight, orientation: -1}),
  y2: new Axis({options: options.y2axis, n: 2, length: this.plotHeight, offset: this.plotHeight, orientation: -1})
  };
  }
  });
 
 
  // Helper Methods
 
 
  function log (value, base) {
  value = Math.log(Math.max(value, Number.MIN_VALUE));
  if (base !== Math.E)
  value /= Math.log(base);
  return value;
  }
 
  function exp (value, base) {
  return (base === Math.E) ? Math.exp(value) : Math.pow(base, value);
  }
 
  Flotr.Axis = Axis;
 
  })();
 
  /**
  * Flotr Color
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  // Constructor
  function Color (r, g, b, a) {
  this.rgba = ['r','g','b','a'];
  var x = 4;
  while(-1<--x){
  this[this.rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0);
  }
  this.normalize();
  }
 
  // Constants
  var COLOR_NAMES = {
  aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],
  brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],
  darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],
  darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],
  darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],
  khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],
  lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],
  maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],
  violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]
  };
 
  Color.prototype = {
  scale: function(rf, gf, bf, af){
  var x = 4;
  while (-1 < --x) {
  if (!_.isUndefined(arguments[x])) this[this.rgba[x]] *= arguments[x];
  }
  return this.normalize();
  },
  alpha: function(alpha) {
  if (!_.isUndefined(alpha) && !_.isNull(alpha)) {
  this.a = alpha;
  }
  return this.normalize();
  },
  clone: function(){
  return new Color(this.r, this.b, this.g, this.a);
  },
  limit: function(val,minVal,maxVal){
  return Math.max(Math.min(val, maxVal), minVal);
  },
  normalize: function(){
  var limit = this.limit;
  this.r = limit(parseInt(this.r, 10), 0, 255);
  this.g = limit(parseInt(this.g, 10), 0, 255);
  this.b = limit(parseInt(this.b, 10), 0, 255);
  this.a = limit(this.a, 0, 1);
  return this;
  },
  distance: function(color){
  if (!color) return;
  color = new Color.parse(color);
  var dist = 0, x = 3;
  while(-1<--x){
  dist += Math.abs(this[this.rgba[x]] - color[this.rgba[x]]);
  }
  return dist;
  },
  toString: function(){
  return (this.a >= 1.0) ? 'rgb('+[this.r,this.g,this.b].join(',')+')' : 'rgba('+[this.r,this.g,this.b,this.a].join(',')+')';
  },
  contrast: function () {
  var
  test = 1 - ( 0.299 * this.r + 0.587 * this.g + 0.114 * this.b) / 255;
  return (test < 0.5 ? '#000000' : '#ffffff');
  }
  };
 
  _.extend(Color, {
  /**
  * Parses a color string and returns a corresponding Color.
  * The different tests are in order of probability to improve speed.
  * @param {String, Color} str - string thats representing a color
  * @return {Color} returns a Color object or false
  */
  parse: function(color){
  if (color instanceof Color) return color;
 
  var result;
 
  // #a0b1c2
  if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)))
  return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
 
  // rgb(num,num,num)
  if((result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
 
  // #fff
  if((result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)))
  return new Color(parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16));
 
  // rgba(num,num,num,num)
  if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
 
  // rgb(num%,num%,num%)
  if((result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55);
 
  // rgba(num%,num%,num%,num)
  if((result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]));
 
  // Otherwise, we're most likely dealing with a named color.
  var name = (color+'').replace(/^\s*([\S\s]*?)\s*$/, '$1').toLowerCase();
  if(name == 'transparent'){
  return new Color(255, 255, 255, 0);
  }
  return (result = COLOR_NAMES[name]) ? new Color(result[0], result[1], result[2]) : new Color(0, 0, 0, 0);
  },
 
  /**
  * Process color and options into color style.
  */
  processColor: function(color, options) {
 
  var opacity = options.opacity;
  if (!color) return 'rgba(0, 0, 0, 0)';
  if (color instanceof Color) return color.alpha(opacity).toString();
  if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
 
  var grad = color.colors ? color : {colors: color};
 
  if (!options.ctx) {
  if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
  return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
  }
  grad = _.extend({start: 'top', end: 'bottom'}, grad);
 
  if (/top/i.test(grad.start)) options.x1 = 0;
  if (/left/i.test(grad.start)) options.y1 = 0;
  if (/bottom/i.test(grad.end)) options.x2 = 0;
  if (/right/i.test(grad.end)) options.y2 = 0;
 
  var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
  for (i = 0; i < grad.colors.length; i++) {
  c = grad.colors[i];
  if (_.isArray(c)) {
  stop = c[0];
  c = c[1];
  }
  else stop = i / (grad.colors.length-1);
  gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
  }
  return gradient;
  }
  });
 
  Flotr.Color = Color;
 
  })();
 
  (function () {
 
  var _ = Flotr._;
 
  function getEl (el) {
  return (el && el.jquery) ? el[0] : el;
  }
 
  Flotr.DOM = {
  addClass: function(element, name){
  element = getEl(element);
  var classList = (element.className ? element.className : '');
  if (_.include(classList.split(/\s+/g), name)) return;
  element.className = (classList ? classList + ' ' : '') + name;
  },
  /**
  * Create an element.
  */
  create: function(tag){
  return document.createElement(tag);
  },
  node: function(html) {
  var div = Flotr.DOM.create('div'), n;
  div.innerHTML = html;
  n = div.children[0];
  div.innerHTML = '';
  return n;
  },
  /**
  * Remove all children.
  */
  empty: function(element){
  element = getEl(element);
  element.innerHTML = '';
  /*
  if (!element) return;
  _.each(element.childNodes, function (e) {
  Flotr.DOM.empty(e);
  element.removeChild(e);
  });
  */
  },
  remove: function (element) {
  element = getEl(element);
  element.parentNode.removeChild(element);
  },
  hide: function(element){
  element = getEl(element);
  Flotr.DOM.setStyles(element, {display:'none'});
  },
  /**
  * Insert a child.
  * @param {Element} element
  * @param {Element|String} Element or string to be appended.
  */
  insert: function(element, child){
  element = getEl(element);
  if(_.isString(child))
  element.innerHTML += child;
  else if (_.isElement(child))
  element.appendChild(child);
  },
  // @TODO find xbrowser implementation
  opacity: function(element, opacity) {
  element = getEl(element);
  element.style.opacity = opacity;
  },
  position: function(element, p){
  element = getEl(element);
  if (!element.offsetParent)
  return {left: (element.offsetLeft || 0), top: (element.offsetTop || 0)};
 
  p = this.position(element.offsetParent);
  p.left += element.offsetLeft;
  p.top += element.offsetTop;
  return p;
  },
  removeClass: function(element, name) {
  var classList = (element.className ? element.className : '');
  element = getEl(element);
  element.className = _.filter(classList.split(/\s+/g), function (c) {
  if (c != name) return true; }
  ).join(' ');
  },
  setStyles: function(element, o) {
  element = getEl(element);
  _.each(o, function (value, key) {
  element.style[key] = value;
  });
  },
  show: function(element){
  element = getEl(element);
  Flotr.DOM.setStyles(element, {display:''});
  },
  /**
  * Return element size.
  */
  size: function(element){
  element = getEl(element);
  return {
  height : element.offsetHeight,
  width : element.offsetWidth };
  }
  };
 
  })();
 
  /**
  * Flotr Date
  */
  Flotr.Date = {
 
  set : function (date, name, mode, value) {
  mode = mode || 'UTC';
  name = 'set' + (mode === 'UTC' ? 'UTC' : '') + name;
  date[name](value);
  },
 
  get : function (date, name, mode) {
  mode = mode || 'UTC';
  name = 'get' + (mode === 'UTC' ? 'UTC' : '') + name;
  return date[name]();
  },
 
  format: function(d, format, mode) {
  if (!d) return;
 
  // We should maybe use an "official" date format spec, like PHP date() or ColdFusion
  // http://fr.php.net/manual/en/function.date.php
  // http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_c-d_29.html
  var
  get = this.get,
  tokens = {
  h: get(d, 'Hours', mode).toString(),
  H: leftPad(get(d, 'Hours', mode)),
  M: leftPad(get(d, 'Minutes', mode)),
  S: leftPad(get(d, 'Seconds', mode)),
  s: get(d, 'Milliseconds', mode),
  d: get(d, 'Date', mode).toString(),
  m: (get(d, 'Month', mode) + 1).toString(),
  y: get(d, 'FullYear', mode).toString(),
  b: Flotr.Date.monthNames[get(d, 'Month', mode)]
  };
 
  function leftPad(n){
  n += '';
  return n.length == 1 ? "0" + n : n;
  }
 
  var r = [], c,
  escape = false;
 
  for (var i = 0; i < format.length; ++i) {
  c = format.charAt(i);
 
  if (escape) {
  r.push(tokens[c] || c);
  escape = false;
  }
  else if (c == "%")
  escape = true;
  else
  r.push(c);
  }
  return r.join('');
  },
  getFormat: function(time, span) {
  var tu = Flotr.Date.timeUnits;
  if (time < tu.second) return "%h:%M:%S.%s";
  else if (time < tu.minute) return "%h:%M:%S";
  else if (time < tu.day) return (span < 2 * tu.day) ? "%h:%M" : "%b %d %h:%M";
  else if (time < tu.month) return "%b %d";
  else if (time < tu.year) return (span < tu.year) ? "%b" : "%b %y";
  else return "%y";
  },
  formatter: function (v, axis) {
  var
  options = axis.options,
  scale = Flotr.Date.timeUnits[options.timeUnit],
  d = new Date(v * scale);
 
  // first check global format
  if (axis.options.timeFormat)
  return Flotr.Date.format(d, options.timeFormat, options.timeMode);
 
  var span = (axis.max - axis.min) * scale,
  t = axis.tickSize * Flotr.Date.timeUnits[axis.tickUnit];
 
  return Flotr.Date.format(d, Flotr.Date.getFormat(t, span), options.timeMode);
  },
  generator: function(axis) {
 
  var
  set = this.set,
  get = this.get,
  timeUnits = this.timeUnits,
  spec = this.spec,
  options = axis.options,
  mode = options.timeMode,
  scale = timeUnits[options.timeUnit],
  min = axis.min * scale,
  max = axis.max * scale,
  delta = (max - min) / options.noTicks,
  ticks = [],
  tickSize = axis.tickSize,
  tickUnit,
  formatter, i;
 
  // Use custom formatter or time tick formatter
  formatter = (options.tickFormatter === Flotr.defaultTickFormatter ?
  this.formatter : options.tickFormatter
  );
 
  for (i = 0; i < spec.length - 1; ++i) {
  var d = spec[i][0] * timeUnits[spec[i][1]];
  if (delta < (d + spec[i+1][0] * timeUnits[spec[i+1][1]]) / 2 && d >= tickSize)
  break;
  }
  tickSize = spec[i][0];
  tickUnit = spec[i][1];
 
  // special-case the possibility of several years
  if (tickUnit == "year") {
  tickSize = Flotr.getTickSize(options.noTicks*timeUnits.year, min, max, 0);
 
  // Fix for 0.5 year case
  if (tickSize == 0.5) {
  tickUnit = "month";
  tickSize = 6;
  }
  }
 
  axis.tickUnit = tickUnit;
  axis.tickSize = tickSize;
 
  var step = tickSize * timeUnits[tickUnit];
  d = new Date(min);
 
  function setTick (name) {
  set(d, name, mode, Flotr.floorInBase(
  get(d, name, mode), tickSize
  ));
  }
 
  switch (tickUnit) {
  case "millisecond": setTick('Milliseconds'); break;
  case "second": setTick('Seconds'); break;
  case "minute": setTick('Minutes'); break;
  case "hour": setTick('Hours'); break;
  case "month": setTick('Month'); break;
  case "year": setTick('FullYear'); break;
  }
 
  // reset smaller components
  if (step >= timeUnits.second) set(d, 'Milliseconds', mode, 0);
  if (step >= timeUnits.minute) set(d, 'Seconds', mode, 0);
  if (step >= timeUnits.hour) set(d, 'Minutes', mode, 0);
  if (step >= timeUnits.day) set(d, 'Hours', mode, 0);
  if (step >= timeUnits.day * 4) set(d, 'Date', mode, 1);
  if (step >= timeUnits.year) set(d, 'Month', mode, 0);
 
  var carry = 0, v = NaN, prev;
  do {
  prev = v;
  v = d.getTime();
  ticks.push({ v: v / scale, label: formatter(v / scale, axis) });
  if (tickUnit == "month") {
  if (tickSize < 1) {
  /* a bit complicated - we'll divide the month up but we need to take care of fractions
  so we don't end up in the middle of a day */
  set(d, 'Date', mode, 1);
  var start = d.getTime();
  set(d, 'Month', mode, get(d, 'Month', mode) + 1);
  var end = d.getTime();
  d.setTime(v + carry * timeUnits.hour + (end - start) * tickSize);
  carry = get(d, 'Hours', mode);
  set(d, 'Hours', mode, 0);
  }
  else
  set(d, 'Month', mode, get(d, 'Month', mode) + tickSize);
  }
  else if (tickUnit == "year") {
  set(d, 'FullYear', mode, get(d, 'FullYear', mode) + tickSize);
  }
  else
  d.setTime(v + step);
 
  } while (v < max && v != prev);
 
  return ticks;
  },
  timeUnits: {
  millisecond: 1,
  second: 1000,
  minute: 1000 * 60,
  hour: 1000 * 60 * 60,
  day: 1000 * 60 * 60 * 24,
  month: 1000 * 60 * 60 * 24 * 30,
  year: 1000 * 60 * 60 * 24 * 365.2425
  },
  // the allowed tick sizes, after 1 year we use an integer algorithm
  spec: [
  [1, "millisecond"], [20, "millisecond"], [50, "millisecond"], [100, "millisecond"], [200, "millisecond"], [500, "millisecond"],
  [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"],
  [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"],
  [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"],
  [1, "day"], [2, "day"], [3, "day"],
  [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"],
  [1, "year"]
  ],
  monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  };
 
  /**
  * Flotr Defaults
  */
  Flotr.defaultOptions = {
  colors: ['#00A8F0', '#C0D800', '#CB4B4B', '#4DA74D', '#9440ED'], //=> The default colorscheme. When there are > 5 series, additional colors are generated.
  ieBackgroundColor: '#FFFFFF', // Background color for excanvas clipping
  title: null, // => The graph's title
  subtitle: null, // => The graph's subtitle
  shadowSize: 4, // => size of the 'fake' shadow
  defaultType: null, // => default series type
  HtmlText: true, // => wether to draw the text using HTML or on the canvas
  fontColor: '#545454', // => default font color
  fontSize: 7.5, // => canvas' text font size
  resolution: 1, // => resolution of the graph, to have printer-friendly graphs !
  parseFloat: true, // => whether to preprocess data for floats (ie. if input is string)
  preventDefault: true, // => preventDefault by default for mobile events. Turn off to enable scroll.
  xaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 0, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => color of the ticks
  mode: 'normal', // => can be 'time' or 'normal'
  timeFormat: null,
  timeMode:'UTC', // => For UTC time ('local' for local time).
  timeUnit:'millisecond',// => Unit for time (millisecond, second, minute, hour, day, month, year)
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  x2axis: {},
  yaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 90, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => The color of the ticks
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  y2axis: {
  titleAngle: 270
  },
  grid: {
  color: '#545454', // => primary color used for outline and labels
  backgroundColor: null, // => null for transparent, else color
  backgroundImage: null, // => background image. String or object with src, left and top
  watermarkAlpha: 0.4, // =>
  tickColor: '#DDDDDD', // => color used for the ticks
  labelMargin: 3, // => margin in pixels
  verticalLines: true, // => whether to show gridlines in vertical direction
  minorVerticalLines: null, // => whether to show gridlines for minor ticks in vertical dir.
  horizontalLines: true, // => whether to show gridlines in horizontal direction
  minorHorizontalLines: null, // => whether to show gridlines for minor ticks in horizontal dir.
  outlineWidth: 1, // => width of the grid outline/border in pixels
  outline : 'nsew', // => walls of the outline to display
  circular: false // => if set to true, the grid will be circular, must be used when radars are drawn
  },
  mouse: {
  track: false, // => true to track the mouse, no tracking otherwise
  trackAll: false,
  position: 'se', // => position of the value box (default south-east)
  relative: false, // => next to the mouse cursor
  trackFormatter: Flotr.defaultTrackFormatter, // => formats the values in the value box
  margin: 5, // => margin in pixels of the valuebox
  lineColor: '#FF3F19', // => line color of points that are drawn when mouse comes near a value of a series
  trackDecimals: 1, // => decimals for the track values
  sensibility: 2, // => the lower this number, the more precise you have to aim to show a value
  trackY: true, // => whether or not to track the mouse in the y axis
  radius: 3, // => radius of the track point
  fillColor: null, // => color to fill our select bar with only applies to bar and similar graphs (only bars for now)
  fillOpacity: 0.4 // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  }
  };
 
  /**
  * Flotr Event Adapter
  */
  (function () {
  var
  F = Flotr,
  bean = F.bean;
  F.EventAdapter = {
  observe: function(object, name, callback) {
  bean.add(object, name, callback);
  return this;
  },
  fire: function(object, name, args) {
  bean.fire(object, name, args);
  if (typeof(Prototype) != 'undefined')
  Event.fire(object, name, args);
  // @TODO Someone who uses mootools, add mootools adapter for existing applciations.
  return this;
  },
  stopObserving: function(object, name, callback) {
  bean.remove(object, name, callback);
  return this;
  },
  eventPointer: function(e) {
  if (!F._.isUndefined(e.touches) && e.touches.length > 0) {
  return {
  x : e.touches[0].pageX,
  y : e.touches[0].pageY
  };
  } else if (!F._.isUndefined(e.changedTouches) && e.changedTouches.length > 0) {
  return {
  x : e.changedTouches[0].pageX,
  y : e.changedTouches[0].pageY
  };
  } else if (e.pageX || e.pageY) {
  return {
  x : e.pageX,
  y : e.pageY
  };
  } else if (e.clientX || e.clientY) {
  var
  d = document,
  b = d.body,
  de = d.documentElement;
  return {
  x: e.clientX + b.scrollLeft + de.scrollLeft,
  y: e.clientY + b.scrollTop + de.scrollTop
  };
  }
  }
  };
  })();
 
  /**
  * Flotr2 (c) 2012 Carl Sutherland
  * MIT License
  * Special thanks to:
  * Flotr: http://code.google.com/p/flotr/ (fork)
  * Flot: https://github.com/flot/flot (original fork)
  */
  (function () {
 
  var
  global = this,
  previousFlotr = this.Flotr,
  Flotr;
 
  Flotr = {
  _: _,
  bean: bean,
  isIphone: /iphone/i.test(navigator.userAgent),
  isIE: (navigator.appVersion.indexOf("MSIE") != -1 ? parseFloat(navigator.appVersion.split("MSIE")[1]) : false),
 
  /**
  * An object of the registered graph types. Use Flotr.addType(type, object)
  * to add your own type.
  */
  graphTypes: {},
 
  /**
  * The list of the registered plugins
  */
  plugins: {},
 
  /**
  * Can be used to add your own chart type.
  * @param {String} name - Type of chart, like 'pies', 'bars' etc.
  * @param {String} graphType - The object containing the basic drawing functions (draw, etc)
  */
  addType: function(name, graphType){
  Flotr.graphTypes[name] = graphType;
  Flotr.defaultOptions[name] = graphType.options || {};
  Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
  },
 
  /**
  * Can be used to add a plugin
  * @param {String} name - The name of the plugin
  * @param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
  */
  addPlugin: function(name, plugin){
  Flotr.plugins[name] = plugin;
  Flotr.defaultOptions[name] = plugin.options || {};
  },
 
  /**
  * Draws the graph. This function is here for backwards compatibility with Flotr version 0.1.0alpha.
  * You could also draw graphs by directly calling Flotr.Graph(element, data, options).
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  * @param {Class} _GraphKlass_ - (optional) Class to pass the arguments to, defaults to Flotr.Graph
  * @return {Object} returns a new graph object and of course draws the graph.
  */
  draw: function(el, data, options, GraphKlass){
  GraphKlass = GraphKlass || Flotr.Graph;
  return new GraphKlass(el, data, options);
  },
 
  /**
  * Recursively merges two objects.
  * @param {Object} src - source object (likely the object with the least properties)
  * @param {Object} dest - destination object (optional, object with the most properties)
  * @return {Object} recursively merged Object
  * @TODO See if we can't remove this.
  */
  merge: function(src, dest){
  var i, v, result = dest || {};
 
  for (i in src) {
  v = src[i];
  if (v && typeof(v) === 'object') {
  if (v.constructor === Array) {
  result[i] = this._.clone(v);
  } else if (
  v.constructor !== RegExp &&
  !this._.isElement(v) &&
  !v.jquery
  ) {
  result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
  } else {
  result[i] = v;
  }
  } else {
  result[i] = v;
  }
  }
 
  return result;
  },
 
  /**
  * Recursively clones an object.
  * @param {Object} object - The object to clone
  * @return {Object} the clone
  * @TODO See if we can't remove this.
  */
  clone: function(object){
  return Flotr.merge(object, {});
  },
 
  /**
  * Function calculates the ticksize and returns it.
  * @param {Integer} noTicks - number of ticks
  * @param {Integer} min - lower bound integer value for the current axis
  * @param {Integer} max - upper bound integer value for the current axis
  * @param {Integer} decimals - number of decimals for the ticks
  * @return {Integer} returns the ticksize in pixels
  */
  getTickSize: function(noTicks, min, max, decimals){
  var delta = (max - min) / noTicks,
  magn = Flotr.getMagnitude(delta),
  tickSize = 10,
  norm = delta / magn; // Norm is between 1.0 and 10.0.
 
  if(norm < 1.5) tickSize = 1;
  else if(norm < 2.25) tickSize = 2;
  else if(norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
  else if(norm < 7.5) tickSize = 5;
 
  return tickSize * magn;
  },
 
  /**
  * Default tick formatter.
  * @param {String, Integer} val - tick value integer
  * @param {Object} axisOpts - the axis' options
  * @return {String} formatted tick string
  */
  defaultTickFormatter: function(val, axisOpts){
  return val+'';
  },
 
  /**
  * Formats the mouse tracker values.
  * @param {Object} obj - Track value Object {x:..,y:..}
  * @return {String} Formatted track string
  */
  defaultTrackFormatter: function(obj){
  return '('+obj.x+', '+obj.y+')';
  },
 
  /**
  * Utility function to convert file size values in bytes to kB, MB, ...
  * @param value {Number} - The value to convert
  * @param precision {Number} - The number of digits after the comma (default: 2)
  * @param base {Number} - The base (default: 1000)
  */
  engineeringNotation: function(value, precision, base){
  var sizes = ['Y','Z','E','P','T','G','M','k',''],
  fractionSizes = ['y','z','a','f','p','n','µ','m',''],
  total = sizes.length;
 
  base = base || 1000;
  precision = Math.pow(10, precision || 2);
 
  if (value === 0) return 0;
 
  if (value > 1) {
  while (total-- && (value >= base)) value /= base;
  }
  else {
  sizes = fractionSizes;
  total = sizes.length;
  while (total-- && (value < 1)) value *= base;
  }
 
  return (Math.round(value * precision) / precision) + sizes[total];
  },
 
  /**
  * Returns the magnitude of the input value.
  * @param {Integer, Float} x - integer or float value
  * @return {Integer, Float} returns the magnitude of the input value
  */
  getMagnitude: function(x){
  return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
  },
  toPixel: function(val){
  return Math.floor(val)+0.5;//((val-Math.round(val) < 0.4) ? (Math.floor(val)-0.5) : val);
  },
  toRad: function(angle){
  return -angle * (Math.PI/180);
  },
  floorInBase: function(n, base) {
  return base * Math.floor(n / base);
  },
  drawText: function(ctx, text, x, y, style) {
  if (!ctx.fillText) {
  ctx.drawText(text, x, y, style);
  return;
  }
 
  style = this._.extend({
  size: Flotr.defaultOptions.fontSize,
  color: '#000000',
  textAlign: 'left',
  textBaseline: 'bottom',
  weight: 1,
  angle: 0
  }, style);
 
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(style.angle);
  ctx.fillStyle = style.color;
  ctx.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  ctx.textAlign = style.textAlign;
  ctx.textBaseline = style.textBaseline;
  ctx.fillText(text, 0, 0);
  ctx.restore();
  },
  getBestTextAlign: function(angle, style) {
  style = style || {textAlign: 'center', textBaseline: 'middle'};
  angle += Flotr.getTextAngleFromAlign(style);
 
  if (Math.abs(Math.cos(angle)) > 10e-3)
  style.textAlign = (Math.cos(angle) > 0 ? 'right' : 'left');
 
  if (Math.abs(Math.sin(angle)) > 10e-3)
  style.textBaseline = (Math.sin(angle) > 0 ? 'top' : 'bottom');
 
  return style;
  },
  alignTable: {
  'right middle' : 0,
  'right top' : Math.PI/4,
  'center top' : Math.PI/2,
  'left top' : 3*(Math.PI/4),
  'left middle' : Math.PI,
  'left bottom' : -3*(Math.PI/4),
  'center bottom': -Math.PI/2,
  'right bottom' : -Math.PI/4,
  'center middle': 0
  },
  getTextAngleFromAlign: function(style) {
  return Flotr.alignTable[style.textAlign+' '+style.textBaseline] || 0;
  },
  noConflict : function () {
  global.Flotr = previousFlotr;
  return this;
  }
  };
 
  global.Flotr = Flotr;
 
  })();
 
  /**
  * Flotr Graph class that plots a graph on creation.
  */
  (function () {
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._,
  flotr = Flotr;
  /**
  * Flotr Graph constructor.
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  */
  Graph = function(el, data, options){
  // Let's see if we can get away with out this [JS]
  // try {
  this._setEl(el);
  this._initMembers();
  this._initPlugins();
 
  E.fire(this.el, 'flotr:beforeinit', [this]);
 
  this.data = data;
  this.series = flotr.Series.getSeries(data);
  this._initOptions(options);
  this._initGraphTypes();
  this._initCanvas();
  this._text = new flotr.Text({
  element : this.el,
  ctx : this.ctx,
  html : this.options.HtmlText,
  textEnabled : this.textEnabled
  });
  E.fire(this.el, 'flotr:afterconstruct', [this]);
  this._initEvents();
 
  this.findDataRanges();
  this.calculateSpacing();
 
  this.draw(_.bind(function() {
  E.fire(this.el, 'flotr:afterinit', [this]);
  }, this));
  /*
  try {
  } catch (e) {
  try {
  console.error(e);
  } catch (e2) {}
  }*/
  };
 
  function observe (object, name, callback) {
  E.observe.apply(this, arguments);
  this._handles.push(arguments);
  return this;
  }
 
  Graph.prototype = {
 
  destroy: function () {
  E.fire(this.el, 'flotr:destroy');
  _.each(this._handles, function (handle) {
  E.stopObserving.apply(this, handle);
  });
  this._handles = [];
  this.el.graph = null;
  },
 
  observe : observe,
 
  /**
  * @deprecated
  */
  _observe : observe,
 
  processColor: function(color, options){
  var o = { x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx };
  _.extend(o, options);
  return flotr.Color.processColor(color, o);
  },
  /**
  * Function determines the min and max values for the xaxis and yaxis.
  *
  * TODO logarithmic range validation (consideration of 0)
  */
  findDataRanges: function(){
  var a = this.axes,
  xaxis, yaxis, range;
 
  _.each(this.series, function (series) {
  range = series.getRange();
  if (range) {
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
  xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
  yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
  yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
  xaxis.used = (xaxis.used || range.xused);
  yaxis.used = (yaxis.used || range.yused);
  }
  }, this);
 
  // Check for empty data, no data case (none used)
  if (!a.x.used && !a.x2.used) a.x.used = true;
  if (!a.y.used && !a.y2.used) a.y.used = true;
 
  _.each(a, function (axis) {
  axis.calculateRange();
  });
 
  var
  types = _.keys(flotr.graphTypes),
  drawn = false;
 
  _.each(this.series, function (series) {
  if (series.hide) return;
  _.each(types, function (type) {
  if (series[type] && series[type].show) {
  this.extendRange(type, series);
  drawn = true;
  }
  }, this);
  if (!drawn) {
  this.extendRange(this.options.defaultType, series);
  }
  }, this);
  },
 
  extendRange : function (type, series) {
  if (this[type].extendRange) this[type].extendRange(series, series.data, series[type], this[type]);
  if (this[type].extendYRange) this[type].extendYRange(series.yaxis, series.data, series[type], this[type]);
  if (this[type].extendXRange) this[type].extendXRange(series.xaxis, series.data, series[type], this[type]);
  },
 
  /**
  * Calculates axis label sizes.
  */
  calculateSpacing: function(){
 
  var a = this.axes,
  options = this.options,
  series = this.series,
  margin = options.grid.labelMargin,
  T = this._text,
  x = a.x,
  x2 = a.x2,
  y = a.y,
  y2 = a.y2,
  maxOutset = options.grid.outlineWidth,
  i, j, l, dim;
 
  // TODO post refactor, fix this
  _.each(a, function (axis) {
  axis.calculateTicks();
  axis.calculateTextDimensions(T, options);
  });
 
  // Title height
  dim = T.dimensions(
  options.title,
  {size: options.fontSize*1.5},
  'font-size:1em;font-weight:bold;',
  'flotr-title'
  );
  this.titleHeight = dim.height;
 
  // Subtitle height
  dim = T.dimensions(
  options.subtitle,
  {size: options.fontSize},
  'font-size:smaller;',
  'flotr-subtitle'
  );
  this.subtitleHeight = dim.height;
 
  for(j = 0; j < options.length; ++j){
  if (series[j].points.show){
  maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
  }
  }
 
  var p = this.plotOffset;
  if (x.options.margin === false) {
  p.bottom = 0;
  p.top = 0;
  } else {
  p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ? (x.maxLabel.height + margin) : 0)) +
  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;
 
  p.top += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
  }
  if (y.options.margin === false) {
  p.left = 0;
  p.right = 0;
  } else {
  p.left += (options.grid.circular ? 0 : (y.used && y.options.showLabels ? (y.maxLabel.width + margin) : 0)) +
  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;
 
  p.right += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
  }
 
  p.top = Math.floor(p.top); // In order the outline not to be blured
 
  this.plotWidth = this.canvasWidth - p.left - p.right;
  this.plotHeight = this.canvasHeight - p.bottom - p.top;
 
  // TODO post refactor, fix this
  x.length = x2.length = this.plotWidth;
  y.length = y2.length = this.plotHeight;
  y.offset = y2.offset = this.plotHeight;
  x.setScale();
  x2.setScale();
  y.setScale();
  y2.setScale();
  },
  /**
  * Draws grid, labels, series and outline.
  */
  draw: function(after) {
 
  var
  context = this.ctx,
  i;
 
  E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
 
  if (this.series.length) {
 
  context.save();
  context.translate(this.plotOffset.left, this.plotOffset.top);
 
  for (i = 0; i < this.series.length; i++) {
  if (!this.series[i].hide) this.drawSeries(this.series[i]);
  }
 
  context.restore();
  this.clip();
  }
 
  E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
  if (after) after();
  },
  /**
  * Actually draws the graph.
  * @param {Object} series - series to draw
  */
  drawSeries: function(series){
 
  function drawChart (series, typeKey) {
  var options = this.getOptions(series, typeKey);
  this[typeKey].draw(options);
  }
 
  var drawn = false;
  series = series || this.series;
 
  _.each(flotr.graphTypes, function (type, typeKey) {
  if (series[typeKey] && series[typeKey].show && this[typeKey]) {
  drawn = true;
  drawChart.call(this, series, typeKey);
  }
  }, this);
 
  if (!drawn) drawChart.call(this, series, this.options.defaultType);
  },
 
  getOptions : function (series, typeKey) {
  var
  type = series[typeKey],
  graphType = this[typeKey],
  xaxis = series.xaxis,
  yaxis = series.yaxis,
  options = {
  context : this.ctx,
  width : this.plotWidth,
  height : this.plotHeight,
  fontSize : this.options.fontSize,
  fontColor : this.options.fontColor,
  textEnabled : this.textEnabled,
  htmlText : this.options.HtmlText,
  text : this._text, // TODO Is this necessary?
  element : this.el,
  data : series.data,
  color : series.color,
  shadowSize : series.shadowSize,
  xScale : xaxis.d2p,
  yScale : yaxis.d2p,
  xInverse : xaxis.p2d,
  yInverse : yaxis.p2d
  };
 
  options = flotr.merge(type, options);
 
  // Fill
  options.fillStyle = this.processColor(
  type.fillColor || series.color,
  {opacity: type.fillOpacity}
  );
 
  return options;
  },
  /**
  * Calculates the coordinates from a mouse event object.
  * @param {Event} event - Mouse Event object.
  * @return {Object} Object with coordinates of the mouse.
  */
  getEventPosition: function (e){
 
  var
  d = document,
  b = d.body,
  de = d.documentElement,
  axes = this.axes,
  plotOffset = this.plotOffset,
  lastMousePos = this.lastMousePos,
  pointer = E.eventPointer(e),
  dx = pointer.x - lastMousePos.pageX,
  dy = pointer.y - lastMousePos.pageY,
  r, rx, ry;
 
  if ('ontouchstart' in this.el) {
  r = D.position(this.overlay);
  rx = pointer.x - r.left - plotOffset.left;
  ry = pointer.y - r.top - plotOffset.top;
  } else {
  r = this.overlay.getBoundingClientRect();
  rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
  ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
  }
 
  return {
  x: axes.x.p2d(rx),
  x2: axes.x2.p2d(rx),
  y: axes.y.p2d(ry),
  y2: axes.y2.p2d(ry),
  relX: rx,
  relY: ry,
  dX: dx,
  dY: dy,
  absX: pointer.x,
  absY: pointer.y,
  pageX: pointer.x,
  pageY: pointer.y
  };
  },
  /**
  * Observes the 'click' event and fires the 'flotr:click' event.
  * @param {Event} event - 'click' Event object.
  */
  clickHandler: function(event){
  if(this.ignoreClick){
  this.ignoreClick = false;
  return this.ignoreClick;
  }
  E.fire(this.el, 'flotr:click', [this.getEventPosition(event), this]);
  },
  /**
  * Observes mouse movement over the graph area. Fires the 'flotr:mousemove' event.
  * @param {Event} event - 'mousemove' Event object.
  */
  mouseMoveHandler: function(event){
  if (this.mouseDownMoveHandler) return;
  var pos = this.getEventPosition(event);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  },
  /**
  * Observes the 'mousedown' event.
  * @param {Event} event - 'mousedown' Event object.
  */
  mouseDownHandler: function (event){
 
  /*
  // @TODO Context menu?
  if(event.isRightClick()) {
  event.stop();
 
  var overlay = this.overlay;
  overlay.hide();
 
  function cancelContextMenu () {
  overlay.show();
  E.stopObserving(document, 'mousemove', cancelContextMenu);
  }
  E.observe(document, 'mousemove', cancelContextMenu);
  return;
  }
  */
 
  if (this.mouseUpHandler) return;
  this.mouseUpHandler = _.bind(function (e) {
  E.stopObserving(document, 'mouseup', this.mouseUpHandler);
  E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
  this.mouseDownMoveHandler = null;
  this.mouseUpHandler = null;
  // @TODO why?
  //e.stop();
  E.fire(this.el, 'flotr:mouseup', [e, this]);
  }, this);
  this.mouseDownMoveHandler = _.bind(function (e) {
  var pos = this.getEventPosition(e);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  }, this);
  E.observe(document, 'mouseup', this.mouseUpHandler);
  E.observe(document, 'mousemove', this.mouseDownMoveHandler);
  E.fire(this.el, 'flotr:mousedown', [event, this]);
  this.ignoreClick = false;
  },
  drawTooltip: function(content, x, y, options) {
  var mt = this.getMouseTrack(),
  style = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;',
  p = options.position,
  m = options.margin,
  plotOffset = this.plotOffset;
 
  if(x !== null && y !== null){
  if (!options.relative) { // absolute to the canvas
  if(p.charAt(0) == 'n') style += 'top:' + (m + plotOffset.top) + 'px;bottom:auto;';
  else if(p.charAt(0) == 's') style += 'bottom:' + (m + plotOffset.bottom) + 'px;top:auto;';
  if(p.charAt(1) == 'e') style += 'right:' + (m + plotOffset.right) + 'px;left:auto;';
  else if(p.charAt(1) == 'w') style += 'left:' + (m + plotOffset.left) + 'px;right:auto;';
  }
  else { // relative to the mouse
  if(p.charAt(0) == 'n') style += 'bottom:' + (m - plotOffset.top - y + this.canvasHeight) + 'px;top:auto;';
  else if(p.charAt(0) == 's') style += 'top:' + (m + plotOffset.top + y) + 'px;bottom:auto;';
  if(p.charAt(1) == 'e') style += 'left:' + (m + plotOffset.left + x) + 'px;right:auto;';
  else if(p.charAt(1) == 'w') style += 'right:' + (m - plotOffset.left - x + this.canvasWidth) + 'px;left:auto;';
  }
 
  mt.style.cssText = style;
  D.empty(mt);
  D.insert(mt, content);
  D.show(mt);
  }
  else {
  D.hide(mt);
  }
  },
 
  clip: function (ctx) {
 
  var
  o = this.plotOffset,
  w = this.canvasWidth,
  h = this.canvasHeight;
 
  ctx = ctx || this.ctx;
 
  if (flotr.isIE && flotr.isIE < 9) {
  // Clipping for excanvas :-(
  ctx.save();
  ctx.fillStyle = this.processColor(this.options.ieBackgroundColor);
  ctx.fillRect(0, 0, w, o.top);
  ctx.fillRect(0, 0, o.left, h);
  ctx.fillRect(0, h - o.bottom, w, o.bottom);
  ctx.fillRect(w - o.right, 0, o.right,h);
  ctx.restore();
  } else {
  ctx.clearRect(0, 0, w, o.top);
  ctx.clearRect(0, 0, o.left, h);
  ctx.clearRect(0, h - o.bottom, w, o.bottom);
  ctx.clearRect(w - o.right, 0, o.right,h);
  }
  },
 
  _initMembers: function() {
  this._handles = [];
  this.lastMousePos = {pageX: null, pageY: null };
  this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
  this.ignoreClick = true;
  this.prevHit = null;
  },
 
  _initGraphTypes: function() {
  _.each(flotr.graphTypes, function(handler, graphType){
  this[graphType] = flotr.clone(handler);
  }, this);
  },
 
  _initEvents: function () {
 
  var
  el = this.el,
  touchendHandler, movement, touchend;
 
  if ('ontouchstart' in el) {
 
  touchendHandler = _.bind(function (e) {
  touchend = true;
  E.stopObserving(document, 'touchend', touchendHandler);
  E.fire(el, 'flotr:mouseup', [event, this]);
  this.multitouches = null;
 
  if (!movement) {
  this.clickHandler(e);
  }
  }, this);
 
  this.observe(this.overlay, 'touchstart', _.bind(function (e) {
  movement = false;
  touchend = false;
  this.ignoreClick = false;
 
  if (e.touches && e.touches.length > 1) {
  this.multitouches = e.touches;
  }
 
  E.fire(el, 'flotr:mousedown', [event, this]);
  this.observe(document, 'touchend', touchendHandler);
  }, this));
 
  this.observe(this.overlay, 'touchmove', _.bind(function (e) {
 
  var pos = this.getEventPosition(e);
 
  if (this.options.preventDefault) {
  e.preventDefault();
  }
 
  movement = true;
 
  if (this.multitouches || (e.touches && e.touches.length > 1)) {
  this.multitouches = e.touches;
  } else {
  if (!touchend) {
  E.fire(el, 'flotr:mousemove', [event, pos, this]);
  }
  }
  this.lastMousePos = pos;
  }, this));
 
  } else {
  this.
  observe(this.overlay, 'mousedown', _.bind(this.mouseDownHandler, this)).
  observe(el, 'mousemove', _.bind(this.mouseMoveHandler, this)).
  observe(this.overlay, 'click', _.bind(this.clickHandler, this)).
  observe(el, 'mouseout', function () {
  E.fire(el, 'flotr:mouseout');
  });
  }
  },
 
  /**
  * Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
  * of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
  * are created, the elements are inserted into the container element.
  */
  _initCanvas: function(){
  var el = this.el,
  o = this.options,
  children = el.children,
  removedChildren = [],
  child, i,
  size, style;
 
  // Empty the el
  for (i = children.length; i--;) {
  child = children[i];
  if (!this.canvas && child.className === 'flotr-canvas') {
  this.canvas = child;
  } else if (!this.overlay && child.className === 'flotr-overlay') {
  this.overlay = child;
  } else {
  removedChildren.push(child);
  }
  }
  for (i = removedChildren.length; i--;) {
  el.removeChild(removedChildren[i]);
  }
 
  D.setStyles(el, {position: 'relative'}); // For positioning labels and overlay.
  size = {};
  size.width = el.clientWidth;
  size.height = el.clientHeight;
 
  if(size.width <= 0 || size.height <= 0 || o.resolution <= 0){
  throw 'Invalid dimensions for plot, width = ' + size.width + ', height = ' + size.height + ', resolution = ' + o.resolution;
  }
 
  // Main canvas for drawing graph types
  this.canvas = getCanvas(this.canvas, 'canvas');
  // Overlay canvas for interactive features
  this.overlay = getCanvas(this.overlay, 'overlay');
  this.ctx = getContext(this.canvas);
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this.octx = getContext(this.overlay);
  this.octx.clearRect(0, 0, this.overlay.width, this.overlay.height);
  this.canvasHeight = size.height;
  this.canvasWidth = size.width;
  this.textEnabled = !!this.ctx.drawText || !!this.ctx.fillText; // Enable text functions
 
  function getCanvas(canvas, name){
  if(!canvas){
  canvas = D.create('canvas');
  if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
  FlashCanvas.initElement(canvas);
  }
  canvas.className = 'flotr-'+name;
  canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
  D.insert(el, canvas);
  }
  _.each(size, function(size, attribute){
  D.show(canvas);
  if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
  return;
  }
  canvas.setAttribute(attribute, size * o.resolution);
  canvas.style[attribute] = size + 'px';
  });
  canvas.context_ = null; // Reset the ExCanvas context
  return canvas;
  }
 
  function getContext(canvas){
  if(window.G_vmlCanvasManager) window.G_vmlCanvasManager.initElement(canvas); // For ExCanvas
  var context = canvas.getContext('2d');
  if(!window.G_vmlCanvasManager) context.scale(o.resolution, o.resolution);
  return context;
  }
  },
 
  _initPlugins: function(){
  // TODO Should be moved to flotr and mixed in.
  _.each(flotr.plugins, function(plugin, name){
  _.each(plugin.callbacks, function(fn, c){
  this.observe(this.el, c, _.bind(fn, this));
  }, this);
  this[name] = flotr.clone(plugin);
  _.each(this[name], function(fn, p){
  if (_.isFunction(fn))
  this[name][p] = _.bind(fn, this);
  }, this);
  }, this);
  },
 
  /**
  * Sets options and initializes some variables and color specific values, used by the constructor.
  * @param {Object} opts - options object
  */
  _initOptions: function(opts){
  var options = flotr.clone(flotr.defaultOptions);
  options.x2axis = _.extend(_.clone(options.xaxis), options.x2axis);
  options.y2axis = _.extend(_.clone(options.yaxis), options.y2axis);
  this.options = flotr.merge(opts || {}, options);
 
  if (this.options.grid.minorVerticalLines === null &&
  this.options.xaxis.scaling === 'logarithmic') {
  this.options.grid.minorVerticalLines = true;
  }
  if (this.options.grid.minorHorizontalLines === null &&
  this.options.yaxis.scaling === 'logarithmic') {
  this.options.grid.minorHorizontalLines = true;
  }
 
  E.fire(this.el, 'flotr:afterinitoptions', [this]);
 
  this.axes = flotr.Axis.getAxes(this.options);
 
  // Initialize some variables used throughout this function.
  var assignedColors = [],
  colors = [],
  ln = this.series.length,
  neededColors = this.series.length,
  oc = this.options.colors,
  usedColors = [],
  variation = 0,
  c, i, j, s;
 
  // Collect user-defined colors from series.
  for(i = neededColors - 1; i > -1; --i){
  c = this.series[i].color;
  if(c){
  --neededColors;
  if(_.isNumber(c)) assignedColors.push(c);
  else usedColors.push(flotr.Color.parse(c));
  }
  }
 
  // Calculate the number of colors that need to be generated.
  for(i = assignedColors.length - 1; i > -1; --i)
  neededColors = Math.max(neededColors, assignedColors[i] + 1);
 
  // Generate needed number of colors.
  for(i = 0; colors.length < neededColors;){
  c = (oc.length == i) ? new flotr.Color(100, 100, 100) : flotr.Color.parse(oc[i]);
 
  // Make sure each serie gets a different color.
  var sign = variation % 2 == 1 ? -1 : 1,
  factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
  c.scale(factor, factor, factor);
 
  /**
  * @todo if we're getting too close to something else, we should probably skip this one
  */
  colors.push(c);
 
  if(++i >= oc.length){
  i = 0;
  ++variation;
  }
  }
 
  // Fill the options with the generated colors.
  for(i = 0, j = 0; i < ln; ++i){
  s = this.series[i];
 
  // Assign the color.
  if (!s.color){
  s.color = colors[j++].toString();
  }else if(_.isNumber(s.color)){
  s.color = colors[s.color].toString();
  }
 
  // Every series needs an axis
  if (!s.xaxis) s.xaxis = this.axes.x;
  if (s.xaxis == 1) s.xaxis = this.axes.x;
  else if (s.xaxis == 2) s.xaxis = this.axes.x2;
 
  if (!s.yaxis) s.yaxis = this.axes.y;
  if (s.yaxis == 1) s.yaxis = this.axes.y;
  else if (s.yaxis == 2) s.yaxis = this.axes.y2;
 
  // Apply missing options to the series.
  for (var t in flotr.graphTypes){
  s[t] = _.extend(_.clone(this.options[t]), s[t]);
  }
  s.mouse = _.extend(_.clone(this.options.mouse), s.mouse);
 
  if (_.isUndefined(s.shadowSize)) s.shadowSize = this.options.shadowSize;
  }
  },
 
  _setEl: function(el) {
  if (!el) throw 'The target container doesn\'t exist';
  else if (el.graph instanceof Graph) el.graph.destroy();
  else if (!el.clientWidth) throw 'The target container must be visible';
 
  el.graph = this;
  this.el = el;
  }
  };
 
  Flotr.Graph = Graph;
 
  })();
 
  /**
  * Flotr Series Library
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  function Series (o) {
  _.extend(this, o);
  }
 
  Series.prototype = {
 
  getRange: function () {
 
  var
  data = this.data,
  length = data.length,
  xmin = Number.MAX_VALUE,
  ymin = Number.MAX_VALUE,
  xmax = -Number.MAX_VALUE,
  ymax = -Number.MAX_VALUE,
  xused = false,
  yused = false,
  x, y, i;
 
  if (length < 0 || this.hide) return false;
 
  for (i = 0; i < length; i++) {
  x = data[i][0];
  y = data[i][1];
  if (x !== null) {
  if (x < xmin) { xmin = x; xused = true; }
  if (x > xmax) { xmax = x; xused = true; }
  }
  if (y !== null) {
  if (y < ymin) { ymin = y; yused = true; }
  if (y > ymax) { ymax = y; yused = true; }
  }
  }
 
  return {
  xmin : xmin,
  xmax : xmax,
  ymin : ymin,
  ymax : ymax,
  xused : xused,
  yused : yused
  };
  }
  };
 
  _.extend(Series, {
  /**
  * Collects dataseries from input and parses the series into the right format. It returns an Array
  * of Objects each having at least the 'data' key set.
  * @param {Array, Object} data - Object or array of dataseries
  * @return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
  */
  getSeries: function(data){
  return _.map(data, function(s){
  var series;
  if (s.data) {
  series = new Series();
  _.extend(series, s);
  } else {
  series = new Series({data:s});
  }
  return series;
  });
  }
  });
 
  Flotr.Series = Series;
 
  })();
 
  /**
  * Text Utilities
  */
  (function () {
 
  var
  F = Flotr,
  D = F.DOM,
  _ = F._,
 
  Text = function (o) {
  this.o = o;
  };
 
  Text.prototype = {
 
  dimensions : function (text, canvasStyle, htmlStyle, className) {
 
  if (!text) return { width : 0, height : 0 };
 
  return (this.o.html) ?
  this.html(text, this.o.element, htmlStyle, className) :
  this.canvas(text, canvasStyle);
  },
 
  canvas : function (text, style) {
 
  if (!this.o.textEnabled) return;
  style = style || {};
 
  var
  metrics = this.measureText(text, style),
  width = metrics.width,
  height = style.size || F.defaultOptions.fontSize,
  angle = style.angle || 0,
  cosAngle = Math.cos(angle),
  sinAngle = Math.sin(angle),
  widthPadding = 2,
  heightPadding = 6,
  bounds;
 
  bounds = {
  width: Math.abs(cosAngle * width) + Math.abs(sinAngle * height) + widthPadding,
  height: Math.abs(sinAngle * width) + Math.abs(cosAngle * height) + heightPadding
  };
 
  return bounds;
  },
 
  html : function (text, element, style, className) {
 
  var div = D.create('div');
 
  D.setStyles(div, { 'position' : 'absolute', 'top' : '-10000px' });
  D.insert(div, '<div style="'+style+'" class="'+className+' flotr-dummy-div">' + text + '</div>');
  D.insert(this.o.element, div);
 
  return D.size(div);
  },
 
  measureText : function (text, style) {
 
  var
  context = this.o.ctx,
  metrics;
 
  if (!context.fillText || (F.isIphone && context.measure)) {
  return { width : context.measure(text, style)};
  }
 
  style = _.extend({
  size: F.defaultOptions.fontSize,
  weight: 1,
  angle: 0
  }, style);
 
  context.save();
  context.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
  metrics = context.measureText(text);
  context.restore();
 
  return metrics;
  }
  };
 
  Flotr.Text = Text;
 
  })();
 
 
  return Flotr;
 
  }));
  (function (root, factory) {
  if (typeof define === 'function' && define.amd) {
  // AMD. Register as an anonymous module.
  define(['bean', 'underscore'], function (bean, _) {
  // Also create a global in case some scripts
  // that are loaded still are looking for
  // a global even when an AMD loader is in use.
  return (root.Flotr = factory(bean, _));
  });
  } else {
  // Browser globals
  root.Flotr = factory(root.bean, root._);
  }
  }(this, function (bean, _) {
 
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('crosshair', {
  options: {
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#FF0000', // => crosshair color
  hideCursor: true // => hide the cursor when the crosshair is shown
  },
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  if (this.options.crosshair.mode) {
  this.crosshair.clearCrosshair();
  this.crosshair.drawCrosshair(pos);
  }
  }
  },
  /**
  * Draws the selection box.
  */
  drawCrosshair: function(pos) {
  var octx = this.octx,
  options = this.options.crosshair,
  plotOffset = this.plotOffset,
  x = plotOffset.left + Math.round(pos.relX) + 0.5,
  y = plotOffset.top + Math.round(pos.relY) + 0.5;
 
  if (pos.relX < 0 || pos.relY < 0 || pos.relX > this.plotWidth || pos.relY > this.plotHeight) {
  this.el.style.cursor = null;
  D.removeClass(this.el, 'flotr-crosshair');
  return;
  }
 
  if (options.hideCursor) {
  this.el.style.cursor = 'none';
  D.addClass(this.el, 'flotr-crosshair');
  }
 
  octx.save();
  octx.strokeStyle = options.color;
  octx.lineWidth = 1;
  octx.beginPath();
 
  if (options.mode.indexOf('x') != -1) {
  octx.moveTo(x, plotOffset.top);
  octx.lineTo(x, plotOffset.top + this.plotHeight);
  }
 
  if (options.mode.indexOf('y') != -1) {
  octx.moveTo(plotOffset.left, y);
  octx.lineTo(plotOffset.left + this.plotWidth, y);
  }
 
  octx.stroke();
  octx.restore();
  },
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearCrosshair: function() {
 
  var
  plotOffset = this.plotOffset,
  position = this.lastMousePos,
  context = this.octx;
 
  if (position) {
  context.clearRect(
  Math.round(position.relX) + plotOffset.left,
  plotOffset.top,
  1,
  this.plotHeight + 1
  );
  context.clearRect(
  plotOffset.left,
  Math.round(position.relY) + plotOffset.top,
  this.plotWidth + 1,
  1
  );
  }
  }
  });
  })();
 
  (function() {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  function getImage (type, canvas, width, height) {
 
  // TODO add scaling for w / h
  var
  mime = 'image/'+type,
  data = canvas.toDataURL(mime),
  image = new Image();
  image.src = data;
  return image;
  }
 
  Flotr.addPlugin('download', {
 
  saveImage: function (type, width, height, replaceCanvas) {
  var image = null;
  if (Flotr.isIE && Flotr.isIE < 9) {
  image = '<html><body>'+this.canvas.firstChild.innerHTML+'</body></html>';
  return window.open().document.write(image);
  }
 
  if (type !== 'jpeg' && type !== 'png') return;
 
  image = getImage(type, this.canvas, width, height);
 
  if (_.isElement(image) && replaceCanvas) {
  this.download.restoreCanvas();
  D.hide(this.canvas);
  D.hide(this.overlay);
  D.setStyles({position: 'absolute'});
  D.insert(this.el, image);
  this.saveImageElement = image;
  } else {
  return window.open(image.src);
  }
  },
 
  restoreCanvas: function() {
  D.show(this.canvas);
  D.show(this.overlay);
  if (this.saveImageElement) this.el.removeChild(this.saveImageElement);
  this.saveImageElement = null;
  }
  });
 
  })();
 
  (function () {
 
  var E = Flotr.EventAdapter,
  _ = Flotr._;
 
  Flotr.addPlugin('graphGrid', {
 
  callbacks: {
  'flotr:beforedraw' : function () {
  this.graphGrid.drawGrid();
  },
  'flotr:afterdraw' : function () {
  this.graphGrid.drawOutline();
  }
  },
 
  drawGrid: function(){
 
  var
  ctx = this.ctx,
  options = this.options,
  grid = options.grid,
  verticalLines = grid.verticalLines,
  horizontalLines = grid.horizontalLines,
  minorVerticalLines = grid.minorVerticalLines,
  minorHorizontalLines = grid.minorHorizontalLines,
  plotHeight = this.plotHeight,
  plotWidth = this.plotWidth,
  a, v, i, j;
 
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:beforegrid', [this.axes.x, this.axes.y, options, this]);
  }
  ctx.save();
  ctx.lineWidth = 1;
  ctx.strokeStyle = grid.tickColor;
 
  function circularHorizontalTicks (ticks) {
  for(i = 0; i < ticks.length; ++i){
  var ratio = ticks[i].v / a.max;
  for(j = 0; j <= sides; ++j){
  ctx[j === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(j*coeff+angle)*radius*ratio,
  Math.sin(j*coeff+angle)*radius*ratio
  );
  }
  }
  }
  function drawGridLines (ticks, callback) {
  _.each(_.pluck(ticks, 'v'), function(v){
  // Don't show lines on upper and lower bounds.
  if ((v <= a.min || v >= a.max) ||
  (v == a.min || v == a.max) && grid.outlineWidth)
  return;
  callback(Math.floor(a.d2p(v)) + ctx.lineWidth/2);
  });
  }
  function drawVerticalLines (x) {
  ctx.moveTo(x, 0);
  ctx.lineTo(x, plotHeight);
  }
  function drawHorizontalLines (y) {
  ctx.moveTo(0, y);
  ctx.lineTo(plotWidth, y);
  }
 
  if (grid.circular) {
  ctx.translate(this.plotOffset.left+plotWidth/2, this.plotOffset.top+plotHeight/2);
  var radius = Math.min(plotHeight, plotWidth)*options.radar.radiusRatio/2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw grid lines in vertical direction.
  ctx.beginPath();
 
  a = this.axes.y;
 
  if(horizontalLines){
  circularHorizontalTicks(a.ticks);
  }
  if(minorHorizontalLines){
  circularHorizontalTicks(a.minorTicks);
  }
 
  if(verticalLines){
  _.times(sides, function(i){
  ctx.moveTo(0, 0);
  ctx.lineTo(Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  });
  }
  ctx.stroke();
  }
  else {
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
 
  // Draw grid background, if present in options.
  if(grid.backgroundColor){
  ctx.fillStyle = this.processColor(grid.backgroundColor, {x1: 0, y1: 0, x2: plotWidth, y2: plotHeight});
  ctx.fillRect(0, 0, plotWidth, plotHeight);
  }
 
  ctx.beginPath();
 
  a = this.axes.x;
  if (verticalLines) drawGridLines(a.ticks, drawVerticalLines);
  if (minorVerticalLines) drawGridLines(a.minorTicks, drawVerticalLines);
 
  a = this.axes.y;
  if (horizontalLines) drawGridLines(a.ticks, drawHorizontalLines);
  if (minorHorizontalLines) drawGridLines(a.minorTicks, drawHorizontalLines);
 
  ctx.stroke();
  }
 
  ctx.restore();
  if(verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines){
  E.fire(this.el, 'flotr:aftergrid', [this.axes.x, this.axes.y, options, this]);
  }
  },
 
  drawOutline: function(){
  var
  that = this,
  options = that.options,
  grid = options.grid,
  outline = grid.outline,
  ctx = that.ctx,
  backgroundImage = grid.backgroundImage,
  plotOffset = that.plotOffset,
  leftOffset = plotOffset.left,
  topOffset = plotOffset.top,
  plotWidth = that.plotWidth,
  plotHeight = that.plotHeight,
  v, img, src, left, top, globalAlpha;
 
  if (!grid.outlineWidth) return;
 
  ctx.save();
 
  if (grid.circular) {
  ctx.translate(leftOffset + plotWidth / 2, topOffset + plotHeight / 2);
  var radius = Math.min(plotHeight, plotWidth) * options.radar.radiusRatio / 2,
  sides = this.axes.x.ticks.length,
  coeff = 2*(Math.PI/sides),
  angle = -Math.PI/2;
 
  // Draw axis/grid border.
  ctx.beginPath();
  ctx.lineWidth = grid.outlineWidth;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'round';
 
  for(i = 0; i <= sides; ++i){
  ctx[i === 0 ? 'moveTo' : 'lineTo'](Math.cos(i*coeff+angle)*radius, Math.sin(i*coeff+angle)*radius);
  }
  //ctx.arc(0, 0, radius, 0, Math.PI*2, true);
 
  ctx.stroke();
  }
  else {
  ctx.translate(leftOffset, topOffset);
 
  // Draw axis/grid border.
  var lw = grid.outlineWidth,
  orig = 0.5-lw+((lw+1)%2/2),
  lineTo = 'lineTo',
  moveTo = 'moveTo';
  ctx.lineWidth = lw;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'miter';
  ctx.beginPath();
  ctx.moveTo(orig, orig);
  plotWidth = plotWidth - (lw / 2) % 1;
  plotHeight = plotHeight + lw / 2;
  ctx[outline.indexOf('n') !== -1 ? lineTo : moveTo](plotWidth, orig);
  ctx[outline.indexOf('e') !== -1 ? lineTo : moveTo](plotWidth, plotHeight);
  ctx[outline.indexOf('s') !== -1 ? lineTo : moveTo](orig, plotHeight);
  ctx[outline.indexOf('w') !== -1 ? lineTo : moveTo](orig, orig);
  ctx.stroke();
  ctx.closePath();
  }
 
  ctx.restore();
 
  if (backgroundImage) {
 
  src = backgroundImage.src || backgroundImage;
  left = (parseInt(backgroundImage.left, 10) || 0) + plotOffset.left;
  top = (parseInt(backgroundImage.top, 10) || 0) + plotOffset.top;
  img = new Image();
 
  img.onload = function() {
  ctx.save();
  if (backgroundImage.alpha) ctx.globalAlpha = backgroundImage.alpha;
  ctx.globalCompositeOperation = 'destination-over';
  ctx.drawImage(img, 0, 0, img.width, img.height, left, top, plotWidth, plotHeight);
  ctx.restore();
  };
 
  img.src = src;
  }
  }
  });
 
  })();
 
  /**
  * Selection Handles Plugin
  *
  * Depends upon options.selection.mode
  *
  * Options
  * show - True enables the handles plugin.
  * drag - Left and Right drag handles
  * scroll - Scrolling handle
  */
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('handles', {
 
  options: {
  show: false,
  drag: true,
  scroll: true
  },
 
  callbacks: {
  'flotr:afterinit': init,
  'flotr:select': handleSelect,
  'flotr:mousedown': reset,
  'flotr:mousemove': mouseMoveHandler
  }
 
  });
 
 
  function init() {
 
  var
  options = this.options,
  handles = this.handles,
  el = this.el,
  scroll, left, right, container;
 
  if (!options.selection.mode || !options.handles.show || 'ontouchstart' in el) return;
 
  handles.initialized = true;
 
  container = D.node('<div class="flotr-handles"></div>');
  options = options.handles;
 
  // Drag handles
  if (options.drag) {
  right = D.node('<div class="flotr-handles-handle flotr-handles-drag flotr-handles-right"></div>');
  left = D.node('<div class="flotr-handles-handle flotr-handles-drag flotr-handles-left"></div>');
  D.insert(container, right);
  D.insert(container, left);
  D.hide(left);
  D.hide(right);
  handles.left = left;
  handles.right = right;
 
  this.observe(left, 'mousedown', function () {
  handles.moveHandler = leftMoveHandler;
  });
  this.observe(right, 'mousedown', function () {
  handles.moveHandler = rightMoveHandler;
  });
  }
 
  // Scroll handle
  if (options.scroll) {
  scroll = D.node('<div class="flotr-handles-handle flotr-handles-scroll"></div>');
  D.insert(container, scroll);
  D.hide(scroll);
  handles.scroll = scroll;
  this.observe(scroll, 'mousedown', function () {
  handles.moveHandler = scrollMoveHandler;
  });
  }
 
  this.observe(document, 'mouseup', function() {
  handles.moveHandler = null;
  });
 
  D.insert(el, container);
  }
 
 
  function handleSelect(selection) {
 
  if (!this.handles.initialized) return;
 
  var
  handles = this.handles,
  options = this.options.handles,
  left = handles.left,
  right = handles.right,
  scroll = handles.scroll;
 
  if (options) {
  if (options.drag) {
  positionDrag(this, left, selection.x1);
  positionDrag(this, right, selection.x2);
  }
 
  if (options.scroll) {
  positionScroll(
  this,
  scroll,
  selection.x1,
  selection.x2
  );
  }
  }
  }
 
  function positionDrag(graph, handle, x) {
 
  D.show(handle);
 
  var size = D.size(handle),
  l = Math.round(graph.axes.x.d2p(x) - size.width / 2),
  t = (graph.plotHeight - size.height) / 2;
 
  D.setStyles(handle, {
  'left' : l+'px',
  'top' : t+'px'
  });
  }
 
  function positionScroll(graph, handle, x1, x2) {
 
  D.show(handle);
 
  var size = D.size(handle),
  l = Math.round(graph.axes.x.d2p(x1)),
  t = (graph.plotHeight) - size.height / 2,
  w = (graph.axes.x.d2p(x2) - graph.axes.x.d2p(x1));
 
  D.setStyles(handle, {
  'left' : l+'px',
  'top' : t+'px',
  'width': w+'px'
  });
  }
 
  function reset() {
 
  if (!this.handles.initialized) return;
 
  var
  handles = this.handles;
  if (handles) {
  D.hide(handles.left);
  D.hide(handles.right);
  D.hide(handles.scroll);
  }
  }
 
  function mouseMoveHandler(e, position) {
 
  if (!this.handles.initialized) return;
  if (!this.handles.moveHandler) return;
 
  var
  delta = position.x - this.lastMousePos.x,
  selection = this.selection.selection,
  area = this.selection.getArea(),
  handles = this.handles;
 
  handles.moveHandler(area, delta);
  checkSwap(area, handles);
 
  this.selection.setSelection(area);
  }
 
  function checkSwap (area, handles) {
  var moveHandler = handles.moveHandler;
  if (area.x1 > area.x2) {
  if (moveHandler == leftMoveHandler) {
  moveHandler = rightMoveHandler;
  } else if (moveHandler == rightMoveHandler) {
  moveHandler = leftMoveHandler;
  }
  handles.moveHandler = moveHandler;
  }
  }
 
  function leftMoveHandler(area, delta) {
  area.x1 += delta;
  }
 
  function rightMoveHandler(area, delta) {
  area.x2 += delta;
  }
 
  function scrollMoveHandler(area, delta) {
  area.x1 += delta;
  area.x2 += delta;
  }
 
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._,
  flotr = Flotr,
  S_MOUSETRACK = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;';
 
  Flotr.addPlugin('hit', {
  callbacks: {
  'flotr:mousemove': function(e, pos) {
  this.hit.track(pos);
  },
  'flotr:click': function(pos) {
  var
  hit = this.hit.track(pos);
  _.defaults(pos, hit);
  },
  'flotr:mouseout': function() {
  this.hit.clearHit();
  },
  'flotr:destroy': function() {
  this.mouseTrack = null;
  }
  },
  track : function (pos) {
  if (this.options.mouse.track || _.any(this.series, function(s){return s.mouse && s.mouse.track;})) {
  return this.hit.hit(pos);
  }
  },
  /**
  * Try a method on a graph type. If the method exists, execute it.
  * @param {Object} series
  * @param {String} method Method name.
  * @param {Array} args Arguments applied to method.
  * @return executed successfully or failed.
  */
  executeOnType: function(s, method, args){
  var
  success = false,
  options;
 
  if (!_.isArray(s)) s = [s];
 
  function e(s, index) {
  _.each(_.keys(flotr.graphTypes), function (type) {
  if (s[type] && s[type].show && this[type][method]) {
  options = this.getOptions(s, type);
 
  options.fill = !!s.mouse.fillColor;
  options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  options.color = s.mouse.lineColor;
  options.context = this.octx;
  options.index = index;
 
  if (args) options.args = args;
  this[type][method].call(this[type], options);
  success = true;
  }
  }, this);
  }
  _.each(s, e, this);
 
  return success;
  },
  /**
  * Updates the mouse tracking point on the overlay.
  */
  drawHit: function(n){
  var octx = this.octx,
  s = n.series;
 
  if (s.mouse.lineColor) {
  octx.save();
  octx.lineWidth = (s.points ? s.points.lineWidth : 1);
  octx.strokeStyle = s.mouse.lineColor;
  octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  octx.translate(this.plotOffset.left, this.plotOffset.top);
 
  if (!this.hit.executeOnType(s, 'drawHit', n)) {
  var
  xa = n.xaxis,
  ya = n.yaxis;
 
  octx.beginPath();
  // TODO fix this (points) should move to general testable graph mixin
  octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.hitRadius || s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
  octx.fill();
  octx.stroke();
  octx.closePath();
  }
  octx.restore();
  this.clip(octx);
  }
  this.prevHit = n;
  },
  /**
  * Removes the mouse tracking point from the overlay.
  */
  clearHit: function(){
  var prev = this.prevHit,
  octx = this.octx,
  plotOffset = this.plotOffset;
  octx.save();
  octx.translate(plotOffset.left, plotOffset.top);
  if (prev) {
  if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
  // TODO fix this (points) should move to general testable graph mixin
  var
  s = prev.series,
  lw = (s.points ? s.points.lineWidth : 1);
  offset = (s.points.hitRadius || s.points.radius || s.mouse.radius) + lw;
  octx.clearRect(
  prev.xaxis.d2p(prev.x) - offset,
  prev.yaxis.d2p(prev.y) - offset,
  offset*2,
  offset*2
  );
  }
  D.hide(this.mouseTrack);
  this.prevHit = null;
  }
  octx.restore();
  },
  /**
  * Retrieves the nearest data point from the mouse cursor. If it's within
  * a certain range, draw a point on the overlay canvas and display the x and y
  * value of the data.
  * @param {Object} mouse - Object that holds the relative x and y coordinates of the cursor.
  */
  hit : function (mouse) {
 
  var
  options = this.options,
  prevHit = this.prevHit,
  closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n;
 
  if (this.series.length === 0) return;
 
  // Nearest data element.
  // dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
  // xaxis, yaxis, series, index, seriesIndex
  n = {
  relX : mouse.relX,
  relY : mouse.relY,
  absX : mouse.absX,
  absY : mouse.absY
  };
 
  if (options.mouse.trackY &&
  !options.mouse.trackAll &&
  this.hit.executeOnType(this.series, 'hit', [mouse, n]) &&
  !_.isUndefined(n.seriesIndex))
  {
  series = this.series[n.seriesIndex];
  n.series = series;
  n.mouse = series.mouse;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  } else {
 
  closest = this.hit.closest(mouse);
 
  if (closest) {
 
  closest = options.mouse.trackY ? closest.point : closest.x;
  seriesIndex = closest.seriesIndex;
  series = this.series[seriesIndex];
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  sensibility = 2 * series.mouse.sensibility;
 
  if
  (options.mouse.trackAll ||
  (closest.distanceX < sensibility / xaxis.scale &&
  (!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale)))
  {
  n.series = series;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  n.mouse = series.mouse;
  n.x = closest.x;
  n.y = closest.y;
  n.dist = closest.distance;
  n.index = closest.dataIndex;
  n.seriesIndex = seriesIndex;
  }
  }
  }
 
  if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
  this.hit.clearHit();
  if (n.series && n.mouse && n.mouse.track) {
  this.hit.drawMouseTrack(n);
  this.hit.drawHit(n);
  Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
  }
  }
 
  return n;
  },
 
  closest : function (mouse) {
 
  var
  series = this.series,
  options = this.options,
  relX = mouse.relX,
  relY = mouse.relY,
  compare = Number.MAX_VALUE,
  compareX = Number.MAX_VALUE,
  closest = {},
  closestX = {},
  check = false,
  serie, data,
  distance, distanceX, distanceY,
  mouseX, mouseY,
  x, y, i, j;
 
  function setClosest (o) {
  o.distance = distance;
  o.distanceX = distanceX;
  o.distanceY = distanceY;
  o.seriesIndex = i;
  o.dataIndex = j;
  o.x = x;
  o.y = y;
  check = true;
  }
 
  for (i = 0; i < series.length; i++) {
 
  serie = series[i];
  data = serie.data;
  mouseX = serie.xaxis.p2d(relX);
  mouseY = serie.yaxis.p2d(relY);
 
  for (j = data.length; j--;) {
 
  x = data[j][0];
  y = data[j][1];
 
  if (x === null || y === null) continue;
 
  // don't check if the point isn't visible in the current range
  if (x < serie.xaxis.min || x > serie.xaxis.max) continue;
 
  distanceX = Math.abs(x - mouseX);
  distanceY = Math.abs(y - mouseY);
 
  // Skip square root for speed
  distance = distanceX * distanceX + distanceY * distanceY;
 
  if (distance < compare) {
  compare = distance;
  setClosest(closest);
  }
 
  if (distanceX < compareX) {
  compareX = distanceX;
  setClosest(closestX);
  }
  }
  }
 
  return check ? {
  point : closest,
  x : closestX
  } : false;
  },
 
  drawMouseTrack : function (n) {
 
  var
  pos = '',
  s = n.series,
  p = n.mouse.position,
  m = n.mouse.margin,
  x = n.x,
  y = n.y,
  elStyle = S_MOUSETRACK,
  mouseTrack = this.mouseTrack,
  plotOffset = this.plotOffset,
  left = plotOffset.left,
  right = plotOffset.right,
  bottom = plotOffset.bottom,
  top = plotOffset.top,
  decimals = n.mouse.trackDecimals,
  options = this.options;
 
  // Create
  if (!mouseTrack) {
  mouseTrack = D.node('<div class="flotr-mouse-value"></div>');
  this.mouseTrack = mouseTrack;
  D.insert(this.el, mouseTrack);
  }
 
  if (!n.mouse.relative) { // absolute to the canvas
 
  if (p.charAt(0) == 'n') pos += 'top:' + (m + top) + 'px;bottom:auto;';
  else if (p.charAt(0) == 's') pos += 'bottom:' + (m + bottom) + 'px;top:auto;';
  if (p.charAt(1) == 'e') pos += 'right:' + (m + right) + 'px;left:auto;';
  else if (p.charAt(1) == 'w') pos += 'left:' + (m + left) + 'px;right:auto;';
 
  // Pie
  } else if (s.pie && s.pie.show) {
  var center = {
  x: (this.plotWidth)/2,
  y: (this.plotHeight)/2
  },
  radius = (Math.min(this.canvasWidth, this.canvasHeight) * s.pie.sizeRatio) / 2,
  bisection = n.sAngle<n.eAngle ? (n.sAngle + n.eAngle) / 2: (n.sAngle + n.eAngle + 2* Math.PI) / 2;
 
  pos += 'bottom:' + (m - top - center.y - Math.sin(bisection) * radius/2 + this.canvasHeight) + 'px;top:auto;';
  pos += 'left:' + (m + left + center.x + Math.cos(bisection) * radius/2) + 'px;right:auto;';
 
  // Default
  } else {
  if (/n/.test(p)) pos += 'bottom:' + (m - top - n.yaxis.d2p(n.y) + this.canvasHeight) + 'px;top:auto;';
  else pos += 'top:' + (m + top + n.yaxis.d2p(n.y)) + 'px;bottom:auto;';
  if (/w/.test(p)) pos += 'right:' + (m - left - n.xaxis.d2p(n.x) + this.canvasWidth) + 'px;left:auto;';
  else pos += 'left:' + (m + left + n.xaxis.d2p(n.x)) + 'px;right:auto;';
  }
 
  elStyle += pos;
  mouseTrack.style.cssText = elStyle;
  if (!decimals || decimals < 0) decimals = 0;
 
  if (x && x.toFixed) x = x.toFixed(decimals);
 
  if (y && y.toFixed) y = y.toFixed(decimals);
 
  mouseTrack.innerHTML = n.mouse.trackFormatter({
  x: x ,
  y: y,
  series: n.series,
  index: n.index,
  nearest: n,
  fraction: n.fraction
  });
 
  D.show(mouseTrack);
 
  if (n.mouse.relative) {
  if (!/[ew]/.test(p)) {
  // Center Horizontally
  mouseTrack.style.left =
  (left + n.xaxis.d2p(n.x) - D.size(mouseTrack).width / 2) + 'px';
  } else
  if (!/[ns]/.test(p)) {
  // Center Vertically
  mouseTrack.style.top =
  (top + n.yaxis.d2p(n.y) - D.size(mouseTrack).height / 2) + 'px';
  }
  }
  }
 
  });
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('labels', {
 
  callbacks : {
  'flotr:afterdraw' : function () {
  this.labels.draw();
  }
  },
 
  draw: function(){
  // Construct fixed width label boxes, which can be styled easily.
  var
  axis, tick, left, top, xBoxWidth,
  radius, sides, coeff, angle,
  div, i, html = '',
  noLabels = 0,
  options = this.options,
  ctx = this.ctx,
  a = this.axes,
  style = { size: options.fontSize };
 
  for (i = 0; i < a.x.ticks.length; ++i){
  if (a.x.ticks[i].label) { ++noLabels; }
  }
  xBoxWidth = this.plotWidth / noLabels;
 
  if (options.grid.circular) {
  ctx.save();
  ctx.translate(this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top + this.plotHeight / 2);
 
  radius = this.plotHeight * options.radar.radiusRatio / 2 + options.fontSize;
  sides = this.axes.x.ticks.length;
  coeff = 2 * (Math.PI / sides);
  angle = -Math.PI / 2;
 
  drawLabelCircular(this, a.x, false);
  drawLabelCircular(this, a.x, true);
  drawLabelCircular(this, a.y, false);
  drawLabelCircular(this, a.y, true);
  ctx.restore();
  }
 
  if (!options.HtmlText && this.textEnabled) {
  drawLabelNoHtmlText(this, a.x, 'center', 'top');
  drawLabelNoHtmlText(this, a.x2, 'center', 'bottom');
  drawLabelNoHtmlText(this, a.y, 'right', 'middle');
  drawLabelNoHtmlText(this, a.y2, 'left', 'middle');
 
  } else if ((
  a.x.options.showLabels ||
  a.x2.options.showLabels ||
  a.y.options.showLabels ||
  a.y2.options.showLabels) &&
  !options.grid.circular
  ) {
 
  html = '';
 
  drawLabelHtml(this, a.x);
  drawLabelHtml(this, a.x2);
  drawLabelHtml(this, a.y);
  drawLabelHtml(this, a.y2);
 
  ctx.stroke();
  ctx.restore();
  div = D.create('div');
  D.setStyles(div, {
  fontSize: 'smaller',
  color: options.grid.color
  });
  div.className = 'flotr-labels';
  D.insert(this.el, div);
  D.insert(div, html);
  }
 
  function drawLabelCircular (graph, axis, minorTicks) {
  var
  ticks = minorTicks ? axis.minorTicks : axis.ticks,
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  angle : Flotr.toRad(axis.options.labelsAngle),
  textBaseline : 'middle'
  };
 
  for (i = 0; i < ticks.length &&
  (minorTicks ? axis.options.showMinorLabels : axis.options.showLabels); ++i){
  tick = ticks[i];
  tick.label += '';
  if (!tick.label || !tick.label.length) { continue; }
 
  x = Math.cos(i * coeff + angle) * radius;
  y = Math.sin(i * coeff + angle) * radius;
 
  style.textAlign = isX ? (Math.abs(x) < 0.1 ? 'center' : (x < 0 ? 'right' : 'left')) : 'left';
 
  Flotr.drawText(
  ctx, tick.label,
  isX ? x : 3,
  isX ? y : -(axis.ticks[i].v / axis.max) * (radius - options.fontSize),
  style
  );
  }
  }
 
  function drawLabelNoHtmlText (graph, axis, textAlign, textBaseline) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color : axis.options.color || options.grid.color,
  textAlign : textAlign,
  textBaseline : textBaseline,
  angle : Flotr.toRad(axis.options.labelsAngle)
  };
  style = Flotr.getBestTextAlign(style.angle, style);
 
  for (i = 0; i < axis.ticks.length && continueShowingLabels(axis); ++i) {
 
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length) { continue; }
 
  offset = axis.d2p(tick.v);
  if (offset < 0 ||
  offset > (isX ? graph.plotWidth : graph.plotHeight)) { continue; }
 
  Flotr.drawText(
  ctx, tick.label,
  leftOffset(graph, isX, isFirst, offset),
  topOffset(graph, isX, isFirst, offset),
  style
  );
 
  // Only draw on axis y2
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = style.color;
  ctx.beginPath();
  ctx.moveTo(graph.plotOffset.left + graph.plotWidth - 8, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.lineTo(graph.plotOffset.left + graph.plotWidth, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.stroke();
  ctx.restore();
  }
  }
 
  function continueShowingLabels (axis) {
  return axis.options.showLabels && axis.used;
  }
  function leftOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.left +
  (isX ? offset :
  (isFirst ?
  -options.grid.labelMargin :
  options.grid.labelMargin + graph.plotWidth));
  }
  function topOffset (graph, isX, isFirst, offset) {
  return graph.plotOffset.top +
  (isX ? options.grid.labelMargin : offset) +
  ((isX && isFirst) ? graph.plotHeight : 0);
  }
  }
 
  function drawLabelHtml (graph, axis) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  name = '',
  left, style, top,
  offset = graph.plotOffset;
 
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = axis.options.color || options.grid.color;
  ctx.beginPath();
  }
 
  if (axis.options.showLabels && (isFirst ? true : axis.used)) {
  for (i = 0; i < axis.ticks.length; ++i) {
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) < 0) ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) > (isX ? graph.canvasWidth : graph.canvasHeight))) {
  continue;
  }
  top = offset.top +
  (isX ?
  ((isFirst ? 1 : -1 ) * (graph.plotHeight + options.grid.labelMargin)) :
  axis.d2p(tick.v) - axis.maxLabel.height / 2);
  left = isX ? (offset.left + axis.d2p(tick.v) - xBoxWidth / 2) : 0;
 
  name = '';
  if (i === 0) {
  name = ' first';
  } else if (i === axis.ticks.length - 1) {
  name = ' last';
  }
  name += isX ? ' flotr-grid-label-x' : ' flotr-grid-label-y';
 
  html += [
  '<div style="position:absolute; text-align:' + (isX ? 'center' : 'right') + '; ',
  'top:' + top + 'px; ',
  ((!isX && !isFirst) ? 'right:' : 'left:') + left + 'px; ',
  'width:' + (isX ? xBoxWidth : ((isFirst ? offset.left : offset.right) - options.grid.labelMargin)) + 'px; ',
  axis.options.color ? ('color:' + axis.options.color + '; ') : ' ',
  '" class="flotr-grid-label' + name + '">' + tick.label + '</div>'
  ].join(' ');
 
  if (!isX && !isFirst) {
  ctx.moveTo(offset.left + graph.plotWidth - 8, offset.top + axis.d2p(tick.v));
  ctx.lineTo(offset.left + graph.plotWidth, offset.top + axis.d2p(tick.v));
  }
  }
  }
  }
  }
 
  });
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('legend', {
  options: {
  show: true, // => setting to true will show the legend, hide otherwise
  noColumns: 1, // => number of colums in legend table // @todo: doesn't work for HtmlText = false
  labelFormatter: function(v){return v;}, // => fn: string -> string
  labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
  labelBoxWidth: 14,
  labelBoxHeight: 10,
  labelBoxMargin: 5,
  container: null, // => container (as jQuery object) to put legend in, null means default on top of graph
  position: 'nw', // => position of default legend container within plot
  margin: 5, // => distance from grid edge to default legend container within plot
  backgroundColor: '#F0F0F0', // => Legend background color.
  backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
  'flotr:afterinit': function() {
  this.legend.insertLegend();
  },
  'flotr:destroy': function() {
  var markup = this.legend.markup;
  if (markup) {
  this.legend.markup = null;
  D.remove(markup);
  }
  }
  },
  /**
  * Adds a legend div to the canvas container or draws it on the canvas.
  */
  insertLegend: function(){
 
  if(!this.options.legend.show)
  return;
 
  var series = this.series,
  plotOffset = this.plotOffset,
  options = this.options,
  legend = options.legend,
  fragments = [],
  rowStarted = false,
  ctx = this.ctx,
  itemCount = _.filter(series, function(s) {return (s.label && !s.hide);}).length,
  p = legend.position,
  m = legend.margin,
  opacity = legend.backgroundOpacity,
  i, label, color;
 
  if (itemCount) {
 
  var lbw = legend.labelBoxWidth,
  lbh = legend.labelBoxHeight,
  lbm = legend.labelBoxMargin,
  offsetX = plotOffset.left + m,
  offsetY = plotOffset.top + m,
  labelMaxWidth = 0,
  style = {
  size: options.fontSize*1.1,
  color: options.grid.color
  };
 
  // We calculate the labels' max width
  for(i = series.length - 1; i > -1; --i){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
  labelMaxWidth = Math.max(labelMaxWidth, this._text.measureText(label, style).width);
  }
 
  var legendWidth = Math.round(lbw + lbm*3 + labelMaxWidth),
  legendHeight = Math.round(itemCount*(lbm+lbh) + lbm);
 
  // Default Opacity
  if (!opacity && opacity !== 0) {
  opacity = 0.1;
  }
 
  if (!options.HtmlText && this.textEnabled && !legend.container) {
 
  if(p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
  if(p.charAt(0) == 'c') offsetY = plotOffset.top + (this.plotHeight/2) - (m + (legendHeight/2));
  if(p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);
 
  // Legend box
  color = this.processColor(legend.backgroundColor, { opacity : opacity });
 
  ctx.fillStyle = color;
  ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);
 
  // Legend labels
  var x = offsetX + lbm;
  var y = offsetY + lbm;
  for(i = 0; i < series.length; i++){
  if(!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
 
  ctx.fillStyle = series[i].color;
  ctx.fillRect(x, y, lbw-1, lbh-1);
 
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.lineWidth = 1;
  ctx.strokeRect(Math.ceil(x)-1.5, Math.ceil(y)-1.5, lbw+2, lbh+2);
 
  // Legend text
  Flotr.drawText(ctx, label, x + lbw + lbm, y + lbh, style);
 
  y += lbh + lbm;
  }
  }
  else {
  for(i = 0; i < series.length; ++i){
  if(!series[i].label || series[i].hide) continue;
 
  if(i % legend.noColumns === 0){
  fragments.push(rowStarted ? '</tr><tr>' : '<tr>');
  rowStarted = true;
  }
 
  var s = series[i],
  boxWidth = legend.labelBoxWidth,
  boxHeight = legend.labelBoxHeight;
 
  label = legend.labelFormatter(s.label);
  color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';
 
  fragments.push(
  '<td class="flotr-legend-color-box">',
  '<div style="border:1px solid ', legend.labelBoxBorderColor, ';padding:1px">',
  '<div style="width:', (boxWidth-1), 'px;height:', (boxHeight-1), 'px;border:1px solid ', series[i].color, '">', // Border
  '<div style="width:', boxWidth, 'px;height:', boxHeight, 'px;', color, '"></div>', // Background
  '</div>',
  '</div>',
  '</td>',
  '<td class="flotr-legend-label">', label, '</td>'
  );
  }
  if(rowStarted) fragments.push('</tr>');
 
  if(fragments.length > 0){
  var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join('') + '</table>';
  if(legend.container){
  table = D.node(table);
  this.legend.markup = table;
  D.insert(legend.container, table);
  }
  else {
  var styles = {position: 'absolute', 'zIndex': '2', 'border' : '1px solid ' + legend.labelBoxBorderColor};
 
  if(p.charAt(0) == 'n') { styles.top = (m + plotOffset.top) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 'c') { styles.top = (m + (this.plotHeight - legendHeight) / 2) + 'px'; styles.bottom = 'auto'; }
  else if(p.charAt(0) == 's') { styles.bottom = (m + plotOffset.bottom) + 'px'; styles.top = 'auto'; }
  if(p.charAt(1) == 'e') { styles.right = (m + plotOffset.right) + 'px'; styles.left = 'auto'; }
  else if(p.charAt(1) == 'w') { styles.left = (m + plotOffset.left) + 'px'; styles.right = 'auto'; }
 
  var div = D.create('div'), size;
  div.className = 'flotr-legend';
  D.setStyles(div, styles);
  D.insert(div, table);
  D.insert(this.el, div);
 
  if (!opacity) return;
 
  var c = legend.backgroundColor || options.grid.backgroundColor || '#ffffff';
 
  _.extend(styles, D.size(div), {
  'backgroundColor': c,
  'zIndex' : '',
  'border' : ''
  });
  styles.width += 'px';
  styles.height += 'px';
 
  // Put in the transparent background separately to avoid blended labels and
  div = D.create('div');
  div.className = 'flotr-legend-bg';
  D.setStyles(div, styles);
  D.opacity(div, opacity);
  D.insert(div, ' ');
  D.insert(this.el, div);
  }
  }
  }
  }
  }
  });
  })();
 
  /**
  * Selection Handles Plugin
  *
  *
  * Options
  * show - True enables the handles plugin.
  * drag - Left and Right drag handles
  * scroll - Scrolling handle
  */
  (function () {
 
  function isLeftClick (e, type) {
  return (e.which ? (e.which === 1) : (e.button === 0 || e.button === 1));
  }
 
  function boundX(x, graph) {
  return Math.min(Math.max(0, x), graph.plotWidth - 1);
  }
 
  function boundY(y, graph) {
  return Math.min(Math.max(0, y), graph.plotHeight);
  }
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._;
 
 
  Flotr.addPlugin('selection', {
 
  options: {
  pinchOnly: null, // Only select on pinch
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#B6D9FF', // => selection box color
  fps: 20 // => frames-per-second
  },
 
  callbacks: {
  'flotr:mouseup' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (selection.interval) clearInterval(selection.interval);
 
  if (this.multitouches) {
  selection.updateSelection();
  } else
  if (!options.pinchOnly) {
  selection.setSelectionPos(selection.selection.second, pointer);
  }
  selection.clearSelection();
 
  if(selection.selecting && selection.selectionIsSane()){
  selection.drawSelection();
  selection.fireSelectEvent();
  this.ignoreClick = true;
  }
  },
  'flotr:mousedown' : function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (!options.mode || (!isLeftClick(event) && _.isUndefined(event.touches))) return;
  if (!options.pinchOnly) selection.setSelectionPos(selection.selection.first, pointer);
  if (selection.interval) clearInterval(selection.interval);
 
  this.lastMousePos.pageX = null;
  selection.selecting = false;
  selection.interval = setInterval(
  _.bind(selection.updateSelection, this),
  1000 / options.fps
  );
  },
  'flotr:destroy' : function (event) {
  clearInterval(this.selection.interval);
  }
  },
 
  // TODO This isn't used. Maybe it belongs in the draw area and fire select event methods?
  getArea: function() {
 
  var
  s = this.selection.selection,
  a = this.axes,
  first = s.first,
  second = s.second,
  x1, x2, y1, y2;
 
  x1 = a.x.p2d(s.first.x);
  x2 = a.x.p2d(s.second.x);
  y1 = a.y.p2d(s.first.y);
  y2 = a.y.p2d(s.second.y);
 
  return {
  x1 : Math.min(x1, x2),
  y1 : Math.min(y1, y2),
  x2 : Math.max(x1, x2),
  y2 : Math.max(y1, y2),
  xfirst : x1,
  xsecond : x2,
  yfirst : y1,
  ysecond : y2
  };
  },
 
  selection: {first: {x: -1, y: -1}, second: {x: -1, y: -1}},
  prevSelection: null,
  interval: null,
 
  /**
  * Fires the 'flotr:select' event when the user made a selection.
  */
  fireSelectEvent: function(name){
  var
  area = this.selection.getArea();
  name = name || 'select';
  area.selection = this.selection.selection;
  E.fire(this.el, 'flotr:'+name, [area, this]);
  },
 
  /**
  * Allows the user the manually select an area.
  * @param {Object} area - Object with coordinates to select.
  */
  setSelection: function(area, preventEvent){
  var options = this.options,
  xa = this.axes.x,
  ya = this.axes.y,
  vertScale = ya.scale,
  hozScale = xa.scale,
  selX = options.selection.mode.indexOf('x') != -1,
  selY = options.selection.mode.indexOf('y') != -1,
  s = this.selection.selection;
 
  this.selection.clearSelection();
 
  s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
  s.second.y = boundY((selX && !selY) ? this.plotHeight - 1: (ya.max - area.y2) * vertScale, this);
  s.first.x = boundX((selY && !selX) ? 0 : (area.x1 - xa.min) * hozScale, this);
  s.second.x = boundX((selY && !selX) ? this.plotWidth : (area.x2 - xa.min) * hozScale, this);
 
  this.selection.drawSelection();
  if (!preventEvent)
  this.selection.fireSelectEvent();
  },
 
  /**
  * Calculates the position of the selection.
  * @param {Object} pos - Position object.
  * @param {Event} event - Event object.
  */
  setSelectionPos: function(pos, pointer) {
  var mode = this.options.selection.mode,
  selection = this.selection.selection;
 
  if(mode.indexOf('x') == -1) {
  pos.x = (pos == selection.first) ? 0 : this.plotWidth;
  }else{
  pos.x = boundX(pointer.relX, this);
  }
 
  if (mode.indexOf('y') == -1) {
  pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
  }else{
  pos.y = boundY(pointer.relY, this);
  }
  },
  /**
  * Draws the selection box.
  */
  drawSelection: function() {
 
  this.selection.fireSelectEvent('selecting');
 
  var s = this.selection.selection,
  octx = this.octx,
  options = this.options,
  plotOffset = this.plotOffset,
  prevSelection = this.selection.prevSelection;
 
  if (prevSelection &&
  s.first.x == prevSelection.first.x &&
  s.first.y == prevSelection.first.y &&
  s.second.x == prevSelection.second.x &&
  s.second.y == prevSelection.second.y) {
  return;
  }
 
  octx.save();
  octx.strokeStyle = this.processColor(options.selection.color, {opacity: 0.8});
  octx.lineWidth = 1;
  octx.lineJoin = 'miter';
  octx.fillStyle = this.processColor(options.selection.color, {opacity: 0.4});
 
  this.selection.prevSelection = {
  first: { x: s.first.x, y: s.first.y },
  second: { x: s.second.x, y: s.second.y }
  };
 
  var x = Math.min(s.first.x, s.second.x),
  y = Math.min(s.first.y, s.second.y),
  w = Math.abs(s.second.x - s.first.x),
  h = Math.abs(s.second.y - s.first.y);
 
  octx.fillRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.strokeRect(x + plotOffset.left+0.5, y + plotOffset.top+0.5, w, h);
  octx.restore();
  },
 
  /**
  * Updates (draws) the selection box.
  */
  updateSelection: function(){
  if (!this.lastMousePos.pageX) return;
 
  this.selection.selecting = true;
 
  if (this.multitouches) {
  this.selection.setSelectionPos(this.selection.selection.first, this.getEventPosition(this.multitouches[0]));
  this.selection.setSelectionPos(this.selection.selection.second, this.getEventPosition(this.multitouches[1]));
  } else
  if (this.options.selection.pinchOnly) {
  return;
  } else {
  this.selection.setSelectionPos(this.selection.selection.second, this.lastMousePos);
  }
 
  this.selection.clearSelection();
 
  if(this.selection.selectionIsSane()) {
  this.selection.drawSelection();
  }
  },
 
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearSelection: function() {
  if (!this.selection.prevSelection) return;
 
  var prevSelection = this.selection.prevSelection,
  lw = 1,
  plotOffset = this.plotOffset,
  x = Math.min(prevSelection.first.x, prevSelection.second.x),
  y = Math.min(prevSelection.first.y, prevSelection.second.y),
  w = Math.abs(prevSelection.second.x - prevSelection.first.x),
  h = Math.abs(prevSelection.second.y - prevSelection.first.y);
 
  this.octx.clearRect(x + plotOffset.left - lw + 0.5,
  y + plotOffset.top - lw,
  w + 2 * lw + 0.5,
  h + 2 * lw + 0.5);
 
  this.selection.prevSelection = null;
  },
  /**
  * Determines whether or not the selection is sane and should be drawn.
  * @return {Boolean} - True when sane, false otherwise.
  */
  selectionIsSane: function(){
  var s = this.selection.selection;
  return Math.abs(s.second.x - s.first.x) >= 5 ||
  Math.abs(s.second.y - s.first.y) >= 5;
  }
 
  });
 
  })();
 
  /** Spreadsheet **/
  (function() {
 
  function getRowLabel(value){
  if (this.options.spreadsheet.tickFormatter){
  //TODO maybe pass the xaxis formatter to the custom tick formatter as an opt-out?
  return this.options.spreadsheet.tickFormatter(value);
  }
  else {
  var t = _.find(this.axes.x.ticks, function(t){return t.v == value;});
  if (t) {
  return t.label;
  }
  return value;
  }
  }
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('spreadsheet', {
  options: {
  show: false, // => show the data grid using two tabs
  tabGraphLabel: 'Graph',
  tabDataLabel: 'Data',
  toolbarDownload: 'Download CSV', // @todo: add better language support
  toolbarSelectAll: 'Select all',
  csvFileSeparator: ',',
  decimalSeparator: '.',
  tickFormatter: null,
  initialTab: 'graph'
  },
  /**
  * Builds the tabs in the DOM
  */
  callbacks: {
  'flotr:afterconstruct': function(){
  // @TODO necessary?
  //this.el.select('.flotr-tabs-group,.flotr-datagrid-container').invoke('remove');
 
  if (!this.options.spreadsheet.show) return;
 
  var ss = this.spreadsheet,
  container = D.node('<div class="flotr-tabs-group" style="position:absolute;left:0px;width:'+this.canvasWidth+'px"></div>'),
  graph = D.node('<div style="float:left" class="flotr-tab selected">'+this.options.spreadsheet.tabGraphLabel+'</div>'),
  data = D.node('<div style="float:left" class="flotr-tab">'+this.options.spreadsheet.tabDataLabel+'</div>'),
  offset;
 
  ss.tabsContainer = container;
  ss.tabs = { graph : graph, data : data };
 
  D.insert(container, graph);
  D.insert(container, data);
  D.insert(this.el, container);
 
  offset = D.size(data).height + 2;
  this.plotOffset.bottom += offset;
 
  D.setStyles(container, {top: this.canvasHeight-offset+'px'});
 
  this.
  observe(graph, 'click', function(){ss.showTab('graph');}).
  observe(data, 'click', function(){ss.showTab('data');});
  if (this.options.spreadsheet.initialTab !== 'graph'){
  ss.showTab(this.options.spreadsheet.initialTab);
  }
  }
  },
  /**
  * Builds a matrix of the data to make the correspondance between the x values and the y values :
  * X value => Y values from the axes
  * @return {Array} The data grid
  */
  loadDataGrid: function(){
  if (this.seriesData) return this.seriesData;
 
  var s = this.series,
  rows = {};
 
  /* The data grid is a 2 dimensions array. There is a row for each X value.
  * Each row contains the x value and the corresponding y value for each serie ('undefined' if there isn't one)
  **/
  _.each(s, function(serie, i){
  _.each(serie.data, function (v) {
  var x = v[0],
  y = v[1],
  r = rows[x];
  if (r) {
  r[i+1] = y;
  } else {
  var newRow = [];
  newRow[0] = x;
  newRow[i+1] = y;
  rows[x] = newRow;
  }
  });
  });
 
  // The data grid is sorted by x value
  this.seriesData = _.sortBy(rows, function(row, x){
  return parseInt(x, 10);
  });
  return this.seriesData;
  },
  /**
  * Constructs the data table for the spreadsheet
  * @todo make a spreadsheet manager (Flotr.Spreadsheet)
  * @return {Element} The resulting table element
  */
  constructDataGrid: function(){
  // If the data grid has already been built, nothing to do here
  if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
 
  var s = this.series,
  datagrid = this.spreadsheet.loadDataGrid(),
  colgroup = ['<colgroup><col />'],
  buttonDownload, buttonSelect, t;
 
  // First row : series' labels
  var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
  html.push('<th>&nbsp;</th>');
  _.each(s, function(serie,i){
  html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>');
  colgroup.push('<col />');
  });
  html.push('</tr>');
  // Data rows
  _.each(datagrid, function(row){
  html.push('<tr>');
  _.times(s.length+1, function(i){
  var tag = 'td',
  value = row[i],
  // TODO: do we really want to handle problems with floating point
  // precision here?
  content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : '');
  if (i === 0) {
  tag = 'th';
  var label = getRowLabel.call(this, content);
  if (label) content = label;
  }
 
  html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>');
  }, this);
  html.push('</tr>');
  }, this);
  colgroup.push('</colgroup>');
  t = D.node(html.join(''));
 
  /**
  * @TODO disabled this
  if (!Flotr.isIE || Flotr.isIE == 9) {
  function handleMouseout(){
  t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
  }
  function handleMouseover(e){
  var td = e.element(),
  siblings = td.previousSiblings();
  t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
  t.select('colgroup col')[siblings.length].addClassName('hover');
  }
  _.each(t.select('td'), function(td) {
  Flotr.EventAdapter.
  observe(td, 'mouseover', handleMouseover).
  observe(td, 'mouseout', handleMouseout);
  });
  }
  */
 
  buttonDownload = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarDownload +
  '</button>');
 
  buttonSelect = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarSelectAll+
  '</button>');
 
  this.
  observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
  observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
 
  var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
  D.insert(toolbar, buttonDownload);
  D.insert(toolbar, buttonSelect);
 
  var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2,
  container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+
  this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>');
 
  D.insert(container, toolbar);
  D.insert(container, t);
  D.insert(this.el, container);
  this.spreadsheet.datagrid = t;
  this.spreadsheet.container = container;
 
  return t;
  },
  /**
  * Shows the specified tab, by its name
  * @todo make a tab manager (Flotr.Tabs)
  * @param {String} tabName - The tab name
  */
  showTab: function(tabName){
  if (this.spreadsheet.activeTab === tabName){
  return;
  }
  switch(tabName) {
  case 'graph':
  D.hide(this.spreadsheet.container);
  D.removeClass(this.spreadsheet.tabs.data, 'selected');
  D.addClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  case 'data':
  if (!this.spreadsheet.datagrid)
  this.spreadsheet.constructDataGrid();
  D.show(this.spreadsheet.container);
  D.addClass(this.spreadsheet.tabs.data, 'selected');
  D.removeClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  default:
  throw 'Illegal tab name: ' + tabName;
  }
  this.spreadsheet.activeTab = tabName;
  },
  /**
  * Selects the data table in the DOM for copy/paste
  */
  selectAllData: function(){
  if (this.spreadsheet.tabs) {
  var selection, range, doc, win, node = this.spreadsheet.constructDataGrid();
 
  this.spreadsheet.showTab('data');
 
  // deferred to be able to select the table
  setTimeout(function () {
  if ((doc = node.ownerDocument) && (win = doc.defaultView) &&
  win.getSelection && doc.createRange &&
  (selection = window.getSelection()) &&
  selection.removeAllRanges) {
  range = doc.createRange();
  range.selectNode(node);
  selection.removeAllRanges();
  selection.addRange(range);
  }
  else if (document.body && document.body.createTextRange &&
  (range = document.body.createTextRange())) {
  range.moveToElementText(node);
  range.select();
  }
  }, 0);
  return true;
  }
  else return false;
  },
  /**
  * Converts the data into CSV in order to download a file
  */
  downloadCSV: function(){
  var csv = '',
  series = this.series,
  options = this.options,
  dg = this.spreadsheet.loadDataGrid(),
  separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
 
  if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
  throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
  }
 
  // The first row
  _.each(series, function(serie, i){
  csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
  });
 
  csv += "%0D%0A"; // \r\n
 
  // For each row
  csv += _.reduce(dg, function(memo, row){
  var rowLabel = getRowLabel.call(this, row[0]) || '';
  rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
  var numbers = row.slice(1).join(separator);
  if (options.spreadsheet.decimalSeparator !== '.') {
  numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
  }
  return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
  }, '', this);
 
  if (Flotr.isIE && Flotr.isIE < 9) {
  csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
  window.open().document.write(csv);
  }
  else window.open('data:text/csv,'+csv);
  }
  });
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('titles', {
  callbacks: {
  'flotr:afterdraw': function() {
  this.titles.drawTitles();
  }
  },
  /**
  * Draws the title and the subtitle
  */
  drawTitles : function () {
  var html,
  options = this.options,
  margin = options.grid.labelMargin,
  ctx = this.ctx,
  a = this.axes;
 
  if (!options.HtmlText && this.textEnabled) {
  var style = {
  size: options.fontSize,
  color: options.grid.color,
  textAlign: 'center'
  };
 
  // Add subtitle
  if (options.subtitle){
  Flotr.drawText(
  ctx, options.subtitle,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight + this.subtitleHeight - 2,
  style
  );
  }
 
  style.weight = 1.5;
  style.size *= 1.5;
 
  // Add title
  if (options.title){
  Flotr.drawText(
  ctx, options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.titleHeight - 2,
  style
  );
  }
 
  style.weight = 1.8;
  style.size *= 0.8;
 
  // Add x axis title
  if (a.x.options.title && a.x.used){
  style.textAlign = a.x.options.titleAlign || 'center';
  style.textBaseline = 'top';
  style.angle = Flotr.toRad(a.x.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top + a.x.maxLabel.height + this.plotHeight + 2 * margin,
  style
  );
  }
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used){
  style.textAlign = a.x2.options.titleAlign || 'center';
  style.textBaseline = 'bottom';
  style.angle = Flotr.toRad(a.x2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x2.options.title,
  this.plotOffset.left + this.plotWidth/2,
  this.plotOffset.top - a.x2.maxLabel.height - 2 * margin,
  style
  );
  }
 
  // Add y axis title
  if (a.y.options.title && a.y.used){
  style.textAlign = a.y.options.titleAlign || 'right';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y.options.title,
  this.plotOffset.left - a.y.maxLabel.width - 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used){
  style.textAlign = a.y2.options.titleAlign || 'left';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y2.options.title,
  this.plotOffset.left + this.plotWidth + a.y2.maxLabel.width + 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
  }
  else {
  html = [];
 
  // Add title
  if (options.title)
  html.push(
  '<div style="position:absolute;top:0;left:',
  this.plotOffset.left, 'px;font-size:1em;font-weight:bold;text-align:center;width:',
  this.plotWidth,'px;" class="flotr-title">', options.title, '</div>'
  );
 
  // Add subtitle
  if (options.subtitle)
  html.push(
  '<div style="position:absolute;top:', this.titleHeight, 'px;left:',
  this.plotOffset.left, 'px;font-size:smaller;text-align:center;width:',
  this.plotWidth, 'px;" class="flotr-subtitle">', options.subtitle, '</div>'
  );
 
  html.push('</div>');
 
  html.push('<div class="flotr-axis-title" style="font-weight:bold;">');
 
  // Add x axis title
  if (a.x.options.title && a.x.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight + options.grid.labelMargin + a.x.titleSize.height),
  'px;left:', this.plotOffset.left, 'px;width:', this.plotWidth,
  'px;text-align:', a.x.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x1">', a.x.options.title, '</div>'
  );
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used)
  html.push(
  '<div style="position:absolute;top:0;left:', this.plotOffset.left, 'px;width:',
  this.plotWidth, 'px;text-align:', a.x2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x2">', a.x2.options.title, '</div>'
  );
 
  // Add y axis title
  if (a.y.options.title && a.y.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;left:0;text-align:', a.y.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y1">', a.y.options.title, '</div>'
  );
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight/2 - a.y.titleSize.height/2),
  'px;right:0;text-align:', a.y2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y2">', a.y2.options.title, '</div>'
  );
 
  html = html.join('');
 
  var div = D.create('div');
  D.setStyles({
  color: options.grid.color
  });
  div.className = 'flotr-titles';
  D.insert(this.el, div);
  D.insert(div, html);
  }
  }
  });
  })();
 
  /** Bars **/
  Flotr.addType('bars', {
 
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  horizontal: false, // => horizontal bars (x and y inverted)
  stacked: false, // => stacked bar charts
  centered: true, // => center the bars to their x axis value
  topPadding: 0.1, // => top padding in percent
  grouped: false // => groups bars together which share x value, hit not supported.
  },
 
  stack : {
  positive : [],
  negative : [],
  _positive : [], // Shadow
  _negative : [] // Shadow
  },
 
  draw : function (options) {
  var
  context = options.context;
 
  this.current += 1;
 
  context.save();
  context.lineJoin = 'miter';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  shadowSize = options.shadowSize,
  i, geometry, left, top, width, height;
 
  if (data.length < 1) return;
 
  this.translate(context, options.horizontal);
 
  for (i = 0; i < data.length; i++) {
 
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (geometry === null) continue;
 
  left = geometry.left;
  top = geometry.top;
  width = geometry.width;
  height = geometry.height;
 
  if (options.fill) context.fillRect(left, top, width, height);
  if (shadowSize) {
  context.save();
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top + shadowSize, width, height);
  context.restore();
  }
  if (options.lineWidth) {
  context.strokeRect(left, top, width, height);
  }
  }
  },
 
  translate : function (context, horizontal) {
  if (horizontal) {
  context.rotate(-Math.PI / 2);
  context.scale(-1, 1);
  }
  },
 
  getBarGeometry : function (x, y, options) {
 
  var
  horizontal = options.horizontal,
  barWidth = options.barWidth,
  centered = options.centered,
  stack = options.stacked ? this.stack : false,
  lineWidth = options.lineWidth,
  bisection = centered ? barWidth / 2 : 0,
  xScale = horizontal ? options.yScale : options.xScale,
  yScale = horizontal ? options.xScale : options.yScale,
  xValue = horizontal ? y : x,
  yValue = horizontal ? x : y,
  stackOffset = 0,
  stackValue, left, right, top, bottom;
 
  if (options.grouped) {
  this.current / this.groups;
  xValue = xValue - bisection;
  barWidth = barWidth / this.groups;
  bisection = barWidth / 2;
  xValue = xValue + barWidth * this.current - bisection;
  }
 
  // Stacked bars
  if (stack) {
  stackValue = yValue > 0 ? stack.positive : stack.negative;
  stackOffset = stackValue[xValue] || stackOffset;
  stackValue[xValue] = stackOffset + yValue;
  }
 
  left = xScale(xValue - bisection);
  right = xScale(xValue + barWidth - bisection);
  top = yScale(yValue + stackOffset);
  bottom = yScale(stackOffset);
 
  // TODO for test passing... probably looks better without this
  if (bottom < 0) bottom = 0;
 
  // TODO Skipping...
  // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;
 
  return (x === null || y === null) ? null : {
  x : xValue,
  y : yValue,
  xScale : xScale,
  yScale : yScale,
  top : top,
  left : Math.min(left, right) - lineWidth / 2,
  width : Math.abs(right - left) - lineWidth,
  height : bottom - top
  };
  },
 
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  x = options.xInverse(mouse.relX),
  y = options.yInverse(mouse.relY),
  hitGeometry = this.getBarGeometry(x, y, options),
  width = hitGeometry.width / 2,
  left = hitGeometry.left,
  height = hitGeometry.y,
  geometry, i;
 
  for (i = data.length; i--;) {
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (
  // Height:
  (
  // Positive Bars:
  (height > 0 && height < geometry.y) ||
  // Negative Bars:
  (height < 0 && height > geometry.y)
  ) &&
  // Width:
  (Math.abs(left - geometry.left) < width)
  ) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  }
  },
 
  drawHit : function (options) {
  // TODO hits for stacked bars; implement using calculateStack option?
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  top = geometry.top,
  width = geometry.width,
  height = geometry.height;
 
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  this.translate(context, options.horizontal);
 
  // Draw highlight
  context.beginPath();
  context.moveTo(left, top + height);
  context.lineTo(left, top);
  context.lineTo(left + width, top);
  context.lineTo(left + width, top + height);
  if (options.fill) {
  context.fillStyle = options.fillStyle;
  context.fill();
  }
  context.stroke();
  context.closePath();
 
  context.restore();
  },
 
  clearHit: function (options) {
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  width = geometry.width,
  top = geometry.top,
  height = geometry.height,
  lineWidth = 2 * options.lineWidth;
 
  context.save();
  this.translate(context, options.horizontal);
  context.clearRect(
  left - lineWidth,
  Math.min(top, top + height) - lineWidth,
  width + 2 * lineWidth,
  Math.abs(height) + 2 * lineWidth
  );
  context.restore();
  },
 
  extendXRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  this.groups = (this.groups + 1) || 1;
  this.current = 0;
  },
 
  extendYRange : function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {
 
  var
  max = axis.options.max;
 
  if (_.isNumber(max) || _.isString(max)) return;
 
  var
  newmin = axis.min,
  newmax = axis.max,
  horizontal = options.horizontal,
  orientation = axis.orientation,
  positiveSums = this.positiveSums || {},
  negativeSums = this.negativeSums || {},
  value, datum, index, j;
 
  // Sides of bars
  if ((orientation == 1 && !horizontal) || (orientation == -1 && horizontal)) {
  if (options.centered) {
  newmax = Math.max(axis.datamax + options.barWidth, newmax);
  newmin = Math.min(axis.datamin - options.barWidth, newmin);
  }
  }
 
  if (options.stacked &&
  ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal))){
 
  for (j = data.length; j--;) {
  value = data[j][(orientation == 1 ? 1 : 0)]+'';
  datum = data[j][(orientation == 1 ? 0 : 1)];
 
  // Positive
  if (datum > 0) {
  positiveSums[value] = (positiveSums[value] || 0) + datum;
  newmax = Math.max(newmax, positiveSums[value]);
  }
 
  // Negative
  else {
  negativeSums[value] = (negativeSums[value] || 0) + datum;
  newmin = Math.min(newmin, negativeSums[value]);
  }
  }
  }
 
  // End of bars
  if ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal)) {
  if (options.topPadding && (axis.max === axis.datamax || (options.stacked && this.stackMax !== newmax))) {
  newmax += options.topPadding * (newmax - newmin);
  }
  }
 
  this.stackMin = newmin;
  this.stackMax = newmax;
  this.negativeSums = negativeSums;
  this.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  });
 
  /** Bubbles **/
  Flotr.addType('bubbles', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  baseRadius: 2 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.lineWidth = options.lineWidth;
 
  // Shadows
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
 
  var
  data = options.data,
  context = options.context,
  geometry,
  i, x, y, z;
 
  offset = offset || 0;
 
  for (i = 0; i < data.length; ++i){
 
  geometry = this.getGeometry(data[i], options);
 
  context.beginPath();
  context.arc(geometry.x + offset, geometry.y + offset, geometry.z, 0, 2 * Math.PI, true);
  context.stroke();
  if (options.fill) context.fill();
  context.closePath();
  }
  },
  getGeometry : function (point, options) {
  return {
  x : options.xScale(point[0]),
  y : options.yScale(point[1]),
  z : point[2] * options.baseRadius
  };
  },
  hit : function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  relX = mouse.relX,
  relY = mouse.relY,
  distance,
  geometry,
  dx, dy;
 
  n.best = n.best || Number.MAX_VALUE;
 
  for (i = data.length; i--;) {
  geometry = this.getGeometry(data[i], options);
 
  dx = geometry.x - relX;
  dy = geometry.y - relY;
  distance = Math.sqrt(dx * dx + dy * dy);
 
  if (distance < geometry.z && geometry.z < n.best) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  n.best = geometry.z;
  }
  }
  },
  drawHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options);
 
  context.save();
  context.lineWidth = options.lineWidth;
  context.fillStyle = options.fillStyle;
  context.strokeStyle = options.color;
  context.beginPath();
  context.arc(geometry.x, geometry.y, geometry.z, 0, 2 * Math.PI, true);
  context.fill();
  context.stroke();
  context.closePath();
  context.restore();
  },
  clearHit : function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options),
  offset = geometry.z + options.lineWidth;
 
  context.save();
  context.clearRect(
  geometry.x - offset,
  geometry.y - offset,
  2 * offset,
  2 * offset
  );
  context.restore();
  }
  // TODO Add a hit calculation method (like pie)
  });
 
  /** Candles **/
  Flotr.addType('candles', {
  options: {
  show: false, // => setting to true will show candle sticks, false will hide
  lineWidth: 1, // => in pixels
  wickLineWidth: 1, // => in pixels
  candleWidth: 0.6, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  upFillColor: '#00A8F0',// => up sticks fill color
  downFillColor: '#CB4B4B',// => down sticks fill color
  fillOpacity: 0.5, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  // TODO Test this barcharts option.
  barcharts: false // => draw as barcharts (not standard bars but financial barcharts)
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineCap = 'butt';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.wickLineWidth || options.lineWidth;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  width = options.candleWidth / 2,
  shadowSize = options.shadowSize,
  lineWidth = options.lineWidth,
  wickLineWidth = options.wickLineWidth,
  pixelOffset = (wickLineWidth % 2) / 2,
  color,
  datum, x, y,
  open, high, low, close,
  left, right, bottom, top, bottom2, top2,
  i;
 
  if (data.length < 1) return;
 
  for (i = 0; i < data.length; i++) {
  datum = data[i];
  x = datum[0];
  open = datum[1];
  high = datum[2];
  low = datum[3];
  close = datum[4];
  left = xScale(x - width);
  right = xScale(x + width);
  bottom = yScale(low);
  top = yScale(high);
  bottom2 = yScale(Math.min(open, close));
  top2 = yScale(Math.max(open, close));
 
  /*
  // TODO skipping
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
  */
 
  color = options[open > close ? 'downFillColor' : 'upFillColor'];
 
  // Fill the candle.
  // TODO Test the barcharts option
  if (options.fill && !options.barcharts) {
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top2 + shadowSize, right - left, bottom2 - top2);
  context.save();
  context.globalAlpha = options.fillOpacity;
  context.fillStyle = color;
  context.fillRect(left, top2 + lineWidth, right - left, bottom2 - top2);
  context.restore();
  }
 
  // Draw candle outline/border, high, low.
  if (lineWidth || wickLineWidth) {
 
  x = Math.floor((left + right) / 2) + pixelOffset;
 
  context.strokeStyle = color;
  context.beginPath();
 
  // TODO Again with the bartcharts
  if (options.barcharts) {
 
  context.moveTo(x, Math.floor(top + width));
  context.lineTo(x, Math.floor(bottom + width));
 
  y = Math.floor(open + width) + 0.5;
  context.moveTo(Math.floor(left) + pixelOffset, y);
  context.lineTo(x, y);
 
  y = Math.floor(close + width) + 0.5;
  context.moveTo(Math.floor(right) + pixelOffset, y);
  context.lineTo(x, y);
  } else {
  context.strokeRect(left, top2 + lineWidth, right - left, bottom2 - top2);
 
  context.moveTo(x, Math.floor(top2 + lineWidth));
  context.lineTo(x, Math.floor(top + lineWidth));
  context.moveTo(x, Math.floor(bottom2 + lineWidth));
  context.lineTo(x, Math.floor(bottom + lineWidth));
  }
 
  context.closePath();
  context.stroke();
  }
  }
  },
  extendXRange: function (axis, data, options) {
  if (axis.options.max === null) {
  axis.max = Math.max(axis.datamax + 0.5, axis.max);
  axis.min = Math.min(axis.datamin - 0.5, axis.min);
  }
  }
  });
 
  /** Gantt
  * Base on data in form [s,y,d] where:
  * y - executor or simply y value
  * s - task start value
  * d - task duration
  * **/
  Flotr.addType('gantt', {
  options: {
  show: false, // => setting to true will show gantt, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  centered: true // => center the bars to their x axis value
  },
  /**
  * Draws gantt series in the canvas element.
  * @param {Object} series - Series with options.gantt.show = true.
  */
  draw: function(series) {
  var ctx = this.ctx,
  bw = series.gantt.barWidth,
  lw = Math.min(series.gantt.lineWidth, bw);
 
  ctx.save();
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
  ctx.lineJoin = 'miter';
 
  /**
  * @todo linewidth not interpreted the right way.
  */
  ctx.lineWidth = lw;
  ctx.strokeStyle = series.color;
 
  ctx.save();
  this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
  ctx.restore();
 
  if(series.gantt.fill){
  var color = series.gantt.fillColor || series.color;
  ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
  }
 
  this.gantt.plot(series, bw, 0, series.gantt.fill);
  ctx.restore();
  },
  plot: function(series, barWidth, offset, fill){
  var data = series.data;
  if(data.length < 1) return;
 
  var xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx, i;
 
  for(i = 0; i < data.length; i++){
  var y = data[i][0],
  s = data[i][1],
  d = data[i][2],
  drawLeft = true, drawTop = true, drawRight = true;
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min){
  left = xa.min;
  drawLeft = false;
  }
 
  if(right > xa.max){
  right = xa.max;
  if (xa.lastSerie != series)
  drawTop = false;
  }
 
  if(bottom < ya.min)
  bottom = ya.min;
 
  if(top > ya.max){
  top = ya.max;
  if (ya.lastSerie != series)
  drawTop = false;
  }
 
  /**
  * Fill the bar.
  */
  if(fill){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
  ctx.lineTo(xa.d2p(left), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(bottom) + offset);
  ctx.fill();
  ctx.closePath();
  }
 
  /**
  * Draw bar outline/border.
  */
  if(series.gantt.lineWidth && (drawLeft || drawRight || drawTop)){
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
 
  ctx[drawLeft ?'lineTo':'moveTo'](xa.d2p(left), ya.d2p(top) + offset);
  ctx[drawTop ?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(top) + offset);
  ctx[drawRight?'lineTo':'moveTo'](xa.d2p(right), ya.d2p(bottom) + offset);
 
  ctx.stroke();
  ctx.closePath();
  }
  }
  },
  plotShadows: function(series, barWidth, offset){
  var data = series.data;
  if(data.length < 1) return;
 
  var i, y, s, d,
  xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx,
  sw = this.options.shadowSize;
 
  for(i = 0; i < data.length; i++){
  y = data[i][0];
  s = data[i][1];
  d = data[i][2];
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth/2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth/2 : 0);
 
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if(left < xa.min) left = xa.min;
  if(right > xa.max) right = xa.max;
  if(bottom < ya.min) bottom = ya.min;
  if(top > ya.max) top = ya.max;
 
  var width = xa.d2p(right)-xa.d2p(left)-((xa.d2p(right)+sw <= this.plotWidth) ? 0 : sw);
  var height = ya.d2p(bottom)-ya.d2p(top)-((ya.d2p(bottom)+sw <= this.plotHeight) ? 0 : sw );
 
  ctx.fillStyle = 'rgba(0,0,0,0.05)';
  ctx.fillRect(Math.min(xa.d2p(left)+sw, this.plotWidth), Math.min(ya.d2p(top)+sw, this.plotHeight), width, height);
  }
  },
  extendXRange: function(axis) {
  if(axis.options.max === null){
  var newmin = axis.min,
  newmax = axis.max,
  i, j, x, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if(g.show && s.xaxis == axis) {
  for (j = 0; j < s.data.length; j++) {
  if (g.show) {
  y = s.data[j][0]+'';
  stackedSumsPos[y] = Math.max((stackedSumsPos[y] || 0), s.data[j][1]+s.data[j][2]);
  lastSerie = s;
  }
  }
  for (j in stackedSumsPos) {
  newmax = Math.max(stackedSumsPos[j], newmax);
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  }
  },
  extendYRange: function(axis){
  if(axis.options.max === null){
  var newmax = Number.MIN_VALUE,
  newmin = Number.MAX_VALUE,
  i, j, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for(i = 0; i < this.series.length; ++i){
  s = this.series[i];
  g = s.gantt;
 
  if (g.show && !s.hide && s.yaxis == axis) {
  var datamax = Number.MIN_VALUE, datamin = Number.MAX_VALUE;
  for(j=0; j < s.data.length; j++){
  datamax = Math.max(datamax,s.data[j][0]);
  datamin = Math.min(datamin,s.data[j][0]);
  }
 
  if (g.centered) {
  newmax = Math.max(datamax + 0.5, newmax);
  newmin = Math.min(datamin - 0.5, newmin);
  }
  else {
  newmax = Math.max(datamax + 1, newmax);
  newmin = Math.min(datamin, newmin);
  }
  // For normal horizontal bars
  if (g.barWidth + datamax > newmax){
  newmax = axis.max + g.barWidth;
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  axis.tickSize = Flotr.getTickSize(axis.options.noTicks, newmin, newmax, axis.options.tickDecimals);
  }
  }
  });
 
  /** Lines **/
  Flotr.addType('lines', {
  options: {
  show: false, // => setting to true will show lines, false will hide
  lineWidth: 2, // => line width in pixels
  fill: false, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillBorder: false, // => draw a border around the fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  steps: false, // => draw steps
  stacked: false // => setting to true will show stacked lines, false will show normal lines
  },
 
  stack : {
  values : []
  },
 
  /**
  * Draws lines series in the canvas element.
  * @param {Object} options
  */
  draw : function (options) {
 
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  offset;
 
  context.save();
  context.lineJoin = 'round';
 
  if (shadowSize) {
 
  context.lineWidth = shadowSize / 2;
  offset = lineWidth / 2 + context.lineWidth / 2;
 
  // @TODO do this instead with a linear gradient
  context.strokeStyle = "rgba(0,0,0,0.1)";
  this.plot(options, offset + shadowSize / 2, false);
 
  context.strokeStyle = "rgba(0,0,0,0.2)";
  this.plot(options, offset, false);
  }
 
  context.lineWidth = lineWidth;
  context.strokeStyle = options.color;
 
  this.plot(options, 0, true);
 
  context.restore();
  },
 
  plot : function (options, shadowOffset, incStack) {
 
  var
  context = options.context,
  width = options.width,
  height = options.height,
  xScale = options.xScale,
  yScale = options.yScale,
  data = options.data,
  stack = options.stacked ? this.stack : false,
  length = data.length - 1,
  prevx = null,
  prevy = null,
  zero = yScale(0),
  start = null,
  x1, x2, y1, y2, stack1, stack2, i;
 
  if (length < 1) return;
 
  context.beginPath();
 
  for (i = 0; i < length; ++i) {
 
  // To allow empty values
  if (data[i][1] === null || data[i+1][1] === null) {
  if (options.fill) {
  if (i > 0 && data[i][1]) {
  context.stroke();
  fill();
  start = null;
  context.closePath();
  context.beginPath();
  }
  }
  continue;
  }
 
  // Zero is infinity for log scales
  // TODO handle zero for logarithmic
  // if (xa.options.scaling === 'logarithmic' && (data[i][0] <= 0 || data[i+1][0] <= 0)) continue;
  // if (ya.options.scaling === 'logarithmic' && (data[i][1] <= 0 || data[i+1][1] <= 0)) continue;
 
  x1 = xScale(data[i][0]);
  x2 = xScale(data[i+1][0]);
 
  if (start === null) start = data[i];
 
  if (stack) {
 
  stack1 = stack.values[data[i][0]] || 0;
  stack2 = stack.values[data[i+1][0]] || stack.values[data[i][0]] || 0;
 
  y1 = yScale(data[i][1] + stack1);
  y2 = yScale(data[i+1][1] + stack2);
 
  if(incStack){
  stack.values[data[i][0]] = data[i][1]+stack1;
 
  if(i == length-1)
  stack.values[data[i+1][0]] = data[i+1][1]+stack2;
  }
  }
  else{
  y1 = yScale(data[i][1]);
  y2 = yScale(data[i+1][1]);
  }
 
  if (
  (y1 > height && y2 > height) ||
  (y1 < 0 && y2 < 0) ||
  (x1 < 0 && x2 < 0) ||
  (x1 > width && x2 > width)
  ) continue;
 
  if((prevx != x1) || (prevy != y1 + shadowOffset))
  context.moveTo(x1, y1 + shadowOffset);
 
  prevx = x2;
  prevy = y2 + shadowOffset;
  if (options.steps) {
  context.lineTo(prevx + shadowOffset / 2, y1 + shadowOffset);
  context.lineTo(prevx + shadowOffset / 2, prevy);
  } else {
  context.lineTo(prevx, prevy);
  }
  }
 
  if (!options.fill || options.fill && !options.fillBorder) context.stroke();
 
  fill();
 
  function fill () {
  // TODO stacked lines
  if(!shadowOffset && options.fill && start){
  x1 = xScale(start[0]);
  context.fillStyle = options.fillStyle;
  context.lineTo(x2, zero);
  context.lineTo(x1, zero);
  context.lineTo(x1, yScale(start[1]));
  context.fill();
  if (options.fillBorder) {
  context.stroke();
  }
  }
  }
 
  context.closePath();
  },
 
  // Perform any pre-render precalculations (this should be run on data first)
  // - Pie chart total for calculating measures
  // - Stacks for lines and bars
  // precalculate : function () {
  // }
  //
  //
  // Get any bounds after pre calculation (axis can fetch this if does not have explicit min/max)
  // getBounds : function () {
  // }
  // getMin : function () {
  // }
  // getMax : function () {
  // }
  //
  //
  // Padding around rendered elements
  // getPadding : function () {
  // }
 
  extendYRange : function (axis, data, options, lines) {
 
  var o = axis.options;
 
  // If stacked and auto-min
  if (options.stacked && ((!o.max && o.max !== 0) || (!o.min && o.min !== 0))) {
 
  var
  newmax = axis.max,
  newmin = axis.min,
  positiveSums = lines.positiveSums || {},
  negativeSums = lines.negativeSums || {},
  x, j;
 
  for (j = 0; j < data.length; j++) {
 
  x = data[j][0] + '';
 
  // Positive
  if (data[j][1] > 0) {
  positiveSums[x] = (positiveSums[x] || 0) + data[j][1];
  newmax = Math.max(newmax, positiveSums[x]);
  }
 
  // Negative
  else {
  negativeSums[x] = (negativeSums[x] || 0) + data[j][1];
  newmin = Math.min(newmin, negativeSums[x]);
  }
  }
 
  lines.negativeSums = negativeSums;
  lines.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  if (options.steps) {
 
  this.hit = function (options) {
  var
  data = options.data,
  args = options.args,
  yScale = options.yScale,
  mouse = args[0],
  length = data.length,
  n = args[1],
  x = options.xInverse(mouse.relX),
  relY = mouse.relY,
  i;
 
  for (i = 0; i < length - 1; i++) {
  if (x >= data[i][0] && x <= data[i+1][0]) {
  if (Math.abs(yScale(data[i][1]) - relY) < 8) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  break;
  }
  }
  };
 
  this.drawHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x2, y);
  context.stroke();
  context.closePath();
  context.restore();
  }
  };
 
  this.clearHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  width = options.lineWidth,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.clearRect(x - width, y - width, x2 - x + 2 * width, 2 * width);
  }
  };
  }
  }
 
  });
 
  /** Markers **/
  /**
  * Formats the marker labels.
  * @param {Object} obj - Marker value Object {x:..,y:..}
  * @return {String} Formatted marker string
  */
  (function () {
 
  Flotr.defaultMarkerFormatter = function(obj){
  return (Math.round(obj.y*100)/100)+'';
  };
 
  Flotr.addType('markers', {
  options: {
  show: false, // => setting to true will show markers, false will hide
  lineWidth: 1, // => line width of the rectangle around the marker
  color: '#000000', // => text color
  fill: false, // => fill or not the marekers' rectangles
  fillColor: "#FFFFFF", // => fill color
  fillOpacity: 0.4, // => fill opacity
  stroke: false, // => draw the rectangle around the markers
  position: 'ct', // => the markers position (vertical align: b, m, t, horizontal align: l, c, r)
  verticalMargin: 0, // => the margin between the point and the text.
  labelFormatter: Flotr.defaultMarkerFormatter,
  fontSize: Flotr.defaultOptions.fontSize,
  stacked: false, // => true if markers should be stacked
  stackingType: 'b', // => define staching behavior, (b- bars like, a - area like) (see Issue 125 for details)
  horizontal: false // => true if markers should be horizontal (For now only in a case on horizontal stacked bars, stacks should be calculated horizontaly)
  },
 
  // TODO test stacked markers.
  stack : {
  positive : [],
  negative : [],
  values : []
  },
 
  draw : function (options) {
 
  var
  data = options.data,
  context = options.context,
  stack = options.stacked ? options.stack : false,
  stackType = options.stackingType,
  stackOffsetNeg,
  stackOffsetPos,
  stackOffset,
  i, x, y, label;
 
  context.save();
  context.lineJoin = 'round';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = 'rgba(0,0,0,0.5)';
  context.fillStyle = options.fillStyle;
 
  function stackPos (a, b) {
  stackOffsetPos = stack.negative[a] || 0;
  stackOffsetNeg = stack.positive[a] || 0;
  if (b > 0) {
  stack.positive[a] = stackOffsetPos + b;
  return stackOffsetPos + b;
  } else {
  stack.negative[a] = stackOffsetNeg + b;
  return stackOffsetNeg + b;
  }
  }
 
  for (i = 0; i < data.length; ++i) {
 
  x = data[i][0];
  y = data[i][1];
 
  if (stack) {
  if (stackType == 'b') {
  if (options.horizontal) y = stackPos(y, x);
  else x = stackPos(x, y);
  } else if (stackType == 'a') {
  stackOffset = stack.values[x] || 0;
  stack.values[x] = stackOffset + y;
  y = stackOffset + y;
  }
  }
 
  label = options.labelFormatter({x: x, y: y, index: i, data : data});
  this.plot(options.xScale(x), options.yScale(y), label, options);
  }
  context.restore();
  },
  plot: function(x, y, label, options) {
  var context = options.context;
  if (isImage(label) && !label.complete) {
  throw 'Marker image not loaded.';
  } else {
  this._plot(x, y, label, options);
  }
  },
 
  _plot: function(x, y, label, options) {
  var context = options.context,
  margin = 2,
  left = x,
  top = y,
  dim;
 
  if (isImage(label))
  dim = {height : label.height, width: label.width};
  else
  dim = options.text.canvas(label);
 
  dim.width = Math.floor(dim.width+margin*2);
  dim.height = Math.floor(dim.height+margin*2);
 
  if (options.position.indexOf('c') != -1) left -= dim.width/2 + margin;
  else if (options.position.indexOf('l') != -1) left -= dim.width;
 
  if (options.position.indexOf('m') != -1) top -= dim.height/2 + margin;
  else if (options.position.indexOf('t') != -1) top -= dim.height + options.verticalMargin;
  else top += options.verticalMargin;
 
  left = Math.floor(left)+0.5;
  top = Math.floor(top)+0.5;
 
  if(options.fill)
  context.fillRect(left, top, dim.width, dim.height);
 
  if(options.stroke)
  context.strokeRect(left, top, dim.width, dim.height);
 
  if (isImage(label))
  context.drawImage(label, left+margin, top+margin);
  else
  Flotr.drawText(context, label, left+margin, top+margin, {textBaseline: 'top', textAlign: 'left', size: options.fontSize, color: options.color});
  }
  });
 
  function isImage (i) {
  return typeof i === 'object' && i.constructor && (Image ? true : i.constructor === Image);
  }
 
  })();
 
  /**
  * Pie
  *
  * Formats the pies labels.
  * @param {Object} slice - Slice object
  * @return {String} Formatted pie label string
  */
  (function () {
 
  var
  _ = Flotr._;
 
  Flotr.defaultPieLabelFormatter = function (total, value) {
  return (100 * value / total).toFixed(2)+'%';
  };
 
  Flotr.addType('pie', {
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 1, // => in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.6, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  explode: 6, // => the number of pixels the splices will be far from the center
  sizeRatio: 0.6, // => the size ratio of the pie relative to the plot
  startAngle: Math.PI/4, // => the first slice start angle
  labelFormatter: Flotr.defaultPieLabelFormatter,
  pie3D: false, // => whether to draw the pie in 3 dimenstions or not (ineffective)
  pie3DviewAngle: (Math.PI/2 * 0.8),
  pie3DspliceThickness: 20,
  epsilon: 0.1 // => how close do you have to get to hit empty slice
  },
 
  draw : function (options) {
 
  // TODO 3D charts what?
 
  var
  data = options.data,
  context = options.context,
  canvas = context.canvas,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  sizeRatio = options.sizeRatio,
  height = options.height,
  width = options.width,
  explode = options.explode,
  color = options.color,
  fill = options.fill,
  fillStyle = options.fillStyle,
  radius = Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  value = data[0][1],
  html = [],
  vScale = 1,//Math.cos(series.pie.viewAngle);
  measure = Math.PI * 2 * value / this.total,
  startAngle = this.startAngle || (2 * Math.PI * options.startAngle), // TODO: this initial startAngle is already in radians (fixing will be test-unstable)
  endAngle = startAngle + measure,
  bisection = startAngle + measure / 2,
  label = options.labelFormatter(this.total, value),
  //plotTickness = Math.sin(series.pie.viewAngle)*series.pie.spliceThickness / vScale;
  explodeCoeff = explode + radius + 4,
  distX = Math.cos(bisection) * explodeCoeff,
  distY = Math.sin(bisection) * explodeCoeff,
  textAlign = distX < 0 ? 'right' : 'left',
  textBaseline = distY > 0 ? 'top' : 'bottom',
  style,
  x, y;
 
  context.save();
  context.translate(width / 2, height / 2);
  context.scale(1, vScale);
 
  x = Math.cos(bisection) * explode;
  y = Math.sin(bisection) * explode;
 
  // Shadows
  if (shadowSize > 0) {
  this.plotSlice(x + shadowSize, y + shadowSize, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = 'rgba(0,0,0,0.1)';
  context.fill();
  }
  }
 
  this.plotSlice(x, y, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = fillStyle;
  context.fill();
  }
  context.lineWidth = lineWidth;
  context.strokeStyle = color;
  context.stroke();
 
  style = {
  size : options.fontSize * 1.2,
  color : options.fontColor,
  weight : 1.5
  };
 
  if (label) {
  if (options.htmlText || !options.textEnabled) {
  divStyle = 'position:absolute;' + textBaseline + ':' + (height / 2 + (textBaseline === 'top' ? distY : -distY)) + 'px;';
  divStyle += textAlign + ':' + (width / 2 + (textAlign === 'right' ? -distX : distX)) + 'px;';
  html.push('<div style="', divStyle, '" class="flotr-grid-label">', label, '</div>');
  }
  else {
  style.textAlign = textAlign;
  style.textBaseline = textBaseline;
  Flotr.drawText(context, label, distX, distY, style);
  }
  }
 
  if (options.htmlText || !options.textEnabled) {
  var div = Flotr.DOM.node('<div style="color:' + options.fontColor + '" class="flotr-labels"></div>');
  Flotr.DOM.insert(div, html.join(''));
  Flotr.DOM.insert(options.element, div);
  }
 
  context.restore();
 
  // New start angle
  this.startAngle = endAngle;
  this.slices = this.slices || [];
  this.slices.push({
  radius : Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  x : x,
  y : y,
  explode : explode,
  start : startAngle,
  end : endAngle
  });
  },
  plotSlice : function (x, y, radius, startAngle, endAngle, context) {
  context.beginPath();
  context.moveTo(x, y);
  context.arc(x, y, radius, startAngle, endAngle, false);
  context.lineTo(x, y);
  context.closePath();
  },
  hit : function (options) {
 
  var
  data = options.data[0],
  args = options.args,
  index = options.index,
  mouse = args[0],
  n = args[1],
  slice = this.slices[index],
  x = mouse.relX - options.width / 2,
  y = mouse.relY - options.height / 2,
  r = Math.sqrt(x * x + y * y),
  theta = Math.atan(y / x),
  circle = Math.PI * 2,
  explode = slice.explode || options.explode,
  start = slice.start % circle,
  end = slice.end % circle,
  epsilon = options.epsilon;
 
  if (x < 0) {
  theta += Math.PI;
  } else if (x > 0 && y < 0) {
  theta += circle;
  }
 
  if (r < slice.radius + explode && r > explode) {
  if (
  (theta > start && theta < end) || // Normal Slice
  (start > end && (theta < end || theta > start)) || // First slice
  // TODO: Document the two cases at the end:
  (start === end && ((slice.start === slice.end && Math.abs(theta - start) < epsilon) || (slice.start !== slice.end && Math.abs(theta-start) > epsilon)))
  ) {
 
  // TODO Decouple this from hit plugin (chart shouldn't know what n means)
  n.x = data[0];
  n.y = data[1];
  n.sAngle = start;
  n.eAngle = end;
  n.index = 0;
  n.seriesIndex = index;
  n.fraction = data[1] / this.total;
  }
  }
  },
  drawHit: function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex];
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  this.plotSlice(slice.x, slice.y, slice.radius, slice.start, slice.end, context);
  context.stroke();
  context.restore();
  },
  clearHit : function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex],
  padding = 2 * options.lineWidth,
  radius = slice.radius + padding;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.clearRect(
  slice.x - radius,
  slice.y - radius,
  2 * radius + padding,
  2 * radius + padding
  );
  context.restore();
  },
  extendYRange : function (axis, data) {
  this.total = (this.total || 0) + data[0][1];
  }
  });
  })();
 
  /** Points **/
  Flotr.addType('points', {
  options: {
  show: false, // => setting to true will show points, false will hide
  radius: 3, // => point radius (pixels)
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the points with a color, false for (transparent) no fill
  fillColor: '#FFFFFF', // => fill color. Null to use series color.
  fillOpacity: 1, // => opacity of color inside the points
  hitRadius: null // => override for points hit radius
  },
 
  draw : function (options) {
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize;
 
  context.save();
 
  if (shadowSize > 0) {
  context.lineWidth = shadowSize / 2;
 
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 2 + context.lineWidth / 2);
 
  context.strokeStyle = 'rgba(0,0,0,0.2)';
  this.plot(options, context.lineWidth / 2);
  }
 
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
  context.restore();
  },
 
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  i, x, y;
 
  for (i = data.length - 1; i > -1; --i) {
  y = data[i][1];
  if (y === null) continue;
 
  x = xScale(data[i][0]);
  y = yScale(y);
 
  if (x < 0 || x > options.width || y < 0 || y > options.height) continue;
 
  context.beginPath();
  if (offset) {
  context.arc(x, y + offset, options.radius, 0, Math.PI, false);
  } else {
  context.arc(x, y, options.radius, 0, 2 * Math.PI, true);
  if (options.fill) context.fill();
  }
  context.stroke();
  context.closePath();
  }
  }
  });
 
  /** Radar **/
  Flotr.addType('radar', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  radiusRatio: 0.90 // => ratio of the radar, against the plot size
  },
  draw : function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.lineWidth = options.lineWidth;
 
  // Shadow
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot : function (options, offset) {
  var
  data = options.data,
  context = options.context,
  radius = Math.min(options.height, options.width) * options.radiusRatio / 2,
  step = 2 * Math.PI / data.length,
  angle = -Math.PI / 2,
  i, ratio;
 
  offset = offset || 0;
 
  context.beginPath();
  for (i = 0; i < data.length; ++i) {
  ratio = data[i][1] / this.max;
 
  context[i === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(i * step + angle) * radius * ratio + offset,
  Math.sin(i * step + angle) * radius * ratio + offset
  );
  }
  context.closePath();
  if (options.fill) context.fill();
  context.stroke();
  },
  extendYRange : function (axis, data) {
  this.max = Math.max(axis.max, this.max || -Number.MAX_VALUE);
  }
  });
 
  Flotr.addType('timeline', {
  options: {
  show: false,
  lineWidth: 1,
  barWidth: 0.2,
  fill: true,
  fillColor: null,
  fillOpacity: 0.4,
  centered: true
  },
 
  draw : function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot : function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  barWidth = options.barWidth,
  lineWidth = options.lineWidth,
  i;
 
  Flotr._.each(data, function (timeline) {
 
  var
  x = timeline[0],
  y = timeline[1],
  w = timeline[2],
  h = barWidth,
 
  xt = Math.ceil(xScale(x)),
  wt = Math.ceil(xScale(x + w)) - xt,
  yt = Math.round(yScale(y)),
  ht = Math.round(yScale(y - h)) - yt,
 
  x0 = xt - lineWidth / 2,
  y0 = Math.round(yt - ht / 2) - lineWidth / 2;
 
  context.strokeRect(x0, y0, wt, ht);
  context.fillRect(x0, y0, wt, ht);
 
  });
  },
 
  extendRange : function (series) {
 
  var
  data = series.data,
  xa = series.xaxis,
  ya = series.yaxis,
  w = series.timeline.barWidth;
 
  if (xa.options.min === null)
  xa.min = xa.datamin - w / 2;
 
  if (xa.options.max === null) {
 
  var
  max = xa.max;
 
  Flotr._.each(data, function (timeline) {
  max = Math.max(max, timeline[0] + timeline[2]);
  }, this);
 
  xa.max = max + w / 2;
  }
 
  if (ya.options.min === null)
  ya.min = ya.datamin - w;
  if (ya.options.min === null)
  ya.max = ya.datamax + w;
  }
 
  });
 
  /* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  * Version: 1.0
  * LastModified: Dec 25 1999
  * This library is free. You can redistribute it and/or modify it.
  */
 
  /*
  * Interfaces:
  * b64 = base64encode(data);
  * data = base64decode(b64);
  */
 
  (function() {
 
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var base64DecodeChars = [
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
  -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1];
 
  function base64encode(str) {
  var out, i, len;
  var c1, c2, c3;
 
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
  c1 = str.charCodeAt(i++) & 0xff;
  if(i == len)
  {
  out += base64EncodeChars.charAt(c1 >> 2);
  out += base64EncodeChars.charAt((c1 & 0x3) << 4);
  out += "==";
  break;
  }
  c2 = str.charCodeAt(i++);
  if(i == len)
  {
  out += base64EncodeChars.charAt(c1 >> 2);
  out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  out += base64EncodeChars.charAt((c2 & 0xF) << 2);
  out += "=";
  break;
  }
  c3 = str.charCodeAt(i++);
  out += base64EncodeChars.charAt(c1 >> 2);
  out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
  out += base64EncodeChars.charAt(c3 & 0x3F);
  }
  return out;
  }
 
  function base64decode(str) {
  var c1, c2, c3, c4;
  var i, len, out;
 
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
  /* c1 */
  do {
  c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  } while(i < len && c1 == -1);
  if(c1 == -1)
  break;
 
  /* c2 */
  do {
  c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
  } while(i < len && c2 == -1);
  if(c2 == -1)
  break;
 
  out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
 
  /* c3 */
  do {
  c3 = str.charCodeAt(i++) & 0xff;
  if(c3 == 61)
  return out;
  c3 = base64DecodeChars[c3];
  } while(i < len && c3 == -1);
  if(c3 == -1)
  break;
 
  out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
 
  /* c4 */
  do {
  c4 = str.charCodeAt(i++) & 0xff;
  if(c4 == 61)
  return out;
  c4 = base64DecodeChars[c4];
  } while(i < len && c4 == -1);
  if(c4 == -1)
  break;
  out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
  }
  return out;
  }
 
  if (!window.btoa) window.btoa = base64encode;
  if (!window.atob) window.atob = base64decode;
 
  })();
  /*!
  * bean.js - copyright Jacob Thornton 2011
  * https://github.com/fat/bean
  * MIT License
  * special thanks to:
  * dean edwards: http://dean.edwards.name/
  * dperini: https://github.com/dperini/nwevents
  * the entire mootools team: github.com/mootools/mootools-core
  *//*global module:true, define:true*/
  !function(a,b,c){typeof module!="undefined"?module.exports=c(a,b):typeof define=="function"&&typeof define.amd=="object"?define(c):b[a]=c(a,b)}("bean",this,function(a,b){var c=window,d=b[a],e=/over|out/,f=/[^\.]*(?=\..*)\.|.*/,g=/\..*/,h="addEventListener",i="attachEvent",j="removeEventListener",k="detachEvent",l=document||{},m=l.documentElement||{},n=m[h],o=n?h:i,p=Array.prototype.slice,q=/click|mouse|menu|drag|drop/i,r=/^touch|^gesture/i,s={one:1},t=function(a,b,c){for(c=0;c<b.length;c++)a[b[c]]=1;return a}({},("click dblclick mouseup mousedown contextmenu mousewheel DOMMouseScroll mouseover mouseout mousemove selectstart selectend keydown keypress keyup orientationchange focus blur change reset select submit load unload beforeunload resize move DOMContentLoaded readystatechange error abort scroll "+(n?"show input invalid touchstart touchmove touchend touchcancel gesturestart gesturechange gestureend message readystatechange pageshow pagehide popstate hashchange offline online afterprint beforeprint dragstart dragenter dragover dragleave drag drop dragend loadstart progress suspend emptied stalled loadmetadata loadeddata canplay canplaythrough playing waiting seeking seeked ended durationchange timeupdate play pause ratechange volumechange cuechange checking noupdate downloading cached updateready obsolete ":"")).split(" ")),u=function(){function a(a,b){while((b=b.parentNode)!==null)if(b===a)return!0;return!1}function b(b){var c=b.relatedTarget;return c?c!==this&&c.prefix!=="xul"&&!/document/.test(this.toString())&&!a(this,c):c===null}return{mouseenter:{base:"mouseover",condition:b},mouseleave:{base:"mouseout",condition:b},mousewheel:{base:/Firefox/.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel"}}}(),v=function(){var a="altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which".split(" "),b=a.concat("button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" ")),c=a.concat("char charCode key keyCode".split(" ")),d=a.concat("touches targetTouches changedTouches scale rotation".split(" ")),f="preventDefault",g=function(a){return function(){a[f]?a[f]():a.returnValue=!1}},h="stopPropagation",i=function(a){return function(){a[h]?a[h]():a.cancelBubble=!0}},j=function(a){return function(){a[f](),a[h](),a.stopped=!0}},k=function(a,b,c){var d,e;for(d=c.length;d--;)e=c[d],!(e in b)&&e in a&&(b[e]=a[e])};return function(n,o){var p={originalEvent:n,isNative:o};if(!n)return p;var s,t=n.type,u=n.target||n.srcElement;p[f]=g(n),p[h]=i(n),p.stop=j(p),p.target=u&&u.nodeType===3?u.parentNode:u;if(o){if(t.indexOf("key")!==-1)s=c,p.keyCode=n.which||n.keyCode;else if(q.test(t)){s=b,p.rightClick=n.which===3||n.button===2,p.pos={x:0,y:0};if(n.pageX||n.pageY)p.clientX=n.pageX,p.clientY=n.pageY;else if(n.clientX||n.clientY)p.clientX=n.clientX+l.body.scrollLeft+m.scrollLeft,p.clientY=n.clientY+l.body.scrollTop+m.scrollTop;e.test(t)&&(p.relatedTarget=n.relatedTarget||n[(t==="mouseover"?"from":"to")+"Element"])}else r.test(t)&&(s=d);k(n,p,s||a)}return p}}(),w=function(a,b){return!n&&!b&&(a===l||a===c)?m:a},x=function(){function a(a,b,c,d,e){this.element=a,this.type=b,this.handler=c,this.original=d,this.namespaces=e,this.custom=u[b],this.isNative=t[b]&&a[o],this.eventType=n||this.isNative?b:"propertychange",this.customType=!n&&!this.isNative&&b,this.target=w(a,this.isNative),this.eventSupport=this.target[o]}return a.prototype={inNamespaces:function(a){var b,c;if(!a)return!0;if(!this.namespaces)return!1;for(b=a.length;b--;)for(c=this.namespaces.length;c--;)if(a[b]===this.namespaces[c])return!0;return!1},matches:function(a,b,c){return this.element===a&&(!b||this.original===b)&&(!c||this.handler===c)}},a}(),y=function(){var a={},b=function(c,d,e,f,g){if(!d||d==="*")for(var h in a)h.charAt(0)==="$"&&b(c,h.substr(1),e,f,g);else{var i=0,j,k=a["$"+d],l=c==="*";if(!k)return;for(j=k.length;i<j;i++)if(l||k[i].matches(c,e,f))if(!g(k[i],k,i,d))return}},c=function(b,c,d){var e,f=a["$"+c];if(f)for(e=f.length;e--;)if(f[e].matches(b,d,null))return!0;return!1},d=function(a,c,d){var e=[];return b(a,c,d,null,function(a){return e.push(a)}),e},e=function(b){return(a["$"+b.type]||(a["$"+b.type]=[])).push(b),b},f=function(c){b(c.element,c.type,null,c.handler,function(b,c,d){return c.splice(d,1),c.length===0&&delete a["$"+b.type],!1})},g=function(){var b,c=[];for(b in a)b.charAt(0)==="$"&&(c=c.concat(a[b]));return c};return{has:c,get:d,put:e,del:f,entries:g}}(),z=n?function(a,b,c,d){a[d?h:j](b,c,!1)}:function(a,b,c,d,e){e&&d&&a["_on"+e]===null&&(a["_on"+e]=0),a[d?i:k]("on"+b,c)},A=function(a,b,d){return function(e){return e=v(e||((this.ownerDocument||this.document||this).parentWindow||c).event,!0),b.apply(a,[e].concat(d))}},B=function(a,b,d,e,f,g){return function(h){if(e?e.apply(this,arguments):n?!0:h&&h.propertyName==="_on"+d||!h)h&&(h=v(h||((this.ownerDocument||this.document||this).parentWindow||c).event,g)),b.apply(a,h&&(!f||f.length===0)?arguments:p.call(arguments,h?0:1).concat(f))}},C=function(a,b,c,d,e){return function(){a(b,c,e),d.apply(this,arguments)}},D=function(a,b,c,d){var e,f,h,i=b&&b.replace(g,""),j=y.get(a,i,c);for(e=0,f=j.length;e<f;e++)j[e].inNamespaces(d)&&((h=j[e]).eventSupport&&z(h.target,h.eventType,h.handler,!1,h.type),y.del(h))},E=function(a,b,c,d,e){var h,i=b.replace(g,""),j=b.replace(f,"").split(".");if(y.has(a,i,c))return a;i==="unload"&&(c=C(D,a,i,c,d)),u[i]&&(u[i].condition&&(c=B(a,c,i,u[i].condition,!0)),i=u[i].base||i),h=y.put(new x(a,i,c,d,j[0]&&j)),h.handler=h.isNative?A(a,h.handler,e):B(a,h.handler,i,!1,e,!1),h.eventSupport&&z(h.target,h.eventType,h.handler,!0,h.customType)},F=function(a,b,c){return function(d){var e,f,g=typeof a=="string"?c(a,this):a;for(e=d.target;e&&e!==this;e=e.parentNode)for(f=g.length;f--;)if(g[f]===e)return b.apply(e,arguments)}},G=function(a,b,c){var d,e,h,i,j,k=D,l=b&&typeof b=="string";if(l&&b.indexOf(" ")>0){b=b.split(" ");for(j=b.length;j--;)G(a,b[j],c);return a}h=l&&b.replace(g,""),h&&u[h]&&(h=u[h].type);if(!b||l){if(i=l&&b.replace(f,""))i=i.split(".");k(a,h,c,i)}else if(typeof b=="function")k(a,null,b);else for(d in b)b.hasOwnProperty(d)&&G(a,d,b[d]);return a},H=function(a,b,c,d,e){var f,g,h,i,j=c,k=c&&typeof c=="string";if(b&&!c&&typeof b=="object")for(f in b)b.hasOwnProperty(f)&&H.apply(this,[a,f,b[f]]);else{i=arguments.length>3?p.call(arguments,3):[],g=(k?c:b).split(" "),k&&(c=F(b,j=d,e))&&(i=p.call(i,1)),this===s&&(c=C(G,a,b,c,j));for(h=g.length;h--;)E(a,g[h],c,j,i)}return a},I=function(){return H.apply(s,arguments)},J=n?function(a,b,d){var e=l.createEvent(a?"HTMLEvents":"UIEvents");e[a?"initEvent":"initUIEvent"](b,!0,!0,c,1),d.dispatchEvent(e)}:function(a,b,c){c=w(c,a),a?c.fireEvent("on"+b,l.createEventObject()):c["_on"+b]++},K=function(a,b,c){var d,e,h,i,j,k=b.split(" ");for(d=k.length;d--;){b=k[d].replace(g,"");if(i=k[d].replace(f,""))i=i.split(".");if(!i&&!c&&a[o])J(t[b],b,a);else{j=y.get(a,b),c=[!1].concat(c);for(e=0,h=j.length;e<h;e++)j[e].inNamespaces(i)&&j[e].handler.apply(a,c)}}return a},L=function(a,b,c){var d=0,e=y.get(b,c),f=e.length;for(;d<f;d++)e[d].original&&H(a,e[d].type,e[d].original);return a},M={add:H,one:I,remove:G,clone:L,fire:K,noConflict:function(){return b[a]=d,this}};if(c[i]){var N=function(){var a,b=y.entries();for(a in b)b[a].type&&b[a].type!=="unload"&&G(b[a].element,b[a].type);c[k]("onunload",N),c.CollectGarbage&&c.CollectGarbage()};c[i]("onunload",N)}return M})
  /*!
  * bean.js - copyright Jacob Thornton 2011
  * https://github.com/fat/bean
  * MIT License
  * special thanks to:
  * dean edwards: http://dean.edwards.name/
  * dperini: https://github.com/dperini/nwevents
  * the entire mootools team: github.com/mootools/mootools-core
  */
  /*global module:true, define:true*/
  !function (name, context, definition) {
  if (typeof module !== 'undefined') module.exports = definition(name, context);
  else if (typeof define === 'function' && typeof define.amd === 'object') define(definition);
  else context[name] = definition(name, context);
  }('bean', this, function (name, context) {
  var win = window
  , old = context[name]
  , overOut = /over|out/
  , namespaceRegex = /[^\.]*(?=\..*)\.|.*/
  , nameRegex = /\..*/
  , addEvent = 'addEventListener'
  , attachEvent = 'attachEvent'
  , removeEvent = 'removeEventListener'
  , detachEvent = 'detachEvent'
  , doc = document || {}
  , root = doc.documentElement || {}
  , W3C_MODEL = root[addEvent]
  , eventSupport = W3C_MODEL ? addEvent : attachEvent
  , slice = Array.prototype.slice
  , mouseTypeRegex = /click|mouse|menu|drag|drop/i
  , touchTypeRegex = /^touch|^gesture/i
  , ONE = { one: 1 } // singleton for quick matching making add() do one()
 
  , nativeEvents = (function (hash, events, i) {
  for (i = 0; i < events.length; i++)
  hash[events[i]] = 1
  return hash
  })({}, (
  'click dblclick mouseup mousedown contextmenu ' + // mouse buttons
  'mousewheel DOMMouseScroll ' + // mouse wheel
  'mouseover mouseout mousemove selectstart selectend ' + // mouse movement
  'keydown keypress keyup ' + // keyboard
  'orientationchange ' + // mobile
  'focus blur change reset select submit ' + // form elements
  'load unload beforeunload resize move DOMContentLoaded readystatechange ' + // window
  'error abort scroll ' + // misc
  (W3C_MODEL ? // element.fireEvent('onXYZ'... is not forgiving if we try to fire an event
  // that doesn't actually exist, so make sure we only do these on newer browsers
  'show ' + // mouse buttons
  'input invalid ' + // form elements
  'touchstart touchmove touchend touchcancel ' + // touch
  'gesturestart gesturechange gestureend ' + // gesture
  'message readystatechange pageshow pagehide popstate ' + // window
  'hashchange offline online ' + // window
  'afterprint beforeprint ' + // printing
  'dragstart dragenter dragover dragleave drag drop dragend ' + // dnd
  'loadstart progress suspend emptied stalled loadmetadata ' + // media
  'loadeddata canplay canplaythrough playing waiting seeking ' + // media
  'seeked ended durationchange timeupdate play pause ratechange ' + // media
  'volumechange cuechange ' + // media
  'checking noupdate downloading cached updateready obsolete ' + // appcache
  '' : '')
  ).split(' ')
  )
 
  , customEvents = (function () {
  function isDescendant(parent, node) {
  while ((node = node.parentNode) !== null) {
  if (node === parent) return true
  }
  return false
  }
 
  function check(event) {
  var related = event.relatedTarget
  if (!related) return related === null
  return (related !== this && related.prefix !== 'xul' && !/document/.test(this.toString()) && !isDescendant(this, related))
  }
 
  return {
  mouseenter: { base: 'mouseover', condition: check }
  , mouseleave: { base: 'mouseout', condition: check }
  , mousewheel: { base: /Firefox/.test(navigator.userAgent) ? 'DOMMouseScroll' : 'mousewheel' }
  }
  })()
 
  , fixEvent = (function () {
  var commonProps = 'altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which'.split(' ')
  , mouseProps = commonProps.concat('button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement'.split(' '))
  , keyProps = commonProps.concat('char charCode key keyCode'.split(' '))
  , touchProps = commonProps.concat('touches targetTouches changedTouches scale rotation'.split(' '))
  , preventDefault = 'preventDefault'
  , createPreventDefault = function (event) {
  return function () {
  if (event[preventDefault])
  event[preventDefault]()
  else
  event.returnValue = false
  }
  }
  , stopPropagation = 'stopPropagation'
  , createStopPropagation = function (event) {
  return function () {
  if (event[stopPropagation])
  event[stopPropagation]()
  else
  event.cancelBubble = true
  }
  }
  , createStop = function (synEvent) {
  return function () {
  synEvent[preventDefault]()
  synEvent[stopPropagation]()
  synEvent.stopped = true
  }
  }
  , copyProps = function (event, result, props) {
  var i, p
  for (i = props.length; i--;) {
  p = props[i]
  if (!(p in result) && p in event) result[p] = event[p]
  }
  }
 
  return function (event, isNative) {
  var result = { originalEvent: event, isNative: isNative }
  if (!event)
  return result
 
  var props
  , type = event.type
  , target = event.target || event.srcElement
 
  result[preventDefault] = createPreventDefault(event)
  result[stopPropagation] = createStopPropagation(event)
  result.stop = createStop(result)
  result.target = target && target.nodeType === 3 ? target.parentNode : target
 
  if (isNative) { // we only need basic augmentation on custom events, the rest is too expensive
  if (type.indexOf('key') !== -1) {
  props = keyProps
  result.keyCode = event.which || event.keyCode
  } else if (mouseTypeRegex.test(type)) {
  props = mouseProps
  result.rightClick = event.which === 3 || event.button === 2
  result.pos = { x: 0, y: 0 }
  if (event.pageX || event.pageY) {
  result.clientX = event.pageX
  result.clientY = event.pageY
  } else if (event.clientX || event.clientY) {
  result.clientX = event.clientX + doc.body.scrollLeft + root.scrollLeft
  result.clientY = event.clientY + doc.body.scrollTop + root.scrollTop
  }
  if (overOut.test(type))
  result.relatedTarget = event.relatedTarget || event[(type === 'mouseover' ? 'from' : 'to') + 'Element']
  } else if (touchTypeRegex.test(type)) {
  props = touchProps
  }
  copyProps(event, result, props || commonProps)
  }
  return result
  }
  })()
 
  // if we're in old IE we can't do onpropertychange on doc or win so we use doc.documentElement for both
  , targetElement = function (element, isNative) {
  return !W3C_MODEL && !isNative && (element === doc || element === win) ? root : element
  }
 
  // we use one of these per listener, of any type
  , RegEntry = (function () {
  function entry(element, type, handler, original, namespaces) {
  this.element = element
  this.type = type
  this.handler = handler
  this.original = original
  this.namespaces = namespaces
  this.custom = customEvents[type]
  this.isNative = nativeEvents[type] && element[eventSupport]
  this.eventType = W3C_MODEL || this.isNative ? type : 'propertychange'
  this.customType = !W3C_MODEL && !this.isNative && type
  this.target = targetElement(element, this.isNative)
  this.eventSupport = this.target[eventSupport]
  }
 
  entry.prototype = {
  // given a list of namespaces, is our entry in any of them?
  inNamespaces: function (checkNamespaces) {
  var i, j
  if (!checkNamespaces)
  return true
  if (!this.namespaces)
  return false
  for (i = checkNamespaces.length; i--;) {
  for (j = this.namespaces.length; j--;) {
  if (checkNamespaces[i] === this.namespaces[j])
  return true
  }
  }
  return false
  }
 
  // match by element, original fn (opt), handler fn (opt)
  , matches: function (checkElement, checkOriginal, checkHandler) {
  return this.element === checkElement &&
  (!checkOriginal || this.original === checkOriginal) &&
  (!checkHandler || this.handler === checkHandler)
  }
  }
 
  return entry
  })()
 
  , registry = (function () {
  // our map stores arrays by event type, just because it's better than storing
  // everything in a single array. uses '$' as a prefix for the keys for safety
  var map = {}
 
  // generic functional search of our registry for matching listeners,
  // `fn` returns false to break out of the loop
  , forAll = function (element, type, original, handler, fn) {
  if (!type || type === '*') {
  // search the whole registry
  for (var t in map) {
  if (t.charAt(0) === '$')
  forAll(element, t.substr(1), original, handler, fn)
  }
  } else {
  var i = 0, l, list = map['$' + type], all = element === '*'
  if (!list)
  return
  for (l = list.length; i < l; i++) {
  if (all || list[i].matches(element, original, handler))
  if (!fn(list[i], list, i, type))
  return
  }
  }
  }
 
  , has = function (element, type, original) {
  // we're not using forAll here simply because it's a bit slower and this
  // needs to be fast
  var i, list = map['$' + type]
  if (list) {
  for (i = list.length; i--;) {
  if (list[i].matches(element, original, null))
  return true
  }
  }
  return false
  }
 
  , get = function (element, type, original) {
  var entries = []
  forAll(element, type, original, null, function (entry) { return entries.push(entry) })
  return entries
  }
 
  , put = function (entry) {
  (map['$' + entry.type] || (map['$' + entry.type] = [])).push(entry)
  return entry
  }
 
  , del = function (entry) {
  forAll(entry.element, entry.type, null, entry.handler, function (entry, list, i) {
  list.splice(i, 1)
  if (list.length === 0)
  delete map['$' + entry.type]
  return false
  })
  }
 
  // dump all entries, used for onunload
  , entries = function () {
  var t, entries = []
  for (t in map) {
  if (t.charAt(0) === '$')
  entries = entries.concat(map[t])
  }
  return entries
  }
 
  return { has: has, get: get, put: put, del: del, entries: entries }
  })()
 
  // add and remove listeners to DOM elements
  , listener = W3C_MODEL ? function (element, type, fn, add) {
  element[add ? addEvent : removeEvent](type, fn, false)
  } : function (element, type, fn, add, custom) {
  if (custom && add && element['_on' + custom] === null)
  element['_on' + custom] = 0
  element[add ? attachEvent : detachEvent]('on' + type, fn)
  }
 
  , nativeHandler = function (element, fn, args) {
  return function (event) {
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, true)
  return fn.apply(element, [event].concat(args))
  }
  }
 
  , customHandler = function (element, fn, type, condition, args, isNative) {
  return function (event) {
  if (condition ? condition.apply(this, arguments) : W3C_MODEL ? true : event && event.propertyName === '_on' + type || !event) {
  if (event)
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, isNative)
  fn.apply(element, event && (!args || args.length === 0) ? arguments : slice.call(arguments, event ? 0 : 1).concat(args))
  }
  }
  }
 
  , once = function (rm, element, type, fn, originalFn) {
  // wrap the handler in a handler that does a remove as well
  return function () {
  rm(element, type, originalFn)
  fn.apply(this, arguments)
  }
  }
 
  , removeListener = function (element, orgType, handler, namespaces) {
  var i, l, entry
  , type = (orgType && orgType.replace(nameRegex, ''))
  , handlers = registry.get(element, type, handler)
 
  for (i = 0, l = handlers.length; i < l; i++) {
  if (handlers[i].inNamespaces(namespaces)) {
  if ((entry = handlers[i]).eventSupport)
  listener(entry.target, entry.eventType, entry.handler, false, entry.type)
  // TODO: this is problematic, we have a registry.get() and registry.del() that
  // both do registry searches so we waste cycles doing this. Needs to be rolled into
  // a single registry.forAll(fn) that removes while finding, but the catch is that
  // we'll be splicing the arrays that we're iterating over. Needs extra tests to
  // make sure we don't screw it up. @rvagg
  registry.del(entry)
  }
  }
  }
 
  , addListener = function (element, orgType, fn, originalFn, args) {
  var entry
  , type = orgType.replace(nameRegex, '')
  , namespaces = orgType.replace(namespaceRegex, '').split('.')
 
  if (registry.has(element, type, fn))
  return element // no dupe
  if (type === 'unload')
  fn = once(removeListener, element, type, fn, originalFn) // self clean-up
  if (customEvents[type]) {
  if (customEvents[type].condition)
  fn = customHandler(element, fn, type, customEvents[type].condition, true)
  type = customEvents[type].base || type
  }
  entry = registry.put(new RegEntry(element, type, fn, originalFn, namespaces[0] && namespaces))
  entry.handler = entry.isNative ?
  nativeHandler(element, entry.handler, args) :
  customHandler(element, entry.handler, type, false, args, false)
  if (entry.eventSupport)
  listener(entry.target, entry.eventType, entry.handler, true, entry.customType)
  }
 
  , del = function (selector, fn, $) {
  return function (e) {
  var target, i, array = typeof selector === 'string' ? $(selector, this) : selector
  for (target = e.target; target && target !== this; target = target.parentNode) {
  for (i = array.length; i--;) {
  if (array[i] === target) {
  return fn.apply(target, arguments)
  }
  }
  }
  }
  }
 
  , remove = function (element, typeSpec, fn) {
  var k, m, type, namespaces, i
  , rm = removeListener
  , isString = typeSpec && typeof typeSpec === 'string'
 
  if (isString && typeSpec.indexOf(' ') > 0) {
  // remove(el, 't1 t2 t3', fn) or remove(el, 't1 t2 t3')
  typeSpec = typeSpec.split(' ')
  for (i = typeSpec.length; i--;)
  remove(element, typeSpec[i], fn)
  return element
  }
  type = isString && typeSpec.replace(nameRegex, '')
  if (type && customEvents[type])
  type = customEvents[type].type
  if (!typeSpec || isString) {
  // remove(el) or remove(el, t1.ns) or remove(el, .ns) or remove(el, .ns1.ns2.ns3)
  if (namespaces = isString && typeSpec.replace(namespaceRegex, ''))
  namespaces = namespaces.split('.')
  rm(element, type, fn, namespaces)
  } else if (typeof typeSpec === 'function') {
  // remove(el, fn)
  rm(element, null, typeSpec)
  } else {
  // remove(el, { t1: fn1, t2, fn2 })
  for (k in typeSpec) {
  if (typeSpec.hasOwnProperty(k))
  remove(element, k, typeSpec[k])
  }
  }
  return element
  }
 
  , add = function (element, events, fn, delfn, $) {
  var type, types, i, args
  , originalFn = fn
  , isDel = fn && typeof fn === 'string'
 
  if (events && !fn && typeof events === 'object') {
  for (type in events) {
  if (events.hasOwnProperty(type))
  add.apply(this, [ element, type, events[type] ])
  }
  } else {
  args = arguments.length > 3 ? slice.call(arguments, 3) : []
  types = (isDel ? fn : events).split(' ')
  isDel && (fn = del(events, (originalFn = delfn), $)) && (args = slice.call(args, 1))
  // special case for one()
  this === ONE && (fn = once(remove, element, events, fn, originalFn))
  for (i = types.length; i--;) addListener(element, types[i], fn, originalFn, args)
  }
  return element
  }
 
  , one = function () {
  return add.apply(ONE, arguments)
  }
 
  , fireListener = W3C_MODEL ? function (isNative, type, element) {
  var evt = doc.createEvent(isNative ? 'HTMLEvents' : 'UIEvents')
  evt[isNative ? 'initEvent' : 'initUIEvent'](type, true, true, win, 1)
  element.dispatchEvent(evt)
  } : function (isNative, type, element) {
  element = targetElement(element, isNative)
  // if not-native then we're using onpropertychange so we just increment a custom property
  isNative ? element.fireEvent('on' + type, doc.createEventObject()) : element['_on' + type]++
  }
 
  , fire = function (element, type, args) {
  var i, j, l, names, handlers
  , types = type.split(' ')
 
  for (i = types.length; i--;) {
  type = types[i].replace(nameRegex, '')
  if (names = types[i].replace(namespaceRegex, ''))
  names = names.split('.')
  if (!names && !args && element[eventSupport]) {
  fireListener(nativeEvents[type], type, element)
  } else {
  // non-native event, either because of a namespace, arguments or a non DOM element
  // iterate over all listeners and manually 'fire'
  handlers = registry.get(element, type)
  args = [false].concat(args)
  for (j = 0, l = handlers.length; j < l; j++) {
  if (handlers[j].inNamespaces(names))
  handlers[j].handler.apply(element, args)
  }
  }
  }
  return element
  }
 
  , clone = function (element, from, type) {
  var i = 0
  , handlers = registry.get(from, type)
  , l = handlers.length
 
  for (;i < l; i++)
  handlers[i].original && add(element, handlers[i].type, handlers[i].original)
  return element
  }
 
  , bean = {
  add: add
  , one: one
  , remove: remove
  , clone: clone
  , fire: fire
  , noConflict: function () {
  context[name] = old
  return this
  }
  }
 
  if (win[attachEvent]) {
  // for IE, clean up on unload to avoid leaks
  var cleanup = function () {
  var i, entries = registry.entries()
  for (i in entries) {
  if (entries[i].type && entries[i].type !== 'unload')
  remove(entries[i].element, entries[i].type)
  }
  win[detachEvent]('onunload', cleanup)
  win.CollectGarbage && win.CollectGarbage()
  }
  win[attachEvent]('onunload', cleanup)
  }
 
  return bean
  });
 
  /*
  * Canvas2Image v0.1
  * Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com
  * MIT License [http://www.opensource.org/licenses/mit-license.php]
  */
 
  var Canvas2Image = (function() {
  // check if we have canvas support
  var oCanvas = document.createElement("canvas"),
  sc = String.fromCharCode,
  strDownloadMime = "image/octet-stream",
  bReplaceDownloadMime = false;
 
  // no canvas, bail out.
  if (!oCanvas.getContext) {
  return {
  saveAsBMP : function(){},
  saveAsPNG : function(){},
  saveAsJPEG : function(){}
  }
  }
 
  var bHasImageData = !!(oCanvas.getContext("2d").getImageData),
  bHasDataURL = !!(oCanvas.toDataURL),
  bHasBase64 = !!(window.btoa);
 
  // ok, we're good
  var readCanvasData = function(oCanvas) {
  var iWidth = parseInt(oCanvas.width),
  iHeight = parseInt(oCanvas.height);
  return oCanvas.getContext("2d").getImageData(0,0,iWidth,iHeight);
  }
 
  // base64 encodes either a string or an array of charcodes
  var encodeData = function(data) {
  var i, aData, strData = "";
 
  if (typeof data == "string") {
  strData = data;
  } else {
  aData = data;
  for (i = 0; i < aData.length; i++) {
  strData += sc(aData[i]);
  }
  }
  return btoa(strData);
  }
 
  // creates a base64 encoded string containing BMP data takes an imagedata object as argument
  var createBMP = function(oData) {
  var strHeader = '',
  iWidth = oData.width,
  iHeight = oData.height;
 
  strHeader += 'BM';
 
  var iFileSize = iWidth*iHeight*4 + 54; // total header size = 54 bytes
  strHeader += sc(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
  strHeader += sc(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
  strHeader += sc(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
  strHeader += sc(iFileSize % 256);
 
  strHeader += sc(0, 0, 0, 0, 54, 0, 0, 0); // data offset
  strHeader += sc(40, 0, 0, 0); // info header size
 
  var iImageWidth = iWidth;
  strHeader += sc(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
  strHeader += sc(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
  strHeader += sc(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
  strHeader += sc(iImageWidth % 256);
 
  var iImageHeight = iHeight;
  strHeader += sc(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
  strHeader += sc(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
  strHeader += sc(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
  strHeader += sc(iImageHeight % 256);
 
  strHeader += sc(1, 0, 32, 0); // num of planes & num of bits per pixel
  strHeader += sc(0, 0, 0, 0); // compression = none
 
  var iDataSize = iWidth*iHeight*4;
  strHeader += sc(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
  strHeader += sc(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
  strHeader += sc(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
  strHeader += sc(iDataSize % 256);
 
  strHeader += sc(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // these bytes are not used
 
  var aImgData = oData.data,
  strPixelData = "",
  c, x, y = iHeight,
  iOffsetX, iOffsetY, strPixelRow;
 
  do {
  iOffsetY = iWidth*(y-1)*4;
  strPixelRow = "";
  for (x = 0; x < iWidth; x++) {
  iOffsetX = 4*x;
  strPixelRow += sc(
  aImgData[iOffsetY + iOffsetX + 2], // B
  aImgData[iOffsetY + iOffsetX + 1], // G
  aImgData[iOffsetY + iOffsetX], // R
  aImgData[iOffsetY + iOffsetX + 3] // A
  );
  }
  strPixelData += strPixelRow;
  } while (--y);
 
  return encodeData(strHeader + strPixelData);
  }
 
  // sends the generated file to the client
  var saveFile = function(strData) {
  if (!window.open(strData)) {
  document.location.href = strData;
  }
  }
 
  var makeDataURI = function(strData, strMime) {
  return "data:" + strMime + ";base64," + strData;
  }
 
  // generates a <img> object containing the imagedata
  var makeImageObject = function(strSource) {
  var oImgElement = document.createElement("img");
  oImgElement.src = strSource;
  return oImgElement;
  }
 
  var scaleCanvas = function(oCanvas, iWidth, iHeight) {
  if (iWidth && iHeight) {
  var oSaveCanvas = document.createElement("canvas");
 
  oSaveCanvas.width = iWidth;
  oSaveCanvas.height = iHeight;
  oSaveCanvas.style.width = iWidth+"px";
  oSaveCanvas.style.height = iHeight+"px";
 
  var oSaveCtx = oSaveCanvas.getContext("2d");
 
  oSaveCtx.drawImage(oCanvas, 0, 0, oCanvas.width, oCanvas.height, 0, 0, iWidth, iWidth);
 
  return oSaveCanvas;
  }
  return oCanvas;
  }
 
  return {
  saveAsPNG : function(oCanvas, bReturnImg, iWidth, iHeight) {
  if (!bHasDataURL) return false;
 
  var oScaledCanvas = scaleCanvas(oCanvas, iWidth, iHeight),
  strMime = "image/png",
  strData = oScaledCanvas.toDataURL(strMime);
 
  if (bReturnImg) {
  return makeImageObject(strData);
  } else {
  saveFile(bReplaceDownloadMime ? strData.replace(strMime, strDownloadMime) : strData);
  }
  return true;
  },
 
  saveAsJPEG : function(oCanvas, bReturnImg, iWidth, iHeight) {
  if (!bHasDataURL) return false;
 
  var oScaledCanvas = scaleCanvas(oCanvas, iWidth, iHeight),
  strMime = "image/jpeg",
  strData = oScaledCanvas.toDataURL(strMime);
 
  // check if browser actually supports jpeg by looking for the mime type in the data uri. if not, return false
  if (strData.indexOf(strMime) != 5) return false;
 
  if (bReturnImg) {
  return makeImageObject(strData);
  } else {
  saveFile(bReplaceDownloadMime ? strData.replace(strMime, strDownloadMime) : strData);
  }
  return true;
  },
 
  saveAsBMP : function(oCanvas, bReturnImg, iWidth, iHeight) {
  if (!(bHasDataURL && bHasImageData && bHasBase64)) return false;
 
  var oScaledCanvas = scaleCanvas(oCanvas, iWidth, iHeight),
  strMime = "image/bmp",
  oData = readCanvasData(oScaledCanvas),
  strImgData = createBMP(oData);
 
  if (bReturnImg) {
  return makeImageObject(makeDataURI(strImgData, strMime));
  } else {
  saveFile(makeDataURI(strImgData, strMime));
  }
  return true;
  }
  };
  })();
  /**
  * This code is released to the public domain by Jim Studt, 2007.
  * He may keep some sort of up to date copy at http://www.federated.com/~jim/canvastext/
 
  * A partial support for special characters has been added too.
  */
  var CanvasText = {
  /** The letters definition. It is a list of letters,
  * with their width, and the coordinates of points compositing them.
  * The syntax for the points is : [x, y], null value means "pen up"
  */
  letters: {
  '\n':{ width: -1, points: [] },
  ' ': { width: 10, points: [] },
  '!': { width: 10, points: [[5,21],[5,7],null,[5,2],[4,1],[5,0],[6,1],[5,2]] },
  '"': { width: 16, points: [[4,21],[4,14],null,[12,21],[12,14]] },
  '#': { width: 21, points: [[11,25],[4,-7],null,[17,25],[10,-7],null,[4,12],[18,12],null,[3,6],[17,6]] },
  '$': { width: 20, points: [[8,25],[8,-4],null,[12,25],[12,-4],null,[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] },
  '%': { width: 24, points: [[21,21],[3,0],null,[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],null,[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]] },
  '&': { width: 26, points: [[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]] },
  '\'':{ width: 10, points: [[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]] },
  '(': { width: 14, points: [[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]] },
  ')': { width: 14, points: [[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]] },
  '*': { width: 16, points: [[8,21],[8,9],null,[3,18],[13,12],null,[13,18],[3,12]] },
  '+': { width: 26, points: [[13,18],[13,0],null,[4,9],[22,9]] },
  ',': { width: 10, points: [[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] },
  '-': { width: 26, points: [[4,9],[22,9]] },
  '.': { width: 10, points: [[5,2],[4,1],[5,0],[6,1],[5,2]] },
  '/': { width: 22, points: [[20,25],[2,-7]] },
  '0': { width: 20, points: [[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]] },
  '1': { width: 20, points: [[6,17],[8,18],[11,21],[11,0]] },
  '2': { width: 20, points: [[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]] },
  '3': { width: 20, points: [[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] },
  '4': { width: 20, points: [[13,21],[3,7],[18,7],null,[13,21],[13,0]] },
  '5': { width: 20, points: [[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] },
  '6': { width: 20, points: [[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]] },
  '7': { width: 20, points: [[17,21],[7,0],null,[3,21],[17,21]] },
  '8': { width: 20, points: [[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]] },
  '9': { width: 20, points: [[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]] },
  ':': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],null,[5,2],[4,1],[5,0],[6,1],[5,2]] },
  ';': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],null,[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] },
  '<': { width: 24, points: [[20,18],[4,9],[20,0]] },
  '=': { width: 26, points: [[4,12],[22,12],null,[4,6],[22,6]] },
  '>': { width: 24, points: [[4,18],[20,9],[4,0]] },
  '?': { width: 18, points: [[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],null,[9,2],[8,1],[9,0],[10,1],[9,2]] },
  '@': { width: 27, points: [[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],null,[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],null,[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],null,[19,16],[18,8],[18,6],[19,5]] },
  'A': { width: 18, points: [[9,21],[1,0],null,[9,21],[17,0],null,[4,7],[14,7]] },
  'B': { width: 21, points: [[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],null,[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]] },
  'C': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]] },
  'D': { width: 21, points: [[4,21],[4,0],null,[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]] },
  'E': { width: 19, points: [[4,21],[4,0],null,[4,21],[17,21],null,[4,11],[12,11],null,[4,0],[17,0]] },
  'F': { width: 18, points: [[4,21],[4,0],null,[4,21],[17,21],null,[4,11],[12,11]] },
  'G': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],null,[13,8],[18,8]] },
  'H': { width: 22, points: [[4,21],[4,0],null,[18,21],[18,0],null,[4,11],[18,11]] },
  'I': { width: 8, points: [[4,21],[4,0]] },
  'J': { width: 16, points: [[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]] },
  'K': { width: 21, points: [[4,21],[4,0],null,[18,21],[4,7],null,[9,12],[18,0]] },
  'L': { width: 17, points: [[4,21],[4,0],null,[4,0],[16,0]] },
  'M': { width: 24, points: [[4,21],[4,0],null,[4,21],[12,0],null,[20,21],[12,0],null,[20,21],[20,0]] },
  'N': { width: 22, points: [[4,21],[4,0],null,[4,21],[18,0],null,[18,21],[18,0]] },
  'O': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]] },
  'P': { width: 21, points: [[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]] },
  'Q': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],null,[12,4],[18,-2]] },
  'R': { width: 21, points: [[4,21],[4,0],null,[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],null,[11,11],[18,0]] },
  'S': { width: 20, points: [[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] },
  'T': { width: 16, points: [[8,21],[8,0],null,[1,21],[15,21]] },
  'U': { width: 22, points: [[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]] },
  'V': { width: 18, points: [[1,21],[9,0],null,[17,21],[9,0]] },
  'W': { width: 24, points: [[2,21],[7,0],null,[12,21],[7,0],null,[12,21],[17,0],null,[22,21],[17,0]] },
  'X': { width: 20, points: [[3,21],[17,0],null,[17,21],[3,0]] },
  'Y': { width: 18, points: [[1,21],[9,11],[9,0],null,[17,21],[9,11]] },
  'Z': { width: 20, points: [[17,21],[3,0],null,[3,21],[17,21],null,[3,0],[17,0]] },
  '[': { width: 14, points: [[4,25],[4,-7],null,[5,25],[5,-7],null,[4,25],[11,25],null,[4,-7],[11,-7]] },
  '\\':{ width: 14, points: [[0,21],[14,-3]] },
  ']': { width: 14, points: [[9,25],[9,-7],null,[10,25],[10,-7],null,[3,25],[10,25],null,[3,-7],[10,-7]] },
  '^': { width: 14, points: [[3,10],[8,18],[13,10]] },
  '_': { width: 16, points: [[0,-2],[16,-2]] },
  '`': { width: 10, points: [[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]] },
  'a': { width: 19, points: [[15,14],[15,0],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'b': { width: 19, points: [[4,21],[4,0],null,[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] },
  'c': { width: 18, points: [[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'd': { width: 19, points: [[15,21],[15,0],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'e': { width: 18, points: [[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'f': { width: 12, points: [[10,21],[8,21],[6,20],[5,17],[5,0],null,[2,14],[9,14]] },
  'g': { width: 19, points: [[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'h': { width: 19, points: [[4,21],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] },
  'i': { width: 8, points: [[3,21],[4,20],[5,21],[4,22],[3,21],null,[4,14],[4,0]] },
  'j': { width: 10, points: [[5,21],[6,20],[7,21],[6,22],[5,21],null,[6,14],[6,-3],[5,-6],[3,-7],[1,-7]] },
  'k': { width: 17, points: [[4,21],[4,0],null,[14,14],[4,4],null,[8,8],[15,0]] },
  'l': { width: 8, points: [[4,21],[4,0]] },
  'm': { width: 30, points: [[4,14],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],null,[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]] },
  'n': { width: 19, points: [[4,14],[4,0],null,[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] },
  'o': { width: 19, points: [[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]] },
  'p': { width: 19, points: [[4,14],[4,-7],null,[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] },
  'q': { width: 19, points: [[15,14],[15,-7],null,[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
  'r': { width: 13, points: [[4,14],[4,0],null,[4,8],[5,11],[7,13],[9,14],[12,14]] },
  's': { width: 17, points: [[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]] },
  't': { width: 12, points: [[5,21],[5,4],[6,1],[8,0],[10,0],null,[2,14],[9,14]] },
  'u': { width: 19, points: [[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],null,[15,14],[15,0]] },
  'v': { width: 16, points: [[2,14],[8,0],null,[14,14],[8,0]] },
  'w': { width: 22, points: [[3,14],[7,0],null,[11,14],[7,0],null,[11,14],[15,0],null,[19,14],[15,0]] },
  'x': { width: 17, points: [[3,14],[14,0],null,[14,14],[3,0]] },
  'y': { width: 16, points: [[2,14],[8,0],null,[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]] },
  'z': { width: 17, points: [[14,14],[3,0],null,[3,14],[14,14],null,[3,0],[14,0]] },
  '{': { width: 14, points: [[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],null,[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],null,[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]] },
  '|': { width: 8, points: [[4,25],[4,-7]] },
  '}': { width: 14, points: [[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],null,[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],null,[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]] },
  '~': { width: 24, points: [[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],null,[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]] },
 
  // Lower case Latin-1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  // Upper case Latin-1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  },
 
  specialchars: {
  'pi': { width: 19, points: [[6,14],[6,0],null,[14,14],[14,0],null,[2,13],[6,16],[13,13],[17,16]] }
  },
 
  /** Diacritics, used to draw accentuated letters */
  diacritics: {
 
 
  '`': { entity: 'grave', points: [[7,22],[12,19]] },
  '^': { entity: 'circ', points: [[5.5,19],[9.5,23],[12.5,19]] },
 
  '~': { entity: 'tilde', points: [[4,18],[7,22],[10,18],[13,22]] }
  },
 
  /** The default font styling */
  style: {
  size: 8, // font height in pixels
  font: null, // not yet implemented
  color: '#000000', // font color
  weight: 1, // float, 1 for 'normal'
  textAlign: 'left', // left, right, center
  textBaseline: 'bottom', // top, middle, bottom
  adjustAlign: false, // modifies the alignments if the angle is different from 0 to make the spin point always at the good position
  angle: 0, // in radians, anticlockwise
  tracking: 1, // space between the letters, float, 1 for 'normal'
  boundingBoxColor: '#ff0000', // color of the bounding box (null to hide), can be used for debug and font drawing
  originPointColor: '#000000' // color of the bounding box (null to hide), can be used for debug and font drawing
  },
 
  debug: false,
  _bufferLexemes: {},
 
  extend: function(dest, src) {
  for (var property in src) {
  if (property in dest) continue;
  dest[property] = src[property];
  }
  return dest;
  },
 
  /** Get the letter data corresponding to a char
  * @param {String} ch - The char
  */
  letter: function(ch) {
  return CanvasText.letters[ch];
  },
 
  parseLexemes: function(str) {
  if (CanvasText._bufferLexemes[str])
  return CanvasText._bufferLexemes[str];
 
  var i, c, matches = str.match(/&[A-Za-z]{2,5};|\s|./g),
  result = [], chars = [];
 
  for (i = 0; i < matches.length; i++) {
  c = matches[i];
  if (c.length == 1)
  chars.push(c);
  else {
  var entity = c.substring(1, c.length-1);
  if (CanvasText.specialchars[entity])
  chars.push(entity);
  else
  chars = chars.concat(c.toArray());
  }
  }
  for (i = 0; i < chars.length; i++) {
  c = chars[i];
  if (c = CanvasText.letters[c] || CanvasText.specialchars[c]) result.push(c);
  }
  for (i = 0; i < result.length; i++) {
  if (result === null || typeof result === 'undefined')
  delete result[i];
  }
  return CanvasText._bufferLexemes[str] = result;
  },
 
  /** Get the font ascent for a given style
  * @param {Object} style - The reference style
  */
  ascent: function(style) {
  style = style || CanvasText.style;
  return (style.size || CanvasText.style.size);
  },
 
  /** Get the font descent for a given style
  * @param {Object} style - The reference style
  * */
  descent: function(style) {
  style = style || CanvasText.style;
  return 7.0*(style.size || CanvasText.style.size)/25.0;
  },
 
  /** Measure the text horizontal size
  * @param {String} str - The text
  * @param {Object} style - Text style
  * */
  measure: function(str, style) {
  if (!str) return;
  style = style || CanvasText.style;
 
  var i, width, lexemes = CanvasText.parseLexemes(str),
  total = 0;
 
  for (i = lexemes.length-1; i > -1; --i) {
  c = lexemes[i];
  width = (c.diacritic) ? CanvasText.letter(c.letter).width : c.width;
  total += width * (style.tracking || CanvasText.style.tracking) * (style.size || CanvasText.style.size) / 25.0;
  }
  return total;
  },
 
  getDimensions: function(str, style) {
  style = style || CanvasText.style;
 
  var width = CanvasText.measure(str, style),
  height = style.size || CanvasText.style.size,
  angle = style.angle || CanvasText.style.angle;
 
  if (style.angle == 0) return {width: width, height: height};
  return {
  width: Math.abs(Math.cos(angle) * width) + Math.abs(Math.sin(angle) * height),
  height: Math.abs(Math.sin(angle) * width) + Math.abs(Math.cos(angle) * height)
  }
  },
 
  /** Draws serie of points at given coordinates
  * @param {Canvas context} ctx - The canvas context
  * @param {Array} points - The points to draw
  * @param {Number} x - The X coordinate
  * @param {Number} y - The Y coordinate
  * @param {Number} mag - The scale
  */
  drawPoints: function (ctx, points, x, y, mag, offset) {
  var i, a, penUp = true, needStroke = 0;
  offset = offset || {x:0, y:0};
 
  ctx.beginPath();
  for (i = 0; i < points.length; i++) {
  a = points[i];
  if (!a) {
  penUp = true;
  continue;
  }
  if (penUp) {
  ctx.moveTo(x + a[0]*mag + offset.x, y - a[1]*mag + offset.y);
  penUp = false;
  }
  else {
  ctx.lineTo(x + a[0]*mag + offset.x, y - a[1]*mag + offset.y);
  }
  }
  ctx.stroke();
  ctx.closePath();
  },
 
  /** Draws a text at given coordinates and with a given style
  * @param {String} str - The text to draw
  * @param {Number} xOrig - The X coordinate
  * @param {Number} yOrig - The Y coordinate
  * @param {Object} style - The font style
  */
  draw: function(str, xOrig, yOrig, style) {
  if (!str) return;
  CanvasText.extend(style, CanvasText.style);
 
  var i, c, total = 0,
  mag = style.size / 25.0,
  x = 0, y = 0,
  lexemes = CanvasText.parseLexemes(str),
  offset = {x: 0, y: 0},
  measure = CanvasText.measure(str, style),
  align;
 
  if (style.adjustAlign) {
  align = CanvasText.getBestAlign(style.angle, style);
  CanvasText.extend(style, align);
  }
 
  switch (style.textAlign) {
  case 'left': break;
  case 'center': offset.x = -measure / 2; break;
  case 'right': offset.x = -measure; break;
  }
 
  switch (style.textBaseline) {
  case 'bottom': break;
  case 'middle': offset.y = style.size / 2; break;
  case 'top': offset.y = style.size; break;
  }
 
  this.save();
  this.translate(xOrig, yOrig);
  this.rotate(style.angle);
  this.lineCap = "round";
  this.lineWidth = 2.0 * mag * (style.weight || CanvasText.style.weight);
  this.strokeStyle = style.color || CanvasText.style.color;
 
  for (i = 0; i < lexemes.length; i++) {
  c = lexemes[i];
  if (c.width == -1) {
  x = 0;
  y = style.size * 1.4;
  continue;
  }
 
  var points = c.points,
  width = c.width;
 
  if (c.diacritic) {
  var dia = CanvasText.diacritics[c.diacritic],
  character = CanvasText.letter(c.letter);
 
  CanvasText.drawPoints(this, dia.points, x, y - (c.letter.toUpperCase() == c.letter ? 3 : 0), mag, offset);
  points = character.points;
  width = character.width;
  }
 
  CanvasText.drawPoints(this, points, x, y, mag, offset);
 
  if (CanvasText.debug) {
  this.save();
  this.lineJoin = "miter";
  this.lineWidth = 0.5;
  this.strokeStyle = (style.boundingBoxColor || CanvasText.style.boundingBoxColor);
  this.strokeRect(x+offset.x, y+offset.y, width*mag, -style.size);
 
  this.fillStyle = (style.originPointColor || CanvasText.style.originPointColor);
  this.beginPath();
  this.arc(0, 0, 1.5, 0, Math.PI*2, true);
  this.fill();
  this.closePath();
  this.restore();
  }
 
  x += width*mag*(style.tracking || CanvasText.style.tracking);
  }
  this.restore();
  return total;
  }
  };
 
  /** The text functions are bound to the CanvasRenderingContext2D prototype */
  CanvasText.proto = window.CanvasRenderingContext2D ? window.CanvasRenderingContext2D.prototype : document.createElement('canvas').getContext('2d').__proto__;
 
  if (CanvasText.proto) {
  CanvasText.proto.drawText = CanvasText.draw;
  CanvasText.proto.measure = CanvasText.measure;
  CanvasText.proto.getTextBounds = CanvasText.getDimensions;
  CanvasText.proto.fontAscent = CanvasText.ascent;
  CanvasText.proto.fontDescent = CanvasText.descent;
  }
  // Copyright 2006 Google Inc.
  //
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //
  // http://www.apache.org/licenses/LICENSE-2.0
  //
  // Unless required by applicable law or agreed to in writing, software
  // distributed under the License is distributed on an "AS IS" BASIS,
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  // See the License for the specific language governing permissions and
  // limitations under the License.
 
 
  // Known Issues:
  //
  // * Patterns only support repeat.
  // * Radial gradient are not implemented. The VML version of these look very
  // different from the canvas one.
  // * Clipping paths are not implemented.
  // * Coordsize. The width and height attribute have higher priority than the
  // width and height style values which isn't correct.
  // * Painting mode isn't implemented.
  // * Canvas width/height should is using content-box by default. IE in
  // Quirks mode will draw the canvas using border-box. Either change your
  // doctype to HTML5
  // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
  // or use Box Sizing Behavior from WebFX
  // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
  // * Non uniform scaling does not correctly scale strokes.
  // * Optimize. There is always room for speed improvements.
 
  // Only add this code if we do not already have a canvas implementation
  if (!document.createElement('canvas').getContext) {
 
  (function() {
 
  // alias some functions to make (compiled) code shorter
  var m = Math;
  var mr = m.round;
  var ms = m.sin;
  var mc = m.cos;
  var abs = m.abs;
  var sqrt = m.sqrt;
 
  // this is used for sub pixel precision
  var Z = 10;
  var Z2 = Z / 2;
 
  var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1];
 
  /**
  * This funtion is assigned to the <canvas> elements as element.getContext().
  * @this {HTMLElement}
  * @return {CanvasRenderingContext2D_}
  */
  function getContext() {
  return this.context_ ||
  (this.context_ = new CanvasRenderingContext2D_(this));
  }
 
  var slice = Array.prototype.slice;
 
  /**
  * Binds a function to an object. The returned function will always use the
  * passed in {@code obj} as {@code this}.
  *
  * Example:
  *
  * g = bind(f, obj, a, b)
  * g(c, d) // will do f.call(obj, a, b, c, d)
  *
  * @param {Function} f The function to bind the object to
  * @param {Object} obj The object that should act as this when the function
  * is called
  * @param {*} var_args Rest arguments that will be used as the initial
  * arguments when the function is called
  * @return {Function} A new function that has bound this
  */
  function bind(f, obj, var_args) {
  var a = slice.call(arguments, 2);
  return function() {
  return f.apply(obj, a.concat(slice.call(arguments)));
  };
  }
 
  function encodeHtmlAttribute(s) {
  return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  }
 
  function addNamespace(doc, prefix, urn) {
  if (!doc.namespaces[prefix]) {
  doc.namespaces.add(prefix, urn, '#default#VML');
  }
  }
 
  function addNamespacesAndStylesheet(doc) {
  addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml');
  addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office');
 
  // Setup default CSS. Only add one style sheet per document
  if (!doc.styleSheets['ex_canvas_']) {
  var ss = doc.createStyleSheet();
  ss.owningElement.id = 'ex_canvas_';
  ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
  // default size is 300x150 in Gecko and Opera
  'text-align:left;width:300px;height:150px}';
  }
  }
 
  // Add namespaces and stylesheet at startup.
  addNamespacesAndStylesheet(document);
 
  var G_vmlCanvasManager_ = {
  init: function(opt_doc) {
  var doc = opt_doc || document;
  // Create a dummy element so that IE will allow canvas elements to be
  // recognized.
  doc.createElement('canvas');
  doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
  },
 
  init_: function(doc) {
  // find all canvas elements
  var els = doc.getElementsByTagName('canvas');
  for (var i = 0; i < els.length; i++) {
  this.initElement(els[i]);
  }
  },
 
  /**
  * Public initializes a canvas element so that it can be used as canvas
  * element from now on. This is called automatically before the page is
  * loaded but if you are creating elements using createElement you need to
  * make sure this is called on the element.
  * @param {HTMLElement} el The canvas element to initialize.
  * @return {HTMLElement} the element that was created.
  */
  initElement: function(el) {
  if (!el.getContext) {
  el.getContext = getContext;
 
  // Add namespaces and stylesheet to document of the element.
  addNamespacesAndStylesheet(el.ownerDocument);
 
  // Remove fallback content. There is no way to hide text nodes so we
  // just remove all childNodes. We could hide all elements and remove
  // text nodes but who really cares about the fallback content.
  el.innerHTML = '';
 
  // do not use inline function because that will leak memory
  el.attachEvent('onpropertychange', onPropertyChange);
  el.attachEvent('onresize', onResize);
 
  var attrs = el.attributes;
  if (attrs.width && attrs.width.specified) {
  // TODO: use runtimeStyle and coordsize
  // el.getContext().setWidth_(attrs.width.nodeValue);
  el.style.width = attrs.width.nodeValue + 'px';
  } else {
  el.width = el.clientWidth;
  }
  if (attrs.height && attrs.height.specified) {
  // TODO: use runtimeStyle and coordsize
  // el.getContext().setHeight_(attrs.height.nodeValue);
  el.style.height = attrs.height.nodeValue + 'px';
  } else {
  el.height = el.clientHeight;
  }
  //el.getContext().setCoordsize_()
  }
  return el;
  }
  };
 
  function onPropertyChange(e) {
  var el = e.srcElement;
 
  switch (e.propertyName) {
  case 'width':
  el.getContext().clearRect();
  el.style.width = el.attributes.width.nodeValue + 'px';
  // In IE8 this does not trigger onresize.
  if (el.firstChild) {
  el.firstChild.style.width = el.clientWidth + 'px';
  }
  break;
  case 'height':
  el.getContext().clearRect();
  el.style.height = el.attributes.height.nodeValue + 'px';
  if (el.firstChild) {
  el.firstChild.style.height = el.clientHeight + 'px';
  }
  break;
  }
  }
 
  function onResize(e) {
  var el = e.srcElement;
  if (el.firstChild) {
  el.firstChild.style.width = el.clientWidth + 'px';
  el.firstChild.style.height = el.clientHeight + 'px';
  }
  }
 
  G_vmlCanvasManager_.init();
 
  // precompute "00" to "FF"
  var decToHex = [];
  for (var i = 0; i < 16; i++) {
  for (var j = 0; j < 16; j++) {
  decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
  }
  }
 
  function createMatrixIdentity() {
  return [
  [1, 0, 0],
  [0, 1, 0],
  [0, 0, 1]
  ];
  }
 
  function matrixMultiply(m1, m2) {
  var result = createMatrixIdentity();
 
  for (var x = 0; x < 3; x++) {
  for (var y = 0; y < 3; y++) {
  var sum = 0;
 
  for (var z = 0; z < 3; z++) {
  sum += m1[x][z] * m2[z][y];
  }
 
  result[x][y] = sum;
  }
  }
  return result;
  }
 
  function copyState(o1, o2) {
  o2.fillStyle = o1.fillStyle;
  o2.lineCap = o1.lineCap;
  o2.lineJoin = o1.lineJoin;
  o2.lineWidth = o1.lineWidth;
  o2.miterLimit = o1.miterLimit;
  o2.shadowBlur = o1.shadowBlur;
  o2.shadowColor = o1.shadowColor;
  o2.shadowOffsetX = o1.shadowOffsetX;
  o2.shadowOffsetY = o1.shadowOffsetY;
  o2.strokeStyle = o1.strokeStyle;
  o2.globalAlpha = o1.globalAlpha;
  o2.font = o1.font;
  o2.textAlign = o1.textAlign;
  o2.textBaseline = o1.textBaseline;
  o2.arcScaleX_ = o1.arcScaleX_;
  o2.arcScaleY_ = o1.arcScaleY_;
  o2.lineScale_ = o1.lineScale_;
  }
 
  var colorData = {
  aliceblue: '#F0F8FF',
  antiquewhite: '#FAEBD7',
  aquamarine: '#7FFFD4',
  azure: '#F0FFFF',
  beige: '#F5F5DC',
  bisque: '#FFE4C4',
  black: '#000000',
  blanchedalmond: '#FFEBCD',
  blueviolet: '#8A2BE2',
  brown: '#A52A2A',
  burlywood: '#DEB887',
  cadetblue: '#5F9EA0',
  chartreuse: '#7FFF00',
  chocolate: '#D2691E',
  coral: '#FF7F50',
  cornflowerblue: '#6495ED',
  cornsilk: '#FFF8DC',
  crimson: '#DC143C',
  cyan: '#00FFFF',
  darkblue: '#00008B',
  darkcyan: '#008B8B',
  darkgoldenrod: '#B8860B',
  darkgray: '#A9A9A9',
  darkgreen: '#006400',
  darkgrey: '#A9A9A9',
  darkkhaki: '#BDB76B',
  darkmagenta: '#8B008B',
  darkolivegreen: '#556B2F',
  darkorange: '#FF8C00',
  darkorchid: '#9932CC',
  darkred: '#8B0000',
  darksalmon: '#E9967A',
  darkseagreen: '#8FBC8F',
  darkslateblue: '#483D8B',
  darkslategray: '#2F4F4F',
  darkslategrey: '#2F4F4F',
  darkturquoise: '#00CED1',
  darkviolet: '#9400D3',
  deeppink: '#FF1493',
  deepskyblue: '#00BFFF',
  dimgray: '#696969',
  dimgrey: '#696969',
  dodgerblue: '#1E90FF',
  firebrick: '#B22222',
  floralwhite: '#FFFAF0',
  forestgreen: '#228B22',
  gainsboro: '#DCDCDC',
  ghostwhite: '#F8F8FF',
  gold: '#FFD700',
  goldenrod: '#DAA520',
  grey: '#808080',
  greenyellow: '#ADFF2F',
  honeydew: '#F0FFF0',
  hotpink: '#FF69B4',
  indianred: '#CD5C5C',
  indigo: '#4B0082',
  ivory: '#FFFFF0',
  khaki: '#F0E68C',
  lavender: '#E6E6FA',
  lavenderblush: '#FFF0F5',
  lawngreen: '#7CFC00',
  lemonchiffon: '#FFFACD',
  lightblue: '#ADD8E6',
  lightcoral: '#F08080',
  lightcyan: '#E0FFFF',
  lightgoldenrodyellow: '#FAFAD2',
  lightgreen: '#90EE90',
  lightgrey: '#D3D3D3',
  lightpink: '#FFB6C1',
  lightsalmon: '#FFA07A',
  lightseagreen: '#20B2AA',
  lightskyblue: '#87CEFA',
  lightslategray: '#778899',
  lightslategrey: '#778899',
  lightsteelblue: '#B0C4DE',
  lightyellow: '#FFFFE0',
  limegreen: '#32CD32',
  linen: '#FAF0E6',
  magenta: '#FF00FF',
  mediumaquamarine: '#66CDAA',
  mediumblue: '#0000CD',
  mediumorchid: '#BA55D3',
  mediumpurple: '#9370DB',
  mediumseagreen: '#3CB371',
  mediumslateblue: '#7B68EE',
  mediumspringgreen: '#00FA9A',
  mediumturquoise: '#48D1CC',
  mediumvioletred: '#C71585',
  midnightblue: '#191970',
  mintcream: '#F5FFFA',
  mistyrose: '#FFE4E1',
  moccasin: '#FFE4B5',
  navajowhite: '#FFDEAD',
  oldlace: '#FDF5E6',
  olivedrab: '#6B8E23',
  orange: '#FFA500',
  orangered: '#FF4500',
  orchid: '#DA70D6',
  palegoldenrod: '#EEE8AA',
  palegreen: '#98FB98',
  paleturquoise: '#AFEEEE',
  palevioletred: '#DB7093',
  papayawhip: '#FFEFD5',
  peachpuff: '#FFDAB9',
  peru: '#CD853F',
  pink: '#FFC0CB',
  plum: '#DDA0DD',
  powderblue: '#B0E0E6',
  rosybrown: '#BC8F8F',
  royalblue: '#4169E1',
  saddlebrown: '#8B4513',
  salmon: '#FA8072',
  sandybrown: '#F4A460',
  seagreen: '#2E8B57',
  seashell: '#FFF5EE',
  sienna: '#A0522D',
  skyblue: '#87CEEB',
  slateblue: '#6A5ACD',
  slategray: '#708090',
  slategrey: '#708090',
  snow: '#FFFAFA',
  springgreen: '#00FF7F',
  steelblue: '#4682B4',
  tan: '#D2B48C',
  thistle: '#D8BFD8',
  tomato: '#FF6347',
  turquoise: '#40E0D0',
  violet: '#EE82EE',
  wheat: '#F5DEB3',
  whitesmoke: '#F5F5F5',
  yellowgreen: '#9ACD32'
  };
 
 
  function getRgbHslContent(styleString) {
  var start = styleString.indexOf('(', 3);
  var end = styleString.indexOf(')', start + 1);
  var parts = styleString.substring(start + 1, end).split(',');
  // add alpha if needed
  if (parts.length != 4 || styleString.charAt(3) != 'a') {
  parts[3] = 1;
  }
  return parts;
  }
 
  function percent(s) {
  return parseFloat(s) / 100;
  }
 
  function clamp(v, min, max) {
  return Math.min(max, Math.max(min, v));
  }
 
  function hslToRgb(parts){
  var r, g, b, h, s, l;
  h = parseFloat(parts[0]) / 360 % 360;
  if (h < 0)
  h++;
  s = clamp(percent(parts[1]), 0, 1);
  l = clamp(percent(parts[2]), 0, 1);
  if (s == 0) {
  r = g = b = l; // achromatic
  } else {
  var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  var p = 2 * l - q;
  r = hueToRgb(p, q, h + 1 / 3);
  g = hueToRgb(p, q, h);
  b = hueToRgb(p, q, h - 1 / 3);
  }
 
  return '#' + decToHex[Math.floor(r * 255)] +
  decToHex[Math.floor(g * 255)] +
  decToHex[Math.floor(b * 255)];
  }
 
  function hueToRgb(m1, m2, h) {
  if (h < 0)
  h++;
  if (h > 1)
  h--;
 
  if (6 * h < 1)
  return m1 + (m2 - m1) * 6 * h;
  else if (2 * h < 1)
  return m2;
  else if (3 * h < 2)
  return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  else
  return m1;
  }
 
  var processStyleCache = {};
 
  function processStyle(styleString) {
  if (styleString in processStyleCache) {
  return processStyleCache[styleString];
  }
 
  var str, alpha = 1;
 
  styleString = String(styleString);
  if (styleString.charAt(0) == '#') {
  str = styleString;
  } else if (/^rgb/.test(styleString)) {
  var parts = getRgbHslContent(styleString);
  var str = '#', n;
  for (var i = 0; i < 3; i++) {
  if (parts[i].indexOf('%') != -1) {
  n = Math.floor(percent(parts[i]) * 255);
  } else {
  n = +parts[i];
  }
  str += decToHex[clamp(n, 0, 255)];
  }
  alpha = +parts[3];
  } else if (/^hsl/.test(styleString)) {
  var parts = getRgbHslContent(styleString);
  str = hslToRgb(parts);
  alpha = parts[3];
  } else {
  str = colorData[styleString] || styleString;
  }
  return processStyleCache[styleString] = {color: str, alpha: alpha};
  }
 
  var DEFAULT_STYLE = {
  style: 'normal',
  variant: 'normal',
  weight: 'normal',
  size: 10,
  family: 'sans-serif'
  };
 
  // Internal text style cache
  var fontStyleCache = {};
 
  function processFontStyle(styleString) {
  if (fontStyleCache[styleString]) {
  return fontStyleCache[styleString];
  }
 
  var el = document.createElement('div');
  var style = el.style;
  try {
  style.font = styleString;
  } catch (ex) {
  // Ignore failures to set to invalid font.
  }
 
  return fontStyleCache[styleString] = {
  style: style.fontStyle || DEFAULT_STYLE.style,
  variant: style.fontVariant || DEFAULT_STYLE.variant,
  weight: style.fontWeight || DEFAULT_STYLE.weight,
  size: style.fontSize || DEFAULT_STYLE.size,
  family: style.fontFamily || DEFAULT_STYLE.family
  };
  }
 
  function getComputedStyle(style, element) {
  var computedStyle = {};
 
  for (var p in style) {
  computedStyle[p] = style[p];
  }
 
  // Compute the size
  var canvasFontSize = parseFloat(element.currentStyle.fontSize),
  fontSize = parseFloat(style.size);
 
  if (typeof style.size == 'number') {
  computedStyle.size = style.size;
  } else if (style.size.indexOf('px') != -1) {
  computedStyle.size = fontSize;
  } else if (style.size.indexOf('em') != -1) {
  computedStyle.size = canvasFontSize * fontSize;
  } else if(style.size.indexOf('%') != -1) {
  computedStyle.size = (canvasFontSize / 100) * fontSize;
  } else if (style.size.indexOf('pt') != -1) {
  computedStyle.size = fontSize / .75;
  } else {
  computedStyle.size = canvasFontSize;
  }
 
  // Different scaling between normal text and VML text. This was found using
  // trial and error to get the same size as non VML text.
  //computedStyle.size *= 0.981;
 
  return computedStyle;
  }
 
  function buildStyle(style) {
  return style.style + ' ' + style.variant + ' ' + style.weight + ' ' +
  style.size + 'px ' + style.family;
  }
 
  var lineCapMap = {
  'butt': 'flat',
  'round': 'round'
  };
 
  function processLineCap(lineCap) {
  return lineCapMap[lineCap] || 'square';
  }
 
  /**
  * This class implements CanvasRenderingContext2D interface as described by
  * the WHATWG.
  * @param {HTMLElement} canvasElement The element that the 2D context should
  * be associated with
  */
  function CanvasRenderingContext2D_(canvasElement) {
  this.m_ = createMatrixIdentity();
 
  this.mStack_ = [];
  this.aStack_ = [];
  this.currentPath_ = [];
 
  // Canvas context properties
  this.strokeStyle = '#000';
  this.fillStyle = '#000';
 
  this.lineWidth = 1;
  this.lineJoin = 'miter';
  this.lineCap = 'butt';
  this.miterLimit = Z * 1;
  this.globalAlpha = 1;
  this.font = '10px sans-serif';
  this.textAlign = 'left';
  this.textBaseline = 'alphabetic';
  this.canvas = canvasElement;
 
  var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' +
  canvasElement.clientHeight + 'px;overflow:hidden;position:absolute';
  var el = canvasElement.ownerDocument.createElement('div');
  el.style.cssText = cssText;
  canvasElement.appendChild(el);
 
  var overlayEl = el.cloneNode(false);
  // Use a non transparent background.
  overlayEl.style.backgroundColor = 'red';
  overlayEl.style.filter = 'alpha(opacity=0)';
  canvasElement.appendChild(overlayEl);
 
  this.element_ = el;
  this.arcScaleX_ = 1;
  this.arcScaleY_ = 1;
  this.lineScale_ = 1;
  }
 
  var contextPrototype = CanvasRenderingContext2D_.prototype;
  contextPrototype.clearRect = function() {
  if (this.textMeasureEl_) {
  this.textMeasureEl_.removeNode(true);
  this.textMeasureEl_ = null;
  }
  this.element_.innerHTML = '';
  };
 
  contextPrototype.beginPath = function() {
  // TODO: Branch current matrix so that save/restore has no effect
  // as per safari docs.
  this.currentPath_ = [];
  };
 
  contextPrototype.moveTo = function(aX, aY) {
  var p = getCoords(this, aX, aY);
  this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
  this.currentX_ = p.x;
  this.currentY_ = p.y;
  };
 
  contextPrototype.lineTo = function(aX, aY) {
  var p = getCoords(this, aX, aY);
  this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
 
  this.currentX_ = p.x;
  this.currentY_ = p.y;
  };
 
  contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
  aCP2x, aCP2y,
  aX, aY) {
  var p = getCoords(this, aX, aY);
  var cp1 = getCoords(this, aCP1x, aCP1y);
  var cp2 = getCoords(this, aCP2x, aCP2y);
  bezierCurveTo(this, cp1, cp2, p);
  };
 
  // Helper function that takes the already fixed cordinates.
  function bezierCurveTo(self, cp1, cp2, p) {
  self.currentPath_.push({
  type: 'bezierCurveTo',
  cp1x: cp1.x,
  cp1y: cp1.y,
  cp2x: cp2.x,
  cp2y: cp2.y,
  x: p.x,
  y: p.y
  });
  self.currentX_ = p.x;
  self.currentY_ = p.y;
  }
 
  contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
  // the following is lifted almost directly from
  // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
 
  var cp = getCoords(this, aCPx, aCPy);
  var p = getCoords(this, aX, aY);
 
  var cp1 = {
  x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
  y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
  };
  var cp2 = {
  x: cp1.x + (p.x - this.currentX_) / 3.0,
  y: cp1.y + (p.y - this.currentY_) / 3.0
  };
 
  bezierCurveTo(this, cp1, cp2, p);
  };
 
  contextPrototype.arc = function(aX, aY, aRadius,
  aStartAngle, aEndAngle, aClockwise) {
  aRadius *= Z;
  var arcType = aClockwise ? 'at' : 'wa';
 
  var xStart = aX + mc(aStartAngle) * aRadius - Z2;
  var yStart = aY + ms(aStartAngle) * aRadius - Z2;
 
  var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
  var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
 
  // IE won't render arches drawn counter clockwise if xStart == xEnd.
  if ((abs(xStart - xEnd) < 10e-8) && !aClockwise) {
  xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
  // that can be represented in binary
  }
  // IE won't render arches drawn clockwise if yStart is very close to yEnd.
  if ((abs(yStart - yEnd) < 10e-8) && aClockwise) {
  yStart -= 0.125; // Offset yStart by 1/80 of a pixel. Use something
  // that can be represented in binary
  }
 
  var p = getCoords(this, aX, aY);
  var pStart = getCoords(this, xStart, yStart);
  var pEnd = getCoords(this, xEnd, yEnd);
 
  this.currentPath_.push({type: arcType,
  x: p.x,
  y: p.y,
  radius: aRadius,
  xStart: pStart.x,
  yStart: pStart.y,
  xEnd: pEnd.x,
  yEnd: pEnd.y});
 
  };
 
  contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
  this.moveTo(aX, aY);
  this.lineTo(aX + aWidth, aY);
  this.lineTo(aX + aWidth, aY + aHeight);
  this.lineTo(aX, aY + aHeight);
  this.closePath();
  };
 
  contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
  var oldPath = this.currentPath_;
  this.beginPath();
 
  this.moveTo(aX, aY);
  this.lineTo(aX + aWidth, aY);
  this.lineTo(aX + aWidth, aY + aHeight);
  this.lineTo(aX, aY + aHeight);
  this.closePath();
  this.stroke();
 
  this.currentPath_ = oldPath;
  };
 
  contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
  var oldPath = this.currentPath_;
  this.beginPath();
 
  this.moveTo(aX, aY);
  this.lineTo(aX + aWidth, aY);
  this.lineTo(aX + aWidth, aY + aHeight);
  this.lineTo(aX, aY + aHeight);
  this.closePath();
  this.fill();
 
  this.currentPath_ = oldPath;
  };
 
  contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
  var gradient = new CanvasGradient_('gradient');
  gradient.x0_ = aX0;
  gradient.y0_ = aY0;
  gradient.x1_ = aX1;
  gradient.y1_ = aY1;
  return gradient;
  };
 
  contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
  aX1, aY1, aR1) {
  var gradient = new CanvasGradient_('gradientradial');
  gradient.x0_ = aX0;
  gradient.y0_ = aY0;
  gradient.r0_ = aR0;
  gradient.x1_ = aX1;
  gradient.y1_ = aY1;
  gradient.r1_ = aR1;
  return gradient;
  };
 
  contextPrototype.drawImage = function(image, var_args) {
  var dx, dy, dw, dh, sx, sy, sw, sh;
 
  // to find the original width we overide the width and height
  var oldRuntimeWidth = image.runtimeStyle.width;
  var oldRuntimeHeight = image.runtimeStyle.height;
  image.runtimeStyle.width = 'auto';
  image.runtimeStyle.height = 'auto';
 
  // get the original size
  var w = image.width;
  var h = image.height;
 
  // and remove overides
  image.runtimeStyle.width = oldRuntimeWidth;
  image.runtimeStyle.height = oldRuntimeHeight;
 
  if (arguments.length == 3) {
  dx = arguments[1];
  dy = arguments[2];
  sx = sy = 0;
  sw = dw = w;
  sh = dh = h;
  } else if (arguments.length == 5) {
  dx = arguments[1];
  dy = arguments[2];
  dw = arguments[3];
  dh = arguments[4];
  sx = sy = 0;
  sw = w;
  sh = h;
  } else if (arguments.length == 9) {
  sx = arguments[1];
  sy = arguments[2];
  sw = arguments[3];
  sh = arguments[4];
  dx = arguments[5];
  dy = arguments[6];
  dw = arguments[7];
  dh = arguments[8];
  } else {
  throw Error('Invalid number of arguments');
  }
 
  var d = getCoords(this, dx, dy);
 
  var w2 = sw / 2;
  var h2 = sh / 2;
 
  var vmlStr = [];
 
  var W = 10;
  var H = 10;
 
  // For some reason that I've now forgotten, using divs didn't work
  vmlStr.push(' <g_vml_:group',
  ' coordsize="', Z * W, ',', Z * H, '"',
  ' coordorigin="0,0"' ,
  ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
 
  // If filters are necessary (rotation exists), create them
  // filters are bog-slow, so only create them if abbsolutely necessary
  // The following check doesn't account for skews (which don't exist
  // in the canvas spec (yet) anyway.
 
  if (this.m_[0][0] != 1 || this.m_[0][1] ||
  this.m_[1][1] != 1 || this.m_[1][0]) {
  var filter = [];
 
  // Note the 12/21 reversal
  filter.push('M11=', this.m_[0][0], ',',
  'M12=', this.m_[1][0], ',',
  'M21=', this.m_[0][1], ',',
  'M22=', this.m_[1][1], ',',
  'Dx=', mr(d.x / Z), ',',
  'Dy=', mr(d.y / Z), '');
 
  // Bounding box calculation (need to minimize displayed area so that
  // filters don't waste time on unused pixels.
  var max = d;
  var c2 = getCoords(this, dx + dw, dy);
  var c3 = getCoords(this, dx, dy + dh);
  var c4 = getCoords(this, dx + dw, dy + dh);
 
  max.x = m.max(max.x, c2.x, c3.x, c4.x);
  max.y = m.max(max.y, c2.y, c3.y, c4.y);
 
  vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
  'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
  filter.join(''), ", sizingmethod='clip');");
 
  } else {
  vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
  }
 
  vmlStr.push(' ">' ,
  '<g_vml_:image src="', image.src, '"',
  ' style="width:', Z * dw, 'px;',
  ' height:', Z * dh, 'px"',
  ' cropleft="', sx / w, '"',
  ' croptop="', sy / h, '"',
  ' cropright="', (w - sx - sw) / w, '"',
  ' cropbottom="', (h - sy - sh) / h, '"',
  ' />',
  '</g_vml_:group>');
 
  this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join(''));
  };
 
  contextPrototype.stroke = function(aFill) {
  var lineStr = [];
  var lineOpen = false;
 
  var W = 10;
  var H = 10;
 
  lineStr.push('<g_vml_:shape',
  ' filled="', !!aFill, '"',
  ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
  ' coordorigin="0,0"',
  ' coordsize="', Z * W, ',', Z * H, '"',
  ' stroked="', !aFill, '"',
  ' path="');
 
  var newSeq = false;
  var min = {x: null, y: null};
  var max = {x: null, y: null};
 
  for (var i = 0; i < this.currentPath_.length; i++) {
  var p = this.currentPath_[i];
  var c;
 
  switch (p.type) {
  case 'moveTo':
  c = p;
  lineStr.push(' m ', mr(p.x), ',', mr(p.y));
  break;
  case 'lineTo':
  lineStr.push(' l ', mr(p.x), ',', mr(p.y));
  break;
  case 'close':
  lineStr.push(' x ');
  p = null;
  break;
  case 'bezierCurveTo':
  lineStr.push(' c ',
  mr(p.cp1x), ',', mr(p.cp1y), ',',
  mr(p.cp2x), ',', mr(p.cp2y), ',',
  mr(p.x), ',', mr(p.y));
  break;
  case 'at':
  case 'wa':
  lineStr.push(' ', p.type, ' ',
  mr(p.x - this.arcScaleX_ * p.radius), ',',
  mr(p.y - this.arcScaleY_ * p.radius), ' ',
  mr(p.x + this.arcScaleX_ * p.radius), ',',
  mr(p.y + this.arcScaleY_ * p.radius), ' ',
  mr(p.xStart), ',', mr(p.yStart), ' ',
  mr(p.xEnd), ',', mr(p.yEnd));
  break;
  }
 
 
  // TODO: Following is broken for curves due to
  // move to proper paths.
 
  // Figure out dimensions so we can do gradient fills
  // properly
  if (p) {
  if (min.x == null || p.x < min.x) {
  min.x = p.x;
  }
  if (max.x == null || p.x > max.x) {
  max.x = p.x;
  }
  if (min.y == null || p.y < min.y) {
  min.y = p.y;
  }
  if (max.y == null || p.y > max.y) {
  max.y = p.y;
  }
  }
  }
  lineStr.push(' ">');
 
  if (!aFill) {
  appendStroke(this, lineStr);
  } else {
  appendFill(this, lineStr, min, max);
  }
 
  lineStr.push('</g_vml_:shape>');
 
  this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
  };
 
  function appendStroke(ctx, lineStr) {
  var a = processStyle(ctx.strokeStyle);
  var color = a.color;
  var opacity = a.alpha * ctx.globalAlpha;
  var lineWidth = ctx.lineScale_ * ctx.lineWidth;
 
  // VML cannot correctly render a line if the width is less than 1px.
  // In that case, we dilute the color to make the line look thinner.
  if (lineWidth < 1) {
  opacity *= lineWidth;
  }
 
  lineStr.push(
  '<g_vml_:stroke',
  ' opacity="', opacity, '"',
  ' joinstyle="', ctx.lineJoin, '"',
  ' miterlimit="', ctx.miterLimit, '"',
  ' endcap="', processLineCap(ctx.lineCap), '"',
  ' weight="', lineWidth, 'px"',
  ' color="', color, '" />'
  );
  }
 
  function appendFill(ctx, lineStr, min, max) {
  var fillStyle = ctx.fillStyle;
  var arcScaleX = ctx.arcScaleX_;
  var arcScaleY = ctx.arcScaleY_;
  var width = max.x - min.x;
  var height = max.y - min.y;
  if (fillStyle instanceof CanvasGradient_) {
  // TODO: Gradients transformed with the transformation matrix.
  var angle = 0;
  var focus = {x: 0, y: 0};
 
  // additional offset
  var shift = 0;
  // scale factor for offset
  var expansion = 1;
 
  if (fillStyle.type_ == 'gradient') {
  var x0 = fillStyle.x0_ / arcScaleX;
  var y0 = fillStyle.y0_ / arcScaleY;
  var x1 = fillStyle.x1_ / arcScaleX;
  var y1 = fillStyle.y1_ / arcScaleY;
  var p0 = getCoords(ctx, x0, y0);
  var p1 = getCoords(ctx, x1, y1);
  var dx = p1.x - p0.x;
  var dy = p1.y - p0.y;
  angle = Math.atan2(dx, dy) * 180 / Math.PI;
 
  // The angle should be a non-negative number.
  if (angle < 0) {
  angle += 360;
  }
 
  // Very small angles produce an unexpected result because they are
  // converted to a scientific notation string.
  if (angle < 1e-6) {
  angle = 0;
  }
  } else {
  var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_);
  focus = {
  x: (p0.x - min.x) / width,
  y: (p0.y - min.y) / height
  };
 
  width /= arcScaleX * Z;
  height /= arcScaleY * Z;
  var dimension = m.max(width, height);
  shift = 2 * fillStyle.r0_ / dimension;
  expansion = 2 * fillStyle.r1_ / dimension - shift;
  }
 
  // We need to sort the color stops in ascending order by offset,
  // otherwise IE won't interpret it correctly.
  var stops = fillStyle.colors_;
  stops.sort(function(cs1, cs2) {
  return cs1.offset - cs2.offset;
  });
 
  var length = stops.length;
  var color1 = stops[0].color;
  var color2 = stops[length - 1].color;
  var opacity1 = stops[0].alpha * ctx.globalAlpha;
  var opacity2 = stops[length - 1].alpha * ctx.globalAlpha;
 
  var colors = [];
  for (var i = 0; i < length; i++) {
  var stop = stops[i];
  colors.push(stop.offset * expansion + shift + ' ' + stop.color);
  }
 
  // When colors attribute is used, the meanings of opacity and o:opacity2
  // are reversed.
  lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
  ' method="none" focus="100%"',
  ' color="', color1, '"',
  ' color2="', color2, '"',
  ' colors="', colors.join(','), '"',
  ' opacity="', opacity2, '"',
  ' g_o_:opacity2="', opacity1, '"',
  ' angle="', angle, '"',
  ' focusposition="', focus.x, ',', focus.y, '" />');
  } else if (fillStyle instanceof CanvasPattern_) {
  if (width && height) {
  var deltaLeft = -min.x;
  var deltaTop = -min.y;
  lineStr.push('<g_vml_:fill',
  ' position="',
  deltaLeft / width * arcScaleX * arcScaleX, ',',
  deltaTop / height * arcScaleY * arcScaleY, '"',
  ' type="tile"',
  // TODO: Figure out the correct size to fit the scale.
  //' size="', w, 'px ', h, 'px"',
  ' src="', fillStyle.src_, '" />');
  }
  } else {
  var a = processStyle(ctx.fillStyle);
  var color = a.color;
  var opacity = a.alpha * ctx.globalAlpha;
  lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
  '" />');
  }
  }
 
  contextPrototype.fill = function() {
  this.stroke(true);
  };
 
  contextPrototype.closePath = function() {
  this.currentPath_.push({type: 'close'});
  };
 
  function getCoords(ctx, aX, aY) {
  var m = ctx.m_;
  return {
  x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
  y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
  };
  };
 
  contextPrototype.save = function() {
  var o = {};
  copyState(this, o);
  this.aStack_.push(o);
  this.mStack_.push(this.m_);
  this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
  };
 
  contextPrototype.restore = function() {
  if (this.aStack_.length) {
  copyState(this.aStack_.pop(), this);
  this.m_ = this.mStack_.pop();
  }
  };
 
  function matrixIsFinite(m) {
  return isFinite(m[0][0]) && isFinite(m[0][1]) &&
  isFinite(m[1][0]) && isFinite(m[1][1]) &&
  isFinite(m[2][0]) && isFinite(m[2][1]);
  }
 
  function setM(ctx, m, updateLineScale) {
  if (!matrixIsFinite(m)) {
  return;
  }
  ctx.m_ = m;
 
  if (updateLineScale) {
  // Get the line scale.
  // Determinant of this.m_ means how much the area is enlarged by the
  // transformation. So its square root can be used as a scale factor
  // for width.
  var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
  ctx.lineScale_ = sqrt(abs(det));
  }
  }
 
  contextPrototype.translate = function(aX, aY) {
  var m1 = [
  [1, 0, 0],
  [0, 1, 0],
  [aX, aY, 1]
  ];
 
  setM(this, matrixMultiply(m1, this.m_), false);
  };
 
  contextPrototype.rotate = function(aRot) {
  var c = mc(aRot);
  var s = ms(aRot);
 
  var m1 = [
  [c, s, 0],
  [-s, c, 0],
  [0, 0, 1]
  ];
 
  setM(this, matrixMultiply(m1, this.m_), false);
  };
 
  contextPrototype.scale = function(aX, aY) {
  this.arcScaleX_ *= aX;
  this.arcScaleY_ *= aY;
  var m1 = [
  [aX, 0, 0],
  [0, aY, 0],
  [0, 0, 1]
  ];
 
  setM(this, matrixMultiply(m1, this.m_), true);
  };
 
  contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
  var m1 = [
  [m11, m12, 0],
  [m21, m22, 0],
  [dx, dy, 1]
  ];
 
  setM(this, matrixMultiply(m1, this.m_), true);
  };
 
  contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
  var m = [
  [m11, m12, 0],
  [m21, m22, 0],
  [dx, dy, 1]
  ];
 
  setM(this, m, true);
  };
 
  /**
  * The text drawing function.
  * The maxWidth argument isn't taken in account, since no browser supports
  * it yet.
  */
  contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) {
  var m = this.m_,
  delta = 1000,
  left = 0,
  right = delta,
  offset = {x: 0, y: 0},
  lineStr = [];
 
  var fontStyle = getComputedStyle(processFontStyle(this.font),
  this.element_);
 
  var fontStyleString = buildStyle(fontStyle);
 
  var elementStyle = this.element_.currentStyle;
  var textAlign = this.textAlign.toLowerCase();
  switch (textAlign) {
  case 'left':
  case 'center':
  case 'right':
  break;
  case 'end':
  textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left';
  break;
  case 'start':
  textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left';
  break;
  default:
  textAlign = 'left';
  }
 
  // 1.75 is an arbitrary number, as there is no info about the text baseline
  switch (this.textBaseline) {
  case 'hanging':
  case 'top':
  offset.y = fontStyle.size / 1.75;
  break;
  case 'middle':
  break;
  default:
  case null:
  case 'alphabetic':
  case 'ideographic':
  case 'bottom':
  offset.y = -fontStyle.size / 2.25;
  break;
  }
 
  switch(textAlign) {
  case 'right':
  left = delta;
  right = 0.05;
  break;
  case 'center':
  left = right = delta / 2;
  break;
  }
 
  var d = getCoords(this, x + offset.x, y + offset.y);
 
  lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ',
  ' coordsize="100 100" coordorigin="0 0"',
  ' filled="', !stroke, '" stroked="', !!stroke,
  '" style="position:absolute;width:1px;height:1px;">');
 
  if (stroke) {
  appendStroke(this, lineStr);
  } else {
  // TODO: Fix the min and max params.
  appendFill(this, lineStr, {x: -left, y: 0},
  {x: right, y: fontStyle.size});
  }
 
  var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' +
  m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0';
 
  var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z);
 
  lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ',
  ' offset="', skewOffset, '" origin="', left ,' 0" />',
  '<g_vml_:path textpathok="true" />',
  '<g_vml_:textpath on="true" string="',
  encodeHtmlAttribute(text),
  '" style="v-text-align:', textAlign,
  ';font:', encodeHtmlAttribute(fontStyleString),
  '" /></g_vml_:line>');
 
  this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
  };
 
  contextPrototype.fillText = function(text, x, y, maxWidth) {
  this.drawText_(text, x, y, maxWidth, false);
  };
 
  contextPrototype.strokeText = function(text, x, y, maxWidth) {
  this.drawText_(text, x, y, maxWidth, true);
  };
 
  contextPrototype.measureText = function(text) {
  if (!this.textMeasureEl_) {
  var s = '<span style="position:absolute;' +
  'top:-20000px;left:0;padding:0;margin:0;border:none;' +
  'white-space:pre;"></span>';
  this.element_.insertAdjacentHTML('beforeEnd', s);
  this.textMeasureEl_ = this.element_.lastChild;
  }
  var doc = this.element_.ownerDocument;
  this.textMeasureEl_.innerHTML = '';
  this.textMeasureEl_.style.font = this.font;
  // Don't use innerHTML or innerText because they allow markup/whitespace.
  this.textMeasureEl_.appendChild(doc.createTextNode(text));
  return {width: this.textMeasureEl_.offsetWidth};
  };
 
  /******** STUBS ********/
  contextPrototype.clip = function() {
  // TODO: Implement
  };
 
  contextPrototype.arcTo = function() {
  // TODO: Implement
  };
 
  contextPrototype.createPattern = function(image, repetition) {
  return new CanvasPattern_(image, repetition);
  };
 
  // Gradient / Pattern Stubs
  function CanvasGradient_(aType) {
  this.type_ = aType;
  this.x0_ = 0;
  this.y0_ = 0;
  this.r0_ = 0;
  this.x1_ = 0;
  this.y1_ = 0;
  this.r1_ = 0;
  this.colors_ = [];
  }
 
  CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
  aColor = processStyle(aColor);
  this.colors_.push({offset: aOffset,
  color: aColor.color,
  alpha: aColor.alpha});
  };
 
  function CanvasPattern_(image, repetition) {
  assertImageIsValid(image);
  switch (repetition) {
  case 'repeat':
  case null:
  case '':
  this.repetition_ = 'repeat';
  break
  case 'repeat-x':
  case 'repeat-y':
  case 'no-repeat':
  this.repetition_ = repetition;
  break;
  default:
  throwException('SYNTAX_ERR');
  }
 
  this.src_ = image.src;
  this.width_ = image.width;
  this.height_ = image.height;
  }
 
  function throwException(s) {
  throw new DOMException_(s);
  }
 
  function assertImageIsValid(img) {
  if (!img || img.nodeType != 1 || img.tagName != 'IMG') {
  throwException('TYPE_MISMATCH_ERR');
  }
  if (img.readyState != 'complete') {
  throwException('INVALID_STATE_ERR');
  }
  }
 
  function DOMException_(s) {
  this.code = this[s];
  this.message = s +': DOM Exception ' + this.code;
  }
  var p = DOMException_.prototype = new Error;
  p.INDEX_SIZE_ERR = 1;
  p.DOMSTRING_SIZE_ERR = 2;
  p.HIERARCHY_REQUEST_ERR = 3;
  p.WRONG_DOCUMENT_ERR = 4;
  p.INVALID_CHARACTER_ERR = 5;
  p.NO_DATA_ALLOWED_ERR = 6;
  p.NO_MODIFICATION_ALLOWED_ERR = 7;
  p.NOT_FOUND_ERR = 8;
  p.NOT_SUPPORTED_ERR = 9;
  p.INUSE_ATTRIBUTE_ERR = 10;
  p.INVALID_STATE_ERR = 11;
  p.SYNTAX_ERR = 12;
  p.INVALID_MODIFICATION_ERR = 13;
  p.NAMESPACE_ERR = 14;
  p.INVALID_ACCESS_ERR = 15;
  p.VALIDATION_ERR = 16;
  p.TYPE_MISMATCH_ERR = 17;
 
  // set up externs
  G_vmlCanvasManager = G_vmlCanvasManager_;
  CanvasRenderingContext2D = CanvasRenderingContext2D_;
  CanvasGradient = CanvasGradient_;
  CanvasPattern = CanvasPattern_;
  DOMException = DOMException_;
  })();
 
  } // if
 
  /*! imagediff.js 1.0.2
  * (c) 2011 Carl Sutherland, Humble Software Development
  * imagediff.js is freely distributable under the MIT license.
  * Thanks to Jacob Thornton for the node/amd integration bits.
  * For details and documentation:
  * https://github.com/HumbleSoftware/js-imagediff
  */
  (function (name, definition) {
  var root = this;
  if (typeof module != 'undefined') {
  module.exports = definition();
  } else if (typeof define == 'function' && typeof define.amd == 'object') {
  define(definition);
  } else {
  root[name] = definition(root, name);
  }
  })('imagediff', function (root, name) {
 
  var
  TYPE_ARRAY = '[object Array]',
  TYPE_CANVAS = '[object HTMLCanvasElement]',
  TYPE_CONTEXT = '[object CanvasRenderingContext2D]',
  TYPE_IMAGE = '[object HTMLImageElement]',
 
  OBJECT = 'object',
  UNDEFINED = 'undefined',
 
  canvas = getCanvas(),
  context = canvas.getContext('2d'),
  previous = root[name],
  imagediff, jasmine;
 
  // Creation
  function getCanvas (width, height) {
  var
  canvas = document.createElement('canvas');
  if (width) canvas.width = width;
  if (height) canvas.height = height;
  return canvas;
  }
  function getImageData (width, height) {
  canvas.width = width;
  canvas.height = height;
  context.clearRect(0, 0, width, height);
  return context.createImageData(width, height);
  }
 
 
  // Type Checking
  function isImage (object) {
  return isType(object, TYPE_IMAGE);
  }
  function isCanvas (object) {
  return isType(object, TYPE_CANVAS);
  }
  function isContext (object) {
  return isType(object, TYPE_CONTEXT);
  }
  function isImageData (object) {
  var
  imageData = getImageData(1, 1);
  isImageData = function (object) {
  return (object && imageData.constructor === object.constructor ? true : false);
  };
  return isImageData(object);
  }
  function isImageType (object) {
  return (
  isImage(object) ||
  isCanvas(object) ||
  isContext(object) ||
  isImageData(object)
  );
  }
  function isType (object, type) {
  return typeof (object) === 'object' && Object.prototype.toString.apply(object) === type;
  }
 
 
  // Type Conversion
  function copyImageData (imageData) {
  var
  height = imageData.height,
  width = imageData.width;
  canvas.width = width;
  canvas.height = height;
  context.putImageData(imageData, 0, 0);
  return context.getImageData(0, 0, width, height);
  }
  function toImageData (object) {
  if (isImage(object)) { return toImageDataFromImage(object); }
  if (isCanvas(object)) { return toImageDataFromCanvas(object); }
  if (isContext(object)) { return toImageDataFromContext(object); }
  if (isImageData(object)) { return object; }
  }
  function toImageDataFromImage (image) {
  var
  height = image.height,
  width = image.width;
  canvas.width = width;
  canvas.height = height;
  context.clearRect(0, 0, width, height);
  context.drawImage(image, 0, 0);
  return context.getImageData(0, 0, width, height);
  }
  function toImageDataFromCanvas (canvas) {
  var
  height = canvas.height,
  width = canvas.width,
  context = canvas.getContext('2d');
  return context.getImageData(0, 0, width, height);
  }
  function toImageDataFromContext (context) {
  var
  canvas = context.canvas,
  height = canvas.height,
  width = canvas.width;
  return context.getImageData(0, 0, width, height);
  }
  function toCanvas (object) {
  var
  data = toImageData(object),
  canvas = getCanvas(data.width, data.height),
  context = canvas.getContext('2d');
 
  context.putImageData(data, 0, 0);
  return canvas;
  }
 
 
  // ImageData Equality Operators
  function equalWidth (a, b) {
  return a.width === b.width;
  }
  function equalHeight (a, b) {
  return a.height === b.height;
  }
  function equalDimensions (a, b) {
  return equalHeight(a, b) && equalWidth(a, b);
  }
  function equal (a, b, tolerance) {
 
  var
  aData = a.data,
  bData = b.data,
  length = aData.length,
  tolerance = tolerance || 0,
  i;
 
  if (!equalDimensions(a, b)) return false;
  for (i = length; i--;) if (aData[i] !== bData[i] && Math.abs(aData[i] - bData[i]) > tolerance) return false;
 
  return true;
  }
 
 
  // Diff
  function diff (a, b) {
  return (equalDimensions(a, b) ? diffEqual : diffUnequal)(a, b);
  }
  function diffEqual (a, b) {
 
  var
  height = a.height,
  width = a.width,
  c = getImageData(width, height), // c = a - b
  aData = a.data,
  bData = b.data,
  cData = c.data,
  length = cData.length,
  row, column,
  i, j, k, v;
 
  for (i = 0; i < length; i += 4) {
  cData[i] = Math.abs(aData[i] - bData[i]);
  cData[i+1] = Math.abs(aData[i+1] - bData[i+1]);
  cData[i+2] = Math.abs(aData[i+2] - bData[i+2]);
  cData[i+3] = Math.abs(255 - aData[i+3] - bData[i+3]);
  }
 
  return c;
  }
  function diffUnequal (a, b) {
 
  var
  height = Math.max(a.height, b.height),
  width = Math.max(a.width, b.width),
  c = getImageData(width, height), // c = a - b
  aData = a.data,
  bData = b.data,
  cData = c.data,
  rowOffset,
  columnOffset,
  row, column,
  i, j, k, v;
 
 
  for (i = cData.length - 1; i > 0; i = i - 4) {
  cData[i] = 255;
  }
 
  // Add First Image
  offsets(a);
  for (row = a.height; row--;){
  for (column = a.width; column--;) {
  i = 4 * ((row + rowOffset) * width + (column + columnOffset));
  j = 4 * (row * a.width + column);
  cData[i+0] = aData[j+0]; // r
  cData[i+1] = aData[j+1]; // g
  cData[i+2] = aData[j+2]; // b
  // cData[i+3] = aData[j+3]; // a
  }
  }
 
  // Subtract Second Image
  offsets(b);
  for (row = b.height; row--;){
  for (column = b.width; column--;) {
  i = 4 * ((row + rowOffset) * width + (column + columnOffset));
  j = 4 * (row * b.width + column);
  cData[i+0] = Math.abs(cData[i+0] - bData[j+0]); // r
  cData[i+1] = Math.abs(cData[i+1] - bData[j+1]); // g
  cData[i+2] = Math.abs(cData[i+2] - bData[j+2]); // b
  }
  }
 
  // Helpers
  function offsets (imageData) {
  rowOffset = Math.floor((height - imageData.height) / 2);
  columnOffset = Math.floor((width - imageData.width) / 2);
  }
 
  return c;
  }
 
 
  // Validation
  function checkType () {
  var i;
  for (i = 0; i < arguments.length; i++) {
  if (!isImageType(arguments[i])) {
  throw {
  name : 'ImageTypeError',
  message : 'Submitted object was not an image.'
  };
  }
  }
  }
 
 
  // Jasmine Matchers
  function get (element, content) {
  element = document.createElement(element);
  if (element && content) {
  element.innerHTML = content;
  }
  return element;
  }
  jasmine = {
 
  toBeImageData : function () {
  return imagediff.isImageData(this.actual);
  },
 
  toImageDiffEqual : function (expected, tolerance) {
 
  this.message = function() {
 
  var
  div = get('div'),
  a = get('div', '<div>Actual:</div>'),
  b = get('div', '<div>Expected:</div>'),
  c = get('div', '<div>Diff:</div>'),
  diff = imagediff.diff(this.actual, expected),
  canvas = getCanvas(),
  context;
 
  canvas.height = diff.height;
  canvas.width = diff.width;
 
  context = canvas.getContext('2d');
  context.putImageData(diff, 0, 0);
 
  a.appendChild(toCanvas(this.actual));
  b.appendChild(toCanvas(expected));
  c.appendChild(canvas);
 
  div.appendChild(a);
  div.appendChild(b);
  div.appendChild(c);
 
  return [
  div,
  "Expected not to be equal."
  ];
  };
 
  return imagediff.equal(this.actual, expected, tolerance);
  }
  };
 
  // Definition
  imagediff = {
 
  createCanvas : getCanvas,
  createImageData : getImageData,
 
  isImage : isImage,
  isCanvas : isCanvas,
  isContext : isContext,
  isImageData : isImageData,
  isImageType : isImageType,
 
  toImageData : function (object) {
  checkType(object);
  if (isImageData(object)) { return copyImageData(object); }
  return toImageData(object);
  },
 
  equal : function (a, b, tolerance) {
  checkType(a, b);
  a = toImageData(a);
  b = toImageData(b);
  return equal(a, b, tolerance);
  },
  diff : function (a, b) {
  checkType(a, b);
  a = toImageData(a);
  b = toImageData(b);
  return diff(a, b);
  },
 
  jasmine : jasmine,
 
  // Compatibility
  noConflict : function () {
  root[name] = previous;
  return imagediff;
  }
  };
 
  return imagediff;
  });
 
  Copyright (c) 2008-2011 Pivotal Labs
 
  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:
 
  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
  jasmine.HtmlReporterHelpers = {};
 
  jasmine.HtmlReporterHelpers.createDom = function (type, attrs, childrenVarArgs) {
  var el = document.createElement(type);
 
  for (var i = 2; i < arguments.length; i++) {
  var child = arguments[i];
 
  if (typeof child === 'string') {
  el.appendChild(document.createTextNode(child));
  } else {
  if (child) {
  el.appendChild(child);
  }
  }
  }
 
  for (var attr in attrs) {
  if (attr == "className") {
  el[attr] = attrs[attr];
  } else {
  el.setAttribute(attr, attrs[attr]);
  }
  }
 
  return el;
  };
 
  jasmine.HtmlReporterHelpers.getSpecStatus = function (child) {
  var results = child.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.skipped) {
  status = 'skipped';
  }
 
  return status;
  };
 
  jasmine.HtmlReporterHelpers.appendToSummary = function (child, childElement) {
  var parentDiv = this.dom.summary;
  var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
  var parent = child[parentSuite];
 
  if (parent) {
  if (typeof this.views.suites[parent.id] == 'undefined') {
  this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
  }
  parentDiv = this.views.suites[parent.id].element;
  }
 
  parentDiv.appendChild(childElement);
  };
 
 
  jasmine.HtmlReporterHelpers.addHelpers = function (ctor) {
  for (var fn in jasmine.HtmlReporterHelpers) {
  ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
  }
  };
 
  jasmine.HtmlReporter = function (_doc) {
  var self = this;
  var doc = _doc || window.document;
 
  var reporterView;
 
  var dom = {};
 
  // Jasmine Reporter Public Interface
  self.logRunningSpecs = false;
 
  self.reportRunnerStarting = function (runner) {
  var specs = runner.specs() || [];
 
  if (specs.length == 0) {
  return;
  }
 
  createReporterDom(runner.env.versionString());
  doc.body.appendChild(dom.reporter);
 
  reporterView = new jasmine.HtmlReporter.ReporterView(dom);
  reporterView.addSpecs(specs, self.specFilter);
  };
 
  self.reportRunnerResults = function (runner) {
  reporterView && reporterView.complete();
  };
 
  self.reportSuiteResults = function (suite) {
  reporterView.suiteComplete(suite);
  };
 
  self.reportSpecStarting = function (spec) {
  if (self.logRunningSpecs) {
  self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
  }
  };
 
  self.reportSpecResults = function (spec) {
  reporterView.specComplete(spec);
  };
 
  self.log = function () {
  var console = jasmine.getGlobal().console;
  if (console && console.log) {
  if (console.log.apply) {
  console.log.apply(console, arguments);
  } else {
  console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
  }
  }
  };
 
  self.specFilter = function (spec) {
  if (!focusedSpecName()) {
  return true;
  }
 
  return spec.getFullName().indexOf(focusedSpecName()) === 0;
  };
 
  return self;
 
  function focusedSpecName() {
  var specName;
 
  (function memoizeFocusedSpec() {
  if (specName) {
  return;
  }
 
  var paramMap = [];
  var params = doc.location.search.substring(1).split('&');
 
  for (var i = 0; i < params.length; i++) {
  var p = params[i].split('=');
  paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
  }
 
  specName = paramMap.spec;
  })();
 
  return specName;
  }
 
  function createReporterDom(version) {
  dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
  dom.banner = self.createDom('div', { className: 'banner' },
  self.createDom('span', { className: 'title' }, "Jasmine "),
  self.createDom('span', { className: 'version' }, version)),
 
  dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}),
  dom.alert = self.createDom('div', {className: 'alert'}),
  dom.results = self.createDom('div', {className: 'results'},
  dom.summary = self.createDom('div', { className: 'summary' }),
  dom.details = self.createDom('div', { id: 'details' }))
  );
  }
  };
  jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
  jasmine.HtmlReporter.ReporterView = function (dom) {
  this.startedAt = new Date();
  this.runningSpecCount = 0;
  this.completeSpecCount = 0;
  this.passedCount = 0;
  this.failedCount = 0;
  this.skippedCount = 0;
 
  this.createResultsMenu = function () {
  this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
  this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'),
  ' | ',
  this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing'));
 
  this.summaryMenuItem.onclick = function () {
  dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '');
  };
 
  this.detailsMenuItem.onclick = function () {
  showDetails();
  };
  };
 
  this.addSpecs = function (specs, specFilter) {
  this.totalSpecCount = specs.length;
 
  this.views = {
  specs: {},
  suites: {}
  };
 
  for (var i = 0; i < specs.length; i++) {
  var spec = specs[i];
  this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
  if (specFilter(spec)) {
  this.runningSpecCount++;
  }
  }
  };
 
  this.specComplete = function (spec) {
  this.completeSpecCount++;
 
  if (isUndefined(this.views.specs[spec.id])) {
  this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
  }
 
  var specView = this.views.specs[spec.id];
 
  switch (specView.status()) {
  case 'passed':
  this.passedCount++;
  break;
 
  case 'failed':
  this.failedCount++;
  break;
 
  case 'skipped':
  this.skippedCount++;
  break;
  }
 
  specView.refresh();
  this.refresh();
  };
 
  this.suiteComplete = function (suite) {
  var suiteView = this.views.suites[suite.id];
  if (isUndefined(suiteView)) {
  return;
  }
  suiteView.refresh();
  };
 
  this.refresh = function () {
 
  if (isUndefined(this.resultsMenu)) {
  this.createResultsMenu();
  }
 
  // currently running UI
  if (isUndefined(this.runningAlert)) {
  this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"});
  dom.alert.appendChild(this.runningAlert);
  }
  this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
 
  // skipped specs UI
  if (isUndefined(this.skippedAlert)) {
  this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"});
  }
 
  this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
 
  if (this.skippedCount === 1 && isDefined(dom.alert)) {
  dom.alert.appendChild(this.skippedAlert);
  }
 
  // passing specs UI
  if (isUndefined(this.passedAlert)) {
  this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"});
  }
  this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
 
  // failing specs UI
  if (isUndefined(this.failedAlert)) {
  this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"});
  }
  this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount);
 
  if (this.failedCount === 1 && isDefined(dom.alert)) {
  dom.alert.appendChild(this.failedAlert);
  dom.alert.appendChild(this.resultsMenu);
  }
 
  // summary info
  this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount);
  this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing";
  };
 
  this.complete = function () {
  dom.alert.removeChild(this.runningAlert);
 
  this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
 
  if (this.failedCount === 0) {
  dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount)));
  } else {
  showDetails();
  }
 
  dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"));
  };
 
  return this;
 
  function showDetails() {
  if (dom.reporter.className.search(/showDetails/) === -1) {
  dom.reporter.className += " showDetails";
  }
  }
 
  function isUndefined(obj) {
  return typeof obj === 'undefined';
  }
 
  function isDefined(obj) {
  return !isUndefined(obj);
  }
 
  function specPluralizedFor(count) {
  var str = count + " spec";
  if (count > 1) {
  str += "s"
  }
  return str;
  }
 
  };
 
  jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
 
 
  jasmine.HtmlReporter.SpecView = function (spec, dom, views) {
  this.spec = spec;
  this.dom = dom;
  this.views = views;
 
  this.symbol = this.createDom('li', { className: 'pending' });
  this.dom.symbolSummary.appendChild(this.symbol);
 
  this.summary = this.createDom('div', { className: 'specSummary' },
  this.createDom('a', {
  className: 'description',
  href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
  title: this.spec.getFullName()
  }, this.spec.description)
  );
 
  this.detail = this.createDom('div', { className: 'specDetail' },
  this.createDom('a', {
  className: 'description',
  href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
  title: this.spec.getFullName()
  }, this.spec.getFullName())
  );
  };
 
  jasmine.HtmlReporter.SpecView.prototype.status = function () {
  return this.getSpecStatus(this.spec);
  };
 
  jasmine.HtmlReporter.SpecView.prototype.refresh = function () {
  this.symbol.className = this.status();
 
  switch (this.status()) {
  case 'skipped':
  break;
 
  case 'passed':
  this.appendSummaryToSuiteDiv();
  break;
 
  case 'failed':
  this.appendSummaryToSuiteDiv();
  this.appendFailureDetail();
  break;
  }
  };
 
  jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function () {
  this.summary.className += ' ' + this.status();
  this.appendToSummary(this.spec, this.summary);
  };
 
  jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function () {
  this.detail.className += ' ' + this.status();
 
  var resultItems = this.spec.results().getItems();
  var messagesDiv = this.createDom('div', { className: 'messages' });
 
  for (var i = 0; i < resultItems.length; i++) {
  var result = resultItems[i];
 
  if (result.type == 'log') {
  messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
  } else if (result.type == 'expect' && result.passed && !result.passed()) {
  messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
 
  if (result.trace.stack) {
  messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
  }
  }
  }
 
  if (messagesDiv.childNodes.length > 0) {
  this.detail.appendChild(messagesDiv);
  this.dom.details.appendChild(this.detail);
  }
  };
 
  jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);
  jasmine.HtmlReporter.SuiteView = function (suite, dom, views) {
  this.suite = suite;
  this.dom = dom;
  this.views = views;
 
  this.element = this.createDom('div', { className: 'suite' },
  this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description)
  );
 
  this.appendToSummary(this.suite, this.element);
  };
 
  jasmine.HtmlReporter.SuiteView.prototype.status = function () {
  return this.getSpecStatus(this.suite);
  };
 
  jasmine.HtmlReporter.SuiteView.prototype.refresh = function () {
  this.element.className += " " + this.status();
  };
 
  jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
 
  /* @deprecated Use jasmine.HtmlReporter instead
  */
  jasmine.TrivialReporter = function (doc) {
  this.document = doc || document;
  this.suiteDivs = {};
  this.logRunningSpecs = false;
  };
 
  jasmine.TrivialReporter.prototype.createDom = function (type, attrs, childrenVarArgs) {
  var el = document.createElement(type);
 
  for (var i = 2; i < arguments.length; i++) {
  var child = arguments[i];
 
  if (typeof child === 'string') {
  el.appendChild(document.createTextNode(child));
  } else {
  if (child) {
  el.appendChild(child);
  }
  }
  }
 
  for (var attr in attrs) {
  if (attr == "className") {
  el[attr] = attrs[attr];
  } else {
  el.setAttribute(attr, attrs[attr]);
  }
  }
 
  return el;
  };
 
  jasmine.TrivialReporter.prototype.reportRunnerStarting = function (runner) {
  var showPassed, showSkipped;
 
  this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' },
  this.createDom('div', { className: 'banner' },
  this.createDom('div', { className: 'logo' },
  this.createDom('span', { className: 'title' }, "Jasmine"),
  this.createDom('span', { className: 'version' }, runner.env.versionString())),
  this.createDom('div', { className: 'options' },
  "Show ",
  showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
  this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
  showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
  this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
  )
  ),
 
  this.runnerDiv = this.createDom('div', { className: 'runner running' },
  this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
  this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
  this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
  );
 
  this.document.body.appendChild(this.outerDiv);
 
  var suites = runner.suites();
  for (var i = 0; i < suites.length; i++) {
  var suite = suites[i];
  var suiteDiv = this.createDom('div', { className: 'suite' },
  this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
  this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
  this.suiteDivs[suite.id] = suiteDiv;
  var parentDiv = this.outerDiv;
  if (suite.parentSuite) {
  parentDiv = this.suiteDivs[suite.parentSuite.id];
  }
  parentDiv.appendChild(suiteDiv);
  }
 
  this.startedAt = new Date();
 
  var self = this;
  showPassed.onclick = function (evt) {
  if (showPassed.checked) {
  self.outerDiv.className += ' show-passed';
  } else {
  self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
  }
  };
 
  showSkipped.onclick = function (evt) {
  if (showSkipped.checked) {
  self.outerDiv.className += ' show-skipped';
  } else {
  self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
  }
  };
  };
 
  jasmine.TrivialReporter.prototype.reportRunnerResults = function (runner) {
  var results = runner.results();
  var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
  this.runnerDiv.setAttribute("class", className);
  //do it twice for IE
  this.runnerDiv.setAttribute("className", className);
  var specs = runner.specs();
  var specCount = 0;
  for (var i = 0; i < specs.length; i++) {
  if (this.specFilter(specs[i])) {
  specCount++;
  }
  }
  var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
  message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
  this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
 
  this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
  };
 
  jasmine.TrivialReporter.prototype.reportSuiteResults = function (suite) {
  var results = suite.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.totalCount === 0) { // todo: change this to check results.skipped
  status = 'skipped';
  }
  this.suiteDivs[suite.id].className += " " + status;
  };
 
  jasmine.TrivialReporter.prototype.reportSpecStarting = function (spec) {
  if (this.logRunningSpecs) {
  this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
  }
  };
 
  jasmine.TrivialReporter.prototype.reportSpecResults = function (spec) {
  var results = spec.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.skipped) {
  status = 'skipped';
  }
  var specDiv = this.createDom('div', { className: 'spec ' + status },
  this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
  this.createDom('a', {
  className: 'description',
  href: '?spec=' + encodeURIComponent(spec.getFullName()),
  title: spec.getFullName()
  }, spec.description));
 
 
  var resultItems = results.getItems();
  var messagesDiv = this.createDom('div', { className: 'messages' });
  for (var i = 0; i < resultItems.length; i++) {
  var result = resultItems[i];
 
  if (result.type == 'log') {
  messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
  } else if (result.type == 'expect' && result.passed && !result.passed()) {
  messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
 
  if (result.trace.stack) {
  messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
  }
  }
  }
 
  if (messagesDiv.childNodes.length > 0) {
  specDiv.appendChild(messagesDiv);
  }
 
  this.suiteDivs[spec.suite.id].appendChild(specDiv);
  };
 
  jasmine.TrivialReporter.prototype.log = function () {
  var console = jasmine.getGlobal().console;
  if (console && console.log) {
  if (console.log.apply) {
  console.log.apply(console, arguments);
  } else {
  console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
  }
  }
  };
 
  jasmine.TrivialReporter.prototype.getLocation = function () {
  return this.document.location;
  };
 
  jasmine.TrivialReporter.prototype.specFilter = function (spec) {
  var paramMap = {};
  var params = this.getLocation().search.substring(1).split('&');
  for (var i = 0; i < params.length; i++) {
  var p = params[i].split('=');
  paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
  }
 
  if (!paramMap.spec) {
  return true;
  }
  return spec.getFullName().indexOf(paramMap.spec) === 0;
  };
 
  body {
  background-color: #eeeeee;
  padding: 0;
  margin: 5px;
  overflow-y: scroll;
  }
 
  #HTMLReporter {
  font-size: 11px;
  font-family: Monaco, "Lucida Console", monospace;
  line-height: 14px;
  color: #333333;
  }
 
  #HTMLReporter a {
  text-decoration: none;
  }
 
  #HTMLReporter a:hover {
  text-decoration: underline;
  }
 
  #HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 {
  margin: 0;
  line-height: 14px;
  }
 
  #HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace {
  padding-left: 9px;
  padding-right: 9px;
  }
 
  #HTMLReporter #jasmine_content {
  position: fixed;
  right: 100%;
  }
 
  #HTMLReporter .version {
  color: #aaaaaa;
  }
 
  #HTMLReporter .banner {
  margin-top: 14px;
  }
 
  #HTMLReporter .duration {
  color: #aaaaaa;
  float: right;
  }
 
  #HTMLReporter .symbolSummary {
  overflow: hidden;
  *zoom: 1;
  margin: 14px 0;
  }
 
  #HTMLReporter .symbolSummary li {
  display: block;
  float: left;
  height: 7px;
  width: 14px;
  margin-bottom: 7px;
  font-size: 16px;
  }
 
  #HTMLReporter .symbolSummary li.passed {
  font-size: 14px;
  }
 
  #HTMLReporter .symbolSummary li.passed:before {
  color: #5e7d00;
  content: "\02022";
  }
 
  #HTMLReporter .symbolSummary li.failed {
  line-height: 9px;
  }
 
  #HTMLReporter .symbolSummary li.failed:before {
  color: #b03911;
  content: "x";
  font-weight: bold;
  margin-left: -1px;
  }
 
  #HTMLReporter .symbolSummary li.skipped {
  font-size: 14px;
  }
 
  #HTMLReporter .symbolSummary li.skipped:before {
  color: #bababa;
  content: "\02022";
  }
 
  #HTMLReporter .symbolSummary li.pending {
  line-height: 11px;
  }
 
  #HTMLReporter .symbolSummary li.pending:before {
  color: #aaaaaa;
  content: "-";
  }
 
  #HTMLReporter .bar {
  line-height: 28px;
  font-size: 14px;
  display: block;
  color: #eee;
  }
 
  #HTMLReporter .runningAlert {
  background-color: #666666;
  }
 
  #HTMLReporter .skippedAlert {
  background-color: #aaaaaa;
  }
 
  #HTMLReporter .skippedAlert:first-child {
  background-color: #333333;
  }
 
  #HTMLReporter .skippedAlert:hover {
  text-decoration: none;
  color: white;
  text-decoration: underline;
  }
 
  #HTMLReporter .passingAlert {
  background-color: #a6b779;
  }
 
  #HTMLReporter .passingAlert:first-child {
  background-color: #5e7d00;
  }
 
  #HTMLReporter .failingAlert {
  background-color: #cf867e;
  }
 
  #HTMLReporter .failingAlert:first-child {
  background-color: #b03911;
  }
 
  #HTMLReporter .results {
  margin-top: 14px;
  }
 
  #HTMLReporter #details {
  display: none;
  }
 
  #HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a {
  background-color: #fff;
  color: #333333;
  }
 
  #HTMLReporter.showDetails .summaryMenuItem {
  font-weight: normal;
  text-decoration: inherit;
  }
 
  #HTMLReporter.showDetails .summaryMenuItem:hover {
  text-decoration: underline;
  }
 
  #HTMLReporter.showDetails .detailsMenuItem {
  font-weight: bold;
  text-decoration: underline;
  }
 
  #HTMLReporter.showDetails .summary {
  display: none;
  }
 
  #HTMLReporter.showDetails #details {
  display: block;
  }
 
  #HTMLReporter .summaryMenuItem {
  font-weight: bold;
  text-decoration: underline;
  }
 
  #HTMLReporter .summary {
  margin-top: 14px;
  }
 
  #HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary {
  margin-left: 14px;
  }
 
  #HTMLReporter .summary .specSummary.passed a {
  color: #5e7d00;
  }
 
  #HTMLReporter .summary .specSummary.failed a {
  color: #b03911;
  }
 
  #HTMLReporter .description + .suite {
  margin-top: 0;
  }
 
  #HTMLReporter .suite {
  margin-top: 14px;
  }
 
  #HTMLReporter .suite a {
  color: #333333;
  }
 
  #HTMLReporter #details .specDetail {
  margin-bottom: 28px;
  }
 
  #HTMLReporter #details .specDetail .description {
  display: block;
  color: white;
  background-color: #b03911;
  }
 
  #HTMLReporter .resultMessage {
  padding-top: 14px;
  color: #333333;
  }
 
  #HTMLReporter .resultMessage span.result {
  display: block;
  }
 
  #HTMLReporter .stackTrace {
  margin: 5px 0 0 0;
  max-height: 224px;
  overflow: auto;
  line-height: 18px;
  color: #666666;
  border: 1px solid #ddd;
  background: white;
  white-space: pre;
  }
 
  #TrivialReporter {
  padding: 8px 13px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-y: scroll;
  background-color: white;
  font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/
  /*white-space: pre;*/
  /*}*/
  }
 
  #TrivialReporter a:visited, #TrivialReporter a {
  color: #303;
  }
 
  #TrivialReporter a:hover, #TrivialReporter a:active {
  color: blue;
  }
 
  #TrivialReporter .run_spec {
  float: right;
  padding-right: 5px;
  font-size: .8em;
  text-decoration: none;
  }
 
  #TrivialReporter .banner {
  color: #303;
  background-color: #fef;
  padding: 5px;
  }
 
  #TrivialReporter .logo {
  float: left;
  font-size: 1.1em;
  padding-left: 5px;
  }
 
  #TrivialReporter .logo .version {
  font-size: .6em;
  padding-left: 1em;
  }
 
  #TrivialReporter .runner.running {
  background-color: yellow;
  }
 
  #TrivialReporter .options {
  text-align: right;
  font-size: .8em;
  }
 
  #TrivialReporter .suite {
  border: 1px outset gray;
  margin: 5px 0;
  padding-left: 1em;
  }
 
  #TrivialReporter .suite .suite {
  margin: 5px;
  }
 
  #TrivialReporter .suite.passed {
  background-color: #dfd;
  }
 
  #TrivialReporter .suite.failed {
  background-color: #fdd;
  }
 
  #TrivialReporter .spec {
  margin: 5px;
  padding-left: 1em;
  clear: both;
  }
 
  #TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped {
  padding-bottom: 5px;
  border: 1px solid gray;
  }
 
  #TrivialReporter .spec.failed {
  background-color: #fbb;
  border-color: red;
  }
 
  #TrivialReporter .spec.passed {
  background-color: #bfb;
  border-color: green;
  }
 
  #TrivialReporter .spec.skipped {
  background-color: #bbb;
  }
 
  #TrivialReporter .messages {
  border-left: 1px dashed gray;
  padding-left: 1em;
  padding-right: 1em;
  }
 
  #TrivialReporter .passed {
  background-color: #cfc;
  display: none;
  }
 
  #TrivialReporter .failed {
  background-color: #fbb;
  }
 
  #TrivialReporter .skipped {
  color: #777;
  background-color: #eee;
  display: none;
  }
 
  #TrivialReporter .resultMessage span.result {
  display: block;
  line-height: 2em;
  color: black;
  }
 
  #TrivialReporter .resultMessage .mismatch {
  color: black;
  }
 
  #TrivialReporter .stackTrace {
  white-space: pre;
  font-size: .8em;
  margin-left: 10px;
  max-height: 5em;
  overflow: auto;
  border: 1px inset red;
  padding: 1em;
  background: #eef;
  }
 
  #TrivialReporter .finished-at {
  padding-left: 1em;
  font-size: .6em;
  }
 
  #TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped {
  display: block;
  }
 
  #TrivialReporter #jasmine_content {
  position: fixed;
  right: 100%;
  }
 
  #TrivialReporter .runner {
  border: 1px solid gray;
  display: block;
  margin: 5px 0;
  padding: 2px 0 2px 10px;
  }
 
  var isCommonJS = typeof window == "undefined";
 
  /**
  * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework.
  *
  * @namespace
  */
  var jasmine = {};
  if (isCommonJS) exports.jasmine = jasmine;
  /**
  * @private
  */
  jasmine.unimplementedMethod_ = function () {
  throw new Error("unimplemented method");
  };
 
  /**
  * Use <code>jasmine.undefined</code> instead of <code>undefined</code>, since <code>undefined</code> is just
  * a plain old variable and may be redefined by somebody else.
  *
  * @private
  */
  jasmine.undefined = jasmine.___undefined___;
 
  /**
  * Show diagnostic messages in the console if set to true
  *
  */
  jasmine.VERBOSE = false;
 
  /**
  * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed.
  *
  */
  jasmine.DEFAULT_UPDATE_INTERVAL = 250;
 
  /**
  * Default timeout interval in milliseconds for waitsFor() blocks.
  */
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
 
  jasmine.getGlobal = function () {
  function getGlobal() {
  return this;
  }
 
  return getGlobal();
  };
 
  /**
  * Allows for bound functions to be compared. Internal use only.
  *
  * @ignore
  * @private
  * @param base {Object} bound 'this' for the function
  * @param name {Function} function to find
  */
  jasmine.bindOriginal_ = function (base, name) {
  var original = base[name];
  if (original.apply) {
  return function () {
  return original.apply(base, arguments);
  };
  } else {
  // IE support
  return jasmine.getGlobal()[name];
  }
  };
 
  jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout');
  jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout');
  jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval');
  jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval');
 
  jasmine.MessageResult = function (values) {
  this.type = 'log';
  this.values = values;
  this.trace = new Error(); // todo: test better
  };
 
  jasmine.MessageResult.prototype.toString = function () {
  var text = "";
  for (var i = 0; i < this.values.length; i++) {
  if (i > 0) text += " ";
  if (jasmine.isString_(this.values[i])) {
  text += this.values[i];
  } else {
  text += jasmine.pp(this.values[i]);
  }
  }
  return text;
  };
 
  jasmine.ExpectationResult = function (params) {
  this.type = 'expect';
  this.matcherName = params.matcherName;
  this.passed_ = params.passed;
  this.expected = params.expected;
  this.actual = params.actual;
  this.message = this.passed_ ? 'Passed.' : params.message;
 
  var trace = (params.trace || new Error(this.message));
  this.trace = this.passed_ ? '' : trace;
  };
 
  jasmine.ExpectationResult.prototype.toString = function () {
  return this.message;
  };
 
  jasmine.ExpectationResult.prototype.passed = function () {
  return this.passed_;
  };
 
  /**
  * Getter for the Jasmine environment. Ensures one gets created
  */
  jasmine.getEnv = function () {
  var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
  return env;
  };
 
  /**
  * @ignore
  * @private
  * @param value
  * @returns {Boolean}
  */
  jasmine.isArray_ = function (value) {
  return jasmine.isA_("Array", value);
  };
 
  /**
  * @ignore
  * @private
  * @param value
  * @returns {Boolean}
  */
  jasmine.isString_ = function (value) {
  return jasmine.isA_("String", value);
  };
 
  /**
  * @ignore
  * @private
  * @param value
  * @returns {Boolean}
  */
  jasmine.isNumber_ = function (value) {
  return jasmine.isA_("Number", value);
  };
 
  /**
  * @ignore
  * @private
  * @param {String} typeName
  * @param value
  * @returns {Boolean}
  */
  jasmine.isA_ = function (typeName, value) {
  return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
  };
 
  /**
  * Pretty printer for expecations. Takes any object and turns it into a human-readable string.
  *
  * @param value {Object} an object to be outputted
  * @returns {String}
  */
  jasmine.pp = function (value) {
  var stringPrettyPrinter = new jasmine.StringPrettyPrinter();
  stringPrettyPrinter.format(value);
  return stringPrettyPrinter.string;
  };
 
  /**
  * Returns true if the object is a DOM Node.
  *
  * @param {Object} obj object to check
  * @returns {Boolean}
  */
  jasmine.isDomNode = function (obj) {
  return obj.nodeType > 0;
  };
 
  /**
  * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter.
  *
  * @example
  * // don't care about which function is passed in, as long as it's a function
  * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function));
  *
  * @param {Class} clazz
  * @returns matchable object of the type clazz
  */
  jasmine.any = function (clazz) {
  return new jasmine.Matchers.Any(clazz);
  };
 
  /**
  * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the
  * attributes on the object.
  *
  * @example
  * // don't care about any other attributes than foo.
  * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"});
  *
  * @param sample {Object} sample
  * @returns matchable object for the sample
  */
  jasmine.objectContaining = function (sample) {
  return new jasmine.Matchers.ObjectContaining(sample);
  };
 
  /**
  * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks.
  *
  * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine
  * expectation syntax. Spies can be checked if they were called or not and what the calling params were.
  *
  * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs).
  *
  * Spies are torn down at the end of every spec.
  *
  * Note: Do <b>not</b> call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj.
  *
  * @example
  * // a stub
  * var myStub = jasmine.createSpy('myStub'); // can be used anywhere
  *
  * // spy example
  * var foo = {
  * not: function(bool) { return !bool; }
  * }
  *
  * // actual foo.not will not be called, execution stops
  * spyOn(foo, 'not');
 
  // foo.not spied upon, execution will continue to implementation
  * spyOn(foo, 'not').andCallThrough();
  *
  * // fake example
  * var foo = {
  * not: function(bool) { return !bool; }
  * }
  *
  * // foo.not(val) will return val
  * spyOn(foo, 'not').andCallFake(function(value) {return value;});
  *
  * // mock example
  * foo.not(7 == 7);
  * expect(foo.not).toHaveBeenCalled();
  * expect(foo.not).toHaveBeenCalledWith(true);
  *
  * @constructor
  * @see spyOn, jasmine.createSpy, jasmine.createSpyObj
  * @param {String} name
  */
  jasmine.Spy = function (name) {
  /**
  * The name of the spy, if provided.
  */
  this.identity = name || 'unknown';
  /**
  * Is this Object a spy?
  */
  this.isSpy = true;
  /**
  * The actual function this spy stubs.
  */
  this.plan = function () {
  };
  /**
  * Tracking of the most recent call to the spy.
  * @example
  * var mySpy = jasmine.createSpy('foo');
  * mySpy(1, 2);
  * mySpy.mostRecentCall.args = [1, 2];
  */
  this.mostRecentCall = {};
 
  /**
  * Holds arguments for each call to the spy, indexed by call count
  * @example
  * var mySpy = jasmine.createSpy('foo');
  * mySpy(1, 2);
  * mySpy(7, 8);
  * mySpy.mostRecentCall.args = [7, 8];
  * mySpy.argsForCall[0] = [1, 2];
  * mySpy.argsForCall[1] = [7, 8];
  */
  this.argsForCall = [];
  this.calls = [];
  };
 
  /**
  * Tells a spy to call through to the actual implemenatation.
  *
  * @example
  * var foo = {
  * bar: function() { // do some stuff }
  * }
  *
  * // defining a spy on an existing property: foo.bar
  * spyOn(foo, 'bar').andCallThrough();
  */
  jasmine.Spy.prototype.andCallThrough = function () {
  this.plan = this.originalValue;
  return this;
  };
 
  /**
  * For setting the return value of a spy.
  *
  * @example
  * // defining a spy from scratch: foo() returns 'baz'
  * var foo = jasmine.createSpy('spy on foo').andReturn('baz');
  *
  * // defining a spy on an existing property: foo.bar() returns 'baz'
  * spyOn(foo, 'bar').andReturn('baz');
  *
  * @param {Object} value
  */
  jasmine.Spy.prototype.andReturn = function (value) {
  this.plan = function () {
  return value;
  };
  return this;
  };
 
  /**
  * For throwing an exception when a spy is called.
  *
  * @example
  * // defining a spy from scratch: foo() throws an exception w/ message 'ouch'
  * var foo = jasmine.createSpy('spy on foo').andThrow('baz');
  *
  * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch'
  * spyOn(foo, 'bar').andThrow('baz');
  *
  * @param {String} exceptionMsg
  */
  jasmine.Spy.prototype.andThrow = function (exceptionMsg) {
  this.plan = function () {
  throw exceptionMsg;
  };
  return this;
  };
 
  /**
  * Calls an alternate implementation when a spy is called.
  *
  * @example
  * var baz = function() {
  * // do some stuff, return something
  * }
  * // defining a spy from scratch: foo() calls the function baz
  * var foo = jasmine.createSpy('spy on foo').andCall(baz);
  *
  * // defining a spy on an existing property: foo.bar() calls an anonymnous function
  * spyOn(foo, 'bar').andCall(function() { return 'baz';} );
  *
  * @param {Function} fakeFunc
  */
  jasmine.Spy.prototype.andCallFake = function (fakeFunc) {
  this.plan = fakeFunc;
  return this;
  };
 
  /**
  * Resets all of a spy's the tracking variables so that it can be used again.
  *
  * @example
  * spyOn(foo, 'bar');
  *
  * foo.bar();
  *
  * expect(foo.bar.callCount).toEqual(1);
  *
  * foo.bar.reset();
  *
  * expect(foo.bar.callCount).toEqual(0);
  */
  jasmine.Spy.prototype.reset = function () {
  this.wasCalled = false;
  this.callCount = 0;
  this.argsForCall = [];
  this.calls = [];
  this.mostRecentCall = {};
  };
 
  jasmine.createSpy = function (name) {
 
  var spyObj = function () {
  spyObj.wasCalled = true;
  spyObj.callCount++;
  var args = jasmine.util.argsToArray(arguments);
  spyObj.mostRecentCall.object = this;
  spyObj.mostRecentCall.args = args;
  spyObj.argsForCall.push(args);
  spyObj.calls.push({object: this, args: args});
  return spyObj.plan.apply(this, arguments);
  };
 
  var spy = new jasmine.Spy(name);
 
  for (var prop in spy) {
  spyObj[prop] = spy[prop];
  }
 
  spyObj.reset();
 
  return spyObj;
  };
 
  /**
  * Determines whether an object is a spy.
  *
  * @param {jasmine.Spy|Object} putativeSpy
  * @returns {Boolean}
  */
  jasmine.isSpy = function (putativeSpy) {
  return putativeSpy && putativeSpy.isSpy;
  };
 
  /**
  * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something
  * large in one call.
  *
  * @param {String} baseName name of spy class
  * @param {Array} methodNames array of names of methods to make spies
  */
  jasmine.createSpyObj = function (baseName, methodNames) {
  if (!jasmine.isArray_(methodNames) || methodNames.length === 0) {
  throw new Error('createSpyObj requires a non-empty array of method names to create spies for');
  }
  var obj = {};
  for (var i = 0; i < methodNames.length; i++) {
  obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]);
  }
  return obj;
  };
 
  /**
  * All parameters are pretty-printed and concatenated together, then written to the current spec's output.
  *
  * Be careful not to leave calls to <code>jasmine.log</code> in production code.
  */
  jasmine.log = function () {
  var spec = jasmine.getEnv().currentSpec;
  spec.log.apply(spec, arguments);
  };
 
  /**
  * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy.
  *
  * @example
  * // spy example
  * var foo = {
  * not: function(bool) { return !bool; }
  * }
  * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops
  *
  * @see jasmine.createSpy
  * @param obj
  * @param methodName
  * @returns a Jasmine spy that can be chained with all spy methods
  */
  var spyOn = function (obj, methodName) {
  return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
  };
  if (isCommonJS) exports.spyOn = spyOn;
 
  /**
  * Creates a Jasmine spec that will be added to the current suite.
  *
  * // TODO: pending tests
  *
  * @example
  * it('should be true', function() {
  * expect(true).toEqual(true);
  * });
  *
  * @param {String} desc description of this specification
  * @param {Function} func defines the preconditions and expectations of the spec
  */
  var it = function (desc, func) {
  return jasmine.getEnv().it(desc, func);
  };
  if (isCommonJS) exports.it = it;
 
  /**
  * Creates a <em>disabled</em> Jasmine spec.
  *
  * A convenience method that allows existing specs to be disabled temporarily during development.
  *
  * @param {String} desc description of this specification
  * @param {Function} func defines the preconditions and expectations of the spec
  */
  var xit = function (desc, func) {
  return jasmine.getEnv().xit(desc, func);
  };
  if (isCommonJS) exports.xit = xit;
 
  /**
  * Starts a chain for a Jasmine expectation.
  *
  * It is passed an Object that is the actual value and should chain to one of the many
  * jasmine.Matchers functions.
  *
  * @param {Object} actual Actual value to test against and expected value
  */
  var expect = function (actual) {
  return jasmine.getEnv().currentSpec.expect(actual);
  };
  if (isCommonJS) exports.expect = expect;
 
  /**
  * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs.
  *
  * @param {Function} func Function that defines part of a jasmine spec.
  */
  var runs = function (func) {
  jasmine.getEnv().currentSpec.runs(func);
  };
  if (isCommonJS) exports.runs = runs;
 
  /**
  * Waits a fixed time period before moving to the next block.
  *
  * @deprecated Use waitsFor() instead
  * @param {Number} timeout milliseconds to wait
  */
  var waits = function (timeout) {
  jasmine.getEnv().currentSpec.waits(timeout);
  };
  if (isCommonJS) exports.waits = waits;
 
  /**
  * Waits for the latchFunction to return true before proceeding to the next block.
  *
  * @param {Function} latchFunction
  * @param {String} optional_timeoutMessage
  * @param {Number} optional_timeout
  */
  var waitsFor = function (latchFunction, optional_timeoutMessage, optional_timeout) {
  jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
  };
  if (isCommonJS) exports.waitsFor = waitsFor;
 
  /**
  * A function that is called before each spec in a suite.
  *
  * Used for spec setup, including validating assumptions.
  *
  * @param {Function} beforeEachFunction
  */
  var beforeEach = function (beforeEachFunction) {
  jasmine.getEnv().beforeEach(beforeEachFunction);
  };
  if (isCommonJS) exports.beforeEach = beforeEach;
 
  /**
  * A function that is called after each spec in a suite.
  *
  * Used for restoring any state that is hijacked during spec execution.
  *
  * @param {Function} afterEachFunction
  */
  var afterEach = function (afterEachFunction) {
  jasmine.getEnv().afterEach(afterEachFunction);
  };
  if (isCommonJS) exports.afterEach = afterEach;
 
  /**
  * Defines a suite of specifications.
  *
  * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared
  * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization
  * of setup in some tests.
  *
  * @example
  * // TODO: a simple suite
  *
  * // TODO: a simple suite with a nested describe block
  *
  * @param {String} description A string, usually the class under test.
  * @param {Function} specDefinitions function that defines several specs.
  */
  var describe = function (description, specDefinitions) {
  return jasmine.getEnv().describe(description, specDefinitions);
  };
  if (isCommonJS) exports.describe = describe;
 
  /**
  * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
  *
  * @param {String} description A string, usually the class under test.
  * @param {Function} specDefinitions function that defines several specs.
  */
  var xdescribe = function (description, specDefinitions) {
  return jasmine.getEnv().xdescribe(description, specDefinitions);
  };
  if (isCommonJS) exports.xdescribe = xdescribe;
 
 
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function () {
  function tryIt(f) {
  try {
  return f();
  } catch (e) {
  }
  return null;
  }
 
  var xhr = tryIt(function () {
  return new ActiveXObject("Msxml2.XMLHTTP.6.0");
  }) ||
  tryIt(function () {
  return new ActiveXObject("Msxml2.XMLHTTP.3.0");
  }) ||
  tryIt(function () {
  return new ActiveXObject("Msxml2.XMLHTTP");
  }) ||
  tryIt(function () {
  return new ActiveXObject("Microsoft.XMLHTTP");
  });
 
  if (!xhr) throw new Error("This browser does not support XMLHttpRequest.");
 
  return xhr;
  } : XMLHttpRequest;
  /**
  * @namespace
  */
  jasmine.util = {};
 
  /**
  * Declare that a child class inherit it's prototype from the parent class.
  *
  * @private
  * @param {Function} childClass
  * @param {Function} parentClass
  */
  jasmine.util.inherit = function (childClass, parentClass) {
  /**
  * @private
  */
  var subclass = function () {
  };
  subclass.prototype = parentClass.prototype;
  childClass.prototype = new subclass();
  };
 
  jasmine.util.formatException = function (e) {
  var lineNumber;
  if (e.line) {
  lineNumber = e.line;
  }
  else if (e.lineNumber) {
  lineNumber = e.lineNumber;
  }
 
  var file;
 
  if (e.sourceURL) {
  file = e.sourceURL;
  }
  else if (e.fileName) {
  file = e.fileName;
  }
 
  var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString();
 
  if (file && lineNumber) {
  message += ' in ' + file + ' (line ' + lineNumber + ')';
  }
 
  return message;
  };
 
  jasmine.util.htmlEscape = function (str) {
  if (!str) return str;
  return str.replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;');
  };
 
  jasmine.util.argsToArray = function (args) {
  var arrayOfArgs = [];
  for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]);
  return arrayOfArgs;
  };
 
  jasmine.util.extend = function (destination, source) {
  for (var property in source) destination[property] = source[property];
  return destination;
  };
 
  /**
  * Environment for Jasmine
  *
  * @constructor
  */
  jasmine.Env = function () {
  this.currentSpec = null;
  this.currentSuite = null;
  this.currentRunner_ = new jasmine.Runner(this);
 
  this.reporter = new jasmine.MultiReporter();
 
  this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL;
  this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL;
  this.lastUpdate = 0;
  this.specFilter = function () {
  return true;
  };
 
  this.nextSpecId_ = 0;
  this.nextSuiteId_ = 0;
  this.equalityTesters_ = [];
 
  // wrap matchers
  this.matchersClass = function () {
  jasmine.Matchers.apply(this, arguments);
  };
  jasmine.util.inherit(this.matchersClass, jasmine.Matchers);
 
  jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass);
  };
 
 
  jasmine.Env.prototype.setTimeout = jasmine.setTimeout;
  jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout;
  jasmine.Env.prototype.setInterval = jasmine.setInterval;
  jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
 
  /**
  * @returns an object containing jasmine version build info, if set.
  */
  jasmine.Env.prototype.version = function () {
  if (jasmine.version_) {
  return jasmine.version_;
  } else {
  throw new Error('Version not set');
  }
  };
 
  /**
  * @returns string containing jasmine version build info, if set.
  */
  jasmine.Env.prototype.versionString = function () {
  if (!jasmine.version_) {
  return "version unknown";
  }
 
  var version = this.version();
  var versionString = version.major + "." + version.minor + "." + version.build;
  if (version.release_candidate) {
  versionString += ".rc" + version.release_candidate;
  }
  versionString += " revision " + version.revision;
  return versionString;
  };
 
  /**
  * @returns a sequential integer starting at 0
  */
  jasmine.Env.prototype.nextSpecId = function () {
  return this.nextSpecId_++;
  };
 
  /**
  * @returns a sequential integer starting at 0
  */
  jasmine.Env.prototype.nextSuiteId = function () {
  return this.nextSuiteId_++;
  };
 
  /**
  * Register a reporter to receive status updates from Jasmine.
  * @param {jasmine.Reporter} reporter An object which will receive status updates.
  */
  jasmine.Env.prototype.addReporter = function (reporter) {
  this.reporter.addReporter(reporter);
  };
 
  jasmine.Env.prototype.execute = function () {
  this.currentRunner_.execute();
  };
 
  jasmine.Env.prototype.describe = function (description, specDefinitions) {
  var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
 
  var parentSuite = this.currentSuite;
  if (parentSuite) {
  parentSuite.add(suite);
  } else {
  this.currentRunner_.add(suite);
  }
 
  this.currentSuite = suite;
 
  var declarationError = null;
  try {
  specDefinitions.call(suite);
  } catch (e) {
  declarationError = e;
  }
 
  if (declarationError) {
  this.it("encountered a declaration exception", function () {
  throw declarationError;
  });
  }
 
  this.currentSuite = parentSuite;
 
  return suite;
  };
 
  jasmine.Env.prototype.beforeEach = function (beforeEachFunction) {
  if (this.currentSuite) {
  this.currentSuite.beforeEach(beforeEachFunction);
  } else {
  this.currentRunner_.beforeEach(beforeEachFunction);
  }
  };
 
  jasmine.Env.prototype.currentRunner = function () {
  return this.currentRunner_;
  };
 
  jasmine.Env.prototype.afterEach = function (afterEachFunction) {
  if (this.currentSuite) {
  this.currentSuite.afterEach(afterEachFunction);
  } else {
  this.currentRunner_.afterEach(afterEachFunction);
  }
 
  };
 
  jasmine.Env.prototype.xdescribe = function (desc, specDefinitions) {
  return {
  execute: function () {
  }
  };
  };
 
  jasmine.Env.prototype.it = function (description, func) {
  var spec = new jasmine.Spec(this, this.currentSuite, description);
  this.currentSuite.add(spec);
  this.currentSpec = spec;
 
  if (func) {
  spec.runs(func);
  }
 
  return spec;
  };
 
  jasmine.Env.prototype.xit = function (desc, func) {
  return {
  id: this.nextSpecId(),
  runs: function () {
  }
  };
  };
 
  jasmine.Env.prototype.compareObjects_ = function (a, b, mismatchKeys, mismatchValues) {
  if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) {
  return true;
  }
 
  a.__Jasmine_been_here_before__ = b;
  b.__Jasmine_been_here_before__ = a;
 
  var hasKey = function (obj, keyName) {
  return obj !== null && obj[keyName] !== jasmine.undefined;
  };
 
  for (var property in b) {
  if (!hasKey(a, property) && hasKey(b, property)) {
  mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
  }
  }
  for (property in a) {
  if (!hasKey(b, property) && hasKey(a, property)) {
  mismatchKeys.push("expected missing key '" + property + "', but present in actual.");
  }
  }
  for (property in b) {
  if (property == '__Jasmine_been_here_before__') continue;
  if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) {
  mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual.");
  }
  }
 
  if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) {
  mismatchValues.push("arrays were not the same length");
  }
 
  delete a.__Jasmine_been_here_before__;
  delete b.__Jasmine_been_here_before__;
  return (mismatchKeys.length === 0 && mismatchValues.length === 0);
  };
 
  jasmine.Env.prototype.equals_ = function (a, b, mismatchKeys, mismatchValues) {
  mismatchKeys = mismatchKeys || [];
  mismatchValues = mismatchValues || [];
 
  for (var i = 0; i < this.equalityTesters_.length; i++) {
  var equalityTester = this.equalityTesters_[i];
  var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
  if (result !== jasmine.undefined) return result;
  }
 
  if (a === b) return true;
 
  if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) {
  return (a == jasmine.undefined && b == jasmine.undefined);
  }
 
  if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {
  return a === b;
  }
 
  if (a instanceof Date && b instanceof Date) {
  return a.getTime() == b.getTime();
  }
 
  if (a.jasmineMatches) {
  return a.jasmineMatches(b);
  }
 
  if (b.jasmineMatches) {
  return b.jasmineMatches(a);
  }
 
  if (a instanceof jasmine.Matchers.ObjectContaining) {
  return a.matches(b);
  }
 
  if (b instanceof jasmine.Matchers.ObjectContaining) {
  return b.matches(a);
  }
 
  if (jasmine.isString_(a) && jasmine.isString_(b)) {
  return (a == b);
  }
 
  if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) {
  return (a == b);
  }
 
  if (typeof a === "object" && typeof b === "object") {
  return this.compareObjects_(a, b, mismatchKeys, mismatchValues);
  }
 
  //Straight check
  return (a === b);
  };
 
  jasmine.Env.prototype.contains_ = function (haystack, needle) {
  if (jasmine.isArray_(haystack)) {
  for (var i = 0; i < haystack.length; i++) {
  if (this.equals_(haystack[i], needle)) return true;
  }
  return false;
  }
  return haystack.indexOf(needle) >= 0;
  };
 
  jasmine.Env.prototype.addEqualityTester = function (equalityTester) {
  this.equalityTesters_.push(equalityTester);
  };
  /** No-op base class for Jasmine reporters.
  *
  * @constructor
  */
  jasmine.Reporter = function () {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.reportRunnerStarting = function (runner) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.reportRunnerResults = function (runner) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.reportSuiteResults = function (suite) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.reportSpecStarting = function (spec) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.reportSpecResults = function (spec) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.Reporter.prototype.log = function (str) {
  };
 
  /**
  * Blocks are functions with executable code that make up a spec.
  *
  * @constructor
  * @param {jasmine.Env} env
  * @param {Function} func
  * @param {jasmine.Spec} spec
  */
  jasmine.Block = function (env, func, spec) {
  this.env = env;
  this.func = func;
  this.spec = spec;
  };
 
  jasmine.Block.prototype.execute = function (onComplete) {
  try {
  this.func.apply(this.spec);
  } catch (e) {
  this.spec.fail(e);
  }
  onComplete();
  };
  /** JavaScript API reporter.
  *
  * @constructor
  */
  jasmine.JsApiReporter = function () {
  this.started = false;
  this.finished = false;
  this.suites_ = [];
  this.results_ = {};
  };
 
  jasmine.JsApiReporter.prototype.reportRunnerStarting = function (runner) {
  this.started = true;
  var suites = runner.topLevelSuites();
  for (var i = 0; i < suites.length; i++) {
  var suite = suites[i];
  this.suites_.push(this.summarize_(suite));
  }
  };
 
  jasmine.JsApiReporter.prototype.suites = function () {
  return this.suites_;
  };
 
  jasmine.JsApiReporter.prototype.summarize_ = function (suiteOrSpec) {
  var isSuite = suiteOrSpec instanceof jasmine.Suite;
  var summary = {
  id: suiteOrSpec.id,
  name: suiteOrSpec.description,
  type: isSuite ? 'suite' : 'spec',
  children: []
  };
 
  if (isSuite) {
  var children = suiteOrSpec.children();
  for (var i = 0; i < children.length; i++) {
  summary.children.push(this.summarize_(children[i]));
  }
  }
  return summary;
  };
 
  jasmine.JsApiReporter.prototype.results = function () {
  return this.results_;
  };
 
  jasmine.JsApiReporter.prototype.resultsForSpec = function (specId) {
  return this.results_[specId];
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.JsApiReporter.prototype.reportRunnerResults = function (runner) {
  this.finished = true;
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.JsApiReporter.prototype.reportSuiteResults = function (suite) {
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.JsApiReporter.prototype.reportSpecResults = function (spec) {
  this.results_[spec.id] = {
  messages: spec.results().getItems(),
  result: spec.results().failedCount > 0 ? "failed" : "passed"
  };
  };
 
  //noinspection JSUnusedLocalSymbols
  jasmine.JsApiReporter.prototype.log = function (str) {
  };
 
  jasmine.JsApiReporter.prototype.resultsForSpecs = function (specIds) {
  var results = {};
  for (var i = 0; i < specIds.length; i++) {
  var specId = specIds[i];
  results[specId] = this.summarizeResult_(this.results_[specId]);
  }
  return results;
  };
 
  jasmine.JsApiReporter.prototype.summarizeResult_ = function (result) {
  var summaryMessages = [];
  var messagesLength = result.messages.length;
  for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) {
  var resultMessage = result.messages[messageIndex];
  summaryMessages.push({
  text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined,
  passed: resultMessage.passed ? resultMessage.passed() : true,
  type: resultMessage.type,
  message: resultMessage.message,
  trace: {
  stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined
  }
  });
  }
 
  return {
  result: result.result,
  messages: summaryMessages
  };
  };
 
  /**
  * @constructor
  * @param {jasmine.Env} env
  * @param actual
  * @param {jasmine.Spec} spec
  */
  jasmine.Matchers = function (env, actual, spec, opt_isNot) {
  this.env = env;
  this.actual = actual;
  this.spec = spec;
  this.isNot = opt_isNot || false;
  this.reportWasCalled_ = false;
  };
 
  // todo: @deprecated as of Jasmine 0.11, remove soon [xw]
  jasmine.Matchers.pp = function (str) {
  throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
  };
 
  // todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw]
  jasmine.Matchers.prototype.report = function (result, failing_message, details) {
  throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs");
  };
 
  jasmine.Matchers.wrapInto_ = function (prototype, matchersClass) {
  for (var methodName in prototype) {
  if (methodName == 'report') continue;
  var orig = prototype[methodName];
  matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig);
  }
  };
 
  jasmine.Matchers.matcherFn_ = function (matcherName, matcherFunction) {
  return function () {
  var matcherArgs = jasmine.util.argsToArray(arguments);
  var result = matcherFunction.apply(this, arguments);
 
  if (this.isNot) {
  result = !result;
  }
 
  if (this.reportWasCalled_) return result;
 
  var message;
  if (!result) {
  if (this.message) {
  message = this.message.apply(this, arguments);
  if (jasmine.isArray_(message)) {
  message = message[this.isNot ? 1 : 0];
  }
  } else {
  var englishyPredicate = matcherName.replace(/[A-Z]/g, function (s) {
  return ' ' + s.toLowerCase();
  });
  message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate;
  if (matcherArgs.length > 0) {
  for (var i = 0; i < matcherArgs.length; i++) {
  if (i > 0) message += ",";
  message += " " + jasmine.pp(matcherArgs[i]);
  }
  }
  message += ".";
  }
  }
  var expectationResult = new jasmine.ExpectationResult({
  matcherName: matcherName,
  passed: result,
  expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0],
  actual: this.actual,
  message: message
  });
  this.spec.addMatcherResult(expectationResult);
  return jasmine.undefined;
  };
  };
 
 
  /**
  * toBe: compares the actual to the expected using ===
  * @param expected
  */
  jasmine.Matchers.prototype.toBe = function (expected) {
  return this.actual === expected;
  };
 
  /**
  * toNotBe: compares the actual to the expected using !==
  * @param expected
  * @deprecated as of 1.0. Use not.toBe() instead.
  */
  jasmine.Matchers.prototype.toNotBe = function (expected) {
  return this.actual !== expected;
  };
 
  /**
  * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc.
  *
  * @param expected
  */
  jasmine.Matchers.prototype.toEqual = function (expected) {
  return this.env.equals_(this.actual, expected);
  };
 
  /**
  * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual
  * @param expected
  * @deprecated as of 1.0. Use not.toEqual() instead.
  */
  jasmine.Matchers.prototype.toNotEqual = function (expected) {
  return !this.env.equals_(this.actual, expected);
  };
 
  /**
  * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes
  * a pattern or a String.
  *
  * @param expected
  */
  jasmine.Matchers.prototype.toMatch = function (expected) {
  return new RegExp(expected).test(this.actual);
  };
 
  /**
  * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch
  * @param expected
  * @deprecated as of 1.0. Use not.toMatch() instead.
  */
  jasmine.Matchers.prototype.toNotMatch = function (expected) {
  return !(new RegExp(expected).test(this.actual));
  };
 
  /**
  * Matcher that compares the actual to jasmine.undefined.
  */
  jasmine.Matchers.prototype.toBeDefined = function () {
  return (this.actual !== jasmine.undefined);
  };
 
  /**
  * Matcher that compares the actual to jasmine.undefined.
  */
  jasmine.Matchers.prototype.toBeUndefined = function () {
  return (this.actual === jasmine.undefined);
  };
 
  /**
  * Matcher that compares the actual to null.
  */
  jasmine.Matchers.prototype.toBeNull = function () {
  return (this.actual === null);
  };
 
  /**
  * Matcher that boolean not-nots the actual.
  */
  jasmine.Matchers.prototype.toBeTruthy = function () {
  return !!this.actual;
  };
 
 
  /**
  * Matcher that boolean nots the actual.
  */
  jasmine.Matchers.prototype.toBeFalsy = function () {
  return !this.actual;
  };
 
 
  /**
  * Matcher that checks to see if the actual, a Jasmine spy, was called.
  */
  jasmine.Matchers.prototype.toHaveBeenCalled = function () {
  if (arguments.length > 0) {
  throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
  }
 
  if (!jasmine.isSpy(this.actual)) {
  throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  }
 
  this.message = function () {
  return [
  "Expected spy " + this.actual.identity + " to have been called.",
  "Expected spy " + this.actual.identity + " not to have been called."
  ];
  };
 
  return this.actual.wasCalled;
  };
 
  /** @deprecated Use expect(xxx).toHaveBeenCalled() instead */
  jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled;
 
  /**
  * Matcher that checks to see if the actual, a Jasmine spy, was not called.
  *
  * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead
  */
  jasmine.Matchers.prototype.wasNotCalled = function () {
  if (arguments.length > 0) {
  throw new Error('wasNotCalled does not take arguments');
  }
 
  if (!jasmine.isSpy(this.actual)) {
  throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  }
 
  this.message = function () {
  return [
  "Expected spy " + this.actual.identity + " to not have been called.",
  "Expected spy " + this.actual.identity + " to have been called."
  ];
  };
 
  return !this.actual.wasCalled;
  };
 
  /**
  * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters.
  *
  * @example
  *
  */
  jasmine.Matchers.prototype.toHaveBeenCalledWith = function () {
  var expectedArgs = jasmine.util.argsToArray(arguments);
  if (!jasmine.isSpy(this.actual)) {
  throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  }
  this.message = function () {
  if (this.actual.callCount === 0) {
  // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw]
  return [
  "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.",
  "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."
  ];
  } else {
  return [
  "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall),
  "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall)
  ];
  }
  };
 
  return this.env.contains_(this.actual.argsForCall, expectedArgs);
  };
 
  /** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */
  jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith;
 
  /** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */
  jasmine.Matchers.prototype.wasNotCalledWith = function () {
  var expectedArgs = jasmine.util.argsToArray(arguments);
  if (!jasmine.isSpy(this.actual)) {
  throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  }
 
  this.message = function () {
  return [
  "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was",
  "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was"
  ];
  };
 
  return !this.env.contains_(this.actual.argsForCall, expectedArgs);
  };
 
  /**
  * Matcher that checks that the expected item is an element in the actual Array.
  *
  * @param {Object} expected
  */
  jasmine.Matchers.prototype.toContain = function (expected) {
  return this.env.contains_(this.actual, expected);
  };
 
  /**
  * Matcher that checks that the expected item is NOT an element in the actual Array.
  *
  * @param {Object} expected
  * @deprecated as of 1.0. Use not.toContain() instead.
  */
  jasmine.Matchers.prototype.toNotContain = function (expected) {
  return !this.env.contains_(this.actual, expected);
  };
 
  jasmine.Matchers.prototype.toBeLessThan = function (expected) {
  return this.actual < expected;
  };
 
  jasmine.Matchers.prototype.toBeGreaterThan = function (expected) {
  return this.actual > expected;
  };
 
  /**
  * Matcher that checks that the expected item is equal to the actual item
  * up to a given level of decimal precision (default 2).
  *
  * @param {Number} expected
  * @param {Number} precision
  */
  jasmine.Matchers.prototype.toBeCloseTo = function (expected, precision) {
  if (!(precision === 0)) {
  precision = precision || 2;
  }
  var multiplier = Math.pow(10, precision);
  var actual = Math.round(this.actual * multiplier);
  expected = Math.round(expected * multiplier);
  return expected == actual;
  };
 
  /**
  * Matcher that checks that the expected exception was thrown by the actual.
  *
  * @param {String} expected
  */
  jasmine.Matchers.prototype.toThrow = function (expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
  throw new Error('Actual is not a function');
  }
  try {
  this.actual();
  } catch (e) {
  exception = e;
  }
  if (exception) {
  result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected));
  }
 
  var not = this.isNot ? "not " : "";
 
  this.message = function () {
  if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
  return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' ');
  } else {
  return "Expected function to throw an exception.";
  }
  };
 
  return result;
  };
 
  jasmine.Matchers.Any = function (expectedClass) {
  this.expectedClass = expectedClass;
  };
 
  jasmine.Matchers.Any.prototype.jasmineMatches = function (other) {
  if (this.expectedClass == String) {
  return typeof other == 'string' || other instanceof String;
  }
 
  if (this.expectedClass == Number) {
  return typeof other == 'number' || other instanceof Number;
  }
 
  if (this.expectedClass == Function) {
  return typeof other == 'function' || other instanceof Function;
  }
 
  if (this.expectedClass == Object) {
  return typeof other == 'object';
  }
 
  return other instanceof this.expectedClass;
  };
 
  jasmine.Matchers.Any.prototype.jasmineToString = function () {
  return '<jasmine.any(' + this.expectedClass + ')>';
  };
 
  jasmine.Matchers.ObjectContaining = function (sample) {
  this.sample = sample;
  };
 
  jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function (other, mismatchKeys, mismatchValues) {
  mismatchKeys = mismatchKeys || [];
  mismatchValues = mismatchValues || [];
 
  var env = jasmine.getEnv();
 
  var hasKey = function (obj, keyName) {
  return obj != null && obj[keyName] !== jasmine.undefined;
  };
 
  for (var property in this.sample) {
  if (!hasKey(other, property) && hasKey(this.sample, property)) {
  mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
  }
  else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) {
  mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual.");
  }
  }
 
  return (mismatchKeys.length === 0 && mismatchValues.length === 0);
  };
 
  jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () {
  return "<jasmine.objectContaining(" + jasmine.pp(this.sample) + ")>";
  };
  // Mock setTimeout, clearTimeout
  // Contributed by Pivotal Computer Systems, www.pivotalsf.com
 
  jasmine.FakeTimer = function () {
  this.reset();
 
  var self = this;
  self.setTimeout = function (funcToCall, millis) {
  self.timeoutsMade++;
  self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
  return self.timeoutsMade;
  };
 
  self.setInterval = function (funcToCall, millis) {
  self.timeoutsMade++;
  self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
  return self.timeoutsMade;
  };
 
  self.clearTimeout = function (timeoutKey) {
  self.scheduledFunctions[timeoutKey] = jasmine.undefined;
  };
 
  self.clearInterval = function (timeoutKey) {
  self.scheduledFunctions[timeoutKey] = jasmine.undefined;
  };
 
  };
 
  jasmine.FakeTimer.prototype.reset = function () {
  this.timeoutsMade = 0;
  this.scheduledFunctions = {};
  this.nowMillis = 0;
  };
 
  jasmine.FakeTimer.prototype.tick = function (millis) {
  var oldMillis = this.nowMillis;
  var newMillis = oldMillis + millis;
  this.runFunctionsWithinRange(oldMillis, newMillis);
  this.nowMillis = newMillis;
  };
 
  jasmine.FakeTimer.prototype.runFunctionsWithinRange = function (oldMillis, nowMillis) {
  var scheduledFunc;
  var funcsToRun = [];
  for (var timeoutKey in this.scheduledFunctions) {
  scheduledFunc = this.scheduledFunctions[timeoutKey];
  if (scheduledFunc != jasmine.undefined &&
  scheduledFunc.runAtMillis >= oldMillis &&
  scheduledFunc.runAtMillis <= nowMillis) {
  funcsToRun.push(scheduledFunc);
  this.scheduledFunctions[timeoutKey] = jasmine.undefined;
  }
  }
 
  if (funcsToRun.length > 0) {
  funcsToRun.sort(function (a, b) {
  return a.runAtMillis - b.runAtMillis;
  });
  for (var i = 0; i < funcsToRun.length; ++i) {
  try {
  var funcToRun = funcsToRun[i];
  this.nowMillis = funcToRun.runAtMillis;
  funcToRun.funcToCall();
  if (funcToRun.recurring) {
  this.scheduleFunction(funcToRun.timeoutKey,
  funcToRun.funcToCall,
  funcToRun.millis,
  true);
  }
  } catch (e) {
  }
  }
  this.runFunctionsWithinRange(oldMillis, nowMillis);
  }
  };
 
  jasmine.FakeTimer.prototype.scheduleFunction = function (timeoutKey, funcToCall, millis, recurring) {
  this.scheduledFunctions[timeoutKey] = {
  runAtMillis: this.nowMillis + millis,
  funcToCall: funcToCall,
  recurring: recurring,
  timeoutKey: timeoutKey,
  millis: millis
  };
  };
 
  /**
  * @namespace
  */
  jasmine.Clock = {
  defaultFakeTimer: new jasmine.FakeTimer(),
 
  reset: function () {
  jasmine.Clock.assertInstalled();
  jasmine.Clock.defaultFakeTimer.reset();
  },
 
  tick: function (millis) {
  jasmine.Clock.assertInstalled();
  jasmine.Clock.defaultFakeTimer.tick(millis);
  },
 
  runFunctionsWithinRange: function (oldMillis, nowMillis) {
  jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
  },
 
  scheduleFunction: function (timeoutKey, funcToCall, millis, recurring) {
  jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
  },
 
  useMock: function () {
  if (!jasmine.Clock.isInstalled()) {
  var spec = jasmine.getEnv().currentSpec;
  spec.after(jasmine.Clock.uninstallMock);
 
  jasmine.Clock.installMock();
  }
  },
 
  installMock: function () {
  jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
  },
 
  uninstallMock: function () {
  jasmine.Clock.assertInstalled();
  jasmine.Clock.installed = jasmine.Clock.real;
  },
 
  real: {
  setTimeout: jasmine.getGlobal().setTimeout,
  clearTimeout: jasmine.getGlobal().clearTimeout,
  setInterval: jasmine.getGlobal().setInterval,
  clearInterval: jasmine.getGlobal().clearInterval
  },
 
  assertInstalled: function () {
  if (!jasmine.Clock.isInstalled()) {
  throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
  }
  },
 
  isInstalled: function () {
  return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer;
  },
 
  installed: null
  };
  jasmine.Clock.installed = jasmine.Clock.real;
 
  //else for IE support
  jasmine.getGlobal().setTimeout = function (funcToCall, millis) {
  if (jasmine.Clock.installed.setTimeout.apply) {
  return jasmine.Clock.installed.setTimeout.apply(this, arguments);
  } else {
  return jasmine.Clock.installed.setTimeout(funcToCall, millis);
  }
  };
 
  jasmine.getGlobal().setInterval = function (funcToCall, millis) {
  if (jasmine.Clock.installed.setInterval.apply) {
  return jasmine.Clock.installed.setInterval.apply(this, arguments);
  } else {
  return jasmine.Clock.installed.setInterval(funcToCall, millis);
  }
  };
 
  jasmine.getGlobal().clearTimeout = function (timeoutKey) {
  if (jasmine.Clock.installed.clearTimeout.apply) {
  return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
  } else {
  return jasmine.Clock.installed.clearTimeout(timeoutKey);
  }
  };
 
  jasmine.getGlobal().clearInterval = function (timeoutKey) {
  if (jasmine.Clock.installed.clearTimeout.apply) {
  return jasmine.Clock.installed.clearInterval.apply(this, arguments);
  } else {
  return jasmine.Clock.installed.clearInterval(timeoutKey);
  }
  };
 
  /**
  * @constructor
  */
  jasmine.MultiReporter = function () {
  this.subReporters_ = [];
  };
  jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter);
 
  jasmine.MultiReporter.prototype.addReporter = function (reporter) {
  this.subReporters_.push(reporter);
  };
 
  (function () {
  var functionNames = [
  "reportRunnerStarting",
  "reportRunnerResults",
  "reportSuiteResults",
  "reportSpecStarting",
  "reportSpecResults",
  "log"
  ];
  for (var i = 0; i < functionNames.length; i++) {
  var functionName = functionNames[i];
  jasmine.MultiReporter.prototype[functionName] = (function (functionName) {
  return function () {
  for (var j = 0; j < this.subReporters_.length; j++) {
  var subReporter = this.subReporters_[j];
  if (subReporter[functionName]) {
  subReporter[functionName].apply(subReporter, arguments);
  }
  }
  };
  })(functionName);
  }
  })();
  /**
  * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults
  *
  * @constructor
  */
  jasmine.NestedResults = function () {
  /**
  * The total count of results
  */
  this.totalCount = 0;
  /**
  * Number of passed results
  */
  this.passedCount = 0;
  /**
  * Number of failed results
  */
  this.failedCount = 0;
  /**
  * Was this suite/spec skipped?
  */
  this.skipped = false;
  /**
  * @ignore
  */
  this.items_ = [];
  };
 
  /**
  * Roll up the result counts.
  *
  * @param result
  */
  jasmine.NestedResults.prototype.rollupCounts = function (result) {
  this.totalCount += result.totalCount;
  this.passedCount += result.passedCount;
  this.failedCount += result.failedCount;
  };
 
  /**
  * Adds a log message.
  * @param values Array of message parts which will be concatenated later.
  */
  jasmine.NestedResults.prototype.log = function (values) {
  this.items_.push(new jasmine.MessageResult(values));
  };
 
  /**
  * Getter for the results: message & results.
  */
  jasmine.NestedResults.prototype.getItems = function () {
  return this.items_;
  };
 
  /**
  * Adds a result, tracking counts (total, passed, & failed)
  * @param {jasmine.ExpectationResult|jasmine.NestedResults} result
  */
  jasmine.NestedResults.prototype.addResult = function (result) {
  if (result.type != 'log') {
  if (result.items_) {
  this.rollupCounts(result);
  } else {
  this.totalCount++;
  if (result.passed()) {
  this.passedCount++;
  } else {
  this.failedCount++;
  }
  }
  }
  this.items_.push(result);
  };
 
  /**
  * @returns {Boolean} True if <b>everything</b> below passed
  */
  jasmine.NestedResults.prototype.passed = function () {
  return this.passedCount === this.totalCount;
  };
  /**
  * Base class for pretty printing for expectation results.
  */
  jasmine.PrettyPrinter = function () {
  this.ppNestLevel_ = 0;
  };
 
  /**
  * Formats a value in a nice, human-readable string.
  *
  * @param value
  */
  jasmine.PrettyPrinter.prototype.format = function (value) {
  if (this.ppNestLevel_ > 40) {
  throw new Error('jasmine.PrettyPrinter: format() nested too deeply!');
  }
 
  this.ppNestLevel_++;
  try {
  if (value === jasmine.undefined) {
  this.emitScalar('undefined');
  } else if (value === null) {
  this.emitScalar('null');
  } else if (value === jasmine.getGlobal()) {
  this.emitScalar('<global>');
  } else if (value.jasmineToString) {
  this.emitScalar(value.jasmineToString());
  } else if (typeof value === 'string') {
  this.emitString(value);
  } else if (jasmine.isSpy(value)) {
  this.emitScalar("spy on " + value.identity);
  } else if (value instanceof RegExp) {
  this.emitScalar(value.toString());
  } else if (typeof value === 'function') {
  this.emitScalar('Function');
  } else if (typeof value.nodeType === 'number') {
  this.emitScalar('HTMLNode');
  } else if (value instanceof Date) {
  this.emitScalar('Date(' + value + ')');
  } else if (value.__Jasmine_been_here_before__) {
  this.emitScalar('<circular reference: ' + (jasmine.isArray_(value) ? 'Array' : 'Object') + '>');
  } else if (jasmine.isArray_(value) || typeof value == 'object') {
  value.__Jasmine_been_here_before__ = true;
  if (jasmine.isArray_(value)) {
  this.emitArray(value);
  } else {
  this.emitObject(value);
  }
  delete value.__Jasmine_been_here_before__;
  } else {
  this.emitScalar(value.toString());
  }
  } finally {
  this.ppNestLevel_--;
  }
  };
 
  jasmine.PrettyPrinter.prototype.iterateObject = function (obj, fn) {
  for (var property in obj) {
  if (property == '__Jasmine_been_here_before__') continue;
  fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined &&
  obj.__lookupGetter__(property) !== null) : false);
  }
  };
 
  jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_;
  jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_;
  jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_;
  jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_;
 
  jasmine.StringPrettyPrinter = function () {
  jasmine.PrettyPrinter.call(this);
 
  this.string = '';
  };
  jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter);
 
  jasmine.StringPrettyPrinter.prototype.emitScalar = function (value) {
  this.append(value);
  };
 
  jasmine.StringPrettyPrinter.prototype.emitString = function (value) {
  this.append("'" + value + "'");
  };
 
  jasmine.StringPrettyPrinter.prototype.emitArray = function (array) {
  this.append('[ ');
  for (var i = 0; i < array.length; i++) {
  if (i > 0) {
  this.append(', ');
  }
  this.format(array[i]);
  }
  this.append(' ]');
  };
 
  jasmine.StringPrettyPrinter.prototype.emitObject = function (obj) {
  var self = this;
  this.append('{ ');
  var first = true;
 
  this.iterateObject(obj, function (property, isGetter) {
  if (first) {
  first = false;
  } else {
  self.append(', ');
  }
 
  self.append(property);
  self.append(' : ');
  if (isGetter) {
  self.append('<getter>');
  } else {
  self.format(obj[property]);
  }
  });
 
  this.append(' }');
  };
 
  jasmine.StringPrettyPrinter.prototype.append = function (value) {
  this.string += value;
  };
  jasmine.Queue = function (env) {
  this.env = env;
  this.blocks = [];
  this.running = false;
  this.index = 0;
  this.offset = 0;
  this.abort = false;
  };
 
  jasmine.Queue.prototype.addBefore = function (block) {
  this.blocks.unshift(block);
  };
 
  jasmine.Queue.prototype.add = function (block) {
  this.blocks.push(block);
  };
 
  jasmine.Queue.prototype.insertNext = function (block) {
  this.blocks.splice((this.index + this.offset + 1), 0, block);
  this.offset++;
  };
 
  jasmine.Queue.prototype.start = function (onComplete) {
  this.running = true;
  this.onComplete = onComplete;
  this.next_();
  };
 
  jasmine.Queue.prototype.isRunning = function () {
  return this.running;
  };
 
  jasmine.Queue.LOOP_DONT_RECURSE = true;
 
  jasmine.Queue.prototype.next_ = function () {
  var self = this;
  var goAgain = true;
 
  while (goAgain) {
  goAgain = false;
 
  if (self.index < self.blocks.length && !this.abort) {
  var calledSynchronously = true;
  var completedSynchronously = false;
 
  var onComplete = function () {
  if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
  completedSynchronously = true;
  return;
  }
 
  if (self.blocks[self.index].abort) {
  self.abort = true;
  }
 
  self.offset = 0;
  self.index++;
 
  var now = new Date().getTime();
  if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
  self.env.lastUpdate = now;
  self.env.setTimeout(function () {
  self.next_();
  }, 0);
  } else {
  if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
  goAgain = true;
  } else {
  self.next_();
  }
  }
  };
  self.blocks[self.index].execute(onComplete);
 
  calledSynchronously = false;
  if (completedSynchronously) {
  onComplete();
  }
 
  } else {
  self.running = false;
  if (self.onComplete) {
  self.onComplete();
  }
  }
  }
  };
 
  jasmine.Queue.prototype.results = function () {
  var results = new jasmine.NestedResults();
  for (var i = 0; i < this.blocks.length; i++) {
  if (this.blocks[i].results) {
  results.addResult(this.blocks[i].results());
  }
  }
  return results;
  };
 
 
  /**
  * Runner
  *
  * @constructor
  * @param {jasmine.Env} env
  */
  jasmine.Runner = function (env) {
  var self = this;
  self.env = env;
  self.queue = new jasmine.Queue(env);
  self.before_ = [];
  self.after_ = [];
  self.suites_ = [];
  };
 
  jasmine.Runner.prototype.execute = function () {
  var self = this;
  if (self.env.reporter.reportRunnerStarting) {
  self.env.reporter.reportRunnerStarting(this);
  }
  self.queue.start(function () {
  self.finishCallback();
  });
  };
 
  jasmine.Runner.prototype.beforeEach = function (beforeEachFunction) {
  beforeEachFunction.typeName = 'beforeEach';
  this.before_.splice(0, 0, beforeEachFunction);
  };
 
  jasmine.Runner.prototype.afterEach = function (afterEachFunction) {
  afterEachFunction.typeName = 'afterEach';
  this.after_.splice(0, 0, afterEachFunction);
  };
 
 
  jasmine.Runner.prototype.finishCallback = function () {
  this.env.reporter.reportRunnerResults(this);
  };
 
  jasmine.Runner.prototype.addSuite = function (suite) {
  this.suites_.push(suite);
  };
 
  jasmine.Runner.prototype.add = function (block) {
  if (block instanceof jasmine.Suite) {
  this.addSuite(block);
  }
  this.queue.add(block);
  };
 
  jasmine.Runner.prototype.specs = function () {
  var suites = this.suites();
  var specs = [];
  for (var i = 0; i < suites.length; i++) {
  specs = specs.concat(suites[i].specs());
  }
  return specs;
  };
 
  jasmine.Runner.prototype.suites = function () {
  return this.suites_;
  };
 
  jasmine.Runner.prototype.topLevelSuites = function () {
  var topLevelSuites = [];
  for (var i = 0; i < this.suites_.length; i++) {
  if (!this.suites_[i].parentSuite) {
  topLevelSuites.push(this.suites_[i]);
  }
  }
  return topLevelSuites;
  };
 
  jasmine.Runner.prototype.results = function () {
  return this.queue.results();
  };
  /**
  * Internal representation of a Jasmine specification, or test.
  *
  * @constructor
  * @param {jasmine.Env} env
  * @param {jasmine.Suite} suite
  * @param {String} description
  */
  jasmine.Spec = function (env, suite, description) {
  if (!env) {
  throw new Error('jasmine.Env() required');
  }
  if (!suite) {
  throw new Error('jasmine.Suite() required');
  }
  var spec = this;
  spec.id = env.nextSpecId ? env.nextSpecId() : null;
  spec.env = env;
  spec.suite = suite;
  spec.description = description;
  spec.queue = new jasmine.Queue(env);
 
  spec.afterCallbacks = [];
  spec.spies_ = [];
 
  spec.results_ = new jasmine.NestedResults();
  spec.results_.description = description;
  spec.matchersClass = null;
  };
 
  jasmine.Spec.prototype.getFullName = function () {
  return this.suite.getFullName() + ' ' + this.description + '.';
  };
 
 
  jasmine.Spec.prototype.results = function () {
  return this.results_;
  };
 
  /**
  * All parameters are pretty-printed and concatenated together, then written to the spec's output.
  *
  * Be careful not to leave calls to <code>jasmine.log</code> in production code.
  */
  jasmine.Spec.prototype.log = function () {
  return this.results_.log(arguments);
  };
 
  jasmine.Spec.prototype.runs = function (func) {
  var block = new jasmine.Block(this.env, func, this);
  this.addToQueue(block);
  return this;
  };
 
  jasmine.Spec.prototype.addToQueue = function (block) {
  if (this.queue.isRunning()) {
  this.queue.insertNext(block);
  } else {
  this.queue.add(block);
  }
  };
 
  /**
  * @param {jasmine.ExpectationResult} result
  */
  jasmine.Spec.prototype.addMatcherResult = function (result) {
  this.results_.addResult(result);
  };
 
  jasmine.Spec.prototype.expect = function (actual) {
  var positive = new (this.getMatchersClass_())(this.env, actual, this);
  positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
  return positive;
  };
 
  /**
  * Waits a fixed time period before moving to the next block.
  *
  * @deprecated Use waitsFor() instead
  * @param {Number} timeout milliseconds to wait
  */
  jasmine.Spec.prototype.waits = function (timeout) {
  var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this);
  this.addToQueue(waitsFunc);
  return this;
  };
 
  /**
  * Waits for the latchFunction to return true before proceeding to the next block.
  *
  * @param {Function} latchFunction
  * @param {String} optional_timeoutMessage
  * @param {Number} optional_timeout
  */
  jasmine.Spec.prototype.waitsFor = function (latchFunction, optional_timeoutMessage, optional_timeout) {
  var latchFunction_ = null;
  var optional_timeoutMessage_ = null;
  var optional_timeout_ = null;
 
  for (var i = 0; i < arguments.length; i++) {
  var arg = arguments[i];
  switch (typeof arg) {
  case 'function':
  latchFunction_ = arg;
  break;
  case 'string':
  optional_timeoutMessage_ = arg;
  break;
  case 'number':
  optional_timeout_ = arg;
  break;
  }
  }
 
  var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this);
  this.addToQueue(waitsForFunc);
  return this;
  };
 
  jasmine.Spec.prototype.fail = function (e) {
  var expectationResult = new jasmine.ExpectationResult({
  passed: false,
  message: e ? jasmine.util.formatException(e) : 'Exception',
  trace: { stack: e.stack }
  });
  this.results_.addResult(expectationResult);
  };
 
  jasmine.Spec.prototype.getMatchersClass_ = function () {
  return this.matchersClass || this.env.matchersClass;
  };
 
  jasmine.Spec.prototype.addMatchers = function (matchersPrototype) {
  var parent = this.getMatchersClass_();
  var newMatchersClass = function () {
  parent.apply(this, arguments);
  };
  jasmine.util.inherit(newMatchersClass, parent);
  jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
  this.matchersClass = newMatchersClass;
  };
 
  jasmine.Spec.prototype.finishCallback = function () {
  this.env.reporter.reportSpecResults(this);
  };
 
  jasmine.Spec.prototype.finish = function (onComplete) {
  this.removeAllSpies();
  this.finishCallback();
  if (onComplete) {
  onComplete();
  }
  };
 
  jasmine.Spec.prototype.after = function (doAfter) {
  if (this.queue.isRunning()) {
  this.queue.add(new jasmine.Block(this.env, doAfter, this));
  } else {
  this.afterCallbacks.unshift(doAfter);
  }
  };
 
  jasmine.Spec.prototype.execute = function (onComplete) {
  var spec = this;
  if (!spec.env.specFilter(spec)) {
  spec.results_.skipped = true;
  spec.finish(onComplete);
  return;
  }
 
  this.env.reporter.reportSpecStarting(this);
 
  spec.env.currentSpec = spec;
 
  spec.addBeforesAndAftersToQueue();
 
  spec.queue.start(function () {
  spec.finish(onComplete);
  });
  };
 
  jasmine.Spec.prototype.addBeforesAndAftersToQueue = function () {
  var runner = this.env.currentRunner();
  var i;
 
  for (var suite = this.suite; suite; suite = suite.parentSuite) {
  for (i = 0; i < suite.before_.length; i++) {
  this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this));
  }
  }
  for (i = 0; i < runner.before_.length; i++) {
  this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
  }
  for (i = 0; i < this.afterCallbacks.length; i++) {
  this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this));
  }
  for (suite = this.suite; suite; suite = suite.parentSuite) {
  for (i = 0; i < suite.after_.length; i++) {
  this.queue.add(new jasmine.Block(this.env, suite.after_[i], this));
  }
  }
  for (i = 0; i < runner.after_.length; i++) {
  this.queue.add(new jasmine.Block(this.env, runner.after_[i], this));
  }
  };
 
  jasmine.Spec.prototype.explodes = function () {
  throw 'explodes function should not have been called';
  };
 
  jasmine.Spec.prototype.spyOn = function (obj, methodName, ignoreMethodDoesntExist) {
  if (obj == jasmine.undefined) {
  throw "spyOn could not find an object to spy upon for " + methodName + "()";
  }
 
  if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) {
  throw methodName + '() method does not exist';
  }
 
  if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
  throw new Error(methodName + ' has already been spied upon');
  }
 
  var spyObj = jasmine.createSpy(methodName);
 
  this.spies_.push(spyObj);
  spyObj.baseObj = obj;
  spyObj.methodName = methodName;
  spyObj.originalValue = obj[methodName];
 
  obj[methodName] = spyObj;
 
  return spyObj;
  };
 
  jasmine.Spec.prototype.removeAllSpies = function () {
  for (var i = 0; i < this.spies_.length; i++) {
  var spy = this.spies_[i];
  spy.baseObj[spy.methodName] = spy.originalValue;
  }
  this.spies_ = [];
  };
 
  /**
  * Internal representation of a Jasmine suite.
  *
  * @constructor
  * @param {jasmine.Env} env
  * @param {String} description
  * @param {Function} specDefinitions
  * @param {jasmine.Suite} parentSuite
  */
  jasmine.Suite = function (env, description, specDefinitions, parentSuite) {
  var self = this;
  self.id = env.nextSuiteId ? env.nextSuiteId() : null;
  self.description = description;
  self.queue = new jasmine.Queue(env);
  self.parentSuite = parentSuite;
  self.env = env;
  self.before_ = [];
  self.after_ = [];
  self.children_ = [];
  self.suites_ = [];
  self.specs_ = [];
  };
 
  jasmine.Suite.prototype.getFullName = function () {
  var fullName = this.description;
  for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
  fullName = parentSuite.description + ' ' + fullName;
  }
  return fullName;
  };
 
  jasmine.Suite.prototype.finish = function (onComplete) {
  this.env.reporter.reportSuiteResults(this);
  this.finished = true;
  if (typeof(onComplete) == 'function') {
  onComplete();
  }
  };
 
  jasmine.Suite.prototype.beforeEach = function (beforeEachFunction) {
  beforeEachFunction.typeName = 'beforeEach';
  this.before_.unshift(beforeEachFunction);
  };
 
  jasmine.Suite.prototype.afterEach = function (afterEachFunction) {
  afterEachFunction.typeName = 'afterEach';
  this.after_.unshift(afterEachFunction);
  };
 
  jasmine.Suite.prototype.results = function () {
  return this.queue.results();
  };
 
  jasmine.Suite.prototype.add = function (suiteOrSpec) {
  this.children_.push(suiteOrSpec);
  if (suiteOrSpec instanceof jasmine.Suite) {
  this.suites_.push(suiteOrSpec);
  this.env.currentRunner().addSuite(suiteOrSpec);
  } else {
  this.specs_.push(suiteOrSpec);
  }
  this.queue.add(suiteOrSpec);
  };
 
  jasmine.Suite.prototype.specs = function () {
  return this.specs_;
  };
 
  jasmine.Suite.prototype.suites = function () {
  return this.suites_;
  };
 
  jasmine.Suite.prototype.children = function () {
  return this.children_;
  };
 
  jasmine.Suite.prototype.execute = function (onComplete) {
  var self = this;
  this.queue.start(function () {
  self.finish(onComplete);
  });
  };
  jasmine.WaitsBlock = function (env, timeout, spec) {
  this.timeout = timeout;
  jasmine.Block.call(this, env, null, spec);
  };
 
  jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
 
  jasmine.WaitsBlock.prototype.execute = function (onComplete) {
  if (jasmine.VERBOSE) {
  this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
  }
  this.env.setTimeout(function () {
  onComplete();
  }, this.timeout);
  };
  /**
  * A block which waits for some condition to become true, with timeout.
  *
  * @constructor
  * @extends jasmine.Block
  * @param {jasmine.Env} env The Jasmine environment.
  * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
  * @param {Function} latchFunction A function which returns true when the desired condition has been met.
  * @param {String} message The message to display if the desired condition hasn't been met within the given time period.
  * @param {jasmine.Spec} spec The Jasmine spec.
  */
  jasmine.WaitsForBlock = function (env, timeout, latchFunction, message, spec) {
  this.timeout = timeout || env.defaultTimeoutInterval;
  this.latchFunction = latchFunction;
  this.message = message;
  this.totalTimeSpentWaitingForLatch = 0;
  jasmine.Block.call(this, env, null, spec);
  };
  jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
 
  jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
 
  jasmine.WaitsForBlock.prototype.execute = function (onComplete) {
  if (jasmine.VERBOSE) {
  this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
  }
  var latchFunctionResult;
  try {
  latchFunctionResult = this.latchFunction.apply(this.spec);
  } catch (e) {
  this.spec.fail(e);
  onComplete();
  return;
  }
 
  if (latchFunctionResult) {
  onComplete();
  } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) {
  var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen');
  this.spec.fail({
  name: 'timeout',
  message: message
  });
 
  this.abort = true;
  onComplete();
  } else {
  this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT;
  var self = this;
  this.env.setTimeout(function () {
  self.execute(onComplete);
  }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
  }
  };
 
  jasmine.version_ = {
  "major": 1,
  "minor": 2,
  "build": 0,
  "revision": 1337005947
  };
 
 Binary files /dev/null and b/js/flotr2/lib/jasmine/jasmine_favicon.png differ
  /* Prototype JavaScript framework, version 1.6.0.3
  * (c) 2005-2008 Sam Stephenson
  *
  * Prototype is freely distributable under the terms of an MIT-style license.
  * For details, see the Prototype web site: http://www.prototypejs.org/
  *
  *--------------------------------------------------------------------------*/
 
  var Prototype = {
  Version: '1.6.0.3',
 
  Browser: {
  IE: !!(window.attachEvent &&
  navigator.userAgent.indexOf('Opera') === -1),
  Opera: navigator.userAgent.indexOf('Opera') > -1,
  WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
  Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
  navigator.userAgent.indexOf('KHTML') === -1,
  MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },
 
  BrowserFeatures: {
  XPath: !!document.evaluate,
  SelectorsAPI: !!document.querySelector,
  ElementExtensions: !!window.HTMLElement,
  SpecificElementExtensions:
  document.createElement('div')['__proto__'] &&
  document.createElement('div')['__proto__'] !==
  document.createElement('form')['__proto__']
  },
 
  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
 
  emptyFunction: function() { },
  K: function(x) { return x }
  };
 
  if (Prototype.Browser.MobileSafari)
  Prototype.BrowserFeatures.SpecificElementExtensions = false;
 
 
  /* Based on Alex Arnell's inheritance implementation. */
  var Class = {
  create: function() {
  var parent = null, properties = $A(arguments);
  if (Object.isFunction(properties[0]))
  parent = properties.shift();
 
  function klass() {
  this.initialize.apply(this, arguments);
  }
 
  Object.extend(klass, Class.Methods);
  klass.superclass = parent;
  klass.subclasses = [];
 
  if (parent) {
  var subclass = function() { };
  subclass.prototype = parent.prototype;
  klass.prototype = new subclass;
  parent.subclasses.push(klass);
  }
 
  for (var i = 0; i < properties.length; i++)
  klass.addMethods(properties[i]);
 
  if (!klass.prototype.initialize)
  klass.prototype.initialize = Prototype.emptyFunction;
 
  klass.prototype.constructor = klass;
 
  return klass;
  }
  };
 
  Class.Methods = {
  addMethods: function(source) {
  var ancestor = this.superclass && this.superclass.prototype;
  var properties = Object.keys(source);
 
  if (!Object.keys({ toString: true }).length)
  properties.push("toString", "valueOf");
 
  for (var i = 0, length = properties.length; i < length; i++) {
  var property = properties[i], value = source[property];
  if (ancestor && Object.isFunction(value) &&
  value.argumentNames().first() == "$super") {
  var method = value;
  value = (function(m) {
  return function() { return ancestor[m].apply(this, arguments) };
  })(property).wrap(method);
 
  value.valueOf = method.valueOf.bind(method);
  value.toString = method.toString.bind(method);
  }
  this.prototype[property] = value;
  }
 
  return this;
  }
  };
 
  var Abstract = { };
 
  Object.extend = function(destination, source) {
  for (var property in source)
  destination[property] = source[property];
  return destination;
  };
 
  Object.extend(Object, {
  inspect: function(object) {
  try {
  if (Object.isUndefined(object)) return 'undefined';
  if (object === null) return 'null';
  return object.inspect ? object.inspect() : String(object);
  } catch (e) {
  if (e instanceof RangeError) return '...';
  throw e;
  }
  },
 
  toJSON: function(object) {
  var type = typeof object;
  switch (type) {
  case 'undefined':
  case 'function':
  case 'unknown': return;
  case 'boolean': return object.toString();
  }
 
  if (object === null) return 'null';
  if (object.toJSON) return object.toJSON();
  if (Object.isElement(object)) return;
 
  var results = [];
  for (var property in object) {
  var value = Object.toJSON(object[property]);
  if (!Object.isUndefined(value))
  results.push(property.toJSON() + ': ' + value);
  }
 
  return '{' + results.join(', ') + '}';
  },
 
  toQueryString: function(object) {
  return $H(object).toQueryString();
  },
 
  toHTML: function(object) {
  return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },
 
  keys: function(object) {
  var keys = [];
  for (var property in object)
  keys.push(property);
  return keys;
  },
 
  values: function(object) {
  var values = [];
  for (var property in object)
  values.push(object[property]);
  return values;
  },
 
  clone: function(object) {
  return Object.extend({ }, object);
  },
 
  isElement: function(object) {
  return !!(object && object.nodeType == 1);
  },
 
  isArray: function(object) {
  return object != null && typeof object == "object" &&
  'splice' in object && 'join' in object;
  },
 
  isHash: function(object) {
  return object instanceof Hash;
  },
 
  isFunction: function(object) {
  return typeof object == "function";
  },
 
  isString: function(object) {
  return typeof object == "string";
  },
 
  isNumber: function(object) {
  return typeof object == "number";
  },
 
  isUndefined: function(object) {
  return typeof object == "undefined";
  }
  });
 
  Object.extend(Function.prototype, {
  argumentNames: function() {
  var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
  .replace(/\s+/g, '').split(',');
  return names.length == 1 && !names[0] ? [] : names;
  },
 
  bind: function() {
  if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
  return __method.apply(object, args.concat($A(arguments)));
  }
  },
 
  bindAsEventListener: function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
  return __method.apply(object, [event || window.event].concat(args));
  }
  },
 
  curry: function() {
  if (!arguments.length) return this;
  var __method = this, args = $A(arguments);
  return function() {
  return __method.apply(this, args.concat($A(arguments)));
  }
  },
 
  delay: function() {
  var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
  return window.setTimeout(function() {
  return __method.apply(__method, args);
  }, timeout);
  },
 
  defer: function() {
  var args = [0.01].concat($A(arguments));
  return this.delay.apply(this, args);
  },
 
  wrap: function(wrapper) {
  var __method = this;
  return function() {
  return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
  }
  },
 
  methodize: function() {
  if (this._methodized) return this._methodized;
  var __method = this;
  return this._methodized = function() {
  return __method.apply(null, [this].concat($A(arguments)));
  };
  }
  });
 
  Date.prototype.toJSON = function() {
  return '"' + this.getUTCFullYear() + '-' +
  (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
  this.getUTCDate().toPaddedString(2) + 'T' +
  this.getUTCHours().toPaddedString(2) + ':' +
  this.getUTCMinutes().toPaddedString(2) + ':' +
  this.getUTCSeconds().toPaddedString(2) + 'Z"';
  };
 
  var Try = {
  these: function() {
  var returnValue;
 
  for (var i = 0, length = arguments.length; i < length; i++) {
  var lambda = arguments[i];
  try {
  returnValue = lambda();
  break;
  } catch (e) { }
  }
 
  return returnValue;
  }
  };
 
  RegExp.prototype.match = RegExp.prototype.test;
 
  RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  };
 
  /*--------------------------------------------------------------------------*/
 
  var PeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
  this.callback = callback;
  this.frequency = frequency;
  this.currentlyExecuting = false;
 
  this.registerCallback();
  },
 
  registerCallback: function() {
  this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },
 
  execute: function() {
  this.callback(this);
  },
 
  stop: function() {
  if (!this.timer) return;
  clearInterval(this.timer);
  this.timer = null;
  },
 
  onTimerEvent: function() {
  if (!this.currentlyExecuting) {
  try {
  this.currentlyExecuting = true;
  this.execute();
  } finally {
  this.currentlyExecuting = false;
  }
  }
  }
  });
  Object.extend(String, {
  interpret: function(value) {
  return value == null ? '' : String(value);
  },
  specialChar: {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '\\': '\\\\'
  }
  });
 
  Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
  var result = '', source = this, match;
  replacement = arguments.callee.prepareReplacement(replacement);
 
  while (source.length > 0) {
  if (match = source.match(pattern)) {
  result += source.slice(0, match.index);
  result += String.interpret(replacement(match));
  source = source.slice(match.index + match[0].length);
  } else {
  result += source, source = '';
  }
  }
  return result;
  },
 
  sub: function(pattern, replacement, count) {
  replacement = this.gsub.prepareReplacement(replacement);
  count = Object.isUndefined(count) ? 1 : count;
 
  return this.gsub(pattern, function(match) {
  if (--count < 0) return match[0];
  return replacement(match);
  });
  },
 
  scan: function(pattern, iterator) {
  this.gsub(pattern, iterator);
  return String(this);
  },
 
  truncate: function(length, truncation) {
  length = length || 30;
  truncation = Object.isUndefined(truncation) ? '...' : truncation;
  return this.length > length ?
  this.slice(0, length - truncation.length) + truncation : String(this);
  },
 
  strip: function() {
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },
 
  stripTags: function() {
  return this.replace(/<\/?[^>]+>/gi, '');
  },
 
  stripScripts: function() {
  return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },
 
  extractScripts: function() {
  var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  return (this.match(matchAll) || []).map(function(scriptTag) {
  return (scriptTag.match(matchOne) || ['', ''])[1];
  });
  },
 
  evalScripts: function() {
  return this.extractScripts().map(function(script) { return eval(script) });
  },
 
  escapeHTML: function() {
  var self = arguments.callee;
  self.text.data = this;
  return self.div.innerHTML;
  },
 
  unescapeHTML: function() {
  var div = new Element('div');
  div.innerHTML = this.stripTags();
  return div.childNodes[0] ? (div.childNodes.length > 1 ?
  $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
  div.childNodes[0].nodeValue) : '';
  },
 
  toQueryParams: function(separator) {
  var match = this.strip().match(/([^?#]*)(#.*)?$/);
  if (!match) return { };
 
  return match[1].split(separator || '&').inject({ }, function(hash, pair) {
  if ((pair = pair.split('='))[0]) {
  var key = decodeURIComponent(pair.shift());
  var value = pair.length > 1 ? pair.join('=') : pair[0];
  if (value != undefined) value = decodeURIComponent(value);
 
  if (key in hash) {
  if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
  hash[key].push(value);
  }
  else hash[key] = value;
  }
  return hash;
  });
  },
 
  toArray: function() {
  return this.split('');
  },
 
  succ: function() {
  return this.slice(0, this.length - 1) +
  String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },
 
  times: function(count) {
  return count < 1 ? '' : new Array(count + 1).join(this);
  },
 
  camelize: function() {
  var parts = this.split('-'), len = parts.length;
  if (len == 1) return parts[0];
 
  var camelized = this.charAt(0) == '-'
  ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  : parts[0];
 
  for (var i = 1; i < len; i++)
  camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
 
  return camelized;
  },
 
  capitalize: function() {
  return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },
 
  underscore: function() {
  return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },
 
  dasherize: function() {
  return this.gsub(/_/,'-');
  },
 
  inspect: function(useDoubleQuotes) {
  var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
  var character = String.specialChar[match[0]];
  return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  });
  if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },
 
  toJSON: function() {
  return this.inspect(true);
  },
 
  unfilterJSON: function(filter) {
  return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },
 
  isJSON: function() {
  var str = this;
  if (str.blank()) return false;
  str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },
 
  evalJSON: function(sanitize) {
  var json = this.unfilterJSON();
  try {
  if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  } catch (e) { }
  throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },
 
  include: function(pattern) {
  return this.indexOf(pattern) > -1;
  },
 
  startsWith: function(pattern) {
  return this.indexOf(pattern) === 0;
  },
 
  endsWith: function(pattern) {
  var d = this.length - pattern.length;
  return d >= 0 && this.lastIndexOf(pattern) === d;
  },
 
  empty: function() {
  return this == '';
  },
 
  blank: function() {
  return /^\s*$/.test(this);
  },
 
  interpolate: function(object, pattern) {
  return new Template(this, pattern).evaluate(object);
  }
  });
 
  if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
  return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
  return this.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
  });
 
  String.prototype.gsub.prepareReplacement = function(replacement) {
  if (Object.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
  };
 
  String.prototype.parseQuery = String.prototype.toQueryParams;
 
  Object.extend(String.prototype.escapeHTML, {
  div: document.createElement('div'),
  text: document.createTextNode('')
  });
 
  String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
 
  var Template = Class.create({
  initialize: function(template, pattern) {
  this.template = template.toString();
  this.pattern = pattern || Template.Pattern;
  },
 
  evaluate: function(object) {
  if (Object.isFunction(object.toTemplateReplacements))
  object = object.toTemplateReplacements();
 
  return this.template.gsub(this.pattern, function(match) {
  if (object == null) return '';
 
  var before = match[1] || '';
  if (before == '\\') return match[2];
 
  var ctx = object, expr = match[3];
  var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
  match = pattern.exec(expr);
  if (match == null) return before;
 
  while (match != null) {
  var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
  ctx = ctx[comp];
  if (null == ctx || '' == match[3]) break;
  expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
  match = pattern.exec(expr);
  }
 
  return before + String.interpret(ctx);
  });
  }
  });
  Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
 
  var $break = { };
 
  var Enumerable = {
  each: function(iterator, context) {
  var index = 0;
  try {
  this._each(function(value) {
  iterator.call(context, value, index++);
  });
  } catch (e) {
  if (e != $break) throw e;
  }
  return this;
  },
 
  eachSlice: function(number, iterator, context) {
  var index = -number, slices = [], array = this.toArray();
  if (number < 1) return array;
  while ((index += number) < array.length)
  slices.push(array.slice(index, index+number));
  return slices.collect(iterator, context);
  },
 
  all: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var result = true;
  this.each(function(value, index) {
  result = result && !!iterator.call(context, value, index);
  if (!result) throw $break;
  });
  return result;
  },
 
  any: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var result = false;
  this.each(function(value, index) {
  if (result = !!iterator.call(context, value, index))
  throw $break;
  });
  return result;
  },
 
  collect: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var results = [];
  this.each(function(value, index) {
  results.push(iterator.call(context, value, index));
  });
  return results;
  },
 
  detect: function(iterator, context) {
  var result;
  this.each(function(value, index) {
  if (iterator.call(context, value, index)) {
  result = value;
  throw $break;
  }
  });
  return result;
  },
 
  findAll: function(iterator, context) {
  var results = [];
  this.each(function(value, index) {
  if (iterator.call(context, value, index))
  results.push(value);
  });
  return results;
  },
 
  grep: function(filter, iterator, context) {
  iterator = iterator || Prototype.K;
  var results = [];
 
  if (Object.isString(filter))
  filter = new RegExp(filter);
 
  this.each(function(value, index) {
  if (filter.match(value))
  results.push(iterator.call(context, value, index));
  });
  return results;
  },
 
  include: function(object) {
  if (Object.isFunction(this.indexOf))
  if (this.indexOf(object) != -1) return true;
 
  var found = false;
  this.each(function(value) {
  if (value == object) {
  found = true;
  throw $break;
  }
  });
  return found;
  },
 
  inGroupsOf: function(number, fillWith) {
  fillWith = Object.isUndefined(fillWith) ? null : fillWith;
  return this.eachSlice(number, function(slice) {
  while(slice.length < number) slice.push(fillWith);
  return slice;
  });
  },
 
  inject: function(memo, iterator, context) {
  this.each(function(value, index) {
  memo = iterator.call(context, memo, value, index);
  });
  return memo;
  },
 
  invoke: function(method) {
  var args = $A(arguments).slice(1);
  return this.map(function(value) {
  return value[method].apply(value, args);
  });
  },
 
  max: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var result;
  this.each(function(value, index) {
  value = iterator.call(context, value, index);
  if (result == null || value >= result)
  result = value;
  });
  return result;
  },
 
  min: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var result;
  this.each(function(value, index) {
  value = iterator.call(context, value, index);
  if (result == null || value < result)
  result = value;
  });
  return result;
  },
 
  partition: function(iterator, context) {
  iterator = iterator || Prototype.K;
  var trues = [], falses = [];
  this.each(function(value, index) {
  (iterator.call(context, value, index) ?
  trues : falses).push(value);
  });
  return [trues, falses];
  },
 
  pluck: function(property) {
  var results = [];
  this.each(function(value) {
  results.push(value[property]);
  });
  return results;
  },
 
  reject: function(iterator, context) {
  var results = [];
  this.each(function(value, index) {
  if (!iterator.call(context, value, index))
  results.push(value);
  });
  return results;
  },
 
  sortBy: function(iterator, context) {
  return this.map(function(value, index) {
  return {
  value: value,
  criteria: iterator.call(context, value, index)
  };
  }).sort(function(left, right) {
  var a = left.criteria, b = right.criteria;
  return a < b ? -1 : a > b ? 1 : 0;
  }).pluck('value');
  },
 
  toArray: function() {
  return this.map();
  },
 
  zip: function() {
  var iterator = Prototype.K, args = $A(arguments);
  if (Object.isFunction(args.last()))
  iterator = args.pop();
 
  var collections = [this].concat(args).map($A);
  return this.map(function(value, index) {
  return iterator(collections.pluck(index));
  });
  },
 
  size: function() {
  return this.toArray().length;
  },
 
  inspect: function() {
  return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
  };
 
  Object.extend(Enumerable, {
  map: Enumerable.collect,
  find: Enumerable.detect,
  select: Enumerable.findAll,
  filter: Enumerable.findAll,
  member: Enumerable.include,
  entries: Enumerable.toArray,
  every: Enumerable.all,
  some: Enumerable.any
  });
  function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
  }
 
  if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
  if (!iterable) return [];
  // In Safari, only use the `toArray` method if it's not a NodeList.
  // A NodeList is a function, has an function `item` property, and a numeric
  // `length` property. Adapted from Google Doctype.
  if (!(typeof iterable === 'function' && typeof iterable.length ===
  'number' && typeof iterable.item === 'function') && iterable.toArray)
  return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
  };
  }
 
  Array.from = $A;
 
  Object.extend(Array.prototype, Enumerable);
 
  if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
 
  Object.extend(Array.prototype, {
  _each: function(iterator) {
  for (var i = 0, length = this.length; i < length; i++)
  iterator(this[i]);
  },
 
  clear: function() {
  this.length = 0;
  return this;
  },
 
  first: function() {
  return this[0];
  },
 
  last: function() {
  return this[this.length - 1];
  },
 
  compact: function() {
  return this.select(function(value) {
  return value != null;
  });
  },
 
  flatten: function() {
  return this.inject([], function(array, value) {
  return array.concat(Object.isArray(value) ?
  value.flatten() : [value]);
  });
  },
 
  without: function() {
  var values = $A(arguments);
  return this.select(function(value) {
  return !values.include(value);
  });
  },
 
  reverse: function(inline) {
  return (inline !== false ? this : this.toArray())._reverse();
  },
 
  reduce: function() {
  return this.length > 1 ? this : this[0];
  },
 
  uniq: function(sorted) {
  return this.inject([], function(array, value, index) {
  if (0 == index || (sorted ? array.last() != value : !array.include(value)))
  array.push(value);
  return array;
  });
  },
 
  intersect: function(array) {
  return this.uniq().findAll(function(item) {
  return array.detect(function(value) { return item === value });
  });
  },
 
  clone: function() {
  return [].concat(this);
  },
 
  size: function() {
  return this.length;
  },
 
  inspect: function() {
  return '[' + this.map(Object.inspect).join(', ') + ']';
  },
 
  toJSON: function() {
  var results = [];
  this.each(function(object) {
  var value = Object.toJSON(object);
  if (!Object.isUndefined(value)) results.push(value);
  });
  return '[' + results.join(', ') + ']';
  }
  });
 
  // use native browser JS 1.6 implementation if available
  if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;
 
  if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
  if (this[i] === item) return i;
  return -1;
  };
 
  if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
  };
 
  Array.prototype.toArray = Array.prototype.clone;
 
  function $w(string) {
  if (!Object.isString(string)) return [];
  string = string.strip();
  return string ? string.split(/\s+/) : [];
  }
 
  if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
  var array = [];
  for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  for (var i = 0, length = arguments.length; i < length; i++) {
  if (Object.isArray(arguments[i])) {
  for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  array.push(arguments[i][j]);
  } else {
  array.push(arguments[i]);
  }
  }
  return array;
  };
  }
  Object.extend(Number.prototype, {
  toColorPart: function() {
  return this.toPaddedString(2, 16);
  },
 
  succ: function() {
  return this + 1;
  },
 
  times: function(iterator, context) {
  $R(0, this, true).each(iterator, context);
  return this;
  },
 
  toPaddedString: function(length, radix) {
  var string = this.toString(radix || 10);
  return '0'.times(length - string.length) + string;
  },
 
  toJSON: function() {
  return isFinite(this) ? this.toString() : 'null';
  }
  });
 
  $w('abs round ceil floor').each(function(method){
  Number.prototype[method] = Math[method].methodize();
  });
  function $H(object) {
  return new Hash(object);
  };
 
  var Hash = Class.create(Enumerable, (function() {
 
  function toQueryPair(key, value) {
  if (Object.isUndefined(value)) return key;
  return key + '=' + encodeURIComponent(String.interpret(value));
  }
 
  return {
  initialize: function(object) {
  this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
  },
 
  _each: function(iterator) {
  for (var key in this._object) {
  var value = this._object[key], pair = [key, value];
  pair.key = key;
  pair.value = value;
  iterator(pair);
  }
  },
 
  set: function(key, value) {
  return this._object[key] = value;
  },
 
  get: function(key) {
  // simulating poorly supported hasOwnProperty
  if (this._object[key] !== Object.prototype[key])
  return this._object[key];
  },
 
  unset: function(key) {
  var value = this._object[key];
  delete this._object[key];
  return value;
  },
 
  toObject: function() {
  return Object.clone(this._object);
  },
 
  keys: function() {
  return this.pluck('key');
  },
 
  values: function() {
  return this.pluck('value');
  },
 
  index: function(value) {
  var match = this.detect(function(pair) {
  return pair.value === value;
  });
  return match && match.key;
  },
 
  merge: function(object) {
  return this.clone().update(object);
  },
 
  update: function(object) {
  return new Hash(object).inject(this, function(result, pair) {
  result.set(pair.key, pair.value);
  return result;
  });
  },
 
  toQueryString: function() {
  return this.inject([], function(results, pair) {
  var key = encodeURIComponent(pair.key), values = pair.value;
 
  if (values && typeof values == 'object') {
  if (Object.isArray(values))
  return results.concat(values.map(toQueryPair.curry(key)));
  } else results.push(toQueryPair(key, values));
  return results;
  }).join('&');
  },
 
  inspect: function() {
  return '#<Hash:{' + this.map(function(pair) {
  return pair.map(Object.inspect).join(': ');
  }).join(', ') + '}>';
  },
 
  toJSON: function() {
  return Object.toJSON(this.toObject());
  },
 
  clone: function() {
  return new Hash(this);
  }
  }
  })());
 
  Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
  Hash.from = $H;
  var ObjectRange = Class.create(Enumerable, {
  initialize: function(start, end, exclusive) {
  this.start = start;
  this.end = end;
  this.exclusive = exclusive;
  },
 
  _each: function(iterator) {
  var value = this.start;
  while (this.include(value)) {
  iterator(value);
  value = value.succ();
  }
  },
 
  include: function(value) {
  if (value < this.start)
  return false;
  if (this.exclusive)
  return value < this.end;
  return value <= this.end;
  }
  });
 
  var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
  };
 
  var Ajax = {
  getTransport: function() {
  return Try.these(
  function() {return new XMLHttpRequest()},
  function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  ) || false;
  },
 
  activeRequestCount: 0
  };
 
  Ajax.Responders = {
  responders: [],
 
  _each: function(iterator) {
  this.responders._each(iterator);
  },
 
  register: function(responder) {
  if (!this.include(responder))
  this.responders.push(responder);
  },
 
  unregister: function(responder) {
  this.responders = this.responders.without(responder);
  },
 
  dispatch: function(callback, request, transport, json) {
  this.each(function(responder) {
  if (Object.isFunction(responder[callback])) {
  try {
  responder[callback].apply(responder, [request, transport, json]);
  } catch (e) { }
  }
  });
  }
  };
 
  Object.extend(Ajax.Responders, Enumerable);
 
  Ajax.Responders.register({
  onCreate: function() { Ajax.activeRequestCount++ },
  onComplete: function() { Ajax.activeRequestCount-- }
  });
 
  Ajax.Base = Class.create({
  initialize: function(options) {
  this.options = {
  method: 'post',
  asynchronous: true,
  contentType: 'application/x-www-form-urlencoded',
  encoding: 'UTF-8',
  parameters: '',
  evalJSON: true,
  evalJS: true
  };
  Object.extend(this.options, options || { });
 
  this.options.method = this.options.method.toLowerCase();
 
  if (Object.isString(this.options.parameters))
  this.options.parameters = this.options.parameters.toQueryParams();
  else if (Object.isHash(this.options.parameters))
  this.options.parameters = this.options.parameters.toObject();
  }
  });
 
  Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,
 
  initialize: function($super, url, options) {
  $super(options);
  this.transport = Ajax.getTransport();
  this.request(url);
  },
 
  request: function(url) {
  this.url = url;
  this.method = this.options.method;
  var params = Object.clone(this.options.parameters);
 
  if (!['get', 'post'].include(this.method)) {
  // simulate other verbs over post
  params['_method'] = this.method;
  this.method = 'post';
  }
 
  this.parameters = params;
 
  if (params = Object.toQueryString(params)) {
  // when GET, append parameters to URL
  if (this.method == 'get')
  this.url += (this.url.include('?') ? '&' : '?') + params;
  else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  params += '&_=';
  }
 
  try {
  var response = new Ajax.Response(this);
  if (this.options.onCreate) this.options.onCreate(response);
  Ajax.Responders.dispatch('onCreate', this, response);
 
  this.transport.open(this.method.toUpperCase(), this.url,
  this.options.asynchronous);
 
  if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
 
  this.transport.onreadystatechange = this.onStateChange.bind(this);
  this.setRequestHeaders();
 
  this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  this.transport.send(this.body);
 
  /* Force Firefox to handle ready state 4 for synchronous requests */
  if (!this.options.asynchronous && this.transport.overrideMimeType)
  this.onStateChange();
 
  }
  catch (e) {
  this.dispatchException(e);
  }
  },
 
  onStateChange: function() {
  var readyState = this.transport.readyState;
  if (readyState > 1 && !((readyState == 4) && this._complete))
  this.respondToReadyState(this.transport.readyState);
  },
 
  setRequestHeaders: function() {
  var headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'X-Prototype-Version': Prototype.Version,
  'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  };
 
  if (this.method == 'post') {
  headers['Content-type'] = this.options.contentType +
  (this.options.encoding ? '; charset=' + this.options.encoding : '');
 
  /* Force "Connection: close" for older Mozilla browsers to work
  * around a bug where XMLHttpRequest sends an incorrect
  * Content-length header. See Mozilla Bugzilla #246651.
  */
  if (this.transport.overrideMimeType &&
  (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  headers['Connection'] = 'close';
  }
 
  // user-defined headers
  if (typeof this.options.requestHeaders == 'object') {
  var extras = this.options.requestHeaders;
 
  if (Object.isFunction(extras.push))
  for (var i = 0, length = extras.length; i < length; i += 2)
  headers[extras[i]] = extras[i+1];
  else
  $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  }
 
  for (var name in headers)
  this.transport.setRequestHeader(name, headers[name]);
  },
 
  success: function() {
  var status = this.getStatus();
  return !status || (status >= 200 && status < 300);
  },
 
  getStatus: function() {
  try {
  return this.transport.status || 0;
  } catch (e) { return 0 }
  },
 
  respondToReadyState: function(readyState) {
  var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
 
  if (state == 'Complete') {
  try {
  this._complete = true;
  (this.options['on' + response.status]
  || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  || Prototype.emptyFunction)(response, response.headerJSON);
  } catch (e) {
  this.dispatchException(e);
  }
 
  var contentType = response.getHeader('Content-type');
  if (this.options.evalJS == 'force'
  || (this.options.evalJS && this.isSameOrigin() && contentType
  && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
  this.evalResponse();
  }
 
  try {
  (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
  Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
  } catch (e) {
  this.dispatchException(e);
  }
 
  if (state == 'Complete') {
  // avoid memory leak in MSIE: clean up
  this.transport.onreadystatechange = Prototype.emptyFunction;
  }
  },
 
  isSameOrigin: function() {
  var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
  return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
  protocol: location.protocol,
  domain: document.domain,
  port: location.port ? ':' + location.port : ''
  }));
  },
 
  getHeader: function(name) {
  try {
  return this.transport.getResponseHeader(name) || null;
  } catch (e) { return null }
  },
 
  evalResponse: function() {
  try {
  return eval((this.transport.responseText || '').unfilterJSON());
  } catch (e) {
  this.dispatchException(e);
  }
  },
 
  dispatchException: function(exception) {
  (this.options.onException || Prototype.emptyFunction)(this, exception);
  Ajax.Responders.dispatch('onException', this, exception);
  }
  });
 
  Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
 
  Ajax.Response = Class.create({
  initialize: function(request){
  this.request = request;
  var transport = this.transport = request.transport,
  readyState = this.readyState = transport.readyState;
 
  if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
  this.status = this.getStatus();
  this.statusText = this.getStatusText();
  this.responseText = String.interpret(transport.responseText);
  this.headerJSON = this._getHeaderJSON();
  }
 
  if(readyState == 4) {
  var xml = transport.responseXML;
  this.responseXML = Object.isUndefined(xml) ? null : xml;
  this.responseJSON = this._getResponseJSON();
  }
  },
 
  status: 0,
  statusText: '',
 
  getStatus: Ajax.Request.prototype.getStatus,
 
  getStatusText: function() {
  try {
  return this.transport.statusText || '';
  } catch (e) { return '' }
  },
 
  getHeader: Ajax.Request.prototype.getHeader,
 
  getAllHeaders: function() {
  try {
  return this.getAllResponseHeaders();
  } catch (e) { return null }
  },
 
  getResponseHeader: function(name) {
  return this.transport.getResponseHeader(name);
  },
 
  getAllResponseHeaders: function() {
  return this.transport.getAllResponseHeaders();
  },
 
  _getHeaderJSON: function() {
  var json = this.getHeader('X-JSON');
  if (!json) return null;
  json = decodeURIComponent(escape(json));
  try {
  return json.evalJSON(this.request.options.sanitizeJSON ||
  !this.request.isSameOrigin());
  } catch (e) {
  this.request.dispatchException(e);
  }
  },
 
  _getResponseJSON: function() {
  var options = this.request.options;
  if (!options.evalJSON || (options.evalJSON != 'force' &&
  !(this.getHeader('Content-type') || '').include('application/json')) ||
  this.responseText.blank())
  return null;
  try {
  return this.responseText.evalJSON(options.sanitizeJSON ||
  !this.request.isSameOrigin());
  } catch (e) {
  this.request.dispatchException(e);
  }
  }
  });
 
  Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
  this.container = {
  success: (container.success || container),
  failure: (container.failure || (container.success ? null : container))
  };
 
  options = Object.clone(options);
  var onComplete = options.onComplete;
  options.onComplete = (function(response, json) {
  this.updateContent(response.responseText);
  if (Object.isFunction(onComplete)) onComplete(response, json);
  }).bind(this);
 
  $super(url, options);
  },
 
  updateContent: function(responseText) {
  var receiver = this.container[this.success() ? 'success' : 'failure'],
  options = this.options;
 
  if (!options.evalScripts) responseText = responseText.stripScripts();
 
  if (receiver = $(receiver)) {
  if (options.insertion) {
  if (Object.isString(options.insertion)) {
  var insertion = { }; insertion[options.insertion] = responseText;
  receiver.insert(insertion);
  }
  else options.insertion(receiver, responseText);
  }
  else receiver.update(responseText);
  }
  }
  });
 
  Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  initialize: function($super, container, url, options) {
  $super(options);
  this.onComplete = this.options.onComplete;
 
  this.frequency = (this.options.frequency || 2);
  this.decay = (this.options.decay || 1);
 
  this.updater = { };
  this.container = container;
  this.url = url;
 
  this.start();
  },
 
  start: function() {
  this.options.onComplete = this.updateComplete.bind(this);
  this.onTimerEvent();
  },
 
  stop: function() {
  this.updater.options.onComplete = undefined;
  clearTimeout(this.timer);
  (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },
 
  updateComplete: function(response) {
  if (this.options.decay) {
  this.decay = (response.responseText == this.lastText ?
  this.decay * this.options.decay : 1);
 
  this.lastText = response.responseText;
  }
  this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  },
 
  onTimerEvent: function() {
  this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
  });
  function $(element) {
  if (arguments.length > 1) {
  for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  elements.push($(arguments[i]));
  return elements;
  }
  if (Object.isString(element))
  element = document.getElementById(element);
  return Element.extend(element);
  }
 
  if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
  var results = [];
  var query = document.evaluate(expression, $(parentElement) || document,
  null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var i = 0, length = query.snapshotLength; i < length; i++)
  results.push(Element.extend(query.snapshotItem(i)));
  return results;
  };
  }
 
  /*--------------------------------------------------------------------------*/
 
  if (!window.Node) var Node = { };
 
  if (!Node.ELEMENT_NODE) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
  ELEMENT_NODE: 1,
  ATTRIBUTE_NODE: 2,
  TEXT_NODE: 3,
  CDATA_SECTION_NODE: 4,
  ENTITY_REFERENCE_NODE: 5,
  ENTITY_NODE: 6,
  PROCESSING_INSTRUCTION_NODE: 7,
  COMMENT_NODE: 8,
  DOCUMENT_NODE: 9,
  DOCUMENT_TYPE_NODE: 10,
  DOCUMENT_FRAGMENT_NODE: 11,
  NOTATION_NODE: 12
  });
  }
 
  (function() {
  var element = this.Element;
  this.Element = function(tagName, attributes) {
  attributes = attributes || { };
  tagName = tagName.toLowerCase();
  var cache = Element.cache;
  if (Prototype.Browser.IE && attributes.name) {
  tagName = '<' + tagName + ' name="' + attributes.name + '">';
  delete attributes.name;
  return Element.writeAttribute(document.createElement(tagName), attributes);
  }
  if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
  return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  };
  Object.extend(this.Element, element || { });
  if (element) this.Element.prototype = element.prototype;
  }).call(window);
 
  Element.cache = { };
 
  Element.Methods = {
  visible: function(element) {
  return $(element).style.display != 'none';
  },
 
  toggle: function(element) {
  element = $(element);
  Element[Element.visible(element) ? 'hide' : 'show'](element);
  return element;
  },
 
  hide: function(element) {
  element = $(element);
  element.style.display = 'none';
  return element;
  },
 
  show: function(element) {
  element = $(element);
  element.style.display = '';
  return element;
  },
 
  remove: function(element) {
  element = $(element);
  element.parentNode.removeChild(element);
  return element;
  },
 
  update: function(element, content) {
  element = $(element);
  if (content && content.toElement) content = content.toElement();
  if (Object.isElement(content)) return element.update().insert(content);
  content = Object.toHTML(content);
  element.innerHTML = content.stripScripts();
  content.evalScripts.bind(content).defer();
  return element;
  },
 
  replace: function(element, content) {
  element = $(element);
  if (content && content.toElement) content = content.toElement();
  else if (!Object.isElement(content)) {
  content = Object.toHTML(content);
  var range = element.ownerDocument.createRange();
  range.selectNode(element);
  content.evalScripts.bind(content).defer();
  content = range.createContextualFragment(content.stripScripts());
  }
  element.parentNode.replaceChild(content, element);
  return element;
  },
 
  insert: function(element, insertions) {
  element = $(element);
 
  if (Object.isString(insertions) || Object.isNumber(insertions) ||
  Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
  insertions = {bottom:insertions};
 
  var content, insert, tagName, childNodes;
 
  for (var position in insertions) {
  content = insertions[position];
  position = position.toLowerCase();
  insert = Element._insertionTranslations[position];
 
  if (content && content.toElement) content = content.toElement();
  if (Object.isElement(content)) {
  insert(element, content);
  continue;
  }
 
  content = Object.toHTML(content);
 
  tagName = ((position == 'before' || position == 'after')
  ? element.parentNode : element).tagName.toUpperCase();
 
  childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
 
  if (position == 'top' || position == 'after') childNodes.reverse();
  childNodes.each(insert.curry(element));
 
  content.evalScripts.bind(content).defer();
  }
 
  return element;
  },
 
  wrap: function(element, wrapper, attributes) {
  element = $(element);
  if (Object.isElement(wrapper))
  $(wrapper).writeAttribute(attributes || { });
  else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
  else wrapper = new Element('div', wrapper);
  if (element.parentNode)
  element.parentNode.replaceChild(wrapper, element);
  wrapper.appendChild(element);
  return wrapper;
  },
 
  inspect: function(element) {
  element = $(element);
  var result = '<' + element.tagName.toLowerCase();
  $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  var property = pair.first(), attribute = pair.last();
  var value = (element[property] || '').toString();
  if (value) result += ' ' + attribute + '=' + value.inspect(true);
  });
  return result + '>';
  },
 
  recursivelyCollect: function(element, property) {
  element = $(element);
  var elements = [];
  while (element = element[property])
  if (element.nodeType == 1)
  elements.push(Element.extend(element));
  return elements;
  },
 
  ancestors: function(element) {
  return $(element).recursivelyCollect('parentNode');
  },
 
  descendants: function(element) {
  return $(element).select("*");
  },
 
  firstDescendant: function(element) {
  element = $(element).firstChild;
  while (element && element.nodeType != 1) element = element.nextSibling;
  return $(element);
  },
 
  immediateDescendants: function(element) {
  if (!(element = $(element).firstChild)) return [];
  while (element && element.nodeType != 1) element = element.nextSibling;
  if (element) return [element].concat($(element).nextSiblings());
  return [];
  },
 
  previousSiblings: function(element) {
  return $(element).recursivelyCollect('previousSibling');
  },
 
  nextSiblings: function(element) {
  return $(element).recursivelyCollect('nextSibling');
  },
 
  siblings: function(element) {
  element = $(element);
  return element.previousSiblings().reverse().concat(element.nextSiblings());
  },
 
  match: function(element, selector) {
  if (Object.isString(selector))
  selector = new Selector(selector);
  return selector.match($(element));
  },
 
  up: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(element.parentNode);
  var ancestors = element.ancestors();
  return Object.isNumber(expression) ? ancestors[expression] :
  Selector.findElement(ancestors, expression, index);
  },
 
  down: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return element.firstDescendant();
  return Object.isNumber(expression) ? element.descendants()[expression] :
  Element.select(element, expression)[index || 0];
  },
 
  previous: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  var previousSiblings = element.previousSiblings();
  return Object.isNumber(expression) ? previousSiblings[expression] :
  Selector.findElement(previousSiblings, expression, index);
  },
 
  next: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  var nextSiblings = element.nextSiblings();
  return Object.isNumber(expression) ? nextSiblings[expression] :
  Selector.findElement(nextSiblings, expression, index);
  },
 
  select: function() {
  var args = $A(arguments), element = $(args.shift());
  return Selector.findChildElements(element, args);
  },
 
  adjacent: function() {
  var args = $A(arguments), element = $(args.shift());
  return Selector.findChildElements(element.parentNode, args).without(element);
  },
 
  identify: function(element) {
  element = $(element);
  var id = element.readAttribute('id'), self = arguments.callee;
  if (id) return id;
  do { id = 'anonymous_element_' + self.counter++ } while ($(id));
  element.writeAttribute('id', id);
  return id;
  },
 
  readAttribute: function(element, name) {
  element = $(element);
  if (Prototype.Browser.IE) {
  var t = Element._attributeTranslations.read;
  if (t.values[name]) return t.values[name](element, name);
  if (t.names[name]) name = t.names[name];
  if (name.include(':')) {
  return (!element.attributes || !element.attributes[name]) ? null :
  element.attributes[name].value;
  }
  }
  return element.getAttribute(name);
  },
 
  writeAttribute: function(element, name, value) {
  element = $(element);
  var attributes = { }, t = Element._attributeTranslations.write;
 
  if (typeof name == 'object') attributes = name;
  else attributes[name] = Object.isUndefined(value) ? true : value;
 
  for (var attr in attributes) {
  name = t.names[attr] || attr;
  value = attributes[attr];
  if (t.values[attr]) name = t.values[attr](element, value);
  if (value === false || value === null)
  element.removeAttribute(name);
  else if (value === true)
  element.setAttribute(name, name);
  else element.setAttribute(name, value);
  }
  return element;
  },
 
  getHeight: function(element) {
  return $(element).getDimensions().height;
  },
 
  getWidth: function(element) {
  return $(element).getDimensions().width;
  },
 
  classNames: function(element) {
  return new Element.ClassNames(element);
  },
 
  hasClassName: function(element, className) {
  if (!(element = $(element))) return;
  var elementClassName = element.className;
  return (elementClassName.length > 0 && (elementClassName == className ||
  new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  },
 
  addClassName: function(element, className) {
  if (!(element = $(element))) return;
  if (!element.hasClassName(className))
  element.className += (element.className ? ' ' : '') + className;
  return element;
  },
 
  removeClassName: function(element, className) {
  if (!(element = $(element))) return;
  element.className = element.className.replace(
  new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
  return element;
  },
 
  toggleClassName: function(element, className) {
  if (!(element = $(element))) return;
  return element[element.hasClassName(className) ?
  'removeClassName' : 'addClassName'](className);
  },
 
  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
  element = $(element);
  var node = element.firstChild;
  while (node) {
  var nextNode = node.nextSibling;
  if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  element.removeChild(node);
  node = nextNode;
  }
  return element;
  },
 
  empty: function(element) {
  return $(element).innerHTML.blank();
  },
 
  descendantOf: function(element, ancestor) {
  element = $(element), ancestor = $(ancestor);
 
  if (element.compareDocumentPosition)
  return (element.compareDocumentPosition(ancestor) & 8) === 8;
 
  if (ancestor.contains)
  return ancestor.contains(element) && ancestor !== element;
 
  while (element = element.parentNode)
  if (element == ancestor) return true;
 
  return false;
  },
 
  scrollTo: function(element) {
  element = $(element);
  var pos = element.cumulativeOffset();
  window.scrollTo(pos[0], pos[1]);
  return element;
  },
 
  getStyle: function(element, style) {
  element = $(element);
  style = style == 'float' ? 'cssFloat' : style.camelize();
  var value = element.style[style];
  if (!value || value == 'auto') {
  var css = document.defaultView.getComputedStyle(element, null);
  value = css ? css[style] : null;
  }
  if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  return value == 'auto' ? null : value;
  },
 
  getOpacity: function(element) {
  return $(element).getStyle('opacity');
  },
 
  setStyle: function(element, styles) {
  element = $(element);
  var elementStyle = element.style, match;
  if (Object.isString(styles)) {
  element.style.cssText += ';' + styles;
  return styles.include('opacity') ?
  element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
  }
  for (var property in styles)
  if (property == 'opacity') element.setOpacity(styles[property]);
  else
  elementStyle[(property == 'float' || property == 'cssFloat') ?
  (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
  property] = styles[property];
 
  return element;
  },
 
  setOpacity: function(element, value) {
  element = $(element);
  element.style.opacity = (value == 1 || value === '') ? '' :
  (value < 0.00001) ? 0 : value;
  return element;
  },
 
  getDimensions: function(element) {
  element = $(element);
  var display = element.getStyle('display');
  if (display != 'none' && display != null) // Safari bug
  return {width: element.offsetWidth, height: element.offsetHeight};
 
  // All *Width and *Height properties give 0 on elements with display none,
  // so enable the element temporarily
  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
  },
 
  makePositioned: function(element) {
  element = $(element);
  var pos = Element.getStyle(element, 'position');
  if (pos == 'static' || !pos) {
  element._madePositioned = true;
  element.style.position = 'relative';
  // Opera returns the offset relative to the positioning context, when an
  // element is position relative but top and left have not been defined
  if (Prototype.Browser.Opera) {
  element.style.top = 0;
  element.style.left = 0;
  }
  }
  return element;
  },
 
  undoPositioned: function(element) {
  element = $(element);
  if (element._madePositioned) {
  element._madePositioned = undefined;
  element.style.position =
  element.style.top =
  element.style.left =
  element.style.bottom =
  element.style.right = '';
  }
  return element;
  },
 
  makeClipping: function(element) {
  element = $(element);
  if (element._overflow) return element;
  element._overflow = Element.getStyle(element, 'overflow') || 'auto';
  if (element._overflow !== 'hidden')
  element.style.overflow = 'hidden';
  return element;
  },
 
  undoClipping: function(element) {
  element = $(element);
  if (!element._overflow) return element;
  element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  element._overflow = null;
  return element;
  },
 
  cumulativeOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
  valueT += element.offsetTop || 0;
  valueL += element.offsetLeft || 0;
  element = element.offsetParent;
  } while (element);
  return Element._returnOffset(valueL, valueT);
  },
 
  positionedOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
  valueT += element.offsetTop || 0;
  valueL += element.offsetLeft || 0;
  element = element.offsetParent;
  if (element) {
  if (element.tagName.toUpperCase() == 'BODY') break;
  var p = Element.getStyle(element, 'position');
  if (p !== 'static') break;
  }
  } while (element);
  return Element._returnOffset(valueL, valueT);
  },
 
  absolutize: function(element) {
  element = $(element);
  if (element.getStyle('position') == 'absolute') return element;
  // Position.prepare(); // To be done manually by Scripty when it needs it.
 
  var offsets = element.positionedOffset();
  var top = offsets[1];
  var left = offsets[0];
  var width = element.clientWidth;
  var height = element.clientHeight;
 
  element._originalLeft = left - parseFloat(element.style.left || 0);
  element._originalTop = top - parseFloat(element.style.top || 0);
  element._originalWidth = element.style.width;
  element._originalHeight = element.style.height;
 
  element.style.position = 'absolute';
  element.style.top = top + 'px';
  element.style.left = left + 'px';
  element.style.width = width + 'px';
  element.style.height = height + 'px';
  return element;
  },
 
  relativize: function(element) {
  element = $(element);
  if (element.getStyle('position') == 'relative') return element;
  // Position.prepare(); // To be done manually by Scripty when it needs it.
 
  element.style.position = 'relative';
  var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
 
  element.style.top = top + 'px';
  element.style.left = left + 'px';
  element.style.height = element._originalHeight;
  element.style.width = element._originalWidth;
  return element;
  },
 
  cumulativeScrollOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
  valueT += element.scrollTop || 0;
  valueL += element.scrollLeft || 0;
  element = element.parentNode;
  } while (element);
  return Element._returnOffset(valueL, valueT);
  },
 
  getOffsetParent: function(element) {
  if (element.offsetParent) return $(element.offsetParent);
  if (element == document.body) return $(element);
 
  while ((element = element.parentNode) && element != document.body)
  if (Element.getStyle(element, 'position') != 'static')
  return $(element);
 
  return $(document.body);
  },
 
  viewportOffset: function(forElement) {
  var valueT = 0, valueL = 0;
 
  var element = forElement;
  do {
  valueT += element.offsetTop || 0;
  valueL += element.offsetLeft || 0;
 
  // Safari fix
  if (element.offsetParent == document.body &&
  Element.getStyle(element, 'position') == 'absolute') break;
 
  } while (element = element.offsetParent);
 
  element = forElement;
  do {
  if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
  valueT -= element.scrollTop || 0;
  valueL -= element.scrollLeft || 0;
  }
  } while (element = element.parentNode);
 
  return Element._returnOffset(valueL, valueT);
  },
 
  clonePosition: function(element, source) {
  var options = Object.extend({
  setLeft: true,
  setTop: true,
  setWidth: true,
  setHeight: true,
  offsetTop: 0,
  offsetLeft: 0
  }, arguments[2] || { });
 
  // find page position of source
  source = $(source);
  var p = source.viewportOffset();
 
  // find coordinate system to use
  element = $(element);
  var delta = [0, 0];
  var parent = null;
  // delta [0,0] will do fine with position: fixed elements,
  // position:absolute needs offsetParent deltas
  if (Element.getStyle(element, 'position') == 'absolute') {
  parent = element.getOffsetParent();
  delta = parent.viewportOffset();
  }
 
  // correct by body offsets (fixes Safari)
  if (parent == document.body) {
  delta[0] -= document.body.offsetLeft;
  delta[1] -= document.body.offsetTop;
  }
 
  // set position
  if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
  if (options.setWidth) element.style.width = source.offsetWidth + 'px';
  if (options.setHeight) element.style.height = source.offsetHeight + 'px';
  return element;
  }
  };
 
  Element.Methods.identify.counter = 1;
 
  Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,
  childElements: Element.Methods.immediateDescendants
  });
 
  Element._attributeTranslations = {
  write: {
  names: {
  className: 'class',
  htmlFor: 'for'
  },
  values: { }
  }
  };
 
  if (Prototype.Browser.Opera) {
  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
  function(proceed, element, style) {
  switch (style) {
  case 'left': case 'top': case 'right': case 'bottom':
  if (proceed(element, 'position') === 'static') return null;
  case 'height': case 'width':
  // returns '0px' for hidden elements; we want it to return null
  if (!Element.visible(element)) return null;
 
  // returns the border-box dimensions rather than the content-box
  // dimensions, so we subtract padding and borders from the value
  var dim = parseInt(proceed(element, style), 10);
 
  if (dim !== element['offset' + style.capitalize()])
  return dim + 'px';
 
  var properties;
  if (style === 'height') {
  properties = ['border-top-width', 'padding-top',
  'padding-bottom', 'border-bottom-width'];
  }
  else {
  properties = ['border-left-width', 'padding-left',
  'padding-right', 'border-right-width'];
  }
  return properties.inject(dim, function(memo, property) {
  var val = proceed(element, property);
  return val === null ? memo : memo - parseInt(val, 10);
  }) + 'px';
  default: return proceed(element, style);
  }
  }
  );
 
  Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
  function(proceed, element, attribute) {
  if (attribute === 'title') return element.title;
  return proceed(element, attribute);
  }
  );
  }
 
  else if (Prototype.Browser.IE) {
  // IE doesn't report offsets correctly for static elements, so we change them
  // to "relative" to get the values, then change them back.
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
  function(proceed, element) {
  element = $(element);
  // IE throws an error if element is not in document
  try { element.offsetParent }
  catch(e) { return $(document.body) }
  var position = element.getStyle('position');
  if (position !== 'static') return proceed(element);
  element.setStyle({ position: 'relative' });
  var value = proceed(element);
  element.setStyle({ position: position });
  return value;
  }
  );
 
  $w('positionedOffset viewportOffset').each(function(method) {
  Element.Methods[method] = Element.Methods[method].wrap(
  function(proceed, element) {
  element = $(element);
  try { element.offsetParent }
  catch(e) { return Element._returnOffset(0,0) }
  var position = element.getStyle('position');
  if (position !== 'static') return proceed(element);
  // Trigger hasLayout on the offset parent so that IE6 reports
  // accurate offsetTop and offsetLeft values for position: fixed.
  var offsetParent = element.getOffsetParent();
  if (offsetParent && offsetParent.getStyle('position') === 'fixed')
  offsetParent.setStyle({ zoom: 1 });
  element.setStyle({ position: 'relative' });
  var value = proceed(element);
  element.setStyle({ position: position });
  return value;
  }
  );
  });
 
  Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
  function(proceed, element) {
  try { element.offsetParent }
  catch(e) { return Element._returnOffset(0,0) }
  return proceed(element);
  }
  );
 
  Element.Methods.getStyle = function(element, style) {
  element = $(element);
  style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  var value = element.style[style];
  if (!value && element.currentStyle) value = element.currentStyle[style];
 
  if (style == 'opacity') {
  if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  if (value[1]) return parseFloat(value[1]) / 100;
  return 1.0;
  }
 
  if (value == 'auto') {
  if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
  return element['offset' + style.capitalize()] + 'px';
  return null;
  }
  return value;
  };
 
  Element.Methods.setOpacity = function(element, value) {
  function stripAlpha(filter){
  return filter.replace(/alpha\([^\)]*\)/gi,'');
  }
  element = $(element);
  var currentStyle = element.currentStyle;
  if ((currentStyle && !currentStyle.hasLayout) ||
  (!currentStyle && element.style.zoom == 'normal'))
  element.style.zoom = 1;
 
  var filter = element.getStyle('filter'), style = element.style;
  if (value == 1 || value === '') {
  (filter = stripAlpha(filter)) ?
  style.filter = filter : style.removeAttribute('filter');
  return element;
  } else if (value < 0.00001) value = 0;
  style.filter = stripAlpha(filter) +
  'alpha(opacity=' + (value * 100) + ')';
  return element;
  };
 
  Element._attributeTranslations = {
  read: {
  names: {
  'class': 'className',
  'for': 'htmlFor'
  },
  values: {
  _getAttr: function(element, attribute) {
  return element.getAttribute(attribute, 2);
  },
  _getAttrNode: function(element, attribute) {
  var node = element.getAttributeNode(attribute);
  return node ? node.value : "";
  },
  _getEv: function(element, attribute) {
  attribute = element.getAttribute(attribute);
  return attribute ? attribute.toString().slice(23, -2) : null;
  },
  _flag: function(element, attribute) {
  return $(element).hasAttribute(attribute) ? attribute : null;
  },
  style: function(element) {
  return element.style.cssText.toLowerCase();
  },
  title: function(element) {
  return element.title;
  }
  }
  }
  };
 
  Element._attributeTranslations.write = {
  names: Object.extend({
  cellpadding: 'cellPadding',
  cellspacing: 'cellSpacing'
  }, Element._attributeTranslations.read.names),
  values: {
  checked: function(element, value) {
  element.checked = !!value;
  },
 
  style: function(element, value) {
  element.style.cssText = value ? value : '';
  }
  }
  };
 
  Element._attributeTranslations.has = {};
 
  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
  'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
  Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
  Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  });
 
  (function(v) {
  Object.extend(v, {
  href: v._getAttr,
  src: v._getAttr,
  type: v._getAttr,
  action: v._getAttrNode,
  disabled: v._flag,
  checked: v._flag,
  readonly: v._flag,
  multiple: v._flag,
  onload: v._getEv,
  onunload: v._getEv,
  onclick: v._getEv,
  ondblclick: v._getEv,
  onmousedown: v._getEv,
  onmouseup: v._getEv,
  onmouseover: v._getEv,
  onmousemove: v._getEv,
  onmouseout: v._getEv,
  onfocus: v._getEv,
  onblur: v._getEv,
  onkeypress: v._getEv,
  onkeydown: v._getEv,
  onkeyup: v._getEv,
  onsubmit: v._getEv,
  onreset: v._getEv,
  onselect: v._getEv,
  onchange: v._getEv
  });
  })(Element._attributeTranslations.read.values);
  }
 
  else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  Element.Methods.setOpacity = function(element, value) {
  element = $(element);
  element.style.opacity = (value == 1) ? 0.999999 :
  (value === '') ? '' : (value < 0.00001) ? 0 : value;
  return element;
  };
  }
 
  else if (Prototype.Browser.WebKit) {
  Element.Methods.setOpacity = function(element, value) {
  element = $(element);
  element.style.opacity = (value == 1 || value === '') ? '' :
  (value < 0.00001) ? 0 : value;
 
  if (value == 1)
  if(element.tagName.toUpperCase() == 'IMG' && element.width) {
  element.width++; element.width--;
  } else try {
  var n = document.createTextNode(' ');
  element.appendChild(n);
  element.removeChild(n);
  } catch (e) { }
 
  return element;
  };
 
  // Safari returns margins on body which is incorrect if the child is absolutely
  // positioned. For performance reasons, redefine Element#cumulativeOffset for
  // KHTML/WebKit only.
  Element.Methods.cumulativeOffset = function(element) {
  var valueT = 0, valueL = 0;
  do {
  valueT += element.offsetTop || 0;
  valueL += element.offsetLeft || 0;
  if (element.offsetParent == document.body)
  if (Element.getStyle(element, 'position') == 'absolute') break;
 
  element = element.offsetParent;
  } while (element);
 
  return Element._returnOffset(valueL, valueT);
  };
  }
 
  if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  Element.Methods.update = function(element, content) {
  element = $(element);
 
  if (content && content.toElement) content = content.toElement();
  if (Object.isElement(content)) return element.update().insert(content);
 
  content = Object.toHTML(content);
  var tagName = element.tagName.toUpperCase();
 
  if (tagName in Element._insertionTranslations.tags) {
  $A(element.childNodes).each(function(node) { element.removeChild(node) });
  Element._getContentFromAnonymousElement(tagName, content.stripScripts())
  .each(function(node) { element.appendChild(node) });
  }
  else element.innerHTML = content.stripScripts();
 
  content.evalScripts.bind(content).defer();
  return element;
  };
  }
 
  if ('outerHTML' in document.createElement('div')) {
  Element.Methods.replace = function(element, content) {
  element = $(element);
 
  if (content && content.toElement) content = content.toElement();
  if (Object.isElement(content)) {
  element.parentNode.replaceChild(content, element);
  return element;
  }
 
  content = Object.toHTML(content);
  var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
 
  if (Element._insertionTranslations.tags[tagName]) {
  var nextSibling = element.next();
  var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
  parent.removeChild(element);
  if (nextSibling)
  fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
  else
  fragments.each(function(node) { parent.appendChild(node) });
  }
  else element.outerHTML = content.stripScripts();
 
  content.evalScripts.bind(content).defer();
  return element;
  };
  }
 
  Element._returnOffset = function(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
  };
 
  Element._getContentFromAnonymousElement = function(tagName, html) {
  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  if (t) {
  div.innerHTML = t[0] + html + t[1];
  t[2].times(function() { div = div.firstChild });
  } else div.innerHTML = html;
  return $A(div.childNodes);
  };
 
  Element._insertionTranslations = {
  before: function(element, node) {
  element.parentNode.insertBefore(node, element);
  },
  top: function(element, node) {
  element.insertBefore(node, element.firstChild);
  },
  bottom: function(element, node) {
  element.appendChild(node);
  },
  after: function(element, node) {
  element.parentNode.insertBefore(node, element.nextSibling);
  },
  tags: {
  TABLE: ['<table>', '</table>', 1],
  TBODY: ['<table><tbody>', '</tbody></table>', 2],
  TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
  TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
  SELECT: ['<select>', '</select>', 1]
  }
  };
 
  (function() {
  Object.extend(this.tags, {
  THEAD: this.tags.TBODY,
  TFOOT: this.tags.TBODY,
  TH: this.tags.TD
  });
  }).call(Element._insertionTranslations);
 
  Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
  attribute = Element._attributeTranslations.has[attribute] || attribute;
  var node = $(element).getAttributeNode(attribute);
  return !!(node && node.specified);
  }
  };
 
  Element.Methods.ByTag = { };
 
  Object.extend(Element, Element.Methods);
 
  if (!Prototype.BrowserFeatures.ElementExtensions &&
  document.createElement('div')['__proto__']) {
  window.HTMLElement = { };
  window.HTMLElement.prototype = document.createElement('div')['__proto__'];
  Prototype.BrowserFeatures.ElementExtensions = true;
  }
 
  Element.extend = (function() {
  if (Prototype.BrowserFeatures.SpecificElementExtensions)
  return Prototype.K;
 
  var Methods = { }, ByTag = Element.Methods.ByTag;
 
  var extend = Object.extend(function(element) {
  if (!element || element._extendedByPrototype ||
  element.nodeType != 1 || element == window) return element;
 
  var methods = Object.clone(Methods),
  tagName = element.tagName.toUpperCase(), property, value;
 
  // extend methods for specific tags
  if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
 
  for (property in methods) {
  value = methods[property];
  if (Object.isFunction(value) && !(property in element))
  element[property] = value.methodize();
  }
 
  element._extendedByPrototype = Prototype.emptyFunction;
  return element;
 
  }, {
  refresh: function() {
  // extend methods for all tags (Safari doesn't need this)
  if (!Prototype.BrowserFeatures.ElementExtensions) {
  Object.extend(Methods, Element.Methods);
  Object.extend(Methods, Element.Methods.Simulated);
  }
  }
  });
 
  extend.refresh();
  return extend;
  })();
 
  Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
  };
 
  Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
 
  if (!methods) {
  Object.extend(Form, Form.Methods);
  Object.extend(Form.Element, Form.Element.Methods);
  Object.extend(Element.Methods.ByTag, {
  "FORM": Object.clone(Form.Methods),
  "INPUT": Object.clone(Form.Element.Methods),
  "SELECT": Object.clone(Form.Element.Methods),
  "TEXTAREA": Object.clone(Form.Element.Methods)
  });
  }
 
  if (arguments.length == 2) {
  var tagName = methods;
  methods = arguments[1];
  }
 
  if (!tagName) Object.extend(Element.Methods, methods || { });
  else {
  if (Object.isArray(tagName)) tagName.each(extend);
  else extend(tagName);
  }
 
  function extend(tagName) {
  tagName = tagName.toUpperCase();
  if (!Element.Methods.ByTag[tagName])
  Element.Methods.ByTag[tagName] = { };
  Object.extend(Element.Methods.ByTag[tagName], methods);
  }
 
  function copy(methods, destination, onlyIfAbsent) {
  onlyIfAbsent = onlyIfAbsent || false;
  for (var property in methods) {
  var value = methods[property];
  if (!Object.isFunction(value)) continue;
  if (!onlyIfAbsent || !(property in destination))
  destination[property] = value.methodize();
  }
  }
 
  function findDOMClass(tagName) {
  var klass;
  var trans = {
  "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
  "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
  "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
  "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
  "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
  "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
  "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
  "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
  "FrameSet", "IFRAME": "IFrame"
  };
  if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  if (window[klass]) return window[klass];
  klass = 'HTML' + tagName + 'Element';
  if (window[klass]) return window[klass];
  klass = 'HTML' + tagName.capitalize() + 'Element';
  if (window[klass]) return window[klass];
 
  window[klass] = { };
  window[klass].prototype = document.createElement(tagName)['__proto__'];
  return window[klass];
  }
 
  if (F.ElementExtensions) {
  copy(Element.Methods, HTMLElement.prototype);
  copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }
 
  if (F.SpecificElementExtensions) {
  for (var tag in Element.Methods.ByTag) {
  var klass = findDOMClass(tag);
  if (Object.isUndefined(klass)) continue;
  copy(T[tag], klass.prototype);
  }
  }
 
  Object.extend(Element, Element.Methods);
  delete Element.ByTag;
 
  if (Element.extend.refresh) Element.extend.refresh();
  Element.cache = { };
  };
 
  document.viewport = {
  getDimensions: function() {
  var dimensions = { }, B = Prototype.Browser;
  $w('width height').each(function(d) {
  var D = d.capitalize();
  if (B.WebKit && !document.evaluate) {
  // Safari <3.0 needs self.innerWidth/Height
  dimensions[d] = self['inner' + D];
  } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
  // Opera <9.5 needs document.body.clientWidth/Height
  dimensions[d] = document.body['client' + D]
  } else {
  dimensions[d] = document.documentElement['client' + D];
  }
  });
  return dimensions;
  },
 
  getWidth: function() {
  return this.getDimensions().width;
  },
 
  getHeight: function() {
  return this.getDimensions().height;
  },
 
  getScrollOffsets: function() {
  return Element._returnOffset(
  window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
  };
  /* Portions of the Selector class are derived from Jack Slocum's DomQuery,
  * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
  * license. Please see http://www.yui-ext.com/ for more information. */
 
  var Selector = Class.create({
  initialize: function(expression) {
  this.expression = expression.strip();
 
  if (this.shouldUseSelectorsAPI()) {
  this.mode = 'selectorsAPI';
  } else if (this.shouldUseXPath()) {
  this.mode = 'xpath';
  this.compileXPathMatcher();
  } else {
  this.mode = "normal";
  this.compileMatcher();
  }
 
  },
 
  shouldUseXPath: function() {
  if (!Prototype.BrowserFeatures.XPath) return false;
 
  var e = this.expression;
 
  // Safari 3 chokes on :*-of-type and :empty
  if (Prototype.Browser.WebKit &&
  (e.include("-of-type") || e.include(":empty")))
  return false;
 
  // XPath can't do namespaced attributes, nor can it read
  // the "checked" property from DOM nodes
  if ((/(\[[\w-]*?:|:checked)/).test(e))
  return false;
 
  return true;
  },
 
  shouldUseSelectorsAPI: function() {
  if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
 
  if (!Selector._div) Selector._div = new Element('div');
 
  // Make sure the browser treats the selector as valid. Test on an
  // isolated element to minimize cost of this check.
  try {
  Selector._div.querySelector(this.expression);
  } catch(e) {
  return false;
  }
 
  return true;
  },
 
  compileMatcher: function() {
  var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
  c = Selector.criteria, le, p, m;
 
  if (Selector._cache[e]) {
  this.matcher = Selector._cache[e];
  return;
  }
 
  this.matcher = ["this.matcher = function(root) {",
  "var r = root, h = Selector.handlers, c = false, n;"];
 
  while (e && le != e && (/\S/).test(e)) {
  le = e;
  for (var i in ps) {
  p = ps[i];
  if (m = e.match(p)) {
  this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
  new Template(c[i]).evaluate(m));
  e = e.replace(m[0], '');
  break;
  }
  }
  }
 
  this.matcher.push("return h.unique(n);\n}");
  eval(this.matcher.join('\n'));
  Selector._cache[this.expression] = this.matcher;
  },
 
  compileXPathMatcher: function() {
  var e = this.expression, ps = Selector.patterns,
  x = Selector.xpath, le, m;
 
  if (Selector._cache[e]) {
  this.xpath = Selector._cache[e]; return;
  }
 
  this.matcher = ['.//*'];
  while (e && le != e && (/\S/).test(e)) {
  le = e;
  for (var i in ps) {
  if (m = e.match(ps[i])) {
  this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
  new Template(x[i]).evaluate(m));
  e = e.replace(m[0], '');
  break;
  }
  }
  }
 
  this.xpath = this.matcher.join('');
  Selector._cache[this.expression] = this.xpath;
  },
 
  findElements: function(root) {
  root = root || document;
  var e = this.expression, results;
 
  switch (this.mode) {
  case 'selectorsAPI':
  // querySelectorAll queries document-wide, then filters to descendants
  // of the context element. That's not what we want.
  // Add an explicit context to the selector if necessary.
  if (root !== document) {
  var oldId = root.id, id = $(root).identify();
  e = "#" + id + " " + e;
  }
 
  results = $A(root.querySelectorAll(e)).map(Element.extend);
  root.id = oldId;
 
  return results;
  case 'xpath':
  return document._getElementsByXPath(this.xpath, root);
  default:
  return this.matcher(root);
  }
  },
 
  match: function(element) {
  this.tokens = [];
 
  var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
  var le, p, m;
 
  while (e && le !== e && (/\S/).test(e)) {
  le = e;
  for (var i in ps) {
  p = ps[i];
  if (m = e.match(p)) {
  // use the Selector.assertions methods unless the selector
  // is too complex.
  if (as[i]) {
  this.tokens.push([i, Object.clone(m)]);
  e = e.replace(m[0], '');
  } else {
  // reluctantly do a document-wide search
  // and look for a match in the array
  return this.findElements(document).include(element);
  }
  }
  }
  }
 
  var match = true, name, matches;
  for (var i = 0, token; token = this.tokens[i]; i++) {
  name = token[0], matches = token[1];
  if (!Selector.assertions[name](element, matches)) {
  match = false; break;
  }
  }
 
  return match;
  },
 
  toString: function() {
  return this.expression;
  },
 
  inspect: function() {
  return "#<Selector:" + this.expression.inspect() + ">";
  }
  });
 
  Object.extend(Selector, {
  _cache: { },
 
  xpath: {
  descendant: "//*",
  child: "/*",
  adjacent: "/following-sibling::*[1]",
  laterSibling: '/following-sibling::*',
  tagName: function(m) {
  if (m[1] == '*') return '';
  return "[local-name()='" + m[1].toLowerCase() +
  "' or local-name()='" + m[1].toUpperCase() + "']";
  },
  className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  id: "[@id='#{1}']",
  attrPresence: function(m) {
  m[1] = m[1].toLowerCase();
  return new Template("[@#{1}]").evaluate(m);
  },
  attr: function(m) {
  m[1] = m[1].toLowerCase();
  m[3] = m[5] || m[6];
  return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  },
  pseudo: function(m) {
  var h = Selector.xpath.pseudos[m[1]];
  if (!h) return '';
  if (Object.isFunction(h)) return h(m);
  return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  },
  operators: {
  '=': "[@#{1}='#{3}']",
  '!=': "[@#{1}!='#{3}']",
  '^=': "[starts-with(@#{1}, '#{3}')]",
  '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
  '*=': "[contains(@#{1}, '#{3}')]",
  '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
  '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  },
  pseudos: {
  'first-child': '[not(preceding-sibling::*)]',
  'last-child': '[not(following-sibling::*)]',
  'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
  'empty': "[count(*) = 0 and (count(text()) = 0)]",
  'checked': "[@checked]",
  'disabled': "[(@disabled) and (@type!='hidden')]",
  'enabled': "[not(@disabled) and (@type!='hidden')]",
  'not': function(m) {
  var e = m[6], p = Selector.patterns,
  x = Selector.xpath, le, v;
 
  var exclusion = [];
  while (e && le != e && (/\S/).test(e)) {
  le = e;
  for (var i in p) {
  if (m = e.match(p[i])) {
  v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
  exclusion.push("(" + v.substring(1, v.length - 1) + ")");
  e = e.replace(m[0], '');
  break;
  }
  }
  }
  return "[not(" + exclusion.join(" and ") + ")]";
  },
  'nth-child': function(m) {
  return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
  },
  'nth-last-child': function(m) {
  return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
  },
  'nth-of-type': function(m) {
  return Selector.xpath.pseudos.nth("position() ", m);
  },
  'nth-last-of-type': function(m) {
  return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
  },
  'first-of-type': function(m) {
  m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
  },
  'last-of-type': function(m) {
  m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
  },
  'only-of-type': function(m) {
  var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
  },
  nth: function(fragment, m) {
  var mm, formula = m[6], predicate;
  if (formula == 'even') formula = '2n+0';
  if (formula == 'odd') formula = '2n+1';
  if (mm = formula.match(/^(\d+)$/)) // digit only
  return '[' + fragment + "= " + mm[1] + ']';
  if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  if (mm[1] == "-") mm[1] = -1;
  var a = mm[1] ? Number(mm[1]) : 1;
  var b = mm[2] ? Number(mm[2]) : 0;
  predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
  "((#{fragment} - #{b}) div #{a} >= 0)]";
  return new Template(predicate).evaluate({
  fragment: fragment, a: a, b: b });
  }
  }
  }
  },
 
  criteria: {
  tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
  className: 'n = h.className(n, r, "#{1}", c); c = false;',
  id: 'n = h.id(n, r, "#{1}", c); c = false;',
  attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
  attr: function(m) {
  m[3] = (m[5] || m[6]);
  return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
  },
  pseudo: function(m) {
  if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
  return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  },
  descendant: 'c = "descendant";',
  child: 'c = "child";',
  adjacent: 'c = "adjacent";',
  laterSibling: 'c = "laterSibling";'
  },
 
  patterns: {
  // combinators must be listed first
  // (and descendant needs to be last combinator)
  laterSibling: /^\s*~\s*/,
  child: /^\s*>\s*/,
  adjacent: /^\s*\+\s*/,
  descendant: /^\s/,
 
  // selectors follow
  tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
  id: /^#([\w\-\*]+)(\b|$)/,
  className: /^\.([\w\-\*]+)(\b|$)/,
  pseudo:
  /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
  attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
  attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  },
 
  // for Selector.match and Element#match
  assertions: {
  tagName: function(element, matches) {
  return matches[1].toUpperCase() == element.tagName.toUpperCase();
  },
 
  className: function(element, matches) {
  return Element.hasClassName(element, matches[1]);
  },
 
  id: function(element, matches) {
  return element.id === matches[1];
  },
 
  attrPresence: function(element, matches) {
  return Element.hasAttribute(element, matches[1]);
  },
 
  attr: function(element, matches) {
  var nodeValue = Element.readAttribute(element, matches[1]);
  return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
  }
  },
 
  handlers: {
  // UTILITY FUNCTIONS
  // joins two collections
  concat: function(a, b) {
  for (var i = 0, node; node = b[i]; i++)
  a.push(node);
  return a;
  },
 
  // marks an array of nodes for counting
  mark: function(nodes) {
  var _true = Prototype.emptyFunction;
  for (var i = 0, node; node = nodes[i]; i++)
  node._countedByPrototype = _true;
  return nodes;
  },
 
  unmark: function(nodes) {
  for (var i = 0, node; node = nodes[i]; i++)
  node._countedByPrototype = undefined;
  return nodes;
  },
 
  // mark each child node with its position (for nth calls)
  // "ofType" flag indicates whether we're indexing for nth-of-type
  // rather than nth-child
  index: function(parentNode, reverse, ofType) {
  parentNode._countedByPrototype = Prototype.emptyFunction;
  if (reverse) {
  for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
  var node = nodes[i];
  if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  }
  } else {
  for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
  if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
  }
  },
 
  // filters out duplicates and extends all nodes
  unique: function(nodes) {
  if (nodes.length == 0) return nodes;
  var results = [], n;
  for (var i = 0, l = nodes.length; i < l; i++)
  if (!(n = nodes[i])._countedByPrototype) {
  n._countedByPrototype = Prototype.emptyFunction;
  results.push(Element.extend(n));
  }
  return Selector.handlers.unmark(results);
  },
 
  // COMBINATOR FUNCTIONS
  descendant: function(nodes) {
  var h = Selector.handlers;
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  h.concat(results, node.getElementsByTagName('*'));
  return results;
  },
 
  child: function(nodes) {
  var h = Selector.handlers;
  for (var i = 0, results = [], node; node = nodes[i]; i++) {
  for (var j = 0, child; child = node.childNodes[j]; j++)
  if (child.nodeType == 1 && child.tagName != '!') results.push(child);
  }
  return results;
  },
 
  adjacent: function(nodes) {
  for (var i = 0, results = [], node; node = nodes[i]; i++) {
  var next = this.nextElementSibling(node);
  if (next) results.push(next);
  }
  return results;
  },
 
  laterSibling: function(nodes) {
  var h = Selector.handlers;
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  h.concat(results, Element.nextSiblings(node));
  return results;
  },
 
  nextElementSibling: function(node) {
  while (node = node.nextSibling)
  if (node.nodeType == 1) return node;
  return null;
  },
 
  previousElementSibling: function(node) {
  while (node = node.previousSibling)
  if (node.nodeType == 1) return node;
  return null;
  },
 
  // TOKEN FUNCTIONS
  tagName: function(nodes, root, tagName, combinator) {
  var uTagName = tagName.toUpperCase();
  var results = [], h = Selector.handlers;
  if (nodes) {
  if (combinator) {
  // fastlane for ordinary descendant combinators
  if (combinator == "descendant") {
  for (var i = 0, node; node = nodes[i]; i++)
  h.concat(results, node.getElementsByTagName(tagName));
  return results;
  } else nodes = this[combinator](nodes);
  if (tagName == "*") return nodes;
  }
  for (var i = 0, node; node = nodes[i]; i++)
  if (node.tagName.toUpperCase() === uTagName) results.push(node);
  return results;
  } else return root.getElementsByTagName(tagName);
  },
 
  id: function(nodes, root, id, combinator) {
  var targetNode = $(id), h = Selector.handlers;
  if (!targetNode) return [];
  if (!nodes && root == document) return [targetNode];
  if (nodes) {
  if (combinator) {
  if (combinator == 'child') {
  for (var i = 0, node; node = nodes[i]; i++)
  if (targetNode.parentNode == node) return [targetNode];
  } else if (combinator == 'descendant') {
  for (var i = 0, node; node = nodes[i]; i++)
  if (Element.descendantOf(targetNode, node)) return [targetNode];
  } else if (combinator == 'adjacent') {
  for (var i = 0, node; node = nodes[i]; i++)
  if (Selector.handlers.previousElementSibling(targetNode) == node)
  return [targetNode];
  } else nodes = h[combinator](nodes);
  }
  for (var i = 0, node; node = nodes[i]; i++)
  if (node == targetNode) return [targetNode];
  return [];
  }
  return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  },
 
  className: function(nodes, root, className, combinator) {
  if (nodes && combinator) nodes = this[combinator](nodes);
  return Selector.handlers.byClassName(nodes, root, className);
  },
 
  byClassName: function(nodes, root, className) {
  if (!nodes) nodes = Selector.handlers.descendant([root]);
  var needle = ' ' + className + ' ';
  for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
  nodeClassName = node.className;
  if (nodeClassName.length == 0) continue;
  if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
  results.push(node);
  }
  return results;
  },
 
  attrPresence: function(nodes, root, attr, combinator) {
  if (!nodes) nodes = root.getElementsByTagName("*");
  if (nodes && combinator) nodes = this[combinator](nodes);
  var results = [];
  for (var i = 0, node; node = nodes[i]; i++)
  if (Element.hasAttribute(node, attr)) results.push(node);
  return results;
  },
 
  attr: function(nodes, root, attr, value, operator, combinator) {
  if (!nodes) nodes = root.getElementsByTagName("*");
  if (nodes && combinator) nodes = this[combinator](nodes);
  var handler = Selector.operators[operator], results = [];
  for (var i = 0, node; node = nodes[i]; i++) {
  var nodeValue = Element.readAttribute(node, attr);
  if (nodeValue === null) continue;
  if (handler(nodeValue, value)) results.push(node);
  }
  return results;
  },
 
  pseudo: function(nodes, name, value, root, combinator) {
  if (nodes && combinator) nodes = this[combinator](nodes);
  if (!nodes) nodes = root.getElementsByTagName("*");
  return Selector.pseudos[name](nodes, value, root);
  }
  },
 
  pseudos: {
  'first-child': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++) {
  if (Selector.handlers.previousElementSibling(node)) continue;
  results.push(node);
  }
  return results;
  },
  'last-child': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++) {
  if (Selector.handlers.nextElementSibling(node)) continue;
  results.push(node);
  }
  return results;
  },
  'only-child': function(nodes, value, root) {
  var h = Selector.handlers;
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
  results.push(node);
  return results;
  },
  'nth-child': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, formula, root);
  },
  'nth-last-child': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, formula, root, true);
  },
  'nth-of-type': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, formula, root, false, true);
  },
  'nth-last-of-type': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, formula, root, true, true);
  },
  'first-of-type': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, "1", root, false, true);
  },
  'last-of-type': function(nodes, formula, root) {
  return Selector.pseudos.nth(nodes, "1", root, true, true);
  },
  'only-of-type': function(nodes, formula, root) {
  var p = Selector.pseudos;
  return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  },
 
  // handles the an+b logic
  getIndices: function(a, b, total) {
  if (a == 0) return b > 0 ? [b] : [];
  return $R(1, total).inject([], function(memo, i) {
  if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
  return memo;
  });
  },
 
  // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
  nth: function(nodes, formula, root, reverse, ofType) {
  if (nodes.length == 0) return [];
  if (formula == 'even') formula = '2n+0';
  if (formula == 'odd') formula = '2n+1';
  var h = Selector.handlers, results = [], indexed = [], m;
  h.mark(nodes);
  for (var i = 0, node; node = nodes[i]; i++) {
  if (!node.parentNode._countedByPrototype) {
  h.index(node.parentNode, reverse, ofType);
  indexed.push(node.parentNode);
  }
  }
  if (formula.match(/^\d+$/)) { // just a number
  formula = Number(formula);
  for (var i = 0, node; node = nodes[i]; i++)
  if (node.nodeIndex == formula) results.push(node);
  } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
  if (m[1] == "-") m[1] = -1;
  var a = m[1] ? Number(m[1]) : 1;
  var b = m[2] ? Number(m[2]) : 0;
  var indices = Selector.pseudos.getIndices(a, b, nodes.length);
  for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
  for (var j = 0; j < l; j++)
  if (node.nodeIndex == indices[j]) results.push(node);
  }
  }
  h.unmark(nodes);
  h.unmark(indexed);
  return results;
  },
 
  'empty': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++) {
  // IE treats comments as element nodes
  if (node.tagName == '!' || node.firstChild) continue;
  results.push(node);
  }
  return results;
  },
 
  'not': function(nodes, selector, root) {
  var h = Selector.handlers, selectorType, m;
  var exclusions = new Selector(selector).findElements(root);
  h.mark(exclusions);
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  if (!node._countedByPrototype) results.push(node);
  h.unmark(exclusions);
  return results;
  },
 
  'enabled': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  if (!node.disabled && (!node.type || node.type !== 'hidden'))
  results.push(node);
  return results;
  },
 
  'disabled': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  if (node.disabled) results.push(node);
  return results;
  },
 
  'checked': function(nodes, value, root) {
  for (var i = 0, results = [], node; node = nodes[i]; i++)
  if (node.checked) results.push(node);
  return results;
  }
  },
 
  operators: {
  '=': function(nv, v) { return nv == v; },
  '!=': function(nv, v) { return nv != v; },
  '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
  '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
  '*=': function(nv, v) { return nv == v || nv && nv.include(v); },
  '$=': function(nv, v) { return nv.endsWith(v); },
  '*=': function(nv, v) { return nv.include(v); },
  '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
  '-').include('-' + (v || "").toUpperCase() + '-'); }
  },
 
  split: function(expression) {
  var expressions = [];
  expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
  expressions.push(m[1].strip());
  });
  return expressions;
  },
 
  matchElements: function(elements, expression) {
  var matches = $$(expression), h = Selector.handlers;
  h.mark(matches);
  for (var i = 0, results = [], element; element = elements[i]; i++)
  if (element._countedByPrototype) results.push(element);
  h.unmark(matches);
  return results;
  },
 
  findElement: function(elements, expression, index) {
  if (Object.isNumber(expression)) {
  index = expression; expression = false;
  }
  return Selector.matchElements(elements, expression || '*')[index || 0];
  },
 
  findChildElements: function(element, expressions) {
  expressions = Selector.split(expressions.join(','));
  var results = [], h = Selector.handlers;
  for (var i = 0, l = expressions.length, selector; i < l; i++) {
  selector = new Selector(expressions[i].strip());
  h.concat(results, selector.findElements(element));
  }
  return (l > 1) ? h.unique(results) : results;
  }
  });
 
  if (Prototype.Browser.IE) {
  Object.extend(Selector.handlers, {
  // IE returns comment nodes on getElementsByTagName("*").
  // Filter them out.
  concat: function(a, b) {
  for (var i = 0, node; node = b[i]; i++)
  if (node.tagName !== "!") a.push(node);
  return a;
  },
 
  // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
  unmark: function(nodes) {
  for (var i = 0, node; node = nodes[i]; i++)
  node.removeAttribute('_countedByPrototype');
  return nodes;
  }
  });
  }
 
  function $$() {
  return Selector.findChildElements(document, $A(arguments));
  }
  var Form = {
  reset: function(form) {
  $(form).reset();
  return form;
  },
 
  serializeElements: function(elements, options) {
  if (typeof options != 'object') options = { hash: !!options };
  else if (Object.isUndefined(options.hash)) options.hash = true;
  var key, value, submitted = false, submit = options.submit;
 
  var data = elements.inject({ }, function(result, element) {
  if (!element.disabled && element.name) {
  key = element.name; value = $(element).getValue();
  if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
  submit !== false && (!submit || key == submit) && (submitted = true)))) {
  if (key in result) {
  // a key is already present; construct an array of values
  if (!Object.isArray(result[key])) result[key] = [result[key]];
  result[key].push(value);
  }
  else result[key] = value;
  }
  }
  return result;
  });
 
  return options.hash ? data : Object.toQueryString(data);
  }
  };
 
  Form.Methods = {
  serialize: function(form, options) {
  return Form.serializeElements(Form.getElements(form), options);
  },
 
  getElements: function(form) {
  return $A($(form).getElementsByTagName('*')).inject([],
  function(elements, child) {
  if (Form.Element.Serializers[child.tagName.toLowerCase()])
  elements.push(Element.extend(child));
  return elements;
  }
  );
  },
 
  getInputs: function(form, typeName, name) {
  form = $(form);
  var inputs = form.getElementsByTagName('input');
 
  if (!typeName && !name) return $A(inputs).map(Element.extend);
 
  for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  var input = inputs[i];
  if ((typeName && input.type != typeName) || (name && input.name != name))
  continue;
  matchingInputs.push(Element.extend(input));
  }
 
  return matchingInputs;
  },
 
  disable: function(form) {
  form = $(form);
  Form.getElements(form).invoke('disable');
  return form;
  },
 
  enable: function(form) {
  form = $(form);
  Form.getElements(form).invoke('enable');
  return form;
  },
 
  findFirstElement: function(form) {
  var elements = $(form).getElements().findAll(function(element) {
  return 'hidden' != element.type && !element.disabled;
  });
  var firstByIndex = elements.findAll(function(element) {
  return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
  }).sortBy(function(element) { return element.tabIndex }).first();
 
  return firstByIndex ? firstByIndex : elements.find(function(element) {
  return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  });
  },
 
  focusFirstElement: function(form) {
  form = $(form);
  form.findFirstElement().activate();
  return form;
  },
 
  request: function(form, options) {
  form = $(form), options = Object.clone(options || { });
 
  var params = options.parameters, action = form.readAttribute('action') || '';
  if (action.blank()) action = window.location.href;
  options.parameters = form.serialize(true);
 
  if (params) {
  if (Object.isString(params)) params = params.toQueryParams();
  Object.extend(options.parameters, params);
  }
 
  if (form.hasAttribute('method') && !options.method)
  options.method = form.method;
 
  return new Ajax.Request(action, options);
  }
  };
 
  /*--------------------------------------------------------------------------*/
 
  Form.Element = {
  focus: function(element) {
  $(element).focus();
  return element;
  },
 
  select: function(element) {
  $(element).select();
  return element;
  }
  };
 
  Form.Element.Methods = {
  serialize: function(element) {
  element = $(element);
  if (!element.disabled && element.name) {
  var value = element.getValue();
  if (value != undefined) {
  var pair = { };
  pair[element.name] = value;
  return Object.toQueryString(pair);
  }
  }
  return '';
  },
 
  getValue: function(element) {
  element = $(element);
  var method = element.tagName.toLowerCase();
  return Form.Element.Serializers[method](element);
  },
 
  setValue: function(element, value) {
  element = $(element);
  var method = element.tagName.toLowerCase();
  Form.Element.Serializers[method](element, value);
  return element;
  },
 
  clear: function(element) {
  $(element).value = '';
  return element;
  },
 
  present: function(element) {
  return $(element).value != '';
  },
 
  activate: function(element) {
  element = $(element);
  try {
  element.focus();
  if (element.select && (element.tagName.toLowerCase() != 'input' ||
  !['button', 'reset', 'submit'].include(element.type)))
  element.select();
  } catch (e) { }
  return element;
  },
 
  disable: function(element) {
  element = $(element);
  element.disabled = true;
  return element;
  },
 
  enable: function(element) {
  element = $(element);
  element.disabled = false;
  return element;
  }
  };
 
  /*--------------------------------------------------------------------------*/
 
  var Field = Form.Element;
  var $F = Form.Element.Methods.getValue;
 
  /*--------------------------------------------------------------------------*/
 
  Form.Element.Serializers = {
  input: function(element, value) {
  switch (element.type.toLowerCase()) {
  case 'checkbox':
  case 'radio':
  return Form.Element.Serializers.inputSelector(element, value);
  default:
  return Form.Element.Serializers.textarea(element, value);
  }
  },
 
  inputSelector: function(element, value) {
  if (Object.isUndefined(value)) return element.checked ? element.value : null;
  else element.checked = !!value;
  },
 
  textarea: function(element, value) {
  if (Object.isUndefined(value)) return element.value;
  else element.value = value;
  },
 
  select: function(element, value) {
  if (Object.isUndefined(value))
  return this[element.type == 'select-one' ?
  'selectOne' : 'selectMany'](element);
  else {
  var opt, currentValue, single = !Object.isArray(value);
  for (var i = 0, length = element.length; i < length; i++) {
  opt = element.options[i];
  currentValue = this.optionValue(opt);
  if (single) {
  if (currentValue == value) {
  opt.selected = true;
  return;
  }
  }
  else opt.selected = value.include(currentValue);
  }
  }
  },
 
  selectOne: function(element) {
  var index = element.selectedIndex;
  return index >= 0 ? this.optionValue(element.options[index]) : null;
  },
 
  selectMany: function(element) {
  var values, length = element.length;
  if (!length) return null;
 
  for (var i = 0, values = []; i < length; i++) {
  var opt = element.options[i];
  if (opt.selected) values.push(this.optionValue(opt));
  }
  return values;
  },
 
  optionValue: function(opt) {
  // extend element because hasAttribute may not be native
  return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
  };
 
  /*--------------------------------------------------------------------------*/
 
  Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  initialize: function($super, element, frequency, callback) {
  $super(callback, frequency);
  this.element = $(element);
  this.lastValue = this.getValue();
  },
 
  execute: function() {
  var value = this.getValue();
  if (Object.isString(this.lastValue) && Object.isString(value) ?
  this.lastValue != value : String(this.lastValue) != String(value)) {
  this.callback(this.element, value);
  this.lastValue = value;
  }
  }
  });
 
  Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
  return Form.Element.getValue(this.element);
  }
  });
 
  Form.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
  return Form.serialize(this.element);
  }
  });
 
  /*--------------------------------------------------------------------------*/
 
  Abstract.EventObserver = Class.create({
  initialize: function(element, callback) {
  this.element = $(element);
  this.callback = callback;
 
  this.lastValue = this.getValue();
  if (this.element.tagName.toLowerCase() == 'form')
  this.registerFormCallbacks();
  else
  this.registerCallback(this.element);
  },
 
  onElementEvent: function() {
  var value = this.getValue();
  if (this.lastValue != value) {
  this.callback(this.element, value);
  this.lastValue = value;
  }
  },
 
  registerFormCallbacks: function() {
  Form.getElements(this.element).each(this.registerCallback, this);
  },
 
  registerCallback: function(element) {
  if (element.type) {
  switch (element.type.toLowerCase()) {
  case 'checkbox':
  case 'radio':
  Event.observe(element, 'click', this.onElementEvent.bind(this));
  break;
  default:
  Event.observe(element, 'change', this.onElementEvent.bind(this));
  break;
  }
  }
  }
  });
 
  Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
  return Form.Element.getValue(this.element);
  }
  });
 
  Form.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
  return Form.serialize(this.element);
  }
  });
  if (!window.Event) var Event = { };
 
  Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB: 9,
  KEY_RETURN: 13,
  KEY_ESC: 27,
  KEY_LEFT: 37,
  KEY_UP: 38,
  KEY_RIGHT: 39,
  KEY_DOWN: 40,
  KEY_DELETE: 46,
  KEY_HOME: 36,
  KEY_END: 35,
  KEY_PAGEUP: 33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT: 45,
 
  cache: { },
 
  relatedTarget: function(event) {
  var element;
  switch(event.type) {
  case 'mouseover': element = event.fromElement; break;
  case 'mouseout': element = event.toElement; break;
  default: return null;
  }
  return Element.extend(element);
  }
  });
 
  Event.Methods = (function() {
  var isButton;
 
  if (Prototype.Browser.IE) {
  var buttonMap = { 0: 1, 1: 4, 2: 2 };
  isButton = function(event, code) {
  return event.button == buttonMap[code];
  };
 
  } else if (Prototype.Browser.WebKit) {
  isButton = function(event, code) {
  switch (code) {
  case 0: return event.which == 1 && !event.metaKey;
  case 1: return event.which == 1 && event.metaKey;
  default: return false;
  }
  };
 
  } else {
  isButton = function(event, code) {
  return event.which ? (event.which === code + 1) : (event.button === code);
  };
  }
 
  return {
  isLeftClick: function(event) { return isButton(event, 0) },
  isMiddleClick: function(event) { return isButton(event, 1) },
  isRightClick: function(event) { return isButton(event, 2) },
 
  element: function(event) {
  event = Event.extend(event);
 
  var node = event.target,
  type = event.type,
  currentTarget = event.currentTarget;
 
  if (currentTarget && currentTarget.tagName) {
  // Firefox screws up the "click" event when moving between radio buttons
  // via arrow keys. It also screws up the "load" and "error" events on images,
  // reporting the document as the target instead of the original image.
  if (type === 'load' || type === 'error' ||
  (type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
  && currentTarget.type === 'radio'))
  node = currentTarget;
  }
  if (node.nodeType == Node.TEXT_NODE) node = node.parentNode;
  return Element.extend(node);
  },
 
  findElement: function(event, expression) {
  var element = Event.element(event);
  if (!expression) return element;
  var elements = [element].concat(element.ancestors());
  return Selector.findElement(elements, expression, 0);
  },
 
  pointer: function(event) {
  var docElement = document.documentElement,
  body = document.body || { scrollLeft: 0, scrollTop: 0 };
  return {
  x: event.pageX || (event.clientX +
  (docElement.scrollLeft || body.scrollLeft) -
  (docElement.clientLeft || 0)),
  y: event.pageY || (event.clientY +
  (docElement.scrollTop || body.scrollTop) -
  (docElement.clientTop || 0))
  };
  },
 
  pointerX: function(event) { return Event.pointer(event).x },
  pointerY: function(event) { return Event.pointer(event).y },
 
  stop: function(event) {
  Event.extend(event);
  event.preventDefault();
  event.stopPropagation();
  event.stopped = true;
  }
  };
  })();
 
  Event.extend = (function() {
  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
  m[name] = Event.Methods[name].methodize();
  return m;
  });
 
  if (Prototype.Browser.IE) {
  Object.extend(methods, {
  stopPropagation: function() { this.cancelBubble = true },
  preventDefault: function() { this.returnValue = false },
  inspect: function() { return "[object Event]" }
  });
 
  return function(event) {
  if (!event) return false;
  if (event._extendedByPrototype) return event;
 
  event._extendedByPrototype = Prototype.emptyFunction;
  var pointer = Event.pointer(event);
  Object.extend(event, {
  target: event.srcElement,
  relatedTarget: Event.relatedTarget(event),
  pageX: pointer.x,
  pageY: pointer.y
  });
  return Object.extend(event, methods);
  };
 
  } else {
  Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
  Object.extend(Event.prototype, methods);
  return Prototype.K;
  }
  })();
 
  Object.extend(Event, (function() {
  var cache = Event.cache;
 
  function getEventID(element) {
  if (element._prototypeEventID) return element._prototypeEventID[0];
  arguments.callee.id = arguments.callee.id || 1;
  return element._prototypeEventID = [++arguments.callee.id];
  }
 
  function getDOMEventName(eventName) {
  if (eventName && eventName.include(':')) return "dataavailable";
  return eventName;
  }
 
  function getCacheForID(id) {
  return cache[id] = cache[id] || { };
  }
 
  function getWrappersForEventName(id, eventName) {
  var c = getCacheForID(id);
  return c[eventName] = c[eventName] || [];
  }
 
  function createWrapper(element, eventName, handler) {
  var id = getEventID(element);
  var c = getWrappersForEventName(id, eventName);
  if (c.pluck("handler").include(handler)) return false;
 
  var wrapper = function(event) {
  if (!Event || !Event.extend ||
  (event.eventName && event.eventName != eventName))
  return false;
 
  Event.extend(event);
  handler.call(element, event);
  };
 
  wrapper.handler = handler;
  c.push(wrapper);
  return wrapper;
  }
 
  function findWrapper(id, eventName, handler) {
  var c = getWrappersForEventName(id, eventName);
  return c.find(function(wrapper) { return wrapper.handler == handler });
  }
 
  function destroyWrapper(id, eventName, handler) {
  var c = getCacheForID(id);
  if (!c[eventName]) return false;
  c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  }
 
  function destroyCache() {
  for (var id in cache)
  for (var eventName in cache[id])
  cache[id][eventName] = null;
  }
 
 
  // Internet Explorer needs to remove event handlers on page unload
  // in order to avoid memory leaks.
  if (window.attachEvent) {
  window.attachEvent("onunload", destroyCache);
  }
 
  // Safari has a dummy event handler on page unload so that it won't
  // use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
  // object when page is returned to via the back button using its bfcache.
  if (Prototype.Browser.WebKit) {
  window.addEventListener('unload', Prototype.emptyFunction, false);
  }
 
  return {
  observe: function(element, eventName, handler) {
  element = $(element);
  var name = getDOMEventName(eventName);
 
  var wrapper = createWrapper(element, eventName, handler);
  if (!wrapper) return element;
 
  if (element.addEventListener) {
  element.addEventListener(name, wrapper, false);
  } else {
  element.attachEvent("on" + name, wrapper);
  }
 
  return element;
  },
 
  stopObserving: function(element, eventName, handler) {
  element = $(element);
  var id = getEventID(element), name = getDOMEventName(eventName);
 
  if (!handler && eventName) {
  getWrappersForEventName(id, eventName).each(function(wrapper) {
  element.stopObserving(eventName, wrapper.handler);
  });
  return element;
 
  } else if (!eventName) {
  Object.keys(getCacheForID(id)).each(function(eventName) {
  element.stopObserving(eventName);
  });
  return element;
  }
 
  var wrapper = findWrapper(id, eventName, handler);
  if (!wrapper) return element;
 
  if (element.removeEventListener) {
  element.removeEventListener(name, wrapper, false);
  } else {
  element.detachEvent("on" + name, wrapper);
  }
 
  destroyWrapper(id, eventName, handler);
 
  return element;
  },
 
  fire: function(element, eventName, memo) {
  element = $(element);
  if (element == document && document.createEvent && !element.dispatchEvent)
  element = document.documentElement;
 
  var event;
  if (document.createEvent) {
  event = document.createEvent("HTMLEvents");
  event.initEvent("dataavailable", true, true);
  } else {
  event = document.createEventObject();
  event.eventType = "ondataavailable";
  }
 
  event.eventName = eventName;
  event.memo = memo || { };
 
  if (document.createEvent) {
  element.dispatchEvent(event);
  } else {
  element.fireEvent(event.eventType, event);
  }
 
  return Event.extend(event);
  }
  };
  })());
 
  Object.extend(Event, Event.Methods);
 
  Element.addMethods({
  fire: Event.fire,
  observe: Event.observe,
  stopObserving: Event.stopObserving
  });
 
  Object.extend(document, {
  fire: Element.Methods.fire.methodize(),
  observe: Element.Methods.observe.methodize(),
  stopObserving: Element.Methods.stopObserving.methodize(),
  loaded: false
  });
 
  (function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
  Matthias Miller, Dean Edwards and John Resig. */
 
  var timer;
 
  function fireContentLoadedEvent() {
  if (document.loaded) return;
  if (timer) window.clearInterval(timer);
  document.fire("dom:loaded");
  document.loaded = true;
  }
 
  if (document.addEventListener) {
  if (Prototype.Browser.WebKit) {
  timer = window.setInterval(function() {
  if (/loaded|complete/.test(document.readyState))
  fireContentLoadedEvent();
  }, 0);
 
  Event.observe(window, "load", fireContentLoadedEvent);
 
  } else {
  document.addEventListener("DOMContentLoaded",
  fireContentLoadedEvent, false);
  }
 
  } else {
  document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
  $("__onDOMContentLoaded").onreadystatechange = function() {
  if (this.readyState == "complete") {
  this.onreadystatechange = null;
  fireContentLoadedEvent();
  }
  };
  }
  })();
  /*------------------------------- DEPRECATED -------------------------------*/
 
  Hash.toQueryString = Object.toQueryString;
 
  var Toggle = { display: Element.toggle };
 
  Element.Methods.childOf = Element.Methods.descendantOf;
 
  var Insertion = {
  Before: function(element, content) {
  return Element.insert(element, {before:content});
  },
 
  Top: function(element, content) {
  return Element.insert(element, {top:content});
  },
 
  Bottom: function(element, content) {
  return Element.insert(element, {bottom:content});
  },
 
  After: function(element, content) {
  return Element.insert(element, {after:content});
  }
  };
 
  var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
 
  // This should be moved to script.aculo.us; notice the deprecated methods
  // further below, that map to the newer Element methods.
  var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,
 
  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
  this.deltaX = window.pageXOffset
  || document.documentElement.scrollLeft
  || document.body.scrollLeft
  || 0;
  this.deltaY = window.pageYOffset
  || document.documentElement.scrollTop
  || document.body.scrollTop
  || 0;
  },
 
  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
  if (this.includeScrollOffsets)
  return this.withinIncludingScrolloffsets(element, x, y);
  this.xcomp = x;
  this.ycomp = y;
  this.offset = Element.cumulativeOffset(element);
 
  return (y >= this.offset[1] &&
  y < this.offset[1] + element.offsetHeight &&
  x >= this.offset[0] &&
  x < this.offset[0] + element.offsetWidth);
  },
 
  withinIncludingScrolloffsets: function(element, x, y) {
  var offsetcache = Element.cumulativeScrollOffset(element);
 
  this.xcomp = x + offsetcache[0] - this.deltaX;
  this.ycomp = y + offsetcache[1] - this.deltaY;
  this.offset = Element.cumulativeOffset(element);
 
  return (this.ycomp >= this.offset[1] &&
  this.ycomp < this.offset[1] + element.offsetHeight &&
  this.xcomp >= this.offset[0] &&
  this.xcomp < this.offset[0] + element.offsetWidth);
  },
 
  // within must be called directly before
  overlap: function(mode, element) {
  if (!mode) return 0;
  if (mode == 'vertical')
  return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
  element.offsetHeight;
  if (mode == 'horizontal')
  return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
  element.offsetWidth;
  },
 
  // Deprecation layer -- use newer Element methods now (1.5.2).
 
  cumulativeOffset: Element.Methods.cumulativeOffset,
 
  positionedOffset: Element.Methods.positionedOffset,
 
  absolutize: function(element) {
  Position.prepare();
  return Element.absolutize(element);
  },
 
  relativize: function(element) {
  Position.prepare();
  return Element.relativize(element);
  },
 
  realOffset: Element.Methods.cumulativeScrollOffset,
 
  offsetParent: Element.Methods.getOffsetParent,
 
  page: Element.Methods.viewportOffset,
 
  clone: function(source, target, options) {
  options = options || { };
  return Element.clonePosition(target, source, options);
  }
  };
 
  /*--------------------------------------------------------------------------*/
 
  if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  function iter(name) {
  return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  }
 
  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
  className = className.toString().strip();
  var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
  return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  } : function(element, className) {
  className = className.toString().strip();
  var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
  if (!classNames && !className) return elements;
 
  var nodes = $(element).getElementsByTagName('*');
  className = ' ' + className + ' ';
 
  for (var i = 0, child, cn; child = nodes[i]; i++) {
  if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
  (classNames && classNames.all(function(name) {
  return !name.toString().blank() && cn.include(' ' + name + ' ');
  }))))
  elements.push(Element.extend(child));
  }
  return elements;
  };
 
  return function(className, parentElement) {
  return $(parentElement || document.body).getElementsByClassName(className);
  };
  }(Element.Methods);
 
  /*--------------------------------------------------------------------------*/
 
  Element.ClassNames = Class.create();
  Element.ClassNames.prototype = {
  initialize: function(element) {
  this.element = $(element);
  },
 
  _each: function(iterator) {
  this.element.className.split(/\s+/).select(function(name) {
  return name.length > 0;
  })._each(iterator);
  },
 
  set: function(className) {
  this.element.className = className;
  },
 
  add: function(classNameToAdd) {
  if (this.include(classNameToAdd)) return;
  this.set($A(this).concat(classNameToAdd).join(' '));
  },
 
  remove: function(classNameToRemove) {
  if (!this.include(classNameToRemove)) return;
  this.set($A(this).without(classNameToRemove).join(' '));
  },
 
  toString: function() {
  return $A(this).join(' ');
  }
  };
 
  Object.extend(Element.ClassNames.prototype, Enumerable);
 
  /*--------------------------------------------------------------------------*/
 
  Element.addMethods();
  // Underscore.js 1.1.7
  // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
  // Underscore is freely distributable under the MIT license.
  // Portions of Underscore are inspired or borrowed from Prototype,
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
  // For all details and documentation:
  // http://documentcloud.github.com/underscore
  (function(){var p=this,C=p._,m={},i=Array.prototype,n=Object.prototype,f=i.slice,D=i.unshift,E=n.toString,l=n.hasOwnProperty,s=i.forEach,t=i.map,u=i.reduce,v=i.reduceRight,w=i.filter,x=i.every,y=i.some,o=i.indexOf,z=i.lastIndexOf;n=Array.isArray;var F=Object.keys,q=Function.prototype.bind,b=function(a){return new j(a)};typeof module!=="undefined"&&module.exports?(module.exports=b,b._=b):p._=b;b.VERSION="1.1.7";var h=b.each=b.forEach=function(a,c,b){if(a!=null)if(s&&a.forEach===s)a.forEach(c,b);else if(a.length===
  +a.length)for(var e=0,k=a.length;e<k;e++){if(e in a&&c.call(b,a[e],e,a)===m)break}else for(e in a)if(l.call(a,e)&&c.call(b,a[e],e,a)===m)break};b.map=function(a,c,b){var e=[];if(a==null)return e;if(t&&a.map===t)return a.map(c,b);h(a,function(a,g,G){e[e.length]=c.call(b,a,g,G)});return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var k=d!==void 0;a==null&&(a=[]);if(u&&a.reduce===u)return e&&(c=b.bind(c,e)),k?a.reduce(c,d):a.reduce(c);h(a,function(a,b,f){k?d=c.call(e,d,a,b,f):(d=a,k=!0)});if(!k)throw new TypeError("Reduce of empty array with no initial value");
  return d};b.reduceRight=b.foldr=function(a,c,d,e){a==null&&(a=[]);if(v&&a.reduceRight===v)return e&&(c=b.bind(c,e)),d!==void 0?a.reduceRight(c,d):a.reduceRight(c);a=(b.isArray(a)?a.slice():b.toArray(a)).reverse();return b.reduce(a,c,d,e)};b.find=b.detect=function(a,c,b){var e;A(a,function(a,g,f){if(c.call(b,a,g,f))return e=a,!0});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(w&&a.filter===w)return a.filter(c,b);h(a,function(a,g,f){c.call(b,a,g,f)&&(e[e.length]=a)});return e};
  b.reject=function(a,c,b){var e=[];if(a==null)return e;h(a,function(a,g,f){c.call(b,a,g,f)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=!0;if(a==null)return e;if(x&&a.every===x)return a.every(c,b);h(a,function(a,g,f){if(!(e=e&&c.call(b,a,g,f)))return m});return e};var A=b.some=b.any=function(a,c,d){c=c||b.identity;var e=!1;if(a==null)return e;if(y&&a.some===y)return a.some(c,d);h(a,function(a,b,f){if(e|=c.call(d,a,b,f))return m});return!!e};b.include=b.contains=function(a,c){var b=
  !1;if(a==null)return b;if(o&&a.indexOf===o)return a.indexOf(c)!=-1;A(a,function(a){if(b=a===c)return!0});return b};b.invoke=function(a,c){var d=f.call(arguments,2);return b.map(a,function(a){return(c.call?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);var e={computed:-Infinity};h(a,function(a,b,f){b=c?c.call(d,a,b,f):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,
  c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);var e={computed:Infinity};h(a,function(a,b,f){b=c?c.call(d,a,b,f):a;b<e.computed&&(e={value:a,computed:b})});return e.value};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,f){return{value:a,criteria:c.call(d,a,b,f)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,b){var d={};h(a,function(a,f){var g=b(a,f);(d[g]||(d[g]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||
  (d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){if(!a)return[];if(a.toArray)return a.toArray();if(b.isArray(a))return f.call(a);if(b.isArguments(a))return f.call(a);return b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?f.call(a,0,b):a[0]};b.rest=b.tail=function(a,b,d){return f.call(a,b==null||d?1:b)};b.last=function(a){return a[a.length-1]};b.compact=function(a){return b.filter(a,
  function(a){return!!a})};b.flatten=function(a){return b.reduce(a,function(a,d){if(b.isArray(d))return a.concat(b.flatten(d));a[a.length]=d;return a},[])};b.without=function(a){return b.difference(a,f.call(arguments,1))};b.uniq=b.unique=function(a,c){return b.reduce(a,function(a,e,f){if(0==f||(c===!0?b.last(a)!=e:!b.include(a,e)))a[a.length]=e;return a},[])};b.union=function(){return b.uniq(b.flatten(arguments))};b.intersection=b.intersect=function(a){var c=f.call(arguments,1);return b.filter(b.uniq(a),
  function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a,c){return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=f.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(o&&a.indexOf===o)return a.indexOf(c);d=0;for(e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,
  b){if(a==null)return-1;if(z&&a.lastIndexOf===z)return a.lastIndexOf(b);for(var d=a.length;d--;)if(a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);d=arguments[2]||1;for(var e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};b.bind=function(a,b){if(a.bind===q&&q)return q.apply(a,f.call(arguments,1));var d=f.call(arguments,2);return function(){return a.apply(b,d.concat(f.call(arguments)))}};b.bindAll=function(a){var c=f.call(arguments,1);
  c.length==0&&(c=b.functions(a));h(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,c){var d={};c||(c=b.identity);return function(){var b=c.apply(this,arguments);return l.call(d,b)?d[b]:d[b]=a.apply(this,arguments)}};b.delay=function(a,b){var d=f.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(f.call(arguments,1)))};var B=function(a,b,d){var e;return function(){var f=this,g=arguments,h=function(){e=null;
  a.apply(f,g)};d&&clearTimeout(e);if(d||!e)e=setTimeout(h,b)}};b.throttle=function(a,b){return B(a,b,!1)};b.debounce=function(a,b){return B(a,b,!0)};b.once=function(a){var b=!1,d;return function(){if(b)return d;b=!0;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(f.call(arguments));return b.apply(this,d)}};b.compose=function(){var a=f.call(arguments);return function(){for(var b=f.call(arguments),d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=
  function(a,b){return function(){if(--a<1)return b.apply(this,arguments)}};b.keys=F||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)l.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){h(f.call(arguments,1),function(b){for(var d in b)b[d]!==void 0&&(a[d]=b[d])});return a};b.defaults=function(a){h(f.call(arguments,
  1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,c){if(a===c)return!0;var d=typeof a;if(d!=typeof c)return!1;if(a==c)return!0;if(!a&&c||a&&!c)return!1;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual)return a.isEqual(c);if(c.isEqual)return c.isEqual(a);if(b.isDate(a)&&b.isDate(c))return a.getTime()===c.getTime();if(b.isNaN(a)&&b.isNaN(c))return!1;
  if(b.isRegExp(a)&&b.isRegExp(c))return a.source===c.source&&a.global===c.global&&a.ignoreCase===c.ignoreCase&&a.multiline===c.multiline;if(d!=="object")return!1;if(a.length&&a.length!==c.length)return!1;d=b.keys(a);var e=b.keys(c);if(d.length!=e.length)return!1;for(var f in a)if(!(f in c)||!b.isEqual(a[f],c[f]))return!1;return!0};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(l.call(a,c))return!1;return!0};b.isElement=function(a){return!!(a&&a.nodeType==
  1)};b.isArray=n||function(a){return E.call(a)==="[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=function(a){return!(!a||!l.call(a,"callee"))};b.isFunction=function(a){return!(!a||!a.constructor||!a.call||!a.apply)};b.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)};b.isNumber=function(a){return!!(a===0||a&&a.toExponential&&a.toFixed)};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===!0||a===!1};b.isDate=function(a){return!(!a||!a.getTimezoneOffset||
  !a.setUTCFullYear)};b.isRegExp=function(a){return!(!a||!a.test||!a.exec||!(a.ignoreCase||a.ignoreCase===!1))};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.noConflict=function(){p._=C;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.mixin=function(a){h(b.functions(a),function(c){H(c,b[c]=a[c])})};var I=0;b.uniqueId=function(a){var b=I++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g};
  b.template=function(a,c){var d=b.templateSettings;d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.interpolate,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||null,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ")+"__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');";d=new Function("obj",d);return c?d(c):d};
  var j=function(a){this._wrapped=a};b.prototype=j.prototype;var r=function(a,c){return c?b(a).chain():a},H=function(a,c){j.prototype[a]=function(){var a=f.call(arguments);D.call(a,this._wrapped);return r(c.apply(b,a),this._chain)}};b.mixin(b);h(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var b=i[a];j.prototype[a]=function(){b.apply(this._wrapped,arguments);return r(this._wrapped,this._chain)}});h(["concat","join","slice"],function(a){var b=i[a];j.prototype[a]=function(){return r(b.apply(this._wrapped,
  arguments),this._chain)}});j.prototype.chain=function(){this._chain=!0;return this};j.prototype.value=function(){return this._wrapped}})();
 
  // Underscore.js 1.1.7
  // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
  // Underscore is freely distributable under the MIT license.
  // Portions of Underscore are inspired or borrowed from Prototype,
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
  // For all details and documentation:
  // http://documentcloud.github.com/underscore
 
  (function() {
 
  // Baseline setup
  // --------------
 
  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;
 
  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;
 
  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};
 
  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
 
  // Create quick reference variables for speed access to core prototypes.
  var slice = ArrayProto.slice,
  unshift = ArrayProto.unshift,
  toString = ObjProto.toString,
  hasOwnProperty = ObjProto.hasOwnProperty;
 
  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
  nativeForEach = ArrayProto.forEach,
  nativeMap = ArrayProto.map,
  nativeReduce = ArrayProto.reduce,
  nativeReduceRight = ArrayProto.reduceRight,
  nativeFilter = ArrayProto.filter,
  nativeEvery = ArrayProto.every,
  nativeSome = ArrayProto.some,
  nativeIndexOf = ArrayProto.indexOf,
  nativeLastIndexOf = ArrayProto.lastIndexOf,
  nativeIsArray = Array.isArray,
  nativeKeys = Object.keys,
  nativeBind = FuncProto.bind;
 
  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) { return new wrapper(obj); };
 
  // Export the Underscore object for **CommonJS**, with backwards-compatibility
  // for the old `require()` API. If we're not in CommonJS, add `_` to the
  // global object.
  if (typeof module !== 'undefined' && module.exports) {
  module.exports = _;
  _._ = _;
  } else {
  // Exported as a string, for Closure Compiler "advanced" mode.
  root['_'] = _;
  }
 
  // Current version.
  _.VERSION = '1.1.7';
 
  // Collection Functions
  // --------------------
 
  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
  if (obj == null) return;
  if (nativeForEach && obj.forEach === nativeForEach) {
  obj.forEach(iterator, context);
  } else if (obj.length === +obj.length) {
  for (var i = 0, l = obj.length; i < l; i++) {
  if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
  }
  } else {
  for (var key in obj) {
  if (hasOwnProperty.call(obj, key)) {
  if (iterator.call(context, obj[key], key, obj) === breaker) return;
  }
  }
  }
  };
 
  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  each(obj, function(value, index, list) {
  results[results.length] = iterator.call(context, value, index, list);
  });
  return results;
  };
 
  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  var initial = memo !== void 0;
  if (obj == null) obj = [];
  if (nativeReduce && obj.reduce === nativeReduce) {
  if (context) iterator = _.bind(iterator, context);
  return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  }
  each(obj, function(value, index, list) {
  if (!initial) {
  memo = value;
  initial = true;
  } else {
  memo = iterator.call(context, memo, value, index, list);
  }
  });
  if (!initial) throw new TypeError("Reduce of empty array with no initial value");
  return memo;
  };
 
  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  if (obj == null) obj = [];
  if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  if (context) iterator = _.bind(iterator, context);
  return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  }
  var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
  return _.reduce(reversed, iterator, memo, context);
  };
 
  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
  var result;
  any(obj, function(value, index, list) {
  if (iterator.call(context, value, index, list)) {
  result = value;
  return true;
  }
  });
  return result;
  };
 
  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  each(obj, function(value, index, list) {
  if (iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  each(obj, function(value, index, list) {
  if (!iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
  var result = true;
  if (obj == null) return result;
  if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  each(obj, function(value, index, list) {
  if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  });
  return result;
  };
 
  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
  iterator = iterator || _.identity;
  var result = false;
  if (obj == null) return result;
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  each(obj, function(value, index, list) {
  if (result |= iterator.call(context, value, index, list)) return breaker;
  });
  return !!result;
  };
 
  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function(obj, target) {
  var found = false;
  if (obj == null) return found;
  if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  any(obj, function(value) {
  if (found = value === target) return true;
  });
  return found;
  };
 
  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
  var args = slice.call(arguments, 2);
  return _.map(obj, function(value) {
  return (method.call ? method || value : value[method]).apply(value, args);
  });
  };
 
  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
  return _.map(obj, function(value){ return value[key]; });
  };
 
  // Return the maximum element or (element-based computation).
  _.max = function(obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  var result = {computed : -Infinity};
  each(obj, function(value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed >= result.computed && (result = {value : value, computed : computed});
  });
  return result.value;
  };
 
  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  var result = {computed : Infinity};
  each(obj, function(value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed < result.computed && (result = {value : value, computed : computed});
  });
  return result.value;
  };
 
  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, iterator, context) {
  return _.pluck(_.map(obj, function(value, index, list) {
  return {
  value : value,
  criteria : iterator.call(context, value, index, list)
  };
  }).sort(function(left, right) {
  var a = left.criteria, b = right.criteria;
  return a < b ? -1 : a > b ? 1 : 0;
  }), 'value');
  };
 
  // Groups the object's values by a criterion produced by an iterator
  _.groupBy = function(obj, iterator) {
  var result = {};
  each(obj, function(value, index) {
  var key = iterator(value, index);
  (result[key] || (result[key] = [])).push(value);
  });
  return result;
  };
 
  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator) {
  iterator || (iterator = _.identity);
  var low = 0, high = array.length;
  while (low < high) {
  var mid = (low + high) >> 1;
  iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  }
  return low;
  };
 
  // Safely convert anything iterable into a real, live array.
  _.toArray = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  if (_.isArray(iterable)) return slice.call(iterable);
  if (_.isArguments(iterable)) return slice.call(iterable);
  return _.values(iterable);
  };
 
  // Return the number of elements in an object.
  _.size = function(obj) {
  return _.toArray(obj).length;
  };
 
  // Array Functions
  // ---------------
 
  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head`. The **guard** check allows it to work
  // with `_.map`.
  _.first = _.head = function(array, n, guard) {
  return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };
 
  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function(array, index, guard) {
  return slice.call(array, (index == null) || guard ? 1 : index);
  };
 
  // Get the last element of an array.
  _.last = function(array) {
  return array[array.length - 1];
  };
 
  // Trim out all falsy values from an array.
  _.compact = function(array) {
  return _.filter(array, function(value){ return !!value; });
  };
 
  // Return a completely flattened version of an array.
  _.flatten = function(array) {
  return _.reduce(array, function(memo, value) {
  if (_.isArray(value)) return memo.concat(_.flatten(value));
  memo[memo.length] = value;
  return memo;
  }, []);
  };
 
  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
  return _.difference(array, slice.call(arguments, 1));
  };
 
  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted) {
  return _.reduce(array, function(memo, el, i) {
  if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
  return memo;
  }, []);
  };
 
  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
  return _.uniq(_.flatten(arguments));
  };
 
  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function(array) {
  var rest = slice.call(arguments, 1);
  return _.filter(_.uniq(array), function(item) {
  return _.every(rest, function(other) {
  return _.indexOf(other, item) >= 0;
  });
  });
  };
 
  // Take the difference between one array and another.
  // Only the elements present in just the first array will remain.
  _.difference = function(array, other) {
  return _.filter(array, function(value){ return !_.include(other, value); });
  };
 
  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
  var args = slice.call(arguments);
  var length = _.max(_.pluck(args, 'length'));
  var results = new Array(length);
  for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  return results;
  };
 
  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
  if (array == null) return -1;
  var i, l;
  if (isSorted) {
  i = _.sortedIndex(array, item);
  return array[i] === item ? i : -1;
  }
  if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
  for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
  return -1;
  };
 
 
  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item) {
  if (array == null) return -1;
  if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
  var i = array.length;
  while (i--) if (array[i] === item) return i;
  return -1;
  };
 
  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
  if (arguments.length <= 1) {
  stop = start || 0;
  start = 0;
  }
  step = arguments[2] || 1;
 
  var len = Math.max(Math.ceil((stop - start) / step), 0);
  var idx = 0;
  var range = new Array(len);
 
  while(idx < len) {
  range[idx++] = start;
  start += step;
  }
 
  return range;
  };
 
  // Function (ahem) Functions
  // ------------------
 
  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function(func, obj) {
  if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  var args = slice.call(arguments, 2);
  return function() {
  return func.apply(obj, args.concat(slice.call(arguments)));
  };
  };
 
  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
  var funcs = slice.call(arguments, 1);
  if (funcs.length == 0) funcs = _.functions(obj);
  each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  return obj;
  };
 
  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
  var memo = {};
  hasher || (hasher = _.identity);
  return function() {
  var key = hasher.apply(this, arguments);
  return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  };
  };
 
  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
  var args = slice.call(arguments, 2);
  return setTimeout(function(){ return func.apply(func, args); }, wait);
  };
 
  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
  return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };
 
  // Internal function used to implement `_.throttle` and `_.debounce`.
  var limit = function(func, wait, debounce) {
  var timeout;
  return function() {
  var context = this, args = arguments;
  var throttler = function() {
  timeout = null;
  func.apply(context, args);
  };
  if (debounce) clearTimeout(timeout);
  if (debounce || !timeout) timeout = setTimeout(throttler, wait);
  };
  };
 
  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
  return limit(func, wait, false);
  };
 
  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds.
  _.debounce = function(func, wait) {
  return limit(func, wait, true);
  };
 
  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
  var ran = false, memo;
  return function() {
  if (ran) return memo;
  ran = true;
  return memo = func.apply(this, arguments);
  };
  };
 
  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
  return function() {
  var args = [func].concat(slice.call(arguments));
  return wrapper.apply(this, args);
  };
  };
 
  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
  var funcs = slice.call(arguments);
  return function() {
  var args = slice.call(arguments);
  for (var i = funcs.length - 1; i >= 0; i--) {
  args = [funcs[i].apply(this, args)];
  }
  return args[0];
  };
  };
 
  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
  return function() {
  if (--times < 1) { return func.apply(this, arguments); }
  };
  };
 
 
  // Object Functions
  // ----------------
 
  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
  if (obj !== Object(obj)) throw new TypeError('Invalid object');
  var keys = [];
  for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
  return keys;
  };
 
  // Retrieve the values of an object's properties.
  _.values = function(obj) {
  return _.map(obj, _.identity);
  };
 
  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
  var names = [];
  for (var key in obj) {
  if (_.isFunction(obj[key])) names.push(key);
  }
  return names.sort();
  };
 
  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
  each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
  if (source[prop] !== void 0) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Fill in a given object with default properties.
  _.defaults = function(obj) {
  each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
  if (obj[prop] == null) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };
 
  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
  interceptor(obj);
  return obj;
  };
 
  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
  // Check object identity.
  if (a === b) return true;
  // Different types?
  var atype = typeof(a), btype = typeof(b);
  if (atype != btype) return false;
  // Basic equality test (watch out for coercions).
  if (a == b) return true;
  // One is falsy and the other truthy.
  if ((!a && b) || (a && !b)) return false;
  // Unwrap any wrapped objects.
  if (a._chain) a = a._wrapped;
  if (b._chain) b = b._wrapped;
  // One of them implements an isEqual()?
  if (a.isEqual) return a.isEqual(b);
  if (b.isEqual) return b.isEqual(a);
  // Check dates' integer values.
  if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
  // Both are NaN?
  if (_.isNaN(a) && _.isNaN(b)) return false;
  // Compare regular expressions.
  if (_.isRegExp(a) && _.isRegExp(b))
  return a.source === b.source &&
  a.global === b.global &&
  a.ignoreCase === b.ignoreCase &&
  a.multiline === b.multiline;
  // If a is not an object by this point, we can't handle it.
  if (atype !== 'object') return false;
  // Check for different array lengths before comparing contents.
  if (a.length && (a.length !== b.length)) return false;
  // Nothing else worked, deep compare the contents.
  var aKeys = _.keys(a), bKeys = _.keys(b);
  // Different object sizes?
  if (aKeys.length != bKeys.length) return false;
  // Recursive comparison of contents.
  for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
  return true;
  };
 
  // Is a given array or object empty?
  _.isEmpty = function(obj) {
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
  return true;
  };
 
  // Is a given value a DOM element?
  _.isElement = function(obj) {
  return !!(obj && obj.nodeType == 1);
  };
 
  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
  return toString.call(obj) === '[object Array]';
  };
 
  // Is a given variable an object?
  _.isObject = function(obj) {
  return obj === Object(obj);
  };
 
  // Is a given variable an arguments object?
  _.isArguments = function(obj) {
  return !!(obj && hasOwnProperty.call(obj, 'callee'));
  };
 
  // Is a given value a function?
  _.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
  };
 
  // Is a given value a string?
  _.isString = function(obj) {
  return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
  };
 
  // Is a given value a number?
  _.isNumber = function(obj) {
  return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
  };
 
  // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
  // that does not equal itself.
  _.isNaN = function(obj) {
  return obj !== obj;
  };
 
  // Is a given value a boolean?
  _.isBoolean = function(obj) {
  return obj === true || obj === false;
  };
 
  // Is a given value a date?
  _.isDate = function(obj) {
  return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
  };
 
  // Is the given value a regular expression?
  _.isRegExp = function(obj) {
  return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };
 
  // Is a given value equal to null?
  _.isNull = function(obj) {
  return obj === null;
  };
 
  // Is a given variable undefined?
  _.isUndefined = function(obj) {
  return obj === void 0;
  };
 
  // Utility Functions
  // -----------------
 
  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
  root._ = previousUnderscore;
  return this;
  };
 
  // Keep the identity function around for default iterators.
  _.identity = function(value) {
  return value;
  };
 
  // Run a function **n** times.
  _.times = function (n, iterator, context) {
  for (var i = 0; i < n; i++) iterator.call(context, i);
  };
 
  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function(obj) {
  each(_.functions(obj), function(name){
  addToWrapper(name, _[name] = obj[name]);
  });
  };
 
  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
  var id = idCounter++;
  return prefix ? prefix + id : id;
  };
 
  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
  evaluate : /<%([\s\S]+?)%>/g,
  interpolate : /<%=([\s\S]+?)%>/g
  };
 
  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(str, data) {
  var c = _.templateSettings;
  var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
  'with(obj||{}){__p.push(\'' +
  str.replace(/\\/g, '\\\\')
  .replace(/'/g, "\\'")
  .replace(c.interpolate, function(match, code) {
  return "'," + code.replace(/\\'/g, "'") + ",'";
  })
  .replace(c.evaluate || null, function(match, code) {
  return "');" + code.replace(/\\'/g, "'")
  .replace(/[\r\n\t]/g, ' ') + "__p.push('";
  })
  .replace(/\r/g, '\\r')
  .replace(/\n/g, '\\n')
  .replace(/\t/g, '\\t')
  + "');}return __p.join('');";
  var func = new Function('obj', tmpl);
  return data ? func(data) : func;
  };
 
  // The OOP Wrapper
  // ---------------
 
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function(obj) { this._wrapped = obj; };
 
  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;
 
  // Helper function to continue chaining intermediate results.
  var result = function(obj, chain) {
  return chain ? _(obj).chain() : obj;
  };
 
  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function(name, func) {
  wrapper.prototype[name] = function() {
  var args = slice.call(arguments);
  unshift.call(args, this._wrapped);
  return result(func.apply(_, args), this._chain);
  };
  };
 
  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);
 
  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function() {
  method.apply(this._wrapped, arguments);
  return result(this._wrapped, this._chain);
  };
  });
 
  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function() {
  return result(method.apply(this._wrapped, arguments), this._chain);
  };
  });
 
  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function() {
  this._chain = true;
  return this;
  };
 
  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function() {
  return this._wrapped;
  };
 
  })();
 
  /*yepnope1.0.2|WTFPL*/(function(a,b,c){function H(){var a=z;a.loader={load:G,i:0};return a}function G(a,b,c){var e=b=="c"?r:q;i=0,b=b||"j",u(a)?F(e,a,b,this.i++,d,c):(h.splice(this.i++,0,a),h.length==1&&E());return this}function F(a,c,d,g,j,l){function q(){!o&&A(n.readyState)&&(p.r=o=1,!i&&B(),n.onload=n.onreadystatechange=null,e(function(){m.removeChild(n)},0))}var n=b.createElement(a),o=0,p={t:d,s:c,e:l};n.src=n.data=c,!k&&(n.style.display="none"),n.width=n.height="0",a!="object"&&(n.type=d),n.onload=n.onreadystatechange=q,a=="img"?n.onerror=q:a=="script"&&(n.onerror=function(){p.e=p.r=1,E()}),h.splice(g,0,p),m.insertBefore(n,k?null:f),e(function(){o||(m.removeChild(n),p.r=p.e=o=1,B())},z.errorTimeout)}function E(){var a=h.shift();i=1,a?a.t?e(function(){a.t=="c"?D(a):C(a)},0):(a(),B()):i=0}function D(a){var c=b.createElement("link"),d;c.href=a.s,c.rel="stylesheet",c.type="text/css";if(!a.e&&(o||j)){var g=function(a){e(function(){if(!d)try{a.sheet.cssRules.length?(d=1,B()):g(a)}catch(b){b.code==1e3||b.message=="security"||b.message=="denied"?(d=1,e(function(){B()},0)):g(a)}},0)};g(c)}else c.onload=function(){d||(d=1,e(function(){B()},0))},a.e&&c.onload();e(function(){d||(d=1,B())},z.errorTimeout),!a.e&&f.parentNode.insertBefore(c,f)}function C(a){var c=b.createElement("script"),d;c.src=a.s,c.onreadystatechange=c.onload=function(){!d&&A(c.readyState)&&(d=1,B(),c.onload=c.onreadystatechange=null)},e(function(){d||(d=1,B())},z.errorTimeout),a.e?c.onload():f.parentNode.insertBefore(c,f)}function B(){var a=1,b=-1;while(h.length- ++b)if(h[b].s&&!(a=h[b].r))break;a&&E()}function A(a){return!a||a=="loaded"||a=="complete"}var d=b.documentElement,e=a.setTimeout,f=b.getElementsByTagName("script")[0],g={}.toString,h=[],i=0,j="MozAppearance"in d.style,k=j&&!!b.createRange().compareNode,l=j&&!k,m=k?d:f.parentNode,n=a.opera&&g.call(a.opera)=="[object Opera]",o="webkitAppearance"in d.style,p=o&&"async"in b.createElement("script"),q=j?"object":n||p?"img":"script",r=o?"img":q,s=Array.isArray||function(a){return g.call(a)=="[object Array]"},t=function(a){return Object(a)===a},u=function(a){return typeof a=="string"},v=function(a){return g.call(a)=="[object Function]"},w=[],x={},y,z;z=function(a){function h(a,b){function i(a){if(u(a))g(a,f,b,0,c);else if(t(a))for(h in a)a.hasOwnProperty(h)&&g(a[h],f,b,h,c)}var c=!!a.test,d=c?a.yep:a.nope,e=a.load||a.both,f=a.callback,h;i(d),i(e),a.complete&&b.load(a.complete)}function g(a,b,d,e,g){var h=f(a),i=h.autoCallback;if(!h.bypass){b&&(b=v(b)?b:b[a]||b[e]||b[a.split("/").pop().split("?")[0]]);if(h.instead)return h.instead(a,b,d,e,g);d.load(h.url,h.forceCSS||!h.forceJS&&/css$/.test(h.url)?"c":c,h.noexec),(v(b)||v(i))&&d.load(function(){H(),b&&b(h.origUrl,g,e),i&&i(h.origUrl,g,e)})}}function f(a){var b=a.split("!"),c=w.length,d=b.pop(),e=b.length,f={url:d,origUrl:d,prefixes:b},g,h;for(h=0;h<e;h++)g=x[b[h]],g&&(f=g(f));for(h=0;h<c;h++)f=w[h](f);return f}var b,d,e=this.yepnope.loader;if(u(a))g(a,0,e,0);else if(s(a))for(b=0;b<a.length;b++)d=a[b],u(d)?g(d,0,e,0):s(d)?z(d):t(d)&&h(d,e);else t(a)&&h(a,e)},z.addPrefix=function(a,b){x[a]=b},z.addFilter=function(a){w.push(a)},z.errorTimeout=1e4,b.readyState==null&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",y=function(){b.removeEventListener("DOMContentLoaded",y,0),b.readyState="complete"},0)),a.yepnope=H()})(this,this.document)
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "flotr2-basic": [
  "./js/Flotr.js",
  "./js/DefaultOptions.js",
  "./js/DOM.js",
  "./js/EventAdapter.js",
  "./js/Color.js",
  "./js/Date.js",
  "./js/Text.js",
  "./js/Graph.js",
  "./js/Axis.js",
  "./js/Series.js",
  "./js/types/lines.js",
  "./js/types/bars.js",
  "./js/types/markers.js",
  "./js/types/points.js",
  "./js/plugins/grid.js",
  "./js/plugins/labels.js",
  "./js/plugins/legend.js",
  "./js/plugins/titles.js"
  ]
  }
  }
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "ie": [
  {
  "src": "./lib/excanvas.js",
  "jshint": false
  },
  {
  "src": "./lib/base64.js",
  "jshint": false
  },
  {
  "src": "./lib/canvastext.js",
  "jshint": false
  }
  ],
  "lib": [
  {
  "src": "./lib/bean.js",
  "jshint": false
  },
  {
  "src": "./lib/underscore.js",
  "jshint": false
  }
  ],
  "flotr2": [
  "./js/Flotr.js",
  "./js/DefaultOptions.js",
  "./js/Color.js",
  "./js/Date.js",
  "./js/DOM.js",
  "./js/EventAdapter.js",
  "./js/Text.js",
  "./js/Graph.js",
  "./js/Axis.js",
  "./js/Series.js",
  "./js/types/lines.js",
  "./js/types/bars.js",
  "./js/types/bubbles.js",
  "./js/types/candles.js",
  "./js/types/gantt.js",
  "./js/types/markers.js",
  "./js/types/pie.js",
  "./js/types/points.js",
  "./js/types/radar.js",
  "./js/types/timeline.js",
  "./js/plugins/crosshair.js",
  "./js/plugins/download.js",
  "./js/plugins/grid.js",
  "./js/plugins/hit.js",
  "./js/plugins/selection.js",
  "./js/plugins/labels.js",
  "./js/plugins/legend.js",
  "./js/plugins/spreadsheet.js",
  "./js/plugins/titles.js"
  ],
  "flotr2-basic": [
  "./js/Flotr.js",
  "./js/DefaultOptions.js",
  "./js/DOM.js",
  "./js/EventAdapter.js",
  "./js/Color.js",
  "./js/Date.js",
  "./js/Text.js",
  "./js/Graph.js",
  "./js/Axis.js",
  "./js/Series.js",
  "./js/types/lines.js",
  "./js/types/bars.js",
  "./js/types/markers.js",
  "./js/types/points.js",
  "./js/plugins/grid.js",
  "./js/plugins/labels.js",
  "./js/plugins/legend.js",
  "./js/plugins/titles.js"
  ],
  "examples": [
  "./examples/js/Examples.js",
  "./examples/js/Example.js",
  "./examples/js/Editor.js",
  "./examples/js/Profile.js"
  ],
  "examples-types": [
  "./examples/js/ExampleList.js",
  "./examples/js/examples/basic.js",
  "./examples/js/examples/basic-stacked.js",
  "./examples/js/examples/basic-axis.js",
  "./examples/js/examples/basic-bars.js",
  "./examples/js/examples/basic-bars-stacked.js",
  "./examples/js/examples/basic-pie.js",
  "./examples/js/examples/basic-radar.js",
  "./examples/js/examples/basic-bubble.js",
  "./examples/js/examples/basic-candle.js",
  "./examples/js/examples/basic-legend.js",
  "./examples/js/examples/mouse-tracking.js",
  "./examples/js/examples/mouse-zoom.js",
  "./examples/js/examples/mouse-drag.js",
  "./examples/js/examples/basic-time.js",
  "./examples/js/examples/negative-values.js",
  "./examples/js/examples/click-example.js",
  "./examples/js/examples/download-image.js",
  "./examples/js/examples/download-data.js",
  "./examples/js/examples/advanced-titles.js",
  "./examples/js/examples/color-gradients.js",
  "./examples/js/examples/profile-bars.js",
  "./examples/js/examples/basic-timeline.js",
  "./examples/js/examples/advanced-markers.js"
  ]
  }
  }
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "examples": [
  "./examples/js/Examples.js",
  "./examples/js/Example.js",
  "./examples/js/Editor.js",
  "./examples/js/Profile.js"
  ],
  "examples-types": [
  "./examples/js/ExampleList.js",
  "./examples/js/examples/basic.js",
  "./examples/js/examples/basic-stacked.js",
  "./examples/js/examples/basic-stepped.js",
  "./examples/js/examples/basic-axis.js",
  "./examples/js/examples/basic-bars.js",
  "./examples/js/examples/basic-bars-stacked.js",
  "./examples/js/examples/basic-pie.js",
  "./examples/js/examples/basic-radar.js",
  "./examples/js/examples/basic-bubble.js",
  "./examples/js/examples/basic-candle.js",
  "./examples/js/examples/basic-legend.js",
  "./examples/js/examples/mouse-tracking.js",
  "./examples/js/examples/mouse-zoom.js",
  "./examples/js/examples/mouse-drag.js",
  "./examples/js/examples/basic-time.js",
  "./examples/js/examples/negative-values.js",
  "./examples/js/examples/click-example.js",
  "./examples/js/examples/download-image.js",
  "./examples/js/examples/download-data.js",
  "./examples/js/examples/advanced-titles.js",
  "./examples/js/examples/color-gradients.js",
  "./examples/js/examples/profile-bars.js",
  "./examples/js/examples/basic-timeline.js",
  "./examples/js/examples/advanced-markers.js"
  ]
  }
  }
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "flotr2": [
  "./js/Flotr.js",
  "./js/DefaultOptions.js",
  "./js/Color.js",
  "./js/Date.js",
  "./js/DOM.js",
  "./js/EventAdapter.js",
  "./js/Text.js",
  "./js/Graph.js",
  "./js/Axis.js",
  "./js/Series.js",
  "./js/types/lines.js",
  "./js/types/bars.js",
  "./js/types/bubbles.js",
  "./js/types/candles.js",
  "./js/types/gantt.js",
  "./js/types/markers.js",
  "./js/types/pie.js",
  "./js/types/points.js",
  "./js/types/radar.js",
  "./js/types/timeline.js",
  "./js/plugins/crosshair.js",
  "./js/plugins/download.js",
  "./js/plugins/grid.js",
  "./js/plugins/hit.js",
  "./js/plugins/selection.js",
  "./js/plugins/labels.js",
  "./js/plugins/legend.js",
  "./js/plugins/spreadsheet.js",
  "./js/plugins/titles.js"
  ]
  }
  }
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "ie": [
  {
  "src": "./lib/excanvas.js",
  "jshint": false
  },
  {
  "src": "./lib/base64.js",
  "jshint": false
  },
  {
  "src": "./lib/canvastext.js",
  "jshint": false
  }
  ]
  }
  }
 
  {
  "JAVASCRIPT": {
  "DIST_DIR": "./build",
  "bean": [
  {
  "src": "./lib/bean.js",
  "jshint": false
  }
  ],
  "underscore": [
  {
  "src": "./lib/underscore.js",
  "jshint": false
  }
  ]
  }
  }
 
  describe('Charts', function () {
 
  var
  width = 480,
  height = 320,
  a, b, options, defaults;
 
  defaults = {
  width: 480,
  height: 320,
  color: "rgb(192,216,0)",
  context: null,
  data: null,
  fill: false,
  fillColor: null,
  fillOpacity: 0.4,
  fillStyle: "rgba(192,216,0,0.4)",
  fontColor: "#545454",
  fontSize: 7.5,
  htmlText: true,
  lineWidth: 2,
  shadowSize: 4,
  show: false,
  stacked: false,
  textEnabled: true,
  xScale: function (x) {
  return x;
  },
  yScale: function (y) {
  return height - y;
  }
  };
 
  /**
  * @param skip bool Skip test against development version (use this when developing test)
  */
  function drawTest(data, o, skip) {
  options.data = data;
  if (o) _.extend(options, o);
 
  if (!skip) TestFlotr.graphTypes.lines.draw(options);
  options.context = b.getContext('2d');
  StableFlotr.graphTypes.lines.draw(options);
 
  expect(b).toImageDiffEqual(a);
  }
 
  describe('Lines', function () {
 
  beforeEach(function () {
  options = _.clone(defaults);
  });
 
  /*
  describe('Data', function () {
  it('gets a range', function () {
  options.stacked = true;
  options.data = [[0, 0], [240, 160], [480, 320]];
  range = TestFlotr.graphTypes.lines.range(options);
  expect(range.min).toEqual(0);
  expect(range.max).toEqual(320);
  });
  });
  */
 
  describe('Draw', function () {
 
  beforeEach(function () {
  this.addMatchers(imagediff.jasmine);
  a = imagediff.createCanvas(width, height);
  b = imagediff.createCanvas(width, height);
  options.context = a.getContext('2d');
  });
 
  it('draws a line chart', function () {
  drawTest([
  [0, 0],
  [240, 300],
  [480, 0]
  ]);
  });
 
  it('skips null values', function () {
  drawTest([
  [0, 0],
  [100, 50],
  [200, null],
  [300, 150],
  [400, 200],
  [480, 240]
  ]);
  });
 
  it('draws two lines', function () {
  // First line
  drawTest([
  [0, 0],
  [240, 160],
  [480, 320]
  ]);
 
  // Second Line
  options.context = a.getContext('2d');
  drawTest([
  [0, 320],
  [240, 160],
  [480, 0]
  ]);
  });
 
  it('fills a line', function () {
  drawTest([
  [0, 0],
  [240, 300],
  [480, 0]
  ], {
  fill: true
  });
  });
 
  it('draws no shadow', function () {
  drawTest([
  [0, 0],
  [240, 300],
  [480, 0]
  ], {
  shadowSize: 0
  });
  });
  });
  });
  });
 
  describe('Colors', function () {
 
  describe('Color Construction', function () {
  it('should have a color class', function () {
  expect(TestFlotr.Color).not.toBeUndefined();
  });
 
  it('should create a color', function () {
  var color = new TestFlotr.Color(0, 0, 0, 0);
  expect(color).toBeTruthy();
  });
 
  it('should have rgba attributes', function () {
  var color = new TestFlotr.Color(0, 0, 0, 0);
  expect(color.r).toEqual(0);
  expect(color.g).toEqual(0);
  expect(color.b).toEqual(0);
  expect(color.a).toEqual(1.0);
  });
  });
 
  describe('Color Manipulation', function () {
 
  var
  color;
 
  afterEach(function () {
  color = null;
  });
 
  it('normalizes colors to upper bound', function () {
  color = new TestFlotr.Color(1000, 1000, 1000, 10);
  expect(color.r).toEqual(255);
  expect(color.g).toEqual(255);
  expect(color.b).toEqual(255);
  expect(color.a).toEqual(1.0);
  });
 
  it('normalizes colors to lower bound', function () {
  color = new TestFlotr.Color(-1000, -1000, -1000, -10);
  expect(color.r).toEqual(0);
  expect(color.g).toEqual(0);
  expect(color.b).toEqual(0);
  expect(color.a).toEqual(0.0);
  });
 
  it('scales colors', function () {
  color = new TestFlotr.Color(200, 200, 200, 1.0);
  color.scale(.5, .5, .5, .5);
  expect(color.r).toEqual(100);
  expect(color.g).toEqual(100);
  expect(color.b).toEqual(100);
  expect(color.a).toEqual(0.5);
  });
  });
 
  describe('Color Conversion', function () {
 
  var
  color;
 
  beforeEach(function () {
  color = new TestFlotr.Color(200, 200, 200, 1.0);
  });
  afterEach(function () {
  color = null;
  });
 
  it('should convert colors to strings, rgb', function () {
  expect(color.toString()).toEqual('rgb(200,200,200)');
  });
 
  it('should convert colors to strings, rgba', function () {
  color.a = 0.5;
  color.normalize();
  expect(color.toString()).toEqual('rgba(200,200,200,0.5)');
  });
 
  it('should clone colors', function () {
 
  var
  color2 = color.clone();
 
  expect(color.toString()).toEqual(color2.toString());
 
  color.a = 0.5;
  color.normalize();
  color2 = color.clone();
  expect(color.toString()).toEqual(color2.toString());
  });
  });
  });
 
  describe('Flotr', function () {
 
  describe('Plots', function () {
 
  var
  nodeA, nodeB,
  a, b;
 
  beforeEach(function () {
 
  // Add imagediff matchers
  this.addMatchers(imagediff.jasmine);
 
  nodeA = buildNode();
  nodeB = buildNode();
  });
 
  afterEach(function () {
  destroyNode(nodeA);
  destroyNode(nodeB);
  a = null;
  b = null;
  Flotr = null;
  });
 
  _.each(TestFlotr.ExampleList.examples, function (example, key) {
 
  it('should draw a `' + example.name + '`line graph', function () {
 
  executeExampleTest(example, StableFlotr, nodeA);
  executeExampleTest(example, TestFlotr, nodeB);
 
  if (example.timeout) {
  waits(example.timeout);
  runs(function () {
  expect(nodeB.graph.ctx).toImageDiffEqual(nodeA.graph.ctx, example.tolerance || 0);
  });
  } else {
  expect(nodeB.graph.ctx).toImageDiffEqual(nodeA.graph.ctx, example.tolerance || 0);
  }
  });
  });
 
  // Helpers
 
  function executeExampleTest(example, flotr, node) {
  Math.seedrandom(example.key);
  Flotr = flotr;
  example.callback.apply(this, [node].concat(example.args || []));
  }
 
  function buildNode() {
  var node = document.createElement('div');
  document.body.appendChild(node);
  node.style.width = '320px';
  node.style.height = '240px';
  return node;
  }
 
  function destroyNode(node) {
  document.body.removeChild(node);
  }
  });
 
  describe('Main', function () {
 
  it('gets a tick size', function () {
  expect(TestFlotr.getTickSize).not.toBeUndefined();
  expect(TestFlotr.getTickSize(10, 0, 100, 1)).toEqual(10);
  expect(TestFlotr.getTickSize(20, 0, 100, 1)).toEqual(5);
  expect(TestFlotr.getTickSize(5, 10, 110, 1)).toEqual(20);
  expect(TestFlotr.getTickSize(0, 0, 10, 1)).toEqual(Number.POSITIVE_INFINITY);
  expect(isNaN(TestFlotr.getTickSize(0, 0, -10, 1))).toBeTruthy();
  });
  });
  });
 
  describe('Graph', function () {
 
  describe('Options', function () {
  var
  nodeA, nodeB,
  a, b, x, i,
  d1 = [],
  options = {};
 
  for (i = 0; i < 100; i++) {
  x = (i * 1000 * 3600 * 24 * 36.5);
  d1.push([x, i + Math.random() * 30 + Math.sin(i / 20 + Math.random() * 2) * 20 + Math.sin(i / 10 + Math.random()) * 10]);
  }
 
  options = {
  xaxis: {
  mode: 'time',
  labelsAngle: 45
  },
  selection: {
  mode: 'x'
  },
  HtmlText: false,
  };
 
  beforeEach(function () {
  nodeA = buildNode();
  Flotr = TestFlotr;
  });
 
  afterEach(function () {
  destroyNode(nodeA);
  a = b = null;
  Flotr = null;
  });
 
  it('should override nested default options with user options', function () {
  a = new TestFlotr.Graph(nodeA, d1, options);
  expect(a.options.xaxis.mode).toEqual(options.xaxis.mode);
  });
 
  it('should retain default options if user option\'s nested object does not define property', function () {
  a = new TestFlotr.Graph(nodeA, d1, options);
  expect(a.options.xaxis.tickFormatter).toBeTruthy();
  });
 
  it('should not affect default options when modifying graph options (objects)', function () {
  a = new TestFlotr.Graph(nodeA, d1, options);
  a.options.x2axis = {
  titleAlign: 'left'
  };
  a.options.xaxis.scaling = 'logarithmic';
  expect(TestFlotr.defaultOptions.xaxis.scaling).toEqual('linear');
  expect(TestFlotr.defaultOptions.x2axis.titleAlign).toBeFalsy();
  });
 
  /*
  it('should not affect default options when modifying graph options (arrays)', function() {
  a = new TestFlotr.Graph(nodeA, d1, options);
  a.options.colors[1] = '#bada55';
  expect(TestFlotr.defaultOptions.colors[1]).toNotBe('#bada55');
  });
  */
 
  });
 
  function buildNode() {
  var node = document.createElement('div');
  document.body.appendChild(node);
  node.style.width = '320px';
  node.style.height = '240px';
  return node;
  }
 
  function destroyNode(node) {
  document.body.removeChild(node);
  }
 
  });
 
  var StableFlotr = Flotr.noConflict();
 
  var TestFlotr = Flotr.noConflict();
 
 Binary files /dev/null and b/js/flotr2/spec/images/butterfly.jpg differ
 Binary files /dev/null and b/js/flotr2/spec/images/checkmark.png differ
 Binary files /dev/null and b/js/flotr2/spec/images/xmark.png differ
 Binary files /dev/null and b/js/flotr2/spec/img/test-background.png differ
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <title>Jasmine Spec Runner</title>
 
  <link rel="shortcut icon" type="image/png" href="../lib/jasmine/jasmine_favicon.png">
 
  <link rel="stylesheet" type="text/css" href="../lib/jasmine/jasmine.css">
  <script type="text/javascript" src="../lib/jasmine/jasmine.js"></script>
  <script type="text/javascript" src="../lib/jasmine/jasmine-html.js"></script>
  <script type="text/javascript" src="../lib/imagediff.js"></script>
  <script type="text/javascript" src="../examples/lib/randomseed.js"></script>
 
  <!-- include source files here... -->
  <script type="text/javascript" src="js/flotr2.stable.js"></script>
  <script type="text/javascript">
  var StableFlotr = Flotr.noConflict();
  </script>
 
  <script src="../lib/bean.js"></script>
  <script src="../lib/underscore.js"></script>
  <script src="../js/Flotr.js"></script>
  <script src="../js/DefaultOptions.js"></script>
  <script src="../js/Color.js"></script>
  <script src="../js/Date.js"></script>
  <script src="../js/DOM.js"></script>
  <script src="../js/EventAdapter.js"></script>
  <script src="../js/Text.js"></script>
  <script src="../js/Graph.js"></script>
  <script src="../js/Axis.js"></script>
  <script src="../js/Series.js"></script>
  <script src="../js/types/lines.js"></script>
  <script src="../js/types/bars.js"></script>
  <script src="../js/types/bubbles.js"></script>
  <script src="../js/types/candles.js"></script>
  <script src="../js/types/gantt.js"></script>
  <script src="../js/types/markers.js"></script>
  <script src="../js/types/pie.js"></script>
  <script src="../js/types/points.js"></script>
  <script src="../js/types/radar.js"></script>
  <script src="../js/types/timeline.js"></script>
  <script src="../js/plugins/crosshair.js"></script>
  <script src="../js/plugins/download.js"></script>
  <script src="../js/plugins/grid.js"></script>
  <script src="../js/plugins/hit.js"></script>
  <script src="../js/plugins/selection.js"></script>
  <script src="../js/plugins/labels.js"></script>
  <script src="../js/plugins/legend.js"></script>
  <script src="../js/plugins/spreadsheet.js"></script>
  <script src="../js/plugins/titles.js"></script>
  <script src="../js/charts/lines.js"></script>
 
  <!-- Test Examples -->
  <script type="text/javascript" src="../flotr2.examples.types.js"></script>
  <script type="text/javascript" src="js/test-background.js"></script>
  <script type="text/javascript" src="js/test-boundaries.js"></script>
  <script type="text/javascript" src="js/test-mountain-nulls.js"></script>
 
  <script type="text/javascript">
  var TestFlotr = Flotr.noConflict();
  </script>
 
  <!-- include spec files here... -->
  <script type="text/javascript" src="Flotr.js"></script>
  <script type="text/javascript" src="Color.js"></script>
  <script type="text/javascript" src="Graph.js"></script>
  <script type="text/javascript" src="Chart.js"></script>
 
  </head>
 
  <body>
  </body>
  <script type="text/javascript">
  (function () {
  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.updateInterval = 1000;
 
  var reporter = new jasmine.HtmlReporter();
 
  jasmineEnv.addReporter(reporter);
 
  jasmineEnv.specFilter = function (spec) {
  return reporter.specFilter(spec);
  };
 
  var currentWindowOnload = window.onload;
 
  window.onload = function () {
  if (currentWindowOnload) {
  currentWindowOnload();
  }
  execJasmine();
  };
 
  function execJasmine() {
  jasmineEnv.execute();
  }
 
  })();
  </script>
  </html>
 
  src_files:
  - "lib/imagediff.js"
  - "examples/lib/randomseed.js"
  - "spec/js/flotr2.stable.js"
  - "spec/helpers/stableFlotr.js"
  - "lib/bean.js"
  - "lib/underscore.js"
  - "js/Flotr.js"
  - "js/DefaultOptions.js"
  - "js/Color.js"
  - "js/Date.js"
  - "js/DOM.js"
  - "js/EventAdapter.js"
  - "js/Text.js"
  - "js/Graph.js"
  - "js/Axis.js"
  - "js/Series.js"
  - "js/types/lines.js"
  - "js/types/bars.js"
  - "js/types/bubbles.js"
  - "js/types/candles.js"
  - "js/types/gantt.js"
  - "js/types/markers.js"
  - "js/types/pie.js"
  - "js/types/points.js"
  - "js/types/radar.js"
  - "js/types/timeline.js"
  - "js/plugins/crosshair.js"
  - "js/plugins/download.js"
  - "js/plugins/grid.js"
  - "js/plugins/hit.js"
  - "js/plugins/selection.js"
  - "js/plugins/labels.js"
  - "js/plugins/legend.js"
  - "js/plugins/spreadsheet.js"
  - "js/plugins/titles.js"
  - "flotr2.examples.types.js"
  - "spec/js/test-background.js"
  - "spec/js/test-boundaries.js"
  - "spec/js/test-mountain-nulls.js"
  - "spec/helpers/testFlotr.js"
  helpers:
  spec_files:
  - "Flotr.js"
  - "Color.js"
  - "Graph.js"
  - "Chart.js"
  src_dir: ".."
  spec_dir: "../spec/"
 
  /*!
  * bean.js - copyright Jacob Thornton 2011
  * https://github.com/fat/bean
  * MIT License
  * special thanks to:
  * dean edwards: http://dean.edwards.name/
  * dperini: https://github.com/dperini/nwevents
  * the entire mootools team: github.com/mootools/mootools-core
  */
  /*global module:true, define:true*/
  !function (name, context, definition) {
  if (typeof module !== 'undefined') module.exports = definition(name, context);
  else if (typeof define === 'function' && typeof define.amd === 'object') define(definition);
  else context[name] = definition(name, context);
  }('bean', this, function (name, context) {
  var win = window
  , old = context[name]
  , overOut = /over|out/
  , namespaceRegex = /[^\.]*(?=\..*)\.|.*/
  , nameRegex = /\..*/
  , addEvent = 'addEventListener'
  , attachEvent = 'attachEvent'
  , removeEvent = 'removeEventListener'
  , detachEvent = 'detachEvent'
  , doc = document || {}
  , root = doc.documentElement || {}
  , W3C_MODEL = root[addEvent]
  , eventSupport = W3C_MODEL ? addEvent : attachEvent
  , slice = Array.prototype.slice
  , mouseTypeRegex = /click|mouse|menu|drag|drop/i
  , touchTypeRegex = /^touch|^gesture/i
  , ONE = { one: 1 } // singleton for quick matching making add() do one()
 
  , nativeEvents = (function (hash, events, i) {
  for (i = 0; i < events.length; i++)
  hash[events[i]] = 1
  return hash
  })({}, (
  'click dblclick mouseup mousedown contextmenu ' + // mouse buttons
  'mousewheel DOMMouseScroll ' + // mouse wheel
  'mouseover mouseout mousemove selectstart selectend ' + // mouse movement
  'keydown keypress keyup ' + // keyboard
  'orientationchange ' + // mobile
  'focus blur change reset select submit ' + // form elements
  'load unload beforeunload resize move DOMContentLoaded readystatechange ' + // window
  'error abort scroll ' + // misc
  (W3C_MODEL ? // element.fireEvent('onXYZ'... is not forgiving if we try to fire an event
  // that doesn't actually exist, so make sure we only do these on newer browsers
  'show ' + // mouse buttons
  'input invalid ' + // form elements
  'touchstart touchmove touchend touchcancel ' + // touch
  'gesturestart gesturechange gestureend ' + // gesture
  'message readystatechange pageshow pagehide popstate ' + // window
  'hashchange offline online ' + // window
  'afterprint beforeprint ' + // printing
  'dragstart dragenter dragover dragleave drag drop dragend ' + // dnd
  'loadstart progress suspend emptied stalled loadmetadata ' + // media
  'loadeddata canplay canplaythrough playing waiting seeking ' + // media
  'seeked ended durationchange timeupdate play pause ratechange ' + // media
  'volumechange cuechange ' + // media
  'checking noupdate downloading cached updateready obsolete ' + // appcache
  '' : '')
  ).split(' ')
  )
 
  , customEvents = (function () {
  function isDescendant(parent, node) {
  while ((node = node.parentNode) !== null) {
  if (node === parent) return true
  }
  return false
  }
 
  function check(event) {
  var related = event.relatedTarget
  if (!related) return related === null
  return (related !== this && related.prefix !== 'xul' && !/document/.test(this.toString()) && !isDescendant(this, related))
  }
 
  return {
  mouseenter: { base: 'mouseover', condition: check }, mouseleave: { base: 'mouseout', condition: check }, mousewheel: { base: /Firefox/.test(navigator.userAgent) ? 'DOMMouseScroll' : 'mousewheel' }
  }
  })()
 
  , fixEvent = (function () {
  var commonProps = 'altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which'.split(' ')
  , mouseProps = commonProps.concat('button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement'.split(' '))
  , keyProps = commonProps.concat('char charCode key keyCode'.split(' '))
  , touchProps = commonProps.concat('touches targetTouches changedTouches scale rotation'.split(' '))
  , preventDefault = 'preventDefault'
  , createPreventDefault = function (event) {
  return function () {
  if (event[preventDefault])
  event[preventDefault]()
  else
  event.returnValue = false
  }
  }
  , stopPropagation = 'stopPropagation'
  , createStopPropagation = function (event) {
  return function () {
  if (event[stopPropagation])
  event[stopPropagation]()
  else
  event.cancelBubble = true
  }
  }
  , createStop = function (synEvent) {
  return function () {
  synEvent[preventDefault]()
  synEvent[stopPropagation]()
  synEvent.stopped = true
  }
  }
  , copyProps = function (event, result, props) {
  var i, p
  for (i = props.length; i--;) {
  p = props[i]
  if (!(p in result) && p in event) result[p] = event[p]
  }
  }
 
  return function (event, isNative) {
  var result = { originalEvent: event, isNative: isNative }
  if (!event)
  return result
 
  var props
  , type = event.type
  , target = event.target || event.srcElement
 
  result[preventDefault] = createPreventDefault(event)
  result[stopPropagation] = createStopPropagation(event)
  result.stop = createStop(result)
  result.target = target && target.nodeType === 3 ? target.parentNode : target
 
  if (isNative) { // we only need basic augmentation on custom events, the rest is too expensive
  if (type.indexOf('key') !== -1) {
  props = keyProps
  result.keyCode = event.which || event.keyCode
  } else if (mouseTypeRegex.test(type)) {
  props = mouseProps
  result.rightClick = event.which === 3 || event.button === 2
  result.pos = { x: 0, y: 0 }
  if (event.pageX || event.pageY) {
  result.clientX = event.pageX
  result.clientY = event.pageY
  } else if (event.clientX || event.clientY) {
  result.clientX = event.clientX + doc.body.scrollLeft + root.scrollLeft
  result.clientY = event.clientY + doc.body.scrollTop + root.scrollTop
  }
  if (overOut.test(type))
  result.relatedTarget = event.relatedTarget || event[(type === 'mouseover' ? 'from' : 'to') + 'Element']
  } else if (touchTypeRegex.test(type)) {
  props = touchProps
  }
  copyProps(event, result, props || commonProps)
  }
  return result
  }
  })()
 
  // if we're in old IE we can't do onpropertychange on doc or win so we use doc.documentElement for both
  , targetElement = function (element, isNative) {
  return !W3C_MODEL && !isNative && (element === doc || element === win) ? root : element
  }
 
  // we use one of these per listener, of any type
  , RegEntry = (function () {
  function entry(element, type, handler, original, namespaces) {
  this.element = element
  this.type = type
  this.handler = handler
  this.original = original
  this.namespaces = namespaces
  this.custom = customEvents[type]
  this.isNative = nativeEvents[type] && element[eventSupport]
  this.eventType = W3C_MODEL || this.isNative ? type : 'propertychange'
  this.customType = !W3C_MODEL && !this.isNative && type
  this.target = targetElement(element, this.isNative)
  this.eventSupport = this.target[eventSupport]
  }
 
  entry.prototype = {
  // given a list of namespaces, is our entry in any of them?
  inNamespaces: function (checkNamespaces) {
  var i, j
  if (!checkNamespaces)
  return true
  if (!this.namespaces)
  return false
  for (i = checkNamespaces.length; i--;) {
  for (j = this.namespaces.length; j--;) {
  if (checkNamespaces[i] === this.namespaces[j])
  return true
  }
  }
  return false
  }
 
  // match by element, original fn (opt), handler fn (opt)
  , matches: function (checkElement, checkOriginal, checkHandler) {
  return this.element === checkElement &&
  (!checkOriginal || this.original === checkOriginal) &&
  (!checkHandler || this.handler === checkHandler)
  }
  }
 
  return entry
  })()
 
  , registry = (function () {
  // our map stores arrays by event type, just because it's better than storing
  // everything in a single array. uses '$' as a prefix for the keys for safety
  var map = {}
 
  // generic functional search of our registry for matching listeners,
  // `fn` returns false to break out of the loop
  , forAll = function (element, type, original, handler, fn) {
  if (!type || type === '*') {
  // search the whole registry
  for (var t in map) {
  if (t.charAt(0) === '$')
  forAll(element, t.substr(1), original, handler, fn)
  }
  } else {
  var i = 0, l, list = map['$' + type], all = element === '*'
  if (!list)
  return
  for (l = list.length; i < l; i++) {
  if (all || list[i].matches(element, original, handler))
  if (!fn(list[i], list, i, type))
  return
  }
  }
  }
 
  , has = function (element, type, original) {
  // we're not using forAll here simply because it's a bit slower and this
  // needs to be fast
  var i, list = map['$' + type]
  if (list) {
  for (i = list.length; i--;) {
  if (list[i].matches(element, original, null))
  return true
  }
  }
  return false
  }
 
  , get = function (element, type, original) {
  var entries = []
  forAll(element, type, original, null, function (entry) {
  return entries.push(entry)
  })
  return entries
  }
 
  , put = function (entry) {
  (map['$' + entry.type] || (map['$' + entry.type] = [])).push(entry)
  return entry
  }
 
  , del = function (entry) {
  forAll(entry.element, entry.type, null, entry.handler, function (entry, list, i) {
  list.splice(i, 1)
  if (list.length === 0)
  delete map['$' + entry.type]
  return false
  })
  }
 
  // dump all entries, used for onunload
  , entries = function () {
  var t, entries = []
  for (t in map) {
  if (t.charAt(0) === '$')
  entries = entries.concat(map[t])
  }
  return entries
  }
 
  return { has: has, get: get, put: put, del: del, entries: entries }
  })()
 
  // add and remove listeners to DOM elements
  , listener = W3C_MODEL ? function (element, type, fn, add) {
  element[add ? addEvent : removeEvent](type, fn, false)
  } : function (element, type, fn, add, custom) {
  if (custom && add && element['_on' + custom] === null)
  element['_on' + custom] = 0
  element[add ? attachEvent : detachEvent]('on' + type, fn)
  }
 
  , nativeHandler = function (element, fn, args) {
  return function (event) {
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, true)
  return fn.apply(element, [event].concat(args))
  }
  }
 
  , customHandler = function (element, fn, type, condition, args, isNative) {
  return function (event) {
  if (condition ? condition.apply(this, arguments) : W3C_MODEL ? true : event && event.propertyName === '_on' + type || !event) {
  if (event)
  event = fixEvent(event || ((this.ownerDocument || this.document || this).parentWindow || win).event, isNative)
  fn.apply(element, event && (!args || args.length === 0) ? arguments : slice.call(arguments, event ? 0 : 1).concat(args))
  }
  }
  }
 
  , once = function (rm, element, type, fn, originalFn) {
  // wrap the handler in a handler that does a remove as well
  return function () {
  rm(element, type, originalFn)
  fn.apply(this, arguments)
  }
  }
 
  , removeListener = function (element, orgType, handler, namespaces) {
  var i, l, entry
  , type = (orgType && orgType.replace(nameRegex, ''))
  , handlers = registry.get(element, type, handler)
 
  for (i = 0, l = handlers.length; i < l; i++) {
  if (handlers[i].inNamespaces(namespaces)) {
  if ((entry = handlers[i]).eventSupport)
  listener(entry.target, entry.eventType, entry.handler, false, entry.type)
  // TODO: this is problematic, we have a registry.get() and registry.del() that
  // both do registry searches so we waste cycles doing this. Needs to be rolled into
  // a single registry.forAll(fn) that removes while finding, but the catch is that
  // we'll be splicing the arrays that we're iterating over. Needs extra tests to
  // make sure we don't screw it up. @rvagg
  registry.del(entry)
  }
  }
  }
 
  , addListener = function (element, orgType, fn, originalFn, args) {
  var entry
  , type = orgType.replace(nameRegex, '')
  , namespaces = orgType.replace(namespaceRegex, '').split('.')
 
  if (registry.has(element, type, fn))
  return element // no dupe
  if (type === 'unload')
  fn = once(removeListener, element, type, fn, originalFn) // self clean-up
  if (customEvents[type]) {
  if (customEvents[type].condition)
  fn = customHandler(element, fn, type, customEvents[type].condition, true)
  type = customEvents[type].base || type
  }
  entry = registry.put(new RegEntry(element, type, fn, originalFn, namespaces[0] && namespaces))
  entry.handler = entry.isNative ?
  nativeHandler(element, entry.handler, args) :
  customHandler(element, entry.handler, type, false, args, false)
  if (entry.eventSupport)
  listener(entry.target, entry.eventType, entry.handler, true, entry.customType)
  }
 
  , del = function (selector, fn, $) {
  return function (e) {
  var target, i, array = typeof selector === 'string' ? $(selector, this) : selector
  for (target = e.target; target && target !== this; target = target.parentNode) {
  for (i = array.length; i--;) {
  if (array[i] === target) {
  return fn.apply(target, arguments)
  }
  }
  }
  }
  }
 
  , remove = function (element, typeSpec, fn) {
  var k, m, type, namespaces, i
  , rm = removeListener
  , isString = typeSpec && typeof typeSpec === 'string'
 
  if (isString && typeSpec.indexOf(' ') > 0) {
  // remove(el, 't1 t2 t3', fn) or remove(el, 't1 t2 t3')
  typeSpec = typeSpec.split(' ')
  for (i = typeSpec.length; i--;)
  remove(element, typeSpec[i], fn)
  return element
  }
  type = isString && typeSpec.replace(nameRegex, '')
  if (type && customEvents[type])
  type = customEvents[type].type
  if (!typeSpec || isString) {
  // remove(el) or remove(el, t1.ns) or remove(el, .ns) or remove(el, .ns1.ns2.ns3)
  if (namespaces = isString && typeSpec.replace(namespaceRegex, ''))
  namespaces = namespaces.split('.')
  rm(element, type, fn, namespaces)
  } else if (typeof typeSpec === 'function') {
  // remove(el, fn)
  rm(element, null, typeSpec)
  } else {
  // remove(el, { t1: fn1, t2, fn2 })
  for (k in typeSpec) {
  if (typeSpec.hasOwnProperty(k))
  remove(element, k, typeSpec[k])
  }
  }
  return element
  }
 
  , add = function (element, events, fn, delfn, $) {
  var type, types, i, args
  , originalFn = fn
  , isDel = fn && typeof fn === 'string'
 
  if (events && !fn && typeof events === 'object') {
  for (type in events) {
  if (events.hasOwnProperty(type))
  add.apply(this, [ element, type, events[type] ])
  }
  } else {
  args = arguments.length > 3 ? slice.call(arguments, 3) : []
  types = (isDel ? fn : events).split(' ')
  isDel && (fn = del(events, (originalFn = delfn), $)) && (args = slice.call(args, 1))
  // special case for one()
  this === ONE && (fn = once(remove, element, events, fn, originalFn))
  for (i = types.length; i--;) addListener(element, types[i], fn, originalFn, args)
  }
  return element
  }
 
  , one = function () {
  return add.apply(ONE, arguments)
  }
 
  , fireListener = W3C_MODEL ? function (isNative, type, element) {
  var evt = doc.createEvent(isNative ? 'HTMLEvents' : 'UIEvents')
  evt[isNative ? 'initEvent' : 'initUIEvent'](type, true, true, win, 1)
  element.dispatchEvent(evt)
  } : function (isNative, type, element) {
  element = targetElement(element, isNative)
  // if not-native then we're using onpropertychange so we just increment a custom property
  isNative ? element.fireEvent('on' + type, doc.createEventObject()) : element['_on' + type]++
  }
 
  , fire = function (element, type, args) {
  var i, j, l, names, handlers
  , types = type.split(' ')
 
  for (i = types.length; i--;) {
  type = types[i].replace(nameRegex, '')
  if (names = types[i].replace(namespaceRegex, ''))
  names = names.split('.')
  if (!names && !args && element[eventSupport]) {
  fireListener(nativeEvents[type], type, element)
  } else {
  // non-native event, either because of a namespace, arguments or a non DOM element
  // iterate over all listeners and manually 'fire'
  handlers = registry.get(element, type)
  args = [false].concat(args)
  for (j = 0, l = handlers.length; j < l; j++) {
  if (handlers[j].inNamespaces(names))
  handlers[j].handler.apply(element, args)
  }
  }
  }
  return element
  }
 
  , clone = function (element, from, type) {
  var i = 0
  , handlers = registry.get(from, type)
  , l = handlers.length
 
  for (; i < l; i++)
  handlers[i].original && add(element, handlers[i].type, handlers[i].original)
  return element
  }
 
  , bean = {
  add: add, one: one, remove: remove, clone: clone, fire: fire, noConflict: function () {
  context[name] = old
  return this
  }
  }
 
  if (win[attachEvent]) {
  // for IE, clean up on unload to avoid leaks
  var cleanup = function () {
  var i, entries = registry.entries()
  for (i in entries) {
  if (entries[i].type && entries[i].type !== 'unload')
  remove(entries[i].element, entries[i].type)
  }
  win[detachEvent]('onunload', cleanup)
  win.CollectGarbage && win.CollectGarbage()
  }
  win[attachEvent]('onunload', cleanup)
  }
 
  return bean
  });
  // Underscore.js 1.1.7
  // (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
  // Underscore is freely distributable under the MIT license.
  // Portions of Underscore are inspired or borrowed from Prototype,
  // Oliver Steele's Functional, and John Resig's Micro-Templating.
  // For all details and documentation:
  // http://documentcloud.github.com/underscore
 
  (function () {
 
  // Baseline setup
  // --------------
 
  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;
 
  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;
 
  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};
 
  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
 
  // Create quick reference variables for speed access to core prototypes.
  var slice = ArrayProto.slice,
  unshift = ArrayProto.unshift,
  toString = ObjProto.toString,
  hasOwnProperty = ObjProto.hasOwnProperty;
 
  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
  nativeForEach = ArrayProto.forEach,
  nativeMap = ArrayProto.map,
  nativeReduce = ArrayProto.reduce,
  nativeReduceRight = ArrayProto.reduceRight,
  nativeFilter = ArrayProto.filter,
  nativeEvery = ArrayProto.every,
  nativeSome = ArrayProto.some,
  nativeIndexOf = ArrayProto.indexOf,
  nativeLastIndexOf = ArrayProto.lastIndexOf,
  nativeIsArray = Array.isArray,
  nativeKeys = Object.keys,
  nativeBind = FuncProto.bind;
 
  // Create a safe reference to the Underscore object for use below.
  var _ = function (obj) {
  return new wrapper(obj);
  };
 
  // Export the Underscore object for **CommonJS**, with backwards-compatibility
  // for the old `require()` API. If we're not in CommonJS, add `_` to the
  // global object.
  if (typeof module !== 'undefined' && module.exports) {
  module.exports = _;
  _._ = _;
  } else {
  // Exported as a string, for Closure Compiler "advanced" mode.
  root['_'] = _;
  }
 
  // Current version.
  _.VERSION = '1.1.7';
 
  // Collection Functions
  // --------------------
 
  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function (obj, iterator, context) {
  if (obj == null) return;
  if (nativeForEach && obj.forEach === nativeForEach) {
  obj.forEach(iterator, context);
  } else if (obj.length === +obj.length) {
  for (var i = 0, l = obj.length; i < l; i++) {
  if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
  }
  } else {
  for (var key in obj) {
  if (hasOwnProperty.call(obj, key)) {
  if (iterator.call(context, obj[key], key, obj) === breaker) return;
  }
  }
  }
  };
 
  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = function (obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  each(obj, function (value, index, list) {
  results[results.length] = iterator.call(context, value, index, list);
  });
  return results;
  };
 
  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function (obj, iterator, memo, context) {
  var initial = memo !== void 0;
  if (obj == null) obj = [];
  if (nativeReduce && obj.reduce === nativeReduce) {
  if (context) iterator = _.bind(iterator, context);
  return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  }
  each(obj, function (value, index, list) {
  if (!initial) {
  memo = value;
  initial = true;
  } else {
  memo = iterator.call(context, memo, value, index, list);
  }
  });
  if (!initial) throw new TypeError("Reduce of empty array with no initial value");
  return memo;
  };
 
  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function (obj, iterator, memo, context) {
  if (obj == null) obj = [];
  if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  if (context) iterator = _.bind(iterator, context);
  return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  }
  var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
  return _.reduce(reversed, iterator, memo, context);
  };
 
  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function (obj, iterator, context) {
  var result;
  any(obj, function (value, index, list) {
  if (iterator.call(context, value, index, list)) {
  result = value;
  return true;
  }
  });
  return result;
  };
 
  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function (obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  each(obj, function (value, index, list) {
  if (iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Return all the elements for which a truth test fails.
  _.reject = function (obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  each(obj, function (value, index, list) {
  if (!iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
  };
 
  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function (obj, iterator, context) {
  var result = true;
  if (obj == null) return result;
  if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  each(obj, function (value, index, list) {
  if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  });
  return result;
  };
 
  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function (obj, iterator, context) {
  iterator = iterator || _.identity;
  var result = false;
  if (obj == null) return result;
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  each(obj, function (value, index, list) {
  if (result |= iterator.call(context, value, index, list)) return breaker;
  });
  return !!result;
  };
 
  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function (obj, target) {
  var found = false;
  if (obj == null) return found;
  if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  any(obj, function (value) {
  if (found = value === target) return true;
  });
  return found;
  };
 
  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function (obj, method) {
  var args = slice.call(arguments, 2);
  return _.map(obj, function (value) {
  return (method.call ? method || value : value[method]).apply(value, args);
  });
  };
 
  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function (obj, key) {
  return _.map(obj, function (value) {
  return value[key];
  });
  };
 
  // Return the maximum element or (element-based computation).
  _.max = function (obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  var result = {computed: -Infinity};
  each(obj, function (value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed >= result.computed && (result = {value: value, computed: computed});
  });
  return result.value;
  };
 
  // Return the minimum element (or element-based computation).
  _.min = function (obj, iterator, context) {
  if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  var result = {computed: Infinity};
  each(obj, function (value, index, list) {
  var computed = iterator ? iterator.call(context, value, index, list) : value;
  computed < result.computed && (result = {value: value, computed: computed});
  });
  return result.value;
  };
 
  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function (obj, iterator, context) {
  return _.pluck(_.map(obj,function (value, index, list) {
  return {
  value: value,
  criteria: iterator.call(context, value, index, list)
  };
  }).sort(function (left, right) {
  var a = left.criteria, b = right.criteria;
  return a < b ? -1 : a > b ? 1 : 0;
  }), 'value');
  };
 
  // Groups the object's values by a criterion produced by an iterator
  _.groupBy = function (obj, iterator) {
  var result = {};
  each(obj, function (value, index) {
  var key = iterator(value, index);
  (result[key] || (result[key] = [])).push(value);
  });
  return result;
  };
 
  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function (array, obj, iterator) {
  iterator || (iterator = _.identity);
  var low = 0, high = array.length;
  while (low < high) {
  var mid = (low + high) >> 1;
  iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  }
  return low;
  };
 
  // Safely convert anything iterable into a real, live array.
  _.toArray = function (iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  if (_.isArray(iterable)) return slice.call(iterable);
  if (_.isArguments(iterable)) return slice.call(iterable);
  return _.values(iterable);
  };
 
  // Return the number of elements in an object.
  _.size = function (obj) {
  return _.toArray(obj).length;
  };
 
  // Array Functions
  // ---------------
 
  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head`. The **guard** check allows it to work
  // with `_.map`.
  _.first = _.head = function (array, n, guard) {
  return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };
 
  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function (array, index, guard) {
  return slice.call(array, (index == null) || guard ? 1 : index);
  };
 
  // Get the last element of an array.
  _.last = function (array) {
  return array[array.length - 1];
  };
 
  // Trim out all falsy values from an array.
  _.compact = function (array) {
  return _.filter(array, function (value) {
  return !!value;
  });
  };
 
  // Return a completely flattened version of an array.
  _.flatten = function (array) {
  return _.reduce(array, function (memo, value) {
  if (_.isArray(value)) return memo.concat(_.flatten(value));
  memo[memo.length] = value;
  return memo;
  }, []);
  };
 
  // Return a version of the array that does not contain the specified value(s).
  _.without = function (array) {
  return _.difference(array, slice.call(arguments, 1));
  };
 
  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function (array, isSorted) {
  return _.reduce(array, function (memo, el, i) {
  if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
  return memo;
  }, []);
  };
 
  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function () {
  return _.uniq(_.flatten(arguments));
  };
 
  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function (array) {
  var rest = slice.call(arguments, 1);
  return _.filter(_.uniq(array), function (item) {
  return _.every(rest, function (other) {
  return _.indexOf(other, item) >= 0;
  });
  });
  };
 
  // Take the difference between one array and another.
  // Only the elements present in just the first array will remain.
  _.difference = function (array, other) {
  return _.filter(array, function (value) {
  return !_.include(other, value);
  });
  };
 
  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function () {
  var args = slice.call(arguments);
  var length = _.max(_.pluck(args, 'length'));
  var results = new Array(length);
  for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  return results;
  };
 
  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function (array, item, isSorted) {
  if (array == null) return -1;
  var i, l;
  if (isSorted) {
  i = _.sortedIndex(array, item);
  return array[i] === item ? i : -1;
  }
  if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
  for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
  return -1;
  };
 
 
  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function (array, item) {
  if (array == null) return -1;
  if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
  var i = array.length;
  while (i--) if (array[i] === item) return i;
  return -1;
  };
 
  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function (start, stop, step) {
  if (arguments.length <= 1) {
  stop = start || 0;
  start = 0;
  }
  step = arguments[2] || 1;
 
  var len = Math.max(Math.ceil((stop - start) / step), 0);
  var idx = 0;
  var range = new Array(len);
 
  while (idx < len) {
  range[idx++] = start;
  start += step;
  }
 
  return range;
  };
 
  // Function (ahem) Functions
  // ------------------
 
  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function (func, obj) {
  if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  var args = slice.call(arguments, 2);
  return function () {
  return func.apply(obj, args.concat(slice.call(arguments)));
  };
  };
 
  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function (obj) {
  var funcs = slice.call(arguments, 1);
  if (funcs.length == 0) funcs = _.functions(obj);
  each(funcs, function (f) {
  obj[f] = _.bind(obj[f], obj);
  });
  return obj;
  };
 
  // Memoize an expensive function by storing its results.
  _.memoize = function (func, hasher) {
  var memo = {};
  hasher || (hasher = _.identity);
  return function () {
  var key = hasher.apply(this, arguments);
  return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  };
  };
 
  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function (func, wait) {
  var args = slice.call(arguments, 2);
  return setTimeout(function () {
  return func.apply(func, args);
  }, wait);
  };
 
  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function (func) {
  return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };
 
  // Internal function used to implement `_.throttle` and `_.debounce`.
  var limit = function (func, wait, debounce) {
  var timeout;
  return function () {
  var context = this, args = arguments;
  var throttler = function () {
  timeout = null;
  func.apply(context, args);
  };
  if (debounce) clearTimeout(timeout);
  if (debounce || !timeout) timeout = setTimeout(throttler, wait);
  };
  };
 
  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function (func, wait) {
  return limit(func, wait, false);
  };
 
  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds.
  _.debounce = function (func, wait) {
  return limit(func, wait, true);
  };
 
  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function (func) {
  var ran = false, memo;
  return function () {
  if (ran) return memo;
  ran = true;
  return memo = func.apply(this, arguments);
  };
  };
 
  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function (func, wrapper) {
  return function () {
  var args = [func].concat(slice.call(arguments));
  return wrapper.apply(this, args);
  };
  };
 
  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function () {
  var funcs = slice.call(arguments);
  return function () {
  var args = slice.call(arguments);
  for (var i = funcs.length - 1; i >= 0; i--) {
  args = [funcs[i].apply(this, args)];
  }
  return args[0];
  };
  };
 
  // Returns a function that will only be executed after being called N times.
  _.after = function (times, func) {
  return function () {
  if (--times < 1) {
  return func.apply(this, arguments);
  }
  };
  };
 
 
  // Object Functions
  // ----------------
 
  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function (obj) {
  if (obj !== Object(obj)) throw new TypeError('Invalid object');
  var keys = [];
  for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
  return keys;
  };
 
  // Retrieve the values of an object's properties.
  _.values = function (obj) {
  return _.map(obj, _.identity);
  };
 
  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function (obj) {
  var names = [];
  for (var key in obj) {
  if (_.isFunction(obj[key])) names.push(key);
  }
  return names.sort();
  };
 
  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function (obj) {
  each(slice.call(arguments, 1), function (source) {
  for (var prop in source) {
  if (source[prop] !== void 0) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Fill in a given object with default properties.
  _.defaults = function (obj) {
  each(slice.call(arguments, 1), function (source) {
  for (var prop in source) {
  if (obj[prop] == null) obj[prop] = source[prop];
  }
  });
  return obj;
  };
 
  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function (obj) {
  return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };
 
  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function (obj, interceptor) {
  interceptor(obj);
  return obj;
  };
 
  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function (a, b) {
  // Check object identity.
  if (a === b) return true;
  // Different types?
  var atype = typeof(a), btype = typeof(b);
  if (atype != btype) return false;
  // Basic equality test (watch out for coercions).
  if (a == b) return true;
  // One is falsy and the other truthy.
  if ((!a && b) || (a && !b)) return false;
  // Unwrap any wrapped objects.
  if (a._chain) a = a._wrapped;
  if (b._chain) b = b._wrapped;
  // One of them implements an isEqual()?
  if (a.isEqual) return a.isEqual(b);
  if (b.isEqual) return b.isEqual(a);
  // Check dates' integer values.
  if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
  // Both are NaN?
  if (_.isNaN(a) && _.isNaN(b)) return false;
  // Compare regular expressions.
  if (_.isRegExp(a) && _.isRegExp(b))
  return a.source === b.source &&
  a.global === b.global &&
  a.ignoreCase === b.ignoreCase &&
  a.multiline === b.multiline;
  // If a is not an object by this point, we can't handle it.
  if (atype !== 'object') return false;
  // Check for different array lengths before comparing contents.
  if (a.length && (a.length !== b.length)) return false;
  // Nothing else worked, deep compare the contents.
  var aKeys = _.keys(a), bKeys = _.keys(b);
  // Different object sizes?
  if (aKeys.length != bKeys.length) return false;
  // Recursive comparison of contents.
  for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
  return true;
  };
 
  // Is a given array or object empty?
  _.isEmpty = function (obj) {
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
  return true;
  };
 
  // Is a given value a DOM element?
  _.isElement = function (obj) {
  return !!(obj && obj.nodeType == 1);
  };
 
  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function (obj) {
  return toString.call(obj) === '[object Array]';
  };
 
  // Is a given variable an object?
  _.isObject = function (obj) {
  return obj === Object(obj);
  };
 
  // Is a given variable an arguments object?
  _.isArguments = function (obj) {
  return !!(obj && hasOwnProperty.call(obj, 'callee'));
  };
 
  // Is a given value a function?
  _.isFunction = function (obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
  };
 
  // Is a given value a string?
  _.isString = function (obj) {
  return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
  };
 
  // Is a given value a number?
  _.isNumber = function (obj) {
  return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
  };
 
  // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
  // that does not equal itself.
  _.isNaN = function (obj) {
  return obj !== obj;
  };
 
  // Is a given value a boolean?
  _.isBoolean = function (obj) {
  return obj === true || obj === false;
  };
 
  // Is a given value a date?
  _.isDate = function (obj) {
  return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
  };
 
  // Is the given value a regular expression?
  _.isRegExp = function (obj) {
  return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  };
 
  // Is a given value equal to null?
  _.isNull = function (obj) {
  return obj === null;
  };
 
  // Is a given variable undefined?
  _.isUndefined = function (obj) {
  return obj === void 0;
  };
 
  // Utility Functions
  // -----------------
 
  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function () {
  root._ = previousUnderscore;
  return this;
  };
 
  // Keep the identity function around for default iterators.
  _.identity = function (value) {
  return value;
  };
 
  // Run a function **n** times.
  _.times = function (n, iterator, context) {
  for (var i = 0; i < n; i++) iterator.call(context, i);
  };
 
  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function (obj) {
  each(_.functions(obj), function (name) {
  addToWrapper(name, _[name] = obj[name]);
  });
  };
 
  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function (prefix) {
  var id = idCounter++;
  return prefix ? prefix + id : id;
  };
 
  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: /<%=([\s\S]+?)%>/g
  };
 
  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function (str, data) {
  var c = _.templateSettings;
  var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
  'with(obj||{}){__p.push(\'' +
  str.replace(/\\/g, '\\\\')
  .replace(/'/g, "\\'")
  .replace(c.interpolate, function (match, code) {
  return "'," + code.replace(/\\'/g, "'") + ",'";
  })
  .replace(c.evaluate || null, function (match, code) {
  return "');" + code.replace(/\\'/g, "'")
  .replace(/[\r\n\t]/g, ' ') + "__p.push('";
  })
  .replace(/\r/g, '\\r')
  .replace(/\n/g, '\\n')
  .replace(/\t/g, '\\t')
  + "');}return __p.join('');";
  var func = new Function('obj', tmpl);
  return data ? func(data) : func;
  };
 
  // The OOP Wrapper
  // ---------------
 
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function (obj) {
  this._wrapped = obj;
  };
 
  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;
 
  // Helper function to continue chaining intermediate results.
  var result = function (obj, chain) {
  return chain ? _(obj).chain() : obj;
  };
 
  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function (name, func) {
  wrapper.prototype[name] = function () {
  var args = slice.call(arguments);
  unshift.call(args, this._wrapped);
  return result(func.apply(_, args), this._chain);
  };
  };
 
  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);
 
  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function (name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function () {
  method.apply(this._wrapped, arguments);
  return result(this._wrapped, this._chain);
  };
  });
 
  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function (name) {
  var method = ArrayProto[name];
  wrapper.prototype[name] = function () {
  return result(method.apply(this._wrapped, arguments), this._chain);
  };
  });
 
  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function () {
  this._chain = true;
  return this;
  };
 
  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function () {
  return this._wrapped;
  };
 
  })();
  /**
  * Flotr2 (c) 2012 Carl Sutherland
  * MIT License
  * Special thanks to:
  * Flotr: http://code.google.com/p/flotr/ (fork)
  * Flot: https://github.com/flot/flot (original fork)
  */
  (function () {
 
  var
  global = this,
  previousFlotr = this.Flotr,
  Flotr;
 
  Flotr = {
  _: _,
  bean: bean,
  isIphone: /iphone/i.test(navigator.userAgent),
  isIE: (navigator.appVersion.indexOf("MSIE") != -1 ? parseFloat(navigator.appVersion.split("MSIE")[1]) : false),
 
  /**
  * An object of the registered graph types. Use Flotr.addType(type, object)
  * to add your own type.
  */
  graphTypes: {},
 
  /**
  * The list of the registered plugins
  */
  plugins: {},
 
  /**
  * Can be used to add your own chart type.
  * @param {String} name - Type of chart, like 'pies', 'bars' etc.
  * @param {String} graphType - The object containing the basic drawing functions (draw, etc)
  */
  addType: function (name, graphType) {
  Flotr.graphTypes[name] = graphType;
  Flotr.defaultOptions[name] = graphType.options || {};
  Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
  },
 
  /**
  * Can be used to add a plugin
  * @param {String} name - The name of the plugin
  * @param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
  */
  addPlugin: function (name, plugin) {
  Flotr.plugins[name] = plugin;
  Flotr.defaultOptions[name] = plugin.options || {};
  },
 
  /**
  * Draws the graph. This function is here for backwards compatibility with Flotr version 0.1.0alpha.
  * You could also draw graphs by directly calling Flotr.Graph(element, data, options).
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  * @param {Class} _GraphKlass_ - (optional) Class to pass the arguments to, defaults to Flotr.Graph
  * @return {Object} returns a new graph object and of course draws the graph.
  */
  draw: function (el, data, options, GraphKlass) {
  GraphKlass = GraphKlass || Flotr.Graph;
  return new GraphKlass(el, data, options);
  },
 
  /**
  * Recursively merges two objects.
  * @param {Object} src - source object (likely the object with the least properties)
  * @param {Object} dest - destination object (optional, object with the most properties)
  * @return {Object} recursively merged Object
  * @TODO See if we can't remove this.
  */
  merge: function (src, dest) {
  var i, v, result = dest || {};
 
  for (i in src) {
  v = src[i];
  if (v && typeof(v) === 'object') {
  if (v.constructor === Array) {
  result[i] = this._.clone(v);
  } else if (v.constructor !== RegExp && !this._.isElement(v)) {
  result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
  } else {
  result[i] = v;
  }
  } else {
  result[i] = v;
  }
  }
 
  return result;
  },
 
  /**
  * Recursively clones an object.
  * @param {Object} object - The object to clone
  * @return {Object} the clone
  * @TODO See if we can't remove this.
  */
  clone: function (object) {
  return Flotr.merge(object, {});
  },
 
  /**
  * Function calculates the ticksize and returns it.
  * @param {Integer} noTicks - number of ticks
  * @param {Integer} min - lower bound integer value for the current axis
  * @param {Integer} max - upper bound integer value for the current axis
  * @param {Integer} decimals - number of decimals for the ticks
  * @return {Integer} returns the ticksize in pixels
  */
  getTickSize: function (noTicks, min, max, decimals) {
  var delta = (max - min) / noTicks,
  magn = Flotr.getMagnitude(delta),
  tickSize = 10,
  norm = delta / magn; // Norm is between 1.0 and 10.0.
 
  if (norm < 1.5) tickSize = 1;
  else if (norm < 2.25) tickSize = 2;
  else if (norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
  else if (norm < 7.5) tickSize = 5;
 
  return tickSize * magn;
  },
 
  /**
  * Default tick formatter.
  * @param {String, Integer} val - tick value integer
  * @param {Object} axisOpts - the axis' options
  * @return {String} formatted tick string
  */
  defaultTickFormatter: function (val, axisOpts) {
  return val + '';
  },
 
  /**
  * Formats the mouse tracker values.
  * @param {Object} obj - Track value Object {x:..,y:..}
  * @return {String} Formatted track string
  */
  defaultTrackFormatter: function (obj) {
  return '(' + obj.x + ', ' + obj.y + ')';
  },
 
  /**
  * Utility function to convert file size values in bytes to kB, MB, ...
  * @param value {Number} - The value to convert
  * @param precision {Number} - The number of digits after the comma (default: 2)
  * @param base {Number} - The base (default: 1000)
  */
  engineeringNotation: function (value, precision, base) {
  var sizes = ['Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'k', ''],
  fractionSizes = ['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', ''],
  total = sizes.length;
 
  base = base || 1000;
  precision = Math.pow(10, precision || 2);
 
  if (value === 0) return 0;
 
  if (value > 1) {
  while (total-- && (value >= base)) value /= base;
  }
  else {
  sizes = fractionSizes;
  total = sizes.length;
  while (total-- && (value < 1)) value *= base;
  }
 
  return (Math.round(value * precision) / precision) + sizes[total];
  },
 
  /**
  * Returns the magnitude of the input value.
  * @param {Integer, Float} x - integer or float value
  * @return {Integer, Float} returns the magnitude of the input value
  */
  getMagnitude: function (x) {
  return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
  },
  toPixel: function (val) {
  return Math.floor(val) + 0.5;//((val-Math.round(val) < 0.4) ? (Math.floor(val)-0.5) : val);
  },
  toRad: function (angle) {
  return -angle * (Math.PI / 180);
  },
  floorInBase: function (n, base) {
  return base * Math.floor(n / base);
  },
  drawText: function (ctx, text, x, y, style) {
  if (!ctx.fillText) {
  ctx.drawText(text, x, y, style);
  return;
  }
 
  style = this._.extend({
  size: Flotr.defaultOptions.fontSize,
  color: '#000000',
  textAlign: 'left',
  textBaseline: 'bottom',
  weight: 1,
  angle: 0
  }, style);
 
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(style.angle);
  ctx.fillStyle = style.color;
  ctx.font = (style.weight > 1 ? "bold " : "") + (style.size * 1.3) + "px sans-serif";
  ctx.textAlign = style.textAlign;
  ctx.textBaseline = style.textBaseline;
  ctx.fillText(text, 0, 0);
  ctx.restore();
  },
  getBestTextAlign: function (angle, style) {
  style = style || {textAlign: 'center', textBaseline: 'middle'};
  angle += Flotr.getTextAngleFromAlign(style);
 
  if (Math.abs(Math.cos(angle)) > 10e-3)
  style.textAlign = (Math.cos(angle) > 0 ? 'right' : 'left');
 
  if (Math.abs(Math.sin(angle)) > 10e-3)
  style.textBaseline = (Math.sin(angle) > 0 ? 'top' : 'bottom');
 
  return style;
  },
  alignTable: {
  'right middle': 0,
  'right top': Math.PI / 4,
  'center top': Math.PI / 2,
  'left top': 3 * (Math.PI / 4),
  'left middle': Math.PI,
  'left bottom': -3 * (Math.PI / 4),
  'center bottom': -Math.PI / 2,
  'right bottom': -Math.PI / 4,
  'center middle': 0
  },
  getTextAngleFromAlign: function (style) {
  return Flotr.alignTable[style.textAlign + ' ' + style.textBaseline] || 0;
  },
  noConflict: function () {
  global.Flotr = previousFlotr;
  return this;
  }
  };
 
  global.Flotr = Flotr;
 
  })();
 
  /**
  * Flotr Defaults
  */
  Flotr.defaultOptions = {
  colors: ['#00A8F0', '#C0D800', '#CB4B4B', '#4DA74D', '#9440ED'], //=> The default colorscheme. When there are > 5 series, additional colors are generated.
  ieBackgroundColor: '#FFFFFF', // Background color for excanvas clipping
  title: null, // => The graph's title
  subtitle: null, // => The graph's subtitle
  shadowSize: 4, // => size of the 'fake' shadow
  defaultType: null, // => default series type
  HtmlText: true, // => wether to draw the text using HTML or on the canvas
  fontColor: '#545454', // => default font color
  fontSize: 7.5, // => canvas' text font size
  resolution: 1, // => resolution of the graph, to have printer-friendly graphs !
  parseFloat: true, // => whether to preprocess data for floats (ie. if input is string)
  xaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 0, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => color of the ticks
  mode: 'normal', // => can be 'time' or 'normal'
  timeFormat: null,
  timeMode: 'UTC', // => For UTC time ('local' for local time).
  timeUnit: 'millisecond',// => Unit for time (millisecond, second, minute, hour, day, month, year)
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  x2axis: {},
  yaxis: {
  ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
  showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
  showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
  labelsAngle: 0, // => labels' angle, in degrees
  title: null, // => axis title
  titleAngle: 90, // => axis title's angle, in degrees
  noTicks: 5, // => number of ticks for automagically generated ticks
  minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
  tickFormatter: Flotr.defaultTickFormatter, // => fn: number, Object -> string
  tickDecimals: null, // => no. of decimals, null means auto
  min: null, // => min. value to show, null means set automatically
  max: null, // => max. value to show, null means set automatically
  autoscale: false, // => Turns autoscaling on with true
  autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
  color: null, // => The color of the ticks
  scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
  base: Math.E,
  titleAlign: 'center',
  margin: true // => Turn off margins with false
  },
  y2axis: {
  titleAngle: 270
  },
  grid: {
  color: '#545454', // => primary color used for outline and labels
  backgroundColor: null, // => null for transparent, else color
  backgroundImage: null, // => background image. String or object with src, left and top
  watermarkAlpha: 0.4, // =>
  tickColor: '#DDDDDD', // => color used for the ticks
  labelMargin: 3, // => margin in pixels
  verticalLines: true, // => whether to show gridlines in vertical direction
  minorVerticalLines: null, // => whether to show gridlines for minor ticks in vertical dir.
  horizontalLines: true, // => whether to show gridlines in horizontal direction
  minorHorizontalLines: null, // => whether to show gridlines for minor ticks in horizontal dir.
  outlineWidth: 1, // => width of the grid outline/border in pixels
  outline: 'nsew', // => walls of the outline to display
  circular: false // => if set to true, the grid will be circular, must be used when radars are drawn
  },
  mouse: {
  track: false, // => true to track the mouse, no tracking otherwise
  trackAll: false,
  position: 'se', // => position of the value box (default south-east)
  relative: false, // => next to the mouse cursor
  trackFormatter: Flotr.defaultTrackFormatter, // => formats the values in the value box
  margin: 5, // => margin in pixels of the valuebox
  lineColor: '#FF3F19', // => line color of points that are drawn when mouse comes near a value of a series
  trackDecimals: 1, // => decimals for the track values
  sensibility: 2, // => the lower this number, the more precise you have to aim to show a value
  trackY: true, // => whether or not to track the mouse in the y axis
  radius: 3, // => radius of the track point
  fillColor: null, // => color to fill our select bar with only applies to bar and similar graphs (only bars for now)
  fillOpacity: 0.4 // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  }
  };
 
  /**
  * Flotr Color
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  // Constructor
  function Color(r, g, b, a) {
  this.rgba = ['r', 'g', 'b', 'a'];
  var x = 4;
  while (-1 < --x) {
  this[this.rgba[x]] = arguments[x] || ((x == 3) ? 1.0 : 0);
  }
  this.normalize();
  }
 
  // Constants
  var COLOR_NAMES = {
  aqua: [0, 255, 255], azure: [240, 255, 255], beige: [245, 245, 220], black: [0, 0, 0], blue: [0, 0, 255],
  brown: [165, 42, 42], cyan: [0, 255, 255], darkblue: [0, 0, 139], darkcyan: [0, 139, 139], darkgrey: [169, 169, 169],
  darkgreen: [0, 100, 0], darkkhaki: [189, 183, 107], darkmagenta: [139, 0, 139], darkolivegreen: [85, 107, 47],
  darkorange: [255, 140, 0], darkorchid: [153, 50, 204], darkred: [139, 0, 0], darksalmon: [233, 150, 122],
  darkviolet: [148, 0, 211], fuchsia: [255, 0, 255], gold: [255, 215, 0], green: [0, 128, 0], indigo: [75, 0, 130],
  khaki: [240, 230, 140], lightblue: [173, 216, 230], lightcyan: [224, 255, 255], lightgreen: [144, 238, 144],
  lightgrey: [211, 211, 211], lightpink: [255, 182, 193], lightyellow: [255, 255, 224], lime: [0, 255, 0], magenta: [255, 0, 255],
  maroon: [128, 0, 0], navy: [0, 0, 128], olive: [128, 128, 0], orange: [255, 165, 0], pink: [255, 192, 203], purple: [128, 0, 128],
  violet: [128, 0, 128], red: [255, 0, 0], silver: [192, 192, 192], white: [255, 255, 255], yellow: [255, 255, 0]
  };
 
  Color.prototype = {
  scale: function (rf, gf, bf, af) {
  var x = 4;
  while (-1 < --x) {
  if (!_.isUndefined(arguments[x])) this[this.rgba[x]] *= arguments[x];
  }
  return this.normalize();
  },
  alpha: function (alpha) {
  if (!_.isUndefined(alpha) && !_.isNull(alpha)) {
  this.a = alpha;
  }
  return this.normalize();
  },
  clone: function () {
  return new Color(this.r, this.b, this.g, this.a);
  },
  limit: function (val, minVal, maxVal) {
  return Math.max(Math.min(val, maxVal), minVal);
  },
  normalize: function () {
  var limit = this.limit;
  this.r = limit(parseInt(this.r, 10), 0, 255);
  this.g = limit(parseInt(this.g, 10), 0, 255);
  this.b = limit(parseInt(this.b, 10), 0, 255);
  this.a = limit(this.a, 0, 1);
  return this;
  },
  distance: function (color) {
  if (!color) return;
  color = new Color.parse(color);
  var dist = 0, x = 3;
  while (-1 < --x) {
  dist += Math.abs(this[this.rgba[x]] - color[this.rgba[x]]);
  }
  return dist;
  },
  toString: function () {
  return (this.a >= 1.0) ? 'rgb(' + [this.r, this.g, this.b].join(',') + ')' : 'rgba(' + [this.r, this.g, this.b, this.a].join(',') + ')';
  },
  contrast: function () {
  var
  test = 1 - ( 0.299 * this.r + 0.587 * this.g + 0.114 * this.b) / 255;
  return (test < 0.5 ? '#000000' : '#ffffff');
  }
  };
 
  _.extend(Color, {
  /**
  * Parses a color string and returns a corresponding Color.
  * The different tests are in order of probability to improve speed.
  * @param {String, Color} str - string thats representing a color
  * @return {Color} returns a Color object or false
  */
  parse: function (color) {
  if (color instanceof Color) return color;
 
  var result;
 
  // #a0b1c2
  if ((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)))
  return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16));
 
  // rgb(num,num,num)
  if ((result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10));
 
  // #fff
  if ((result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)))
  return new Color(parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16));
 
  // rgba(num,num,num,num)
  if ((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4]));
 
  // rgb(num%,num%,num%)
  if ((result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)))
  return new Color(parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55);
 
  // rgba(num%,num%,num%,num)
  if ((result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(color)))
  return new Color(parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55, parseFloat(result[4]));
 
  // Otherwise, we're most likely dealing with a named color.
  var name = (color + '').replace(/^\s*([\S\s]*?)\s*$/, '$1').toLowerCase();
  if (name == 'transparent') {
  return new Color(255, 255, 255, 0);
  }
  return (result = COLOR_NAMES[name]) ? new Color(result[0], result[1], result[2]) : new Color(0, 0, 0, 0);
  },
 
  /**
  * Process color and options into color style.
  */
  processColor: function (color, options) {
 
  var opacity = options.opacity;
  if (!color) return 'rgba(0, 0, 0, 0)';
  if (color instanceof Color) return color.alpha(opacity).toString();
  if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
 
  var grad = color.colors ? color : {colors: color};
 
  if (!options.ctx) {
  if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
  return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
  }
  grad = _.extend({start: 'top', end: 'bottom'}, grad);
 
  if (/top/i.test(grad.start)) options.x1 = 0;
  if (/left/i.test(grad.start)) options.y1 = 0;
  if (/bottom/i.test(grad.end)) options.x2 = 0;
  if (/right/i.test(grad.end)) options.y2 = 0;
 
  var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
  for (i = 0; i < grad.colors.length; i++) {
  c = grad.colors[i];
  if (_.isArray(c)) {
  stop = c[0];
  c = c[1];
  }
  else stop = i / (grad.colors.length - 1);
  gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
  }
  return gradient;
  }
  });
 
  Flotr.Color = Color;
 
  })();
 
  /**
  * Flotr Date
  */
  Flotr.Date = {
 
  set: function (date, name, mode, value) {
  mode = mode || 'UTC';
  name = 'set' + (mode === 'UTC' ? 'UTC' : '') + name;
  date[name](value);
  },
 
  get: function (date, name, mode) {
  mode = mode || 'UTC';
  name = 'get' + (mode === 'UTC' ? 'UTC' : '') + name;
  return date[name]();
  },
 
  format: function (d, format, mode) {
  if (!d) return;
 
  // We should maybe use an "official" date format spec, like PHP date() or ColdFusion
  // http://fr.php.net/manual/en/function.date.php
  // http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_c-d_29.html
  var
  get = this.get,
  tokens = {
  h: get(d, 'Hours', mode).toString(),
  H: leftPad(get(d, 'Hours', mode)),
  M: leftPad(get(d, 'Minutes', mode)),
  S: leftPad(get(d, 'Seconds', mode)),
  s: get(d, 'Milliseconds', mode),
  d: get(d, 'Date', mode).toString(),
  m: (get(d, 'Month') + 1).toString(),
  y: get(d, 'FullYear').toString(),
  b: Flotr.Date.monthNames[get(d, 'Month', mode)]
  };
 
  function leftPad(n) {
  n += '';
  return n.length == 1 ? "0" + n : n;
  }
 
  var r = [], c,
  escape = false;
 
  for (var i = 0; i < format.length; ++i) {
  c = format.charAt(i);
 
  if (escape) {
  r.push(tokens[c] || c);
  escape = false;
  }
  else if (c == "%")
  escape = true;
  else
  r.push(c);
  }
  return r.join('');
  },
  getFormat: function (time, span) {
  var tu = Flotr.Date.timeUnits;
  if (time < tu.second) return "%h:%M:%S.%s";
  else if (time < tu.minute) return "%h:%M:%S";
  else if (time < tu.day) return (span < 2 * tu.day) ? "%h:%M" : "%b %d %h:%M";
  else if (time < tu.month) return "%b %d";
  else if (time < tu.year) return (span < tu.year) ? "%b" : "%b %y";
  else return "%y";
  },
  formatter: function (v, axis) {
  var
  options = axis.options,
  scale = Flotr.Date.timeUnits[options.timeUnit],
  d = new Date(v * scale);
 
  // first check global format
  if (axis.options.timeFormat)
  return Flotr.Date.format(d, options.timeFormat, options.timeMode);
 
  var span = (axis.max - axis.min) * scale,
  t = axis.tickSize * Flotr.Date.timeUnits[axis.tickUnit];
 
  return Flotr.Date.format(d, Flotr.Date.getFormat(t, span), options.timeMode);
  },
  generator: function (axis) {
 
  var
  set = this.set,
  get = this.get,
  timeUnits = this.timeUnits,
  spec = this.spec,
  options = axis.options,
  mode = options.timeMode,
  scale = timeUnits[options.timeUnit],
  min = axis.min * scale,
  max = axis.max * scale,
  delta = (max - min) / options.noTicks,
  ticks = [],
  tickSize = axis.tickSize,
  tickUnit,
  formatter, i;
 
  // Use custom formatter or time tick formatter
  formatter = (options.tickFormatter === Flotr.defaultTickFormatter ?
  this.formatter : options.tickFormatter
  );
 
  for (i = 0; i < spec.length - 1; ++i) {
  var d = spec[i][0] * timeUnits[spec[i][1]];
  if (delta < (d + spec[i + 1][0] * timeUnits[spec[i + 1][1]]) / 2 && d >= tickSize)
  break;
  }
  tickSize = spec[i][0];
  tickUnit = spec[i][1];
 
  // special-case the possibility of several years
  if (tickUnit == "year") {
  tickSize = Flotr.getTickSize(options.noTicks * timeUnits.year, min, max, 0);
 
  // Fix for 0.5 year case
  if (tickSize == 0.5) {
  tickUnit = "month";
  tickSize = 6;
  }
  }
 
  axis.tickUnit = tickUnit;
  axis.tickSize = tickSize;
 
  var
  d = new Date(min);
 
  var step = tickSize * timeUnits[tickUnit];
 
  function setTick(name) {
  set(d, name, mode, Flotr.floorInBase(
  get(d, name, mode), tickSize
  ));
  }
 
  switch (tickUnit) {
  case "millisecond":
  setTick('Milliseconds');
  break;
  case "second":
  setTick('Seconds');
  break;
  case "minute":
  setTick('Minutes');
  break;
  case "hour":
  setTick('Hours');
  break;
  case "month":
  setTick('Month');
  break;
  case "year":
  setTick('FullYear');
  break;
  }
 
  // reset smaller components
  if (step >= timeUnits.second) set(d, 'Milliseconds', mode, 0);
  if (step >= timeUnits.minute) set(d, 'Seconds', mode, 0);
  if (step >= timeUnits.hour) set(d, 'Minutes', mode, 0);
  if (step >= timeUnits.day) set(d, 'Hours', mode, 0);
  if (step >= timeUnits.day * 4) set(d, 'Date', mode, 1);
  if (step >= timeUnits.year) set(d, 'Month', mode, 0);
 
  var carry = 0, v = NaN, prev;
  do {
  prev = v;
  v = d.getTime();
  ticks.push({ v: v / scale, label: formatter(v / scale, axis) });
  if (tickUnit == "month") {
  if (tickSize < 1) {
  /* a bit complicated - we'll divide the month up but we need to take care of fractions
  so we don't end up in the middle of a day */
  set(d, 'Date', mode, 1);
  var start = d.getTime();
  set(d, 'Month', mode, get(d, 'Month', mode) + 1)
  var end = d.getTime();
  d.setTime(v + carry * timeUnits.hour + (end - start) * tickSize);
  carry = get(d, 'Hours', mode)
  set(d, 'Hours', mode, 0);
  }
  else
  set(d, 'Month', mode, get(d, 'Month', mode) + tickSize);
  }
  else if (tickUnit == "year") {
  set(d, 'FullYear', mode, get(d, 'FullYear', mode) + tickSize);
  }
  else
  d.setTime(v + step);
 
  } while (v < max && v != prev);
 
  return ticks;
  },
  timeUnits: {
  millisecond: 1,
  second: 1000,
  minute: 1000 * 60,
  hour: 1000 * 60 * 60,
  day: 1000 * 60 * 60 * 24,
  month: 1000 * 60 * 60 * 24 * 30,
  year: 1000 * 60 * 60 * 24 * 365.2425
  },
  // the allowed tick sizes, after 1 year we use an integer algorithm
  spec: [
  [1, "millisecond"],
  [20, "millisecond"],
  [50, "millisecond"],
  [100, "millisecond"],
  [200, "millisecond"],
  [500, "millisecond"],
  [1, "second"],
  [2, "second"],
  [5, "second"],
  [10, "second"],
  [30, "second"],
  [1, "minute"],
  [2, "minute"],
  [5, "minute"],
  [10, "minute"],
  [30, "minute"],
  [1, "hour"],
  [2, "hour"],
  [4, "hour"],
  [8, "hour"],
  [12, "hour"],
  [1, "day"],
  [2, "day"],
  [3, "day"],
  [0.25, "month"],
  [0.5, "month"],
  [1, "month"],
  [2, "month"],
  [3, "month"],
  [6, "month"],
  [1, "year"]
  ],
  monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  };
 
  (function () {
 
  var _ = Flotr._;
 
  Flotr.DOM = {
  addClass: function (element, name) {
  var classList = (element.className ? element.className : '');
  if (_.include(classList.split(/\s+/g), name)) return;
  element.className = (classList ? classList + ' ' : '') + name;
  },
  /**
  * Create an element.
  */
  create: function (tag) {
  return document.createElement(tag);
  },
  node: function (html) {
  var div = Flotr.DOM.create('div'), n;
  div.innerHTML = html;
  n = div.children[0];
  div.innerHTML = '';
  return n;
  },
  /**
  * Remove all children.
  */
  empty: function (element) {
  element.innerHTML = '';
  /*
  if (!element) return;
  _.each(element.childNodes, function (e) {
  Flotr.DOM.empty(e);
  element.removeChild(e);
  });
  */
  },
  hide: function (element) {
  Flotr.DOM.setStyles(element, {display: 'none'});
  },
  /**
  * Insert a child.
  * @param {Element} element
  * @param {Element|String} Element or string to be appended.
  */
  insert: function (element, child) {
  if (_.isString(child))
  element.innerHTML += child;
  else if (_.isElement(child))
  element.appendChild(child);
  },
  // @TODO find xbrowser implementation
  opacity: function (element, opacity) {
  element.style.opacity = opacity;
  },
  position: function (element, p) {
  if (!element.offsetParent)
  return {left: (element.offsetLeft || 0), top: (element.offsetTop || 0)};
 
  p = this.position(element.offsetParent);
  p.left += element.offsetLeft;
  p.top += element.offsetTop;
  return p;
  },
  removeClass: function (element, name) {
  var classList = (element.className ? element.className : '');
  element.className = _.filter(classList.split(/\s+/g),function (c) {
  if (c != name) return true;
  }
  ).join(' ');
  },
  setStyles: function (element, o) {
  _.each(o, function (value, key) {
  element.style[key] = value;
  });
  },
  show: function (element) {
  Flotr.DOM.setStyles(element, {display: ''});
  },
  /**
  * Return element size.
  */
  size: function (element) {
  return {
  height: element.offsetHeight,
  width: element.offsetWidth };
  }
  };
 
  })();
 
  /**
  * Flotr Event Adapter
  */
  (function () {
  var
  F = Flotr,
  bean = F.bean;
  F.EventAdapter = {
  observe: function (object, name, callback) {
  bean.add(object, name, callback);
  return this;
  },
  fire: function (object, name, args) {
  bean.fire(object, name, args);
  if (typeof(Prototype) != 'undefined')
  Event.fire(object, name, args);
  // @TODO Someone who uses mootools, add mootools adapter for existing applciations.
  return this;
  },
  stopObserving: function (object, name, callback) {
  bean.remove(object, name, callback);
  return this;
  },
  eventPointer: function (e) {
  if (!F._.isUndefined(e.touches) && e.touches.length > 0) {
  return {
  x: e.touches[0].pageX,
  y: e.touches[0].pageY
  };
  } else if (!F._.isUndefined(e.changedTouches) && e.changedTouches.length > 0) {
  return {
  x: e.changedTouches[0].pageX,
  y: e.changedTouches[0].pageY
  };
  } else if (e.pageX || e.pageY) {
  return {
  x: e.pageX,
  y: e.pageY
  };
  } else if (e.clientX || e.clientY) {
  var
  d = document,
  b = d.body,
  de = d.documentElement;
  return {
  x: e.clientX + b.scrollLeft + de.scrollLeft,
  y: e.clientY + b.scrollTop + de.scrollTop
  };
  }
  }
  };
  })();
 
  /**
  * Text Utilities
  */
  (function () {
 
  var
  F = Flotr,
  D = F.DOM,
  _ = F._,
 
  Text = function (o) {
  this.o = o;
  };
 
  Text.prototype = {
 
  dimensions: function (text, canvasStyle, htmlStyle, className) {
 
  if (!text) return { width: 0, height: 0 };
 
  return (this.o.html) ?
  this.html(text, this.o.element, htmlStyle, className) :
  this.canvas(text, canvasStyle);
  },
 
  canvas: function (text, style) {
 
  if (!this.o.textEnabled) return;
  style = style || {};
 
  var
  metrics = this.measureText(text, style),
  width = metrics.width,
  height = style.size || F.defaultOptions.fontSize,
  angle = style.angle || 0,
  cosAngle = Math.cos(angle),
  sinAngle = Math.sin(angle),
  widthPadding = 2,
  heightPadding = 6,
  bounds;
 
  bounds = {
  width: Math.abs(cosAngle * width) + Math.abs(sinAngle * height) + widthPadding,
  height: Math.abs(sinAngle * width) + Math.abs(cosAngle * height) + heightPadding
  };
 
  return bounds;
  },
 
  html: function (text, element, style, className) {
 
  var div = D.create('div');
 
  D.setStyles(div, { 'position': 'absolute', 'top': '-10000px' });
  D.insert(div, '<div style="' + style + '" class="' + className + ' flotr-dummy-div">' + text + '</div>');
  D.insert(this.o.element, div);
 
  return D.size(div);
  },
 
  measureText: function (text, style) {
 
  var
  context = this.o.ctx,
  metrics;
 
  if (!context.fillText || (F.isIphone && context.measure)) {
  return { width: context.measure(text, style)};
  }
 
  style = _.extend({
  size: F.defaultOptions.fontSize,
  weight: 1,
  angle: 0
  }, style);
 
  context.save();
  context.font = (style.weight > 1 ? "bold " : "") + (style.size * 1.3) + "px sans-serif";
  metrics = context.measureText(text);
  context.restore();
 
  return metrics;
  }
  };
 
  Flotr.Text = Text;
 
  })();
 
  /**
  * Flotr Graph class that plots a graph on creation.
  */
  (function () {
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._,
  flotr = Flotr;
  /**
  * Flotr Graph constructor.
  * @param {Element} el - element to insert the graph into
  * @param {Object} data - an array or object of dataseries
  * @param {Object} options - an object containing options
  */
  Graph = function (el, data, options) {
  // Let's see if we can get away with out this [JS]
  // try {
  this._setEl(el);
  this._initMembers();
  this._initPlugins();
 
  E.fire(this.el, 'flotr:beforeinit', [this]);
 
  this.data = data;
  this.series = flotr.Series.getSeries(data);
  this._initOptions(options);
  this._initGraphTypes();
  this._initCanvas();
  this._text = new flotr.Text({
  element: this.el,
  ctx: this.ctx,
  html: this.options.HtmlText,
  textEnabled: this.textEnabled
  });
  E.fire(this.el, 'flotr:afterconstruct', [this]);
  this._initEvents();
 
  this.findDataRanges();
  this.calculateSpacing();
 
  this.draw(_.bind(function () {
  E.fire(this.el, 'flotr:afterinit', [this]);
  }, this));
  /*
  try {
  } catch (e) {
  try {
  console.error(e);
  } catch (e2) {}
  }*/
  };
 
  function observe(object, name, callback) {
  E.observe.apply(this, arguments);
  this._handles.push(arguments);
  return this;
  }
 
  Graph.prototype = {
 
  destroy: function () {
  E.fire(this.el, 'flotr:destroy');
  _.each(this._handles, function (handle) {
  E.stopObserving.apply(this, handle);
  });
  this._handles = [];
  this.el.graph = null;
  },
 
  observe: observe,
 
  /**
  * @deprecated
  */
  _observe: observe,
 
  processColor: function (color, options) {
  var o = { x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx };
  _.extend(o, options);
  return flotr.Color.processColor(color, o);
  },
  /**
  * Function determines the min and max values for the xaxis and yaxis.
  *
  * TODO logarithmic range validation (consideration of 0)
  */
  findDataRanges: function () {
  var a = this.axes,
  xaxis, yaxis, range;
 
  _.each(this.series, function (series) {
  range = series.getRange();
  if (range) {
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
  xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
  yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
  yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
  xaxis.used = (xaxis.used || range.xused);
  yaxis.used = (yaxis.used || range.yused);
  }
  }, this);
 
  // Check for empty data, no data case (none used)
  if (!a.x.used && !a.x2.used) a.x.used = true;
  if (!a.y.used && !a.y2.used) a.y.used = true;
 
  _.each(a, function (axis) {
  axis.calculateRange();
  });
 
  var
  types = _.keys(flotr.graphTypes),
  drawn = false;
 
  _.each(this.series, function (series) {
  if (series.hide) return;
  _.each(types, function (type) {
  if (series[type] && series[type].show) {
  this.extendRange(type, series);
  drawn = true;
  }
  }, this);
  if (!drawn) {
  this.extendRange(this.options.defaultType, series);
  }
  }, this);
  },
 
  extendRange: function (type, series) {
  if (this[type].extendRange) this[type].extendRange(series, series.data, series[type], this[type]);
  if (this[type].extendYRange) this[type].extendYRange(series.yaxis, series.data, series[type], this[type]);
  if (this[type].extendXRange) this[type].extendXRange(series.xaxis, series.data, series[type], this[type]);
  },
 
  /**
  * Calculates axis label sizes.
  */
  calculateSpacing: function () {
 
  var a = this.axes,
  options = this.options,
  series = this.series,
  margin = options.grid.labelMargin,
  T = this._text,
  x = a.x,
  x2 = a.x2,
  y = a.y,
  y2 = a.y2,
  maxOutset = options.grid.outlineWidth,
  i, j, l, dim;
 
  // TODO post refactor, fix this
  _.each(a, function (axis) {
  axis.calculateTicks();
  axis.calculateTextDimensions(T, options);
  });
 
  // Title height
  dim = T.dimensions(
  options.title,
  {size: options.fontSize * 1.5},
  'font-size:1em;font-weight:bold;',
  'flotr-title'
  );
  this.titleHeight = dim.height;
 
  // Subtitle height
  dim = T.dimensions(
  options.subtitle,
  {size: options.fontSize},
  'font-size:smaller;',
  'flotr-subtitle'
  );
  this.subtitleHeight = dim.height;
 
  for (j = 0; j < options.length; ++j) {
  if (series[j].points.show) {
  maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth / 2);
  }
  }
 
  var p = this.plotOffset;
  if (x.options.margin === false) {
  p.bottom = 0;
  p.top = 0;
  } else {
  p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ? (x.maxLabel.height + margin) : 0)) +
  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;
 
  p.top += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
  }
  if (y.options.margin === false) {
  p.left = 0;
  p.right = 0;
  } else {
  p.left += (options.grid.circular ? 0 : (y.used && y.options.showLabels ? (y.maxLabel.width + margin) : 0)) +
  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;
 
  p.right += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
  }
 
  p.top = Math.floor(p.top); // In order the outline not to be blured
 
  this.plotWidth = this.canvasWidth - p.left - p.right;
  this.plotHeight = this.canvasHeight - p.bottom - p.top;
 
  // TODO post refactor, fix this
  x.length = x2.length = this.plotWidth;
  y.length = y2.length = this.plotHeight;
  y.offset = y2.offset = this.plotHeight;
  x.setScale();
  x2.setScale();
  y.setScale();
  y2.setScale();
  },
  /**
  * Draws grid, labels, series and outline.
  */
  draw: function (after) {
 
  var
  context = this.ctx,
  i;
 
  E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
 
  if (this.series.length) {
 
  context.save();
  context.translate(this.plotOffset.left, this.plotOffset.top);
 
  for (i = 0; i < this.series.length; i++) {
  if (!this.series[i].hide) this.drawSeries(this.series[i]);
  }
 
  context.restore();
  this.clip();
  }
 
  E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
  if (after) after();
  },
  /**
  * Actually draws the graph.
  * @param {Object} series - series to draw
  */
  drawSeries: function (series) {
 
  function drawChart(series, typeKey) {
  var options = this.getOptions(series, typeKey);
  this[typeKey].draw(options);
  }
 
  var drawn = false;
  series = series || this.series;
 
  _.each(flotr.graphTypes, function (type, typeKey) {
  if (series[typeKey] && series[typeKey].show && this[typeKey]) {
  drawn = true;
  drawChart.call(this, series, typeKey);
  }
  }, this);
 
  if (!drawn) drawChart.call(this, series, this.options.defaultType);
  },
 
  getOptions: function (series, typeKey) {
  var
  type = series[typeKey],
  graphType = this[typeKey],
  options = {
  context: this.ctx,
  width: this.plotWidth,
  height: this.plotHeight,
  fontSize: this.options.fontSize,
  fontColor: this.options.fontColor,
  textEnabled: this.textEnabled,
  htmlText: this.options.HtmlText,
  text: this._text, // TODO Is this necessary?
  element: this.el,
  data: series.data,
  color: series.color,
  shadowSize: series.shadowSize,
  xScale: _.bind(series.xaxis.d2p, series.xaxis),
  yScale: _.bind(series.yaxis.d2p, series.yaxis)
  };
 
  options = flotr.merge(type, options);
 
  // Fill
  options.fillStyle = this.processColor(
  type.fillColor || series.color,
  {opacity: type.fillOpacity}
  );
 
  return options;
  },
  /**
  * Calculates the coordinates from a mouse event object.
  * @param {Event} event - Mouse Event object.
  * @return {Object} Object with coordinates of the mouse.
  */
  getEventPosition: function (e) {
 
  var
  d = document,
  b = d.body,
  de = d.documentElement,
  axes = this.axes,
  plotOffset = this.plotOffset,
  lastMousePos = this.lastMousePos,
  pointer = E.eventPointer(e),
  dx = pointer.x - lastMousePos.pageX,
  dy = pointer.y - lastMousePos.pageY,
  r, rx, ry;
 
  if ('ontouchstart' in this.el) {
  r = D.position(this.overlay);
  rx = pointer.x - r.left - plotOffset.left;
  ry = pointer.y - r.top - plotOffset.top;
  } else {
  r = this.overlay.getBoundingClientRect();
  rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
  ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
  }
 
  return {
  x: axes.x.p2d(rx),
  x2: axes.x2.p2d(rx),
  y: axes.y.p2d(ry),
  y2: axes.y2.p2d(ry),
  relX: rx,
  relY: ry,
  dX: dx,
  dY: dy,
  absX: pointer.x,
  absY: pointer.y,
  pageX: pointer.x,
  pageY: pointer.y
  };
  },
  /**
  * Observes the 'click' event and fires the 'flotr:click' event.
  * @param {Event} event - 'click' Event object.
  */
  clickHandler: function (event) {
  if (this.ignoreClick) {
  this.ignoreClick = false;
  return this.ignoreClick;
  }
  E.fire(this.el, 'flotr:click', [this.getEventPosition(event), this]);
  },
  /**
  * Observes mouse movement over the graph area. Fires the 'flotr:mousemove' event.
  * @param {Event} event - 'mousemove' Event object.
  */
  mouseMoveHandler: function (event) {
  if (this.mouseDownMoveHandler) return;
  var pos = this.getEventPosition(event);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  },
  /**
  * Observes the 'mousedown' event.
  * @param {Event} event - 'mousedown' Event object.
  */
  mouseDownHandler: function (event) {
 
  /*
  // @TODO Context menu?
  if(event.isRightClick()) {
  event.stop();
 
  var overlay = this.overlay;
  overlay.hide();
 
  function cancelContextMenu () {
  overlay.show();
  E.stopObserving(document, 'mousemove', cancelContextMenu);
  }
  E.observe(document, 'mousemove', cancelContextMenu);
  return;
  }
  */
 
  if (this.mouseUpHandler) return;
  this.mouseUpHandler = _.bind(function (e) {
  E.stopObserving(document, 'mouseup', this.mouseUpHandler);
  E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
  this.mouseDownMoveHandler = null;
  this.mouseUpHandler = null;
  // @TODO why?
  //e.stop();
  E.fire(this.el, 'flotr:mouseup', [e, this]);
  }, this);
  this.mouseDownMoveHandler = _.bind(function (e) {
  var pos = this.getEventPosition(e);
  E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
  this.lastMousePos = pos;
  }, this);
  E.observe(document, 'mouseup', this.mouseUpHandler);
  E.observe(document, 'mousemove', this.mouseDownMoveHandler);
  E.fire(this.el, 'flotr:mousedown', [event, this]);
  this.ignoreClick = false;
  },
  drawTooltip: function (content, x, y, options) {
  var mt = this.getMouseTrack(),
  style = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;',
  p = options.position,
  m = options.margin,
  plotOffset = this.plotOffset;
 
  if (x !== null && y !== null) {
  if (!options.relative) { // absolute to the canvas
  if (p.charAt(0) == 'n') style += 'top:' + (m + plotOffset.top) + 'px;bottom:auto;';
  else if (p.charAt(0) == 's') style += 'bottom:' + (m + plotOffset.bottom) + 'px;top:auto;';
  if (p.charAt(1) == 'e') style += 'right:' + (m + plotOffset.right) + 'px;left:auto;';
  else if (p.charAt(1) == 'w') style += 'left:' + (m + plotOffset.left) + 'px;right:auto;';
  }
  else { // relative to the mouse
  if (p.charAt(0) == 'n') style += 'bottom:' + (m - plotOffset.top - y + this.canvasHeight) + 'px;top:auto;';
  else if (p.charAt(0) == 's') style += 'top:' + (m + plotOffset.top + y) + 'px;bottom:auto;';
  if (p.charAt(1) == 'e') style += 'left:' + (m + plotOffset.left + x) + 'px;right:auto;';
  else if (p.charAt(1) == 'w') style += 'right:' + (m - plotOffset.left - x + this.canvasWidth) + 'px;left:auto;';
  }
 
  mt.style.cssText = style;
  D.empty(mt);
  D.insert(mt, content);
  D.show(mt);
  }
  else {
  D.hide(mt);
  }
  },
 
  clip: function (ctx) {
 
  var
  o = this.plotOffset,
  w = this.canvasWidth,
  h = this.canvasHeight;
 
  ctx = ctx || this.ctx;
 
  if (flotr.isIE && flotr.isIE < 9) {
  // Clipping for excanvas :-(
  ctx.save();
  ctx.fillStyle = this.processColor(this.options.ieBackgroundColor);
  ctx.fillRect(0, 0, w, o.top);
  ctx.fillRect(0, 0, o.left, h);
  ctx.fillRect(0, h - o.bottom, w, o.bottom);
  ctx.fillRect(w - o.right, 0, o.right, h);
  ctx.restore();
  } else {
  ctx.clearRect(0, 0, w, o.top);
  ctx.clearRect(0, 0, o.left, h);
  ctx.clearRect(0, h - o.bottom, w, o.bottom);
  ctx.clearRect(w - o.right, 0, o.right, h);
  }
  },
 
  _initMembers: function () {
  this._handles = [];
  this.lastMousePos = {pageX: null, pageY: null };
  this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
  this.ignoreClick = true;
  this.prevHit = null;
  },
 
  _initGraphTypes: function () {
  _.each(flotr.graphTypes, function (handler, graphType) {
  this[graphType] = flotr.clone(handler);
  }, this);
  },
 
  _initEvents: function () {
 
  var
  el = this.el,
  touchendHandler, movement, touchend;
 
  if ('ontouchstart' in el) {
 
  touchendHandler = _.bind(function (e) {
  touchend = true;
  E.stopObserving(document, 'touchend', touchendHandler);
  E.fire(el, 'flotr:mouseup', [event, this]);
  this.multitouches = null;
 
  if (!movement) {
  this.clickHandler(e);
  }
  }, this);
 
  this.observe(this.overlay, 'touchstart', _.bind(function (e) {
  movement = false;
  touchend = false;
  this.ignoreClick = false;
 
  if (e.touches && e.touches.length > 1) {
  this.multitouches = e.touches;
  }
 
  E.fire(el, 'flotr:mousedown', [event, this]);
  this.observe(document, 'touchend', touchendHandler);
  }, this));
 
  this.observe(this.overlay, 'touchmove', _.bind(function (e) {
 
  var pos = this.getEventPosition(e);
 
  e.preventDefault();
 
  movement = true;
 
  if (this.multitouches || (e.touches && e.touches.length > 1)) {
  this.multitouches = e.touches;
  } else {
  if (!touchend) {
  E.fire(el, 'flotr:mousemove', [event, pos, this]);
  }
  }
  this.lastMousePos = pos;
  }, this));
 
  } else {
  this.
  observe(this.overlay, 'mousedown', _.bind(this.mouseDownHandler, this)).
  observe(el, 'mousemove', _.bind(this.mouseMoveHandler, this)).
  observe(this.overlay, 'click', _.bind(this.clickHandler, this)).
  observe(el, 'mouseout', function () {
  E.fire(el, 'flotr:mouseout');
  });
  }
  },
 
  /**
  * Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
  * of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
  * are created, the elements are inserted into the container element.
  */
  _initCanvas: function () {
  var el = this.el,
  o = this.options,
  children = el.children,
  removedChildren = [],
  child, i,
  size, style;
 
  // Empty the el
  for (i = children.length; i--;) {
  child = children[i];
  if (!this.canvas && child.className === 'flotr-canvas') {
  this.canvas = child;
  } else if (!this.overlay && child.className === 'flotr-overlay') {
  this.overlay = child;
  } else {
  removedChildren.push(child);
  }
  }
  for (i = removedChildren.length; i--;) {
  el.removeChild(removedChildren[i]);
  }
 
  D.setStyles(el, {position: 'relative'}); // For positioning labels and overlay.
  size = {};
  size.width = el.clientWidth;
  size.height = el.clientHeight;
 
  if (size.width <= 0 || size.height <= 0 || o.resolution <= 0) {
  throw 'Invalid dimensions for plot, width = ' + size.width + ', height = ' + size.height + ', resolution = ' + o.resolution;
  }
 
  // Main canvas for drawing graph types
  this.canvas = getCanvas(this.canvas, 'canvas');
  // Overlay canvas for interactive features
  this.overlay = getCanvas(this.overlay, 'overlay');
  this.ctx = getContext(this.canvas);
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this.octx = getContext(this.overlay);
  this.octx.clearRect(0, 0, this.overlay.width, this.overlay.height);
  this.canvasHeight = size.height;
  this.canvasWidth = size.width;
  this.textEnabled = !!this.ctx.drawText || !!this.ctx.fillText; // Enable text functions
 
  function getCanvas(canvas, name) {
  if (!canvas) {
  canvas = D.create('canvas');
  if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
  FlashCanvas.initElement(canvas);
  }
  canvas.className = 'flotr-' + name;
  canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
  D.insert(el, canvas);
  }
  _.each(size, function (size, attribute) {
  D.show(canvas);
  if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
  return;
  }
  canvas.setAttribute(attribute, size * o.resolution);
  canvas.style[attribute] = size + 'px';
  });
  canvas.context_ = null; // Reset the ExCanvas context
  return canvas;
  }
 
  function getContext(canvas) {
  if (window.G_vmlCanvasManager) window.G_vmlCanvasManager.initElement(canvas); // For ExCanvas
  var context = canvas.getContext('2d');
  if (!window.G_vmlCanvasManager) context.scale(o.resolution, o.resolution);
  return context;
  }
  },
 
  _initPlugins: function () {
  // TODO Should be moved to flotr and mixed in.
  _.each(flotr.plugins, function (plugin, name) {
  _.each(plugin.callbacks, function (fn, c) {
  this.observe(this.el, c, _.bind(fn, this));
  }, this);
  this[name] = flotr.clone(plugin);
  _.each(this[name], function (fn, p) {
  if (_.isFunction(fn))
  this[name][p] = _.bind(fn, this);
  }, this);
  }, this);
  },
 
  /**
  * Sets options and initializes some variables and color specific values, used by the constructor.
  * @param {Object} opts - options object
  */
  _initOptions: function (opts) {
  var options = flotr.clone(flotr.defaultOptions);
  options.x2axis = _.extend(_.clone(options.xaxis), options.x2axis);
  options.y2axis = _.extend(_.clone(options.yaxis), options.y2axis);
  this.options = flotr.merge(opts || {}, options);
 
  if (this.options.grid.minorVerticalLines === null &&
  this.options.xaxis.scaling === 'logarithmic') {
  this.options.grid.minorVerticalLines = true;
  }
  if (this.options.grid.minorHorizontalLines === null &&
  this.options.yaxis.scaling === 'logarithmic') {
  this.options.grid.minorHorizontalLines = true;
  }
 
  E.fire(this.el, 'flotr:afterinitoptions', [this]);
 
  this.axes = flotr.Axis.getAxes(this.options);
 
  // Initialize some variables used throughout this function.
  var assignedColors = [],
  colors = [],
  ln = this.series.length,
  neededColors = this.series.length,
  oc = this.options.colors,
  usedColors = [],
  variation = 0,
  c, i, j, s;
 
  // Collect user-defined colors from series.
  for (i = neededColors - 1; i > -1; --i) {
  c = this.series[i].color;
  if (c) {
  --neededColors;
  if (_.isNumber(c)) assignedColors.push(c);
  else usedColors.push(flotr.Color.parse(c));
  }
  }
 
  // Calculate the number of colors that need to be generated.
  for (i = assignedColors.length - 1; i > -1; --i)
  neededColors = Math.max(neededColors, assignedColors[i] + 1);
 
  // Generate needed number of colors.
  for (i = 0; colors.length < neededColors;) {
  c = (oc.length == i) ? new flotr.Color(100, 100, 100) : flotr.Color.parse(oc[i]);
 
  // Make sure each serie gets a different color.
  var sign = variation % 2 == 1 ? -1 : 1,
  factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
  c.scale(factor, factor, factor);
 
  /**
  * @todo if we're getting too close to something else, we should probably skip this one
  */
  colors.push(c);
 
  if (++i >= oc.length) {
  i = 0;
  ++variation;
  }
  }
 
  // Fill the options with the generated colors.
  for (i = 0, j = 0; i < ln; ++i) {
  s = this.series[i];
 
  // Assign the color.
  if (!s.color) {
  s.color = colors[j++].toString();
  } else if (_.isNumber(s.color)) {
  s.color = colors[s.color].toString();
  }
 
  // Every series needs an axis
  if (!s.xaxis) s.xaxis = this.axes.x;
  if (s.xaxis == 1) s.xaxis = this.axes.x;
  else if (s.xaxis == 2) s.xaxis = this.axes.x2;
 
  if (!s.yaxis) s.yaxis = this.axes.y;
  if (s.yaxis == 1) s.yaxis = this.axes.y;
  else if (s.yaxis == 2) s.yaxis = this.axes.y2;
 
  // Apply missing options to the series.
  for (var t in flotr.graphTypes) {
  s[t] = _.extend(_.clone(this.options[t]), s[t]);
  }
  s.mouse = _.extend(_.clone(this.options.mouse), s.mouse);
 
  if (_.isUndefined(s.shadowSize)) s.shadowSize = this.options.shadowSize;
  }
  },
 
  _setEl: function (el) {
  if (!el) throw 'The target container doesn\'t exist';
  else if (el.graph instanceof Graph) el.graph.destroy();
  else if (!el.clientWidth) throw 'The target container must be visible';
 
  el.graph = this;
  this.el = el;
  }
  };
 
  Flotr.Graph = Graph;
 
  })();
 
  /**
  * Flotr Axis Library
  */
 
  (function () {
 
  var
  _ = Flotr._,
  LOGARITHMIC = 'logarithmic';
 
  function Axis(o) {
 
  this.orientation = 1;
  this.offset = 0;
  this.datamin = Number.MAX_VALUE;
  this.datamax = -Number.MAX_VALUE;
 
  _.extend(this, o);
 
  this._setTranslations();
  }
 
 
  // Prototype
  Axis.prototype = {
 
  setScale: function () {
  var length = this.length;
  if (this.options.scaling == LOGARITHMIC) {
  this.scale = length / (log(this.max, this.options.base) - log(this.min, this.options.base));
  } else {
  this.scale = length / (this.max - this.min);
  }
  },
 
  calculateTicks: function () {
  var options = this.options;
 
  this.ticks = [];
  this.minorTicks = [];
 
  // User Ticks
  if (options.ticks) {
  this._cleanUserTicks(options.ticks, this.ticks);
  this._cleanUserTicks(options.minorTicks || [], this.minorTicks);
  }
  else {
  if (options.mode == 'time') {
  this._calculateTimeTicks();
  } else if (options.scaling === 'logarithmic') {
  this._calculateLogTicks();
  } else {
  this._calculateTicks();
  }
  }
 
  // Ticks to strings
  _.each(this.ticks, function (tick) {
  tick.label += '';
  });
  _.each(this.minorTicks, function (tick) {
  tick.label += '';
  });
  },
 
  /**
  * Calculates the range of an axis to apply autoscaling.
  */
  calculateRange: function () {
 
  if (!this.used) return;
 
  var axis = this,
  o = axis.options,
  min = o.min !== null ? o.min : axis.datamin,
  max = o.max !== null ? o.max : axis.datamax,
  margin = o.autoscaleMargin;
 
  if (o.scaling == 'logarithmic') {
  if (min <= 0) min = axis.datamin;
 
  // Let it widen later on
  if (max <= 0) max = min;
  }
 
  if (max == min) {
  var widen = max ? 0.01 : 1.00;
  if (o.min === null) min -= widen;
  if (o.max === null) max += widen;
  }
 
  if (o.scaling === 'logarithmic') {
  if (min < 0) min = max / o.base; // Could be the result of widening
 
  var maxexp = Math.log(max);
  if (o.base != Math.E) maxexp /= Math.log(o.base);
  maxexp = Math.ceil(maxexp);
 
  var minexp = Math.log(min);
  if (o.base != Math.E) minexp /= Math.log(o.base);
  minexp = Math.ceil(minexp);
 
  axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
 
  // Try to determine a suitable amount of miniticks based on the length of a decade
  if (o.minorTickFreq === null) {
  if (maxexp - minexp > 10)
  o.minorTickFreq = 0;
  else if (maxexp - minexp > 5)
  o.minorTickFreq = 2;
  else
  o.minorTickFreq = 5;
  }
  } else {
  axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
  }
 
  axis.min = min;
  axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
 
  // Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
  if (o.min === null && o.autoscale) {
  axis.min -= axis.tickSize * margin;
  // Make sure we don't go below zero if all values are positive.
  if (axis.min < 0 && axis.datamin >= 0) axis.min = 0;
  axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
  }
 
  if (o.max === null && o.autoscale) {
  axis.max += axis.tickSize * margin;
  if (axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
  axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
  }
 
  if (axis.min == axis.max) axis.max = axis.min + 1;
  },
 
  calculateTextDimensions: function (T, options) {
 
  var maxLabel = '',
  length,
  i;
 
  if (this.options.showLabels) {
  for (i = 0; i < this.ticks.length; ++i) {
  length = this.ticks[i].label.length;
  if (length > maxLabel.length) {
  maxLabel = this.ticks[i].label;
  }
  }
  }
 
  this.maxLabel = T.dimensions(
  maxLabel,
  {size: options.fontSize, angle: Flotr.toRad(this.options.labelsAngle)},
  'font-size:smaller;',
  'flotr-grid-label'
  );
 
  this.titleSize = T.dimensions(
  this.options.title,
  {size: options.fontSize * 1.2, angle: Flotr.toRad(this.options.titleAngle)},
  'font-weight:bold;',
  'flotr-axis-title'
  );
  },
 
  _cleanUserTicks: function (ticks, axisTicks) {
 
  var axis = this, options = this.options,
  v, i, label, tick;
 
  if (_.isFunction(ticks)) ticks = ticks({min: axis.min, max: axis.max});
 
  for (i = 0; i < ticks.length; ++i) {
  tick = ticks[i];
  if (typeof(tick) === 'object') {
  v = tick[0];
  label = (tick.length > 1) ? tick[1] : options.tickFormatter(v, {min: axis.min, max: axis.max});
  } else {
  v = tick;
  label = options.tickFormatter(v, {min: this.min, max: this.max});
  }
  axisTicks[i] = { v: v, label: label };
  }
  },
 
  _calculateTimeTicks: function () {
  this.ticks = Flotr.Date.generator(this);
  },
 
  _calculateLogTicks: function () {
 
  var axis = this,
  o = axis.options,
  v,
  decadeStart;
 
  var max = Math.log(axis.max);
  if (o.base != Math.E) max /= Math.log(o.base);
  max = Math.ceil(max);
 
  var min = Math.log(axis.min);
  if (o.base != Math.E) min /= Math.log(o.base);
  min = Math.ceil(min);
 
  for (i = min; i < max; i += axis.tickSize) {
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  // Next decade begins here:
  var decadeEnd = decadeStart * ((o.base == Math.E) ? Math.exp(axis.tickSize) : Math.pow(o.base, axis.tickSize));
  var stepSize = (decadeEnd - decadeStart) / o.minorTickFreq;
 
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min: axis.min, max: axis.max})});
  for (v = decadeStart + stepSize; v < decadeEnd; v += stepSize)
  axis.minorTicks.push({v: v, label: o.tickFormatter(v, {min: axis.min, max: axis.max})});
  }
 
  // Always show the value at the would-be start of next decade (end of this decade)
  decadeStart = (o.base == Math.E) ? Math.exp(i) : Math.pow(o.base, i);
  axis.ticks.push({v: decadeStart, label: o.tickFormatter(decadeStart, {min: axis.min, max: axis.max})});
  },
 
  _calculateTicks: function () {
 
  var axis = this,
  o = axis.options,
  tickSize = axis.tickSize,
  min = axis.min,
  max = axis.max,
  start = tickSize * Math.ceil(min / tickSize), // Round to nearest multiple of tick size.
  decimals,
  minorTickSize,
  v, v2,
  i, j;
 
  if (o.minorTickFreq)
  minorTickSize = tickSize / o.minorTickFreq;
 
  // Then store all possible ticks.
  for (i = 0; (v = v2 = start + i * tickSize) <= max; ++i) {
 
  // Round (this is always needed to fix numerical instability).
  decimals = o.tickDecimals;
  if (decimals === null) decimals = 1 - Math.floor(Math.log(tickSize) / Math.LN10);
  if (decimals < 0) decimals = 0;
 
  v = v.toFixed(decimals);
  axis.ticks.push({ v: v, label: o.tickFormatter(v, {min: axis.min, max: axis.max}) });
 
  if (o.minorTickFreq) {
  for (j = 0; j < o.minorTickFreq && (i * tickSize + j * minorTickSize) < max; ++j) {
  v = v2 + j * minorTickSize;
  axis.minorTicks.push({ v: v, label: o.tickFormatter(v, {min: axis.min, max: axis.max}) });
  }
  }
  }
 
  },
 
  _setTranslations: function (logarithmic) {
  this.d2p = (logarithmic ? d2pLog : d2p);
  this.p2d = (logarithmic ? p2dLog : p2d);
  }
  };
 
 
  // Static Methods
  _.extend(Axis, {
  getAxes: function (options) {
  return {
  x: new Axis({options: options.xaxis, n: 1, length: this.plotWidth}),
  x2: new Axis({options: options.x2axis, n: 2, length: this.plotWidth}),
  y: new Axis({options: options.yaxis, n: 1, length: this.plotHeight, offset: this.plotHeight, orientation: -1}),
  y2: new Axis({options: options.y2axis, n: 2, length: this.plotHeight, offset: this.plotHeight, orientation: -1})
  };
  }
  });
 
 
  // Helper Methods
 
  function d2p(dataValue) {
  return this.offset + this.orientation * (dataValue - this.min) * this.scale;
  }
 
  function p2d(pointValue) {
  return (this.offset + this.orientation * pointValue) / this.scale + this.min;
  }
 
  function d2pLog(dataValue) {
  return this.offset + this.orientation * (log(dataValue, this.options.base) - log(this.min, this.options.base)) * this.scale;
  }
 
  function p2dLog(pointValue) {
  return exp((this.offset + this.orientation * pointValue) / this.scale + log(this.min, this.options.base), this.options.base);
  }
 
  function log(value, base) {
  value = Math.log(Math.max(value, Number.MIN_VALUE));
  if (base !== Math.E)
  value /= Math.log(base);
  return value;
  }
 
  function exp(value, base) {
  return (base === Math.E) ? Math.exp(value) : Math.pow(base, value);
  }
 
  Flotr.Axis = Axis;
 
  })();
 
  /**
  * Flotr Series Library
  */
 
  (function () {
 
  var
  _ = Flotr._;
 
  function Series(o) {
  _.extend(this, o);
  }
 
  Series.prototype = {
 
  getRange: function () {
 
  var
  data = this.data,
  length = data.length,
  xmin = Number.MAX_VALUE,
  ymin = Number.MAX_VALUE,
  xmax = -Number.MAX_VALUE,
  ymax = -Number.MAX_VALUE,
  xused = false,
  yused = false,
  x, y, i;
 
  if (length < 0 || this.hide) return false;
 
  for (i = 0; i < length; i++) {
  x = data[i][0];
  y = data[i][1];
  if (x < xmin) {
  xmin = x;
  xused = true;
  }
  if (x > xmax) {
  xmax = x;
  xused = true;
  }
  if (y < ymin) {
  ymin = y;
  yused = true;
  }
  if (y > ymax) {
  ymax = y;
  yused = true;
  }
  }
 
  return {
  xmin: xmin,
  xmax: xmax,
  ymin: ymin,
  ymax: ymax,
  xused: xused,
  yused: yused
  };
  }
  };
 
  _.extend(Series, {
  /**
  * Collects dataseries from input and parses the series into the right format. It returns an Array
  * of Objects each having at least the 'data' key set.
  * @param {Array, Object} data - Object or array of dataseries
  * @return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
  */
  getSeries: function (data) {
  return _.map(data, function (s) {
  var series;
  if (s.data) {
  series = new Series();
  _.extend(series, s);
  } else {
  series = new Series({data: s});
  }
  return series;
  });
  }
  });
 
  Flotr.Series = Series;
 
  })();
 
  /** Lines **/
  Flotr.addType('lines', {
  options: {
  show: false, // => setting to true will show lines, false will hide
  lineWidth: 2, // => line width in pixels
  fill: false, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillBorder: false, // => draw a border around the fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  steps: false, // => draw steps
  stacked: false // => setting to true will show stacked lines, false will show normal lines
  },
 
  stack: {
  values: []
  },
 
  /**
  * Draws lines series in the canvas element.
  * @param {Object} options
  */
  draw: function (options) {
 
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  offset;
 
  context.save();
  context.lineJoin = 'round';
 
  if (shadowSize) {
 
  context.lineWidth = shadowSize / 2;
  offset = lineWidth / 2 + context.lineWidth / 2;
 
  // @TODO do this instead with a linear gradient
  context.strokeStyle = "rgba(0,0,0,0.1)";
  this.plot(options, offset + shadowSize / 2, false);
 
  context.strokeStyle = "rgba(0,0,0,0.2)";
  this.plot(options, offset, false);
  }
 
  context.lineWidth = lineWidth;
  context.strokeStyle = options.color;
 
  this.plot(options, 0, true);
 
  context.restore();
  },
 
  plot: function (options, shadowOffset, incStack) {
 
  var
  context = options.context,
  width = options.width,
  height = options.height,
  xScale = options.xScale,
  yScale = options.yScale,
  data = options.data,
  stack = options.stacked ? this.stack : false,
  length = data.length - 1,
  prevx = null,
  prevy = null,
  zero = yScale(0),
  start = null,
  x1, x2, y1, y2, stack1, stack2, i;
 
  if (length < 1) return;
 
  context.beginPath();
 
  for (i = 0; i < length; ++i) {
 
  // To allow empty values
  if (data[i][1] === null || data[i + 1][1] === null) {
  if (options.fill) {
  if (i > 0 && data[i][1]) {
  context.stroke();
  fill();
  start = null;
  context.closePath();
  context.beginPath();
  }
  }
  continue;
  }
 
  // Zero is infinity for log scales
  // TODO handle zero for logarithmic
  // if (xa.options.scaling === 'logarithmic' && (data[i][0] <= 0 || data[i+1][0] <= 0)) continue;
  // if (ya.options.scaling === 'logarithmic' && (data[i][1] <= 0 || data[i+1][1] <= 0)) continue;
 
  x1 = xScale(data[i][0]);
  x2 = xScale(data[i + 1][0]);
 
  if (start === null) start = data[i];
 
  if (stack) {
 
  stack1 = stack.values[data[i][0]] || 0;
  stack2 = stack.values[data[i + 1][0]] || stack.values[data[i][0]] || 0;
 
  y1 = yScale(data[i][1] + stack1);
  y2 = yScale(data[i + 1][1] + stack2);
 
  if (incStack) {
  stack.values[data[i][0]] = data[i][1] + stack1;
 
  if (i == length - 1)
  stack.values[data[i + 1][0]] = data[i + 1][1] + stack2;
  }
  }
  else {
  y1 = yScale(data[i][1]);
  y2 = yScale(data[i + 1][1]);
  }
 
  if (
  (y1 > height && y2 > height) ||
  (y1 < 0 && y2 < 0) ||
  (x1 < 0 && x2 < 0) ||
  (x1 > width && x2 > width)
  ) continue;
 
  if ((prevx != x1) || (prevy != y1 + shadowOffset))
  context.moveTo(x1, y1 + shadowOffset);
 
  prevx = x2;
  prevy = y2 + shadowOffset;
  if (options.steps) {
  context.lineTo(prevx + shadowOffset / 2, y1 + shadowOffset);
  context.lineTo(prevx + shadowOffset / 2, prevy);
  } else {
  context.lineTo(prevx, prevy);
  }
  }
 
  if (!options.fill || options.fill && !options.fillBorder) context.stroke();
 
  fill();
 
  function fill() {
  // TODO stacked lines
  if (!shadowOffset && options.fill && start) {
  x1 = xScale(start[0]);
  context.fillStyle = options.fillStyle;
  context.lineTo(x2, zero);
  context.lineTo(x1, zero);
  context.lineTo(x1, yScale(start[1]));
  context.fill();
  if (options.fillBorder) {
  context.stroke();
  }
  }
  }
 
  context.closePath();
  },
 
  // Perform any pre-render precalculations (this should be run on data first)
  // - Pie chart total for calculating measures
  // - Stacks for lines and bars
  // precalculate : function () {
  // }
  //
  //
  // Get any bounds after pre calculation (axis can fetch this if does not have explicit min/max)
  // getBounds : function () {
  // }
  // getMin : function () {
  // }
  // getMax : function () {
  // }
  //
  //
  // Padding around rendered elements
  // getPadding : function () {
  // }
 
  extendYRange: function (axis, data, options, lines) {
 
  var o = axis.options;
 
  // If stacked and auto-min
  if (options.stacked && ((!o.max && o.max !== 0) || (!o.min && o.min !== 0))) {
 
  var
  newmax = axis.max,
  newmin = axis.min,
  positiveSums = lines.positiveSums || {},
  negativeSums = lines.negativeSums || {},
  x, j;
 
  for (j = 0; j < data.length; j++) {
 
  x = data[j][0] + '';
 
  // Positive
  if (data[j][1] > 0) {
  positiveSums[x] = (positiveSums[x] || 0) + data[j][1];
  newmax = Math.max(newmax, positiveSums[x]);
  }
 
  // Negative
  else {
  negativeSums[x] = (negativeSums[x] || 0) + data[j][1];
  newmin = Math.min(newmin, negativeSums[x]);
  }
  }
 
  lines.negativeSums = negativeSums;
  lines.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  if (options.steps) {
 
  this.hit = function (options) {
  var
  data = options.data,
  args = options.args,
  yScale = options.yScale,
  mouse = args[0],
  length = data.length,
  n = args[1],
  x = mouse.x,
  relY = mouse.relY,
  i;
 
  for (i = 0; i < length - 1; i++) {
  if (x >= data[i][0] && x <= data[i + 1][0]) {
  if (Math.abs(yScale(data[i][1]) - relY) < 8) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  break;
  }
  }
  };
 
  this.drawHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x2, y);
  context.stroke();
  context.closePath();
  context.restore();
  }
  };
 
  this.clearHit = function (options) {
  var
  context = options.context,
  args = options.args,
  data = options.data,
  xScale = options.xScale,
  width = options.lineWidth,
  index = args.index,
  x = xScale(args.x),
  y = options.yScale(args.y),
  x2;
 
  if (data.length - 1 > index) {
  x2 = options.xScale(data[index + 1][0]);
  context.clearRect(x - width, y - width, x2 - x + 2 * width, 2 * width);
  }
  };
  }
  }
 
  });
 
  /** Bars **/
  Flotr.addType('bars', {
 
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  horizontal: false, // => horizontal bars (x and y inverted)
  stacked: false, // => stacked bar charts
  centered: true, // => center the bars to their x axis value
  topPadding: 0.1, // => top padding in percent
  grouped: false // => groups bars together which share x value, hit not supported.
  },
 
  stack: {
  positive: [],
  negative: [],
  _positive: [], // Shadow
  _negative: [] // Shadow
  },
 
  draw: function (options) {
  var
  context = options.context;
 
  this.current += 1;
 
  context.save();
  context.lineJoin = 'miter';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  if (options.fill) context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot: function (options) {
 
  var
  data = options.data,
  context = options.context,
  shadowSize = options.shadowSize,
  i, geometry, left, top, width, height;
 
  if (data.length < 1) return;
 
  this.translate(context, options.horizontal);
 
  for (i = 0; i < data.length; i++) {
 
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (geometry === null) continue;
 
  left = geometry.left;
  top = geometry.top;
  width = geometry.width;
  height = geometry.height;
 
  if (options.fill) context.fillRect(left, top, width, height);
  if (shadowSize) {
  context.save();
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top + shadowSize, width, height);
  context.restore();
  }
  if (options.lineWidth) {
  context.strokeRect(left, top, width, height);
  }
  }
  },
 
  translate: function (context, horizontal) {
  if (horizontal) {
  context.rotate(-Math.PI / 2);
  context.scale(-1, 1);
  }
  },
 
  getBarGeometry: function (x, y, options) {
 
  var
  horizontal = options.horizontal,
  barWidth = options.barWidth,
  centered = options.centered,
  stack = options.stacked ? this.stack : false,
  lineWidth = options.lineWidth,
  bisection = centered ? barWidth / 2 : 0,
  xScale = horizontal ? options.yScale : options.xScale,
  yScale = horizontal ? options.xScale : options.yScale,
  xValue = horizontal ? y : x,
  yValue = horizontal ? x : y,
  stackOffset = 0,
  stackValue, left, right, top, bottom;
 
  if (options.grouped) {
  this.current / this.groups
  xValue = xValue - bisection;
  barWidth = barWidth / this.groups;
  bisection = barWidth / 2;
  xValue = xValue + barWidth * this.current - bisection;
  }
 
  // Stacked bars
  if (stack) {
  stackValue = yValue > 0 ? stack.positive : stack.negative;
  stackOffset = stackValue[xValue] || stackOffset;
  stackValue[xValue] = stackOffset + yValue;
  }
 
  left = xScale(xValue - bisection);
  right = xScale(xValue + barWidth - bisection);
  top = yScale(yValue + stackOffset);
  bottom = yScale(stackOffset);
 
  // TODO for test passing... probably looks better without this
  if (bottom < 0) bottom = 0;
 
  // TODO Skipping...
  // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;
 
  return (x === null || y === null) ? null : {
  x: xValue,
  y: yValue,
  xScale: xScale,
  yScale: yScale,
  top: top,
  left: Math.min(left, right) - lineWidth / 2,
  width: Math.abs(right - left) - lineWidth,
  height: bottom - top
  };
  },
 
  hit: function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  x = mouse.x,
  y = mouse.y,
  hitGeometry = this.getBarGeometry(x, y, options),
  width = hitGeometry.width / 2,
  left = hitGeometry.left,
  geometry, i;
 
  for (i = data.length; i--;) {
  geometry = this.getBarGeometry(data[i][0], data[i][1], options);
  if (geometry.y > hitGeometry.y && Math.abs(left - geometry.left) < width) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  }
  }
  },
 
  drawHit: function (options) {
  // TODO hits for stacked bars; implement using calculateStack option?
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  top = geometry.top,
  width = geometry.width,
  height = geometry.height;
 
  context.save();
  context.strokeStyle = options.color;
  context.lineWidth = options.lineWidth;
  this.translate(context, options.horizontal);
 
  // Draw highlight
  context.beginPath();
  context.moveTo(left, top + height);
  context.lineTo(left, top);
  context.lineTo(left + width, top);
  context.lineTo(left + width, top + height);
  if (options.fill) {
  context.fillStyle = options.fillStyle;
  context.fill();
  }
  context.stroke();
  context.closePath();
 
  context.restore();
  },
 
  clearHit: function (options) {
  var
  context = options.context,
  args = options.args,
  geometry = this.getBarGeometry(args.x, args.y, options),
  left = geometry.left,
  width = geometry.width,
  top = geometry.top,
  height = geometry.height,
  lineWidth = 2 * options.lineWidth;
 
  context.save();
  this.translate(context, options.horizontal);
  context.clearRect(
  left - lineWidth,
  Math.min(top, top + height) - lineWidth,
  width + 2 * lineWidth,
  Math.abs(height) + 2 * lineWidth
  );
  context.restore();
  },
 
  extendXRange: function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  this.groups = (this.groups + 1) || 1;
  this.current = 0;
  },
 
  extendYRange: function (axis, data, options, bars) {
  this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {
 
  var
  max = axis.options.max;
 
  if (_.isNumber(max) || _.isString(max)) return;
 
  var
  newmin = axis.min,
  newmax = axis.max,
  horizontal = options.horizontal,
  orientation = axis.orientation,
  positiveSums = this.positiveSums || {},
  negativeSums = this.negativeSums || {},
  value, datum, index, j;
 
  // Sides of bars
  if ((orientation == 1 && !horizontal) || (orientation == -1 && horizontal)) {
  if (options.centered) {
  newmax = Math.max(axis.datamax + options.barWidth, newmax);
  newmin = Math.min(axis.datamin - options.barWidth, newmin);
  }
  }
 
  if (options.stacked &&
  ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal))) {
 
  for (j = data.length; j--;) {
  value = data[j][(orientation == 1 ? 1 : 0)] + '';
  datum = data[j][(orientation == 1 ? 0 : 1)];
 
  // Positive
  if (datum > 0) {
  positiveSums[value] = (positiveSums[value] || 0) + datum;
  newmax = Math.max(newmax, positiveSums[value]);
  }
 
  // Negative
  else {
  negativeSums[value] = (negativeSums[value] || 0) + datum;
  newmin = Math.min(newmin, negativeSums[value]);
  }
  }
  }
 
  // End of bars
  if ((orientation == 1 && horizontal) || (orientation == -1 && !horizontal)) {
  if (options.topPadding && (axis.max === axis.datamax || (options.stacked && this.stackMax !== newmax))) {
  newmax += options.topPadding * (newmax - newmin);
  }
  }
 
  this.stackMin = newmin;
  this.stackMax = newmax;
  this.negativeSums = negativeSums;
  this.positiveSums = positiveSums;
 
  axis.max = newmax;
  axis.min = newmin;
  }
 
  });
 
  /** Bubbles **/
  Flotr.addType('bubbles', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  baseRadius: 2 // => ratio of the radar, against the plot size
  },
  draw: function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.lineWidth = options.lineWidth;
 
  // Shadows
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot: function (options, offset) {
 
  var
  data = options.data,
  context = options.context,
  geometry,
  i, x, y, z;
 
  offset = offset || 0;
 
  for (i = 0; i < data.length; ++i) {
 
  geometry = this.getGeometry(data[i], options);
 
  context.beginPath();
  context.arc(geometry.x + offset, geometry.y + offset, geometry.z, 0, 2 * Math.PI, true);
  context.stroke();
  if (options.fill) context.fill();
  context.closePath();
  }
  },
  getGeometry: function (point, options) {
  return {
  x: options.xScale(point[0]),
  y: options.yScale(point[1]),
  z: point[2] * options.baseRadius
  };
  },
  hit: function (options) {
  var
  data = options.data,
  args = options.args,
  mouse = args[0],
  n = args[1],
  x = mouse.x,
  y = mouse.y,
  distance,
  geometry,
  dx, dy;
 
  n.best = n.best || Number.MAX_VALUE;
 
  for (i = data.length; i--;) {
  geometry = this.getGeometry(data[i], options);
 
  dx = geometry.x - options.xScale(x);
  dy = geometry.y - options.yScale(y);
  distance = Math.sqrt(dx * dx + dy * dy);
 
  if (distance < geometry.z && geometry.z < n.best) {
  n.x = data[i][0];
  n.y = data[i][1];
  n.index = i;
  n.seriesIndex = options.index;
  n.best = geometry.z;
  }
  }
  },
  drawHit: function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options);
 
  context.save();
  context.lineWidth = options.lineWidth;
  context.fillStyle = options.fillStyle;
  context.strokeStyle = options.color;
  context.beginPath();
  context.arc(geometry.x, geometry.y, geometry.z, 0, 2 * Math.PI, true);
  context.fill();
  context.stroke();
  context.closePath();
  context.restore();
  },
  clearHit: function (options) {
 
  var
  context = options.context,
  geometry = this.getGeometry(options.data[options.args.index], options),
  offset = geometry.z + options.lineWidth;
 
  context.save();
  context.clearRect(
  geometry.x - offset,
  geometry.y - offset,
  2 * offset,
  2 * offset
  );
  context.restore();
  }
  // TODO Add a hit calculation method (like pie)
  });
 
  /** Candles **/
  Flotr.addType('candles', {
  options: {
  show: false, // => setting to true will show candle sticks, false will hide
  lineWidth: 1, // => in pixels
  wickLineWidth: 1, // => in pixels
  candleWidth: 0.6, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  upFillColor: '#00A8F0',// => up sticks fill color
  downFillColor: '#CB4B4B',// => down sticks fill color
  fillOpacity: 0.5, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  // TODO Test this barcharts option.
  barcharts: false // => draw as barcharts (not standard bars but financial barcharts)
  },
 
  draw: function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineCap = 'butt';
  // @TODO linewidth not interpreted the right way.
  context.lineWidth = options.wickLineWidth || options.lineWidth;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot: function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  width = options.candleWidth / 2,
  shadowSize = options.shadowSize,
  lineWidth = options.lineWidth,
  wickLineWidth = options.wickLineWidth,
  pixelOffset = (wickLineWidth % 2) / 2,
  color,
  datum, x, y,
  open, high, low, close,
  left, right, bottom, top, bottom2, top2,
  i;
 
  if (data.length < 1) return;
 
  for (i = 0; i < data.length; i++) {
  datum = data[i];
  x = datum[0];
  open = datum[1];
  high = datum[2];
  low = datum[3];
  close = datum[4];
  left = xScale(x - width);
  right = xScale(x + width);
  bottom = yScale(low);
  top = yScale(high);
  bottom2 = yScale(Math.min(open, close));
  top2 = yScale(Math.max(open, close));
 
  /*
  // TODO skipping
  if(right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
  */
 
  color = options[open > close ? 'downFillColor' : 'upFillColor'];
 
  // Fill the candle.
  // TODO Test the barcharts option
  if (options.fill && !options.barcharts) {
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.fillRect(left + shadowSize, top2 + shadowSize, right - left, bottom2 - top2);
  context.save();
  context.globalAlpha = options.fillOpacity;
  context.fillStyle = color;
  context.fillRect(left, top2 + lineWidth, right - left, bottom2 - top2);
  context.restore();
  }
 
  // Draw candle outline/border, high, low.
  if (lineWidth || wickLineWidth) {
 
  x = Math.floor((left + right) / 2) + pixelOffset;
 
  context.strokeStyle = color;
  context.beginPath();
 
  // TODO Again with the bartcharts
  if (options.barcharts) {
 
  context.moveTo(x, Math.floor(top + width));
  context.lineTo(x, Math.floor(bottom + width));
 
  y = Math.floor(open + width) + 0.5;
  context.moveTo(Math.floor(left) + pixelOffset, y);
  context.lineTo(x, y);
 
  y = Math.floor(close + width) + 0.5;
  context.moveTo(Math.floor(right) + pixelOffset, y);
  context.lineTo(x, y);
  } else {
  context.strokeRect(left, top2 + lineWidth, right - left, bottom2 - top2);
 
  context.moveTo(x, Math.floor(top2 + lineWidth));
  context.lineTo(x, Math.floor(top + lineWidth));
  context.moveTo(x, Math.floor(bottom2 + lineWidth));
  context.lineTo(x, Math.floor(bottom + lineWidth));
  }
 
  context.closePath();
  context.stroke();
  }
  }
  },
  extendXRange: function (axis, data, options) {
  if (axis.options.max === null) {
  axis.max = Math.max(axis.datamax + 0.5, axis.max);
  axis.min = Math.min(axis.datamin - 0.5, axis.min);
  }
  }
  });
 
  /** Gantt
  * Base on data in form [s,y,d] where:
  * y - executor or simply y value
  * s - task start value
  * d - task duration
  * **/
  Flotr.addType('gantt', {
  options: {
  show: false, // => setting to true will show gantt, false will hide
  lineWidth: 2, // => in pixels
  barWidth: 1, // => in units of the x axis
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  centered: true // => center the bars to their x axis value
  },
  /**
  * Draws gantt series in the canvas element.
  * @param {Object} series - Series with options.gantt.show = true.
  */
  draw: function (series) {
  var ctx = this.ctx,
  bw = series.gantt.barWidth,
  lw = Math.min(series.gantt.lineWidth, bw);
 
  ctx.save();
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
  ctx.lineJoin = 'miter';
 
  /**
  * @todo linewidth not interpreted the right way.
  */
  ctx.lineWidth = lw;
  ctx.strokeStyle = series.color;
 
  ctx.save();
  this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
  ctx.restore();
 
  if (series.gantt.fill) {
  var color = series.gantt.fillColor || series.color;
  ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
  }
 
  this.gantt.plot(series, bw, 0, series.gantt.fill);
  ctx.restore();
  },
  plot: function (series, barWidth, offset, fill) {
  var data = series.data;
  if (data.length < 1) return;
 
  var xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx, i;
 
  for (i = 0; i < data.length; i++) {
  var y = data[i][0],
  s = data[i][1],
  d = data[i][2],
  drawLeft = true, drawTop = true, drawRight = true;
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth / 2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth / 2 : 0);
 
  if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if (left < xa.min) {
  left = xa.min;
  drawLeft = false;
  }
 
  if (right > xa.max) {
  right = xa.max;
  if (xa.lastSerie != series)
  drawTop = false;
  }
 
  if (bottom < ya.min)
  bottom = ya.min;
 
  if (top > ya.max) {
  top = ya.max;
  if (ya.lastSerie != series)
  drawTop = false;
  }
 
  /**
  * Fill the bar.
  */
  if (fill) {
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
  ctx.lineTo(xa.d2p(left), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(top) + offset);
  ctx.lineTo(xa.d2p(right), ya.d2p(bottom) + offset);
  ctx.fill();
  ctx.closePath();
  }
 
  /**
  * Draw bar outline/border.
  */
  if (series.gantt.lineWidth && (drawLeft || drawRight || drawTop)) {
  ctx.beginPath();
  ctx.moveTo(xa.d2p(left), ya.d2p(bottom) + offset);
 
  ctx[drawLeft ? 'lineTo' : 'moveTo'](xa.d2p(left), ya.d2p(top) + offset);
  ctx[drawTop ? 'lineTo' : 'moveTo'](xa.d2p(right), ya.d2p(top) + offset);
  ctx[drawRight ? 'lineTo' : 'moveTo'](xa.d2p(right), ya.d2p(bottom) + offset);
 
  ctx.stroke();
  ctx.closePath();
  }
  }
  },
  plotShadows: function (series, barWidth, offset) {
  var data = series.data;
  if (data.length < 1) return;
 
  var i, y, s, d,
  xa = series.xaxis,
  ya = series.yaxis,
  ctx = this.ctx,
  sw = this.options.shadowSize;
 
  for (i = 0; i < data.length; i++) {
  y = data[i][0];
  s = data[i][1];
  d = data[i][2];
 
  if (s === null || d === null) continue;
 
  var left = s,
  right = s + d,
  bottom = y - (series.gantt.centered ? barWidth / 2 : 0),
  top = y + barWidth - (series.gantt.centered ? barWidth / 2 : 0);
 
  if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max)
  continue;
 
  if (left < xa.min) left = xa.min;
  if (right > xa.max) right = xa.max;
  if (bottom < ya.min) bottom = ya.min;
  if (top > ya.max) top = ya.max;
 
  var width = xa.d2p(right) - xa.d2p(left) - ((xa.d2p(right) + sw <= this.plotWidth) ? 0 : sw);
  var height = ya.d2p(bottom) - ya.d2p(top) - ((ya.d2p(bottom) + sw <= this.plotHeight) ? 0 : sw );
 
  ctx.fillStyle = 'rgba(0,0,0,0.05)';
  ctx.fillRect(Math.min(xa.d2p(left) + sw, this.plotWidth), Math.min(ya.d2p(top) + sw, this.plotHeight), width, height);
  }
  },
  extendXRange: function (axis) {
  if (axis.options.max === null) {
  var newmin = axis.min,
  newmax = axis.max,
  i, j, x, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for (i = 0; i < this.series.length; ++i) {
  s = this.series[i];
  g = s.gantt;
 
  if (g.show && s.xaxis == axis) {
  for (j = 0; j < s.data.length; j++) {
  if (g.show) {
  y = s.data[j][0] + '';
  stackedSumsPos[y] = Math.max((stackedSumsPos[y] || 0), s.data[j][1] + s.data[j][2]);
  lastSerie = s;
  }
  }
  for (j in stackedSumsPos) {
  newmax = Math.max(stackedSumsPos[j], newmax);
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  }
  },
  extendYRange: function (axis) {
  if (axis.options.max === null) {
  var newmax = Number.MIN_VALUE,
  newmin = Number.MAX_VALUE,
  i, j, s, g,
  stackedSumsPos = {},
  stackedSumsNeg = {},
  lastSerie = null;
 
  for (i = 0; i < this.series.length; ++i) {
  s = this.series[i];
  g = s.gantt;
 
  if (g.show && !s.hide && s.yaxis == axis) {
  var datamax = Number.MIN_VALUE, datamin = Number.MAX_VALUE;
  for (j = 0; j < s.data.length; j++) {
  datamax = Math.max(datamax, s.data[j][0]);
  datamin = Math.min(datamin, s.data[j][0]);
  }
 
  if (g.centered) {
  newmax = Math.max(datamax + 0.5, newmax);
  newmin = Math.min(datamin - 0.5, newmin);
  }
  else {
  newmax = Math.max(datamax + 1, newmax);
  newmin = Math.min(datamin, newmin);
  }
  // For normal horizontal bars
  if (g.barWidth + datamax > newmax) {
  newmax = axis.max + g.barWidth;
  }
  }
  }
  axis.lastSerie = lastSerie;
  axis.max = newmax;
  axis.min = newmin;
  axis.tickSize = Flotr.getTickSize(axis.options.noTicks, newmin, newmax, axis.options.tickDecimals);
  }
  }
  });
 
  /** Markers **/
  /**
  * Formats the marker labels.
  * @param {Object} obj - Marker value Object {x:..,y:..}
  * @return {String} Formatted marker string
  */
  (function () {
 
  Flotr.defaultMarkerFormatter = function (obj) {
  return (Math.round(obj.y * 100) / 100) + '';
  };
 
  Flotr.addType('markers', {
  options: {
  show: false, // => setting to true will show markers, false will hide
  lineWidth: 1, // => line width of the rectangle around the marker
  color: '#000000', // => text color
  fill: false, // => fill or not the marekers' rectangles
  fillColor: "#FFFFFF", // => fill color
  fillOpacity: 0.4, // => fill opacity
  stroke: false, // => draw the rectangle around the markers
  position: 'ct', // => the markers position (vertical align: b, m, t, horizontal align: l, c, r)
  verticalMargin: 0, // => the margin between the point and the text.
  labelFormatter: Flotr.defaultMarkerFormatter,
  fontSize: Flotr.defaultOptions.fontSize,
  stacked: false, // => true if markers should be stacked
  stackingType: 'b', // => define staching behavior, (b- bars like, a - area like) (see Issue 125 for details)
  horizontal: false // => true if markers should be horizontal (For now only in a case on horizontal stacked bars, stacks should be calculated horizontaly)
  },
 
  // TODO test stacked markers.
  stack: {
  positive: [],
  negative: [],
  values: []
  },
 
  draw: function (options) {
 
  var
  data = options.data,
  context = options.context,
  stack = options.stacked ? options.stack : false,
  stackType = options.stackingType,
  stackOffsetNeg,
  stackOffsetPos,
  stackOffset,
  i, x, y, label;
 
  context.save();
  context.lineJoin = 'round';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = 'rgba(0,0,0,0.5)';
  context.fillStyle = options.fillStyle;
 
  function stackPos(a, b) {
  stackOffsetPos = stack.negative[a] || 0;
  stackOffsetNeg = stack.positive[a] || 0;
  if (b > 0) {
  stack.positive[a] = stackOffsetPos + b;
  return stackOffsetPos + b;
  } else {
  stack.negative[a] = stackOffsetNeg + b;
  return stackOffsetNeg + b;
  }
  }
 
  for (i = 0; i < data.length; ++i) {
 
  x = data[i][0];
  y = data[i][1];
 
  if (stack) {
  if (stackType == 'b') {
  if (options.horizontal) y = stackPos(y, x);
  else x = stackPos(x, y);
  } else if (stackType == 'a') {
  stackOffset = stack.values[x] || 0;
  stack.values[x] = stackOffset + y;
  y = stackOffset + y;
  }
  }
 
  label = options.labelFormatter({x: x, y: y, index: i, data: data});
  this.plot(options.xScale(x), options.yScale(y), label, options);
  }
  context.restore();
  },
  plot: function (x, y, label, options) {
  var context = options.context;
  if (isImage(label) && !label.complete) {
  throw 'Marker image not loaded.';
  } else {
  this._plot(x, y, label, options);
  }
  },
 
  _plot: function (x, y, label, options) {
  var context = options.context,
  margin = 2,
  left = x,
  top = y,
  dim;
 
  if (isImage(label))
  dim = {height: label.height, width: label.width};
  else
  dim = options.text.canvas(label);
 
  dim.width = Math.floor(dim.width + margin * 2);
  dim.height = Math.floor(dim.height + margin * 2);
 
  if (options.position.indexOf('c') != -1) left -= dim.width / 2 + margin;
  else if (options.position.indexOf('l') != -1) left -= dim.width;
 
  if (options.position.indexOf('m') != -1) top -= dim.height / 2 + margin;
  else if (options.position.indexOf('t') != -1) top -= dim.height + options.verticalMargin;
  else top += options.verticalMargin;
 
  left = Math.floor(left) + 0.5;
  top = Math.floor(top) + 0.5;
 
  if (options.fill)
  context.fillRect(left, top, dim.width, dim.height);
 
  if (options.stroke)
  context.strokeRect(left, top, dim.width, dim.height);
 
  if (isImage(label))
  context.drawImage(label, left + margin, top + margin);
  else
  Flotr.drawText(context, label, left + margin, top + margin, {textBaseline: 'top', textAlign: 'left', size: options.fontSize, color: options.color});
  }
  });
 
  function isImage(i) {
  return typeof i === 'object' && i.constructor && (Image ? true : i.constructor === Image);
  }
 
  })();
 
  /** Pie **/
  /**
  * Formats the pies labels.
  * @param {Object} slice - Slice object
  * @return {String} Formatted pie label string
  */
  (function () {
 
  var
  _ = Flotr._;
 
  Flotr.defaultPieLabelFormatter = function (total, value) {
  return (100 * value / total).toFixed(2) + '%';
  };
 
  Flotr.addType('pie', {
  options: {
  show: false, // => setting to true will show bars, false will hide
  lineWidth: 1, // => in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillColor: null, // => fill color
  fillOpacity: 0.6, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  explode: 6, // => the number of pixels the splices will be far from the center
  sizeRatio: 0.6, // => the size ratio of the pie relative to the plot
  startAngle: Math.PI / 4, // => the first slice start angle
  labelFormatter: Flotr.defaultPieLabelFormatter,
  pie3D: false, // => whether to draw the pie in 3 dimenstions or not (ineffective)
  pie3DviewAngle: (Math.PI / 2 * 0.8),
  pie3DspliceThickness: 20
  },
 
  draw: function (options) {
 
  // TODO 3D charts what?
 
  var
  data = options.data,
  context = options.context,
  canvas = context.canvas,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize,
  sizeRatio = options.sizeRatio,
  height = options.height,
  width = options.width,
  explode = options.explode,
  color = options.color,
  fill = options.fill,
  fillStyle = options.fillStyle,
  radius = Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  value = data[0][1],
  html = [],
  vScale = 1,//Math.cos(series.pie.viewAngle);
  measure = Math.PI * 2 * value / this.total,
  startAngle = this.startAngle || (2 * Math.PI * options.startAngle), // TODO: this initial startAngle is already in radians (fixing will be test-unstable)
  endAngle = startAngle + measure,
  bisection = startAngle + measure / 2,
  label = options.labelFormatter(this.total, value),
  //plotTickness = Math.sin(series.pie.viewAngle)*series.pie.spliceThickness / vScale;
  explodeCoeff = explode + radius + 4,
  distX = Math.cos(bisection) * explodeCoeff,
  distY = Math.sin(bisection) * explodeCoeff,
  textAlign = distX < 0 ? 'right' : 'left',
  textBaseline = distY > 0 ? 'top' : 'bottom',
  style,
  x, y,
  distX, distY;
 
  context.save();
  context.translate(width / 2, height / 2);
  context.scale(1, vScale);
 
  x = Math.cos(bisection) * explode;
  y = Math.sin(bisection) * explode;
 
  // Shadows
  if (shadowSize > 0) {
  this.plotSlice(x + shadowSize, y + shadowSize, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = 'rgba(0,0,0,0.1)';
  context.fill();
  }
  }
 
  this.plotSlice(x, y, radius, startAngle, endAngle, context);
  if (fill) {
  context.fillStyle = fillStyle;
  context.fill();
  }
  context.lineWidth = lineWidth;
  context.strokeStyle = color;
  context.stroke();
 
  style = {
  size: options.fontSize * 1.2,
  color: options.fontColor,
  weight: 1.5
  };
 
  if (label) {
  if (options.htmlText || !options.textEnabled) {
  divStyle = 'position:absolute;' + textBaseline + ':' + (height / 2 + (textBaseline === 'top' ? distY : -distY)) + 'px;';
  divStyle += textAlign + ':' + (width / 2 + (textAlign === 'right' ? -distX : distX)) + 'px;';
  html.push('<div style="', divStyle, '" class="flotr-grid-label">', label, '</div>');
  }
  else {
  style.textAlign = textAlign;
  style.textBaseline = textBaseline;
  Flotr.drawText(context, label, distX, distY, style);
  }
  }
 
  if (options.htmlText || !options.textEnabled) {
  var div = Flotr.DOM.node('<div style="color:' + options.fontColor + '" class="flotr-labels"></div>');
  Flotr.DOM.insert(div, html.join(''));
  Flotr.DOM.insert(options.element, div);
  }
 
  context.restore();
 
  // New start angle
  this.startAngle = endAngle;
  this.slices = this.slices || [];
  this.slices.push({
  radius: Math.min(canvas.width, canvas.height) * sizeRatio / 2,
  x: x,
  y: y,
  explode: explode,
  start: startAngle,
  end: endAngle
  });
  },
  plotSlice: function (x, y, radius, startAngle, endAngle, context) {
  context.beginPath();
  context.moveTo(x, y);
  context.arc(x, y, radius, startAngle, endAngle, false);
  context.lineTo(x, y);
  context.closePath();
  },
  hit: function (options) {
 
  var
  data = options.data[0],
  args = options.args,
  index = options.index,
  mouse = args[0],
  n = args[1],
  slice = this.slices[index],
  x = mouse.relX - options.width / 2,
  y = mouse.relY - options.height / 2,
  r = Math.sqrt(x * x + y * y),
  theta = Math.atan(y / x),
  circle = Math.PI * 2,
  explode = slice.explode || options.explode,
  start = slice.start % circle,
  end = slice.end % circle;
 
  if (x < 0) {
  theta += Math.PI;
  } else if (x > 0 && y < 0) {
  theta += circle;
  }
 
  if (r < slice.radius + explode && r > explode) {
  if ((start >= end && (theta < end || theta > start)) ||
  (theta > start && theta < end)) {
 
  // TODO Decouple this from hit plugin (chart shouldn't know what n means)
  n.x = data[0];
  n.y = data[1];
  n.sAngle = start;
  n.eAngle = end;
  n.index = 0;
  n.seriesIndex = index;
  n.fraction = data[1] / this.total;
  }
  }
  },
  drawHit: function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex];
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  this.plotSlice(slice.x, slice.y, slice.radius, slice.start, slice.end, context);
  context.stroke();
  context.restore();
  },
  clearHit: function (options) {
  var
  context = options.context,
  slice = this.slices[options.args.seriesIndex],
  padding = 2 * options.lineWidth,
  radius = slice.radius + padding;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.clearRect(
  slice.x - radius,
  slice.y - radius,
  2 * radius + padding,
  2 * radius + padding
  );
  context.restore();
  },
  extendYRange: function (axis, data) {
  this.total = (this.total || 0) + data[0][1];
  }
  });
  })();
 
  /** Points **/
  Flotr.addType('points', {
  options: {
  show: false, // => setting to true will show points, false will hide
  radius: 3, // => point radius (pixels)
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the points with a color, false for (transparent) no fill
  fillColor: '#FFFFFF', // => fill color
  fillOpacity: 0.4 // => opacity of color inside the points
  },
 
  draw: function (options) {
  var
  context = options.context,
  lineWidth = options.lineWidth,
  shadowSize = options.shadowSize;
 
  context.save();
 
  if (shadowSize > 0) {
  context.lineWidth = shadowSize / 2;
 
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 2 + context.lineWidth / 2);
 
  context.strokeStyle = 'rgba(0,0,0,0.2)';
  this.plot(options, context.lineWidth / 2);
  }
 
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  context.fillStyle = options.fillColor || options.color;
 
  this.plot(options);
  context.restore();
  },
 
  plot: function (options, offset) {
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  i, x, y;
 
  for (i = data.length - 1; i > -1; --i) {
  y = data[i][1];
  if (y === null) continue;
 
  x = xScale(data[i][0]);
  y = yScale(y);
 
  if (x < 0 || x > options.width || y < 0 || y > options.height) continue;
 
  context.beginPath();
  if (offset) {
  context.arc(x, y + offset, options.radius, 0, Math.PI, false);
  } else {
  context.arc(x, y, options.radius, 0, 2 * Math.PI, true);
  if (options.fill) context.fill();
  }
  context.stroke();
  context.closePath();
  }
  }
  });
 
  /** Radar **/
  Flotr.addType('radar', {
  options: {
  show: false, // => setting to true will show radar chart, false will hide
  lineWidth: 2, // => line width in pixels
  fill: true, // => true to fill the area from the line to the x axis, false for (transparent) no fill
  fillOpacity: 0.4, // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
  radiusRatio: 0.90 // => ratio of the radar, against the plot size
  },
  draw: function (options) {
  var
  context = options.context,
  shadowSize = options.shadowSize;
 
  context.save();
  context.translate(options.width / 2, options.height / 2);
  context.lineWidth = options.lineWidth;
 
  // Shadow
  context.fillStyle = 'rgba(0,0,0,0.05)';
  context.strokeStyle = 'rgba(0,0,0,0.05)';
  this.plot(options, shadowSize / 2);
  context.strokeStyle = 'rgba(0,0,0,0.1)';
  this.plot(options, shadowSize / 4);
 
  // Chart
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
  this.plot(options);
 
  context.restore();
  },
  plot: function (options, offset) {
  var
  data = options.data,
  context = options.context,
  radius = Math.min(options.height, options.width) * options.radiusRatio / 2,
  step = 2 * Math.PI / data.length,
  angle = -Math.PI / 2,
  i, ratio;
 
  offset = offset || 0;
 
  context.beginPath();
  for (i = 0; i < data.length; ++i) {
  ratio = data[i][1] / this.max;
 
  context[i === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(i * step + angle) * radius * ratio + offset,
  Math.sin(i * step + angle) * radius * ratio + offset
  );
  }
  context.closePath();
  if (options.fill) context.fill();
  context.stroke();
  },
  extendYRange: function (axis, data) {
  this.max = Math.max(axis.max, this.max || -Number.MAX_VALUE);
  }
  });
 
  Flotr.addType('timeline', {
  options: {
  show: false,
  lineWidth: 1,
  barWidth: 0.2,
  fill: true,
  fillColor: null,
  fillOpacity: 0.4,
  centered: true
  },
 
  draw: function (options) {
 
  var
  context = options.context;
 
  context.save();
  context.lineJoin = 'miter';
  context.lineWidth = options.lineWidth;
  context.strokeStyle = options.color;
  context.fillStyle = options.fillStyle;
 
  this.plot(options);
 
  context.restore();
  },
 
  plot: function (options) {
 
  var
  data = options.data,
  context = options.context,
  xScale = options.xScale,
  yScale = options.yScale,
  barWidth = options.barWidth,
  lineWidth = options.lineWidth,
  i;
 
  Flotr._.each(data, function (timeline) {
 
  var
  x = timeline[0],
  y = timeline[1],
  w = timeline[2],
  h = barWidth,
 
  xt = Math.ceil(xScale(x)),
  wt = Math.ceil(xScale(x + w)) - xt,
  yt = Math.round(yScale(y)),
  ht = Math.round(yScale(y - h)) - yt,
 
  x0 = xt - lineWidth / 2,
  y0 = Math.round(yt - ht / 2) - lineWidth / 2;
 
  context.strokeRect(x0, y0, wt, ht);
  context.fillRect(x0, y0, wt, ht);
 
  });
  },
 
  extendRange: function (series) {
 
  var
  data = series.data,
  xa = series.xaxis,
  ya = series.yaxis,
  w = series.timeline.barWidth;
 
  if (xa.options.min === null)
  xa.min = xa.datamin - w / 2;
 
  if (xa.options.max === null) {
 
  var
  max = xa.max;
 
  Flotr._.each(data, function (timeline) {
  max = Math.max(max, timeline[0] + timeline[2]);
  }, this);
 
  xa.max = max + w / 2;
  }
 
  if (ya.options.min === null)
  ya.min = ya.datamin - w;
  if (ya.options.min === null)
  ya.max = ya.datamax + w;
  }
 
  });
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('crosshair', {
  options: {
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#FF0000', // => crosshair color
  hideCursor: true // => hide the cursor when the crosshair is shown
  },
  callbacks: {
  'flotr:mousemove': function (e, pos) {
  if (this.options.crosshair.mode) {
  this.crosshair.clearCrosshair();
  this.crosshair.drawCrosshair(pos);
  }
  }
  },
  /**
  * Draws the selection box.
  */
  drawCrosshair: function (pos) {
  var octx = this.octx,
  options = this.options.crosshair,
  plotOffset = this.plotOffset,
  x = plotOffset.left + pos.relX + 0.5,
  y = plotOffset.top + pos.relY + 0.5;
 
  if (pos.relX < 0 || pos.relY < 0 || pos.relX > this.plotWidth || pos.relY > this.plotHeight) {
  this.el.style.cursor = null;
  D.removeClass(this.el, 'flotr-crosshair');
  return;
  }
 
  if (options.hideCursor) {
  this.el.style.cursor = 'none';
  D.addClass(this.el, 'flotr-crosshair');
  }
 
  octx.save();
  octx.strokeStyle = options.color;
  octx.lineWidth = 1;
  octx.beginPath();
 
  if (options.mode.indexOf('x') != -1) {
  octx.moveTo(x, plotOffset.top);
  octx.lineTo(x, plotOffset.top + this.plotHeight);
  }
 
  if (options.mode.indexOf('y') != -1) {
  octx.moveTo(plotOffset.left, y);
  octx.lineTo(plotOffset.left + this.plotWidth, y);
  }
 
  octx.stroke();
  octx.restore();
  },
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearCrosshair: function () {
 
  var
  plotOffset = this.plotOffset,
  position = this.lastMousePos,
  context = this.octx;
 
  if (position) {
  context.clearRect(
  position.relX + plotOffset.left,
  plotOffset.top,
  1,
  this.plotHeight + 1
  );
  context.clearRect(
  plotOffset.left,
  position.relY + plotOffset.top,
  this.plotWidth + 1,
  1
  );
  }
  }
  });
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  function getImage(type, canvas, width, height) {
 
  // TODO add scaling for w / h
  var
  mime = 'image/' + type,
  data = canvas.toDataURL(mime),
  image = new Image();
  image.src = data;
  return image;
  }
 
  Flotr.addPlugin('download', {
 
  saveImage: function (type, width, height, replaceCanvas) {
  var image = null;
  if (Flotr.isIE && Flotr.isIE < 9) {
  image = '<html><body>' + this.canvas.firstChild.innerHTML + '</body></html>';
  return window.open().document.write(image);
  }
 
  if (type !== 'jpeg' && type !== 'png') return;
 
  image = getImage(type, this.canvas, width, height);
 
  if (_.isElement(image) && replaceCanvas) {
  this.download.restoreCanvas();
  D.hide(this.canvas);
  D.hide(this.overlay);
  D.setStyles({position: 'absolute'});
  D.insert(this.el, image);
  this.saveImageElement = image;
  } else {
  return window.open(image.src);
  }
  },
 
  restoreCanvas: function () {
  D.show(this.canvas);
  D.show(this.overlay);
  if (this.saveImageElement) this.el.removeChild(this.saveImageElement);
  this.saveImageElement = null;
  }
  });
 
  })();
 
  (function () {
 
  var E = Flotr.EventAdapter,
  _ = Flotr._;
 
  Flotr.addPlugin('graphGrid', {
 
  callbacks: {
  'flotr:beforedraw': function () {
  this.graphGrid.drawGrid();
  },
  'flotr:afterdraw': function () {
  this.graphGrid.drawOutline();
  }
  },
 
  drawGrid: function () {
 
  var
  ctx = this.ctx,
  options = this.options,
  grid = options.grid,
  verticalLines = grid.verticalLines,
  horizontalLines = grid.horizontalLines,
  minorVerticalLines = grid.minorVerticalLines,
  minorHorizontalLines = grid.minorHorizontalLines,
  plotHeight = this.plotHeight,
  plotWidth = this.plotWidth,
  a, v, i, j;
 
  if (verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines) {
  E.fire(this.el, 'flotr:beforegrid', [this.axes.x, this.axes.y, options, this]);
  }
  ctx.save();
  ctx.lineWidth = 1;
  ctx.strokeStyle = grid.tickColor;
 
  function circularHorizontalTicks(ticks) {
  for (i = 0; i < ticks.length; ++i) {
  var ratio = ticks[i].v / a.max;
  for (j = 0; j <= sides; ++j) {
  ctx[j === 0 ? 'moveTo' : 'lineTo'](
  Math.cos(j * coeff + angle) * radius * ratio,
  Math.sin(j * coeff + angle) * radius * ratio
  );
  }
  }
  }
 
  function drawGridLines(ticks, callback) {
  _.each(_.pluck(ticks, 'v'), function (v) {
  // Don't show lines on upper and lower bounds.
  if ((v <= a.min || v >= a.max) ||
  (v == a.min || v == a.max) && grid.outlineWidth)
  return;
  callback(Math.floor(a.d2p(v)) + ctx.lineWidth / 2);
  });
  }
 
  function drawVerticalLines(x) {
  ctx.moveTo(x, 0);
  ctx.lineTo(x, plotHeight);
  }
 
  function drawHorizontalLines(y) {
  ctx.moveTo(0, y);
  ctx.lineTo(plotWidth, y);
  }
 
  if (grid.circular) {
  ctx.translate(this.plotOffset.left + plotWidth / 2, this.plotOffset.top + plotHeight / 2);
  var radius = Math.min(plotHeight, plotWidth) * options.radar.radiusRatio / 2,
  sides = this.axes.x.ticks.length,
  coeff = 2 * (Math.PI / sides),
  angle = -Math.PI / 2;
 
  // Draw grid lines in vertical direction.
  ctx.beginPath();
 
  a = this.axes.y;
 
  if (horizontalLines) {
  circularHorizontalTicks(a.ticks);
  }
  if (minorHorizontalLines) {
  circularHorizontalTicks(a.minorTicks);
  }
 
  if (verticalLines) {
  _.times(sides, function (i) {
  ctx.moveTo(0, 0);
  ctx.lineTo(Math.cos(i * coeff + angle) * radius, Math.sin(i * coeff + angle) * radius);
  });
  }
  ctx.stroke();
  }
  else {
  ctx.translate(this.plotOffset.left, this.plotOffset.top);
 
  // Draw grid background, if present in options.
  if (grid.backgroundColor) {
  ctx.fillStyle = this.processColor(grid.backgroundColor, {x1: 0, y1: 0, x2: plotWidth, y2: plotHeight});
  ctx.fillRect(0, 0, plotWidth, plotHeight);
  }
 
  ctx.beginPath();
 
  a = this.axes.x;
  if (verticalLines) drawGridLines(a.ticks, drawVerticalLines);
  if (minorVerticalLines) drawGridLines(a.minorTicks, drawVerticalLines);
 
  a = this.axes.y;
  if (horizontalLines) drawGridLines(a.ticks, drawHorizontalLines);
  if (minorHorizontalLines) drawGridLines(a.minorTicks, drawHorizontalLines);
 
  ctx.stroke();
  }
 
  ctx.restore();
  if (verticalLines || minorVerticalLines ||
  horizontalLines || minorHorizontalLines) {
  E.fire(this.el, 'flotr:aftergrid', [this.axes.x, this.axes.y, options, this]);
  }
  },
 
  drawOutline: function () {
  var
  that = this,
  options = that.options,
  grid = options.grid,
  outline = grid.outline,
  ctx = that.ctx,
  backgroundImage = grid.backgroundImage,
  plotOffset = that.plotOffset,
  leftOffset = plotOffset.left,
  topOffset = plotOffset.top,
  plotWidth = that.plotWidth,
  plotHeight = that.plotHeight,
  v, img, src, left, top, globalAlpha;
 
  if (!grid.outlineWidth) return;
 
  ctx.save();
 
  if (grid.circular) {
  ctx.translate(leftOffset + plotWidth / 2, topOffset + plotHeight / 2);
  var radius = Math.min(plotHeight, plotWidth) * options.radar.radiusRatio / 2,
  sides = this.axes.x.ticks.length,
  coeff = 2 * (Math.PI / sides),
  angle = -Math.PI / 2;
 
  // Draw axis/grid border.
  ctx.beginPath();
  ctx.lineWidth = grid.outlineWidth;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'round';
 
  for (i = 0; i <= sides; ++i) {
  ctx[i === 0 ? 'moveTo' : 'lineTo'](Math.cos(i * coeff + angle) * radius, Math.sin(i * coeff + angle) * radius);
  }
  //ctx.arc(0, 0, radius, 0, Math.PI*2, true);
 
  ctx.stroke();
  }
  else {
  ctx.translate(leftOffset, topOffset);
 
  // Draw axis/grid border.
  var lw = grid.outlineWidth,
  orig = 0.5 - lw + ((lw + 1) % 2 / 2),
  lineTo = 'lineTo',
  moveTo = 'moveTo';
  ctx.lineWidth = lw;
  ctx.strokeStyle = grid.color;
  ctx.lineJoin = 'miter';
  ctx.beginPath();
  ctx.moveTo(orig, orig);
  plotWidth = plotWidth - (lw / 2) % 1;
  plotHeight = plotHeight + lw / 2;
  ctx[outline.indexOf('n') !== -1 ? lineTo : moveTo](plotWidth, orig);
  ctx[outline.indexOf('e') !== -1 ? lineTo : moveTo](plotWidth, plotHeight);
  ctx[outline.indexOf('s') !== -1 ? lineTo : moveTo](orig, plotHeight);
  ctx[outline.indexOf('w') !== -1 ? lineTo : moveTo](orig, orig);
  ctx.stroke();
  ctx.closePath();
  }
 
  ctx.restore();
 
  if (backgroundImage) {
 
  src = backgroundImage.src || backgroundImage;
  left = (parseInt(backgroundImage.left, 10) || 0) + plotOffset.left;
  top = (parseInt(backgroundImage.top, 10) || 0) + plotOffset.top;
  img = new Image();
 
  img.onload = function () {
  ctx.save();
  if (backgroundImage.alpha) ctx.globalAlpha = backgroundImage.alpha;
  ctx.globalCompositeOperation = 'destination-over';
  ctx.drawImage(img, 0, 0, img.width, img.height, left, top, plotWidth, plotHeight);
  ctx.restore();
  };
 
  img.src = src;
  }
  }
  });
 
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._,
  flotr = Flotr,
  S_MOUSETRACK = 'opacity:0.7;background-color:#000;color:#fff;display:none;position:absolute;padding:2px 8px;-moz-border-radius:4px;border-radius:4px;white-space:nowrap;';
 
  Flotr.addPlugin('hit', {
  callbacks: {
  'flotr:mousemove': function (e, pos) {
  this.hit.track(pos);
  },
  'flotr:click': function (pos) {
  this.hit.track(pos);
  },
  'flotr:mouseout': function () {
  this.hit.clearHit();
  }
  },
  track: function (pos) {
  if (this.options.mouse.track || _.any(this.series, function (s) {
  return s.mouse && s.mouse.track;
  })) {
  this.hit.hit(pos);
  }
  },
  /**
  * Try a method on a graph type. If the method exists, execute it.
  * @param {Object} series
  * @param {String} method Method name.
  * @param {Array} args Arguments applied to method.
  * @return executed successfully or failed.
  */
  executeOnType: function (s, method, args) {
  var
  success = false,
  options;
 
  if (!_.isArray(s)) s = [s];
 
  function e(s, index) {
  _.each(_.keys(flotr.graphTypes), function (type) {
  if (s[type] && s[type].show && this[type][method]) {
  options = this.getOptions(s, type);
 
  options.fill = !!s.mouse.fillColor;
  options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  options.color = s.mouse.lineColor;
  options.context = this.octx;
  options.index = index;
 
  if (args) options.args = args;
  this[type][method].call(this[type], options);
  success = true;
  }
  }, this);
  }
 
  _.each(s, e, this);
 
  return success;
  },
  /**
  * Updates the mouse tracking point on the overlay.
  */
  drawHit: function (n) {
  var octx = this.octx,
  s = n.series;
 
  if (s.mouse.lineColor) {
  octx.save();
  octx.lineWidth = (s.points ? s.points.lineWidth : 1);
  octx.strokeStyle = s.mouse.lineColor;
  octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
  octx.translate(this.plotOffset.left, this.plotOffset.top);
 
  if (!this.hit.executeOnType(s, 'drawHit', n)) {
  var xa = n.xaxis,
  ya = n.yaxis;
 
  octx.beginPath();
  // TODO fix this (points) should move to general testable graph mixin
  octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
  octx.fill();
  octx.stroke();
  octx.closePath();
  }
  octx.restore();
  this.clip(octx);
  }
  this.prevHit = n;
  },
  /**
  * Removes the mouse tracking point from the overlay.
  */
  clearHit: function () {
  var prev = this.prevHit,
  octx = this.octx,
  plotOffset = this.plotOffset;
  octx.save();
  octx.translate(plotOffset.left, plotOffset.top);
  if (prev) {
  if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
  // TODO fix this (points) should move to general testable graph mixin
  var
  s = prev.series,
  lw = (s.points ? s.points.lineWidth : 1);
  offset = (s.points.radius || s.mouse.radius) + lw;
  octx.clearRect(
  prev.xaxis.d2p(prev.x) - offset,
  prev.yaxis.d2p(prev.y) - offset,
  offset * 2,
  offset * 2
  );
  }
  D.hide(this.mouseTrack);
  this.prevHit = null;
  }
  octx.restore();
  },
  /**
  * Retrieves the nearest data point from the mouse cursor. If it's within
  * a certain range, draw a point on the overlay canvas and display the x and y
  * value of the data.
  * @param {Object} mouse - Object that holds the relative x and y coordinates of the cursor.
  */
  hit: function (mouse) {
 
  var
  options = this.options,
  prevHit = this.prevHit,
  closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis;
 
  if (this.series.length === 0) return;
 
  // Nearest data element.
  // dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
  // xaxis, yaxis, series, index, seriesIndex
  n = {
  relX: mouse.relX,
  relY: mouse.relY,
  absX: mouse.absX,
  absY: mouse.absY
  };
 
  if (options.mouse.trackY && !options.mouse.trackAll &&
  this.hit.executeOnType(this.series, 'hit', [mouse, n])) {
 
  if (!_.isUndefined(n.seriesIndex)) {
  series = this.series[n.seriesIndex];
  n.series = series;
  n.mouse = series.mouse;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  }
  } else {
 
  closest = this.hit.closest(mouse);
 
  if (closest) {
 
  closest = options.mouse.trackY ? closest.point : closest.x;
  seriesIndex = closest.seriesIndex;
  series = this.series[seriesIndex];
  xaxis = series.xaxis;
  yaxis = series.yaxis;
  sensibility = 2 * series.mouse.sensibility;
 
  if
  (options.mouse.trackAll ||
  (closest.distanceX < sensibility / xaxis.scale &&
  (!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale))) {
  n.series = series;
  n.xaxis = series.xaxis;
  n.yaxis = series.yaxis;
  n.mouse = series.mouse;
  n.x = closest.x;
  n.y = closest.y;
  n.dist = closest.distance;
  n.index = closest.dataIndex;
  n.seriesIndex = seriesIndex;
  }
  }
  }
 
  if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
  this.hit.clearHit();
  if (n.series && n.mouse && n.mouse.track) {
  this.hit.drawMouseTrack(n);
  this.hit.drawHit(n);
  Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
  }
  }
  },
 
  closest: function (mouse) {
 
  var
  series = this.series,
  options = this.options,
  relX = mouse.relX,
  relY = mouse.relY,
  compare = Number.MAX_VALUE,
  compareX = Number.MAX_VALUE,
  closest = {},
  closestX = {},
  check = false,
  serie, data,
  distance, distanceX, distanceY,
  mouseX, mouseY,
  x, y, i, j;
 
  function setClosest(o) {
  o.distance = distance;
  o.distanceX = distanceX;
  o.distanceY = distanceY;
  o.seriesIndex = i;
  o.dataIndex = j;
  o.x = x;
  o.y = y;
  }
 
  for (i = 0; i < series.length; i++) {
 
  serie = series[i];
  data = serie.data;
  mouseX = serie.xaxis.p2d(relX);
  mouseY = serie.yaxis.p2d(relY);
 
  if (data.length) check = true;
 
  for (j = data.length; j--;) {
 
  x = data[j][0];
  y = data[j][1];
 
  if (x === null || y === null) continue;
 
  // don't check if the point isn't visible in the current range
  if (x < serie.xaxis.min || x > serie.xaxis.max) continue;
 
  distanceX = Math.abs(x - mouseX);
  distanceY = Math.abs(y - mouseY);
 
  // Skip square root for speed
  distance = distanceX * distanceX + distanceY * distanceY;
 
  if (distance < compare) {
  compare = distance;
  setClosest(closest);
  }
 
  if (distanceX < compareX) {
  compareX = distanceX;
  setClosest(closestX);
  }
  }
  }
 
  return check ? {
  point: closest,
  x: closestX
  } : false;
  },
 
  drawMouseTrack: function (n) {
 
  var
  pos = '',
  s = n.series,
  p = n.mouse.position,
  m = n.mouse.margin,
  elStyle = S_MOUSETRACK,
  mouseTrack = this.mouseTrack,
  plotOffset = this.plotOffset,
  left = plotOffset.left,
  right = plotOffset.right,
  bottom = plotOffset.bottom,
  top = plotOffset.top,
  decimals = n.mouse.trackDecimals,
  options = this.options;
 
  // Create
  if (!mouseTrack) {
  mouseTrack = D.node('<div class="flotr-mouse-value"></div>');
  this.mouseTrack = mouseTrack;
  D.insert(this.el, mouseTrack);
  }
 
  if (!n.mouse.relative) { // absolute to the canvas
 
  if (p.charAt(0) == 'n') pos += 'top:' + (m + top) + 'px;bottom:auto;';
  else if (p.charAt(0) == 's') pos += 'bottom:' + (m + bottom) + 'px;top:auto;';
  if (p.charAt(1) == 'e') pos += 'right:' + (m + right) + 'px;left:auto;';
  else if (p.charAt(1) == 'w') pos += 'left:' + (m + left) + 'px;right:auto;';
 
  // Bars
  } else if (s.bars.show) {
  pos += 'bottom:' + (m - top - n.yaxis.d2p(n.y / 2) + this.canvasHeight) + 'px;top:auto;';
  pos += 'left:' + (m + left + n.xaxis.d2p(n.x - options.bars.barWidth / 2)) + 'px;right:auto;';
 
  // Pie
  } else if (s.pie.show) {
  var center = {
  x: (this.plotWidth) / 2,
  y: (this.plotHeight) / 2
  },
  radius = (Math.min(this.canvasWidth, this.canvasHeight) * s.pie.sizeRatio) / 2,
  bisection = n.sAngle < n.eAngle ? (n.sAngle + n.eAngle) / 2 : (n.sAngle + n.eAngle + 2 * Math.PI) / 2;
 
  pos += 'bottom:' + (m - top - center.y - Math.sin(bisection) * radius / 2 + this.canvasHeight) + 'px;top:auto;';
  pos += 'left:' + (m + left + center.x + Math.cos(bisection) * radius / 2) + 'px;right:auto;';
 
  // Default
  } else {
  if (p.charAt(0) == 'n') pos += 'bottom:' + (m - top - n.yaxis.d2p(n.y) + this.canvasHeight) + 'px;top:auto;';
  else if (p.charAt(0) == 's') pos += 'top:' + (m + top + n.yaxis.d2p(n.y)) + 'px;bottom:auto;';
  if (p.charAt(1) == 'e') pos += 'left:' + (m + left + n.xaxis.d2p(n.x)) + 'px;right:auto;';
  else if (p.charAt(1) == 'w') pos += 'right:' + (m - left - n.xaxis.d2p(n.x) + this.canvasWidth) + 'px;left:auto;';
  }
 
  elStyle += pos;
  mouseTrack.style.cssText = elStyle;
 
  if (!decimals || decimals < 0) decimals = 0;
 
  mouseTrack.innerHTML = n.mouse.trackFormatter({
  x: n.x.toFixed(decimals),
  y: n.y.toFixed(decimals),
  series: n.series,
  index: n.index,
  nearest: n,
  fraction: n.fraction
  });
 
  D.show(mouseTrack);
  }
 
  });
  })();
 
  /**
  * Selection Handles Plugin
  *
  *
  * Options
  * show - True enables the handles plugin.
  * drag - Left and Right drag handles
  * scroll - Scrolling handle
  */
  (function () {
 
  function isLeftClick(e, type) {
  return (e.which ? (e.which === 1) : (e.button === 0 || e.button === 1));
  }
 
  function boundX(x, graph) {
  return Math.min(Math.max(0, x), graph.plotWidth - 1);
  }
 
  function boundY(y, graph) {
  return Math.min(Math.max(0, y), graph.plotHeight);
  }
 
  var
  D = Flotr.DOM,
  E = Flotr.EventAdapter,
  _ = Flotr._;
 
 
  Flotr.addPlugin('selection', {
 
  options: {
  pinchOnly: null, // Only select on pinch
  mode: null, // => one of null, 'x', 'y' or 'xy'
  color: '#B6D9FF', // => selection box color
  fps: 20 // => frames-per-second
  },
 
  callbacks: {
  'flotr:mouseup': function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (selection.interval) clearInterval(selection.interval);
 
  if (this.multitouches) {
  selection.updateSelection();
  } else if (!options.pinchOnly) {
  selection.setSelectionPos(selection.selection.second, pointer);
  }
  selection.clearSelection();
 
  if (selection.selecting && selection.selectionIsSane()) {
  selection.drawSelection();
  selection.fireSelectEvent();
  this.ignoreClick = true;
  }
  },
  'flotr:mousedown': function (event) {
 
  var
  options = this.options.selection,
  selection = this.selection,
  pointer = this.getEventPosition(event);
 
  if (!options || !options.mode) return;
  if (!options.mode || (!isLeftClick(event) && _.isUndefined(event.touches))) return;
  if (!options.pinchOnly) selection.setSelectionPos(selection.selection.first, pointer);
  if (selection.interval) clearInterval(selection.interval);
 
  this.lastMousePos.pageX = null;
  selection.selecting = false;
  selection.interval = setInterval(
  _.bind(selection.updateSelection, this),
  1000 / options.fps
  );
  },
  'flotr:destroy': function (event) {
  clearInterval(this.selection.interval);
  }
  },
 
  // TODO This isn't used. Maybe it belongs in the draw area and fire select event methods?
  getArea: function () {
 
  var s = this.selection.selection,
  first = s.first,
  second = s.second;
 
  return {
  x1: Math.min(first.x, second.x),
  x2: Math.max(first.x, second.x),
  y1: Math.min(first.y, second.y),
  y2: Math.max(first.y, second.y)
  };
  },
 
  selection: {first: {x: -1, y: -1}, second: {x: -1, y: -1}},
  prevSelection: null,
  interval: null,
 
  /**
  * Fires the 'flotr:select' event when the user made a selection.
  */
  fireSelectEvent: function (name) {
  var a = this.axes,
  s = this.selection.selection,
  x1, x2, y1, y2;
 
  name = name || 'select';
 
  x1 = a.x.p2d(s.first.x);
  x2 = a.x.p2d(s.second.x);
  y1 = a.y.p2d(s.first.y);
  y2 = a.y.p2d(s.second.y);
 
  E.fire(this.el, 'flotr:' + name, [
  {
  x1: Math.min(x1, x2),
  y1: Math.min(y1, y2),
  x2: Math.max(x1, x2),
  y2: Math.max(y1, y2),
  xfirst: x1, xsecond: x2, yfirst: y1, ysecond: y2
  },
  this
  ]);
  },
 
  /**
  * Allows the user the manually select an area.
  * @param {Object} area - Object with coordinates to select.
  */
  setSelection: function (area, preventEvent) {
  var options = this.options,
  xa = this.axes.x,
  ya = this.axes.y,
  vertScale = ya.scale,
  hozScale = xa.scale,
  selX = options.selection.mode.indexOf('x') != -1,
  selY = options.selection.mode.indexOf('y') != -1,
  s = this.selection.selection;
 
  this.selection.clearSelection();
 
  s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
  s.second.y = boundY((selX && !selY) ? this.plotHeight - 1 : (ya.max - area.y2) * vertScale, this);
  s.first.x = boundX((selY && !selX) ? 0 : area.x1, this);
  s.second.x = boundX((selY && !selX) ? this.plotWidth : area.x2, this);
 
  this.selection.drawSelection();
  if (!preventEvent)
  this.selection.fireSelectEvent();
  },
 
  /**
  * Calculates the position of the selection.
  * @param {Object} pos - Position object.
  * @param {Event} event - Event object.
  */
  setSelectionPos: function (pos, pointer) {
  var mode = this.options.selection.mode,
  selection = this.selection.selection;
 
  if (mode.indexOf('x') == -1) {
  pos.x = (pos == selection.first) ? 0 : this.plotWidth;
  } else {
  pos.x = boundX(pointer.relX, this);
  }
 
  if (mode.indexOf('y') == -1) {
  pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
  } else {
  pos.y = boundY(pointer.relY, this);
  }
  },
  /**
  * Draws the selection box.
  */
  drawSelection: function () {
 
  this.selection.fireSelectEvent('selecting');
 
  var s = this.selection.selection,
  octx = this.octx,
  options = this.options,
  plotOffset = this.plotOffset,
  prevSelection = this.selection.prevSelection;
 
  if (prevSelection &&
  s.first.x == prevSelection.first.x &&
  s.first.y == prevSelection.first.y &&
  s.second.x == prevSelection.second.x &&
  s.second.y == prevSelection.second.y) {
  return;
  }
 
  octx.save();
  octx.strokeStyle = this.processColor(options.selection.color, {opacity: 0.8});
  octx.lineWidth = 1;
  octx.lineJoin = 'miter';
  octx.fillStyle = this.processColor(options.selection.color, {opacity: 0.4});
 
  this.selection.prevSelection = {
  first: { x: s.first.x, y: s.first.y },
  second: { x: s.second.x, y: s.second.y }
  };
 
  var x = Math.min(s.first.x, s.second.x),
  y = Math.min(s.first.y, s.second.y),
  w = Math.abs(s.second.x - s.first.x),
  h = Math.abs(s.second.y - s.first.y);
 
  octx.fillRect(x + plotOffset.left + 0.5, y + plotOffset.top + 0.5, w, h);
  octx.strokeRect(x + plotOffset.left + 0.5, y + plotOffset.top + 0.5, w, h);
  octx.restore();
  },
 
  /**
  * Updates (draws) the selection box.
  */
  updateSelection: function () {
  if (!this.lastMousePos.pageX) return;
 
  this.selection.selecting = true;
 
  if (this.multitouches) {
  this.selection.setSelectionPos(this.selection.selection.first, this.getEventPosition(this.multitouches[0]));
  this.selection.setSelectionPos(this.selection.selection.second, this.getEventPosition(this.multitouches[1]));
  } else if (this.options.selection.pinchOnly) {
  return;
  } else {
  this.selection.setSelectionPos(this.selection.selection.second, this.lastMousePos);
  }
 
  this.selection.clearSelection();
 
  if (this.selection.selectionIsSane()) {
  this.selection.drawSelection();
  }
  },
 
  /**
  * Removes the selection box from the overlay canvas.
  */
  clearSelection: function () {
  if (!this.selection.prevSelection) return;
 
  var prevSelection = this.selection.prevSelection,
  lw = 1,
  plotOffset = this.plotOffset,
  x = Math.min(prevSelection.first.x, prevSelection.second.x),
  y = Math.min(prevSelection.first.y, prevSelection.second.y),
  w = Math.abs(prevSelection.second.x - prevSelection.first.x),
  h = Math.abs(prevSelection.second.y - prevSelection.first.y);
 
  this.octx.clearRect(x + plotOffset.left - lw + 0.5,
  y + plotOffset.top - lw,
  w + 2 * lw + 0.5,
  h + 2 * lw + 0.5);
 
  this.selection.prevSelection = null;
  },
  /**
  * Determines whether or not the selection is sane and should be drawn.
  * @return {Boolean} - True when sane, false otherwise.
  */
  selectionIsSane: function () {
  var s = this.selection.selection;
  return Math.abs(s.second.x - s.first.x) >= 5 ||
  Math.abs(s.second.y - s.first.y) >= 5;
  }
 
  });
 
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('labels', {
 
  callbacks: {
  'flotr:afterdraw': function () {
  this.labels.draw();
  }
  },
 
  draw: function () {
  // Construct fixed width label boxes, which can be styled easily.
  var
  axis, tick, left, top, xBoxWidth,
  radius, sides, coeff, angle,
  div, i, html = '',
  noLabels = 0,
  options = this.options,
  ctx = this.ctx,
  a = this.axes,
  style = { size: options.fontSize };
 
  for (i = 0; i < a.x.ticks.length; ++i) {
  if (a.x.ticks[i].label) {
  ++noLabels;
  }
  }
  xBoxWidth = this.plotWidth / noLabels;
 
  if (options.grid.circular) {
  ctx.save();
  ctx.translate(this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top + this.plotHeight / 2);
 
  radius = this.plotHeight * options.radar.radiusRatio / 2 + options.fontSize;
  sides = this.axes.x.ticks.length;
  coeff = 2 * (Math.PI / sides);
  angle = -Math.PI / 2;
 
  drawLabelCircular(this, a.x, false);
  drawLabelCircular(this, a.x, true);
  drawLabelCircular(this, a.y, false);
  drawLabelCircular(this, a.y, true);
  ctx.restore();
  }
 
  if (!options.HtmlText && this.textEnabled) {
  drawLabelNoHtmlText(this, a.x, 'center', 'top');
  drawLabelNoHtmlText(this, a.x2, 'center', 'bottom');
  drawLabelNoHtmlText(this, a.y, 'right', 'middle');
  drawLabelNoHtmlText(this, a.y2, 'left', 'middle');
 
  } else if ((
  a.x.options.showLabels ||
  a.x2.options.showLabels ||
  a.y.options.showLabels ||
  a.y2.options.showLabels) && !options.grid.circular
  ) {
 
  html = '';
 
  drawLabelHtml(this, a.x);
  drawLabelHtml(this, a.x2);
  drawLabelHtml(this, a.y);
  drawLabelHtml(this, a.y2);
 
  ctx.stroke();
  ctx.restore();
  div = D.create('div');
  D.setStyles(div, {
  fontSize: 'smaller',
  color: options.grid.color
  });
  div.className = 'flotr-labels';
  D.insert(this.el, div);
  D.insert(div, html);
  }
 
  function drawLabelCircular(graph, axis, minorTicks) {
  var
  ticks = minorTicks ? axis.minorTicks : axis.ticks,
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color: axis.options.color || options.grid.color,
  angle: Flotr.toRad(axis.options.labelsAngle),
  textBaseline: 'middle'
  };
 
  for (i = 0; i < ticks.length &&
  (minorTicks ? axis.options.showMinorLabels : axis.options.showLabels); ++i) {
  tick = ticks[i];
  tick.label += '';
  if (!tick.label || !tick.label.length) {
  continue;
  }
 
  x = Math.cos(i * coeff + angle) * radius;
  y = Math.sin(i * coeff + angle) * radius;
 
  style.textAlign = isX ? (Math.abs(x) < 0.1 ? 'center' : (x < 0 ? 'right' : 'left')) : 'left';
 
  Flotr.drawText(
  ctx, tick.label,
  isX ? x : 3,
  isX ? y : -(axis.ticks[i].v / axis.max) * (radius - options.fontSize),
  style
  );
  }
  }
 
  function drawLabelNoHtmlText(graph, axis, textAlign, textBaseline) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  style, offset;
 
  style = {
  color: axis.options.color || options.grid.color,
  textAlign: textAlign,
  textBaseline: textBaseline,
  angle: Flotr.toRad(axis.options.labelsAngle)
  };
  style = Flotr.getBestTextAlign(style.angle, style);
 
  for (i = 0; i < axis.ticks.length && continueShowingLabels(axis); ++i) {
 
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length) {
  continue;
  }
 
  offset = axis.d2p(tick.v);
  if (offset < 0 ||
  offset > (isX ? graph.plotWidth : graph.plotHeight)) {
  continue;
  }
 
  Flotr.drawText(
  ctx, tick.label,
  leftOffset(graph, isX, isFirst, offset),
  topOffset(graph, isX, isFirst, offset),
  style
  );
 
  // Only draw on axis y2
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = style.color;
  ctx.beginPath();
  ctx.moveTo(graph.plotOffset.left + graph.plotWidth - 8, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.lineTo(graph.plotOffset.left + graph.plotWidth, graph.plotOffset.top + axis.d2p(tick.v));
  ctx.stroke();
  ctx.restore();
  }
  }
 
  function continueShowingLabels(axis) {
  return axis.options.showLabels && axis.used;
  }
 
  function leftOffset(graph, isX, isFirst, offset) {
  return graph.plotOffset.left +
  (isX ? offset :
  (isFirst ?
  -options.grid.labelMargin :
  options.grid.labelMargin + graph.plotWidth));
  }
 
  function topOffset(graph, isX, isFirst, offset) {
  return graph.plotOffset.top +
  (isX ? options.grid.labelMargin : offset) +
  ((isX && isFirst) ? graph.plotHeight : 0);
  }
  }
 
  function drawLabelHtml(graph, axis) {
  var
  isX = axis.orientation === 1,
  isFirst = axis.n === 1,
  name = '',
  left, style, top,
  offset = graph.plotOffset;
 
  if (!isX && !isFirst) {
  ctx.save();
  ctx.strokeStyle = axis.options.color || options.grid.color;
  ctx.beginPath();
  }
 
  if (axis.options.showLabels && (isFirst ? true : axis.used)) {
  for (i = 0; i < axis.ticks.length; ++i) {
  tick = axis.ticks[i];
  if (!tick.label || !tick.label.length ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) < 0) ||
  ((isX ? offset.left : offset.top) + axis.d2p(tick.v) > (isX ? graph.canvasWidth : graph.canvasHeight))) {
  continue;
  }
  top = offset.top +
  (isX ?
  ((isFirst ? 1 : -1 ) * (graph.plotHeight + options.grid.labelMargin)) :
  axis.d2p(tick.v) - axis.maxLabel.height / 2);
  left = isX ? (offset.left + axis.d2p(tick.v) - xBoxWidth / 2) : 0;
 
  name = '';
  if (i === 0) {
  name = ' first';
  } else if (i === axis.ticks.length - 1) {
  name = ' last';
  }
  name += isX ? ' flotr-grid-label-x' : ' flotr-grid-label-y';
 
  html += [
  '<div style="position:absolute; text-align:' + (isX ? 'center' : 'right') + '; ',
  'top:' + top + 'px; ',
  ((!isX && !isFirst) ? 'right:' : 'left:') + left + 'px; ',
  'width:' + (isX ? xBoxWidth : ((isFirst ? offset.left : offset.right) - options.grid.labelMargin)) + 'px; ',
  axis.options.color ? ('color:' + axis.options.color + '; ') : ' ',
  '" class="flotr-grid-label' + name + '">' + tick.label + '</div>'
  ].join(' ');
 
  if (!isX && !isFirst) {
  ctx.moveTo(offset.left + graph.plotWidth - 8, offset.top + axis.d2p(tick.v));
  ctx.lineTo(offset.left + graph.plotWidth, offset.top + axis.d2p(tick.v));
  }
  }
  }
  }
  }
 
  });
  })();
 
  (function () {
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('legend', {
  options: {
  show: true, // => setting to true will show the legend, hide otherwise
  noColumns: 1, // => number of colums in legend table // @todo: doesn't work for HtmlText = false
  labelFormatter: function (v) {
  return v;
  }, // => fn: string -> string
  labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
  labelBoxWidth: 14,
  labelBoxHeight: 10,
  labelBoxMargin: 5,
  labelBoxOpacity: 0.4,
  container: null, // => container (as jQuery object) to put legend in, null means default on top of graph
  position: 'nw', // => position of default legend container within plot
  margin: 5, // => distance from grid edge to default legend container within plot
  backgroundColor: null, // => null means auto-detect
  backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
  },
  callbacks: {
  'flotr:afterinit': function () {
  this.legend.insertLegend();
  }
  },
  /**
  * Adds a legend div to the canvas container or draws it on the canvas.
  */
  insertLegend: function () {
 
  if (!this.options.legend.show)
  return;
 
  var series = this.series,
  plotOffset = this.plotOffset,
  options = this.options,
  legend = options.legend,
  fragments = [],
  rowStarted = false,
  ctx = this.ctx,
  itemCount = _.filter(series,function (s) {
  return (s.label && !s.hide);
  }).length,
  p = legend.position,
  m = legend.margin,
  i, label, color;
 
  if (itemCount) {
  if (!options.HtmlText && this.textEnabled && !legend.container) {
  var style = {
  size: options.fontSize * 1.1,
  color: options.grid.color
  };
 
  var lbw = legend.labelBoxWidth,
  lbh = legend.labelBoxHeight,
  lbm = legend.labelBoxMargin,
  offsetX = plotOffset.left + m,
  offsetY = plotOffset.top + m;
 
  // We calculate the labels' max width
  var labelMaxWidth = 0;
  for (i = series.length - 1; i > -1; --i) {
  if (!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
  labelMaxWidth = Math.max(labelMaxWidth, this._text.measureText(label, style).width);
  }
 
  var legendWidth = Math.round(lbw + lbm * 3 + labelMaxWidth),
  legendHeight = Math.round(itemCount * (lbm + lbh) + lbm);
 
  if (p.charAt(0) == 's') offsetY = plotOffset.top + this.plotHeight - (m + legendHeight);
  if (p.charAt(1) == 'e') offsetX = plotOffset.left + this.plotWidth - (m + legendWidth);
 
  // Legend box
  color = this.processColor(legend.backgroundColor || 'rgb(240,240,240)', {opacity: legend.backgroundOpacity || 0.1});
 
  ctx.fillStyle = color;
  ctx.fillRect(offsetX, offsetY, legendWidth, legendHeight);
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.strokeRect(Flotr.toPixel(offsetX), Flotr.toPixel(offsetY), legendWidth, legendHeight);
 
  // Legend labels
  var x = offsetX + lbm;
  var y = offsetY + lbm;
  for (i = 0; i < series.length; i++) {
  if (!series[i].label || series[i].hide) continue;
  label = legend.labelFormatter(series[i].label);
 
  ctx.fillStyle = series[i].color;
  ctx.fillRect(x, y, lbw - 1, lbh - 1);
 
  ctx.strokeStyle = legend.labelBoxBorderColor;
  ctx.lineWidth = 1;
  ctx.strokeRect(Math.ceil(x) - 1.5, Math.ceil(y) - 1.5, lbw + 2, lbh + 2);
 
  // Legend text
  Flotr.drawText(ctx, label, x + lbw + lbm, y + lbh, style);
 
  y += lbh + lbm;
  }
  }
  else {
  for (i = 0; i < series.length; ++i) {
  if (!series[i].label || series[i].hide) continue;
 
  if (i % legend.noColumns === 0) {
  fragments.push(rowStarted ? '</tr><tr>' : '<tr>');
  rowStarted = true;
  }
 
  // @TODO remove requirement on bars
  var s = series[i],
  boxWidth = legend.labelBoxWidth,
  boxHeight = legend.labelBoxHeight,
  opacityValue = (s.bars ? s.bars.fillOpacity : legend.labelBoxOpacity),
  opacity = 'opacity:' + opacityValue + ';filter:alpha(opacity=' + opacityValue * 100 + ');';
 
  label = legend.labelFormatter(s.label);
  color = 'background-color:' + ((s.bars && s.bars.show && s.bars.fillColor && s.bars.fill) ? s.bars.fillColor : s.color) + ';';
 
  fragments.push(
  '<td class="flotr-legend-color-box">',
  '<div style="border:1px solid ', legend.labelBoxBorderColor, ';padding:1px">',
  '<div style="width:', (boxWidth - 1), 'px;height:', (boxHeight - 1), 'px;border:1px solid ', series[i].color, '">', // Border
  '<div style="width:', boxWidth, 'px;height:', boxHeight, 'px;', 'opacity:.4;', color, '"></div>', // Background
  '</div>',
  '</div>',
  '</td>',
  '<td class="flotr-legend-label">', label, '</td>'
  );
  }
  if (rowStarted) fragments.push('</tr>');
 
  if (fragments.length > 0) {
  var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join('') + '</table>';
  if (legend.container) {
  D.insert(legend.container, table);
  }
  else {
  var styles = {position: 'absolute', 'z-index': 2};
 
  if (p.charAt(0) == 'n') {
  styles.top = (m + plotOffset.top) + 'px';
  styles.bottom = 'auto';
  }
  else if (p.charAt(0) == 's') {
  styles.bottom = (m + plotOffset.bottom) + 'px';
  styles.top = 'auto';
  }
  if (p.charAt(1) == 'e') {
  styles.right = (m + plotOffset.right) + 'px';
  styles.left = 'auto';
  }
  else if (p.charAt(1) == 'w') {
  styles.left = (m + plotOffset.left) + 'px';
  styles.right = 'auto';
  }
 
  var div = D.create('div'), size;
  div.className = 'flotr-legend';
  D.setStyles(div, styles);
  D.insert(div, table);
  D.insert(this.el, div);
 
  if (!legend.backgroundOpacity)
  return;
 
  var c = legend.backgroundColor || options.grid.backgroundColor || '#ffffff';
 
  _.extend(styles, D.size(div), {
  'backgroundColor': c,
  'z-index': 1
  });
  styles.width += 'px';
  styles.height += 'px';
 
  // Put in the transparent background separately to avoid blended labels and
  div = D.create('div');
  div.className = 'flotr-legend-bg';
  D.setStyles(div, styles);
  D.opacity(div, legend.backgroundOpacity);
  D.insert(div, ' ');
  D.insert(this.el, div);
  }
  }
  }
  }
  }
  });
  })();
 
  /** Spreadsheet **/
  (function () {
 
  function getRowLabel(value) {
  if (this.options.spreadsheet.tickFormatter) {
  //TODO maybe pass the xaxis formatter to the custom tick formatter as an opt-out?
  return this.options.spreadsheet.tickFormatter(value);
  }
  else {
  var t = _.find(this.axes.x.ticks, function (t) {
  return t.v == value;
  });
  if (t) {
  return t.label;
  }
  return value;
  }
  }
 
  var
  D = Flotr.DOM,
  _ = Flotr._;
 
  Flotr.addPlugin('spreadsheet', {
  options: {
  show: false, // => show the data grid using two tabs
  tabGraphLabel: 'Graph',
  tabDataLabel: 'Data',
  toolbarDownload: 'Download CSV', // @todo: add better language support
  toolbarSelectAll: 'Select all',
  csvFileSeparator: ',',
  decimalSeparator: '.',
  tickFormatter: null,
  initialTab: 'graph'
  },
  /**
  * Builds the tabs in the DOM
  */
  callbacks: {
  'flotr:afterconstruct': function () {
  // @TODO necessary?
  //this.el.select('.flotr-tabs-group,.flotr-datagrid-container').invoke('remove');
 
  if (!this.options.spreadsheet.show) return;
 
  var ss = this.spreadsheet,
  container = D.node('<div class="flotr-tabs-group" style="position:absolute;left:0px;width:' + this.canvasWidth + 'px"></div>'),
  graph = D.node('<div style="float:left" class="flotr-tab selected">' + this.options.spreadsheet.tabGraphLabel + '</div>'),
  data = D.node('<div style="float:left" class="flotr-tab">' + this.options.spreadsheet.tabDataLabel + '</div>'),
  offset;
 
  ss.tabsContainer = container;
  ss.tabs = { graph: graph, data: data };
 
  D.insert(container, graph);
  D.insert(container, data);
  D.insert(this.el, container);
 
  offset = D.size(data).height + 2;
  this.plotOffset.bottom += offset;
 
  D.setStyles(container, {top: this.canvasHeight - offset + 'px'});
 
  this.
  observe(graph, 'click',function () {
  ss.showTab('graph');
  }).
  observe(data, 'click', function () {
  ss.showTab('data');
  });
  if (this.options.spreadsheet.initialTab !== 'graph') {
  ss.showTab(this.options.spreadsheet.initialTab);
  }
  }
  },
  /**
  * Builds a matrix of the data to make the correspondance between the x values and the y values :
  * X value => Y values from the axes
  * @return {Array} The data grid
  */
  loadDataGrid: function () {
  if (this.seriesData) return this.seriesData;
 
  var s = this.series,
  rows = {};
 
  /* The data grid is a 2 dimensions array. There is a row for each X value.
  * Each row contains the x value and the corresponding y value for each serie ('undefined' if there isn't one)
  **/
  _.each(s, function (serie, i) {
  _.each(serie.data, function (v) {
  var x = v[0],
  y = v[1],
  r = rows[x];
  if (r) {
  r[i + 1] = y;
  } else {
  var newRow = [];
  newRow[0] = x;
  newRow[i + 1] = y;
  rows[x] = newRow;
  }
  });
  });
 
  // The data grid is sorted by x value
  this.seriesData = _.sortBy(rows, function (row, x) {
  return parseInt(x, 10);
  });
  return this.seriesData;
  },
  /**
  * Constructs the data table for the spreadsheet
  * @todo make a spreadsheet manager (Flotr.Spreadsheet)
  * @return {Element} The resulting table element
  */
  constructDataGrid: function () {
  // If the data grid has already been built, nothing to do here
  if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
 
  var s = this.series,
  datagrid = this.spreadsheet.loadDataGrid(),
  colgroup = ['<colgroup><col />'],
  buttonDownload, buttonSelect, t;
 
  // First row : series' labels
  var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
  html.push('<th>&nbsp;</th>');
  _.each(s, function (serie, i) {
  html.push('<th scope="col">' + (serie.label || String.fromCharCode(65 + i)) + '</th>');
  colgroup.push('<col />');
  });
  html.push('</tr>');
  // Data rows
  _.each(datagrid, function (row) {
  html.push('<tr>');
  _.times(s.length + 1, function (i) {
  var tag = 'td',
  value = row[i],
  // TODO: do we really want to handle problems with floating point
  // precision here?
  content = (!_.isUndefined(value) ? Math.round(value * 100000) / 100000 : '');
  if (i === 0) {
  tag = 'th';
  var label = getRowLabel.call(this, content);
  if (label) content = label;
  }
 
  html.push('<' + tag + (tag == 'th' ? ' scope="row"' : '') + '>' + content + '</' + tag + '>');
  }, this);
  html.push('</tr>');
  }, this);
  colgroup.push('</colgroup>');
  t = D.node(html.join(''));
 
  /**
  * @TODO disabled this
  if (!Flotr.isIE || Flotr.isIE == 9) {
  function handleMouseout(){
  t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
  }
  function handleMouseover(e){
  var td = e.element(),
  siblings = td.previousSiblings();
  t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
  t.select('colgroup col')[siblings.length].addClassName('hover');
  }
  _.each(t.select('td'), function(td) {
  Flotr.EventAdapter.
  observe(td, 'mouseover', handleMouseover).
  observe(td, 'mouseout', handleMouseout);
  });
  }
  */
 
  buttonDownload = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarDownload +
  '</button>');
 
  buttonSelect = D.node(
  '<button type="button" class="flotr-datagrid-toolbar-button">' +
  this.options.spreadsheet.toolbarSelectAll +
  '</button>');
 
  this.
  observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
  observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
 
  var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
  D.insert(toolbar, buttonDownload);
  D.insert(toolbar, buttonSelect);
 
  var containerHeight = this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height - 2,
  container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:' +
  this.canvasWidth + 'px;height:' + containerHeight + 'px;overflow:auto;z-index:10"></div>');
 
  D.insert(container, toolbar);
  D.insert(container, t);
  D.insert(this.el, container);
  this.spreadsheet.datagrid = t;
  this.spreadsheet.container = container;
 
  return t;
  },
  /**
  * Shows the specified tab, by its name
  * @todo make a tab manager (Flotr.Tabs)
  * @param {String} tabName - The tab name
  */
  showTab: function (tabName) {
  if (this.spreadsheet.activeTab === tabName) {
  return;
  }
  switch (tabName) {
  case 'graph':
  D.hide(this.spreadsheet.container);
  D.removeClass(this.spreadsheet.tabs.data, 'selected');
  D.addClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  case 'data':
  if (!this.spreadsheet.datagrid)
  this.spreadsheet.constructDataGrid();
  D.show(this.spreadsheet.container);
  D.addClass(this.spreadsheet.tabs.data, 'selected');
  D.removeClass(this.spreadsheet.tabs.graph, 'selected');
  break;
  default:
  throw 'Illegal tab name: ' + tabName;
  }
  this.spreadsheet.activeTab = tabName;
  },
  /**
  * Selects the data table in the DOM for copy/paste
  */
  selectAllData: function () {
  if (this.spreadsheet.tabs) {
  var selection, range, doc, win, node = this.spreadsheet.constructDataGrid();
 
  this.spreadsheet.showTab('data');
 
  // deferred to be able to select the table
  setTimeout(function () {
  if ((doc = node.ownerDocument) && (win = doc.defaultView) &&
  win.getSelection && doc.createRange &&
  (selection = window.getSelection()) &&
  selection.removeAllRanges) {
  range = doc.createRange();
  range.selectNode(node);
  selection.removeAllRanges();
  selection.addRange(range);
  }
  else if (document.body && document.body.createTextRange &&
  (range = document.body.createTextRange())) {
  range.moveToElementText(node);
  range.select();
  }
  }, 0);
  return true;
  }
  else return false;
  },
  /**
  * Converts the data into CSV in order to download a file
  */
  downloadCSV: function () {
  var csv = '',
  series = this.series,
  options = this.options,
  dg = this.spreadsheet.loadDataGrid(),
  separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
 
  if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
  throw "The decimal separator is the same as the column separator (" + options.spreadsheet.decimalSeparator + ")";
  }
 
  // The first row
  _.each(series, function (serie, i) {
  csv += separator + '"' + (serie.label || String.fromCharCode(65 + i)).replace(/\"/g, '\\"') + '"';
  });
 
  csv += "%0D%0A"; // \r\n
 
  // For each row
  csv += _.reduce(dg, function (memo, row) {
  var rowLabel = getRowLabel.call(this, row[0]) || '';
  rowLabel = '"' + (rowLabel + '').replace(/\"/g, '\\"') + '"';
  var numbers = row.slice(1).join(separator);
  if (options.spreadsheet.decimalSeparator !== '.') {
  numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
  }
  return memo + rowLabel + separator + numbers + "%0D%0A"; // \t and \r\n
  }, '', this);
 
  if (Flotr.isIE && Flotr.isIE < 9) {
  csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
  window.open().document.write(csv);
  }
  else window.open('data:text/csv,' + csv);
  }
  });
  })();
 
  (function () {
 
  var D = Flotr.DOM;
 
  Flotr.addPlugin('titles', {
  callbacks: {
  'flotr:afterdraw': function () {
  this.titles.drawTitles();
  }
  },
  /**
  * Draws the title and the subtitle
  */
  drawTitles: function () {
  var html,
  options = this.options,
  margin = options.grid.labelMargin,
  ctx = this.ctx,
  a = this.axes;
 
  if (!options.HtmlText && this.textEnabled) {
  var style = {
  size: options.fontSize,
  color: options.grid.color,
  textAlign: 'center'
  };
 
  // Add subtitle
  if (options.subtitle) {
  Flotr.drawText(
  ctx, options.subtitle,
  this.plotOffset.left + this.plotWidth / 2,
  this.titleHeight + this.subtitleHeight - 2,
  style
  );
  }
 
  style.weight = 1.5;
  style.size *= 1.5;
 
  // Add title
  if (options.title) {
  Flotr.drawText(
  ctx, options.title,
  this.plotOffset.left + this.plotWidth / 2,
  this.titleHeight - 2,
  style
  );
  }
 
  style.weight = 1.8;
  style.size *= 0.8;
 
  // Add x axis title
  if (a.x.options.title && a.x.used) {
  style.textAlign = a.x.options.titleAlign || 'center';
  style.textBaseline = 'top';
  style.angle = Flotr.toRad(a.x.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x.options.title,
  this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top + a.x.maxLabel.height + this.plotHeight + 2 * margin,
  style
  );
  }
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used) {
  style.textAlign = a.x2.options.titleAlign || 'center';
  style.textBaseline = 'bottom';
  style.angle = Flotr.toRad(a.x2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.x2.options.title,
  this.plotOffset.left + this.plotWidth / 2,
  this.plotOffset.top - a.x2.maxLabel.height - 2 * margin,
  style
  );
  }
 
  // Add y axis title
  if (a.y.options.title && a.y.used) {
  style.textAlign = a.y.options.titleAlign || 'right';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y.options.title,
  this.plotOffset.left - a.y.maxLabel.width - 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used) {
  style.textAlign = a.y2.options.titleAlign || 'left';
  style.textBaseline = 'middle';
  style.angle = Flotr.toRad(a.y2.options.titleAngle);
  style = Flotr.getBestTextAlign(style.angle, style);
  Flotr.drawText(
  ctx, a.y2.options.title,
  this.plotOffset.left + this.plotWidth + a.y2.maxLabel.width + 2 * margin,
  this.plotOffset.top + this.plotHeight / 2,
  style
  );
  }
  }
  else {
  html = [];
 
  // Add title
  if (options.title)
  html.push(
  '<div style="position:absolute;top:0;left:',
  this.plotOffset.left, 'px;font-size:1em;font-weight:bold;text-align:center;width:',
  this.plotWidth, 'px;" class="flotr-title">', options.title, '</div>'
  );
 
  // Add subtitle
  if (options.subtitle)
  html.push(
  '<div style="position:absolute;top:', this.titleHeight, 'px;left:',
  this.plotOffset.left, 'px;font-size:smaller;text-align:center;width:',
  this.plotWidth, 'px;" class="flotr-subtitle">', options.subtitle, '</div>'
  );
 
  html.push('</div>');
 
  html.push('<div class="flotr-axis-title" style="font-weight:bold;">');
 
  // Add x axis title
  if (a.x.options.title && a.x.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight + options.grid.labelMargin + a.x.titleSize.height),
  'px;left:', this.plotOffset.left, 'px;width:', this.plotWidth,
  'px;text-align:', a.x.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x1">', a.x.options.title, '</div>'
  );
 
  // Add x2 axis title
  if (a.x2.options.title && a.x2.used)
  html.push(
  '<div style="position:absolute;top:0;left:', this.plotOffset.left, 'px;width:',
  this.plotWidth, 'px;text-align:', a.x2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-x2">', a.x2.options.title, '</div>'
  );
 
  // Add y axis title
  if (a.y.options.title && a.y.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight / 2 - a.y.titleSize.height / 2),
  'px;left:0;text-align:', a.y.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y1">', a.y.options.title, '</div>'
  );
 
  // Add y2 axis title
  if (a.y2.options.title && a.y2.used)
  html.push(
  '<div style="position:absolute;top:',
  (this.plotOffset.top + this.plotHeight / 2 - a.y.titleSize.height / 2),
  'px;right:0;text-align:', a.y2.options.titleAlign, ';" class="flotr-axis-title flotr-axis-title-y2">', a.y2.options.title, '</div>'
  );
 
  html = html.join('');
 
  var div = D.create('div');
  D.setStyles({
  color: options.grid.color
  });
  div.className = 'flotr-titles';
  D.insert(this.el, div);
  D.insert(div, html);
  }
  }
  });
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key: 'test-background',
  name: 'Test Background',
  callback: test_background,
  timeout: 100,
  tolerance: 10
  });
 
  function test_background(container) {
 
  var
  d1 = [],
  d2 = [],
  d3 = [],
  d4 = [],
  d5 = [], // Data
  ticks = [
  [ 0, "Lower"],
  10,
  20,
  30,
  [40, "Upper"]
  ], // Ticks for the Y-Axis
  graph;
 
  for (var i = 0; i <= 10; i += 0.1) {
  d1.push([i, 4 + Math.pow(i, 1.5)]);
  d2.push([i, Math.pow(i, 3)]);
  d3.push([i, i * 5 + 3 * Math.sin(i * 4)]);
  d4.push([i, i]);
  if (i.toFixed(1) % 1 == 0) {
  d5.push([i, 2 * i]);
  }
  }
 
  d3[30][1] = null;
  d3[31][1] = null;
 
  function ticksFn(n) {
  return '(' + n + ')';
  }
 
  graph = Flotr.draw(container, [
  { data: d1, label: 'y = 4 + x^(1.5)', lines: { fill: true } },
  { data: d2, label: 'y = x^3'},
  { data: d3, label: 'y = 5x + 3sin(4x)'},
  { data: d4, label: 'y = x'},
  { data: d5, label: 'y = 2x', lines: { show: true }, points: { show: true } }
  ], {
  xaxis: {
  noTicks: 7, // Display 7 ticks.
  tickFormatter: ticksFn, // Displays tick values between brackets.
  min: 1, // Part of the series is not displayed.
  max: 7.5 // Part of the series is not displayed.
  },
  yaxis: {
  ticks: ticks, // Set Y-Axis ticks
  max: 40 // Maximum value along Y-Axis
  },
  grid: {
  verticalLines: false,
  backgroundImage: {
  src: 'img/test-background.png?' + Math.random()
  }
  },
  legend: {
  position: 'nw'
  },
  title: 'Basic Axis example',
  subtitle: 'This is a subtitle'
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key: 'test-boundaries',
  name: 'Test Boundaries',
  callback: test_boundaries
  });
 
  function test_boundaries(container) {
 
  var
  d1 = [
  [0, 0],
  [5, 0],
  [6, 10],
  [9, 10]
  ], // First data series
  i, graph;
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1 ], {
  title: 'test',
  xaxis: {
  minorTickFreq: 4
  },
  lines: {
  lineWidth: 2
  },
  grid: {
  outlineWidth: 2,
  minorVerticalLines: true
  }
  });
  }
 
  })();
 
  (function () {
 
  Flotr.ExampleList.add({
  key: 'test-mountain-nulls',
  name: 'Mountain Nulls',
  callback: function (container) {
  var
  d1 = [
  [0, 3],
  [4, 8],
  [5, 6],
  [6, null],
  [7, 7],
  [8, 5]
  ], // First data series
  d2 = [], // Second data series
  i, graph;
 
  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
  }
 
  // Multiple nulls
  d2[9][1] = null;
  d2[10][1] = null;
  d2[11][1] = null;
 
  // Single not null surrounded by null
  d2[13][1] = null;
 
  // < 0 null
  d2[23][1] = null;
 
  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
  xaxis: {
  minorTickFreq: 4
  },
  lines: {
  fill: true
  },
  grid: {
  minorVerticalLines: true
  }
  });
  },
  type: 'test'
  });
 
  })();
 
  /*! jQuery v1.8.2 jquery.com | jquery.org/license */
  (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,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(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.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):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.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,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(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){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[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","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
file:b/js/main.js (new)
 
 
file:b/js/plugins.js (new)
  // Avoid `console` errors in browsers that lack a console.
  if (!(window.console && console.log)) {
  (function() {
  var noop = function() {};
  var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
  var length = methods.length;
  var console = window.console = {};
  while (length--) {
  console[methods[length]] = noop;
  }
  }());
  }
 
  // Place any jQuery/helper plugins in here.
 
  /*! jQuery v@1.8.0 jquery.com | jquery.org/license */
  (function (a, b) {
  function G(a) {
  var b = F[a] = {};
  return p.each(a.split(s), function (a, c) {
  b[c] = !0
  }), b
  }
 
  function J(a, c, d) {
  if (d === b && a.nodeType === 1) {
  var e = "data-" + c.replace(I, "-$1").toLowerCase();
  d = a.getAttribute(e);
  if (typeof d == "string") {
  try {
  d = d === "true" ? !0 : d === "false" ? !1 : d === "null" ? null : +d + "" === d ? +d : H.test(d) ? p.parseJSON(d) : d
  } catch (f) {
  }
  p.data(a, c, d)
  } else d = b
  }
  return d
  }
 
  function K(a) {
  var b;
  for (b in a) {
  if (b === "data" && p.isEmptyObject(a[b]))continue;
  if (b !== "toJSON")return!1
  }
  return!0
  }
 
  function ba() {
  return!1
  }
 
  function bb() {
  return!0
  }
 
  function bh(a) {
  return!a || !a.parentNode || a.parentNode.nodeType === 11
  }
 
  function bi(a, b) {
  do a = a[b]; while (a && a.nodeType !== 1);
  return a
  }
 
  function bj(a, b, c) {
  b = b || 0;
  if (p.isFunction(b))return p.grep(a, function (a, d) {
  var e = !!b.call(a, d, a);
  return e === c
  });
  if (b.nodeType)return p.grep(a, function (a, d) {
  return a === b === c
  });
  if (typeof b == "string") {
  var d = p.grep(a, function (a) {
  return a.nodeType === 1
  });
  if (be.test(b))return p.filter(b, d, !c);
  b = p.filter(b, d)
  }
  return p.grep(a, function (a, d) {
  return p.inArray(a, b) >= 0 === c
  })
  }
 
  function bk(a) {
  var b = bl.split("|"), c = a.createDocumentFragment();
  if (c.createElement)while (b.length)c.createElement(b.pop());
  return c
  }
 
  function bC(a, b) {
  return a.getElementsByTagName(b)[0] || a.appendChild(a.ownerDocument.createElement(b))
  }
 
  function bD(a, b) {
  if (b.nodeType !== 1 || !p.hasData(a))return;
  var c, d, e, f = p._data(a), g = p._data(b, f), h = f.events;
  if (h) {
  delete g.handle, g.events = {};
  for (c in h)for (d = 0, e = h[c].length; d < e; d++)p.event.add(b, c, h[c][d])
  }
  g.data && (g.data = p.extend({}, g.data))
  }
 
  function bE(a, b) {
  var c;
  if (b.nodeType !== 1)return;
  b.clearAttributes && b.clearAttributes(), b.mergeAttributes && b.mergeAttributes(a), c = b.nodeName.toLowerCase(), c === "object" ? (b.parentNode && (b.outerHTML = a.outerHTML), p.support.html5Clone && a.innerHTML && !p.trim(b.innerHTML) && (b.innerHTML = a.innerHTML)) : c === "input" && bv.test(a.type) ? (b.defaultChecked = b.checked = a.checked, b.value !== a.value && (b.value = a.value)) : c === "option" ? b.selected = a.defaultSelected : c === "input" || c === "textarea" ? b.defaultValue = a.defaultValue : c === "script" && b.text !== a.text && (b.text = a.text), b.removeAttribute(p.expando)
  }
 
  function bF(a) {
  return typeof a.getElementsByTagName != "undefined" ? a.getElementsByTagName("*") : typeof a.querySelectorAll != "undefined" ? a.querySelectorAll("*") : []
  }
 
  function bG(a) {
  bv.test(a.type) && (a.defaultChecked = a.checked)
  }
 
  function bX(a, b) {
  if (b in a)return b;
  var c = b.charAt(0).toUpperCase() + b.slice(1), d = b, e = bV.length;
  while (e--) {
  b = bV[e] + c;
  if (b in a)return b
  }
  return d
  }
 
  function bY(a, b) {
  return a = b || a, p.css(a, "display") === "none" || !p.contains(a.ownerDocument, a)
  }
 
  function bZ(a, b) {
  var c, d, e = [], f = 0, g = a.length;
  for (; f < g; f++) {
  c = a[f];
  if (!c.style)continue;
  e[f] = p._data(c, "olddisplay"), b ? (!e[f] && c.style.display === "none" && (c.style.display = ""), c.style.display === "" && bY(c) && (e[f] = p._data(c, "olddisplay", cb(c.nodeName)))) : (d = bH(c, "display"), !e[f] && d !== "none" && p._data(c, "olddisplay", d))
  }
  for (f = 0; f < g; f++) {
  c = a[f];
  if (!c.style)continue;
  if (!b || c.style.display === "none" || c.style.display === "")c.style.display = b ? e[f] || "" : "none"
  }
  return a
  }
 
  function b$(a, b, c) {
  var d = bO.exec(b);
  return d ? Math.max(0, d[1] - (c || 0)) + (d[2] || "px") : b
  }
 
  function b_(a, b, c, d) {
  var e = c === (d ? "border" : "content") ? 4 : b === "width" ? 1 : 0, f = 0;
  for (; e < 4; e += 2)c === "margin" && (f += p.css(a, c + bU[e], !0)), d ? (c === "content" && (f -= parseFloat(bH(a, "padding" + bU[e])) || 0), c !== "margin" && (f -= parseFloat(bH(a, "border" + bU[e] + "Width")) || 0)) : (f += parseFloat(bH(a, "padding" + bU[e])) || 0, c !== "padding" && (f += parseFloat(bH(a, "border" + bU[e] + "Width")) || 0));
  return f
  }
 
  function ca(a, b, c) {
  var d = b === "width" ? a.offsetWidth : a.offsetHeight, e = !0, f = p.support.boxSizing && p.css(a, "boxSizing") === "border-box";
  if (d <= 0) {
  d = bH(a, b);
  if (d < 0 || d == null)d = a.style[b];
  if (bP.test(d))return d;
  e = f && (p.support.boxSizingReliable || d === a.style[b]), d = parseFloat(d) || 0
  }
  return d + b_(a, b, c || (f ? "border" : "content"), e) + "px"
  }
 
  function cb(a) {
  if (bR[a])return bR[a];
  var b = p("<" + a + ">").appendTo(e.body), c = b.css("display");
  b.remove();
  if (c === "none" || c === "") {
  bI = e.body.appendChild(bI || p.extend(e.createElement("iframe"), {frameBorder: 0, width: 0, height: 0}));
  if (!bJ || !bI.createElement)bJ = (bI.contentWindow || bI.contentDocument).document, bJ.write("<!doctype html><html><body>"), bJ.close();
  b = bJ.body.appendChild(bJ.createElement(a)), c = bH(b, "display"), e.body.removeChild(bI)
  }
  return bR[a] = c, c
  }
 
  function ch(a, b, c, d) {
  var e;
  if (p.isArray(b))p.each(b, function (b, e) {
  c || cd.test(a) ? d(a, e) : ch(a + "[" + (typeof e == "object" ? b : "") + "]", e, c, d)
  }); else if (!c && p.type(b) === "object")for (e in b)ch(a + "[" + e + "]", b[e], c, d); else d(a, b)
  }
 
  function cy(a) {
  return function (b, c) {
  typeof b != "string" && (c = b, b = "*");
  var d, e, f, g = b.toLowerCase().split(s), h = 0, i = g.length;
  if (p.isFunction(c))for (; h < i; h++)d = g[h], f = /^\+/.test(d), f && (d = d.substr(1) || "*"), e = a[d] = a[d] || [], e[f ? "unshift" : "push"](c)
  }
  }
 
  function cz(a, c, d, e, f, g) {
  f = f || c.dataTypes[0], g = g || {}, g[f] = !0;
  var h, i = a[f], j = 0, k = i ? i.length : 0, l = a === cu;
  for (; j < k && (l || !h); j++)h = i[j](c, d, e), typeof h == "string" && (!l || g[h] ? h = b : (c.dataTypes.unshift(h), h = cz(a, c, d, e, h, g)));
  return(l || !h) && !g["*"] && (h = cz(a, c, d, e, "*", g)), h
  }
 
  function cA(a, c) {
  var d, e, f = p.ajaxSettings.flatOptions || {};
  for (d in c)c[d] !== b && ((f[d] ? a : e || (e = {}))[d] = c[d]);
  e && p.extend(!0, a, e)
  }
 
  function cB(a, c, d) {
  var e, f, g, h, i = a.contents, j = a.dataTypes, k = a.responseFields;
  for (f in k)f in d && (c[k[f]] = d[f]);
  while (j[0] === "*")j.shift(), e === b && (e = a.mimeType || c.getResponseHeader("content-type"));
  if (e)for (f in i)if (i[f] && i[f].test(e)) {
  j.unshift(f);
  break
  }
  if (j[0]in d)g = j[0]; else {
  for (f in d) {
  if (!j[0] || a.converters[f + " " + j[0]]) {
  g = f;
  break
  }
  h || (h = f)
  }
  g = g || h
  }
  if (g)return g !== j[0] && j.unshift(g), d[g]
  }
 
  function cC(a, b) {
  var c, d, e, f, g = a.dataTypes.slice(), h = g[0], i = {}, j = 0;
  a.dataFilter && (b = a.dataFilter(b, a.dataType));
  if (g[1])for (c in a.converters)i[c.toLowerCase()] = a.converters[c];
  for (; e = g[++j];)if (e !== "*") {
  if (h !== "*" && h !== e) {
  c = i[h + " " + e] || i["* " + e];
  if (!c)for (d in i) {
  f = d.split(" ");
  if (f[1] === e) {
  c = i[h + " " + f[0]] || i["* " + f[0]];
  if (c) {
  c === !0 ? c = i[d] : i[d] !== !0 && (e = f[0], g.splice(j--, 0, e));
  break
  }
  }
  }
  if (c !== !0)if (c && a["throws"])b = c(b); else try {
  b = c(b)
  } catch (k) {
  return{state: "parsererror", error: c ? k : "No conversion from " + h + " to " + e}
  }
  }
  h = e
  }
  return{state: "success", data: b}
  }
 
  function cK() {
  try {
  return new a.XMLHttpRequest
  } catch (b) {
  }
  }
 
  function cL() {
  try {
  return new a.ActiveXObject("Microsoft.XMLHTTP")
  } catch (b) {
  }
  }
 
  function cT() {
  return setTimeout(function () {
  cM = b
  }, 0), cM = p.now()
  }
 
  function cU(a, b) {
  p.each(b, function (b, c) {
  var d = (cS[b] || []).concat(cS["*"]), e = 0, f = d.length;
  for (; e < f; e++)if (d[e].call(a, b, c))return
  })
  }
 
  function cV(a, b, c) {
  var d, e = 0, f = 0, g = cR.length, h = p.Deferred().always(function () {
  delete i.elem
  }), i = function () {
  var b = cM || cT(), c = Math.max(0, j.startTime + j.duration - b), d = 1 - (c / j.duration || 0), e = 0, f = j.tweens.length;
  for (; e < f; e++)j.tweens[e].run(d);
  return h.notifyWith(a, [j, d, c]), d < 1 && f ? c : (h.resolveWith(a, [j]), !1)
  }, j = h.promise({elem: a, props: p.extend({}, b), opts: p.extend(!0, {specialEasing: {}}, c), originalProperties: b, originalOptions: c, startTime: cM || cT(), duration: c.duration, tweens: [], createTween: function (b, c, d) {
  var e = p.Tween(a, j.opts, b, c, j.opts.specialEasing[b] || j.opts.easing);
  return j.tweens.push(e), e
  }, stop: function (b) {
  var c = 0, d = b ? j.tweens.length : 0;
  for (; c < d; c++)j.tweens[c].run(1);
  return b ? h.resolveWith(a, [j, b]) : h.rejectWith(a, [j, b]), this
  }}), k = j.props;
  cW(k, j.opts.specialEasing);
  for (; e < g; e++) {
  d = cR[e].call(j, a, k, j.opts);
  if (d)return d
  }
  return cU(j, k), p.isFunction(j.opts.start) && j.opts.start.call(a, j), p.fx.timer(p.extend(i, {anim: j, queue: j.opts.queue, elem: a})), j.progress(j.opts.progress).done(j.opts.done, j.opts.complete).fail(j.opts.fail).always(j.opts.always)
  }
 
  function cW(a, b) {
  var c, d, e, f, g;
  for (c in a) {
  d = p.camelCase(c), e = b[d], f = a[c], p.isArray(f) && (e = f[1], f = a[c] = f[0]), c !== d && (a[d] = f, delete a[c]), g = p.cssHooks[d];
  if (g && "expand"in g) {
  f = g.expand(f), delete a[d];
  for (c in f)c in a || (a[c] = f[c], b[c] = e)
  } else b[d] = e
  }
  }
 
  function cX(a, b, c) {
  var d, e, f, g, h, i, j, k, l = this, m = a.style, n = {}, o = [], q = a.nodeType && bY(a);
  c.queue || (j = p._queueHooks(a, "fx"), j.unqueued == null && (j.unqueued = 0, k = j.empty.fire, j.empty.fire = function () {
  j.unqueued || k()
  }), j.unqueued++, l.always(function () {
  l.always(function () {
  j.unqueued--, p.queue(a, "fx").length || j.empty.fire()
  })
  })), a.nodeType === 1 && ("height"in b || "width"in b) && (c.overflow = [m.overflow, m.overflowX, m.overflowY], p.css(a, "display") === "inline" && p.css(a, "float") === "none" && (!p.support.inlineBlockNeedsLayout || cb(a.nodeName) === "inline" ? m.display = "inline-block" : m.zoom = 1)), c.overflow && (m.overflow = "hidden", p.support.shrinkWrapBlocks || l.done(function () {
  m.overflow = c.overflow[0], m.overflowX = c.overflow[1], m.overflowY = c.overflow[2]
  }));
  for (d in b) {
  f = b[d];
  if (cO.exec(f)) {
  delete b[d];
  if (f === (q ? "hide" : "show"))continue;
  o.push(d)
  }
  }
  g = o.length;
  if (g) {
  h = p._data(a, "fxshow") || p._data(a, "fxshow", {}), q ? p(a).show() : l.done(function () {
  p(a).hide()
  }), l.done(function () {
  var b;
  p.removeData(a, "fxshow", !0);
  for (b in n)p.style(a, b, n[b])
  });
  for (d = 0; d < g; d++)e = o[d], i = l.createTween(e, q ? h[e] : 0), n[e] = h[e] || p.style(a, e), e in h || (h[e] = i.start, q && (i.end = i.start, i.start = e === "width" || e === "height" ? 1 : 0))
  }
  }
 
  function cY(a, b, c, d, e) {
  return new cY.prototype.init(a, b, c, d, e)
  }
 
  function cZ(a, b) {
  var c, d = {height: a}, e = 0;
  for (; e < 4; e += 2 - b)c = bU[e], d["margin" + c] = d["padding" + c] = a;
  return b && (d.opacity = d.width = a), d
  }
 
  function c_(a) {
  return p.isWindow(a) ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : !1
  }
 
  var c, d, e = a.document, f = a.location, g = a.navigator, h = a.jQuery, i = a.$, j = Array.prototype.push, k = Array.prototype.slice, l = Array.prototype.indexOf, m = Object.prototype.toString, n = Object.prototype.hasOwnProperty, o = String.prototype.trim, p = function (a, b) {
  return new p.fn.init(a, b, c)
  }, q = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, r = /\S/, s = /\s+/, t = r.test(" ") ? /^[\s\xA0]+|[\s\xA0]+$/g : /^\s+|\s+$/g, u = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, v = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, w = /^[\],:{}\s]*$/, x = /(?:^|:|,)(?:\s*\[)+/g, y = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, z = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, A = /^-ms-/, B = /-([\da-z])/gi, C = function (a, b) {
  return(b + "").toUpperCase()
  }, D = function () {
  e.addEventListener ? (e.removeEventListener("DOMContentLoaded", D, !1), p.ready()) : e.readyState === "complete" && (e.detachEvent("onreadystatechange", D), p.ready())
  }, E = {};
  p.fn = p.prototype = {constructor: p, init: function (a, c, d) {
  var f, g, h, i;
  if (!a)return this;
  if (a.nodeType)return this.context = this[0] = a, this.length = 1, this;
  if (typeof a == "string") {
  a.charAt(0) === "<" && a.charAt(a.length - 1) === ">" && a.length >= 3 ? f = [null, a, null] : f = u.exec(a);
  if (f && (f[1] || !c)) {
  if (f[1])return c = c instanceof p ? c[0] : c, i = c && c.nodeType ? c.ownerDocument || c : e, a = p.parseHTML(f[1], i, !0), v.test(f[1]) && p.isPlainObject(c) && this.attr.call(a, c, !0), p.merge(this, a);
  g = e.getElementById(f[2]);
  if (g && g.parentNode) {
  if (g.id !== f[2])return d.find(a);
  this.length = 1, this[0] = g
  }
  return this.context = e, this.selector = a, this
  }
  return!c || c.jquery ? (c || d).find(a) : this.constructor(c).find(a)
  }
  return p.isFunction(a) ? d.ready(a) : (a.selector !== b && (this.selector = a.selector, this.context = a.context), p.makeArray(a, this))
  }, selector: "", jquery: "1.8.0", length: 0, size: function () {
  return this.length
  }, toArray: function () {
  return k.call(this)
  }, get: function (a) {
  return a == null ? this.toArray() : a < 0 ? this[this.length + a] : this[a]
  }, pushStack: function (a, b, c) {
  var d = p.merge(this.constructor(), a);
  return d.prevObject = this, d.context = this.context, b === "find" ? d.selector = this.selector + (this.selector ? " " : "") + c : b && (d.selector = this.selector + "." + b + "(" + c + ")"), d
  }, each: function (a, b) {
  return p.each(this, a, b)
  }, ready: function (a) {
  return p.ready.promise().done(a), this
  }, eq: function (a) {
  return a = +a, 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(k.apply(this, arguments), "slice", k.call(arguments).join(","))
  }, map: function (a) {
  return this.pushStack(p.map(this, function (b, c) {
  return a.call(b, c, b)
  }))
  }, end: function () {
  return this.prevObject || this.constructor(null)
  }, push: j, sort: [].sort, splice: [].splice}, p.fn.init.prototype = p.fn, p.extend = p.fn.extend = function () {
  var a, c, d, e, f, g, h = arguments[0] || {}, i = 1, j = arguments.length, k = !1;
  typeof h == "boolean" && (k = h, h = arguments[1] || {}, i = 2), typeof h != "object" && !p.isFunction(h) && (h = {}), j === i && (h = this, --i);
  for (; i < j; i++)if ((a = arguments[i]) != null)for (c in a) {
  d = h[c], e = a[c];
  if (h === e)continue;
  k && e && (p.isPlainObject(e) || (f = p.isArray(e))) ? (f ? (f = !1, g = d && p.isArray(d) ? d : []) : g = d && p.isPlainObject(d) ? d : {}, h[c] = p.extend(k, g, e)) : e !== b && (h[c] = e)
  }
  return h
  }, p.extend({noConflict: function (b) {
  return a.$ === p && (a.$ = i), b && a.jQuery === p && (a.jQuery = h), p
  }, isReady: !1, readyWait: 1, holdReady: function (a) {
  a ? p.readyWait++ : p.ready(!0)
  }, ready: function (a) {
  if (a === !0 ? --p.readyWait : p.isReady)return;
  if (!e.body)return setTimeout(p.ready, 1);
  p.isReady = !0;
  if (a !== !0 && --p.readyWait > 0)return;
  d.resolveWith(e, [p]), p.fn.trigger && p(e).trigger("ready").off("ready")
  }, isFunction: function (a) {
  return p.type(a) === "function"
  }, isArray: Array.isArray || function (a) {
  return p.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) : E[m.call(a)] || "object"
  }, isPlainObject: function (a) {
  if (!a || p.type(a) !== "object" || a.nodeType || p.isWindow(a))return!1;
  try {
  if (a.constructor && !n.call(a, "constructor") && !n.call(a.constructor.prototype, "isPrototypeOf"))return!1
  } catch (c) {
  return!1
  }
  var d;
  for (d in a);
  return d === b || n.call(a, d)
  }, isEmptyObject: function (a) {
  var b;
  for (b in a)return!1;
  return!0
  }, error: function (a) {
  throw new Error(a)
  }, parseHTML: function (a, b, c) {
  var d;
  return!a || typeof a != "string" ? null : (typeof b == "boolean" && (c = b, b = 0), b = b || e, (d = v.exec(a)) ? [b.createElement(d[1])] : (d = p.buildFragment([a], b, c ? null : []), p.merge([], (d.cacheable ? p.clone(d.fragment) : d.fragment).childNodes)))
  }, parseJSON: function (b) {
  if (!b || typeof b != "string")return null;
  b = p.trim(b);
  if (a.JSON && a.JSON.parse)return a.JSON.parse(b);
  if (w.test(b.replace(y, "@").replace(z, "]").replace(x, "")))return(new Function("return " + b))();
  p.error("Invalid JSON: " + b)
  }, parseXML: function (c) {
  var d, e;
  if (!c || typeof c != "string")return null;
  try {
  a.DOMParser ? (e = new DOMParser, d = e.parseFromString(c, "text/xml")) : (d = new ActiveXObject("Microsoft.XMLDOM"), d.async = "false", d.loadXML(c))
  } catch (f) {
  d = b
  }
  return(!d || !d.documentElement || d.getElementsByTagName("parsererror").length) && p.error("Invalid XML: " + c), d
  }, noop: function () {
  }, globalEval: function (b) {
  b && r.test(b) && (a.execScript || function (b) {
  a.eval.call(a, b)
  })(b)
  }, camelCase: function (a) {
  return a.replace(A, "ms-").replace(B, C)
  }, nodeName: function (a, b) {
  return a.nodeName && a.nodeName.toUpperCase() === b.toUpperCase()
  }, each: function (a, c, d) {
  var e, f = 0, g = a.length, h = g === b || p.isFunction(a);
  if (d) {
  if (h) {
  for (e in a)if (c.apply(a[e], d) === !1)break
  } else for (; f < g;)if (c.apply(a[f++], d) === !1)break
  } else if (h) {
  for (e in a)if (c.call(a[e], e, a[e]) === !1)break
  } else for (; f < g;)if (c.call(a[f], f, a[f++]) === !1)break;
  return a
  }, trim: o ? function (a) {
  return a == null ? "" : o.call(a)
  } : function (a) {
  return a == null ? "" : a.toString().replace(t, "")
  }, makeArray: function (a, b) {
  var c, d = b || [];
  return a != null && (c = p.type(a), a.length == null || c === "string" || c === "function" || c === "regexp" || p.isWindow(a) ? j.call(d, a) : p.merge(d, a)), d
  }, inArray: function (a, b, c) {
  var d;
  if (b) {
  if (l)return l.call(b, a, c);
  d = b.length, c = c ? c < 0 ? Math.max(0, d + c) : c : 0;
  for (; c < d; c++)if (c in b && b[c] === a)return c
  }
  return-1
  }, merge: function (a, c) {
  var d = c.length, e = a.length, f = 0;
  if (typeof d == "number")for (; f < d; f++)a[e++] = c[f]; else while (c[f] !== b)a[e++] = c[f++];
  return a.length = e, a
  }, grep: function (a, b, c) {
  var d, e = [], f = 0, g = a.length;
  c = !!c;
  for (; f < g; f++)d = !!b(a[f], f), c !== d && e.push(a[f]);
  return e
  }, map: function (a, c, d) {
  var e, f, g = [], h = 0, i = a.length, j = a instanceof p || i !== b && typeof i == "number" && (i > 0 && a[0] && a[i - 1] || i === 0 || p.isArray(a));
  if (j)for (; h < i; h++)e = c(a[h], h, d), e != null && (g[g.length] = e); else for (f in a)e = c(a[f], f, d), e != null && (g[g.length] = e);
  return g.concat.apply([], g)
  }, guid: 1, proxy: function (a, c) {
  var d, e, f;
  return typeof c == "string" && (d = a[c], c = a, a = d), p.isFunction(a) ? (e = k.call(arguments, 2), f = function () {
  return a.apply(c, e.concat(k.call(arguments)))
  }, f.guid = a.guid = a.guid || f.guid || p.guid++, f) : b
  }, access: function (a, c, d, e, f, g, h) {
  var i, j = d == null, k = 0, l = a.length;
  if (d && typeof d == "object") {
  for (k in d)p.access(a, c, k, d[k], 1, g, e);
  f = 1
  } else if (e !== b) {
  i = h === b && p.isFunction(e), j && (i ? (i = c, c = function (a, b, c) {
  return i.call(p(a), c)
  }) : (c.call(a, e), c = null));
  if (c)for (; k < l; k++)c(a[k], d, i ? e.call(a[k], k, c(a[k], d)) : e, h);
  f = 1
  }
  return f ? a : j ? c.call(a) : l ? c(a[0], d) : g
  }, now: function () {
  return(new Date).getTime()
  }}), p.ready.promise = function (b) {
  if (!d) {
  d = p.Deferred();
  if (e.readyState === "complete" || e.readyState !== "loading" && e.addEventListener)setTimeout(p.ready, 1); else if (e.addEventListener)e.addEventListener("DOMContentLoaded", D, !1), a.addEventListener("load", p.ready, !1); else {
  e.attachEvent("onreadystatechange", D), a.attachEvent("onload", p.ready);
  var c = !1;
  try {
  c = a.frameElement == null && e.documentElement
  } catch (f) {
  }
  c && c.doScroll && function g() {
  if (!p.isReady) {
  try {
  c.doScroll("left")
  } catch (a) {
  return setTimeout(g, 50)
  }
  p.ready()
  }
  }()
  }
  }
  return d.promise(b)
  }, p.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (a, b) {
  E["[object " + b + "]"] = b.toLowerCase()
  }), c = p(e);
  var F = {};
  p.Callbacks = function (a) {
  a = typeof a == "string" ? F[a] || G(a) : p.extend({}, a);
  var c, d, e, f, g, h, i = [], j = !a.once && [], k = function (b) {
  c = a.memory && b, d = !0, h = f || 0, f = 0, g = i.length, e = !0;
  for (; i && h < g; h++)if (i[h].apply(b[0], b[1]) === !1 && a.stopOnFalse) {
  c = !1;
  break
  }
  e = !1, i && (j ? j.length && k(j.shift()) : c ? i = [] : l.disable())
  }, l = {add: function () {
  if (i) {
  var b = i.length;
  (function d(b) {
  p.each(b, function (b, c) {
  p.isFunction(c) && (!a.unique || !l.has(c)) ? i.push(c) : c && c.length && d(c)
  })
  })(arguments), e ? g = i.length : c && (f = b, k(c))
  }
  return this
  }, remove: function () {
  return i && p.each(arguments, function (a, b) {
  var c;
  while ((c = p.inArray(b, i, c)) > -1)i.splice(c, 1), e && (c <= g && g--, c <= h && h--)
  }), this
  }, has: function (a) {
  return p.inArray(a, i) > -1
  }, empty: function () {
  return i = [], this
  }, disable: function () {
  return i = j = c = b, this
  }, disabled: function () {
  return!i
  }, lock: function () {
  return j = b, c || l.disable(), this
  }, locked: function () {
  return!j
  }, fireWith: function (a, b) {
  return b = b || [], b = [a, b.slice ? b.slice() : b], i && (!d || j) && (e ? j.push(b) : k(b)), this
  }, fire: function () {
  return l.fireWith(this, arguments), this
  }, fired: function () {
  return!!d
  }};
  return l
  }, p.extend({Deferred: function (a) {
  var b = [
  ["resolve", "done", p.Callbacks("once memory"), "resolved"],
  ["reject", "fail", p.Callbacks("once memory"), "rejected"],
  ["notify", "progress", p.Callbacks("memory")]
  ], c = "pending", d = {state: function () {
  return c
  }, always: function () {
  return e.done(arguments).fail(arguments), this
  }, then: function () {
  var a = arguments;
  return p.Deferred(function (c) {
  p.each(b, function (b, d) {
  var f = d[0], g = a[b];
  e[d[1]](p.isFunction(g) ? function () {
  var a = g.apply(this, arguments);
  a && p.isFunction(a.promise) ? a.promise().done(c.resolve).fail(c.reject).progress(c.notify) : c[f + "With"](this === e ? c : this, [a])
  } : c[f])
  }), a = null
  }).promise()
  }, promise: function (a) {
  return typeof a == "object" ? p.extend(a, d) : d
  }}, e = {};
  return d.pipe = d.then, p.each(b, function (a, f) {
  var g = f[2], h = f[3];
  d[f[1]] = g.add, h && g.add(function () {
  c = h
  }, b[a ^ 1][2].disable, b[2][2].lock), e[f[0]] = g.fire, e[f[0] + "With"] = g.fireWith
  }), d.promise(e), a && a.call(e, e), e
  }, when: function (a) {
  var b = 0, c = k.call(arguments), d = c.length, e = d !== 1 || a && p.isFunction(a.promise) ? d : 0, f = e === 1 ? a : p.Deferred(), g = function (a, b, c) {
  return function (d) {
  b[a] = this, c[a] = arguments.length > 1 ? k.call(arguments) : d, c === h ? f.notifyWith(b, c) : --e || f.resolveWith(b, c)
  }
  }, h, i, j;
  if (d > 1) {
  h = new Array(d), i = new Array(d), j = new Array(d);
  for (; b < d; b++)c[b] && p.isFunction(c[b].promise) ? c[b].promise().done(g(b, j, c)).fail(f.reject).progress(g(b, i, h)) : --e
  }
  return e || f.resolveWith(j, c), f.promise()
  }}), p.support = function () {
  var b, c, d, f, g, h, i, j, k, l, m, n = e.createElement("div");
  n.setAttribute("className", "t"), n.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", c = n.getElementsByTagName("*"), d = n.getElementsByTagName("a")[0], d.style.cssText = "top:1px;float:left;opacity:.5";
  if (!c || !c.length || !d)return{};
  f = e.createElement("select"), g = f.appendChild(e.createElement("option")), h = n.getElementsByTagName("input")[0], b = {leadingWhitespace: n.firstChild.nodeType === 3, tbody: !n.getElementsByTagName("tbody").length, htmlSerialize: !!n.getElementsByTagName("link").length, style: /top/.test(d.getAttribute("style")), hrefNormalized: d.getAttribute("href") === "/a", opacity: /^0.5/.test(d.style.opacity), cssFloat: !!d.style.cssFloat, checkOn: h.value === "on", optSelected: g.selected, getSetAttribute: n.className !== "t", enctype: !!e.createElement("form").enctype, html5Clone: e.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>", boxModel: e.compatMode === "CSS1Compat", submitBubbles: !0, changeBubbles: !0, focusinBubbles: !1, deleteExpando: !0, noCloneEvent: !0, inlineBlockNeedsLayout: !1, shrinkWrapBlocks: !1, reliableMarginRight: !0, boxSizingReliable: !0, pixelPosition: !1}, h.checked = !0, b.noCloneChecked = h.cloneNode(!0).checked, f.disabled = !0, b.optDisabled = !g.disabled;
  try {
  delete n.test
  } catch (o) {
  b.deleteExpando = !1
  }
  !n.addEventListener && n.attachEvent && n.fireEvent && (n.attachEvent("onclick", m = function () {
  b.noCloneEvent = !1
  }), n.cloneNode(!0).fireEvent("onclick"), n.detachEvent("onclick", m)), h = e.createElement("input"), h.value = "t", h.setAttribute("type", "radio"), b.radioValue = h.value === "t", h.setAttribute("checked", "checked"), h.setAttribute("name", "t"), n.appendChild(h), i = e.createDocumentFragment(), i.appendChild(n.lastChild), b.checkClone = i.cloneNode(!0).cloneNode(!0).lastChild.checked, b.appendChecked = h.checked, i.removeChild(h), i.appendChild(n);
  if (n.attachEvent)for (k in{submit: !0, change: !0, focusin: !0})j = "on" + k, l = j in n, l || (n.setAttribute(j, "return;"), l = typeof n[j] == "function"), b[k + "Bubbles"] = l;
  return p(function () {
  var c, d, f, g, h = "padding:0;margin:0;border:0;display:block;overflow:hidden;", i = e.getElementsByTagName("body")[0];
  if (!i)return;
  c = e.createElement("div"), c.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px", i.insertBefore(c, i.firstChild), d = e.createElement("div"), c.appendChild(d), d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", f = d.getElementsByTagName("td"), f[0].style.cssText = "padding:0;margin:0;border:0;display:none", l = f[0].offsetHeight === 0, f[0].style.display = "", f[1].style.display = "none", b.reliableHiddenOffsets = l && f[0].offsetHeight === 0, d.innerHTML = "", d.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%;", b.boxSizing = d.offsetWidth === 4, b.doesNotIncludeMarginInBodyOffset = i.offsetTop !== 1, a.getComputedStyle && (b.pixelPosition = (a.getComputedStyle(d, null) || {}).top !== "1%", b.boxSizingReliable = (a.getComputedStyle(d, null) || {width: "4px"}).width === "4px", g = e.createElement("div"), g.style.cssText = d.style.cssText = h, g.style.marginRight = g.style.width = "0", d.style.width = "1px", d.appendChild(g), b.reliableMarginRight = !parseFloat((a.getComputedStyle(g, null) || {}).marginRight)), typeof d.style.zoom != "undefined" && (d.innerHTML = "", d.style.cssText = h + "width:1px;padding:1px;display:inline;zoom:1", b.inlineBlockNeedsLayout = d.offsetWidth === 3, d.style.display = "block", d.style.overflow = "visible", d.innerHTML = "<div></div>", d.firstChild.style.width = "5px", b.shrinkWrapBlocks = d.offsetWidth !== 3, c.style.zoom = 1), i.removeChild(c), c = d = f = g = null
  }), i.removeChild(n), c = d = f = g = h = i = n = null, b
  }();
  var H = /^(?:\{.*\}|\[.*\])$/, I = /([A-Z])/g;
  p.extend({cache: {}, deletedIds: [], uuid: 0, expando: "jQuery" + (p.fn.jquery + Math.random()).replace(/\D/g, ""), noData: {embed: !0, object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", applet: !0}, hasData: function (a) {
  return a = a.nodeType ? p.cache[a[p.expando]] : a[p.expando], !!a && !K(a)
  }, data: function (a, c, d, e) {
  if (!p.acceptData(a))return;
  var f, g, h = p.expando, i = typeof c == "string", j = a.nodeType, k = j ? p.cache : a, l = j ? a[h] : a[h] && h;
  if ((!l || !k[l] || !e && !k[l].data) && i && d === b)return;
  l || (j ? a[h] = l = p.deletedIds.pop() || ++p.uuid : l = h), k[l] || (k[l] = {}, j || (k[l].toJSON = p.noop));
  if (typeof c == "object" || typeof c == "function")e ? k[l] = p.extend(k[l], c) : k[l].data = p.extend(k[l].data, c);
  return f = k[l], e || (f.data || (f.data = {}), f = f.data), d !== b && (f[p.camelCase(c)] = d), i ? (g = f[c], g == null && (g = f[p.camelCase(c)])) : g = f, g
  }, removeData: function (a, b, c) {
  if (!p.acceptData(a))return;
  var d, e, f, g = a.nodeType, h = g ? p.cache : a, i = g ? a[p.expando] : p.expando;
  if (!h[i])return;
  if (b) {
  d = c ? h[i] : h[i].data;
  if (d) {
  p.isArray(b) || (b in d ? b = [b] : (b = p.camelCase(b), b in d ? b = [b] : b = b.split(" ")));
  for (e = 0, f = b.length; e < f; e++)delete d[b[e]];
  if (!(c ? K : p.isEmptyObject)(d))return
  }
  }
  if (!c) {
  delete h[i].data;
  if (!K(h[i]))return
  }
  g ? p.cleanData([a], !0) : p.support.deleteExpando || h != h.window ? delete h[i] : h[i] = null
  }, _data: function (a, b, c) {
  return p.data(a, b, c, !0)
  }, acceptData: function (a) {
  var b = a.nodeName && p.noData[a.nodeName.toLowerCase()];
  return!b || b !== !0 && a.getAttribute("classid") === b
  }}), p.fn.extend({data: function (a, c) {
  var d, e, f, g, h, i = this[0], j = 0, k = null;
  if (a === b) {
  if (this.length) {
  k = p.data(i);
  if (i.nodeType === 1 && !p._data(i, "parsedAttrs")) {
  f = i.attributes;
  for (h = f.length; j < h; j++)g = f[j].name, g.indexOf("data-") === 0 && (g = p.camelCase(g.substring(5)), J(i, g, k[g]));
  p._data(i, "parsedAttrs", !0)
  }
  }
  return k
  }
  return typeof a == "object" ? this.each(function () {
  p.data(this, a)
  }) : (d = a.split(".", 2), d[1] = d[1] ? "." + d[1] : "", e = d[1] + "!", p.access(this, function (c) {
  if (c === b)return k = this.triggerHandler("getData" + e, [d[0]]), k === b && i && (k = p.data(i, a), k = J(i, a, k)), k === b && d[1] ? this.data(d[0]) : k;
  d[1] = c, this.each(function () {
  var b = p(this);
  b.triggerHandler("setData" + e, d), p.data(this, a, c), b.triggerHandler("changeData" + e, d)
  })
  }, null, c, arguments.length > 1, null, !1))
  }, removeData: function (a) {
  return this.each(function () {
  p.removeData(this, a)
  })
  }}), p.extend({queue: function (a, b, c) {
  var d;
  if (a)return b = (b || "fx") + "queue", d = p._data(a, b), c && (!d || p.isArray(c) ? d = p._data(a, b, p.makeArray(c)) : d.push(c)), d || []
  }, dequeue: function (a, b) {
  b = b || "fx";
  var c = p.queue(a, b), d = c.shift(), e = p._queueHooks(a, b), f = function () {
  p.dequeue(a, b)
  };
  d === "inprogress" && (d = c.shift()), d && (b === "fx" && c.unshift("inprogress"), delete e.stop, d.call(a, f, e)), !c.length && e && e.empty.fire()
  }, _queueHooks: function (a, b) {
  var c = b + "queueHooks";
  return p._data(a, c) || p._data(a, c, {empty: p.Callbacks("once memory").add(function () {
  p.removeData(a, b + "queue", !0), p.removeData(a, c, !0)
  })})
  }}), p.fn.extend({queue: function (a, c) {
  var d = 2;
  return typeof a != "string" && (c = a, a = "fx", d--), arguments.length < d ? p.queue(this[0], a) : c === b ? this : this.each(function () {
  var b = p.queue(this, a, c);
  p._queueHooks(this, a), a === "fx" && b[0] !== "inprogress" && p.dequeue(this, a)
  })
  }, dequeue: function (a) {
  return this.each(function () {
  p.dequeue(this, a)
  })
  }, delay: function (a, b) {
  return a = p.fx ? p.fx.speeds[a] || a : a, b = b || "fx", this.queue(b, function (b, c) {
  var d = setTimeout(b, a);
  c.stop = function () {
  clearTimeout(d)
  }
  })
  }, clearQueue: function (a) {
  return this.queue(a || "fx", [])
  }, promise: function (a, c) {
  var d, e = 1, f = p.Deferred(), g = this, h = this.length, i = function () {
  --e || f.resolveWith(g, [g])
  };
  typeof a != "string" && (c = a, a = b), a = a || "fx";
  while (h--)(d = p._data(g[h], a + "queueHooks")) && d.empty && (e++, d.empty.add(i));
  return i(), f.promise(c)
  }});
  var L, M, N, O = /[\t\r\n]/g, P = /\r/g, Q = /^(?:button|input)$/i, R = /^(?:button|input|object|select|textarea)$/i, S = /^a(?:rea|)$/i, T = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, U = p.support.getSetAttribute;
  p.fn.extend({attr: function (a, b) {
  return p.access(this, p.attr, a, b, arguments.length > 1)
  }, removeAttr: function (a) {
  return this.each(function () {
  p.removeAttr(this, a)
  })
  }, prop: function (a, b) {
  return p.access(this, p.prop, a, b, arguments.length > 1)
  }, removeProp: function (a) {
  return a = p.propFix[a] || a, this.each(function () {
  try {
  this[a] = b, delete this[a]
  } catch (c) {
  }
  })
  }, addClass: function (a) {
  var b, c, d, e, f, g, h;
  if (p.isFunction(a))return this.each(function (b) {
  p(this).addClass(a.call(this, b, this.className))
  });
  if (a && typeof a == "string") {
  b = a.split(s);
  for (c = 0, d = this.length; c < d; c++) {
  e = this[c];
  if (e.nodeType === 1)if (!e.className && b.length === 1)e.className = a; else {
  f = " " + e.className + " ";
  for (g = 0, h = b.length; g < h; g++)~f.indexOf(" " + b[g] + " ") || (f += b[g] + " ");
  e.className = p.trim(f)
  }
  }
  }
  return this
  }, removeClass: function (a) {
  var c, d, e, f, g, h, i;
  if (p.isFunction(a))return this.each(function (b) {
  p(this).removeClass(a.call(this, b, this.className))
  });
  if (a && typeof a == "string" || a === b) {
  c = (a || "").split(s);
  for (h = 0, i = this.length; h < i; h++) {
  e = this[h];
  if (e.nodeType === 1 && e.className) {
  d = (" " + e.className + " ").replace(O, " ");
  for (f = 0, g = c.length; f < g; f++)while (d.indexOf(" " + c[f] + " ") > -1)d = d.replace(" " + c[f] + " ", " ");
  e.className = a ? p.trim(d) : ""
  }
  }
  }
  return this
  }, toggleClass: function (a, b) {
  var c = typeof a, d = typeof b == "boolean";
  return p.isFunction(a) ? this.each(function (c) {
  p(this).toggleClass(a.call(this, c, this.className, b), b)
  }) : this.each(function () {
  if (c === "string") {
  var e, f = 0, g = p(this), h = b, i = a.split(s);
  while (e = i[f++])h = d ? h : !g.hasClass(e), g[h ? "addClass" : "removeClass"](e)
  } else if (c === "undefined" || c === "boolean")this.className && p._data(this, "__className__", this.className), this.className = this.className || a === !1 ? "" : p._data(this, "__className__") || ""
  })
  }, hasClass: function (a) {
  var b = " " + a + " ", c = 0, d = this.length;
  for (; c < d; c++)if (this[c].nodeType === 1 && (" " + this[c].className + " ").replace(O, " ").indexOf(b) > -1)return!0;
  return!1
  }, val: function (a) {
  var c, d, e, f = this[0];
  if (!arguments.length) {
  if (f)return c = p.valHooks[f.type] || p.valHooks[f.nodeName.toLowerCase()], c && "get"in c && (d = c.get(f, "value")) !== b ? d : (d = f.value, typeof d == "string" ? d.replace(P, "") : d == null ? "" : d);
  return
  }
  return e = p.isFunction(a), this.each(function (d) {
  var f, g = p(this);
  if (this.nodeType !== 1)return;
  e ? f = a.call(this, d, g.val()) : f = a, f == null ? f = "" : typeof f == "number" ? f += "" : p.isArray(f) && (f = p.map(f, function (a) {
  return a == null ? "" : a + ""
  })), c = p.valHooks[this.type] || p.valHooks[this.nodeName.toLowerCase()];
  if (!c || !("set"in c) || c.set(this, f, "value") === b)this.value = f
  })
  }}), p.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, f = a.selectedIndex, g = [], h = a.options, i = a.type === "select-one";
  if (f < 0)return null;
  c = i ? f : 0, d = i ? f + 1 : h.length;
  for (; c < d; c++) {
  e = h[c];
  if (e.selected && (p.support.optDisabled ? !e.disabled : e.getAttribute("disabled") === null) && (!e.parentNode.disabled || !p.nodeName(e.parentNode, "optgroup"))) {
  b = p(e).val();
  if (i)return b;
  g.push(b)
  }
  }
  return i && !g.length && h.length ? p(h[f]).val() : g
  }, set: function (a, b) {
  var c = p.makeArray(b);
  return p(a).find("option").each(function () {
  this.selected = p.inArray(p(this).val(), c) >= 0
  }), c.length || (a.selectedIndex = -1), c
  }}}, attrFn: {}, attr: function (a, c, d, e) {
  var f, g, h, i = a.nodeType;
  if (!a || i === 3 || i === 8 || i === 2)return;
  if (e && p.isFunction(p.fn[c]))return p(a)[c](d);
  if (typeof a.getAttribute == "undefined")return p.prop(a, c, d);
  h = i !== 1 || !p.isXMLDoc(a), h && (c = c.toLowerCase(), g = p.attrHooks[c] || (T.test(c) ? M : L));
  if (d !== b) {
  if (d === null) {
  p.removeAttr(a, c);
  return
  }
  return g && "set"in g && h && (f = g.set(a, d, c)) !== b ? f : (a.setAttribute(c, "" + d), d)
  }
  return g && "get"in g && h && (f = g.get(a, c)) !== null ? f : (f = a.getAttribute(c), f === null ? b : f)
  }, removeAttr: function (a, b) {
  var c, d, e, f, g = 0;
  if (b && a.nodeType === 1) {
  d = b.split(s);
  for (; g < d.length; g++)e = d[g], e && (c = p.propFix[e] || e, f = T.test(e), f || p.attr(a, e, ""), a.removeAttribute(U ? e : c), f && c in a && (a[c] = !1))
  }
  }, attrHooks: {type: {set: function (a, b) {
  if (Q.test(a.nodeName) && a.parentNode)p.error("type property can't be changed"); else if (!p.support.radioValue && b === "radio" && p.nodeName(a, "input")) {
  var c = a.value;
  return a.setAttribute("type", b), c && (a.value = c), b
  }
  }}, value: {get: function (a, b) {
  return L && p.nodeName(a, "button") ? L.get(a, b) : b in a ? a.value : null
  }, set: function (a, b, c) {
  if (L && p.nodeName(a, "button"))return L.set(a, b, c);
  a.value = b
  }}}, propFix: {tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable"}, prop: function (a, c, d) {
  var e, f, g, h = a.nodeType;
  if (!a || h === 3 || h === 8 || h === 2)return;
  return g = h !== 1 || !p.isXMLDoc(a), g && (c = p.propFix[c] || c, f = p.propHooks[c]), d !== b ? f && "set"in f && (e = f.set(a, d, c)) !== b ? e : a[c] = d : f && "get"in f && (e = f.get(a, c)) !== null ? e : a[c]
  }, propHooks: {tabIndex: {get: function (a) {
  var c = a.getAttributeNode("tabindex");
  return c && c.specified ? parseInt(c.value, 10) : R.test(a.nodeName) || S.test(a.nodeName) && a.href ? 0 : b
  }}}}), M = {get: function (a, c) {
  var d, e = p.prop(a, c);
  return e === !0 || typeof e != "boolean" && (d = a.getAttributeNode(c)) && d.nodeValue !== !1 ? c.toLowerCase() : b
  }, set: function (a, b, c) {
  var d;
  return b === !1 ? p.removeAttr(a, c) : (d = p.propFix[c] || c, d in a && (a[d] = !0), a.setAttribute(c, c.toLowerCase())), c
  }}, U || (N = {name: !0, id: !0, coords: !0}, L = p.valHooks.button = {get: function (a, c) {
  var d;
  return d = a.getAttributeNode(c), d && (N[c] ? d.value !== "" : d.specified) ? d.value : b
  }, set: function (a, b, c) {
  var d = a.getAttributeNode(c);
  return d || (d = e.createAttribute(c), a.setAttributeNode(d)), d.value = b + ""
  }}, p.each(["width", "height"], function (a, b) {
  p.attrHooks[b] = p.extend(p.attrHooks[b], {set: function (a, c) {
  if (c === "")return a.setAttribute(b, "auto"), c
  }})
  }), p.attrHooks.contenteditable = {get: L.get, set: function (a, b, c) {
  b === "" && (b = "false"), L.set(a, b, c)
  }}), p.support.hrefNormalized || p.each(["href", "src", "width", "height"], function (a, c) {
  p.attrHooks[c] = p.extend(p.attrHooks[c], {get: function (a) {
  var d = a.getAttribute(c, 2);
  return d === null ? b : d
  }})
  }), p.support.style || (p.attrHooks.style = {get: function (a) {
  return a.style.cssText.toLowerCase() || b
  }, set: function (a, b) {
  return a.style.cssText = "" + b
  }}), p.support.optSelected || (p.propHooks.selected = p.extend(p.propHooks.selected, {get: function (a) {
  var b = a.parentNode;
  return b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex), null
  }})), p.support.enctype || (p.propFix.enctype = "encoding"), p.support.checkOn || p.each(["radio", "checkbox"], function () {
  p.valHooks[this] = {get: function (a) {
  return a.getAttribute("value") === null ? "on" : a.value
  }}
  }), p.each(["radio", "checkbox"], function () {
  p.valHooks[this] = p.extend(p.valHooks[this], {set: function (a, b) {
  if (p.isArray(b))return a.checked = p.inArray(p(a).val(), b) >= 0
  }})
  });
  var V = /^(?:textarea|input|select)$/i, W = /^([^\.]*|)(?:\.(.+)|)$/, X = /(?:^|\s)hover(\.\S+|)\b/, Y = /^key/, Z = /^(?:mouse|contextmenu)|click/, $ = /^(?:focusinfocus|focusoutblur)$/, _ = function (a) {
  return p.event.special.hover ? a : a.replace(X, "mouseenter$1 mouseleave$1")
  };
  p.event = {add: function (a, c, d, e, f) {
  var g, h, i, j, k, l, m, n, o, q, r;
  if (a.nodeType === 3 || a.nodeType === 8 || !c || !d || !(g = p._data(a)))return;
  d.handler && (o = d, d = o.handler, f = o.selector), d.guid || (d.guid = p.guid++), i = g.events, i || (g.events = i = {}), h = g.handle, h || (g.handle = h = function (a) {
  return typeof p != "undefined" && (!a || p.event.triggered !== a.type) ? p.event.dispatch.apply(h.elem, arguments) : b
  }, h.elem = a), c = p.trim(_(c)).split(" ");
  for (j = 0; j < c.length; j++) {
  k = W.exec(c[j]) || [], l = k[1], m = (k[2] || "").split(".").sort(), r = p.event.special[l] || {}, l = (f ? r.delegateType : r.bindType) || l, r = p.event.special[l] || {}, n = p.extend({type: l, origType: k[1], data: e, handler: d, guid: d.guid, selector: f, namespace: m.join(".")}, o), q = i[l];
  if (!q) {
  q = i[l] = [], q.delegateCount = 0;
  if (!r.setup || r.setup.call(a, e, m, h) === !1)a.addEventListener ? a.addEventListener(l, h, !1) : a.attachEvent && a.attachEvent("on" + l, h)
  }
  r.add && (r.add.call(a, n), n.handler.guid || (n.handler.guid = d.guid)), f ? q.splice(q.delegateCount++, 0, n) : q.push(n), p.event.global[l] = !0
  }
  a = null
  }, global: {}, remove: function (a, b, c, d, e) {
  var f, g, h, i, j, k, l, m, n, o, q, r = p.hasData(a) && p._data(a);
  if (!r || !(m = r.events))return;
  b = p.trim(_(b || "")).split(" ");
  for (f = 0; f < b.length; f++) {
  g = W.exec(b[f]) || [], h = i = g[1], j = g[2];
  if (!h) {
  for (h in m)p.event.remove(a, h + b[f], c, d, !0);
  continue
  }
  n = p.event.special[h] || {}, h = (d ? n.delegateType : n.bindType) || h, o = m[h] || [], k = o.length, j = j ? new RegExp("(^|\\.)" + j.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
  for (l = 0; l < o.length; l++)q = o[l], (e || i === q.origType) && (!c || c.guid === q.guid) && (!j || j.test(q.namespace)) && (!d || d === q.selector || d === "**" && q.selector) && (o.splice(l--, 1), q.selector && o.delegateCount--, n.remove && n.remove.call(a, q));
  o.length === 0 && k !== o.length && ((!n.teardown || n.teardown.call(a, j, r.handle) === !1) && p.removeEvent(a, h, r.handle), delete m[h])
  }
  p.isEmptyObject(m) && (delete r.handle, p.removeData(a, "events", !0))
  }, customEvent: {getData: !0, setData: !0, changeData: !0}, trigger: function (c, d, f, g) {
  if (!f || f.nodeType !== 3 && f.nodeType !== 8) {
  var h, i, j, k, l, m, n, o, q, r, s = c.type || c, t = [];
  if ($.test(s + p.event.triggered))return;
  s.indexOf("!") >= 0 && (s = s.slice(0, -1), i = !0), s.indexOf(".") >= 0 && (t = s.split("."), s = t.shift(), t.sort());
  if ((!f || p.event.customEvent[s]) && !p.event.global[s])return;
  c = typeof c == "object" ? c[p.expando] ? c : new p.Event(s, c) : new p.Event(s), c.type = s, c.isTrigger = !0, c.exclusive = i, c.namespace = t.join("."), c.namespace_re = c.namespace ? new RegExp("(^|\\.)" + t.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, m = s.indexOf(":") < 0 ? "on" + s : "";
  if (!f) {
  h = p.cache;
  for (j in h)h[j].events && h[j].events[s] && p.event.trigger(c, d, h[j].handle.elem, !0);
  return
  }
  c.result = b, c.target || (c.target = f), d = d != null ? p.makeArray(d) : [], d.unshift(c), n = p.event.special[s] || {};
  if (n.trigger && n.trigger.apply(f, d) === !1)return;
  q = [
  [f, n.bindType || s]
  ];
  if (!g && !n.noBubble && !p.isWindow(f)) {
  r = n.delegateType || s, k = $.test(r + s) ? f : f.parentNode;
  for (l = f; k; k = k.parentNode)q.push([k, r]), l = k;
  l === (f.ownerDocument || e) && q.push([l.defaultView || l.parentWindow || a, r])
  }
  for (j = 0; j < q.length && !c.isPropagationStopped(); j++)k = q[j][0], c.type = q[j][1], o = (p._data(k, "events") || {})[c.type] && p._data(k, "handle"), o && o.apply(k, d), o = m && k[m], o && p.acceptData(k) && o.apply(k, d) === !1 && c.preventDefault();
  return c.type = s, !g && !c.isDefaultPrevented() && (!n._default || n._default.apply(f.ownerDocument, d) === !1) && (s !== "click" || !p.nodeName(f, "a")) && p.acceptData(f) && m && f[s] && (s !== "focus" && s !== "blur" || c.target.offsetWidth !== 0) && !p.isWindow(f) && (l = f[m], l && (f[m] = null), p.event.triggered = s, f[s](), p.event.triggered = b, l && (f[m] = l)), c.result
  }
  return
  }, dispatch: function (c) {
  c = p.event.fix(c || a.event);
  var d, e, f, g, h, i, j, k, l, m, n, o = (p._data(this, "events") || {})[c.type] || [], q = o.delegateCount, r = [].slice.call(arguments), s = !c.exclusive && !c.namespace, t = p.event.special[c.type] || {}, u = [];
  r[0] = c, c.delegateTarget = this;
  if (t.preDispatch && t.preDispatch.call(this, c) === !1)return;
  if (q && (!c.button || c.type !== "click")) {
  g = p(this), g.context = this;
  for (f = c.target; f != this; f = f.parentNode || this)if (f.disabled !== !0 || c.type !== "click") {
  i = {}, k = [], g[0] = f;
  for (d = 0; d < q; d++)l = o[d], m = l.selector, i[m] === b && (i[m] = g.is(m)), i[m] && k.push(l);
  k.length && u.push({elem: f, matches: k})
  }
  }
  o.length > q && u.push({elem: this, matches: o.slice(q)});
  for (d = 0; d < u.length && !c.isPropagationStopped(); d++) {
  j = u[d], c.currentTarget = j.elem;
  for (e = 0; e < j.matches.length && !c.isImmediatePropagationStopped(); e++) {
  l = j.matches[e];
  if (s || !c.namespace && !l.namespace || c.namespace_re && c.namespace_re.test(l.namespace))c.data = l.data, c.handleObj = l, h = ((p.event.special[l.origType] || {}).handle || l.handler).apply(j.elem, r), h !== b && (c.result = h, h === !1 && (c.preventDefault(), c.stopPropagation()))
  }
  }
  return t.postDispatch && t.postDispatch.call(this, c), c.result
  }, props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: {props: "char charCode key keyCode".split(" "), filter: function (a, b) {
  return a.which == null && (a.which = b.charCode != null ? b.charCode : b.keyCode), a
  }}, mouseHooks: {props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (a, c) {
  var d, f, g, h = c.button, i = c.fromElement;
  return a.pageX == null && c.clientX != null && (d = a.target.ownerDocument || e, f = d.documentElement, g = d.body, a.pageX = c.clientX + (f && f.scrollLeft || g && g.scrollLeft || 0) - (f && f.clientLeft || g && g.clientLeft || 0), a.pageY = c.clientY + (f && f.scrollTop || g && g.scrollTop || 0) - (f && f.clientTop || g && g.clientTop || 0)), !a.relatedTarget && i && (a.relatedTarget = i === a.target ? c.toElement : i), !a.which && h !== b && (a.which = h & 1 ? 1 : h & 2 ? 3 : h & 4 ? 2 : 0), a
  }}, fix: function (a) {
  if (a[p.expando])return a;
  var b, c, d = a, f = p.event.fixHooks[a.type] || {}, g = f.props ? this.props.concat(f.props) : this.props;
  a = p.Event(d);
  for (b = g.length; b;)c = g[--b], a[c] = d[c];
  return a.target || (a.target = d.srcElement || e), a.target.nodeType === 3 && (a.target = a.target.parentNode), a.metaKey = !!a.metaKey, f.filter ? f.filter(a, d) : a
  }, special: {ready: {setup: p.bindReady}, load: {noBubble: !0}, focus: {delegateType: "focusin"}, blur: {delegateType: "focusout"}, beforeunload: {setup: function (a, b, c) {
  p.isWindow(this) && (this.onbeforeunload = c)
  }, teardown: function (a, b) {
  this.onbeforeunload === b && (this.onbeforeunload = null)
  }}}, simulate: function (a, b, c, d) {
  var e = p.extend(new p.Event, c, {type: a, isSimulated: !0, originalEvent: {}});
  d ? p.event.trigger(e, null, b) : p.event.dispatch.call(b, e), e.isDefaultPrevented() && c.preventDefault()
  }}, p.event.handle = p.event.dispatch, p.removeEvent = e.removeEventListener ? function (a, b, c) {
  a.removeEventListener && a.removeEventListener(b, c, !1)
  } : function (a, b, c) {
  var d = "on" + b;
  a.detachEvent && (typeof a[d] == "undefined" && (a[d] = null), a.detachEvent(d, c))
  }, p.Event = function (a, b) {
  if (this instanceof p.Event)a && a.type ? (this.originalEvent = a, this.type = a.type, this.isDefaultPrevented = a.defaultPrevented || a.returnValue === !1 || a.getPreventDefault && a.getPreventDefault() ? bb : ba) : this.type = a, b && p.extend(this, b), this.timeStamp = a && a.timeStamp || p.now(), this[p.expando] = !0; else return new p.Event(a, b)
  }, p.Event.prototype = {preventDefault: function () {
  this.isDefaultPrevented = bb;
  var a = this.originalEvent;
  if (!a)return;
  a.preventDefault ? a.preventDefault() : a.returnValue = !1
  }, stopPropagation: function () {
  this.isPropagationStopped = bb;
  var a = this.originalEvent;
  if (!a)return;
  a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0
  }, stopImmediatePropagation: function () {
  this.isImmediatePropagationStopped = bb, this.stopPropagation()
  }, isDefaultPrevented: ba, isPropagationStopped: ba, isImmediatePropagationStopped: ba}, p.each({mouseenter: "mouseover", mouseleave: "mouseout"}, function (a, b) {
  p.event.special[a] = {delegateType: b, bindType: b, handle: function (a) {
  var c, d = this, e = a.relatedTarget, f = a.handleObj, g = f.selector;
  if (!e || e !== d && !p.contains(d, e))a.type = f.origType, c = f.handler.apply(this, arguments), a.type = b;
  return c
  }}
  }), p.support.submitBubbles || (p.event.special.submit = {setup: function () {
  if (p.nodeName(this, "form"))return!1;
  p.event.add(this, "click._submit keypress._submit", function (a) {
  var c = a.target, d = p.nodeName(c, "input") || p.nodeName(c, "button") ? c.form : b;
  d && !p._data(d, "_submit_attached") && (p.event.add(d, "submit._submit", function (a) {
  a._submit_bubble = !0
  }), p._data(d, "_submit_attached", !0))
  })
  }, postDispatch: function (a) {
  a._submit_bubble && (delete a._submit_bubble, this.parentNode && !a.isTrigger && p.event.simulate("submit", this.parentNode, a, !0))
  }, teardown: function () {
  if (p.nodeName(this, "form"))return!1;
  p.event.remove(this, "._submit")
  }}), p.support.changeBubbles || (p.event.special.change = {setup: function () {
  if (V.test(this.nodeName)) {
  if (this.type === "checkbox" || this.type === "radio")p.event.add(this, "propertychange._change", function (a) {
  a.originalEvent.propertyName === "checked" && (this._just_changed = !0)
  }), p.event.add(this, "click._change", function (a) {
  this._just_changed && !a.isTrigger && (this._just_changed = !1), p.event.simulate("change", this, a, !0)
  });
  return!1
  }
  p.event.add(this, "beforeactivate._change", function (a) {
  var b = a.target;
  V.test(b.nodeName) && !p._data(b, "_change_attached") && (p.event.add(b, "change._change", function (a) {
  this.parentNode && !a.isSimulated && !a.isTrigger && p.event.simulate("change", this.parentNode, a, !0)
  }), p._data(b, "_change_attached", !0))
  })
  }, handle: function (a) {
  var b = a.target;
  if (this !== b || a.isSimulated || a.isTrigger || b.type !== "radio" && b.type !== "checkbox")return a.handleObj.handler.apply(this, arguments)
  }, teardown: function () {
  return p.event.remove(this, "._change"), V.test(this.nodeName)
  }}), p.support.focusinBubbles || p.each({focus: "focusin", blur: "focusout"}, function (a, b) {
  var c = 0, d = function (a) {
  p.event.simulate(b, a.target, p.event.fix(a), !0)
  };
  p.event.special[b] = {setup: function () {
  c++ === 0 && e.addEventListener(a, d, !0)
  }, teardown: function () {
  --c === 0 && e.removeEventListener(a, d, !0)
  }}
  }), p.fn.extend({on: function (a, c, d, e, f) {
  var g, h;
  if (typeof a == "object") {
  typeof c != "string" && (d = d || c, c = b);
  for (h in a)this.on(h, c, d, a[h], f);
  return this
  }
  d == null && e == null ? (e = c, d = c = b) : e == null && (typeof c == "string" ? (e = d, d = b) : (e = d, d = c, c = b));
  if (e === !1)e = ba; else if (!e)return this;
  return f === 1 && (g = e, e = function (a) {
  return p().off(a), g.apply(this, arguments)
  }, e.guid = g.guid || (g.guid = p.guid++)), this.each(function () {
  p.event.add(this, a, e, d, c)
  })
  }, one: function (a, b, c, d) {
  return this.on(a, b, c, d, 1)
  }, off: function (a, c, d) {
  var e, f;
  if (a && a.preventDefault && a.handleObj)return e = a.handleObj, p(a.delegateTarget).off(e.namespace ? e.origType + "." + e.namespace : e.origType, e.selector, e.handler), this;
  if (typeof a == "object") {
  for (f in a)this.off(f, c, a[f]);
  return this
  }
  if (c === !1 || typeof c == "function")d = c, c = b;
  return d === !1 && (d = ba), this.each(function () {
  p.event.remove(this, a, d, c)
  })
  }, bind: function (a, b, c) {
  return this.on(a, null, b, c)
  }, unbind: function (a, b) {
  return this.off(a, null, b)
  }, live: function (a, b, c) {
  return p(this.context).on(a, this.selector, b, c), this
  }, die: function (a, b) {
  return p(this.context).off(a, this.selector || "**", b), this
  }, delegate: function (a, b, c, d) {
  return this.on(b, a, c, d)
  }, undelegate: function (a, b, c) {
  return arguments.length == 1 ? this.off(a, "**") : this.off(b, a || "**", c)
  }, trigger: function (a, b) {
  return this.each(function () {
  p.event.trigger(a, b, this)
  })
  }, triggerHandler: function (a, b) {
  if (this[0])return p.event.trigger(a, b, this[0], !0)
  }, toggle: function (a) {
  var b = arguments, c = a.guid || p.guid++, d = 0, e = function (c) {
  var e = (p._data(this, "lastToggle" + a.guid) || 0) % d;
  return p._data(this, "lastToggle" + a.guid, e + 1), c.preventDefault(), b[e].apply(this, arguments) || !1
  };
  e.guid = c;
  while (d < b.length)b[d++].guid = c;
  return this.click(e)
  }, hover: function (a, b) {
  return this.mouseenter(a).mouseleave(b || a)
  }}), p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function (a, b) {
  p.fn[b] = function (a, c) {
  return c == null && (c = a, a = null), arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
  }, Y.test(b) && (p.event.fixHooks[b] = p.event.keyHooks), Z.test(b) && (p.event.fixHooks[b] = p.event.mouseHooks)
  }), function (a, b) {
  function bd(a, b, c, d) {
  var e = 0, f = b.length;
  for (; e < f; e++)Z(a, b[e], c, d)
  }
 
  function be(a, b, c, d, e, f) {
  var g, h = $.setFilters[b.toLowerCase()];
  return h || Z.error(b), (a || !(g = e)) && bd(a || "*", d, g = [], e), g.length > 0 ? h(g, c, f) : []
  }
 
  function bf(a, c, d, e, f) {
  var g, h, i, j, k, l, m, n, p = 0, q = f.length, s = L.POS, t = new RegExp("^" + s.source + "(?!" + r + ")", "i"), u = function () {
  var a = 1, c = arguments.length - 2;
  for (; a < c; a++)arguments[a] === b && (g[a] = b)
  };
  for (; p < q; p++) {
  s.exec(""), a = f[p], j = [], i = 0, k = e;
  while (g = s.exec(a)) {
  n = s.lastIndex = g.index + g[0].length;
  if (n > i) {
  m = a.slice(i, g.index), i = n, l = [c], B.test(m) && (k && (l = k), k = e);
  if (h = H.test(m))m = m.slice(0, -5).replace(B, "$&*");
  g.length > 1 && g[0].replace(t, u), k = be(m, g[1], g[2], l, k, h)
  }
  }
  k ? (j = j.concat(k), (m = a.slice(i)) && m !== ")" ? B.test(m) ? bd(m, j, d, e) : Z(m, c, d, e ? e.concat(k) : k) : o.apply(d, j)) : Z(a, c, d, e)
  }
  return q === 1 ? d : Z.uniqueSort(d)
  }
 
  function bg(a, b, c) {
  var d, e, f, g = [], i = 0, j = D.exec(a), k = !j.pop() && !j.pop(), l = k && a.match(C) || [""], m = $.preFilter, n = $.filter, o = !c && b !== h;
  for (; (e = l[i]) != null && k; i++) {
  g.push(d = []), o && (e = " " + e);
  while (e) {
  k = !1;
  if (j = B.exec(e))e = e.slice(j[0].length), k = d.push({part: j.pop().replace(A, " "), captures: j});
  for (f in n)(j = L[f].exec(e)) && (!m[f] || (j = m[f](j, b, c))) && (e = e.slice(j.shift().length), k = d.push({part: f, captures: j}));
  if (!k)break
  }
  }
  return k || Z.error(a), g
  }
 
  function bh(a, b, e) {
  var f = b.dir, g = m++;
  return a || (a = function (a) {
  return a === e
  }), b.first ? function (b, c) {
  while (b = b[f])if (b.nodeType === 1)return a(b, c) && b
  } : function (b, e) {
  var h, i = g + "." + d, j = i + "." + c;
  while (b = b[f])if (b.nodeType === 1) {
  if ((h = b[q]) === j)return b.sizset;
  if (typeof h == "string" && h.indexOf(i) === 0) {
  if (b.sizset)return b
  } else {
  b[q] = j;
  if (a(b, e))return b.sizset = !0, b;
  b.sizset = !1
  }
  }
  }
  }
 
  function bi(a, b) {
  return a ? function (c, d) {
  var e = b(c, d);
  return e && a(e === !0 ? c : e, d)
  } : b
  }
 
  function bj(a, b, c) {
  var d, e, f = 0;
  for (; d = a[f]; f++)$.relative[d.part] ? e = bh(e, $.relative[d.part], b) : (d.captures.push(b, c), e = bi(e, $.filter[d.part].apply(null, d.captures)));
  return e
  }
 
  function bk(a) {
  return function (b, c) {
  var d, e = 0;
  for (; d = a[e]; e++)if (d(b, c))return!0;
  return!1
  }
  }
 
  var c, d, e, f, g, h = a.document, i = h.documentElement, j = "undefined", k = !1, l = !0, m = 0, n = [].slice, o = [].push, q = ("sizcache" + Math.random()).replace(".", ""), r = "[\\x20\\t\\r\\n\\f]", s = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", t = s.replace("w", "w#"), u = "([*^$|!~]?=)", v = "\\[" + r + "*(" + s + ")" + r + "*(?:" + u + r + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + t + ")|)|)" + r + "*\\]", w = ":(" + s + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", x = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", y = r + "*([\\x20\\t\\r\\n\\f>+~])" + r + "*", z = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + v + "|" + w.replace(2, 7) + "|[^\\\\(),])+", A = new RegExp("^" + r + "+|((?:^|[^\\\\])(?:\\\\.)*)" + r + "+$", "g"), B = new RegExp("^" + y), C = new RegExp(z + "?(?=" + r + "*,|$)", "g"), D = new RegExp("^(?:(?!,)(?:(?:^|,)" + r + "*" + z + ")*?|" + r + "*(.*?))(\\)|$)"), E = new RegExp(z.slice(19, -6) + "\\x20\\t\\r\\n\\f>+~])+|" + y, "g"), F = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, G = /[\x20\t\r\n\f]*[+~]/, H = /:not\($/, I = /h\d/i, J = /input|select|textarea|button/i, K = /\\(?!\\)/g, L = {ID: new RegExp("^#(" + s + ")"), CLASS: new RegExp("^\\.(" + s + ")"), NAME: new RegExp("^\\[name=['\"]?(" + s + ")['\"]?\\]"), TAG: new RegExp("^(" + s.replace("[-", "[-\\*") + ")"), ATTR: new RegExp("^" + v), PSEUDO: new RegExp("^" + w), CHILD: new RegExp("^:(only|nth|last|first)-child(?:\\(" + r + "*(even|odd|(([+-]|)(\\d*)n|)" + r + "*(?:([+-]|)" + r + "*(\\d+)|))" + r + "*\\)|)", "i"), POS: new RegExp(x, "ig"), needsContext: new RegExp("^" + r + "*[>+~]|" + x, "i")}, M = {}, N = [], O = {}, P = [], Q = function (a) {
  return a.sizzleFilter = !0, a
  }, R = function (a) {
  return function (b) {
  return b.nodeName.toLowerCase() === "input" && b.type === a
  }
  }, S = function (a) {
  return function (b) {
  var c = b.nodeName.toLowerCase();
  return(c === "input" || c === "button") && b.type === a
  }
  }, T = function (a) {
  var b = !1, c = h.createElement("div");
  try {
  b = a(c)
  } catch (d) {
  }
  return c = null, b
  }, U = T(function (a) {
  a.innerHTML = "<select></select>";
  var b = typeof a.lastChild.getAttribute("multiple");
  return b !== "boolean" && b !== "string"
  }), V = T(function (a) {
  a.id = q + 0, a.innerHTML = "<a name='" + q + "'></a><div name='" + q + "'></div>", i.insertBefore(a, i.firstChild);
  var b = h.getElementsByName && h.getElementsByName(q).length === 2 + h.getElementsByName(q + 0).length;
  return g = !h.getElementById(q), i.removeChild(a), b
  }), W = T(function (a) {
  return a.appendChild(h.createComment("")), a.getElementsByTagName("*").length === 0
  }), X = T(function (a) {
  return a.innerHTML = "<a href='#'></a>", a.firstChild && typeof a.firstChild.getAttribute !== j && a.firstChild.getAttribute("href") === "#"
  }), Y = T(function (a) {
  return a.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !a.getElementsByClassName || a.getElementsByClassName("e").length === 0 ? !1 : (a.lastChild.className = "e", a.getElementsByClassName("e").length !== 1)
  }), Z = function (a, b, c, d) {
  c = c || [], b = b || h;
  var e, f, g, i, j = b.nodeType;
  if (j !== 1 && j !== 9)return[];
  if (!a || typeof a != "string")return c;
  g = ba(b);
  if (!g && !d)if (e = F.exec(a))if (i = e[1]) {
  if (j === 9) {
  f = b.getElementById(i);
  if (!f || !f.parentNode)return c;
  if (f.id === i)return c.push(f), c
  } else if (b.ownerDocument && (f = b.ownerDocument.getElementById(i)) && bb(b, f) && f.id === i)return c.push(f), c
  } else {
  if (e[2])return o.apply(c, n.call(b.getElementsByTagName(a), 0)), c;
  if ((i = e[3]) && Y && b.getElementsByClassName)return o.apply(c, n.call(b.getElementsByClassName(i), 0)), c
  }
  return bm(a, b, c, d, g)
  }, $ = Z.selectors = {cacheLength: 50, match: L, order: ["ID", "TAG"], attrHandle: {}, createPseudo: Q, find: {ID: g ? function (a, b, c) {
  if (typeof b.getElementById !== j && !c) {
  var d = b.getElementById(a);
  return d && d.parentNode ? [d] : []
  }
  } : function (a, c, d) {
  if (typeof c.getElementById !== j && !d) {
  var e = c.getElementById(a);
  return e ? e.id === a || typeof e.getAttributeNode !== j && e.getAttributeNode("id").value === a ? [e] : b : []
  }
  }, TAG: W ? function (a, b) {
  if (typeof b.getElementsByTagName !== j)return b.getElementsByTagName(a)
  } : function (a, b) {
  var c = b.getElementsByTagName(a);
  if (a === "*") {
  var d, e = [], f = 0;
  for (; d = c[f]; f++)d.nodeType === 1 && e.push(d);
  return e
  }
  return c
  }}, relative: {">": {dir: "parentNode", first: !0}, " ": {dir: "parentNode"}, "+": {dir: "previousSibling", first: !0}, "~": {dir: "previousSibling"}}, preFilter: {ATTR: function (a) {
  return a[1] = a[1].replace(K, ""), a[3] = (a[4] || a[5] || "").replace(K, ""), a[2] === "~=" && (a[3] = " " + a[3] + " "), a.slice(0, 4)
  }, CHILD: function (a) {
  return a[1] = a[1].toLowerCase(), a[1] === "nth" ? (a[2] || Z.error(a[0]), a[3] = +(a[3] ? a[4] + (a[5] || 1) : 2 * (a[2] === "even" || a[2] === "odd")), a[4] = +(a[6] + a[7] || a[2] === "odd")) : a[2] && Z.error(a[0]), a
  }, PSEUDO: function (a) {
  var b, c = a[4];
  return L.CHILD.test(a[0]) ? null : (c && (b = D.exec(c)) && b.pop() && (a[0] = a[0].slice(0, b[0].length - c.length - 1), c = b[0].slice(0, -1)), a.splice(2, 3, c || a[3]), a)
  }}, filter: {ID: g ? function (a) {
  return a = a.replace(K, ""), function (b) {
  return b.getAttribute("id") === a
  }
  } : function (a) {
  return a = a.replace(K, ""), function (b) {
  var c = typeof b.getAttributeNode !== j && b.getAttributeNode("id");
  return c && c.value === a
  }
  }, TAG: function (a) {
  return a === "*" ? function () {
  return!0
  } : (a = a.replace(K, "").toLowerCase(), function (b) {
  return b.nodeName && b.nodeName.toLowerCase() === a
  })
  }, CLASS: function (a) {
  var b = M[a];
  return b || (b = M[a] = new RegExp("(^|" + r + ")" + a + "(" + r + "|$)"), N.push(a), N.length > $.cacheLength && delete M[N.shift()]), function (a) {
  return b.test(a.className || typeof a.getAttribute !== j && a.getAttribute("class") || "")
  }
  }, ATTR: function (a, b, c) {
  return b ? function (d) {
  var e = Z.attr(d, a), f = e + "";
  if (e == null)return b === "!=";
  switch (b) {
  case"=":
  return f === c;
  case"!=":
  return f !== c;
  case"^=":
  return c && f.indexOf(c) === 0;
  case"*=":
  return c && f.indexOf(c) > -1;
  case"$=":
  return c && f.substr(f.length - c.length) === c;
  case"~=":
  return(" " + f + " ").indexOf(c) > -1;
  case"|=":
  return f === c || f.substr(0, c.length + 1) === c + "-"
  }
  } : function (b) {
  return Z.attr(b, a) != null
  }
  }, CHILD: function (a, b, c, d) {
  if (a === "nth") {
  var e = m++;
  return function (a) {
  var b, f, g = 0, h = a;
  if (c === 1 && d === 0)return!0;
  b = a.parentNode;
  if (b && (b[q] !== e || !a.sizset)) {
  for (h = b.firstChild; h; h = h.nextSibling)if (h.nodeType === 1) {
  h.sizset = ++g;
  if (h === a)break
  }
  b[q] = e
  }
  return f = a.sizset - d, c === 0 ? f === 0 : f % c === 0 && f / c >= 0
  }
  }
  return function (b) {
  var c = b;
  switch (a) {
  case"only":
  case"first":
  while (c = c.previousSibling)if (c.nodeType === 1)return!1;
  if (a === "first")return!0;
  c = b;
  case"last":
  while (c = c.nextSibling)if (c.nodeType === 1)return!1;
  return!0
  }
  }
  }, PSEUDO: function (a, b, c, d) {
  var e = $.pseudos[a] || $.pseudos[a.toLowerCase()];
  return e || Z.error("unsupported pseudo: " + a), e.sizzleFilter ? e(b, c, d) : e
  }}, pseudos: {not: Q(function (a, b, c) {
  var d = bl(a.replace(A, "$1"), b, c);
  return function (a) {
  return!d(a)
  }
  }), enabled: function (a) {
  return a.disabled === !1
  }, disabled: function (a) {
  return a.disabled === !0
  }, checked: function (a) {
  var b = a.nodeName.toLowerCase();
  return b === "input" && !!a.checked || b === "option" && !!a.selected
  }, selected: function (a) {
  return a.parentNode && a.parentNode.selectedIndex, a.selected === !0
  }, parent: function (a) {
  return!$.pseudos.empty(a)
  }, empty: function (a) {
  var b;
  a = a.firstChild;
  while (a) {
  if (a.nodeName > "@" || (b = a.nodeType) === 3 || b === 4)return!1;
  a = a.nextSibling
  }
  return!0
  }, contains: Q(function (a) {
  return function (b) {
  return(b.textContent || b.innerText || bc(b)).indexOf(a) > -1
  }
  }), has: Q(function (a) {
  return function (b) {
  return Z(a, b).length > 0
  }
  }), header: function (a) {
  return I.test(a.nodeName)
  }, text: function (a) {
  var b, c;
  return a.nodeName.toLowerCase() === "input" && (b = a.type) === "text" && ((c = a.getAttribute("type")) == null || c.toLowerCase() === b)
  }, radio: R("radio"), checkbox: R("checkbox"), file: R("file"), password: R("password"), image: R("image"), submit: S("submit"), reset: S("reset"), button: function (a) {
  var b = a.nodeName.toLowerCase();
  return b === "input" && a.type === "button" || b === "button"
  }, input: function (a) {
  return J.test(a.nodeName)
  }, focus: function (a) {
  var b = a.ownerDocument;
  return a === b.activeElement && (!b.hasFocus || b.hasFocus()) && (!!a.type || !!a.href)
  }, active: function (a) {
  return a === a.ownerDocument.activeElement
  }}, setFilters: {first: function (a, b, c) {
  return c ? a.slice(1) : [a[0]]
  }, last: function (a, b, c) {
  var d = a.pop();
  return c ? a : [d]
  }, even: function (a, b, c) {
  var d = [], e = c ? 1 : 0, f = a.length;
  for (; e < f; e = e + 2)d.push(a[e]);
  return d
  }, odd: function (a, b, c) {
  var d = [], e = c ? 0 : 1, f = a.length;
  for (; e < f; e = e + 2)d.push(a[e]);
  return d
  }, lt: function (a, b, c) {
  return c ? a.slice(+b) : a.slice(0, +b)
  }, gt: function (a, b, c) {
  return c ? a.slice(0, +b + 1) : a.slice(+b + 1)
  }, eq: function (a, b, c) {
  var d = a.splice(+b, 1);
  return c ? a : d
  }}};
  $.setFilters.nth = $.setFilters.eq, $.filters = $.pseudos, X || ($.attrHandle = {href: function (a) {
  return a.getAttribute("href", 2)
  }, type: function (a) {
  return a.getAttribute("type")
  }}), V && ($.order.push("NAME"), $.find.NAME = function (a, b) {
  if (typeof b.getElementsByName !== j)return b.getElementsByName(a)
  }), Y && ($.order.splice(1, 0, "CLASS"), $.find.CLASS = function (a, b, c) {
  if (typeof b.getElementsByClassName !== j && !c)return b.getElementsByClassName(a)
  });
  try {
  n.call(i.childNodes, 0)[0].nodeType
  } catch (_) {
  n = function (a) {
  var b, c = [];
  for (; b = this[a]; a++)c.push(b);
  return c
  }
  }
  var ba = Z.isXML = function (a) {
  var b = a && (a.ownerDocument || a).documentElement;
  return b ? b.nodeName !== "HTML" : !1
  }, bb = Z.contains = i.compareDocumentPosition ? function (a, b) {
  return!!(a.compareDocumentPosition(b) & 16)
  } : i.contains ? function (a, b) {
  var c = a.nodeType === 9 ? a.documentElement : a, d = b.parentNode;
  return a === d || !!(d && d.nodeType === 1 && c.contains && c.contains(d))
  } : function (a, b) {
  while (b = b.parentNode)if (b === a)return!0;
  return!1
  }, bc = Z.getText = function (a) {
  var b, c = "", d = 0, e = a.nodeType;
  if (e) {
  if (e === 1 || e === 9 || e === 11) {
  if (typeof a.textContent == "string")return a.textContent;
  for (a = a.firstChild; a; a = a.nextSibling)c += bc(a)
  } else if (e === 3 || e === 4)return a.nodeValue
  } else for (; b = a[d]; d++)c += bc(b);
  return c
  };
  Z.attr = function (a, b) {
  var c, d = ba(a);
  return d || (b = b.toLowerCase()), $.attrHandle[b] ? $.attrHandle[b](a) : U || d ? a.getAttribute(b) : (c = a.getAttributeNode(b), c ? typeof a[b] == "boolean" ? a[b] ? b : null : c.specified ? c.value : null : null)
  }, Z.error = function (a) {
  throw new Error("Syntax error, unrecognized expression: " + a)
  }, [0, 0].sort(function () {
  return l = 0
  }), i.compareDocumentPosition ? e = function (a, b) {
  return a === b ? (k = !0, 0) : (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4) ? -1 : 1
  } : (e = function (a, b) {
  if (a === b)return k = !0, 0;
  if (a.sourceIndex && b.sourceIndex)return a.sourceIndex - b.sourceIndex;
  var c, d, e = [], g = [], h = a.parentNode, i = b.parentNode, j = h;
  if (h === i)return f(a, b);
  if (!h)return-1;
  if (!i)return 1;
  while (j)e.unshift(j), j = j.parentNode;
  j = i;
  while (j)g.unshift(j), j = j.parentNode;
  c = e.length, d = g.length;
  for (var l = 0; l < c && l < d; l++)if (e[l] !== g[l])return f(e[l], g[l]);
  return l === c ? f(a, g[l], -1) : f(e[l], b, 1)
  }, f = function (a, b, c) {
  if (a === b)return c;
  var d = a.nextSibling;
  while (d) {
  if (d === b)return-1;
  d = d.nextSibling
  }
  return 1
  }), Z.uniqueSort = function (a) {
  var b, c = 1;
  if (e) {
  k = l, a.sort(e);
  if (k)for (; b = a[c]; c++)b === a[c - 1] && a.splice(c--, 1)
  }
  return a
  };
  var bl = Z.compile = function (a, b, c) {
  var d, e, f, g = O[a];
  if (g && g.context === b)return g;
  e = bg(a, b, c);
  for (f = 0; d = e[f]; f++)e[f] = bj(d, b, c);
  return g = O[a] = bk(e), g.context = b, g.runs = g.dirruns = 0, P.push(a), P.length > $.cacheLength && delete O[P.shift()], g
  };
  Z.matches = function (a, b) {
  return Z(a, null, null, b)
  }, Z.matchesSelector = function (a, b) {
  return Z(b, null, null, [a]).length > 0
  };
  var bm = function (a, b, e, f, g) {
  a = a.replace(A, "$1");
  var h, i, j, k, l, m, p, q, r, s = a.match(C), t = a.match(E), u = b.nodeType;
  if (L.POS.test(a))return bf(a, b, e, f, s);
  if (f)h = n.call(f, 0); else if (s && s.length === 1) {
  if (t.length > 1 && u === 9 && !g && (s = L.ID.exec(t[0]))) {
  b = $.find.ID(s[1], b, g)[0];
  if (!b)return e;
  a = a.slice(t.shift().length)
  }
  q = (s = G.exec(t[0])) && !s.index && b.parentNode || b, r = t.pop(), m = r.split(":not")[0];
  for (j = 0, k = $.order.length; j < k; j++) {
  p = $.order[j];
  if (s = L[p].exec(m)) {
  h = $.find[p]((s[1] || "").replace(K, ""), q, g);
  if (h == null)continue;
  m === r && (a = a.slice(0, a.length - r.length) + m.replace(L[p], ""), a || o.apply(e, n.call(h, 0)));
  break
  }
  }
  }
  if (a) {
  i = bl(a, b, g), d = i.dirruns++, h == null && (h = $.find.TAG("*", G.test(a) && b.parentNode || b));
  for (j = 0; l = h[j]; j++)c = i.runs++, i(l, b) && e.push(l)
  }
  return e
  };
  h.querySelectorAll && function () {
  var a, b = bm, c = /'|\\/g, d = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, e = [], f = [":active"], g = i.matchesSelector || i.mozMatchesSelector || i.webkitMatchesSelector || i.oMatchesSelector || i.msMatchesSelector;
  T(function (a) {
  a.innerHTML = "<select><option selected></option></select>", a.querySelectorAll("[selected]").length || e.push("\\[" + r + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"), a.querySelectorAll(":checked").length || e.push(":checked")
  }), T(function (a) {
  a.innerHTML = "<p test=''></p>", a.querySelectorAll("[test^='']").length && e.push("[*^$]=" + r + "*(?:\"\"|'')"), a.innerHTML = "<input type='hidden'>", a.querySelectorAll(":enabled").length || e.push(":enabled", ":disabled")
  }), e = e.length && new RegExp(e.join("|")), bm = function (a, d, f, g, h) {
  if (!g && !h && (!e || !e.test(a)))if (d.nodeType === 9)try {
  return o.apply(f, n.call(d.querySelectorAll(a), 0)), f
  } catch (i) {
  } else if (d.nodeType === 1 && d.nodeName.toLowerCase() !== "object") {
  var j = d.getAttribute("id"), k = j || q, l = G.test(a) && d.parentNode || d;
  j ? k = k.replace(c, "\\$&") : d.setAttribute("id", k);
  try {
  return o.apply(f, n.call(l.querySelectorAll(a.replace(C, "[id='" + k + "'] $&")), 0)), f
  } catch (i) {
  } finally {
  j || d.removeAttribute("id")
  }
  }
  return b(a, d, f, g, h)
  }, g && (T(function (b) {
  a = g.call(b, "div");
  try {
  g.call(b, "[test!='']:sizzle"), f.push($.match.PSEUDO)
  } catch (c) {
  }
  }), f = new RegExp(f.join("|")), Z.matchesSelector = function (b, c) {
  c = c.replace(d, "='$1']");
  if (!ba(b) && !f.test(c) && (!e || !e.test(c)))try {
  var h = g.call(b, c);
  if (h || a || b.document && b.document.nodeType !== 11)return h
  } catch (i) {
  }
  return Z(c, null, null, [b]).length > 0
  })
  }(), Z.attr = p.attr, p.find = Z, p.expr = Z.selectors, p.expr[":"] = p.expr.pseudos, p.unique = Z.uniqueSort, p.text = Z.getText, p.isXMLDoc = Z.isXML, p.contains = Z.contains
  }(a);
  var bc = /Until$/, bd = /^(?:parents|prev(?:Until|All))/, be = /^.[^:#\[\.,]*$/, bf = p.expr.match.needsContext, bg = {children: !0, contents: !0, next: !0, prev: !0};
  p.fn.extend({find: function (a) {
  var b, c, d, e, f, g, h = this;
  if (typeof a != "string")return p(a).filter(function () {
  for (b = 0, c = h.length; b < c; b++)if (p.contains(h[b], this))return!0
  });
  g = this.pushStack("", "find", a);
  for (b = 0, c = this.length; b < c; b++) {
  d = g.length, p.find(a, this[b], g);
  if (b > 0)for (e = d; e < g.length; e++)for (f = 0; f < d; f++)if (g[f] === g[e]) {
  g.splice(e--, 1);
  break
  }
  }
  return g
  }, has: function (a) {
  var b, c = p(a, this), d = c.length;
  return this.filter(function () {
  for (b = 0; b < d; b++)if (p.contains(this, c[b]))return!0
  })
  }, not: function (a) {
  return this.pushStack(bj(this, a, !1), "not", a)
  }, filter: function (a) {
  return this.pushStack(bj(this, a, !0), "filter", a)
  }, is: function (a) {
  return!!a && (typeof a == "string" ? bf.test(a) ? p(a, this.context).index(this[0]) >= 0 : p.filter(a, this).length > 0 : this.filter(a).length > 0)
  }, closest: function (a, b) {
  var c, d = 0, e = this.length, f = [], g = bf.test(a) || typeof a != "string" ? p(a, b || this.context) : 0;
  for (; d < e; d++) {
  c = this[d];
  while (c && c.ownerDocument && c !== b && c.nodeType !== 11) {
  if (g ? g.index(c) > -1 : p.find.matchesSelector(c, a)) {
  f.push(c);
  break
  }
  c = c.parentNode
  }
  }
  return f = f.length > 1 ? p.unique(f) : f, this.pushStack(f, "closest", a)
  }, index: function (a) {
  return a ? typeof a == "string" ? p.inArray(this[0], p(a)) : p.inArray(a.jquery ? a[0] : a, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1
  }, add: function (a, b) {
  var c = typeof a == "string" ? p(a, b) : p.makeArray(a && a.nodeType ? [a] : a), d = p.merge(this.get(), c);
  return this.pushStack(bh(c[0]) || bh(d[0]) ? d : p.unique(d))
  }, addBack: function (a) {
  return this.add(a == null ? this.prevObject : this.prevObject.filter(a))
  }}), p.fn.andSelf = p.fn.addBack, p.each({parent: function (a) {
  var b = a.parentNode;
  return b && b.nodeType !== 11 ? b : null
  }, parents: function (a) {
  return p.dir(a, "parentNode")
  }, parentsUntil: function (a, b, c) {
  return p.dir(a, "parentNode", c)
  }, next: function (a) {
  return bi(a, "nextSibling")
  }, prev: function (a) {
  return bi(a, "previousSibling")
  }, nextAll: function (a) {
  return p.dir(a, "nextSibling")
  }, prevAll: function (a) {
  return p.dir(a, "previousSibling")
  }, nextUntil: function (a, b, c) {
  return p.dir(a, "nextSibling", c)
  }, prevUntil: function (a, b, c) {
  return p.dir(a, "previousSibling", c)
  }, siblings: function (a) {
  return p.sibling((a.parentNode || {}).firstChild, a)
  }, children: function (a) {
  return p.sibling(a.firstChild)
  }, contents: function (a) {
  return p.nodeName(a, "iframe") ? a.contentDocument || a.contentWindow.document : p.merge([], a.childNodes)
  }}, function (a, b) {
  p.fn[a] = function (c, d) {
  var e = p.map(this, b, c);
  return bc.test(a) || (d = c), d && typeof d == "string" && (e = p.filter(d, e)), e = this.length > 1 && !bg[a] ? p.unique(e) : e, this.length > 1 && bd.test(a) && (e = e.reverse()), this.pushStack(e, a, k.call(arguments).join(","))
  }
  }), p.extend({filter: function (a, b, c) {
  return c && (a = ":not(" + a + ")"), b.length === 1 ? p.find.matchesSelector(b[0], a) ? [b[0]] : [] : p.find.matches(a, b)
  }, dir: function (a, c, d) {
  var e = [], f = a[c];
  while (f && f.nodeType !== 9 && (d === b || f.nodeType !== 1 || !p(f).is(d)))f.nodeType === 1 && e.push(f), f = f[c];
  return e
  }, sibling: function (a, b) {
  var c = [];
  for (; a; a = a.nextSibling)a.nodeType === 1 && a !== b && c.push(a);
  return c
  }});
  var bl = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", bm = / jQuery\d+="(?:null|\d+)"/g, bn = /^\s+/, bo = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, bp = /<([\w:]+)/, bq = /<tbody/i, br = /<|&#?\w+;/, bs = /<(?:script|style|link)/i, bt = /<(?:script|object|embed|option|style)/i, bu = new RegExp("<(?:" + bl + ")[\\s/>]", "i"), bv = /^(?:checkbox|radio)$/, bw = /checked\s*(?:[^=]|=\s*.checked.)/i, bx = /\/(java|ecma)script/i, by = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, bz = {option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], area: [1, "<map>", "</map>"], _default: [0, "", ""]}, bA = bk(e), bB = bA.appendChild(e.createElement("div"));
  bz.optgroup = bz.option, bz.tbody = bz.tfoot = bz.colgroup = bz.caption = bz.thead, bz.th = bz.td, p.support.htmlSerialize || (bz._default = [1, "X<div>", "</div>"]), p.fn.extend({text: function (a) {
  return p.access(this, function (a) {
  return a === b ? p.text(this) : this.empty().append((this[0] && this[0].ownerDocument || e).createTextNode(a))
  }, null, a, arguments.length)
  }, wrapAll: function (a) {
  if (p.isFunction(a))return this.each(function (b) {
  p(this).wrapAll(a.call(this, b))
  });
  if (this[0]) {
  var b = p(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) {
  return p.isFunction(a) ? this.each(function (b) {
  p(this).wrapInner(a.call(this, b))
  }) : this.each(function () {
  var b = p(this), c = b.contents();
  c.length ? c.wrapAll(a) : b.append(a)
  })
  }, wrap: function (a) {
  var b = p.isFunction(a);
  return this.each(function (c) {
  p(this).wrapAll(b ? a.call(this, c) : a)
  })
  }, unwrap: function () {
  return this.parent().each(function () {
  p.nodeName(this, "body") || p(this).replaceWith(this.childNodes)
  }).end()
  }, append: function () {
  return this.domManip(arguments, !0, function (a) {
  (this.nodeType === 1 || this.nodeType === 11) && this.appendChild(a)
  })
  }, prepend: function () {
  return this.domManip(arguments, !0, function (a) {
  (this.nodeType === 1 || this.nodeType === 11) && this.insertBefore(a, this.firstChild)
  })
  }, before: function () {
  if (!bh(this[0]))return this.domManip(arguments, !1, function (a) {
  this.parentNode.insertBefore(a, this)
  });
  if (arguments.length) {
  var a = p.clean(arguments);
  return this.pushStack(p.merge(a, this), "before", this.selector)
  }
  }, after: function () {
  if (!bh(this[0]))return this.domManip(arguments, !1, function (a) {
  this.parentNode.insertBefore(a, this.nextSibling)
  });
  if (arguments.length) {
  var a = p.clean(arguments);
  return this.pushStack(p.merge(this, a), "after", this.selector)
  }
  }, remove: function (a, b) {
  var c, d = 0;
  for (; (c = this[d]) != null; d++)if (!a || p.filter(a, [c]).length)!b && c.nodeType === 1 && (p.cleanData(c.getElementsByTagName("*")), p.cleanData([c])), c.parentNode && c.parentNode.removeChild(c);
  return this
  }, empty: function () {
  var a, b = 0;
  for (; (a = this[b]) != null; b++) {
  a.nodeType === 1 && p.cleanData(a.getElementsByTagName("*"));
  while (a.firstChild)a.removeChild(a.firstChild)
  }
  return this
  }, clone: function (a, b) {
  return a = a == null ? !1 : a, b = b == null ? a : b, this.map(function () {
  return p.clone(this, a, b)
  })
  }, html: function (a) {
  return p.access(this, function (a) {
  var c = this[0] || {}, d = 0, e = this.length;
  if (a === b)return c.nodeType === 1 ? c.innerHTML.replace(bm, "") : b;
  if (typeof a == "string" && !bs.test(a) && (p.support.htmlSerialize || !bu.test(a)) && (p.support.leadingWhitespace || !bn.test(a)) && !bz[(bp.exec(a) || ["", ""])[1].toLowerCase()]) {
  a = a.replace(bo, "<$1></$2>");
  try {
  for (; d < e; d++)c = this[d] || {}, c.nodeType === 1 && (p.cleanData(c.getElementsByTagName("*")), c.innerHTML = a);
  c = 0
  } catch (f) {
  }
  }
  c && this.empty().append(a)
  }, null, a, arguments.length)
  }, replaceWith: function (a) {
  return bh(this[0]) ? this.length ? this.pushStack(p(p.isFunction(a) ? a() : a), "replaceWith", a) : this : p.isFunction(a) ? this.each(function (b) {
  var c = p(this), d = c.html();
  c.replaceWith(a.call(this, b, d))
  }) : (typeof a != "string" && (a = p(a).detach()), this.each(function () {
  var b = this.nextSibling, c = this.parentNode;
  p(this).remove(), b ? p(b).before(a) : p(c).append(a)
  }))
  }, detach: function (a) {
  return this.remove(a, !0)
  }, domManip: function (a, c, d) {
  a = [].concat.apply([], a);
  var e, f, g, h, i = 0, j = a[0], k = [], l = this.length;
  if (!p.support.checkClone && l > 1 && typeof j == "string" && bw.test(j))return this.each(function () {
  p(this).domManip(a, c, d)
  });
  if (p.isFunction(j))return this.each(function (e) {
  var f = p(this);
  a[0] = j.call(this, e, c ? f.html() : b), f.domManip(a, c, d)
  });
  if (this[0]) {
  e = p.buildFragment(a, this, k), g = e.fragment, f = g.firstChild, g.childNodes.length === 1 && (g = f);
  if (f) {
  c = c && p.nodeName(f, "tr");
  for (h = e.cacheable || l - 1; i < l; i++)d.call(c && p.nodeName(this[i], "table") ? bC(this[i], "tbody") : this[i], i === h ? g : p.clone(g, !0, !0))
  }
  g = f = null, k.length && p.each(k, function (a, b) {
  b.src ? p.ajax ? p.ajax({url: b.src, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0}) : p.error("no ajax") : p.globalEval((b.text || b.textContent || b.innerHTML || "").replace(by, "")), b.parentNode && b.parentNode.removeChild(b)
  })
  }
  return this
  }}), p.buildFragment = function (a, c, d) {
  var f, g, h, i = a[0];
  return c = c || e, c = (c[0] || c).ownerDocument || c[0] || c, typeof c.createDocumentFragment == "undefined" && (c = e), a.length === 1 && typeof i == "string" && i.length < 512 && c === e && i.charAt(0) === "<" && !bt.test(i) && (p.support.checkClone || !bw.test(i)) && (p.support.html5Clone || !bu.test(i)) && (g = !0, f = p.fragments[i], h = f !== b), f || (f = c.createDocumentFragment(), p.clean(a, c, f, d), g && (p.fragments[i] = h && f)), {fragment: f, cacheable: g}
  }, p.fragments = {}, p.each({appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith"}, function (a, b) {
  p.fn[a] = function (c) {
  var d, e = 0, f = [], g = p(c), h = g.length, i = this.length === 1 && this[0].parentNode;
  if ((i == null || i && i.nodeType === 11 && i.childNodes.length === 1) && h === 1)return g[b](this[0]), this;
  for (; e < h; e++)d = (e > 0 ? this.clone(!0) : this).get(), p(g[e])[b](d), f = f.concat(d);
  return this.pushStack(f, a, g.selector)
  }
  }), p.extend({clone: function (a, b, c) {
  var d, e, f, g;
  p.support.html5Clone || p.isXMLDoc(a) || !bu.test("<" + a.nodeName + ">") ? g = a.cloneNode(!0) : (bB.innerHTML = a.outerHTML, bB.removeChild(g = bB.firstChild));
  if ((!p.support.noCloneEvent || !p.support.noCloneChecked) && (a.nodeType === 1 || a.nodeType === 11) && !p.isXMLDoc(a)) {
  bE(a, g), d = bF(a), e = bF(g);
  for (f = 0; d[f]; ++f)e[f] && bE(d[f], e[f])
  }
  if (b) {
  bD(a, g);
  if (c) {
  d = bF(a), e = bF(g);
  for (f = 0; d[f]; ++f)bD(d[f], e[f])
  }
  }
  return d = e = null, g
  }, clean: function (a, b, c, d) {
  var f, g, h, i, j, k, l, m, n, o, q, r, s = 0, t = [];
  if (!b || typeof b.createDocumentFragment == "undefined")b = e;
  for (g = b === e && bA; (h = a[s]) != null; s++) {
  typeof h == "number" && (h += "");
  if (!h)continue;
  if (typeof h == "string")if (!br.test(h))h = b.createTextNode(h); else {
  g = g || bk(b), l = l || g.appendChild(b.createElement("div")), h = h.replace(bo, "<$1></$2>"), i = (bp.exec(h) || ["", ""])[1].toLowerCase(), j = bz[i] || bz._default, k = j[0], l.innerHTML = j[1] + h + j[2];
  while (k--)l = l.lastChild;
  if (!p.support.tbody) {
  m = bq.test(h), n = i === "table" && !m ? l.firstChild && l.firstChild.childNodes : j[1] === "<table>" && !m ? l.childNodes : [];
  for (f = n.length - 1; f >= 0; --f)p.nodeName(n[f], "tbody") && !n[f].childNodes.length && n[f].parentNode.removeChild(n[f])
  }
  !p.support.leadingWhitespace && bn.test(h) && l.insertBefore(b.createTextNode(bn.exec(h)[0]), l.firstChild), h = l.childNodes, l = g.lastChild
  }
  h.nodeType ? t.push(h) : t = p.merge(t, h)
  }
  l && (g.removeChild(l), h = l = g = null);
  if (!p.support.appendChecked)for (s = 0; (h = t[s]) != null; s++)p.nodeName(h, "input") ? bG(h) : typeof h.getElementsByTagName != "undefined" && p.grep(h.getElementsByTagName("input"), bG);
  if (c) {
  q = function (a) {
  if (!a.type || bx.test(a.type))return d ? d.push(a.parentNode ? a.parentNode.removeChild(a) : a) : c.appendChild(a)
  };
  for (s = 0; (h = t[s]) != null; s++)if (!p.nodeName(h, "script") || !q(h))c.appendChild(h), typeof h.getElementsByTagName != "undefined" && (r = p.grep(p.merge([], h.getElementsByTagName("script")), q), t.splice.apply(t, [s + 1, 0].concat(r)), s += r.length)
  }
  return t
  }, cleanData: function (a, b) {
  var c, d, e, f, g = 0, h = p.expando, i = p.cache, j = p.support.deleteExpando, k = p.event.special;
  for (; (e = a[g]) != null; g++)if (b || p.acceptData(e)) {
  d = e[h], c = d && i[d];
  if (c) {
  if (c.events)for (f in c.events)k[f] ? p.event.remove(e, f) : p.removeEvent(e, f, c.handle);
  i[d] && (delete i[d], j ? delete e[h] : e.removeAttribute ? e.removeAttribute(h) : e[h] = null, p.deletedIds.push(d))
  }
  }
  }}), function () {
  var a, b;
  p.uaMatch = function (a) {
  a = a.toLowerCase();
  var b = /(chrome)[ \/]([\w.]+)/.exec(a) || /(webkit)[ \/]([\w.]+)/.exec(a) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a) || /(msie) ([\w.]+)/.exec(a) || a.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a) || [];
  return{browser: b[1] || "", version: b[2] || "0"}
  }, a = p.uaMatch(g.userAgent), b = {}, a.browser && (b[a.browser] = !0, b.version = a.version), b.webkit && (b.safari = !0), p.browser = b, p.sub = function () {
  function a(b, c) {
  return new a.fn.init(b, c)
  }
 
  p.extend(!0, a, this), a.superclass = this, a.fn = a.prototype = this(), a.fn.constructor = a, a.sub = this.sub, a.fn.init = function c(c, d) {
  return d && d instanceof p && !(d instanceof a) && (d = a(d)), p.fn.init.call(this, c, d, b)
  }, a.fn.init.prototype = a.fn;
  var b = a(e);
  return a
  }
  }();
  var bH, bI, bJ, bK = /alpha\([^)]*\)/i, bL = /opacity=([^)]*)/, bM = /^(top|right|bottom|left)$/, bN = /^margin/, bO = new RegExp("^(" + q + ")(.*)$", "i"), bP = new RegExp("^(" + q + ")(?!px)[a-z%]+$", "i"), bQ = new RegExp("^([-+])=(" + q + ")", "i"), bR = {}, bS = {position: "absolute", visibility: "hidden", display: "block"}, bT = {letterSpacing: 0, fontWeight: 400, lineHeight: 1}, bU = ["Top", "Right", "Bottom", "Left"], bV = ["Webkit", "O", "Moz", "ms"], bW = p.fn.toggle;
  p.fn.extend({css: function (a, c) {
  return p.access(this, function (a, c, d) {
  return d !== b ? p.style(a, c, d) : p.css(a, c)
  }, a, c, arguments.length > 1)
  }, show: function () {
  return bZ(this, !0)
  }, hide: function () {
  return bZ(this)
  }, toggle: function (a, b) {
  var c = typeof a == "boolean";
  return p.isFunction(a) && p.isFunction(b) ? bW.apply(this, arguments) : this.each(function () {
  (c ? a : bY(this)) ? p(this).show() : p(this).hide()
  })
  }}), p.extend({cssHooks: {opacity: {get: function (a, b) {
  if (b) {
  var c = bH(a, "opacity");
  return c === "" ? "1" : c
  }
  }}}, cssNumber: {fillOpacity: !0, fontWeight: !0, lineHeight: !0, opacity: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0}, cssProps: {"float": p.support.cssFloat ? "cssFloat" : "styleFloat"}, style: function (a, c, d, e) {
  if (!a || a.nodeType === 3 || a.nodeType === 8 || !a.style)return;
  var f, g, h, i = p.camelCase(c), j = a.style;
  c = p.cssProps[i] || (p.cssProps[i] = bX(j, i)), h = p.cssHooks[c] || p.cssHooks[i];
  if (d === b)return h && "get"in h && (f = h.get(a, !1, e)) !== b ? f : j[c];
  g = typeof d, g === "string" && (f = bQ.exec(d)) && (d = (f[1] + 1) * f[2] + parseFloat(p.css(a, c)), g = "number");
  if (d == null || g === "number" && isNaN(d))return;
  g === "number" && !p.cssNumber[i] && (d += "px");
  if (!h || !("set"in h) || (d = h.set(a, d, e)) !== b)try {
  j[c] = d
  } catch (k) {
  }
  }, css: function (a, c, d, e) {
  var f, g, h, i = p.camelCase(c);
  return c = p.cssProps[i] || (p.cssProps[i] = bX(a.style, i)), h = p.cssHooks[c] || p.cssHooks[i], h && "get"in h && (f = h.get(a, !0, e)), f === b && (f = bH(a, c)), f === "normal" && c in bT && (f = bT[c]), d || e !== b ? (g = parseFloat(f), d || p.isNumeric(g) ? g || 0 : f) : f
  }, swap: function (a, b, c) {
  var d, e, f = {};
  for (e in b)f[e] = a.style[e], a.style[e] = b[e];
  d = c.call(a);
  for (e in b)a.style[e] = f[e];
  return d
  }}), a.getComputedStyle ? bH = function (a, b) {
  var c, d, e, f, g = getComputedStyle(a, null), h = a.style;
  return g && (c = g[b], c === "" && !p.contains(a.ownerDocument.documentElement, a) && (c = p.style(a, b)), bP.test(c) && bN.test(b) && (d = h.width, e = h.minWidth, f = h.maxWidth, h.minWidth = h.maxWidth = h.width = c, c = g.width, h.width = d, h.minWidth = e, h.maxWidth = f)), c
  } : e.documentElement.currentStyle && (bH = function (a, b) {
  var c, d, e = a.currentStyle && a.currentStyle[b], f = a.style;
  return e == null && f && f[b] && (e = f[b]), bP.test(e) && !bM.test(b) && (c = f.left, d = a.runtimeStyle && a.runtimeStyle.left, d && (a.runtimeStyle.left = a.currentStyle.left), f.left = b === "fontSize" ? "1em" : e, e = f.pixelLeft + "px", f.left = c, d && (a.runtimeStyle.left = d)), e === "" ? "auto" : e
  }), p.each(["height", "width"], function (a, b) {
  p.cssHooks[b] = {get: function (a, c, d) {
  if (c)return a.offsetWidth !== 0 || bH(a, "display") !== "none" ? ca(a, b, d) : p.swap(a, bS, function () {
  return ca(a, b, d)
  })
  }, set: function (a, c, d) {
  return b$(a, c, d ? b_(a, b, d, p.support.boxSizing && p.css(a, "boxSizing") === "border-box") : 0)
  }}
  }), p.support.opacity || (p.cssHooks.opacity = {get: function (a, b) {
  return bL.test((b && a.currentStyle ? a.currentStyle.filter : a.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : b ? "1" : ""
  }, set: function (a, b) {
  var c = a.style, d = a.currentStyle, e = p.isNumeric(b) ? "alpha(opacity=" + b * 100 + ")" : "", f = d && d.filter || c.filter || "";
  c.zoom = 1;
  if (b >= 1 && p.trim(f.replace(bK, "")) === "" && c.removeAttribute) {
  c.removeAttribute("filter");
  if (d && !d.filter)return
  }
  c.filter = bK.test(f) ? f.replace(bK, e) : f + " " + e
  }}), p(function () {
  p.support.reliableMarginRight || (p.cssHooks.marginRight = {get: function (a, b) {
  return p.swap(a, {display: "inline-block"}, function () {
  if (b)return bH(a, "marginRight")
  })
  }}), !p.support.pixelPosition && p.fn.position && p.each(["top", "left"], function (a, b) {
  p.cssHooks[b] = {get: function (a, c) {
  if (c) {
  var d = bH(a, b);
  return bP.test(d) ? p(a).position()[b] + "px" : d
  }
  }}
  })
  }), p.expr && p.expr.filters && (p.expr.filters.hidden = function (a) {
  return a.offsetWidth === 0 && a.offsetHeight === 0 || !p.support.reliableHiddenOffsets && (a.style && a.style.display || bH(a, "display")) === "none"
  }, p.expr.filters.visible = function (a) {
  return!p.expr.filters.hidden(a)
  }), p.each({margin: "", padding: "", border: "Width"}, function (a, b) {
  p.cssHooks[a + b] = {expand: function (c) {
  var d, e = typeof c == "string" ? c.split(" ") : [c], f = {};
  for (d = 0; d < 4; d++)f[a + bU[d] + b] = e[d] || e[d - 2] || e[0];
  return f
  }}, bN.test(a) || (p.cssHooks[a + b].set = b$)
  });
  var cc = /%20/g, cd = /\[\]$/, ce = /\r?\n/g, cf = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, cg = /^(?:select|textarea)/i;
  p.fn.extend({serialize: function () {
  return p.param(this.serializeArray())
  }, serializeArray: function () {
  return this.map(function () {
  return this.elements ? p.makeArray(this.elements) : this
  }).filter(function () {
  return this.name && !this.disabled && (this.checked || cg.test(this.nodeName) || cf.test(this.type))
  }).map(function (a, b) {
  var c = p(this).val();
  return c == null ? null : p.isArray(c) ? p.map(c, function (a, c) {
  return{name: b.name, value: a.replace(ce, "\r\n")}
  }) : {name: b.name, value: c.replace(ce, "\r\n")}
  }).get()
  }}), p.param = function (a, c) {
  var d, e = [], f = function (a, b) {
  b = p.isFunction(b) ? b() : b == null ? "" : b, e[e.length] = encodeURIComponent(a) + "=" + encodeURIComponent(b)
  };
  c === b && (c = p.ajaxSettings && p.ajaxSettings.traditional);
  if (p.isArray(a) || a.jquery && !p.isPlainObject(a))p.each(a, function () {
  f(this.name, this.value)
  }); else for (d in a)ch(d, a[d], c, f);
  return e.join("&").replace(cc, "+")
  };
  var ci, cj, ck = /#.*$/, cl = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, cm = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, cn = /^(?:GET|HEAD)$/, co = /^\/\//, cp = /\?/, cq = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, cr = /([?&])_=[^&]*/, cs = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, ct = p.fn.load, cu = {}, cv = {}, cw = ["*/"] + ["*"];
  try {
  ci = f.href
  } catch (cx) {
  ci = e.createElement("a"), ci.href = "", ci = ci.href
  }
  cj = cs.exec(ci.toLowerCase()) || [], p.fn.load = function (a, c, d) {
  if (typeof a != "string" && ct)return ct.apply(this, arguments);
  if (!this.length)return this;
  var e, f, g, h = this, i = a.indexOf(" ");
  return i >= 0 && (e = a.slice(i, a.length), a = a.slice(0, i)), p.isFunction(c) ? (d = c, c = b) : typeof c == "object" && (f = "POST"), p.ajax({url: a, type: f, dataType: "html", data: c, complete: function (a, b) {
  d && h.each(d, g || [a.responseText, b, a])
  }}).done(function (a) {
  g = arguments, h.html(e ? p("<div>").append(a.replace(cq, "")).find(e) : a)
  }), this
  }, p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function (a, b) {
  p.fn[b] = function (a) {
  return this.on(b, a)
  }
  }), p.each(["get", "post"], function (a, c) {
  p[c] = function (a, d, e, f) {
  return p.isFunction(d) && (f = f || e, e = d, d = b), p.ajax({type: c, url: a, data: d, success: e, dataType: f})
  }
  }), p.extend({getScript: function (a, c) {
  return p.get(a, b, c, "script")
  }, getJSON: function (a, b, c) {
  return p.get(a, b, c, "json")
  }, ajaxSetup: function (a, b) {
  return b ? cA(a, p.ajaxSettings) : (b = a, a = p.ajaxSettings), cA(a, b), a
  }, ajaxSettings: {url: ci, isLocal: cm.test(cj[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", "*": cw}, contents: {xml: /xml/, html: /html/, json: /json/}, responseFields: {xml: "responseXML", text: "responseText"}, converters: {"* text": a.String, "text html": !0, "text json": p.parseJSON, "text xml": p.parseXML}, flatOptions: {context: !0, url: !0}}, ajaxPrefilter: cy(cu), ajaxTransport: cy(cv), ajax: function (a, c) {
  function y(a, c, f, i) {
  var k, s, t, u, w, y = c;
  if (v === 2)return;
  v = 2, h && clearTimeout(h), g = b, e = i || "", x.readyState = a > 0 ? 4 : 0, f && (u = cB(l, x, f));
  if (a >= 200 && a < 300 || a === 304)l.ifModified && (w = x.getResponseHeader("Last-Modified"), w && (p.lastModified[d] = w), w = x.getResponseHeader("Etag"), w && (p.etag[d] = w)), a === 304 ? (y = "notmodified", k = !0) : (k = cC(l, u), y = k.state, s = k.data, t = k.error, k = !t); else {
  t = y;
  if (!y || a)y = "error", a < 0 && (a = 0)
  }
  x.status = a, x.statusText = "" + (c || y), k ? o.resolveWith(m, [s, y, x]) : o.rejectWith(m, [x, y, t]), x.statusCode(r), r = b, j && n.trigger("ajax" + (k ? "Success" : "Error"), [x, l, k ? s : t]), q.fireWith(m, [x, y]), j && (n.trigger("ajaxComplete", [x, l]), --p.active || p.event.trigger("ajaxStop"))
  }
 
  typeof a == "object" && (c = a, a = b), c = c || {};
  var d, e, f, g, h, i, j, k, l = p.ajaxSetup({}, c), m = l.context || l, n = m !== l && (m.nodeType || m instanceof p) ? p(m) : p.event, o = p.Deferred(), q = p.Callbacks("once memory"), r = l.statusCode || {}, t = {}, u = {}, v = 0, w = "canceled", x = {readyState: 0, setRequestHeader: function (a, b) {
  if (!v) {
  var c = a.toLowerCase();
  a = u[c] = u[c] || a, t[a] = b
  }
  return this
  }, getAllResponseHeaders: function () {
  return v === 2 ? e : null
  }, getResponseHeader: function (a) {
  var c;
  if (v === 2) {
  if (!f) {
  f = {};
  while (c = cl.exec(e))f[c[1].toLowerCase()] = c[2]
  }
  c = f[a.toLowerCase()]
  }
  return c === b ? null : c
  }, overrideMimeType: function (a) {
  return v || (l.mimeType = a), this
  }, abort: function (a) {
  return a = a || w, g && g.abort(a), y(0, a), this
  }};
  o.promise(x), x.success = x.done, x.error = x.fail, x.complete = q.add, x.statusCode = function (a) {
  if (a) {
  var b;
  if (v < 2)for (b in a)r[b] = [r[b], a[b]]; else b = a[x.status], x.always(b)
  }
  return this
  }, l.url = ((a || l.url) + "").replace(ck, "").replace(co, cj[1] + "//"), l.dataTypes = p.trim(l.dataType || "*").toLowerCase().split(s), l.crossDomain == null && (i = cs.exec(l.url.toLowerCase()), l.crossDomain = !(!i || i[1] == cj[1] && i[2] == cj[2] && (i[3] || (i[1] === "http:" ? 80 : 443)) == (cj[3] || (cj[1] === "http:" ? 80 : 443)))), l.data && l.processData && typeof l.data != "string" && (l.data = p.param(l.data, l.traditional)), cz(cu, l, c, x);
  if (v === 2)return x;
  j = l.global, l.type = l.type.toUpperCase(), l.hasContent = !cn.test(l.type), j && p.active++ === 0 && p.event.trigger("ajaxStart");
  if (!l.hasContent) {
  l.data && (l.url += (cp.test(l.url) ? "&" : "?") + l.data, delete l.data), d = l.url;
  if (l.cache === !1) {
  var z = p.now(), A = l.url.replace(cr, "$1_=" + z);
  l.url = A + (A === l.url ? (cp.test(l.url) ? "&" : "?") + "_=" + z : "")
  }
  }
  (l.data && l.hasContent && l.contentType !== !1 || c.contentType) && x.setRequestHeader("Content-Type", l.contentType), l.ifModified && (d = d || l.url, p.lastModified[d] && x.setRequestHeader("If-Modified-Since", p.lastModified[d]), p.etag[d] && x.setRequestHeader("If-None-Match", p.etag[d])), x.setRequestHeader("Accept", l.dataTypes[0] && l.accepts[l.dataTypes[0]] ? l.accepts[l.dataTypes[0]] + (l.dataTypes[0] !== "*" ? ", " + cw + "; q=0.01" : "") : l.accepts["*"]);
  for (k in l.headers)x.setRequestHeader(k, l.headers[k]);
  if (!l.beforeSend || l.beforeSend.call(m, x, l) !== !1 && v !== 2) {
  w = "abort";
  for (k in{success: 1, error: 1, complete: 1})x[k](l[k]);
  g = cz(cv, l, c, x);
  if (!g)y(-1, "No Transport"); else {
  x.readyState = 1, j && n.trigger("ajaxSend", [x, l]), l.async && l.timeout > 0 && (h = setTimeout(function () {
  x.abort("timeout")
  }, l.timeout));
  try {
  v = 1, g.send(t, y)
  } catch (B) {
  if (v < 2)y(-1, B); else throw B
  }
  }
  return x
  }
  return x.abort()
  }, active: 0, lastModified: {}, etag: {}});
  var cD = [], cE = /\?/, cF = /(=)\?(?=&|$)|\?\?/, cG = p.now();
  p.ajaxSetup({jsonp: "callback", jsonpCallback: function () {
  var a = cD.pop() || p.expando + "_" + cG++;
  return this[a] = !0, a
  }}), p.ajaxPrefilter("json jsonp", function (c, d, e) {
  var f, g, h, i = c.data, j = c.url, k = c.jsonp !== !1, l = k && cF.test(j), m = k && !l && typeof i == "string" && !(c.contentType || "").indexOf("application/x-www-form-urlencoded") && cF.test(i);
  if (c.dataTypes[0] === "jsonp" || l || m)return f = c.jsonpCallback = p.isFunction(c.jsonpCallback) ? c.jsonpCallback() : c.jsonpCallback, g = a[f], l ? c.url = j.replace(cF, "$1" + f) : m ? c.data = i.replace(cF, "$1" + f) : k && (c.url += (cE.test(j) ? "&" : "?") + c.jsonp + "=" + f), c.converters["script json"] = function () {
  return h || p.error(f + " was not called"), h[0]
  }, c.dataTypes[0] = "json", a[f] = function () {
  h = arguments
  }, e.always(function () {
  a[f] = g, c[f] && (c.jsonpCallback = d.jsonpCallback, cD.push(f)), h && p.isFunction(g) && g(h[0]), h = g = b
  }), "script"
  }), p.ajaxSetup({accepts: {script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents: {script: /javascript|ecmascript/}, converters: {"text script": function (a) {
  return p.globalEval(a), a
  }}}), p.ajaxPrefilter("script", function (a) {
  a.cache === b && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1)
  }), p.ajaxTransport("script", function (a) {
  if (a.crossDomain) {
  var c, d = e.head || e.getElementsByTagName("head")[0] || e.documentElement;
  return{send: function (f, g) {
  c = e.createElement("script"), c.async = "async", a.scriptCharset && (c.charset = a.scriptCharset), c.src = a.url, c.onload = c.onreadystatechange = function (a, e) {
  if (e || !c.readyState || /loaded|complete/.test(c.readyState))c.onload = c.onreadystatechange = null, d && c.parentNode && d.removeChild(c), c = b, e || g(200, "success")
  }, d.insertBefore(c, d.firstChild)
  }, abort: function () {
  c && c.onload(0, 1)
  }}
  }
  });
  var cH, cI = a.ActiveXObject ? function () {
  for (var a in cH)cH[a](0, 1)
  } : !1, cJ = 0;
  p.ajaxSettings.xhr = a.ActiveXObject ? function () {
  return!this.isLocal && cK() || cL()
  } : cK, function (a) {
  p.extend(p.support, {ajax: !!a, cors: !!a && "withCredentials"in a})
  }(p.ajaxSettings.xhr()), p.support.ajax && p.ajaxTransport(function (c) {
  if (!c.crossDomain || p.support.cors) {
  var d;
  return{send: function (e, f) {
  var g, h, i = c.xhr();
  c.username ? i.open(c.type, c.url, c.async, c.username, c.password) : i.open(c.type, c.url, c.async);
  if (c.xhrFields)for (h in c.xhrFields)i[h] = c.xhrFields[h];
  c.mimeType && i.overrideMimeType && i.overrideMimeType(c.mimeType), !c.crossDomain && !e["X-Requested-With"] && (e["X-Requested-With"] = "XMLHttpRequest");
  try {
  for (h in e)i.setRequestHeader(h, e[h])
  } catch (j) {
  }
  i.send(c.hasContent && c.data || null), d = function (a, e) {
  var h, j, k, l, m;
  try {
  if (d && (e || i.readyState === 4)) {
  d = b, g && (i.onreadystatechange = p.noop, cI && delete cH[g]);
  if (e)i.readyState !== 4 && i.abort(); else {
  h = i.status, k = i.getAllResponseHeaders(), l = {}, m = i.responseXML, m && m.documentElement && (l.xml = m);
  try {
  l.text = i.responseText
  } catch (a) {
  }
  try {
  j = i.statusText
  } catch (n) {
  j = ""
  }
  !h && c.isLocal && !c.crossDomain ? h = l.text ? 200 : 404 : h === 1223 && (h = 204)
  }
  }
  } catch (o) {
  e || f(-1, o)
  }
  l && f(h, j, l, k)
  }, c.async ? i.readyState === 4 ? setTimeout(d, 0) : (g = ++cJ, cI && (cH || (cH = {}, p(a).unload(cI)), cH[g] = d), i.onreadystatechange = d) : d()
  }, abort: function () {
  d && d(0, 1)
  }}
  }
  });
  var cM, cN, cO = /^(?:toggle|show|hide)$/, cP = new RegExp("^(?:([-+])=|)(" + q + ")([a-z%]*)$", "i"), cQ = /queueHooks$/, cR = [cX], cS = {"*": [function (a, b) {
  var c, d, e, f = this.createTween(a, b), g = cP.exec(b), h = f.cur(), i = +h || 0, j = 1;
  if (g) {
  c = +g[2], d = g[3] || (p.cssNumber[a] ? "" : "px");
  if (d !== "px" && i) {
  i = p.css(f.elem, a, !0) || c || 1;
  do e = j = j || ".5", i = i / j, p.style(f.elem, a, i + d), j = f.cur() / h; while (j !== 1 && j !== e)
  }
  f.unit = d, f.start = i, f.end = g[1] ? i + (g[1] + 1) * c : c
  }
  return f
  }]};
  p.Animation = p.extend(cV, {tweener: function (a, b) {
  p.isFunction(a) ? (b = a, a = ["*"]) : a = a.split(" ");
  var c, d = 0, e = a.length;
  for (; d < e; d++)c = a[d], cS[c] = cS[c] || [], cS[c].unshift(b)
  }, prefilter: function (a, b) {
  b ? cR.unshift(a) : cR.push(a)
  }}), p.Tween = cY, cY.prototype = {constructor: cY, init: function (a, b, c, d, e, f) {
  this.elem = a, this.prop = c, this.easing = e || "swing", this.options = b, this.start = this.now = this.cur(), this.end = d, this.unit = f || (p.cssNumber[c] ? "" : "px")
  }, cur: function () {
  var a = cY.propHooks[this.prop];
  return a && a.get ? a.get(this) : cY.propHooks._default.get(this)
  }, run: function (a) {
  var b, c = cY.propHooks[this.prop];
  return this.pos = b = p.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration), this.now = (this.end - this.start) * b + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), c && c.set ? c.set(this) : cY.propHooks._default.set(this), this
  }}, cY.prototype.init.prototype = cY.prototype, cY.propHooks = {_default: {get: function (a) {
  var b;
  return a.elem[a.prop] == null || !!a.elem.style && a.elem.style[a.prop] != null ? (b = p.css(a.elem, a.prop, !1, ""), !b || b === "auto" ? 0 : b) : a.elem[a.prop]
  }, set: function (a) {
  p.fx.step[a.prop] ? p.fx.step[a.prop](a) : a.elem.style && (a.elem.style[p.cssProps[a.prop]] != null || p.cssHooks[a.prop]) ? p.style(a.elem, a.prop, a.now + a.unit) : a.elem[a.prop] = a.now
  }}}, cY.propHooks.scrollTop = cY.propHooks.scrollLeft = {set: function (a) {
  a.elem.nodeType && a.elem.parentNode && (a.elem[a.prop] = a.now)
  }}, p.each(["toggle", "show", "hide"], function (a, b) {
  var c = p.fn[b];
  p.fn[b] = function (d, e, f) {
  return d == null || typeof d == "boolean" || !a && p.isFunction(d) && p.isFunction(e) ? c.apply(this, arguments) : this.animate(cZ(b, !0), d, e, f)
  }
  }), p.fn.extend({fadeTo: function (a, b, c, d) {
  return this.filter(bY).css("opacity", 0).show().end().animate({opacity: b}, a, c, d)
  }, animate: function (a, b, c, d) {
  var e = p.isEmptyObject(a), f = p.speed(b, c, d), g = function () {
  var b = cV(this, p.extend({}, a), f);
  e && b.stop(!0)
  };
  return e || f.queue === !1 ? this.each(g) : this.queue(f.queue, g)
  }, stop: function (a, c, d) {
  var e = function (a) {
  var b = a.stop;
  delete a.stop, b(d)
  };
  return typeof a != "string" && (d = c, c = a, a = b), c && a !== !1 && this.queue(a || "fx", []), this.each(function () {
  var b = !0, c = a != null && a + "queueHooks", f = p.timers, g = p._data(this);
  if (c)g[c] && g[c].stop && e(g[c]); else for (c in g)g[c] && g[c].stop && cQ.test(c) && e(g[c]);
  for (c = f.length; c--;)f[c].elem === this && (a == null || f[c].queue === a) && (f[c].anim.stop(d), b = !1, f.splice(c, 1));
  (b || !d) && p.dequeue(this, a)
  })
  }}), p.each({slideDown: cZ("show"), slideUp: cZ("hide"), slideToggle: cZ("toggle"), fadeIn: {opacity: "show"}, fadeOut: {opacity: "hide"}, fadeToggle: {opacity: "toggle"}}, function (a, b) {
  p.fn[a] = function (a, c, d) {
  return this.animate(b, a, c, d)
  }
  }), p.speed = function (a, b, c) {
  var d = a && typeof a == "object" ? p.extend({}, a) : {complete: c || !c && b || p.isFunction(a) && a, duration: a, easing: c && b || b && !p.isFunction(b) && b};
  d.duration = p.fx.off ? 0 : typeof d.duration == "number" ? d.duration : d.duration in p.fx.speeds ? p.fx.speeds[d.duration] : p.fx.speeds._default;
  if (d.queue == null || d.queue === !0)d.queue = "fx";
  return d.old = d.complete, d.complete = function () {
  p.isFunction(d.old) && d.old.call(this), d.queue && p.dequeue(this, d.queue)
  }, d
  }, p.easing = {linear: function (a) {
  return a
  }, swing: function (a) {
  return.5 - Math.cos(a * Math.PI) / 2
  }}, p.timers = [], p.fx = cY.prototype.init, p.fx.tick = function () {
  var a, b = p.timers, c = 0;
  for (; c < b.length; c++)a = b[c], !a() && b[c] === a && b.splice(c--, 1);
  b.length || p.fx.stop()
  }, p.fx.timer = function (a) {
  a() && p.timers.push(a) && !cN && (cN = setInterval(p.fx.tick, p.fx.interval))
  }, p.fx.interval = 13, p.fx.stop = function () {
  clearInterval(cN), cN = null
  }, p.fx.speeds = {slow: 600, fast: 200, _default: 400}, p.fx.step = {}, p.expr && p.expr.filters && (p.expr.filters.animated = function (a) {
  return p.grep(p.timers,function (b) {
  return a === b.elem
  }).length
  });
  var c$ = /^(?:body|html)$/i;
  p.fn.offset = function (a) {
  if (arguments.length)return a === b ? this : this.each(function (b) {
  p.offset.setOffset(this, a, b)
  });
  var c, d, e, f, g, h, i, j, k, l, m = this[0], n = m && m.ownerDocument;
  if (!n)return;
  return(e = n.body) === m ? p.offset.bodyOffset(m) : (d = n.documentElement, p.contains(d, m) ? (c = m.getBoundingClientRect(), f = c_(n), g = d.clientTop || e.clientTop || 0, h = d.clientLeft || e.clientLeft || 0, i = f.pageYOffset || d.scrollTop, j = f.pageXOffset || d.scrollLeft, k = c.top + i - g, l = c.left + j - h, {top: k, left: l}) : {top: 0, left: 0})
  }, p.offset = {bodyOffset: function (a) {
  var b = a.offsetTop, c = a.offsetLeft;
  return p.support.doesNotIncludeMarginInBodyOffset && (b += parseFloat(p.css(a, "marginTop")) || 0, c += parseFloat(p.css(a, "marginLeft")) || 0), {top: b, left: c}
  }, setOffset: function (a, b, c) {
  var d = p.css(a, "position");
  d === "static" && (a.style.position = "relative");
  var e = p(a), f = e.offset(), g = p.css(a, "top"), h = p.css(a, "left"), i = (d === "absolute" || d === "fixed") && p.inArray("auto", [g, h]) > -1, j = {}, k = {}, l, m;
  i ? (k = e.position(), l = k.top, m = k.left) : (l = parseFloat(g) || 0, m = parseFloat(h) || 0), p.isFunction(b) && (b = b.call(a, c, f)), b.top != null && (j.top = b.top - f.top + l), b.left != null && (j.left = b.left - f.left + m), "using"in b ? b.using.call(a, j) : e.css(j)
  }}, p.fn.extend({position: function () {
  if (!this[0])return;
  var a = this[0], b = this.offsetParent(), c = this.offset(), d = c$.test(b[0].nodeName) ? {top: 0, left: 0} : b.offset();
  return c.top -= parseFloat(p.css(a, "marginTop")) || 0, c.left -= parseFloat(p.css(a, "marginLeft")) || 0, d.top += parseFloat(p.css(b[0], "borderTopWidth")) || 0, d.left += parseFloat(p.css(b[0], "borderLeftWidth")) || 0, {top: c.top - d.top, left: c.left - d.left}
  }, offsetParent: function () {
  return this.map(function () {
  var a = this.offsetParent || e.body;
  while (a && !c$.test(a.nodeName) && p.css(a, "position") === "static")a = a.offsetParent;
  return a || e.body
  })
  }}), p.each({scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function (a, c) {
  var d = /Y/.test(c);
  p.fn[a] = function (e) {
  return p.access(this, function (a, e, f) {
  var g = c_(a);
  if (f === b)return g ? c in g ? g[c] : g.document.documentElement[e] : a[e];
  g ? g.scrollTo(d ? p(g).scrollLeft() : f, d ? f : p(g).scrollTop()) : a[e] = f
  }, a, e, arguments.length, null)
  }
  }), p.each({Height: "height", Width: "width"}, function (a, c) {
  p.each({padding: "inner" + a, content: c, "": "outer" + a}, function (d, e) {
  p.fn[e] = function (e, f) {
  var g = arguments.length && (d || typeof e != "boolean"), h = d || (e === !0 || f === !0 ? "margin" : "border");
  return p.access(this, function (c, d, e) {
  var f;
  return p.isWindow(c) ? c.document.documentElement["client" + a] : c.nodeType === 9 ? (f = c.documentElement, Math.max(c.body["scroll" + a], f["scroll" + a], c.body["offset" + a], f["offset" + a], f["client" + a])) : e === b ? p.css(c, d, e, h) : p.style(c, d, e, h)
  }, c, g ? e : b, g)
  }
  })
  }), a.jQuery = a.$ = p, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function () {
  return p
  })
  })(window);
 
  /* Modernizr 2.6.1 (Custom Build) | MIT & BSD
  * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
  */
  ;
  window.Modernizr = function (a, b, c) {
  function D(a) {
  j.cssText = a
  }
 
  function E(a, b) {
  return D(n.join(a + ";") + (b || ""))
  }
 
  function F(a, b) {
  return typeof a === b
  }
 
  function G(a, b) {
  return!!~("" + a).indexOf(b)
  }
 
  function H(a, b) {
  for (var d in a) {
  var e = a[d];
  if (!G(e, "-") && j[e] !== c)return b == "pfx" ? e : !0
  }
  return!1
  }
 
  function I(a, b, d) {
  for (var e in a) {
  var f = b[a[e]];
  if (f !== c)return d === !1 ? a[e] : F(f, "function") ? f.bind(d || b) : f
  }
  return!1
  }
 
  function J(a, b, c) {
  var d = a.charAt(0).toUpperCase() + a.slice(1), e = (a + " " + p.join(d + " ") + d).split(" ");
  return F(b, "string") || F(b, "undefined") ? H(e, b) : (e = (a + " " + q.join(d + " ") + d).split(" "), I(e, b, c))
  }
 
  function K() {
  e.input = function (c) {
  for (var d = 0, e = c.length; d < e; d++)u[c[d]] = c[d]in k;
  return u.list && (u.list = !!b.createElement("datalist") && !!a.HTMLDataListElement), u
  }("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")), e.inputtypes = function (a) {
  for (var d = 0, e, f, h, i = a.length; d < i; d++)k.setAttribute("type", f = a[d]), e = k.type !== "text", e && (k.value = l, k.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(f) && k.style.WebkitAppearance !== c ? (g.appendChild(k), h = b.defaultView, e = h.getComputedStyle && h.getComputedStyle(k, null).WebkitAppearance !== "textfield" && k.offsetHeight !== 0, g.removeChild(k)) : /^(search|tel)$/.test(f) || (/^(url|email)$/.test(f) ? e = k.checkValidity && k.checkValidity() === !1 : e = k.value != l)), t[a[d]] = !!e;
  return t
  }("search tel url email datetime date month week time datetime-local number range color".split(" "))
  }
 
  var d = "2.6.1", e = {}, f = !0, g = b.documentElement, h = "modernizr", i = b.createElement(h), j = i.style, k = b.createElement("input"), l = ":)", m = {}.toString, n = " -webkit- -moz- -o- -ms- ".split(" "), o = "Webkit Moz O ms", p = o.split(" "), q = o.toLowerCase().split(" "), r = {svg: "http://www.w3.org/2000/svg"}, s = {}, t = {}, u = {}, v = [], w = v.slice, x, y = function (a, c, d, e) {
  var f, i, j, k = b.createElement("div"), l = b.body, m = l ? l : b.createElement("body");
  if (parseInt(d, 10))while (d--)j = b.createElement("div"), j.id = e ? e[d] : h + (d + 1), k.appendChild(j);
  return f = ["&#173;", '<style id="s', h, '">', a, "</style>"].join(""), k.id = h, (l ? k : m).innerHTML += f, m.appendChild(k), l || (m.style.background = "", g.appendChild(m)), i = c(k, a), l ? k.parentNode.removeChild(k) : m.parentNode.removeChild(m), !!i
  }, z = function (b) {
  var c = a.matchMedia || a.msMatchMedia;
  if (c)return c(b).matches;
  var d;
  return y("@media " + b + " { #" + h + " { position: absolute; } }", function (b) {
  d = (a.getComputedStyle ? getComputedStyle(b, null) : b.currentStyle)["position"] == "absolute"
  }), d
  }, A = function () {
  function d(d, e) {
  e = e || b.createElement(a[d] || "div"), d = "on" + d;
  var f = d in e;
  return f || (e.setAttribute || (e = b.createElement("div")), e.setAttribute && e.removeAttribute && (e.setAttribute(d, ""), f = F(e[d], "function"), F(e[d], "undefined") || (e[d] = c), e.removeAttribute(d))), e = null, f
  }
 
  var a = {select: "input", change: "input", submit: "form", reset: "form", error: "img", load: "img", abort: "img"};
  return d
  }(), B = {}.hasOwnProperty, C;
  !F(B, "undefined") && !F(B.call, "undefined") ? C = function (a, b) {
  return B.call(a, b)
  } : C = function (a, b) {
  return b in a && F(a.constructor.prototype[b], "undefined")
  }, Function.prototype.bind || (Function.prototype.bind = function (b) {
  var c = this;
  if (typeof c != "function")throw new TypeError;
  var d = w.call(arguments, 1), e = function () {
  if (this instanceof e) {
  var a = function () {
  };
  a.prototype = c.prototype;
  var f = new a, g = c.apply(f, d.concat(w.call(arguments)));
  return Object(g) === g ? g : f
  }
  return c.apply(b, d.concat(w.call(arguments)))
  };
  return e
  }), s.flexbox = function () {
  return J("flexWrap")
  }, s.canvas = function () {
  var a = b.createElement("canvas");
  return!!a.getContext && !!a.getContext("2d")
  }, s.canvastext = function () {
  return!!e.canvas && !!F(b.createElement("canvas").getContext("2d").fillText, "function")
  }, s.webgl = function () {
  return!!a.WebGLRenderingContext
  }, s.touch = function () {
  var c;
  return"ontouchstart"in a || a.DocumentTouch && b instanceof DocumentTouch ? c = !0 : y(["@media (", n.join("touch-enabled),("), h, ")", "{#modernizr{top:9px;position:absolute}}"].join(""), function (a) {
  c = a.offsetTop === 9
  }), c
  }, s.geolocation = function () {
  return"geolocation"in navigator
  }, s.postmessage = function () {
  return!!a.postMessage
  }, s.websqldatabase = function () {
  return!!a.openDatabase
  }, s.indexedDB = function () {
  return!!J("indexedDB", a)
  }, s.hashchange = function () {
  return A("hashchange", a) && (b.documentMode === c || b.documentMode > 7)
  }, s.history = function () {
  return!!a.history && !!history.pushState
  }, s.draganddrop = function () {
  var a = b.createElement("div");
  return"draggable"in a || "ondragstart"in a && "ondrop"in a
  }, s.websockets = function () {
  return"WebSocket"in a || "MozWebSocket"in a
  }, s.rgba = function () {
  return D("background-color:rgba(150,255,150,.5)"), G(j.backgroundColor, "rgba")
  }, s.hsla = function () {
  return D("background-color:hsla(120,40%,100%,.5)"), G(j.backgroundColor, "rgba") || G(j.backgroundColor, "hsla")
  }, s.multiplebgs = function () {
  return D("background:url(https://),url(https://),red url(https://)"), /(url\s*\(.*?){3}/.test(j.background)
  }, s.backgroundsize = function () {
  return J("backgroundSize")
  }, s.borderimage = function () {
  return J("borderImage")
  }, s.borderradius = function () {
  return J("borderRadius")
  }, s.boxshadow = function () {
  return J("boxShadow")
  }, s.textshadow = function () {
  return b.createElement("div").style.textShadow === ""
  }, s.opacity = function () {
  return E("opacity:.55"), /^0.55$/.test(j.opacity)
  }, s.cssanimations = function () {
  return J("animationName")
  }, s.csscolumns = function () {
  return J("columnCount")
  }, s.cssgradients = function () {
  var a = "background-image:", b = "gradient(linear,left top,right bottom,from(#9f9),to(white));", c = "linear-gradient(left top,#9f9, white);";
  return D((a + "-webkit- ".split(" ").join(b + a) + n.join(c + a)).slice(0, -a.length)), G(j.backgroundImage, "gradient")
  }, s.cssreflections = function () {
  return J("boxReflect")
  }, s.csstransforms = function () {
  return!!J("transform")
  }, s.csstransforms3d = function () {
  var a = !!J("perspective");
  return a && "webkitPerspective"in g.style && y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}", function (b, c) {
  a = b.offsetLeft === 9 && b.offsetHeight === 3
  }), a
  }, s.csstransitions = function () {
  return J("transition")
  }, s.fontface = function () {
  var a;
  return y('@font-face {font-family:"font";src:url("https://")}', function (c, d) {
  var e = b.getElementById("smodernizr"), f = e.sheet || e.styleSheet, g = f ? f.cssRules && f.cssRules[0] ? f.cssRules[0].cssText : f.cssText || "" : "";
  a = /src/i.test(g) && g.indexOf(d.split(" ")[0]) === 0
  }), a
  }, s.generatedcontent = function () {
  var a;
  return y(['#modernizr:after{content:"', l, '";visibility:hidden}'].join(""), function (b) {
  a = b.offsetHeight >= 1
  }), a
  }, s.video = function () {
  var a = b.createElement("video"), c = !1;
  try {
  if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ""), c.h264 = a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ""), c.webm = a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, "")
  } catch (d) {
  }
  return c
  }, s.audio = function () {
  var a = b.createElement("audio"), c = !1;
  try {
  if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ""), c.mp3 = a.canPlayType("audio/mpeg;").replace(/^no$/, ""), c.wav = a.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ""), c.m4a = (a.canPlayType("audio/x-m4a;") || a.canPlayType("audio/aac;")).replace(/^no$/, "")
  } catch (d) {
  }
  return c
  }, s.localstorage = function () {
  try {
  return localStorage.setItem(h, h), localStorage.removeItem(h), !0
  } catch (a) {
  return!1
  }
  }, s.sessionstorage = function () {
  try {
  return sessionStorage.setItem(h, h), sessionStorage.removeItem(h), !0
  } catch (a) {
  return!1
  }
  }, s.webworkers = function () {
  return!!a.Worker
  }, s.applicationcache = function () {
  return!!a.applicationCache
  }, s.svg = function () {
  return!!b.createElementNS && !!b.createElementNS(r.svg, "svg").createSVGRect
  }, s.inlinesvg = function () {
  var a = b.createElement("div");
  return a.innerHTML = "<svg/>", (a.firstChild && a.firstChild.namespaceURI) == r.svg
  }, s.smil = function () {
  return!!b.createElementNS && /SVGAnimate/.test(m.call(b.createElementNS(r.svg, "animate")))
  }, s.svgclippaths = function () {
  return!!b.createElementNS && /SVGClipPath/.test(m.call(b.createElementNS(r.svg, "clipPath")))
  };
  for (var L in s)C(s, L) && (x = L.toLowerCase(), e[x] = s[L](), v.push((e[x] ? "" : "no-") + x));
  return e.input || K(), e.addTest = function (a, b) {
  if (typeof a == "object")for (var d in a)C(a, d) && e.addTest(d, a[d]); else {
  a = a.toLowerCase();
  if (e[a] !== c)return e;
  b = typeof b == "function" ? b() : b, f && (g.className += " " + (b ? "" : "no-") + a), e[a] = b
  }
  return e
  }, D(""), i = k = null, function (a, b) {
  function k(a, b) {
  var c = a.createElement("p"), d = a.getElementsByTagName("head")[0] || a.documentElement;
  return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild)
  }
 
  function l() {
  var a = r.elements;
  return typeof a == "string" ? a.split(" ") : a
  }
 
  function m(a) {
  var b = i[a[g]];
  return b || (b = {}, h++, a[g] = h, i[h] = b), b
  }
 
  function n(a, c, f) {
  c || (c = b);
  if (j)return c.createElement(a);
  f || (f = m(c));
  var g;
  return f.cache[a] ? g = f.cache[a].cloneNode() : e.test(a) ? g = (f.cache[a] = f.createElem(a)).cloneNode() : g = f.createElem(a), g.canHaveChildren && !d.test(a) ? f.frag.appendChild(g) : g
  }
 
  function o(a, c) {
  a || (a = b);
  if (j)return a.createDocumentFragment();
  c = c || m(a);
  var d = c.frag.cloneNode(), e = 0, f = l(), g = f.length;
  for (; e < g; e++)d.createElement(f[e]);
  return d
  }
 
  function p(a, b) {
  b.cache || (b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()), a.createElement = function (c) {
  return r.shivMethods ? n(c, a, b) : b.createElem(c)
  }, a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + l().join().replace(/\w+/g, function (a) {
  return b.createElem(a), b.frag.createElement(a), 'c("' + a + '")'
  }) + ");return n}")(r, b.frag)
  }
 
  function q(a) {
  a || (a = b);
  var c = m(a);
  return r.shivCSS && !f && !c.hasCSS && (c.hasCSS = !!k(a, "article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")), j || p(a, c), a
  }
 
  var c = a.html5 || {}, d = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, e = /^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i, f, g = "_html5shiv", h = 0, i = {}, j;
  (function () {
  try {
  var a = b.createElement("a");
  a.innerHTML = "<xyz></xyz>", f = "hidden"in a, j = a.childNodes.length == 1 || function () {
  b.createElement("a");
  var a = b.createDocumentFragment();
  return typeof a.cloneNode == "undefined" || typeof a.createDocumentFragment == "undefined" || typeof a.createElement == "undefined"
  }()
  } catch (c) {
  f = !0, j = !0
  }
  })();
  var r = {elements: c.elements || "abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video", shivCSS: c.shivCSS !== !1, supportsUnknownElements: j, shivMethods: c.shivMethods !== !1, type: "default", shivDocument: q, createElement: n, createDocumentFragment: o};
  a.html5 = r, q(b)
  }(this, b), e._version = d, e._prefixes = n, e._domPrefixes = q, e._cssomPrefixes = p, e.mq = z, e.hasEvent = A, e.testProp = function (a) {
  return H([a])
  }, e.testAllProps = J, e.testStyles = y, e.prefixed = function (a, b, c) {
  return b ? J(a, b, c) : J(a, "pfx")
  }, g.className = g.className.replace(/(^|\s)no-js(\s|$)/, "$1$2") + (f ? " js " + v.join(" ") : ""), e
  }(this, this.document), function (a, b, c) {
  function d(a) {
  return o.call(a) == "[object Function]"
  }
 
  function e(a) {
  return typeof a == "string"
  }
 
  function f() {
  }
 
  function g(a) {
  return!a || a == "loaded" || a == "complete" || a == "uninitialized"
  }
 
  function h() {
  var a = p.shift();
  q = 1, a ? a.t ? m(function () {
  (a.t == "c" ? B.injectCss : B.injectJs)(a.s, 0, a.a, a.x, a.e, 1)
  }, 0) : (a(), h()) : q = 0
  }
 
  function i(a, c, d, e, f, i, j) {
  function k(b) {
  if (!o && g(l.readyState) && (u.r = o = 1, !q && h(), l.onload = l.onreadystatechange = null, b)) {
  a != "img" && m(function () {
  t.removeChild(l)
  }, 50);
  for (var d in y[c])y[c].hasOwnProperty(d) && y[c][d].onload()
  }
  }
 
  var j = j || B.errorTimeout, l = {}, o = 0, r = 0, u = {t: d, s: c, e: f, a: i, x: j};
  y[c] === 1 && (r = 1, y[c] = [], l = b.createElement(a)), a == "object" ? l.data = c : (l.src = c, l.type = a), l.width = l.height = "0", l.onerror = l.onload = l.onreadystatechange = function () {
  k.call(this, r)
  }, p.splice(e, 0, u), a != "img" && (r || y[c] === 2 ? (t.insertBefore(l, s ? null : n), m(k, j)) : y[c].push(l))
  }
 
  function j(a, b, c, d, f) {
  return q = 0, b = b || "j", e(a) ? i(b == "c" ? v : u, a, b, this.i++, c, d, f) : (p.splice(this.i++, 0, a), p.length == 1 && h()), this
  }
 
  function k() {
  var a = B;
  return a.loader = {load: j, i: 0}, a
  }
 
  var l = b.documentElement, m = a.setTimeout, n = b.getElementsByTagName("script")[0], o = {}.toString, p = [], q = 0, r = "MozAppearance"in l.style, s = r && !!b.createRange().compareNode, t = s ? l : n.parentNode, l = a.opera && o.call(a.opera) == "[object Opera]", l = !!b.attachEvent && !l, u = r ? "object" : l ? "script" : "img", v = l ? "script" : u, w = Array.isArray || function (a) {
  return o.call(a) == "[object Array]"
  }, x = [], y = {}, z = {timeout: function (a, b) {
  return b.length && (a.timeout = b[0]), a
  }}, A, B;
  B = function (a) {
  function b(a) {
  var a = a.split("!"), b = x.length, c = a.pop(), d = a.length, c = {url: c, origUrl: c, prefixes: a}, e, f, g;
  for (f = 0; f < d; f++)g = a[f].split("="), (e = z[g.shift()]) && (c = e(c, g));
  for (f = 0; f < b; f++)c = x[f](c);
  return c
  }
 
  function g(a, e, f, g, i) {
  var j = b(a), l = j.autoCallback;
  j.url.split(".").pop().split("?").shift(), j.bypass || (e && (e = d(e) ? e : e[a] || e[g] || e[a.split("/").pop().split("?")[0]] || h), j.instead ? j.instead(a, e, f, g, i) : (y[j.url] ? j.noexec = !0 : y[j.url] = 1, f.load(j.url, j.forceCSS || !j.forceJS && "css" == j.url.split(".").pop().split("?").shift() ? "c" : c, j.noexec, j.attrs, j.timeout), (d(e) || d(l)) && f.load(function () {
  k(), e && e(j.origUrl, i, g), l && l(j.origUrl, i, g), y[j.url] = 2
  })))
  }
 
  function i(a, b) {
  function c(a, c) {
  if (a) {
  if (e(a))c || (j = function () {
  var a = [].slice.call(arguments);
  k.apply(this, a), l()
  }), g(a, j, b, 0, h); else if (Object(a) === a)for (n in m = function () {
  var b = 0, c;
  for (c in a)a.hasOwnProperty(c) && b++;
  return b
  }(), a)a.hasOwnProperty(n) && (!c && !--m && (d(j) ? j = function () {
  var a = [].slice.call(arguments);
  k.apply(this, a), l()
  } : j[n] = function (a) {
  return function () {
  var b = [].slice.call(arguments);
  a && a.apply(this, b), l()
  }
  }(k[n])), g(a[n], j, b, n, h))
  } else!c && l()
  }
 
  var h = !!a.test, i = a.load || a.both, j = a.callback || f, k = j, l = a.complete || f, m, n;
  c(h ? a.yep : a.nope, !!i), i && c(i)
  }
 
  var j, l, m = this.yepnope.loader;
  if (e(a))g(a, 0, m, 0); else if (w(a))for (j = 0; j < a.length; j++)l = a[j], e(l) ? g(l, 0, m, 0) : w(l) ? B(l) : Object(l) === l && i(l, m); else Object(a) === a && i(a, m)
  }, B.addPrefix = function (a, b) {
  z[a] = b
  }, B.addFilter = function (a) {
  x.push(a)
  }, B.errorTimeout = 1e4, b.readyState == null && b.addEventListener && (b.readyState = "loading", b.addEventListener("DOMContentLoaded", A = function () {
  b.removeEventListener("DOMContentLoaded", A, 0), b.readyState = "complete"
  }, 0)), a.yepnope = k(), a.yepnope.executeStack = h, a.yepnope.injectJs = function (a, c, d, e, i, j) {
  var k = b.createElement("script"), l, o, e = e || B.errorTimeout;
  k.src = a;
  for (o in d)k.setAttribute(o, d[o]);
  c = j ? h : c || f, k.onreadystatechange = k.onload = function () {
  !l && g(k.readyState) && (l = 1, c(), k.onload = k.onreadystatechange = null)
  }, m(function () {
  l || (l = 1, c(1))
  }, e), i ? k.onload() : n.parentNode.insertBefore(k, n)
  }, a.yepnope.injectCss = function (a, c, d, e, g, i) {
  var e = b.createElement("link"), j, c = i ? h : c || f;
  e.href = a, e.rel = "stylesheet", e.type = "text/css";
  for (j in d)e.setAttribute(j, d[j]);
  g || (n.parentNode.insertBefore(e, n), m(c, 0))
  }
  }(this, document), Modernizr.load = function () {
  yepnope.apply(window, [].slice.call(arguments, 0))
  };
 
  include.path=${php.global.include.path}
  php.version=PHP_5
  source.encoding=UTF-8
  src.dir=.
  tags.asp=false
  tags.short=true
  web.root=.
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://www.netbeans.org/ns/project/1">
  <type>org.netbeans.modules.php.project</type>
  <configuration>
  <data xmlns="http://www.netbeans.org/ns/php-project/1">
  <name>scannr</name>
  </data>
  </configuration>
  </project>
file:b/robots.txt (new)
  # robotstxt.org/
 
  User-agent: *
 
file:b/run.bat (new)
  python scannr.py > output.txt
  pause
file:a/scannr.py -> file:b/scannr.py
import logging import logging
   
logging.basicConfig(level=logging.DEBUG, logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s\t%(levelname)s\t%(message)s') format='%(asctime)s\t%(levelname)s\t%(message)s')
   
import snd import snd
import time import time
from datetime import date from datetime import date
import threading import threading
from pydispatch import dispatcher from pydispatch import dispatcher
import wave import wave
import serial import serial
#python -m serial.tools.miniterm -p COM20 -e -b 115200 --cr #python -m serial.tools.miniterm -p COM20 -e -b 115200 --cr
import psycopg2 import psycopg2
import sys,os import csv
  import sys
  import os
   
   
sys.path.insert(0, os.path.join(os.path.dirname(__file__) or '.', 'pynma')) sys.path.insert(0, os.path.join(os.path.dirname(__file__) or '.', 'pynma'))
import pynma import pynma
   
filename = "demo.wav" filename = "demo.wav"
  last_call = (None, None, None)
MIN_LENGTH = 90000 MIN_LENGTH = 90000
nma = pynma.PyNMA( "apikey(s)", "developerkey") lock = threading.RLock()
conn = psycopg2.connect("dbname=test user=postgres")  
   
def worker(filename):  
   
  def get_call():
  global lock
  with lock:
  ser.write("GLG\r")
  line = ser.readline() # read a '\n' terminated line
  print line
  reader = csv.reader([line])
  for row in reader:
  #GLG,40078,NFM,0,0,CanberraBlackMnt,AustralianCapita,SES Ops 1,1,0
  #,NONE,NONE,NONE
  if (row[0] != 'GLG' or row[1] == ''):
  print "uh oh"
  return (None, None, None)
  if (row[1] != ''):
  tgid = row[1]
  #nma.push("scannr", "ping", filename, "http://www.google.com")
  tgname = row[7]
  sitename = row[5]
  return (tgid, tgname, sitename)
   
   
  def log_recording(tgid, tgname, sitename, filename, length):
  cur = conn.cursor()
  cur.execute("INSERT INTO recordings \
  (tgid, tgname, sitename, filename, length)\
  VALUES (%s, %s, %s, %s, %s)", ( tgid, tgname, sitename, filename, length))
  conn.commit()
  cur.close()
   
   
  def tgid_worker():
  global last_call
  last_call = get_call()
   
   
  def save_worker(filename, length):
  global last_call
"""thread worker function """thread worker function
http://www.doughellmann.com/PyMOTW/threading/ http://www.doughellmann.com/PyMOTW/threading/
https://github.com/uskr/pynma https://github.com/uskr/pynma
ffmpeg -i 2012-09-29-1348911268.34-demo.wav -ar 8000 -ab 4.75k test.3gp ffmpeg -i 2012-09-29-1348911268.34-demo.wav -ar 8000 -ab 4.75k test.3gp
http://stackoverflow.com/questions/2559746/getting-error-while-converting-wav-to-amr-using-ffmpeg http://stackoverflow.com/questions/2559746/getting-error-while-converting-
  wav-to-amr-using-ffmpeg
""" """
print 'Worker for '+filename print 'Worker for ' + filename
ser.write("GLG\r") (oldtgid, oldtgname, oldsitename) = last_call
line = ser.readline() # read a '\n' terminated line (tgid, tgname, sitename) = get_call()
print line if oldtgid == tgid:
"""nma.push(application, event, description, (opt) url,)""" if tgid is None or tgid == '':
"""http://initd.org/psycopg/docs/usage.html""" print filename + " has no TGID"
#cur = conn.cursor() else:
#cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def")) log_recording(tgid, tgname, sitename, filename, length)
#conn.commit() else:
#cur.close() if tgid is None or tgid == '':
  print filename + " has no TGID"
  else:
  log_recording(tgid, tgname, sitename, filename, length)
  if oldtgid is None or oldtgid == '':
  print filename + " has no old TGID"
  else:
  log_recording(oldtgid, oldtgname, oldsitename, filename, length)
  return
   
return  
   
def filenameMaker(): def filenameMaker():
global filename global filename
filename = date.today().isoformat()+'-'+str(time.time())+'-demo.wav' filename = date.today().isoformat() + '-' + str(time.time()) + '-demo.wav'
   
def record_to_async_file():  
"Records from the microphone and outputs the resulting data to `path`" def do_record():
  #global filename
sample_width, data = snd.record() sample_width, data = snd.record()
print str(len(data)) thr = threading.Thread(target=record_to_async_file, args=(sample_width, data, filename))
  thr.start()
   
   
  def record_to_async_file(sample_width, data, filename):
  "Records from the microphone and outputs the resulting data to `filename`"
  print "Recording complete"
if len(data) > MIN_LENGTH: if len(data) > MIN_LENGTH:
data = snd.pack('<' + ('h'*len(data)), *data) print "Recording being saved..."
path = filename dispatcher.send(signal='FILE_CREATED', sender=filename, filename=filename, length=len(data))
dispatcher.send( signal='FILE_CREATED', sender=filename, filename=filename) print str(len(data))
  data = snd.pack('<' + ('h' * len(data)), *data)
  path = "./data/" + filename
wf = wave.open(path, 'wb') wf = wave.open(path, 'wb')
wf.setnchannels(1) wf.setnchannels(2)
wf.setsampwidth(sample_width) wf.setsampwidth(sample_width)
wf.setframerate(snd.RATE) wf.setframerate(snd.RATE)
wf.writeframes(data) wf.writeframes(data)
wf.close() wf.close()
print("done - result "+str(len(data))+" frames written to "+path) del wf
  print("done - result " + str(len(data)) + " frames written to " + path)
  del data
   
dispatcher.connect( filenameMaker, signal='SND_STARTED', sender=dispatcher.Any ) dispatcher.connect(filenameMaker, signal='SND_STARTED', sender=dispatcher.Any)
dispatcher.connect( worker, signal='FILE_CREATED', sender=dispatcher.Any ) dispatcher.connect(tgid_worker, signal='SND_STARTED', sender=dispatcher.Any)
  dispatcher.connect(save_worker, signal='FILE_CREATED', sender=dispatcher.Any)
   
ser = serial.Serial('COM20', 112500, timeout=1) print "Opening serial port..."
  if sys.platform.startswith('darwin'):
  ser = serial.Serial('/dev/tty.usbserial-FTB3VL83', 112500, timeout=1)
  elif sys.platform.startswith('win32'):
  ser = serial.Serial('COM20', 112500, timeout=1)
  print "Loading notifymyandroid..."
  nma = pynma.PyNMA("a6f50f76119eda33befe4325b4b9e1dd25eef7bad2868e4f")
  print "Connecting database..."
  conn = psycopg2.connect("dbname=scannr user=postgres password=snmc")
  print "Scannr started."
  while True:
  print "ready to record again"
  do_record()
  ser.close()
   
print "Scannr started..."  
while True:  
print "ready to record"  
record_to_async_file()  
ser.close()  
  bin
  gen
  target
  .settings
  .classpath
  .project
  *.keystore
  *.swp
  *.orig
  *.log
  *.properties
  seed.txt
  map.txt
 
  scannrmobile
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="AntConfiguration">
  <defaultAnt bundledAnt="true" />
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="CompilerConfiguration">
  <option name="DEFAULT_COMPILER" value="Javac" />
  <excludeFromCompile>
  <directory url="file://$PROJECT_DIR$/gen" includeSubdirectories="true" />
  </excludeFromCompile>
  <resourceExtensions />
  <wildcardResourcePatterns>
  <entry name="!?*.java" />
  <entry name="!?*.form" />
  <entry name="!?*.class" />
  <entry name="!?*.groovy" />
  <entry name="!?*.scala" />
  <entry name="!?*.flex" />
  <entry name="!?*.kt" />
  <entry name="!?*.clj" />
  </wildcardResourcePatterns>
  <annotationProcessing>
  <profile default="true" name="Default" enabled="false">
  <processorPath useClasspath="true" />
  </profile>
  </annotationProcessing>
  </component>
  </project>
 
 
  <component name="CopyrightManager">
  <settings default="">
  <module2copyright />
  </settings>
  </component>
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="EntryPointsManager">
  <entry_points version="2.0" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="Android 4.2 Platform" project-jdk-type="Android SDK">
  <output url="file://$PROJECT_DIR$/out" />
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="ProjectModuleManager">
  <modules>
  <module fileurl="file://$PROJECT_DIR$/scannrmobile.iml" filepath="$PROJECT_DIR$/scannrmobile.iml" />
  </modules>
  </component>
  </project>
 
 
  <component name="DependencyValidationManager">
  <state>
  <option name="SKIP_IMPORT_STATEMENTS" value="false" />
  </state>
  </component>
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="Palette2">
  <group name="Swing">
  <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
  </item>
  <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
  </item>
  <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
  <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
  <initial-values>
  <property name="text" value="Button" />
  </initial-values>
  </item>
  <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="RadioButton" />
  </initial-values>
  </item>
  <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="CheckBox" />
  </initial-values>
  </item>
  <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
  <initial-values>
  <property name="text" value="Label" />
  </initial-values>
  </item>
  <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
  <preferred-size width="150" height="-1" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
  <preferred-size width="150" height="50" />
  </default-constraints>
  </item>
  <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
  <preferred-size width="200" height="200" />
  </default-constraints>
  </item>
  <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
  <preferred-size width="200" height="200" />
  </default-constraints>
  </item>
  <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
  </item>
  <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
  </item>
  <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
  </item>
  <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
  <preferred-size width="-1" height="20" />
  </default-constraints>
  </item>
  <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
  <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
  </item>
  <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
  <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
  </item>
  </group>
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="VcsDirectoryMappings">
  <mapping directory="" vcs="" />
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project version="4">
  <component name="AndroidConfiguredLogFilters">
  <filters>
  <filter>
  <option name="logLevel" value="verbose" />
  <option name="logMessagePattern" value="Scannr" />
  <option name="logTagPattern" value="" />
  <option name="name" value="Scannr" />
  <option name="pid" value="" />
  </filter>
  </filters>
  </component>
  <component name="AndroidDesignerProfile">
  <option name="fullProfile">
  <profile>
  <option name="device" value="2.7in QVGA" />
  <option name="deviceConfiguration" value="Portrait" />
  <option name="targetHashString" value="android-17" />
  <option name="theme" value="Theme" />
  </profile>
  </option>
  <option name="selection" value="[Full]" />
  </component>
  <component name="AndroidLogFilters">
  <option name="TOOL_WINDOW_CONFIGURED_FILTER" value="Scannr" />
  </component>
  <component name="ChangeListManager">
  <list default="true" id="4912fbca-fcd2-420f-a992-61830c24c4b5" name="Default" comment="" />
  <ignored path="scannrmobile.iws" />
  <ignored path=".idea/workspace.xml" />
  <file path="$PROJECT_DIR$/res/values/strings.xml" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356156665048" ignored="false" />
  <file path="/fragment.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356173506003" ignored="false" />
  <file path="/HttpTask.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356175420628" ignored="false" />
  <file path="$PROJECT_DIR$/gen/com/example/scannrmobile/Manifest.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356176134813" ignored="false" />
  <file path="$PROJECT_DIR$/gen/com/example/scannrmobile/R.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356176134813" ignored="false" />
  <file path="$PROJECT_DIR$/gen/com/example/scannrmobile/BuildConfig.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356176134813" ignored="false" />
  <file path="/ScannrMobile.java" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356177267735" ignored="false" />
  <file path="/Dummy.txt" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356175572532" ignored="false" />
  <file path="$USER_HOME$/Sites/scannr/calls.json.php" changelist="4912fbca-fcd2-420f-a992-61830c24c4b5" time="1356175698040" ignored="false" />
  <option name="TRACKING_ENABLED" value="true" />
  <option name="SHOW_DIALOG" value="false" />
  <option name="HIGHLIGHT_CONFLICTS" value="true" />
  <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
  <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
  <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
  <disable_hints />
  </component>
  <component name="DebuggerManager">
  <line_breakpoints default_suspend_policy="SuspendAll" default_condition_enabled="true" />
  <breakpoint_any default_suspend_policy="SuspendAll" default_condition_enabled="true">
  <breakpoint>
  <option name="NOTIFY_CAUGHT" value="true" />
  <option name="NOTIFY_UNCAUGHT" value="true" />
  <option name="ENABLED" value="false" />
  <option name="LOG_ENABLED" value="false" />
  <option name="LOG_EXPRESSION_ENABLED" value="false" />
  <option name="SUSPEND_POLICY" value="SuspendAll" />
  <option name="SUSPEND" value="true" />
  <option name="COUNT_FILTER_ENABLED" value="false" />
  <option name="COUNT_FILTER" value="0" />
  <option name="CONDITION_ENABLED" value="true" />
  <option name="CLASS_FILTERS_ENABLED" value="false" />
  <option name="INSTANCE_FILTERS_ENABLED" value="false" />
  <option name="CONDITION" value="" />
  <option name="LOG_MESSAGE" value="" />
  </breakpoint>
  <breakpoint>
  <option name="NOTIFY_CAUGHT" value="true" />
  <option name="NOTIFY_UNCAUGHT" value="true" />
  <option name="ENABLED" value="false" />
  <option name="LOG_ENABLED" value="false" />
  <option name="LOG_EXPRESSION_ENABLED" value="false" />
  <option name="SUSPEND_POLICY" value="SuspendAll" />
  <option name="SUSPEND" value="true" />
  <option name="COUNT_FILTER_ENABLED" value="false" />
  <option name="COUNT_FILTER" value="0" />
  <option name="CONDITION_ENABLED" value="true" />
  <option name="CLASS_FILTERS_ENABLED" value="false" />
  <option name="INSTANCE_FILTERS_ENABLED" value="false" />
  <option name="CONDITION" value="" />
  <option name="LOG_MESSAGE" value="" />
  </breakpoint>
  </breakpoint_any>
  <ui_properties default_suspend_policy="SuspendAll" default_condition_enabled="true" />
  <breakpoint_rules />
  <ui_properties />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
  <favorites_list name="scannrmobile" />
  </component>
  <component name="FileEditorManager">
  <leaf>
  <file leaf-file-name="ScannrMobile.java" pinned="false" current="true" current-in-tab="true">
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/ScannrMobile.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="32" column="50" selection-start="1063" selection-end="1073" vertical-scroll-proportion="0.44060475">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="ArrayAdapter.java" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$USER_HOME$/Downloads/android-sdk-macosx/sources/android-17/android/widget/ArrayAdapter.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="46" column="13" selection-start="1860" selection-end="1860" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="simplerow.xml" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/res/layout/simplerow.xml">
  <provider selected="true" editor-type-id="android-designer">
  <state />
  </provider>
  <provider editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="HttpTask.java" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/HttpTask.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="61" column="28" selection-start="1919" selection-end="1919" vertical-scroll-proportion="0.0">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  </file>
  <file leaf-file-name="AndroidManifest.xml" pinned="false" current="false" current-in-tab="false">
  <entry file="file://$PROJECT_DIR$/AndroidManifest.xml">
  <provider selected="true" editor-type-id="text-editor">
  <state line="5" column="68" selection-start="266" selection-end="266" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  </file>
  </leaf>
  </component>
  <component name="FindManager">
  <FindUsagesManager>
  <setting name="OPEN_NEW_TAB" value="false" />
  </FindUsagesManager>
  </component>
  <component name="IdeDocumentHistory">
  <option name="changedFiles">
  <list>
  <option value="$PROJECT_DIR$/AndroidManifest.xml" />
  <option value="$PROJECT_DIR$/src/com/example/scannrmobile/HttpTask.java" />
  <option value="$PROJECT_DIR$/res/layout/main.xml" />
  <option value="$PROJECT_DIR$/src/com/example/scannrmobile/ScannrMobile.java" />
  </list>
  </option>
  </component>
  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
  <component name="ProjectFrameBounds">
  <option name="y" value="22" />
  <option name="width" value="1680" />
  <option name="height" value="937" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
  <OptionsSetting value="true" id="Add" />
  <OptionsSetting value="true" id="Remove" />
  <OptionsSetting value="true" id="Checkout" />
  <OptionsSetting value="true" id="Update" />
  <OptionsSetting value="true" id="Status" />
  <OptionsSetting value="true" id="Edit" />
  <ConfirmationsSetting value="0" id="Add" />
  <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectReloadState">
  <option name="STATE" value="0" />
  </component>
  <component name="ProjectView">
  <navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
  <flattenPackages />
  <showMembers />
  <showModules />
  <showLibraryContents />
  <hideEmptyPackages />
  <abbreviatePackageNames />
  <autoscrollToSource />
  <autoscrollFromSource />
  <sortByType />
  </navigator>
  <panes>
  <pane id="ProjectPane">
  <subPane>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  </PATH>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  </PATH>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="src" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  </PATH>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="res" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  </PATH>
  <PATH>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="scannrmobile" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="res" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  <PATH_ELEMENT>
  <option name="myItemId" value="layout" />
  <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
  </PATH_ELEMENT>
  </PATH>
  </subPane>
  </pane>
  <pane id="PackagesPane" />
  <pane id="Scope" />
  </panes>
  </component>
  <component name="PropertiesComponent">
  <property name="GoToFile.includeJavaFiles" value="false" />
  <property name="project.structure.last.edited" value="Modules" />
  <property name="project.structure.proportion" value="0.0" />
  <property name="options.splitter.main.proportions" value="0.3" />
  <property name="options.lastSelected" value="preferences.pluginManager" />
  <property name="MemberChooser.sorted" value="false" />
  <property name="recentsLimit" value="5" />
  <property name="AndroidLayoutSelectedEditor" value="android-designer" />
  <property name="project.structure.side.proportion" value="0.2" />
  <property name="MemberChooser.copyJavadoc" value="false" />
  <property name="GoToClass.toSaveIncludeLibraries" value="false" />
  <property name="WebServerToolWindowFactoryState" value="false" />
  <property name="restartRequiresConfirmation" value="true" />
  <property name="FullScreen" value="false" />
  <property name="MemberChooser.showClasses" value="true" />
  <property name="GoToClass.includeLibraries" value="false" />
  <property name="options.splitter.details.proportions" value="0.2" />
  <property name="options.searchVisible" value="true" />
  </component>
  <component name="PyConsoleOptionsProvider">
  <option name="myPythonConsoleState">
  <PyConsoleSettings />
  </option>
  <option name="myDjangoConsoleState">
  <PyConsoleSettings />
  </option>
  </component>
  <component name="RunManager" selected="Android Application.scannrmobile">
  <configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin">
  <module name="" />
  <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m" />
  <option name="PROGRAM_PARAMETERS" />
  <method />
  </configuration>
  <configuration default="true" type="AndroidTestRunConfigurationType" factoryName="Android Tests">
  <module name="" />
  <option name="TESTING_TYPE" value="0" />
  <option name="INSTRUMENTATION_RUNNER_CLASS" value="" />
  <option name="METHOD_NAME" value="" />
  <option name="CLASS_NAME" value="" />
  <option name="PACKAGE_NAME" value="" />
  <option name="TARGET_SELECTION_MODE" value="EMULATOR" />
  <option name="PREFERRED_AVD" value="" />
  <option name="COMMAND_LINE" value="" />
  <option name="WIPE_USER_DATA" value="false" />
  <option name="DISABLE_BOOT_ANIMATION" value="false" />
  <option name="NETWORK_SPEED" value="full" />
  <option name="NETWORK_LATENCY" value="none" />
  <option name="CLEAR_LOGCAT" value="false" />
  <method />
  </configuration>
  <configuration default="true" type="Remote" factoryName="Remote">
  <option name="USE_SOCKET_TRANSPORT" value="true" />
  <option name="SERVER_MODE" value="false" />
  <option name="SHMEM_ADDRESS" value="javadebug" />
  <option name="HOST" value="localhost" />
  <option name="PORT" value="5005" />
  <method />
  </configuration>
  <configuration default="true" type="Applet" factoryName="Applet">
  <module name="" />
  <option name="MAIN_CLASS_NAME" />
  <option name="HTML_FILE_NAME" />
  <option name="HTML_USED" value="false" />
  <option name="WIDTH" value="400" />
  <option name="HEIGHT" value="300" />
  <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
  <option name="VM_PARAMETERS" />
  <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
  <option name="ALTERNATIVE_JRE_PATH" />
  <method />
  </configuration>
  <configuration default="true" type="TestNG" factoryName="TestNG">
  <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
  <module name="" />
  <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
  <option name="ALTERNATIVE_JRE_PATH" />
  <option name="SUITE_NAME" />
  <option name="PACKAGE_NAME" />
  <option name="MAIN_CLASS_NAME" />
  <option name="METHOD_NAME" />
  <option name="GROUP_NAME" />
  <option name="TEST_OBJECT" value="CLASS" />
  <option name="VM_PARAMETERS" value="-ea" />
  <option name="PARAMETERS" />
  <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
  <option name="OUTPUT_DIRECTORY" />
  <option name="ANNOTATION_TYPE" />
  <option name="ENV_VARIABLES" />
  <option name="PASS_PARENT_ENVS" value="true" />
  <option name="TEST_SEARCH_SCOPE">
  <value defaultName="moduleWithDependencies" />
  </option>
  <option name="USE_DEFAULT_REPORTERS" value="false" />
  <option name="PROPERTIES_FILE" />
  <envs />
  <properties />
  <listeners />
  <method />
  </configuration>
  <configuration default="true" type="Application" factoryName="Application">
  <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
  <option name="MAIN_CLASS_NAME" />
  <option name="VM_PARAMETERS" />
  <option name="PROGRAM_PARAMETERS" />
  <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
  <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
  <option name="ALTERNATIVE_JRE_PATH" />
  <option name="ENABLE_SWING_INSPECTOR" value="false" />
  <option name="ENV_VARIABLES" />
  <option name="PASS_PARENT_ENVS" value="true" />
  <module name="" />
  <envs />
  <method />
  </configuration>
  <configuration default="true" type="JUnit" factoryName="JUnit">
  <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
  <module name="" />
  <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
  <option name="ALTERNATIVE_JRE_PATH" />
  <option name="PACKAGE_NAME" />
  <option name="MAIN_CLASS_NAME" />
  <option name="METHOD_NAME" />
  <option name="TEST_OBJECT" value="class" />
  <option name="VM_PARAMETERS" value="-ea" />
  <option name="PARAMETERS" />
  <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
  <option name="ENV_VARIABLES" />
  <option name="PASS_PARENT_ENVS" value="true" />
  <option name="TEST_SEARCH_SCOPE">
  <value defaultName="moduleWithDependencies" />
  </option>
  <envs />
  <patterns />
  <method />
  </configuration>
  <configuration default="true" type="AndroidRunConfigurationType" factoryName="Android Application">
  <module name="" />
  <option name="ACTIVITY_CLASS" value="" />
  <option name="MODE" value="default_activity" />
  <option name="DEPLOY" value="true" />
  <option name="TARGET_SELECTION_MODE" value="EMULATOR" />
  <option name="PREFERRED_AVD" value="" />
  <option name="COMMAND_LINE" value="" />
  <option name="WIPE_USER_DATA" value="false" />
  <option name="DISABLE_BOOT_ANIMATION" value="false" />
  <option name="NETWORK_SPEED" value="full" />
  <option name="NETWORK_LATENCY" value="none" />
  <option name="CLEAR_LOGCAT" value="false" />
  <method />
  </configuration>
  <configuration default="false" name="scannrmobile" type="AndroidRunConfigurationType" factoryName="Android Application">
  <module name="scannrmobile" />
  <option name="ACTIVITY_CLASS" value="com.example.scannrmobile.ScannrMobile" />
  <option name="MODE" value="specific_activity" />
  <option name="DEPLOY" value="true" />
  <option name="TARGET_SELECTION_MODE" value="EMULATOR" />
  <option name="PREFERRED_AVD" value="MyAvd0" />
  <option name="COMMAND_LINE" value="" />
  <option name="WIPE_USER_DATA" value="false" />
  <option name="DISABLE_BOOT_ANIMATION" value="false" />
  <option name="NETWORK_SPEED" value="full" />
  <option name="NETWORK_LATENCY" value="none" />
  <option name="CLEAR_LOGCAT" value="true" />
  <RunnerSettings RunnerId="AndroidDebugRunner" />
  <ConfigurationWrapper RunnerId="AndroidDebugRunner" />
  <method />
  </configuration>
  <list size="1">
  <item index="0" class="java.lang.String" itemvalue="Android Application.scannrmobile" />
  </list>
  <configuration name="&lt;template&gt;" type="WebApp" default="true" selected="false">
  <Host>localhost</Host>
  <Port>5050</Port>
  </configuration>
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="SvnConfiguration" maxAnnotateRevisions="500" myUseAcceleration="nothing" myAutoUpdateAfterCommit="false" cleanupOnStartRun="false">
  <option name="USER" value="" />
  <option name="PASSWORD" value="" />
  <option name="mySSHConnectionTimeout" value="30000" />
  <option name="mySSHReadTimeout" value="30000" />
  <option name="LAST_MERGED_REVISION" />
  <option name="MERGE_DRY_RUN" value="false" />
  <option name="MERGE_DIFF_USE_ANCESTRY" value="true" />
  <option name="UPDATE_LOCK_ON_DEMAND" value="false" />
  <option name="IGNORE_SPACES_IN_MERGE" value="false" />
  <option name="DETECT_NESTED_COPIES" value="true" />
  <option name="CHECK_NESTED_FOR_QUICK_MERGE" value="false" />
  <option name="IGNORE_SPACES_IN_ANNOTATE" value="true" />
  <option name="SHOW_MERGE_SOURCES_IN_ANNOTATE" value="true" />
  <option name="FORCE_UPDATE" value="false" />
  <option name="IGNORE_EXTERNALS" value="false" />
  <myIsUseDefaultProxy>false</myIsUseDefaultProxy>
  </component>
  <component name="TaskManager">
  <task active="true" id="Default" summary="Default task">
  <changelist id="4912fbca-fcd2-420f-a992-61830c24c4b5" name="Default" comment="" />
  <created>1356156646856</created>
  <updated>1356156646856</updated>
  </task>
  <servers />
  </component>
  <component name="ToolWindowManager">
  <frame x="0" y="22" width="1680" height="937" extended-state="6" />
  <editor active="true" />
  <layout>
  <window_info id="Palette&#9;" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32986537" sideWeight="0.6719706" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32986537" sideWeight="0.6719706" order="2" side_tool="false" content_ui="tabs" />
  <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
  <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.39902082" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32925338" sideWeight="0.500612" order="7" side_tool="true" content_ui="tabs" />
  <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
  <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32802936" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="Android" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32925338" sideWeight="0.49510404" order="7" side_tool="false" content_ui="tabs" />
  <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
  <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" />
  <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
  <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
  <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.249694" sideWeight="0.6009792" order="0" side_tool="false" content_ui="combo" />
  <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32925338" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
  <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
  <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
  <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32925338" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
  <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
  <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
  </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
  <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
  <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
  <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
  <option name="CHECK_NEW_TODO" value="true" />
  <option name="myTodoPanelSettings">
  <value>
  <are-packages-shown value="false" />
  <are-modules-shown value="false" />
  <flatten-packages value="false" />
  <is-autoscroll-to-source value="false" />
  </value>
  </option>
  <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
  <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
  <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
  <option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
  <option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="false" />
  <option name="CHANGED_ON_SERVER_INTERVAL" value="60" />
  <option name="SHOW_ONLY_CHANGED_IN_SELECTION_DIFF" value="true" />
  <option name="CHECK_COMMIT_MESSAGE_SPELLING" value="true" />
  <option name="DEFAULT_PATCH_EXTENSION" value="patch" />
  <option name="SHORT_DIFF_HORISONTALLY" value="true" />
  <option name="SHORT_DIFF_EXTRA_LINES" value="2" />
  <option name="SOFT_WRAPS_IN_SHORT_DIFF" value="true" />
  <option name="INCLUDE_TEXT_INTO_PATCH" value="false" />
  <option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
  <option name="SHOW_FILE_HISTORY_DETAILS" value="true" />
  <option name="SHOW_VCS_ERROR_NOTIFICATIONS" value="true" />
  <option name="SHOW_DIRTY_RECURSIVELY" value="false" />
  <option name="LIMIT_HISTORY" value="true" />
  <option name="MAXIMUM_HISTORY_ROWS" value="1000" />
  <option name="FORCE_NON_EMPTY_COMMENT" value="false" />
  <option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="false" />
  <option name="LAST_COMMIT_MESSAGE" />
  <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="false" />
  <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
  <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
  <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
  <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
  <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
  <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
  <option name="ACTIVE_VCS_NAME" />
  <option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
  <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
  <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
  <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
  </component>
  <component name="XDebuggerManager">
  <breakpoint-manager />
  </component>
  <component name="antWorkspaceConfiguration">
  <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" />
  <option name="FILTER_TARGETS" value="false" />
  </component>
  <component name="editorHistoryManager">
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/HttpTask.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="6" column="30" selection-start="184" selection-end="184" vertical-scroll-proportion="0.0">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  <entry file="file://$USER_HOME$/Downloads/android-sdk-macosx/sources/android-17/android/os/AsyncTask.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="347" column="53" selection-start="14141" selection-end="14141" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/AndroidManifest.xml">
  <provider selected="true" editor-type-id="text-editor">
  <state line="5" column="68" selection-start="266" selection-end="266" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/res/layout/main.xml">
  <provider selected="true" editor-type-id="android-designer">
  <state />
  </provider>
  <provider editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/ScannrMobile.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="37" column="0" selection-start="1317" selection-end="1317" vertical-scroll-proportion="0.0">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/AndroidManifest.xml">
  <provider selected="true" editor-type-id="text-editor">
  <state line="5" column="68" selection-start="266" selection-end="266" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/res/layout/main.xml">
  <provider selected="true" editor-type-id="android-designer">
  <state />
  </provider>
  <provider editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/ScannrMobile.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="48" column="0" selection-start="1666" selection-end="1666" vertical-scroll-proportion="0.0">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/AndroidManifest.xml">
  <provider selected="true" editor-type-id="text-editor">
  <state line="5" column="68" selection-start="266" selection-end="266" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$USER_HOME$/Downloads/android-sdk-macosx/sources/android-17/android/os/AsyncTask.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="347" column="53" selection-start="14141" selection-end="14141" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/AndroidManifest.xml">
  <provider selected="true" editor-type-id="text-editor">
  <state line="5" column="68" selection-start="266" selection-end="266" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/res/layout/main.xml">
  <provider selected="true" editor-type-id="android-designer">
  <state />
  </provider>
  <provider editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/res/layout/simplerow.xml">
  <provider selected="true" editor-type-id="android-designer">
  <state />
  </provider>
  <provider editor-type-id="text-editor">
  <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$USER_HOME$/Downloads/android-sdk-macosx/sources/android-17/android/widget/ArrayAdapter.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="46" column="13" selection-start="1860" selection-end="1860" vertical-scroll-proportion="0.0">
  <folding />
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/HttpTask.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="61" column="28" selection-start="1919" selection-end="1919" vertical-scroll-proportion="0.0">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  <entry file="file://$PROJECT_DIR$/src/com/example/scannrmobile/ScannrMobile.java">
  <provider selected="true" editor-type-id="text-editor">
  <state line="32" column="50" selection-start="1063" selection-end="1073" vertical-scroll-proportion="0.44060475">
  <folding>
  <element signature="imports" expanded="true" />
  </folding>
  </state>
  </provider>
  </entry>
  </component>
  <component name="masterDetails">
  <states>
  <state key="ArtifactsStructureConfigurable.UI">
  <settings>
  <artifact-editor />
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  <state key="FacetStructureConfigurable.UI">
  <settings>
  <last-edited>Android</last-edited>
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  <state key="GlobalLibrariesConfigurable.UI">
  <settings>
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  <state key="JdkListConfigurable.UI">
  <settings>
  <last-edited>Android 4.2 Platform</last-edited>
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  <state key="ModuleStructureConfigurable.UI">
  <settings>
  <last-edited>Android|scannrmobile</last-edited>
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  <state key="ProjectLibrariesConfigurable.UI">
  <settings>
  <splitter-proportions>
  <option name="proportions">
  <list>
  <option value="0.2" />
  </list>
  </option>
  </splitter-proportions>
  </settings>
  </state>
  </states>
  </component>
  </project>
 
 
  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.scannrmobile"
  android:versionCode="1"
  android:versionName="1.0">
  <uses-sdk android:minSdkVersion="17"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
  <activity android:name="ScannrMobile"
  android:label="@string/app_name">
  <intent-filter>
  <action android:name="android.intent.action.MAIN"/>
  <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
  </activity>
  </application>
  </manifest>
 
  <?xml version="1.0" encoding="UTF-8"?>
  <project name="scannrmobile" default="help">
 
  <!-- The local.properties file is created and updated by the 'android' tool.
  It contains the path to the SDK. It should *NOT* be checked into
  Version Control Systems. -->
  <property file="local.properties"/>
 
  <!-- The ant.properties file can be created by you. It is only edited by the
  'android' tool to add properties to it.
  This is the place to change some Ant specific build properties.
  Here are some properties you may want to change/update:
 
  source.dir
  The name of the source directory. Default is 'src'.
  out.dir
  The name of the output directory. Default is 'bin'.
 
  For other overridable properties, look at the beginning of the rules
  files in the SDK, at tools/ant/build.xml
 
  Properties related to the SDK location or the project target should
  be updated using the 'android' tool with the 'update' action.
 
  This file is an integral part of the build system for your
  application and should be checked into Version Control Systems.
 
  -->
  <property file="ant.properties"/>
 
  <!-- if sdk.dir was not set from one of the property file, then
  get it from the ANDROID_HOME env var.
  This must be done before we load project.properties since
  the proguard config can use sdk.dir -->
  <property environment="env"/>
  <condition property="sdk.dir" value="${env.ANDROID_HOME}">
  <isset property="env.ANDROID_HOME"/>
  </condition>
 
  <!-- The project.properties file is created and updated by the 'android'
  tool, as well as ADT.
 
  This contains project specific properties such as project target, and library
  dependencies. Lower level build properties are stored in ant.properties
  (or in .classpath for Eclipse projects).
 
  This file is an integral part of the build system for your
  application and should be checked into Version Control Systems. -->
  <loadproperties srcFile="project.properties"/>
 
  <!-- quick check on sdk.dir -->
  <fail
  message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
  unless="sdk.dir"
  />
 
  <!--
  Import per project custom build rules if present at the root of the project.
  This is the place to put custom intermediary targets such as:
  -pre-build
  -pre-compile
  -post-compile (This is typically used for code obfuscation.
  Compiled code location: ${out.classes.absolute.dir}
  If this is not done in place, override ${out.dex.input.absolute.dir})
  -post-package
  -post-build
  -pre-clean
  -->
  <import file="custom_rules.xml" optional="true"/>
 
  <!-- Import the actual build file.
 
  To customize existing targets, there are two options:
  - Customize only one target:
  - copy/paste the target into this file, *before* the
  <import> task.
  - customize it to your needs.
  - Customize the whole content of build.xml
  - copy/paste the content of the rules files (minus the top node)
  into this file, replacing the <import> task.
  - customize to your needs.
 
  ***********************
  ****** IMPORTANT ******
  ***********************
  In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
  in order to avoid having your file be overridden by tools such as "android update project"
  -->
  <!-- version-tag: 1 -->
  <import file="${sdk.dir}/tools/ant/build.xml"/>
 
  </project>
 
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/BuildConfig.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/HttpTask$HttpTaskHandler.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/HttpTask.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R$attr.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R$drawable.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R$id.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R$layout.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R$string.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/R.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/ScannrMobile$1.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/com/example/scannrmobile/ScannrMobile.class differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/scannrmobile.afp.apk differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/scannrmobile.apk differ
 Binary files /dev/null and b/scannrmobile/out/production/scannrmobile/scannrmobile.unaligned.apk differ
  # To enable ProGuard in your project, edit project.properties
  # to define the proguard.config property as described in that file.
  #
  # Add project specific ProGuard rules here.
  # By default, the flags in this file are appended to flags specified
  # in ${sdk.dir}/tools/proguard/proguard-android.txt
  # You can edit the include path and order by changing the ProGuard
  # include property in project.properties.
  #
  # For more details, see
  # http://developer.android.com/guide/developing/tools/proguard.html
 
  # Add any project specific keep options here:
 
  # If your project uses WebView with JS, uncomment the following
  # and specify the fully qualified class name to the JavaScript interface
  # class:
  #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
  # public *;
  #}
 
 Binary files /dev/null and b/scannrmobile/res/drawable-hdpi/ic_launcher.png differ
 Binary files /dev/null and b/scannrmobile/res/drawable-ldpi/ic_launcher.png differ
 Binary files /dev/null and b/scannrmobile/res/drawable-mdpi/ic_launcher.png differ
 Binary files /dev/null and b/scannrmobile/res/drawable-xhdpi/ic_launcher.png differ
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
 
  <ListView android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/mainListView">
  </ListView>
 
  </LinearLayout>
 
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rowTextView"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="10dp"
  android:textSize="16sp" >
  </TextView>
 
  <?xml version="1.0" encoding="utf-8"?>
  <resources>
  <string name="app_name">scannrmobile</string>
  </resources>
 
  <?xml version="1.0" encoding="UTF-8"?>
  <module type="JAVA_MODULE" version="4">
  <component name="FacetManager">
  <facet type="android" name="Android">
  <configuration>
  <option name="GEN_FOLDER_RELATIVE_PATH_APT" value="/gen" />
  <option name="GEN_FOLDER_RELATIVE_PATH_AIDL" value="/gen" />
  <option name="MANIFEST_FILE_RELATIVE_PATH" value="/AndroidManifest.xml" />
  <option name="RES_FOLDER_RELATIVE_PATH" value="/res" />
  <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/assets" />
  <option name="LIBS_FOLDER_RELATIVE_PATH" value="/libs" />
  <option name="USE_CUSTOM_APK_RESOURCE_FOLDER" value="false" />
  <option name="CUSTOM_APK_RESOURCE_FOLDER" value="" />
  <option name="USE_CUSTOM_COMPILER_MANIFEST" value="false" />
  <option name="CUSTOM_COMPILER_MANIFEST" value="" />
  <option name="APK_PATH" value="" />
  <option name="LIBRARY_PROJECT" value="false" />
  <option name="RUN_PROCESS_RESOURCES_MAVEN_TASK" value="true" />
  <option name="GENERATE_UNSIGNED_APK" value="false" />
  <option name="CUSTOM_DEBUG_KEYSTORE_PATH" value="" />
  <option name="PACK_TEST_CODE" value="false" />
  <option name="RUN_PROGUARD" value="false" />
  <option name="PROGUARD_CFG_PATH" value="/proguard-project.txt" />
  <resOverlayFolders>
  <path>/res-overlay</path>
  </resOverlayFolders>
  <includeSystemProguardFile>true</includeSystemProguardFile>
  <includeAssetsFromLibraries>false</includeAssetsFromLibraries>
  <additionalNativeLibs />
  </configuration>
  </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
  <exclude-output />
  <content url="file://$MODULE_DIR$">
  <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
  <sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" />
  </content>
  <orderEntry type="inheritedJdk" />
  <orderEntry type="sourceFolder" forTests="false" />
  </component>
  </module>
 
 
  package com.example.scannrmobile;
 
  import android.os.AsyncTask;
 
  import org.apache.http.client.methods.*;
  import java.io.BufferedReader;
  import java.io.InputStreamReader;
 
  import org.apache.http.HttpResponse;
  import org.apache.http.client.HttpClient;
  import org.apache.http.impl.client.DefaultHttpClient;
 
  import org.json.*;
  import android.util.Log;
 
 
  //http://www.accella.net/android-http-get-json/
  public class HttpTask extends AsyncTask<HttpUriRequest,Void,JSONArray> {
  private static final String TAG = "Scannr_HTTP_TASK";
 
  @Override
  protected JSONArray doInBackground(HttpUriRequest...params) {
 
  // Performed on Background Thread
 
  HttpUriRequest request = params[0];
  HttpClient client = new DefaultHttpClient();
 
  try {
  // The UI Thread shouldn't be blocked long enough to do the reading in of the stream.
  HttpResponse response = client.execute(request);
 
  // TODO handle bad response codes (such as 404, etc)
 
  BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
  StringBuilder builder = new StringBuilder();
  for (String line = null; (line = reader.readLine()) != null; ) {
  builder.append(line).append("\n");
  }
  JSONTokener tokener = new JSONTokener(builder.toString());
  JSONArray json = new JSONArray(tokener);
  return json;
 
  } catch (Exception e) {
  // TODO handle different exception cases
  Log.e(TAG,e.toString());
  e.printStackTrace();
  return null;
  }
  }
 
  @Override
  protected void onPostExecute(JSONArray json) {
  // Done on UI Thread
  if(json != null) {
  taskHandler.taskSuccessful(json);
  } else {
  taskHandler.taskFailed();
  }
  }
 
  public static interface HttpTaskHandler {
  void taskSuccessful(JSONArray json);
  void taskFailed();
  }
 
  HttpTaskHandler taskHandler;
 
  public void setTaskHandler(HttpTaskHandler taskHandler) {
  this.taskHandler = taskHandler;
  }
 
  }
  package com.example.scannrmobile;
 
  import android.app.Activity;
  import android.os.Bundle;
  import android.util.Log;
  import android.widget.ArrayAdapter;
  import android.widget.ListView;
  import com.example.scannrmobile.HttpTask.HttpTaskHandler;
  import org.apache.http.client.methods.HttpGet;
  import org.json.JSONArray;
  import org.json.JSONException;
 
  import java.util.ArrayList;
 
  public class ScannrMobile extends Activity {
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
  private ScannrMobile view;
  /**
  * Called when the activity is first created.
  */
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mainListView = (ListView) findViewById( R.id.mainListView );
  view = this;
  //DownloadWebPageTask task = new DownloadWebPageTask();
  //task.execute(new String[] { "http://www.vogella.com" });
  HttpTask task = new HttpTask();
 
  task.setTaskHandler(new HttpTaskHandler()
  {
  public void taskSuccessful(JSONArray nodes) {
  // Just put the JSONObjects into an array list so we can use a ListAdapter
  ArrayList<String> data = new ArrayList();
  // Ingest Data
  try {
 
  Log.d(this.getClass().getName(), "Total Nodes: "+nodes.length());
  for (int i = 0; i < nodes.length(); i++ ) {
  data.add(nodes.getJSONObject(i).toString() );
  }
  // TODO update the list
  } catch (JSONException j){
  Log.e(this.getClass().getName(), j.getMessage());
  }
  // Create ArrayAdapter using the planet list.
  listAdapter = new ArrayAdapter<String>(view, R.layout.simplerow, R.id.rowTextView, data);
 
  // Set the ArrayAdapter as the ListView's adapter.
  mainListView.setAdapter( listAdapter );
  }
 
  public void taskFailed() {
  // handler failure (e.g network not available etc.)
  Log.e(this.getClass().getName(),"Task Failed");
  }
  });
  task.execute(new HttpGet("http://192.168.1.113/~maxious/scannr/calls.json.php?action=data"));
  }
 
 
  }
 
 
file:a/snd.py -> file:b/snd.py
""" Record a few seconds of audio and save to a WAVE file. """ Record a few seconds of audio and save to a WAVE file.
Based on http://stackoverflow.com/questions/892199/detect-record-audio-in-python/6743593#6743593 Based on http://stackoverflow.com/questions/892199/detect-record-audio-in-python/6743593#6743593
""" """
   
import pyaudio import pyaudio
import wave import wave
import sys import sys
import audioop # http://docs.python.org/library/audioop  
from os.path import exists  
from array import array from array import array
from struct import unpack, pack from struct import unpack, pack
import threading  
from pydispatch import dispatcher from pydispatch import dispatcher
   
CHANNELS = 1  
THRESHOLD = 500 THRESHOLD = 500
CHUNK_SIZE = 1024 CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16 FORMAT = pyaudio.paInt16
RATE = 44100 RATE = 44100
MAX_SILENT = 30 if sys.platform.startswith('darwin'):
  CHANNELS = 2
  elif sys.platform.startswith('win32'):
  CHANNELS = 1
   
  MAX_SILENT = 80
   
def is_silent(L): def is_silent(L):
"Returns `True` if below the 'silent' threshold" "Returns `True` if below the 'silent' threshold"
"print max(L)" "print max(L)"
"print max(L) < THRESHOLD" "print max(L) < THRESHOLD"
return max(L) < THRESHOLD return max(L) < THRESHOLD
   
   
def normalize(L): def normalize(L):
"Average the volume out" "Average the volume out"
MAXIMUM = 16384 MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in L) times = float(MAXIMUM) / max(abs(i) for i in L)
   
LRtn = array('h') LRtn = array('h')
for i in L: for i in L:
LRtn.append(int(i*times)) LRtn.append(int(i * times))
return LRtn return LRtn
   
   
def trim(L): def trim(L):
"Trim the blank spots at the start and end" "Trim the blank spots at the start and end"
   
def _trim(L): def _trim(L):
snd_started = False snd_started = False
LRtn = array('h') LRtn = array('h')
   
for i in L: for i in L:
if not snd_started and abs(i)>THRESHOLD: if not snd_started and abs(i) > THRESHOLD:
snd_started = True snd_started = True
LRtn.append(i) LRtn.append(i)
   
elif snd_started: elif snd_started:
LRtn.append(i) LRtn.append(i)
return LRtn return LRtn
   
# Trim to the left # Trim to the left
L = _trim(L) L = _trim(L)
   
# Trim to the right # Trim to the right
L.reverse() L.reverse()
L = _trim(L) L = _trim(L)
L.reverse() L.reverse()
return L return L
   
   
def add_silence(L, seconds): def add_silence(L, seconds):
"Add silence to the start and end of `L` of length `seconds` (float)" "Add silence to the start and end of `L` of length `seconds` (float)"
LRtn = array('h', [0 for i in xrange(int(seconds*RATE))]) LRtn = array('h', [0 for i in xrange(int(seconds * RATE))])
LRtn.extend(L) LRtn.extend(L)
LRtn.extend([0 for i in xrange(int(seconds*RATE))]) LRtn.extend([0 for i in xrange(int(seconds * RATE))])
return LRtn return LRtn
   
   
def record(): def record():
""" """
Record a word or words from the microphone and Record a word or words from the microphone and
return the data as an array of signed shorts. return the data as an array of signed shorts.
   
Normalizes the audio, trims silence from the Normalizes the audio, trims silence from the
start and end, and pads with 0.5 seconds of start and end, and pads with 0.5 seconds of
blank sound to make sure VLC et al can play blank sound to make sure VLC et al can play
it without getting chopped off. it without getting chopped off.
""" """
p = pyaudio.PyAudio() p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=1, rate=RATE, stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
input=True, output=True, input=True,
frames_per_buffer=CHUNK_SIZE) frames_per_buffer=CHUNK_SIZE)
   
num_silent = 0 num_silent = 0
snd_started = False snd_started = False
   
LRtn = array('h') LRtn = array('h')
   
while 1: while 1:
data = stream.read(CHUNK_SIZE) try:
L = unpack('<' + ('h'*(len(data)/2)), data) # little endian, signed short data = stream.read(CHUNK_SIZE)
  except IOError as ex:
  if ex[1] != pyaudio.paInputOverflowed:
  raise
  data = '\x00' * CHUNK_SIZE
  L = unpack('<' + ('h' * (len(data) / 2)), data) # little endian, signed short
L = array('h', L) L = array('h', L)
LRtn.extend(L)  
   
silent = is_silent(L) silent = is_silent(L)
#print silent, num_silent, L[:10] #print silent, num_silent, L[:10]
   
if silent and snd_started: if silent and snd_started:
num_silent += 1 num_silent += 1
print num_silent #print num_silent
elif not silent and not snd_started: elif not silent and not snd_started:
dispatcher.send( signal='SND_STARTED') dispatcher.send(signal='SND_STARTED')
snd_started = True snd_started = True
print snd_started print snd_started
  if snd_started and not silent:
  num_silent = 0
  if snd_started:
  LRtn.extend(L)
if snd_started and num_silent > MAX_SILENT: if snd_started and num_silent > MAX_SILENT:
break break
   
sample_width = p.get_sample_size(FORMAT) sample_width = p.get_sample_size(FORMAT)
stream.stop_stream() stream.stop_stream()
stream.close() stream.close()
p.terminate() p.terminate()
   
LRtn = normalize(LRtn) LRtn = normalize(LRtn)
LRtn = trim(LRtn) LRtn = trim(LRtn)
LRtn = add_silence(LRtn, 0.5) LRtn = add_silence(LRtn, 0.5)
return sample_width, LRtn return sample_width, LRtn
   
   
def record_to_file(path): def record_to_file(path):
"Records from the microphone and outputs the resulting data to `path`" "Records from the microphone and outputs the resulting data to `path`"
sample_width, data = record() sample_width, data = record()
data = pack('<' + ('h'*len(data)), *data) data = pack('<' + ('h' * len(data)), *data)
   
wf = wave.open(path, 'wb') wf = wave.open(path, 'wb')
wf.setnchannels(1) wf.setnchannels(CHANNELS)
wf.setsampwidth(sample_width) wf.setsampwidth(sample_width)
wf.setframerate(RATE) wf.setframerate(RATE)
wf.writeframes(data) wf.writeframes(data)
wf.close() wf.close()
print("done - result written to "+path) print("done - result written to " + path)
  del data
   
   
   
if __name__ == '__main__': if __name__ == '__main__':
filename = 'demo.wav' filename = 'demo.wav'
record_to_file(filename) record_to_file(filename)
print("done - result written to "+filename) print("done - result written to " + filename)
   
file:b/test.py (new)
  """PyAudio example: Record a few seconds of audio and save to a WAVE file."""
 
  import pyaudio
  import wave
 
  CHUNK = 1024
  FORMAT = pyaudio.paInt16
  CHANNELS = 2
  RATE = 44100
  RECORD_SECONDS = 5
  WAVE_OUTPUT_FILENAME = "output.wav"
 
  p = pyaudio.PyAudio()
  device_idx = 0;
  for i in range (0, p.get_device_count()):
  print(p.get_device_info_by_index(i))
  if p.get_device_info_by_index(i)['name'] == 'Built-in Input':
  device_idx = i
  print i
  stream = p.open(format=FORMAT,
  channels=CHANNELS,
  rate=RATE,
  input=True,
  input_device_index=device_idx,
  frames_per_buffer=CHUNK)
 
  print("* recording")
 
  frames = []
 
  for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  data = stream.read(CHUNK)
  frames.append(data)
 
  print("* done recording")
 
  stream.stop_stream()
  stream.close()
  p.terminate()
 
  wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  wf.writeframes(b''.join(frames))
  wf.close()
 
file:b/test2.py (new)
  from os.path import exists
  from array import array
  from struct import unpack, pack
 
  import pyaudio
  import wave
 
  THRESHOLD = 500
  CHUNK_SIZE = 1024
  FORMAT = pyaudio.paInt16
  RATE = 44100
 
  def is_silent(L):
  "Returns `True` if below the 'silent' threshold"
  return max(L) < THRESHOLD
 
 
  def normalize(L):
  "Average the volume out"
  MAXIMUM = 16384
  times = float(MAXIMUM) / max(abs(i) for i in L)
 
  LRtn = array('h')
  for i in L:
  LRtn.append(int(i * times))
  return LRtn
 
 
  def trim(L):
  "Trim the blank spots at the start and end"
 
  def _trim(L):
  snd_started = False
  LRtn = array('h')
 
  for i in L:
  if not snd_started and abs(i) > THRESHOLD:
  snd_started = True
  LRtn.append(i)
 
  elif snd_started:
  LRtn.append(i)
  return LRtn
 
  # Trim to the left
  L = _trim(L)
 
  # Trim to the right
  L.reverse()
  L = _trim(L)
  L.reverse()
  return L
 
 
  def add_silence(L, seconds):
  "Add silence to the start and end of `L` of length `seconds` (float)"
  LRtn = array('h', [0 for i in xrange(int(seconds * RATE))])
  LRtn.extend(L)
  LRtn.extend([0 for i in xrange(int(seconds * RATE))])
  return LRtn
 
 
  def record():
  """
  Record a word or words from the microphone and
  return the data as an array of signed shorts.
 
  Normalizes the audio, trims silence from the
  start and end, and pads with 0.5 seconds of
  blank sound to make sure VLC et al can play
  it without getting chopped off.
  """
  p = pyaudio.PyAudio()
  stream = p.open(format=FORMAT, channels=2, rate=RATE,
  input=True,
  frames_per_buffer=CHUNK_SIZE)
 
  num_silent = 0
  snd_started = False
 
  LRtn = array('h')
 
  while 1:
  data = stream.read(CHUNK_SIZE)
  L = unpack('<' + ('h' * (len(data) / 2)), data) # little endian, signed short
  L = array('h', L)
  LRtn.extend(L)
 
  silent = is_silent(L)
  #print silent, num_silent, L[:10]
 
  if silent and snd_started:
  num_silent += 1
  elif not silent and not snd_started:
  snd_started = True
 
  if snd_started and num_silent > 30:
  break
 
  sample_width = p.get_sample_size(FORMAT)
  stream.stop_stream()
  stream.close()
  p.terminate()
 
  LRtn = normalize(LRtn)
  LRtn = trim(LRtn)
  LRtn = add_silence(LRtn, 0.5)
  return sample_width, LRtn
 
 
  def record_to_file(path):
  "Records from the microphone and outputs the resulting data to `path`"
  sample_width, data = record()
  data = pack('<' + ('h' * len(data)), *data)
 
  wf = wave.open(path, 'wb')
  wf.setnchannels(2)
  wf.setsampwidth(sample_width)
  wf.setframerate(RATE)
  wf.writeframes(data)
  wf.close()
 
  if __name__ == '__main__':
  print("please speak a word into the microphone")
  record_to_file('demo.wav')
  print("done - result written to demo.wav")
 
file:b/tgid.csv (new)
  tgid,subfleet,alpha_tag,mode,description,service_tag,category 10000,,GL 1,D,GL 1,Fire-Tac,Rural Fire Service RFS 10001,,GL 2,D,GL 2,Fire-Tac,Rural Fire Service RFS 10002,,GL 3,D,GL 3,Fire-Tac,Rural Fire Service RFS 10003,,GL 4,D,GL 4,Fire-Tac,Rural Fire Service RFS 10004,,GL 5,D,GL 5,Fire-Tac,Rural Fire Service RFS 10005,,GL 6,D,GL 6,Fire-Tac,Rural Fire Service RFS 10006,,GL 7,D,GL 7,Fire-Tac,Rural Fire Service RFS 10007,,GL 8,D,GL 8,Fire-Tac,Rural Fire Service RFS 10008,,GL 9,D,GL 9,Fire-Tac,Rural Fire Service RFS 10009,,GL 10,D,GL 10,Fire-Tac,Rural Fire Service RFS 10010,,ESO 1,D,ESO 1,Fire-Tac,Rural Fire Service RFS 10011,,ESO 2,D,ESO 2,Fire-Tac,Rural Fire Service RFS 10012,,ESO 3,D,ESO 3,Fire-Tac,Rural Fire Service RFS 10013,,ESO 4,D,ESO 4,Fire-Tac,Rural Fire Service RFS 10014,,ESO 5,D,ESO 5,Fire-Tac,Rural Fire Service RFS 10015,,ESO 6,D,ESO 6,Fire-Tac,Rural Fire Service RFS 10016,,ESO 7,D,ESO 7,Fire-Tac,Rural Fire Service RFS 10017,,ESO 8,D,ESO 8,Fire-Tac,Rural Fire Service RFS 10018,,ESO 9,D,ESO 9,Fire-Tac,Rural Fire Service RFS 10019,,ESO 10,D,ESO 10,Fire-Tac,Rural Fire Service RFS 10020,,ESO 11,D,ESO 11,Fire-Tac,Rural Fire Service RFS 10021,,ESO 12,D,ESO 12,Fire-Tac,Rural Fire Service RFS 10022,,ESO 13,D,ESO 13,Fire-Tac,Rural Fire Service RFS 10023,,ESO 14,D,ESO 14,Fire-Tac,Rural Fire Service RFS 10024,,ESO 15,D,ESO 15,Fire-Tac,Rural Fire Service RFS 10025,,ESO 16,D,ESO 16,Fire-Tac,Rural Fire Service RFS 10026,,ESO 17,D,ESO 17,Fire-Tac,Rural Fire Service RFS 10027,,ESO 18,D,ESO 18,Fire-Tac,Rural Fire Service RFS 10028,,ESO 19,D,ESO 19,Fire-Tac,Rural Fire Service RFS 10029,,ESO 20,D,ESO 20,Fire-Tac,Rural Fire Service RFS 10030,,AVIATN1,D,RFS GD01 AVIATN1,Fire-Tac,Rural Fire Service RFS 10031,,AVIATN2,D,RFS GD02 AVIATN2,Fire-Tac,Rural Fire Service RFS 10032,,AVIATN3,D,RFS GD03 AVIATN3,Fire-Tac,Rural Fire Service RFS 10033,,AVIATN4,D,RFS GD04 AVIATN4,Fire-Tac,Rural Fire Service RFS 10034,,AVIATN5,D,RFS GD05 AVIATN5,Fire-Tac,Rural Fire Service RFS 10035,,AVIATN6,D,RFS GD06 AVIATN6,Fire-Tac,Rural Fire Service RFS 10036,,BLKM HL,D,RFS GD08 BLKM HL,Fire-Tac,Rural Fire Service RFS 10037,,BL MTNS,D,RFS GD10 BL MTNS,Fire-Tac,Rural Fire Service RFS 10038,,CISS,D,RFS GD14 CISS,Fire-Tac,Rural Fire Service RFS 10039,,COM ED1,D,RFS GD16 COM ED1,Fire-Tac,Rural Fire Service RFS 10040,,COM ED2,D,RFS GD17 COM ED2,Fire-Tac,Rural Fire Service RFS 10041,,COM ED3,D,RFS GD18 COM ED3,Fire-Tac,Rural Fire Service RFS 10042,,CMBRLND,D,RFS GD20 CMBRLND,Fire-Tac,Rural Fire Service RFS 10043,,EAST OP,D,RFS GD21 EAST OP,Fire-Tac,Rural Fire Service RFS 10044,,EXEC OP,D,RFS GD22 EXEC OP,Fire-Tac,Rural Fire Service RFS 10045,,FIU 1,D,RFS GD26 FIU 1,Fire-Tac,Rural Fire Service RFS 10046,,FIU 2,D,RFS GD27 FIU 2,Fire-Tac,Rural Fire Service RFS 10047,,GOSFORD,D,RFS GD28 GOSFORD,Fire-Tac,Rural Fire Service RFS 10048,,HAWKESB,D,RFS GD29 HAWKESB,Fire-Tac,Rural Fire Service RFS 10049,,HORNSBY,D,RFS GD30 HORNSBY,Fire-Tac,Rural Fire Service RFS 10050,,LDS 1,D,RFS GD38 LDS 1,Fire-Tac,Rural Fire Service RFS 10051,,LDS 2,D,RFS GD39 LDS 2,Fire-Tac,Rural Fire Service RFS 10052,,MCARTHR,D,RFS GD42 MCARTHR,Fire-Tac,Rural Fire Service RFS 10053,,MEDIA 1,D,RFS GD44 MEDIA 1,Fire-Tac,Rural Fire Service RFS 10054,,MEDIA 2,D,RFS GD45 MEDIA 2,Fire-Tac,Rural Fire Service RFS 10055,,OP COM1,D,RFS GD58 OP COM1,Fire-Tac,Rural Fire Service RFS 10056,,OP COM2,D,RFS GD59 OP COM2,Fire-Tac,Rural Fire Service RFS 10057,,OP COM3,D,RFS GD60 OP COM3,Fire-Tac,Rural Fire Service RFS 10058,,OPS1,D,RFS GD62 OPS1,Fire-Tac,Rural Fire Service RFS 10059,,OPS2,D,RFS GD63 OPS2,Fire-Tac,Rural Fire Service RFS 10060,,OPS3,D,RFS GD64 OPS3,Fire-Tac,Rural Fire Service RFS 10061,,OPS4,D,RFS GD65 OPS4,Fire-Tac,Rural Fire Service RFS 10062,,OPS5,D,RFS GD66 OPS5,Fire-Tac,Rural Fire Service RFS 10063,,OPS6,D,RFS GD67 OPS6,Fire-Tac,Rural Fire Service RFS 10064,,OPS7,D,RFS GD68 OPS7,Fire-Tac,Rural Fire Service RFS 10065,,OPS8,D,RFS GD69 OPS8,Fire-Tac,Rural Fire Service RFS 10066,,OPS9,D,RFS GD70 OPS9,Fire-Tac,Rural Fire Service RFS 10067,,OPS10,D,RFS GD71 OPS10,Fire-Tac,Rural Fire Service RFS 10068,,OPS11,D,RFS GD72 OPS11,Fire-Tac,Rural Fire Service RFS 10069,,OPS12,D,RFS GD73 OPS12,Fire-Tac,Rural Fire Service RFS 10070,,OPS13,D,RFS GD74 OPS13,Fire-Tac,Rural Fire Service RFS 10071,,OPS14,D,RFS GD75 OPS14,Fire-Tac,Rural Fire Service RFS 10072,,OPS15,D,RFS GD76 OPS15,Fire-Tac,Rural Fire Service RFS 10073,,RGN EST,D,RFS GD77 RGN EST,Fire-Tac,Rural Fire Service RFS 10074,,STATEOP,D,RFS GD87 STATEOP,Fire-Tac,Rural Fire Service RFS 10075,,STHRLND,D,RFS GD88 STHRLND,Fire-Tac,Rural Fire Service RFS 10076,,WARINGH,D,RFS GD91 WARINGH,Fire-Tac,Rural Fire Service RFS 10077,,WOLONDL,D,RFS GD94 WOLONDL,Fire-Tac,Rural Fire Service RFS 10101,,SYD 1,D,SYD 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10102,,SYD 2,D,SYD 2,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10103,,SYD 3,D,SYD 3,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10104,,SYD 4,D,SYD 4,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10105,,SYD 6,D,SYD 6,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10106,,SYD 7,D,SYD 7,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10107,,SYD 8,D,SYD 8,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10108,,SYD 9,D,SYD 9,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10109,,SYD 10,D,SYD 10,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10110,,SYD 11,D,SYD 11,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10111,,SYD 12,D,SYD 12,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10112,,New 1,D,New 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10113,,New 2,D,New 2,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10114,,Gos 1,D,Gos 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10115,,Gos 2,D,Gos 2,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10117,,HAST 1,D,HAST 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10118,,SUMLND1,D,SUMLND1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10119,,PEEL 1,D,PEEL 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10120,,WOLL 1,D,WOLL 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10121,,WOLL 2,D,WOLL 2,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10122,,SHIGH1,D,SHIGH1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10123,,GOULB1,D,GOULB1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10124,,MONARO1,D,MONARO1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10125,,SCST 1,D,SCST 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10126,,ACTNSW,D,ACTNSW,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10127,,GRIFFTH,D,GRIFFTH,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10128,,MURRAY1,D,MURRAY1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10129,,CWEST1,D,CWEST1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10130,,BLU MT1,D,BLU MT1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10131,,BLU MT2,D,BLU MT2,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10132,,BOGAN 1,D,BOGAN 1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10133,,LACHLN1,D,LACHLN1,Fire Dispatch,Fire and Rescue New South Wales FRNSW 10134,,Ops 1,D,Special Operations 1,Fire-Tac,Fire and Rescue New South Wales FRNSW 10135,,Ops 2,D,Special Operations 2,Fire-Tac,Fire and Rescue New South Wales FRNSW 10136,,Ops 3,D,Special Operations 3,Fire-Tac,Fire and Rescue New South Wales FRNSW 10137,,Ops 4,D,Special Operations 4,Fire-Tac,Fire and Rescue New South Wales FRNSW 10138,,Ops 5,D,Special Operations 5,Fire-Tac,Fire and Rescue New South Wales FRNSW 10139,,Ops 6,D,Special Operations 6,Fire-Tac,Fire and Rescue New South Wales FRNSW 10144,,Ops 11,D,Special Operations 11,Fire-Tac,Fire and Rescue New South Wales FRNSW 10145,,Ops 12,D,Special Operations 12,Fire-Tac,Fire and Rescue New South Wales FRNSW 10146,,Ops 13,D,Special Operations 13,Fire-Tac,Fire and Rescue New South Wales FRNSW 10147,,Ops 14,D,Special Operations 14,Fire-Tac,Fire and Rescue New South Wales FRNSW 10148,,Ops 15,D,Special Operations 15,Fire-Tac,Fire and Rescue New South Wales FRNSW 10149,,Ops 16,D,Special Operations 16,Fire-Tac,Fire and Rescue New South Wales FRNSW 10154,,Comms,D,Communications,Fire-Talk,Fire and Rescue New South Wales FRNSW 10155,,Property,D,Property,Fire-Talk,Fire and Rescue New South Wales FRNSW 10156,,Fleet,D,Fleet,Fire-Talk,Fire and Rescue New South Wales FRNSW 10157,,Admin,D,Administration,Fire-Talk,Fire and Rescue New South Wales FRNSW 10158,,Mech,D,Mechanics,Fire-Talk,Fire and Rescue New South Wales FRNSW 10159,,Eng,D,Engineers,Fire-Talk,Fire and Rescue New South Wales FRNSW 10160,,Op Comms,D,Operation Communications,Fire-Talk,Fire and Rescue New South Wales FRNSW 10161,,Hazmat,D,BAHazmat,Fire-Talk,Fire and Rescue New South Wales FRNSW 10162,,Bushfire,D,Bushfire,Fire-Talk,Fire and Rescue New South Wales FRNSW 10163,,FIU,D,Fire Investigation Unit,Fire-Talk,Fire and Rescue New South Wales FRNSW 10164,,Fire Prev,D,Fire Prevention,Fire-Talk,Fire and Rescue New South Wales FRNSW 10165,,Train,D,Training,Fire-Talk,Fire and Rescue New South Wales FRNSW 10166,,Rescue,D,Rescue,Fire-Talk,Fire and Rescue New South Wales FRNSW 10201,,SNTAC1,D,SES 307SNTAC1,EMS-Tac,State Emergency Service SES 10202,,SNTAC2,D,SES 308SNTAC2,EMS-Tac,State Emergency Service SES 10203,,SNTAC3,D,SES 309SNTAC3,EMS-Tac,State Emergency Service SES 10204,,SNTAC4,D,SES 310SNTAC4,EMS-Tac,State Emergency Service SES 10205,,SNTAC5,D,SES 311SNTAC5,EMS-Tac,State Emergency Service SES 10206,,SNTAC6,D,SES 312SNTAC6,EMS-Tac,State Emergency Service SES 10207,,SNSTRAT,D,SES 314SNSTRAT,EMS-Tac,State Emergency Service SES 10208,,SSTAC1,D,SES 316SSTAC1,EMS-Tac,State Emergency Service SES 10209,,SSTAC2,D,SES 317SSTAC2,EMS-Tac,State Emergency Service SES 10210,,SSTAC3,D,SES 318SSTAC3,EMS-Tac,State Emergency Service SES 10211,,SSTAC4,D,SES 319SSTAC4,EMS-Tac,State Emergency Service SES 10212,,SSTAC5,D,SES 320SSTAC5,EMS-Tac,State Emergency Service SES 10213,,SSTAC6,D,SES 321SSTAC6,EMS-Tac,State Emergency Service SES 10214,,SSSTRAT,D,SES 323SSSTRAT,EMS-Tac,State Emergency Service SES 10215,,SWTAC1,D,SES 324SWTAC1,EMS-Tac,State Emergency Service SES 10216,,SWTAC2,D,SES 325SWTAC2,EMS-Tac,State Emergency Service SES 10217,,SWTAC3,D,SES 326SWTAC3,EMS-Tac,State Emergency Service SES 10218,,SWTAC4,D,SES 327SWTAC4,EMS-Tac,State Emergency Service SES 10219,,SWTAC5,D,SES 328SWTAC5,EMS-Tac,State Emergency Service SES 10220,,SWTAC6,D,SES 329SWTAC6,EMS-Tac,State Emergency Service SES 10221,,SWSTRAT,D,SES 331SWSTRAT,EMS-Tac,State Emergency Service SES 10222,,SWRCR,D,SES 332SWRCR,EMS-Tac,State Emergency Service SES 10223,,HNCNT1,D,SES 340HNCNT1,EMS-Tac,State Emergency Service SES 10224,,HNCNT2,D,SES 341HNCNT2,EMS-Tac,State Emergency Service SES 10225,,HNCNT3,D,SES 342HNCNT3,EMS-Tac,State Emergency Service SES 10226,,HNCNT4,D,SES 343HNCNT4,EMS-Tac,State Emergency Service SES 10227,,HNCNT5,D,SES 344HNCNT5,EMS-Tac,State Emergency Service SES 10228,,TRNSPRT,D,SES 347TRNSPRT,EMS-Tac,State Emergency Service SES 10229,,COORD,D,SES 348COORD,EMS-Tac,State Emergency Service SES 10230,,TSKFCE1,D,SES 349TSKFCE1,EMS-Tac,State Emergency Service SES 10231,,TSKFCE2,D,SES 350TSKFCE2,EMS-Tac,State Emergency Service SES 10232,,TSKFCE3,D,SES 351TSKFCE3,EMS-Tac,State Emergency Service SES 10233,,TSKFCE4,D,SES 352TSKFCE4,EMS-Tac,State Emergency Service SES 10234,,SOPS1,D,SES 353SOPS1,EMS-Tac,State Emergency Service SES 10235,,SOPS2,D,SES 354SOPS2,EMS-Tac,State Emergency Service SES 10236,,SOPS3,D,SES 355SOPS3,EMS-Tac,State Emergency Service SES 10237,,SOPS4,D,SES 356SOPS4,EMS-Tac,State Emergency Service SES 10238,,SOPS5,D,SES 357SOPS5,EMS-Tac,State Emergency Service SES 10239,,SOPS6,D,SES 358SOPS6,EMS-Tac,State Emergency Service SES 10240,,SOPS7,D,SES 359SOPS7,EMS-Tac,State Emergency Service SES 10241,,SOPS8,D,SES 360SOPS8,EMS-Tac,State Emergency Service SES 10242,,SOPS9,D,SES 361SOPS9,EMS-Tac,State Emergency Service SES 10243,,SOPS10,D,SES 362SOPS10,EMS-Tac,State Emergency Service SES 10244,,SOPS11,D,SES 363SOPS11,EMS-Tac,State Emergency Service SES 10245,,SOPS12,D,SES 364SOPS12,EMS-Tac,State Emergency Service SES 10246,,COMMS1,D,SES 367COMMS1,EMS-Tac,State Emergency Service SES 10247,,DOCSLO,D,SES 345DOCSLO,EMS-Tac,State Emergency Service SES 10248,,DOCSST,D,SES 346DOCSST,EMS-Tac,State Emergency Service SES 10301,,MRU,D,Administration 1 State Ops MRU,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10302,,Admin 2,D,Administration 2,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10303,,Admin 3,D,Administration 3,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10304,,Admin 4,D,Administration 4,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10305,,Admin 5,D,Administration 5,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10306,,NETS,D,Administration 6 NETS,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10307,,7 PUB HLTH,,Administration Public Health Service Liaison,,Ambulance Service of New South Wales ASNSW 10308,,8 GWEST AH,,Administration Greater West AHS,,Ambulance Service of New South Wales ASNSW 10309,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10310,,10 NSCC AH,,Administration North SydneyCentral Coast AHS,,Ambulance Service of New South Wales ASNSW 10311,,11 SW AH,,Administration Sydney West AHS,,Ambulance Service of New South Wales ASNSW 10312,,12 SSW AH,,Administration Sydney South West AHS,,Ambulance Service of New South Wales ASNSW 10313,,13 SESI AH,,Administration South Eastern SydneyIllawarra AHS,,Ambulance Service of New South Wales ASNSW 10314,,14 AH INCDT,,Administration AHS Incident 1,,Ambulance Service of New South Wales ASNSW 10315,,15 AH INCDT,,Administration AHS Incident 2,,Ambulance Service of New South Wales ASNSW 10316,,16 AH INCDT,,Administration AHS Incident 3,,Ambulance Service of New South Wales ASNSW 10317,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10318,,18 MEDI 2,,Administration Medical 2,,Ambulance Service of New South Wales ASNSW 10319,,PTO Ops 1,D,Patient Transport,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10320,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10321,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10322,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10323,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10324,,PTO OPS 6,,Patient Transport Operations 6,,Ambulance Service of New South Wales ASNSW 10325,,Syd North,D,Sydney North,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10326,,Syd South,D,Sydney South,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10327,,Syd East,D,Sydney East,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10328,,Syd West,D,Sydney West,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10329,,Syd SW,D,Sydney SW,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10330,,Syd Outer,D,Sydney Outer SW,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10331,,Syd Rural,D,Sydney Rural West Outer WestBlue Mts,EMS Dispatch,Ambulance Service of New South Wales ASNSW 10332,,10 ECP 1,,Sydney Extended Care Paramedic 1,,Ambulance Service of New South Wales ASNSW 10333,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10334,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10335,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10336,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10337,,15 INCDNT 4,,Sydney Incident 4,,Ambulance Service of New South Wales ASNSW 10338,,16 INCDNT 5,,Sydney Incident 5,,Ambulance Service of New South Wales ASNSW 10339,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10340,,18 INCDNT 7,,Sydney Incident 7,,Ambulance Service of New South Wales ASNSW 10341,,Sports,D,Sports,EMS-Talk,Ambulance Service of New South Wales ASNSW 10342,,Workshop,D,Workshops,EMS-Talk,Ambulance Service of New South Wales ASNSW 10343,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10344,,Sth Hosps,D,South Hospitals,Hospital,Ambulance Service of New South Wales ASNSW 10345,,ASNSW,D,ASNSW,EMS-Talk,Ambulance Service of New South Wales ASNSW 10346,,West Hosp,D,West Hospitals,Hospital,Ambulance Service of New South Wales ASNSW 10347,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10348,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10349,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10350,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10351,,FAULT REPORT,,FAULT REPORT,,Ambulance Service of New South Wales ASNSW 10352,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10353,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10354,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10355,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10356,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10357,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 10358,,IT SUPPORT,,IT SUPPORT,,Ambulance Service of New South Wales ASNSW 10381,,Net 1,D,Hatzolah Net 1,EMS Dispatch,Hatzolah Ambulance Service 10382,,Net 2,D,Hatzolah Net 2,EMS Dispatch,Hatzolah Ambulance Service 10383,,Net 3,D,Hatzolah Net 3,EMS Dispatch,Hatzolah Ambulance Service 10384,,Net 4,D,Hatzolah Net 4,EMS Dispatch,Hatzolah Ambulance Service 10385,,Net 5,D,Hatzolah Net 5,EMS Dispatch,Hatzolah Ambulance Service 10386,,Net 6,D,Hatzolah Net 6,EMS Dispatch,Hatzolah Ambulance Service 10387,,Net 7,D,Hatzolah Net 7,EMS Dispatch,Hatzolah Ambulance Service 10388,,Net 8,D,Hatzolah Net 8,EMS Dispatch,Hatzolah Ambulance Service 10389,,Net 9,D,Hatzolah Net 9,EMS Dispatch,Hatzolah Ambulance Service 10390,,Net 10,D,Hatzolah Net 10,EMS Dispatch,Hatzolah Ambulance Service 10402,,Transport,D,Corrective Services Transports,Corrections,Corrective Services 10403,,VG visits,D,Corrective Services VG visits,Corrections,Corrective Services 10404,,VK visits,D,Corrective Services VK visits,Corrections,Corrective Services 10405,,NC visits,D,Corrective Services NC visits,Corrections,Corrective Services 10406,,WG visits,D,Corrective Services WG visits,Corrections,Corrective Services 10407,,unk,D,Corrective Services,Corrections,Corrective Services 10408,,unk,D,Corrective Services,Corrections,Corrective Services 10409,,Ext Escorts,D,Corrective Service External escorts,Corrections,Corrective Services 10411,,unk,D,Corrective Services ,Corrections,Corrective Services 10413,,unk,D,Corrective Services,Corrections,Corrective Services 10414,,Secure Unit,D,Corrective Services Secure Unit,Corrections,Corrective Services 10415,,unk,D,Corrective Services,Corrections,Corrective Services 10419,,unk,D,Corrective Services,Corrections,Corrective Services 10421,,Projects,D,Corrective Services projects,Corrections,Corrective Services 10422,,unk,D,Corrective Services,Corrections,Corrective Services 10423,,unk,D,Corrective Services,Corrections,Corrective Services 10427,,unk,D,Corrective Services ,Corrections,Corrective Services 10428,,unk,D,Corrective Services ,Corrections,Corrective Services 10429,,unk,D,Corrective Services ,Corrections,Corrective Services 10430,,unk,D,Corrective Services ,Corrections,Corrective Services 10451,,unk,D,Corrective Services ,Corrections,Corrective Services 10481,,unk,D,Corrective Services ,Corrections,Corrective Services 10502,,unk,D,Ausgrid ,Utilities,AusGrid 10503,,GH UG,D,AusGrid Gore Hill Underground,Utilities,AusGrid 10504,,GH OH,D,AusGrid Gore Hill Overhead,Utilities,AusGrid 10505,,Horn OH,D,AusGrid Hornsby Overhead,Utilities,AusGrid 10506,,Horn UG,D,AusGrid Hornsby Underground,Utilities,AusGrid 10507,,Nth Subs,D,AusGrid North Substations,Utilities,AusGrid 10508,,Nth Prot,D,AusGrid North Protection,Utilities,AusGrid 10509,,Nth DistOps,D,AusGrid North District Operators,Utilities,AusGrid 10510,,GH Street,D,AusGrid Gore Hill Street Lighting,Utilities,AusGrid 10511,,Nth Op,D,AusGrid North Operator,Utilities,AusGrid 10512,,Util 1,D,AusGrid Utility 1,Utilities,AusGrid 10513,,Nth EMSO 1,D,AusGrid North EMSO Data 1,Utilities,AusGrid 10514,,DY OH 1,D,AusGrid Dee Why Overhead 1,Utilities,AusGrid 10515,,DY OH 2,D,AusGrid Dee Why Overhead 2,Utilities,AusGrid 10516,,DY Op,D,AusGrid Dee Why Operator,Utilities,AusGrid 10517,,DY Subs,D,AusGrid Dee Why Substations,Utilities,AusGrid 10518,,Projects,D,AusGrid Projects and Contracts,Utilities,AusGrid 10519,,East Op,D,AusGrid East Operator,Utilities,AusGrid 10520,,Util 1,D,AusGrid Utility 1,Utilities,AusGrid 10521,,Util 2,D,AusGrid Utility 2,Utilities,AusGrid 10522,,East UG,D,AusGrid East Underground,Utilities,AusGrid 10523,,East OH,D,AusGrid East Overhead,Utilities,AusGrid 10524,,East Subs,D,AusGrid East Substations,Utilities,AusGrid 10525,,Asset Acc,D,AusGrid Asset Access,Utilities,AusGrid 10526,,East DistOps,D,AusGrid East District Operators,Utilities,AusGrid 10527,,East Prot,D,AusGrid East Protection,Utilities,AusGrid 10528,,CBD HV UG,D,AusGrid CBD High Voltage Underground,Utilities,AusGrid 10529,,PINC Ctrl,D,AusGrid PINC Network Operations Controller,Utilities,AusGrid 10530,,SO TPDR 1,D,AusGrid SO Transponder 1,Utilities,AusGrid 10531,,SO TODR 2,D,AusGrid SO Transponder 2,Utilities,AusGrid 10532,,Rad CMDR,D,AusGrid Radio Commander,Utilities,AusGrid 10533,,unk,D,Ausgrid ,Utilities,AusGrid 10534,,unk,D,Ausgrid ,Utilities,AusGrid 10535,,Sth OP,D,AusGrid South Operator,Utilities,AusGrid 10536,,IW OH,D,AusGrid Inner West Overhead,Utilities,AusGrid 10537,,HB UG,D,AusGrid Homebush Underground,Utilities,AusGrid 10538,,SW Train,D,AusGrid Silverwater Training Centre,Utilities,AusGrid 10539,,BT OH,D,AusGrid Bankstown Overhead,Utilities,AusGrid 10540,,BT Dist Op,D,AusGrid Bankstown District Operators,Utilities,AusGrid 10541,,Sth Dist Op,D,AusGrid South District Operators,Utilities,AusGrid 10542,,BT Op,D,AusGrid Bankstown Operator,Utilities,AusGrid 10543,,unk,D,Ausgrid ,Utilities,AusGrid 10544,,OAT OH,D,AusGrid Oatley Overhead,Utilities,AusGrid 10545,,Nth EMSO 1,D,AusGrid South EMSO Data 1,Utilities,AusGrid 10546,,unk,D,Ausgrid ,Utilities,AusGrid 10547,,unk,D,Ausgrid ,Utilities,AusGrid 10548,,Trans 1,D,AusGrid Transmission 1,Utilities,AusGrid 10549,,Trans 2,D,AusGrid Transmission 2,Utilities,AusGrid 10550,,unk,D,Ausgrid ,Utilities,AusGrid 10551,,unk,D,Ausgrid ,Utilities,AusGrid 10556,,Nth Op,D,AusGrid North Operator,Utilities,AusGrid 10557,,Sth Op,D,AusGrid South Operator,Utilities,AusGrid 10558,,East Op,D,AusGrid East Operator,Utilities,AusGrid 10559,,BT Op,D,AusGrid Bankstown Operator,Utilities,AusGrid 10560,,DY Op,D,AusGrid Dee Why Operator,Utilities,AusGrid 10561,,TeleCtrl,D,AusGrid TelecontrolFacilitiesDriver Training,Utilities,AusGrid 10562,,CIPIMS,D,AusGrid CIPIMS ControlDuty Managers,Utilities,AusGrid 10563,,INC Ops,D,AusGrid Incident Operations,Utilities,AusGrid 10564,,Subs Meter,D,AusGrid TCA Substations Metering,Utilities,AusGrid 10565,,Net Test 1,D,AusGrid TCA Network Test 1,Utilities,AusGrid 10566,,Net Test 2,D,AusGrid TCA Network Test 2,Utilities,AusGrid 10567,,Net Test 3,D,AusGrid TCA Network Test 3,Utilities,AusGrid 10568,,Net Test 4,D,AusGrid TCA Network Test 4,Utilities,AusGrid 10569,,Net Test 5,D,AusGrid TCA Network Test 5,Utilities,AusGrid 10570,,CASS Data1,D,AusGrid CASS Data 1,Utilities,AusGrid 10601,,Control 1,D,Integral Energy Control,Utilities,Integral Energy 10602,,Control 2,D,Integral Energy Control,Utilities,Integral Energy 10603,,Control 3,D,Integral Energy Control,Utilities,Integral Energy 10604,,Control 4,D,Integral Energy Control,Utilities,Integral Energy 10605,,Control 5,D,Integral Energy Control,Utilities,Integral Energy 10606,,Control 6,D,Integral Energy Control,Utilities,Integral Energy 10607,,Control 7,D,Integral Energy Control,Utilities,Integral Energy 10608,,Control 8,D,Integral Energy Control,Utilities,Integral Energy 10609,,Control 9,D,Integral Energy Control,Utilities,Integral Energy 10610,,Control 10,D,Integral Energy Consion Control,Utilities,Integral Energy 10611,,unk,D,Integral Energy ,Utilities,Integral Energy 10612,,unk,D,Integral Energy ,Utilities,Integral Energy 10613,,unk,D,Integral Energy ,Utilities,Integral Energy 10614,,unk,D,Integral Energy ,Utilities,Integral Energy 10615,,unk,D,Integral Energy ,Utilities,Integral Energy 10616,,unk,D,Integral Energy ,Utilities,Integral Energy 10617,,unk,D,Integral Energy ,Utilities,Integral Energy 10618,,unk,D,Integral Energy ,Utilities,Integral Energy 10619,,unk,D,Integral Energy ,Utilities,Integral Energy 10620,,unk,D,Integral Energy ,Utilities,Integral Energy 10621,,unk,D,Integral Energy ,Utilities,Integral Energy 10622,,Katoomba,D,Integral Energy Katoomba,Utilities,Integral Energy 10623,,unk,D,Integral Energy ,Utilities,Integral Energy 10624,,Penrith 1,D,Integral Energy Penrith 1,Utilities,Integral Energy 10625,,Penrith 2,D,Integral Energy Penrith 2,Utilities,Integral Energy 10626,,Windsor,D,Integral Energy Windsor,Utilities,Integral Energy 10627,,Kings Park 1,D,Integral Energy Kings Park 1,Utilities,Integral Energy 10628,,Kings Park 2,D,Integral Energy Kings Park 2,Utilities,Integral Energy 10629,,Parramatta 1,D,Integral Energy Parramatta 1,Utilities,Integral Energy 10630,,Parramatta 2,D,Integral Energy Parramatta 2,Utilities,Integral Energy 10631,,Hoxton 1,D,Integral Energy Hoxton 1,Utilities,Integral Energy 10632,,Hoxton 2,D,Integral Energy Hoxton 2,Utilities,Integral Energy 10633,,Narellan 1,D,Integral Energy Narellan 1,Utilities,Integral Energy 10634,,Narellan 2,D,Integral Energy Narellan 2,Utilities,Integral Energy 10635,,unk,D,Integral Energy ,Utilities,Integral Energy 10636,,unk,D,Integral Energy ,Utilities,Integral Energy 10637,,unk,D,Integral Energy ,Utilities,Integral Energy 10638,,unk,D,Integral Energy ,Utilities,Integral Energy 10639,,unk,D,Integral Energy ,Utilities,Integral Energy 10640,,unk,D,Integral Energy ,Utilities,Integral Energy 10641,,unk,D,Integral Energy ,Utilities,Integral Energy 10642,,unk,D,Integral Energy ,Utilities,Integral Energy 10643,,unk,D,Integral Energy ,Utilities,Integral Energy 10644,,unk,D,Integral Energy ,Utilities,Integral Energy 10645,,Techs,D,Integral Energy Radio techs and workshop,Utilities,Integral Energy 10649,,unk,D,Integral Energy ,Utilities,Integral Energy 10901,,Ch 1 ,D,Sydney Ferries,Transportation,Sydney Ferries 10905,,Ch 5 ,D,Sydney Ferries,Transportation,Sydney Ferries 10906,,Ch 6 ,D,Sydney Ferries,Transportation,Sydney Ferries 10907,,Ch 7 ,D,Sydney Ferries,Transportation,Sydney Ferries 10909,,Ch 9 ,D,Sydney Ferries,Transportation,Sydney Ferries 10910,,Ch 10 ,D,Sydney Ferries,Transportation,Sydney Ferries 10911,,Ch 11 ,D,Sydney Ferries,Transportation,Sydney Ferries 10914,,Ch 14 ,D,Sydney Ferries,Transportation,Sydney Ferries 10951,,Syd Region,D,NSW Maritime Sydney Region,Public Works,NSW Maritime 10952,,unk,D,NSW Maritime,Public Works,NSW Maritime 10953,,unk,D,NSW Maritime,Public Works,NSW Maritime 10954,,Hbr Clean,D,NSW Maritime Harbour Cleaning,Public Works,NSW Maritime 10955,,TG Alpha,D,NSW Maritime Special talkgroup Alpha,Public Works,NSW Maritime 10956,,TG Bravo,D,NSW Maritime Special talkgroup Bravo,Public Works,NSW Maritime 10957,,unk,D,NSW Maritime ,Public Works,NSW Maritime 10958,,unk,D,NSW Maritime,Public Works,NSW Maritime 10959,,unk,D,NSW Maritime,Public Works,NSW Maritime 10960,,unk,D,NSW Maritime,Public Works,NSW Maritime 10961,,unk,D,NSW Maritime,Public Works,NSW Maritime 11021,,City,D,Sheriff City,Law Dispatch,NSW Sheriff 11022,,West,D,Sheriff West,Law Dispatch,NSW Sheriff 11023,,North,D,Sheriff North,Law Dispatch,NSW Sheriff 11024,,Nth BC 1,D,Sheriff Nth Region Back Ch 1,Law Talk,NSW Sheriff 11025,,South,D,Sheriff South,Law Dispatch,NSW Sheriff 11026,,Sth BC 1,D,Sheriff Sth Region Back Ch 1,Law Talk,NSW Sheriff 11027,,Tac 1,D,Sheriff Tactical 1 ch17,Law Tac,NSW Sheriff 11028,,Tac 2,D,Sheriff Tactical 2,Law Tac,NSW Sheriff 11029,,Tac 3,D,Sheriff Tactical 3,Law Tac,NSW Sheriff 11030,,JTF Sec Ch,D,Sheriff Joint Task Fed Sec Channel,Interop,NSW Sheriff 11034,,unk,D,Sheriff ,Law Talk,NSW Sheriff 11071,,unk,D,Sutherland Council,Public Works,Sutherland Council 11072,,unk,D,Sutherland Council,Public Works,Sutherland Council 11073,,unk,D,Sutherland Council,Public Works,Sutherland Council 11074,,Depot WS,D,Sutherland Council depot workshop,Public Works,Sutherland Council 11075,,unk,D,Sutherland Council,Public Works,Sutherland Council 11076,,Rangers,D,Sutherland Council Rangers,Public Works,Sutherland Council 11077,,Back Chan,D,Sutherland Council Rangers back channel,Public Works,Sutherland Council 11078,,Work Crews,D,Sutherland Council Work crews,Public Works,Sutherland Council 11079,,unk,D,Sutherland Council,Public Works,Sutherland Council 11080,,unk,D,Sutherland Council,Public Works,Sutherland Council 11081,,unk,D,Sutherland Council,Public Works,Sutherland Council 11082,,unk,D,Sutherland Council,Public Works,Sutherland Council 11104,,SEC 1,D,Rail SEC 1,Railroad,Railways 11105,,SEC 2,D,Rail SEC 2,Railroad,Railways 11106,,SEC 3,D,Rail SEC 3,Railroad,Railways 11107,,SEC 4,D,Rail SEC 4,Railroad,Railways 11108,,PATROL 1,D,Rail PATROL 1,Railroad,Railways 11109,,PATROL 2,D,Rail PATROL 2,Railroad,Railways 11110,,PATROL 3,D,Rail PATROL 3,Railroad,Railways 11111,,CONSEC,D,Rail CONSEC,Railroad,Railways 11112,,SP OPS 1,D,Rail SP OPS 1,Railroad,Railways 11113,,SP OPS 2,D,Rail SP OPS 2,Railroad,Railways 11114,,SP OPS 3,D,Rail SP OPS 3,Railroad,Railways 11115,,REV PR 1,D,Rail REV PR 1,Railroad,Railways 11116,,REV PR 2,D,Rail REV PR 2,Railroad,Railways 11117,,REV PR 3,D,Rail REV PR 3,Railroad,Railways 11118,,REV PR 4,D,Rail REV PR 4,Railroad,Railways 11120,,BLACK 1,D,Rail BLACK 1,Railroad,Railways 11121,,BLACK 2,D,Rail BLACK 2,Railroad,Railways 11122,,CITY 1,D,Rail CITY 1,Railroad,Railways 11123,,CITY 2,D,Rail CITY 2,Railroad,Railways 11124,,GOSFORD 1,D,Rail GOSFORD 1,Railroad,Railways 11125,,GOSFORD 2,D,Rail GOSFORD 2,Railroad,Railways 11126,,NEWC 1,D,Rail NEWC 1,Railroad,Railways 11127,,NEWC 2,D,Rail NEWC 2,Railroad,Railways 11128,,SOUTH 1,D,Rail SOUTH 1,Railroad,Railways 11129,,SOUTH 2,D,Rail SOUTH 2,Railroad,Railways 11130,,ILLAW 1,D,Rail ILLAW 1,Railroad,Railways 11131,,ILLAWA 2,D,Rail ILLAWA 2,Railroad,Railways 11132,,SCOAST 1,D,Rail S COAST 1,Railroad,Railways 11136,,Chan 01,D,Rail CHAN 01,Railroad,Railways 11144,,Chan 9,D,Rail Channel 9,Railroad,Railways 11145,,Hunter Ops,D,Rail Hunter Operations,Railroad,Railways 11146,,Hunter Inc,D,Rail Hunter Incidents,Railroad,Railways 11147,,Chan 12,D,Rail CHAN 12,Railroad,Railways 11151,,ALL Chans,D,Rail All channels,Railroad,Railways 11158,,unk,D,Rail ,Railroad,Railways 11168,,SW Rail 1,D,Rail SW Rail 1,Railroad,Railways 11169,,SW Rail 2,D,Rail SW Rail 2,Railroad,Railways 11173,,Rail 6,D,Rail Rail 6,Railroad,Railways 11184,,unk,D,Rail ,Railroad,Railways 11200,,unk,D,Rail ,Railroad,Railways 11218,,CIVSTRUCT,D,Rail CIVSTRUCT,Railroad,Railways 11229,,Sig Cent3,D,Rail SIG CENT3,Railroad,Railways 11240,,WGong 1,D,Rail WGong 1,Railroad,Railways 11291,,Earth,D,Rail earth,Railroad,Railways 11294,,WONDABYNE,D,Rail WONDABYNE,Railroad,Railways 11316,,unk,D,Rail ,Railroad,Railways 11317,,unk,D,Rail ,Railroad,Railways 11320,,unk,D,Rail ,Railroad,Railways 11321,,unk,D,Rail ,Railroad,Railways 11322,,unk,D,Rail ,Railroad,Railways 11323,,unk,D,Rail ,Railroad,Railways 11324,,unk,D,Rail ,Railroad,Railways 11325,,unk,D,Rail ,Railroad,Railways 11350,,Row 1,D,Rail Row 1,Railroad,Railways 11471,,ABC 1,D,ABC News,Media,Australian Broadcasting Corporation ABC News 11472,,ABC 2,D,ABC News,Media,Australian Broadcasting Corporation ABC News 11473,,ABC 3,D,ABC News,Media,Australian Broadcasting Corporation ABC News 11474,,ABC 4,D,ABC News,Media,Australian Broadcasting Corporation ABC News 11475,,ABC 5,D,ABC News,Media,Australian Broadcasting Corporation ABC News 19801,,Rent 1,D,Short term rental,Business,GRN Short Term Rental 19802,,Rent 2,D,Short term rental,Business,GRN Short Term Rental 19803,,Rent 3,D,Short term rental,Business,GRN Short Term Rental 19804,,Rent 4,D,Short term rental,Business,GRN Short Term Rental 19805,,Rent 5,D,Short term rental,Business,GRN Short Term Rental 19901,,Test TG 1,D,Test talkgroup 1,Business,Test 19902,,Test TG 2,D,Test talkgroup 2,Business,Test 19903,,Test TG 3,D,Test talkgroup 3,Business,Test 19904,,Test TG 4,D,Test talkgroup 4,Business,Test 19905,,Test TG 5,D,Test talkgroup 5,Business,Test 19906,,Test TG 6,D,Test talkgroup 6,Business,Test 20000,,BAR DRL,D,RFS GD07 BAR DRL,Fire-Tac,Rural Fire Service RFS 20001,,CANBOLS,D,RFS GD11 CANBOLS,Fire-Tac,Rural Fire Service RFS 20002,,CSTLRGH,D,RFS GD12 CSTLRGH,Fire-Tac,Rural Fire Service RFS 20003,,CHIFLEY,D,RFS GD13 CHIFLEY,Fire-Tac,Rural Fire Service RFS 20004,,CLARNCE,D,RFS GD15 CLARNCE,Fire-Tac,Rural Fire Service RFS 20005,,CDGEGNG,D,RFS GD19 CDGEGNG,Fire-Tac,Rural Fire Service RFS 20006,,FARNHCO,D,RFS GD23 FARNHCO,Fire-Tac,Rural Fire Service RFS 20007,,FAR WST,D,RFS GD25 FAR WST,Fire-Tac,Rural Fire Service RFS 20008,,HUNTER,D,RFS GD32 HUNTER,Fire-Tac,Rural Fire Service RFS 20009,,HUNTVAL,D,RFS GD33 HUNTVAL,Fire-Tac,Rural Fire Service RFS 20010,,LITHGOW,D,RFS GD36 LITHGOW,Fire-Tac,Rural Fire Service RFS 20011,,LVPL RG,D,RFS GD37 LVPL RG,Fire-Tac,Rural Fire Service RFS 20012,,LOWNHCO,D,RFS GD40 LOWNHCO,Fire-Tac,Rural Fire Service RFS 20013,,MANNING,D,RFS GD43 MANNING,Fire-Tac,Rural Fire Service RFS 20014,,MD LACH,D,RFS GD47 MD LACH,Fire-Tac,Rural Fire Service RFS 20015,,MIDNHCO,D,RFS GD49 MIDNHCO,Fire-Tac,Rural Fire Service RFS 20016,,NMGWYDR,D,RFS GD52 NMGWYDR,Fire-Tac,Rural Fire Service RFS 20017,,NWENGLD,D,RFS GD53 NWENGLD,Fire-Tac,Rural Fire Service RFS 20018,,NTH OPS,D,RFS GD54 NTH OPS,Fire-Tac,Rural Fire Service RFS 20019,,NTHWEST,D,RFS GD55 NTHWEST,Fire-Tac,Rural Fire Service RFS 20020,,NTHN RIV,D,RFS GD56 NTHN RIV,Fire-Tac,Rural Fire Service RFS 20021,,NTH TAB,D,RFS GD57 NTH TAB,Fire-Tac,Rural Fire Service RFS 20022,,ORANA,D,RFS GD61 ORANA,Fire-Tac,Rural Fire Service RFS 20023,,RGN NTH,D,RFS GD78 RGN NTH,Fire-Tac,Rural Fire Service RFS 20024,,RGN WST,D,RFS GD80 RGN WST,Fire-Tac,Rural Fire Service RFS 20025,,TAMWRTH,D,RFS GD89 TAMWRTH,Fire-Tac,Rural Fire Service RFS 20026,,THE LKS,D,RFS GD90 THE LKS,Fire-Tac,Rural Fire Service RFS 20027,,WST OPS,D,RFS GD92 WST OPS,Fire-Tac,Rural Fire Service RFS 20201,,CNTAC1,D,SES 107CNTAC1,EMS-Tac,State Emergency Service SES 20202,,CNTAC2,D,SES 108CNTAC2,EMS-Tac,State Emergency Service SES 20203,,CNTAC3,D,SES 109CNTAC3,EMS-Tac,State Emergency Service SES 20204,,CNTAC4,D,SES 110CNTAC4,EMS-Tac,State Emergency Service SES 20205,,CNTAC5,D,SES 111CNTAC5,EMS-Tac,State Emergency Service SES 20206,,CNTAC6,D,SES 112CNTAC6,EMS-Tac,State Emergency Service SES 20207,,CNTAC7,D,SES 113CNTAC7,EMS-Tac,State Emergency Service SES 20208,,CNTAC8,D,SES 114CNTAC8,EMS-Tac,State Emergency Service SES 20209,,CNSTRAT,D,SES 116CNSTRAT,EMS-Tac,State Emergency Service SES 20210,,CWTAC1,D,SES 127CWTAC1,EMS-Tac,State Emergency Service SES 20211,,CWTAC2,D,SES 128CWTAC2,EMS-Tac,State Emergency Service SES 20212,,CWTAC3,D,SES 129CWTAC3,EMS-Tac,State Emergency Service SES 20213,,CWTAC4,D,SES 130CWTAC4,EMS-Tac,State Emergency Service SES 20214,,CWTAC5,D,SES 131CWTAC5,EMS-Tac,State Emergency Service SES 20215,,CWSTRAT,D,SES 133CWSTRAT,EMS-Tac,State Emergency Service SES 20216,,FWTAC1,D,SES 135FWTAC1,EMS-Tac,State Emergency Service SES 20217,,FWTAC2,D,SES 136FWTAC2,EMS-Tac,State Emergency Service SES 20218,,FWTAC3,D,SES 137FWTAC3,EMS-Tac,State Emergency Service SES 20219,,FWTAC4,D,SES 138FWTAC4,EMS-Tac,State Emergency Service SES 20220,,FWTAC5,D,SES 139FWTAC5,EMS-Tac,State Emergency Service SES 20221,,FWTAC6,D,SES 140FWTAC6,EMS-Tac,State Emergency Service SES 20222,,FWSTRAT,D,SES 142FWSTRAT,EMS-Tac,State Emergency Service SES 20223,,HUTAC1,D,SES 155HUTAC1,EMS-Tac,State Emergency Service SES 20224,,HUTAC2,D,SES 156HUTAC2,EMS-Tac,State Emergency Service SES 20225,,HUTAC3,D,SES 157HUTAC3,EMS-Tac,State Emergency Service SES 20226,,HUTAC4,D,SES 158HUTAC4,EMS-Tac,State Emergency Service SES 20227,,HUTAC5,D,SES 159HUTAC5,EMS-Tac,State Emergency Service SES 20228,,HUTAC6,D,SES 160HUTAC6,EMS-Tac,State Emergency Service SES 20229,,HUSTRAT,D,SES 162HUSTRAT,EMS-Tac,State Emergency Service SES 20230,,LATAC1,D,SES 173LATAC1,EMS-Tac,State Emergency Service SES 20231,,LATAC2,D,SES 174LATAC2,EMS-Tac,State Emergency Service SES 20232,,LATAC3,D,SES 175LATAC3,EMS-Tac,State Emergency Service SES 20233,,LATAC4,D,SES 176LATAC4,EMS-Tac,State Emergency Service SES 20234,,LATAC5,D,SES 177LATAC5,EMS-Tac,State Emergency Service SES 20235,,LATAC6,D,SES 178LATAC6,EMS-Tac,State Emergency Service SES 20236,,LASTRAT,D,SES 180LASTRAT,EMS-Tac,State Emergency Service SES 20237,,NMTAC1,D,SES 1129NMTAC1,EMS-Tac,State Emergency Service SES 20238,,NMTAC2,D,SES 1130NMTAC2,EMS-Tac,State Emergency Service SES 20239,,NMTAC3,D,SES 1131NMTAC3,EMS-Tac,State Emergency Service SES 20240,,NMTAC4,D,SES 1132NMTAC4,EMS-Tac,State Emergency Service SES 20241,,NMTAC5,D,SES 1133NMTAC5,EMS-Tac,State Emergency Service SES 20242,,NMTAC6,D,SES 1134NMTAC6,EMS-Tac,State Emergency Service SES 20243,,NMSTRAT,D,SES 1136NMSTRAT,EMS-Tac,State Emergency Service SES 20244,,NWTAC1,D,SES 1144NWTAC1,EMS-Tac,State Emergency Service SES 20245,,NWTAC2,D,SES 1145NWTAC2,EMS-Tac,State Emergency Service SES 20246,,NWTAC3,D,SES 1146NWTAC3,EMS-Tac,State Emergency Service SES 20247,,NWTAC4,D,SES 1147NWTAC4,EMS-Tac,State Emergency Service SES 20248,,NWTAC5,D,SES 1148NWTAC5,EMS-Tac,State Emergency Service SES 20249,,NWTAC6,D,SES 1149NWTAC6,EMS-Tac,State Emergency Service SES 20250,,NWTAC7,D,SES 1150NWTAC7,EMS-Tac,State Emergency Service SES 20251,,NWTAC8,D,SES 1151NWTAC8,EMS-Tac,State Emergency Service SES 20252,,NWSTRAT,D,SES 1153NWSTRAT,EMS-Tac,State Emergency Service SES 20253,,OXTAC1,D,SES 1165OXTAC1,EMS-Tac,State Emergency Service SES 20254,,OXTAC2,D,SES 1166OXTAC2,EMS-Tac,State Emergency Service SES 20255,,OXTAC3,D,SES 1167OXTAC3,EMS-Tac,State Emergency Service SES 20256,,OXTAC4,D,SES 1168OXTAC4,EMS-Tac,State Emergency Service SES 20257,,OXTAC5,D,SES 1169OXTAC5,EMS-Tac,State Emergency Service SES 20258,,OXTAC6,D,SES 1170OXTAC6,EMS-Tac,State Emergency Service SES 20259,,OXTAC7,D,SES 1171OXTAC7,EMS-Tac,State Emergency Service SES 20260,,OXTAC8,D,SES 1172OXTAC8,EMS-Tac,State Emergency Service SES 20261,,OXSTRAT,D,SES 1174OXSTRAT,EMS-Tac,State Emergency Service SES 20262,,RTTAC1,D,SES 1185RTTAC1,EMS-Tac,State Emergency Service SES 20263,,RTTAC2,D,SES 1186RTTAC2,EMS-Tac,State Emergency Service SES 20264,,RTTAC3,D,SES 1187RTTAC3,EMS-Tac,State Emergency Service SES 20265,,RTTAC4,D,SES 1188RTTAC4,EMS-Tac,State Emergency Service SES 20266,,RTTAC5,D,SES 1189RTTAC5,EMS-Tac,State Emergency Service SES 20267,,RTTAC6,D,SES 1190RTTAC6,EMS-Tac,State Emergency Service SES 20268,,RTTAC7,D,SES 1191RTTAC7,EMS-Tac,State Emergency Service SES 20269,,RTTAC8,D,SES 1192RTTAC8,EMS-Tac,State Emergency Service SES 20270,,RTSTRAT,D,SES 1194RTSTRAT,EMS-Tac,State Emergency Service SES 20301,,NewcOps,D,Newcastle Operations,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20302,,HuntOps,D,Outer Hunter Operations,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20303,,GosOps,D,Gosford Operations,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20304,,Nth Inc1,D,North Incident 1,EMS-Tac,Ambulance Service of New South Wales ASNSW 20305,,Nth Inc2,D,North Incident 2,EMS-Tac,Ambulance Service of New South Wales ASNSW 20306,,Hunt Hosp,D,Hunter Hospitals,Hospital,Ambulance Service of New South Wales ASNSW 20307,,MidWest1,D,MidWest Operations 1,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20308,,MidWest2,D,MidWest Operations 2,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20309,,MQOps1,D,Macquarie Operations 1,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20310,,MQOps2,D,Macquarie Operations 2,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20311,,NEOps1,D,New England Operations 1,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20312,,NEOps2,D,New England Operations 2,EMS Dispatch,Ambulance Service of New South Wales ASNSW 20313,,West Inc1,D,West Incident 1,EMS-Tac,Ambulance Service of New South Wales ASNSW 20314,,West Inc2,D,West Incident 2,EMS-Tac,Ambulance Service of New South Wales ASNSW 20315,,INCIDENT 1,,West Incident 1,,Ambulance Service of New South Wales ASNSW 20316,,INCIDENT 2,,West Incident 2,,Ambulance Service of New South Wales ASNSW 20317,,INCIDENT 3,,West Incident 3,,Ambulance Service of New South Wales ASNSW 20318,,HOSP 1,,West Hospital 1,,Ambulance Service of New South Wales ASNSW 20319,,HOSP 2,,West Hospital 2,,Ambulance Service of New South Wales ASNSW 20320,,HUN HOSP,,North Hunter Hospitals,,Ambulance Service of New South Wales ASNSW 20501,,CC Op,D,AusGrid Central Coast Operator,Utilities,AusGrid 20502,,CC Inspect,D,AusGrid Central Coast Installation Inspectors,Utilities,AusGrid 20503,,CC EMSOs,D,AusGrid Central Coast EMSOs,Utilities,AusGrid 20504,,CC Subs,D,AusGrid Central Coast Substations,Utilities,AusGrid 20505,,Gos OH,D,AusGrid Gosford Overhead,Utilities,AusGrid 20506,,CC UG,D,AusGrid Central Coast Underground,Utilities,AusGrid 20508,,Nora OH,D,AusGrid Noraville Overhead,Utilities,AusGrid 20509,,CC Prot,D,AusGrid Central Coast Protection,Utilities,AusGrid 20510,,Nora OH,D,AusGrid Noraville Overhead,Utilities,AusGrid 20511,,CC EMSO 1,D,AusGrid Central Coast EMSO Data 1,Utilities,AusGrid 20512,,CC Op,D,AusGrid Central Coast Operator,Utilities,AusGrid 20513,,Newc Op,D,AusGrid Newcastle Operator,Utilities,AusGrid 20514,,Newc Des Dat,D,AusGrid Newcastle Despatch Data 1,Utilities,AusGrid 20515,,Wall OH 1,D,AusGrid Wallsend Overhead 1,Utilities,AusGrid 20516,,Wall UG,D,AusGrid Wallsend Underground,Utilities,AusGrid 20517,,Wall Subs,D,AusGrid Wallsend Substations,Utilities,AusGrid 20518,,Mait 1,D,AusGrid Maitland 1,Utilities,AusGrid 20519,,Wall OH 2,D,AusGrid Wallsend Overhead 2,Utilities,AusGrid 20520,,Hunt TCA,D,AusGrid TCA Hunter,Utilities,AusGrid 20521,,Hunt Op,D,AusGrid Hunter Operator,Utilities,AusGrid 20522,,Musw 1,D,AusGrid Muswellbrook 1,Utilities,AusGrid 20523,,Musw 2,D,AusGrid Muswellbrook 2,Utilities,AusGrid 20524,,CASS Data2,D,AusGrid CASS Data 2,Utilities,AusGrid 20525,,Sing,D,AusGrid Singleton,Utilities,AusGrid 20526,,Hunt DistOp,D,AusGrid Hunter District Operators,Utilities,AusGrid 20527,,Newc DistOp,D,AusGrid Newcastle District Operators,Utilities,AusGrid 20528,,Hunt Proj,D,AusGrid Hunter Projects,Utilities,AusGrid 21001,,HuntWat Est,D,Hunter Water East,Utilities,Hunter Water 21002,,HuntWat 2,D,Hunter Water,Utilities,Hunter Water 21003,,HuntWat Nth,D,Hunter Water North,Utilities,Hunter Water 21004,,HuntWat 4,D,Hunter Water,Utilities,Hunter Water 21005,,HuntWat 5,D,Hunter Water,Utilities,Hunter Water 21006,,HuntWat 6,D,Hunter Water,Utilities,Hunter Water 30000,,BLD TEM,D,RFS GD09 BLD TEM,Fire-Tac,Rural Fire Service RFS 30001,,FARSHCO,D,RFS GD24 FARSHCO,Fire-Tac,Rural Fire Service RFS 30002,,HUME SB,D,RFS GD31 HUME SB,Fire-Tac,Rural Fire Service RFS 30003,,ILLWARA,D,RFS GD34 ILLWARA,Fire-Tac,Rural Fire Service RFS 30004,,L GEORG,D,RFS GD35 L GEORG,Fire-Tac,Rural Fire Service RFS 30005,,LOWWSTN,D,RFS GD41 LOWWSTN,Fire-Tac,Rural Fire Service RFS 30006,,MIA,D,RFS GD46 MIA,Fire-Tac,Rural Fire Service RFS 30007,,MID MUR,D,RFS GD48 MID MUR,Fire-Tac,Rural Fire Service RFS 30008,,MID WST,D,RFS GD50 MID WST,Fire-Tac,Rural Fire Service RFS 30009,,MONARO,D,RFS GD51 MONARO,Fire-Tac,Rural Fire Service RFS 30010,,RGN STH,D,RFS GD79 RGN STH,Fire-Tac,Rural Fire Service RFS 30011,,RV HIGH,D,RFS GD81 RV HIGH,Fire-Tac,Rural Fire Service RFS 30012,,RIVERNA,D,RFS GD82 RIVERNA,Fire-Tac,Rural Fire Service RFS 30013,,SHOALHN,D,RFS GD83 SHOALHN,Fire-Tac,Rural Fire Service RFS 30014,,STH OPS,D,RFS GD84 STH OPS,Fire-Tac,Rural Fire Service RFS 30015,,SWSZ,D,RFS GD85 SWSZ,Fire-Tac,Rural Fire Service RFS 30016,,STHN TD,D,RFS GD86 STHN TD,Fire-Tac,Rural Fire Service RFS 30017,,WNGCARI,D,RFS GD93 WNGCARI,Fire-Tac,Rural Fire Service RFS 30201,,ISTAC1,D,SES 163ISTAC1,EMS-Tac,State Emergency Service SES 30202,,ISTAC2,D,SES 164ISTAC2,EMS-Tac,State Emergency Service SES 30203,,ISTAC3,D,SES 165ISTAC3,EMS-Tac,State Emergency Service SES 30204,,ISTAC4,D,SES 166ISTAC4,EMS-Tac,State Emergency Service SES 30205,,ISTAC5,D,SES 167ISTAC5,EMS-Tac,State Emergency Service SES 30206,,ISTAC6,D,SES 168ISTAC6,EMS-Tac,State Emergency Service SES 30207,,ISTAC7,D,SES 169ISTAC7,EMS-Tac,State Emergency Service SES 30208,,ISTAC8,D,SES 170ISTAC8,EMS-Tac,State Emergency Service SES 30209,,ISSTRAT,D,SES 172ISSTRAT,EMS-Tac,State Emergency Service SES 30210,,METAC1,D,SES 181METAC1,EMS-Tac,State Emergency Service SES 30211,,METAC2,D,SES 182METAC2,EMS-Tac,State Emergency Service SES 30212,,METAC3,D,SES 183METAC3,EMS-Tac,State Emergency Service SES 30213,,METAC4,D,SES 184METAC4,EMS-Tac,State Emergency Service SES 30214,,METAC5,D,SES 185METAC5,EMS-Tac,State Emergency Service SES 30215,,METAC6,D,SES 186METAC6,EMS-Tac,State Emergency Service SES 30216,,METAC7,D,SES 187METAC7,EMS-Tac,State Emergency Service SES 30217,,METAC8,D,SES 188METAC8,EMS-Tac,State Emergency Service SES 30218,,MESTRAT,D,SES 190MESTRAT,EMS-Tac,State Emergency Service SES 30219,,MQTAC1,D,SES 1101MQTAC1,EMS-Tac,State Emergency Service SES 30220,,MQTAC2,D,SES 1102MQTAC2,EMS-Tac,State Emergency Service SES 30221,,MQTAC3,D,SES 1103MQTAC3,EMS-Tac,State Emergency Service SES 30222,,MQTAC4,D,SES 1104MQTAC4,EMS-Tac,State Emergency Service SES 30223,,MQTAC5,D,SES 1105MQTAC5,EMS-Tac,State Emergency Service SES 30224,,MQTAC6,D,SES 1106MQTAC6,EMS-Tac,State Emergency Service SES 30225,,MQSTRAT,D,SES 1108MQSTRAT,EMS-Tac,State Emergency Service SES 30226,,MYTAC1,D,SES 1109MYTAC1,EMS-Tac,State Emergency Service SES 30227,,MYTAC2,D,SES 1110MYTAC2,EMS-Tac,State Emergency Service SES 30228,,MYTAC3,D,SES 1111MYTAC3,EMS-Tac,State Emergency Service SES 30229,,MYTAC4,D,SES 1112MYTAC4,EMS-Tac,State Emergency Service SES 30230,,MYTAC5,D,SES 1113MYTAC5,EMS-Tac,State Emergency Service SES 30231,,MYTAC6,D,SES 1114MYTAC6,EMS-Tac,State Emergency Service SES 30232,,MYSTRAT,D,SES 1116MYSTRAT,EMS-Tac,State Emergency Service SES 30233,,SHTAC1,D,SES 1209SHTAC1,EMS-Tac,State Emergency Service SES 30234,,SHTAC2,D,SES 1210SHTAC2,EMS-Tac,State Emergency Service SES 30235,,SHTAC3,D,SES 1211SHTAC3,EMS-Tac,State Emergency Service SES 30236,,SHTAC4,D,SES 1212SHTAC4,EMS-Tac,State Emergency Service SES 30237,,SHTAC5,D,SES 1213SHTAC5,EMS-Tac,State Emergency Service SES 30238,,SHTAC6,D,SES 1214SHTAC6,EMS-Tac,State Emergency Service SES 30239,,SHTAC7,D,SES 1215SHTAC7,EMS-Tac,State Emergency Service SES 30240,,SHTAC8,D,SES 1216SHTAC8,EMS-Tac,State Emergency Service SES 30241,,SHSTRAT,D,SES 1218SHSTRAT,EMS-Tac,State Emergency Service SES 30301,,FSC OPS,,South Far South Coast Operations,,Ambulance Service of New South Wales ASNSW 30302,,ILLA OPS,,South Illawarra Operations,,Ambulance Service of New South Wales ASNSW 30303,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 30304,,WAGGA OPS,,South Wagga Operations,,Ambulance Service of New South Wales ASNSW 30305,,RIV OPS,,South Riverina Operations,,Ambulance Service of New South Wales ASNSW 30306,,MURRAY OPS,,South Murray Operations,,Ambulance Service of New South Wales ASNSW 30307,,ECP 3,,South Extended Care Paramedic 3,,Ambulance Service of New South Wales ASNSW 30308,,INCIDENT 1,,South Incident 1,,Ambulance Service of New South Wales ASNSW 30309,,INCIDENT 2,,South Incident 2,,Ambulance Service of New South Wales ASNSW 30310,,INCIDENT 3,,South Incident 3,,Ambulance Service of New South Wales ASNSW 30311,,INCIDENT 4,,South Incident 4,,Ambulance Service of New South Wales ASNSW 30312,,INCIDENT 5,,South Incident 5,,Ambulance Service of New South Wales ASNSW 30313,,INCIDENT 6,,South Incident 6,,Ambulance Service of New South Wales ASNSW 30314,,ILLAW HOSP,,South Illawarra Hospitals,,Ambulance Service of New South Wales ASNSW 30315,,GOULB HOSP,,South Goulburn Hospitals,,Ambulance Service of New South Wales ASNSW 30316,,SHAVEN OPS,,South Shoalhaven Operations,,Ambulance Service of New South Wales ASNSW 30317,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 30318,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 30319,,ASNSW,,ASNSW,,Ambulance Service of New South Wales ASNSW 30320,,ACT AMB,,South ACT Ambulance Liaison,,Ambulance Service of New South Wales ASNSW 30321,,STH EAST OPS,,South South East Operations,,Ambulance Service of New South Wales ASNSW 40010,,ESA 7,D,ESA 7,Interop,ACT ESA 40011,,ESA 8,D,ESA 8,Interop,ACT ESA 40013,,ACTAS Ops1,D,ACT Ambulance Ops 1,EMS Dispatch,ACT ESA 40031,,Air Sup,D,Air Sup,Interop,ACT ESA 40032,,ESA 1,D,ESA 1,Interop,ACT ESA 40033,,ESA 2,D,ESA 2,Interop,ACT ESA 40034,,ESA 3,D,ESA 3,Interop,ACT ESA 40035,,ESA 4,D,ESA 4,Interop,ACT ESA 40036,,ESA 5,D,ESA 5,Interop,ACT ESA 40037,,ESA 6,D,ESA 6,Interop,ACT ESA 40038,,ESA 9,D,ESA 9,Interop,ACT ESA 40039,,ESA 10,D,ESA 10,Interop,ACT ESA 40040,,ESA 11,D,ESA 11,Interop,ACT ESA 40041,,ESA 12,D,ESA 12,Interop,ACT ESA 40042,,ESA 13,D,ESA 13,Interop,ACT ESA 40043,,Joint T,D,Joint T,Interop,ACT ESA 40050,,ACTFB,E,ACTFB ,Public Works,ACT ESA 40051,,ACTFB,E,ACTFB ,Public Works,ACT ESA 40052,,ACTFB,E,ACTFB ,Public Works,ACT ESA 40059,,Priority,D,RFS Priority Channel,Emergency Ops,ACT RFS 40068,,RFS Ops 1,D,ACT RFS Ops 1,Fire-Tac,ACT RFS 40069,,FG 2,D,ACT RFS FG 2,Fire-Tac,ACT RFS 40070,,FG 3,D,ACT RFS FG 3,Fire-Tac,ACT RFS 40071,,FG 4,D,ACT RFS FG 4,Fire-Tac,ACT RFS 40072,,FG 5,D,ACT RFS FG 5,Fire-Tac,ACT RFS 40073,,RFS Ops 6,D,ACT RFS Ops 6,Fire-Tac,ACT RFS 40074,,FG 7,D,ACT RFS FG 7,Fire-Tac,ACT RFS 40075,,IMT,D,ACT RFS IMT,Fire-Tac,ACT RFS 40076,,Air Ops,D,ACT RFS Air Ops,Fire-Tac,ACT RFS 40077,,RFS Plt Ops,D,ACT RFS Plant Ops,Fire-Tac,ACT RFS 40078,,SES Ops 1,D,ACT SES Ops 1,EMS-Tac,ACT SES 40079,,SES Ops 2,D,ACT SES Ops 2,EMS-Tac,ACT SES 40080,,SES Ops 3,D,ACT SES Ops 3,EMS-Tac,ACT SES 40081,,SES Ops 4,D,ACT SES Ops 4,EMS-Tac,ACT SES 40082,,SES Ops 5,D,ACT SES Ops 5 Vehicle Talkgroup,EMS-Tac,ACT SES 40083,,SES Ops 6,D,ACT SES Ops 6,EMS-Tac,ACT SES 40084,,SES Ops 7,D,ACT SES Ops 7,EMS-Tac,ACT SES 40085,,SES Ops 8,D,ACT SES Ops 8,EMS-Tac,ACT SES 40086,,SES Ops 9,D,ACT SES Ops 9,EMS-Tac,ACT SES 40087,,SES Ops 10,D,ACT SES Ops 10,EMS-Tac,ACT SES 40088,,SES Ops 11,D,ACT SES Ops 11,EMS-Tac,ACT SES 40089,,PCL Ops,D,Parks Conserv Land Ops,Fire-Tac,ACT PCL 40090,,PCL Ops,D,Parks Conserv Land Ops,Fire-Tac,ACT PCL 40091,,Fire Mgt,D,TAMS Fire Mgmt,Fire Dispatch,ACT PCL 40092,,PCL CNP,D,Canberra Nature Parks,Fire-Tac,ACT PCL 40093,,PCL Rural,D,Parks Conserv Land Rural,Fire-Tac,ACT PCL 40097,,PCL HRB,D,Hazard Reduction Burn,Fire-Tac,ACT PCL 42000,,Guises Ck,D,RFS Guises Creek,Fire Dispatch,ACT RFS 42001,,Gunghalin,D,RFS Gunghalin,Fire Dispatch,ACT RFS 42002,,Hall,D,RFS Hall,Fire Dispatch,ACT RFS 42003,,Jerrabombera,D,RFS Jerrabombera,Fire Dispatch,ACT RFS 42004,,Molonglo,D,RFS Molongo,Fire Dispatch,ACT RFS 42005,,ACT,D,ACT RFS ,,ACT RFS 44010,,ACTION 44010,D,ACTION Buses,Transportation,ACTION Buses 44011,,ACTION 44011,D,ACTION Buses,Transportation,ACTION Buses 44012,,ACTION 44012,D,ACTION Buses,Transportation,ACTION Buses 44013,,ACTION 44013,D,ACTION Buses,Transportation,ACTION Buses
<?php <?php
// http://www.unitrunker.com/logs.html // http://www.unitrunker.com/logs.html
/* /*
Timestamp as YYYYMMDDHHMMSS Timestamp as YYYYMMDDHHMMSS
Site number in unformatted decimal Site number in unformatted decimal
Action: Call, Leaves, Joins, Login, Logout, Drop, Add, Busy, Deny, Kill Action: Call, Leaves, Joins, Login, Logout, Drop, Add, Busy, Deny, Kill
Source type I or G Source type I or G
Source ID in unformatted decimal Source ID in unformatted decimal
Target type I or G Target type I or G
Target ID in unformatted decimal Target ID in unformatted decimal
Channel number in unformatted decimal Channel number in unformatted decimal
Call Type*/ Call Type*/
$row = 0; $row = 0;
echo "<table>"; echo "<table>";
if (($handle = fopen("C:\Users\Madoka\AppData\Roaming\UniTrunker\S00000001\UniTrunker-20120411.LOG", "r")) !== FALSE) { if (($handle = fopen("C:\Users\Madoka\AppData\Roaming\UniTrunker\S00000001\UniTrunker-20120411.LOG", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   
if ($row > 0 && count($data) == 9) { if ($row > 0 && count($data) == 9) {
   
echo "<tr>"; echo "<tr>";
for ($c=0; $c < count($data); $c++) { for ($c = 0; $c < count($data); $c++) {
echo '<td>'.$data[$c] . "</td>\n"; echo '<td>' . $data[$c] . "</td>\n";
} }
echo "</tr>"; echo "</tr>";
} }
$row++; $row++;
} }
fclose($handle); fclose($handle);
} }
echo "</table>"; echo "</table>";
?> ?>
file:b/viewcalls.php (new)
  <?php
  include('common.inc.php');
  $tgid = 44028;
  $from = (isset($_REQUEST['from']) ? $_REQUEST['from'] : strtotime("2012-09-12"));
  $to = (isset($_REQUEST['to']) ? $_REQUEST['to'] : strtotime("2012-12-12"));
  include_header("fdds");
  $sth = $conn->prepare('select distinct date_trunc(\'day\', call_timestamp) as rdate from recordings order by rdate');
 
  $sth->execute();
  foreach ($sth->fetchAll() as $row) {
  echo '<a href="?from=' . strtotime($row['rdate']) . '&amp;to=' . strtotime($row['rdate'] . ' +1 day') . '">' . $row['rdate'] . '</a> <br>';
  }
 
  ?>
  <div class="span12">
 
  <table width="100%" height="775px">
  <tr>
  <td valign="middle"><span class="arrow-w" style="font-size:2em;">&lt;</span></td>
  <td width="95%">
  <div id="placeholder" style="width:100%;height:575px;"></div>
  </td>
  <td valign="middle"><span class="arrow-e" style="font-size:2em;">&gt;</span></td>
  </tr>
  </table>
  <script>
  var data = [];
  var plot;
  var options = {
  lines: { show: true },
  points: { show: true },
  xaxis: {
  mode: 'time',
  labelsAngle: 45
  },
  selection: { mode: 'x', fps: 30 },
  series: {
  lines: { show: true },
  points: { show: true }
  },
  mouse: {
  track: true,
  relative: true
  }
  };
  $(function () {
  // graph
 
 
  var placeholder = document.getElementById("placeholder");
 
  drawGraph(options);
 
  // Hook into the 'flotr:select' event.
  Flotr.EventAdapter.observe(placeholder, 'flotr:select', function (area) {
 
  // Draw graph with new area
  graph = drawGraph({
  xaxis: {min: area.x1, max: area.x2, mode: 'time', labelsAngle: 45},
  yaxis: {min: area.y1, max: area.y2}
  });
  });
 
  // When graph is clicked, draw the graph with default area.
  Flotr.EventAdapter.observe(placeholder, 'flotr:click', function () {
  drawGraph();
  });
 
 
  getData('<?php echo $tgid; ?>', '<?php echo $from ?>', '<?php echo $to ?>');
 
  });
 
  // Draw graph with default options, overwriting with passed options
  function drawGraph(opts) {
 
  // Clone the options, so the 'options' variable always keeps intact.
  var o = Flotr._.extend(Flotr._.clone(options), opts || {});
 
  // Return a new graph.
  return Flotr.draw(
  placeholder,
  data,
  o
  );
  }
 
 
  function onDataReceived(series) {
  data = []
  for (var key in series.data) {
  data[data.length] = {label: key, data: series.data[key]};
  }
  drawGraph(options);
  }
  function getData(sensorID, from, to) {
  $.ajax({
  url: "<?php echo $basePath; ?>calls.json.php?action=graphcount&tgid=" + sensorID + "&from=" + from + "&to=" + to,
  method: 'GET',
  dataType: 'json',
  success: onDataReceived
  });
  }
 
 
  </script>
  </div>
  <?php
  include_footer();
  ?>