fookebox-0.6.1/0000755000175000017500000000000011743153607014123 5ustar stefanstefan00000000000000fookebox-0.6.1/docs/0000755000175000017500000000000011743153607015053 5ustar stefanstefan00000000000000fookebox-0.6.1/docs/examples/0000755000175000017500000000000011743153607016671 5ustar stefanstefan00000000000000fookebox-0.6.1/docs/examples/apache/0000755000175000017500000000000011743153607020112 5ustar stefanstefan00000000000000fookebox-0.6.1/docs/examples/apache/apache-fcgi.conf0000644000175000017500000000047311743150153023105 0ustar stefanstefan00000000000000 Alias /fookebox /etc/fookebox/fookebox.fcgi RedirectMatch ^/fookebox$ /fookebox/ Options +ExecCGI Order deny,allow Allow from all Order deny,allow Deny from all Allow from localhost fookebox-0.6.1/docs/examples/apache/apache-wsgi.conf0000644000175000017500000000050011743153532023141 0ustar stefanstefan00000000000000 WSGIScriptAlias /fookebox /etc/fookebox/fookebox.wsgi WSGIDaemonProcess fookebox WSGIProcessGroup fookebox Order deny,allow Allow from all Order deny,allow Deny from all Allow from localhost fookebox-0.6.1/docs/examples/apache/fookebox.fcgi0000755000175000017500000000051611743150150022553 0ustar stefanstefan00000000000000#!/usr/bin/python # # requires the python flup module BASE_PATH = '/usr/share/fookebox' APP_CONFIG = '/etc/fookebox/config.ini' import sys if BASE_PATH not in sys.path: sys.path.append(BASE_PATH) from paste.deploy import loadapp app = loadapp('config:' + APP_CONFIG) from flup.server.fcgi import WSGIServer WSGIServer(app).run() fookebox-0.6.1/docs/examples/apache/fookebox.wsgi0000644000175000017500000000034111743150152022607 0ustar stefanstefan00000000000000BASE_PATH = '/usr/share/fookebox' APP_CONFIG = '/etc/fookebox/config.ini' import sys if BASE_PATH not in sys.path: sys.path.append(BASE_PATH) from paste.deploy import loadapp application = loadapp('config:' + APP_CONFIG) fookebox-0.6.1/docs/changes.txt0000644000175000017500000001030111743150145017211 0ustar stefanstefan00000000000000#summary ChangeLog for fookebox #labels Featured,Phase-Deploy == 0.6.1 (17 Apr 2012) == * Use python's json module instead of simplejson * Use mpd's "setvol" command instead of the deprecated "volume". Thanks to Jan Hruban for reporting this and sending a patch. * Skipping the current song would lead to interruptions in the audio stream if it was the last entry in the playlist. Fixed this by auto-queuing before skipping tracks. Thanks to Artem Savkov for noticing this and providing a patch. * Pulsate the time display when playback is paused. * Added an example configuration file for using fookebox through fcgi/flup == 0.6.0 (30 Apr 2011) == * Cleaned up the configuration options regarding cover art * Show a proper error message when the connection to MPD fails * Properly report errors during template rendering * Show artists in search result pages again * Added an option to hide the credits * Tracks with artist featuring others no longer trigger compilation mode * Genre/artist links can now be opened in a new browser tab * (Hopefully) fixed an encoding issue that would cause errors in search * Reduced the number of HTTP requests when the current song has no cover art * Generally reduced the number of requests to mpd * Fixed an issue that could cause errors when modwsgi reloaded the application * Rewrote/reorganized most of the javascript code * Added special CSS for mobile devices * Fixed compatibility with python-mpd 0.3.0 * Updated the included libraries to scriptaculous 1.9.0 / prototype 1.7 * Updated example config files for apache * Added a proper favicon * Some API changes == 0.5.2 (02 Dec 2010) == * Use mpd's "consume" command if available (versions >= 0.15) * Added support for in-directory cover art * Cover art can now be cached * Auto-queuing can now be limited to a specific genre * Albums are now properly sorted on the search result page * The current track's time display should be updated much more smoothly now == 0.5.1 (07 Jul 2010) == * Catch some more exceptions and properly close all connections if they occur * Added classifiers to setup.py * fookebox' version information is now read from the package meta data == 0.5.0 (01 Jul 2010) == * Re-implemented fookebox in Python (using Pylons) * Added support for rhythmbox' covert art file naming scheme * Added German translation == 0.4.3 (21 Jun 2010) == * Fixed a possible race-condition where a song would get played twice in a row * Synchronized javascript with upcoming 0.5 release * Artist, genre names and cover paths are now base64 encoded == 0.4.2 (24 May 2010) == * Database rebuild was broken, fixed * Fixed typo in README == 0.4.1 (23 Mar 2010) == * Thanks to Gavin Cameron for his contributions * Can now pick the auto-queued songs from a predefined playlist * Some internal code cleanup * Changed license to GPLv3 * Set the default time zone to UTC to get PHP to shut up (Gavin) * Replaced calls to split (deprecated) with explode (Gavin) * Added support for cover art for compilations (Gavin again, also: see README) * Added the ability to auto queue songs before the playlist is empty == 0.4.0 (4 Feb 2010) == * Fixed queuing of full albums * Added support for cover art * Minor CSS changes * Some internal code cleanup * We now need at least PHP 5.1.0 * Updated smarty to version 2.6.26 * Updated prototype to version 1.6.1 * Updated scriptaculous to version 1.8.3 == 0.3.0 (11 May 2009) == * Dropped php4 compatibility * Albums in search results are now automatically expanded * Added support for forward/back buttons * Fixed filename/any search * Updated smarty * Code cleanup == 0.2.0 (1 Dec 2008) == * Added the ability to auto-queue songs when the playlist gets empty * Fixed some issues when running fookebox in a sub directory * Switched to using prototype for JSON data transport * Updated smarty, scriptaculous and prototype to their latest versions == 0.1.1 (12 Jun 2008) == * Made the right part scrollable without scrolling the whole window * Made sure all clients are informed on playlist updates * Updated smarty to version 2.6.19 * Updated the JavaScript JSON library * Minor documentation updates == 0.1.0 (11 Jun 2008) == * Initial public release fookebox-0.6.1/docs/config.txt0000644000175000017500000001561011743150144017055 0ustar stefanstefan00000000000000#summary ReadMe for fookebox #labels Featured,Phase-Deploy fookebox is a jukebox-style web-frontend to mpd. It offers the following jukebox features: * Browse your music library by artist or genre * Add songs to the play list (obviously) * Limit the queue size (see note below) * Add whole albums to the play list (optional) * Remove songs from the play list (optional) * Search for artists/albums/titles/files (optional) * Control mpd (optional) In addition to that, fookebox has a second frontend intended for a projector showing the currently playing song as well as the first queue entry. Also, in case you are organizing an event where you only want to use the jukebox between other events (live bands, DJs) fookebox can be told so and display that information on the secondary frontend (details: see below). == What you need == In order to run fookebox you will need: * Python (at least version 2.6) * MPD (at least version 0.15) * Some web server (eg. apache) with WSGI support * Pylons (http://pylonshq.com/) == How to set it up == === web server === You can use the provided apache-wsgi.conf and fookebox.wsgi to run fookebox through apache's mod_wsgi or apache-fcgi.conf and fookebox.fcgi if you prefer mod_fcgi with python's flup module. === fookebox === Have a look at README.txt for general information on how to install and configure fookebox. For details on the config options, see below. Also, make sure that your webserver can write to the data/templates directory. == Detailed setup == You can tweak the following fookebox-specific settings: * mpd_host: The host name of the machine running mpd (eg. localhost) * mpd_port: The port mpd is running on (6600 by default) * mpd_pass: The password required to access mpd * site_name: A name for your site (eg. 'my home') * max_queue_length: The maximum queue length (see below for details) * auto_queue: Whether to play random songs when the queue gets empty (see below) * auto_queue_genre: Genre to pick auto-queued songs from * auto_queue_playlist: Playlist to play when idle (see below) * auto_queue_random: (see below) * show_search_tab: Enable/disable 'search' tab (eg. for mouse-only jukeboxes) * enable_controls: Enable/disable mpd control (disable on public jukeboxes) * enable_song_removal: Whether to allow the user to remove songs in the queue * enable_queue_album: Enables/disables the ability to queue whole albums * find_over_search: Whether to use mpd's 'find' or 'search' (see below) * music_base_path: Path that contains your music (see below) * hide_credits: Set to true if you want to hide the credits in the client view * show_cover_art: Whether to show cover art (enabled by default) * cache_cover_art: Whether to cache cover art (disabled by default) * album_cover_path: Path that contains album cover art (see below) == Secondary frontend == If you don't care about projectors and stuff, just ignore this section. It's purely optional. If you point your browser to yourfookeboxurl/program you will see fookebox' secondary front end which is intended to be projected to a wall / shown on a screen without user interaction. It will not only inform users about the currently playing and the next song but in case you're using fookebox at some kind of party, this front end will allow you to inform your users about any other events that might be coming up (eg. a live band or a DJ). To enter your event's schedule, point your web browser to yourfookeboxurl/schedule. == Additional notes == === Queue length === It's important to note that while fookebox does try to enforce your mpd queue length value, people who click fast enough might be able to bypass that check so make sure to set your mpd's max_playlist_length accordingly (note that mpd's count includes the song which is being played so if you want 3 queue positions, set max_playlist_length to 4). === Cover art === Fookebox can display cover art for your music. In order to do that, set show_cover_art to true. If enabled, the following mechanisms are used to find cover art: * If set, search album_cover_path for files named - "Artist-Album.jpg", replace all of '\/:<>?*|' with underscores (_) - Retry as compilation (see below) - "Artist - Album.jpg", replace slashes (/) with underscores (_) - Retry as compilation (see below) * If music_base_path is set, look for JPEG files in the directory where the album's first track is located (see below) In case no cover art is found for an album, fookebox tries to be smart and assumes this is a compilation. The 'compliations_name' ('Various Artists' by default) option determines what artist name is used for compilations. If you want to provide a cover for a compilation called 'My Best Music', the corresponding file would be called 'Various Artists-My Best Music.jpg'. If you would like fookebox to look for cover art in the same directory where you store you music files, set 'music_base_path' accordingly. In order for this to work, you will need to have the music/cover files on the same machine where fookebox is running (if that's not the case, consider mounting the music directory remotely, eg. using NFS). fookebox will use any JPEG file in that directory, giving priority to files named cover.jpg, album.jpg or front.jpg (.jpeg is acceptable too). File names are case-insensitive, so whether you name your cover art front.jpg or ALBum.jpeg doesn't matter. On systems where disk access is expensive and generally on slower hardware you might want to enable 'cache_cover_art'. This causes fookebox to remember the result of its search for an album's cover art for 5 minutes. The only way to clear the cache (i.e. make fookebox forget the cached information) is to restart fookebox (as in, restart apache or whatever web server you are using). Note that your covers need to be JPEG files and they will get scaled to a width of 100 pixels. === Find or search? === When an artist/genre/album has been clicked, you can decide whether we tell mpd to 'find' that item or to 'search' for it. The difference is that 'find' only returns exact matches while 'search' also matches substrings (eg. if you click on 'Air', 'find' will only return songs by 'Air' while 'search' will also include 'Air feat. Joe Random' and 'Fair play'). === Auto-queuing === If you enable 'auto_queue', fookebox will automatically pick a completely random song from your collection whenever there is nothing else to play (by setting 'auto_queue_time_left' you can define how many seconds before the current song ends this happens - useful for large music collections on slow machines where auto-queuing takes a few seconds). If you would like to have a predefined set of songs to be played instead, use 'auto_queue_playlist' to specify an mpd playlist. If you want the song selection to be random but limited to a set of songs, define a playlist as explained before and set 'auto_queue_random' to true. You can also 'auto_queue_genre' in order to limit auto-playing to a specific genre. fookebox-0.6.1/docs/i18n.txt0000644000175000017500000000067511556665236016413 0ustar stefanstefan00000000000000This document is mostly for myself, in order to remember the i18n-related commands. Anyway. To update the translations, do: python setup.py extract_messages (needs python-pybabel to be installed) python setup.py update_catalog -l de python setup.py compile_catalog To add a new translation, do: python setup.py init_catalog -l es See http://wiki.pylonshq.com/display/pylonsdocs/Internationalization+and+Localization for more details. fookebox-0.6.1/fookebox/0000755000175000017500000000000011743153607015737 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/config/0000755000175000017500000000000011743153607017204 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/config/__init__.py0000644000175000017500000000000011525403055021274 0ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/config/deployment.ini_tmpl0000644000175000017500000000530711525403055023117 0ustar stefanstefan00000000000000# # fookebox - Pylons configuration # # The %(here)s variable will be replaced with the parent directory of this file # [DEFAULT] debug = false email_to = you@yourdomain.com smtp_server = localhost error_email_from = paste@localhost [server:main] use = egg:Paste#http host = 0.0.0.0 port = 5000 [app:main] use = egg:fookebox #lang = de full_stack = true static_files = true cache_dir = %(here)s/data sqlalchemy.url = sqlite:///%(cache_dir)s/fookebox.sqlite beaker.session.key = fookebox beaker.session.secret = ${app_instance_secret} app_instance_uuid = ${app_instance_uuid} #site_name = fookebox #mpd_host = localhost #mpd_port = 6600 #mpd_pass = password # NOTE: See the README for details on this #max_queue_length = 4 # automatically queue a random song when the playlist gets empty #auto_queue = true # genre to use for auto_queue #auto_queue_genre = Comedy # do auto-queuing before the playlist is empty [seconds] (0 to disable) #auto_queue_time_left = 1 # if you want the 'random' song to come from a pre-defined (mpd) playlist # you can set the playlist's name here #auto_queue_playlist = idle # pick a random song from the idle playlist (see README) #auto_queue_random = false # show the full-text search tab #show_search_tab = true # enable mpd controls #enable_controls = true # allow users to remove songs from the queue #enable_song_removal = true # allow users to queue a full album with one click #enable_queue_album = true # be anal about artist/album names (see README) #find_over_search = false # directory with cover art #album_cover_path = /home/stefan/.cache/rhythmbox/covers/ # directory where the music can be found (used for in-directory cover art) #music_base_path = /var/lib/mpd/music/ # what to use as artist name when looking for compilations' cover art? #compliations_name = Various Artists # if you would like cover art to be cached, set this to true #cache_cover_art = false # If you'd like to fine-tune the individual locations of the cache data dirs # for the Cache data, or the Session saves, un-comment the desired settings # here: #beaker.cache.data_dir = %(here)s/data/cache #beaker.session.data_dir = %(here)s/data/sessions # WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* # Debug mode will enable the interactive debugging tool, allowing ANYONE to # execute malicious code after an exception is raised. set debug = false # Logging configuration [loggers] keys = root [handlers] keys = console [formatters] keys = generic [logger_root] level = INFO handlers = console [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(asctime)s %(levelname)-5.5s [%(name)s] [%(threadName)s] %(message)s fookebox-0.6.1/fookebox/config/environment.py0000644000175000017500000000551411556607055022132 0ustar stefanstefan00000000000000"""Pylons environment configuration""" import os from mako.lookup import TemplateLookup from pylons.configuration import PylonsConfig from pylons.error import handle_mako_error from paste.deploy.converters import asbool from sqlalchemy import engine_from_config from sqlalchemy.pool import NullPool from fookebox.model import init_model import fookebox.lib.app_globals as app_globals import fookebox.lib.helpers from fookebox.config.routing import make_map def load_environment(global_conf, app_conf): """Configure the Pylons environment via the ``pylons.config`` object """ config = PylonsConfig() # Pylons paths root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templates=[os.path.join(root, 'templates')]) # Initialize config with the basic options config.init_app(global_conf, app_conf, package='fookebox', paths=paths) config['routes.map'] = make_map(config) config['pylons.app_globals'] = app_globals.Globals(config) config['pylons.h'] = fookebox.lib.helpers # Setup cache object as early as possible import pylons pylons.cache._push_object(config['pylons.app_globals'].cache) # Create the database engine engine = engine_from_config(config, 'sqlalchemy.', poolclass=NullPool) init_model(engine) # Create the Mako TemplateLookup, with the default auto-escaping config['pylons.app_globals'].mako_lookup = TemplateLookup( directories=paths['templates'], error_handler=handle_mako_error, module_directory=os.path.join(app_conf['cache_dir'], 'templates'), input_encoding='utf-8', default_filters=['escape'], imports=['from webhelpers.html import escape']) import pkg_resources config['version'] = pkg_resources.get_distribution("fookebox").version # CONFIGURATION OPTIONS HERE (note: all config options will override # any Pylons config options) default_strings = { 'site_name': 'fookebox', 'mpd_host': 'localhost', 'compliations_name': 'Various Artists', } default_ints = { 'mpd_port': 6600, 'max_queue_length': 4, 'auto_queue_time_left': 1, } default_bools = { 'auto_queue': True, 'auto_queue_random': False, 'show_search_tab': True, 'enable_controls': True, 'enable_song_removal': True, 'enable_queue_album': True, 'find_over_search': False, 'cache_cover_art': False, 'hide_credits': False, 'show_cover_art': True, } for key in default_strings: if key not in config: config[key] = default_strings[key] for key in default_ints: if key in config and config[key].isdigit(): config[key] = int(config[key]) else: config[key] = default_ints[key] for key in default_bools: if key in config: try: config[key] = asbool(config[key]) except: config[key] = default_bools[key] else: config[key] = default_bools[key] return config fookebox-0.6.1/fookebox/config/middleware.py0000644000175000017500000000456211525403055021673 0ustar stefanstefan00000000000000"""Pylons middleware initialization""" from beaker.middleware import SessionMiddleware from paste.cascade import Cascade from paste.registry import RegistryManager from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool from pylons.middleware import ErrorHandler, StatusCodeRedirect from pylons.wsgiapp import PylonsApp from routes.middleware import RoutesMiddleware from fookebox.config.environment import load_environment def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``static_files`` Whether this application serves its own static files; disable when another web server is responsible for serving them. ``app_conf`` The application's local configuration. Normally specified in the [app:] section of the Paste ini file (where defaults to main). """ # Configure the Pylons environment config = load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp(config=config) # Routing/Session Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app, [400, 404, 409, 500]) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 409, 500]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) app.config = config return app fookebox-0.6.1/fookebox/config/routing.py0000644000175000017500000000324511556607056021255 0ustar stefanstefan00000000000000"""Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from routes import Mapper def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') map.connect('/program', controller='program', action='index') map.connect('/schedule/{action}', controller='program') map.connect('/schedule', controller='program', action='edit') map.connect('/mobile', controller='jukebox', action='mobile') map.connect('/', controller='jukebox', action='index') map.connect('/{action}', controller='jukebox') map.connect('/findcover', controller='jukebox', action='findcover') map.connect('/cover/{artist}/{album}', controller='jukebox', action='cover') map.connect('/genre/{genreBase64}', controller='jukebox', action='genre') map.connect('/genre/', controller='jukebox', action='genre') map.connect('/artist/{artistBase64}', controller='jukebox', action='artist') map.connect('/artist/', controller='jukebox', action='artist') return map fookebox-0.6.1/fookebox/controllers/0000755000175000017500000000000011743153607020305 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/controllers/__init__.py0000644000175000017500000000000011525403055022375 0ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/controllers/error.py0000644000175000017500000000472111525403201021776 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import cgi import logging from paste.urlparser import PkgResourcesParser from pylons import request from pylons.controllers.util import forward from pylons.middleware import error_document_template from webhelpers.html.builder import literal from fookebox.lib.base import BaseController log = logging.getLogger(__name__) class ErrorController(BaseController): """Generates error documents as and when they are required. The ErrorDocuments middleware forwards to ErrorController when error related status codes are returned from the application. This behaviour can be altered by changing the parameters to the ErrorDocuments middleware in your config/middleware.py file. """ def document(self): """Render the error document""" resp = request.environ.get('pylons.original_response') content = literal(resp.body) or cgi.escape(request.GET.get( 'message', '')) accept = request.headers.get('accept') error = request.environ.get('pylons.controller.exception') if accept == 'application/json' and error: content = error.detail elif accept == 'application/json': content = "ERROR" page = error_document_template % \ dict(prefix=request.environ.get('SCRIPT_NAME', ''), code=cgi.escape(request.GET.get('code', str(resp.status_int))), message=content) return page def img(self, id): """Serve Pylons' stock images""" return self._serve_file('/'.join(['media/img', id])) def style(self, id): """Serve Pylons' stock stylesheets""" return self._serve_file('/'.join(['media/style', id])) def _serve_file(self, path): """Call Paste's FileApp (a WSGI application) to serve the file at the specified path """ request.environ['PATH_INFO'] = '/%s' % path return forward(PkgResourcesParser('pylons', 'pylons')) fookebox-0.6.1/fookebox/controllers/jukebox.py0000644000175000017500000002073411743150161022324 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys import json import base64 import socket import logging from pylons import config, cache, request, response from pylons.decorators import jsonify, rest from pylons.controllers.util import abort from pylons.i18n.translation import _ from fookebox.lib.base import BaseController, render from fookebox.model.jukebox import Jukebox, QueueFull from fookebox.model.mpdconn import Album from fookebox.model.albumart import AlbumArt logging.basicConfig(level=logging.WARNING) log = logging.getLogger(__name__) class JukeboxController(BaseController): def __render(self, template, extra_vars): try: return render(template, extra_vars = extra_vars) except IOError: exctype, value = sys.exc_info()[:2] abort(500, value) def __search(self, where, what, forceSearch = False): log.debug("SEARCH: '%s' in '%s'" % (what, where)) jukebox = Jukebox() tracks = jukebox.search(where, what, forceSearch) jukebox.close() log.debug("SEARCH: found %d track(s)" % len(tracks)) return {'meta': {'what': what }, 'tracks': tracks} @rest.restrict('GET') def index(self): try: jukebox = Jukebox() except socket.error: log.error("Error on /index") return self.__render('/error.tpl', extra_vars={ 'error': 'Connection to MPD failed'}) except: log.error("Error on /index") exctype, value = sys.exc_info()[:2] return self.__render('/error.tpl', extra_vars={ 'error': value}) artists = jukebox.getArtists() genres = jukebox.getGenres() jukebox.close() user_agent = request.environ.get('HTTP_USER_AGENT') return self.__render('/client.tpl', extra_vars={ 'genres': genres, 'artists': artists, 'config': config, 'mobile': 'mobile' in user_agent.lower(), }) @rest.restrict('GET') @jsonify def status(self): jukebox = Jukebox() try: queueLength = jukebox.getQueueLength() enabled = jukebox.isEnabled() timeLeft = jukebox.timeLeft() except: log.error("Could not read status") jukebox.close() exctype, value = sys.exc_info()[:2] abort(500, value) if (config.get('auto_queue') and queueLength == 0 and enabled and timeLeft <= config.get('auto_queue_time_left')): try: jukebox.autoQueue() except: log.error("Auto-queue failed") jukebox.close() raise try: track = jukebox.getCurrentSong() except: log.error('Failed to get the current song') abort(500, _('Failed to get the current song')) finally: jukebox.close() data = { 'queueLength': queueLength, 'jukebox': enabled } if track: songPos = int(track.timePassed) songTime = track.time total = "%02d:%02d" % (songTime / 60, songTime % 60) position = "%02d:%02d" % (songPos / 60, songPos % 60) album = Album(track.artist, track.album) album.add(track) data['artist'] = track.artist data['track'] = track.title data['album'] = track.album data['has_cover'] = album.hasCover() data['cover_uri'] = album.getCoverURI() data['timePassed'] = position data['timeTotal'] = total data['playing'] = jukebox.isPlaying() return data @rest.restrict('POST') def enqueue(self): try: data = json.load(request.environ['wsgi.input']) except ValueError: log.error('ENQUEUE: Could not parse JSON data') abort(400, _('Malformed JSON data')) files = data.get('files') if not (files and len(files) > 0): log.error('ENQUEUE: No files specified') abort(400, _('No files specified')) jukebox = Jukebox() for file in files: if not file: log.error('ENQUEUE: Skipping empty file') abort(400, _('Missing file name')) try: jukebox.queue(file.encode('utf8')) except QueueFull: jukebox.close() log.error('ENQUEUE: Full, aborting') abort(409, _('The queue is full')) jukebox.close() abort(204) # no content @rest.dispatch_on(POST='enqueue') @rest.restrict('GET') @jsonify def queue(self): jukebox = Jukebox() items = jukebox.getPlaylist() jukebox.close() return {'queue': items[1:]} @rest.restrict('GET') @jsonify def genre(self, genreBase64=''): try: genre = genreBase64.decode('base64') except: log.error("GENRE: Failed to decode base64 data: %s" % genreBase64) abort(400, _('Malformed request')) return self.__search('genre', genre) @rest.restrict('GET') @jsonify def artist(self, artistBase64=''): try: artist = artistBase64.decode('base64') except: log.error("ARTIST: Failed to decode base64 data: %s" % artistBase64) abort(400, _('Malformed request')) return self.__search('artist', artist) @rest.restrict('POST') @jsonify def search(self): try: data = json.load(request.environ['wsgi.input']) except ValueError: log.error('SEARCH: Could not parse JSON data') abort(400, _('Malformed JSON data')) what = data.get('what') where = data.get('where') if not where: log.error("SEARCH: Incomplete JSON data") abort(400, _('Malformed request')) forceSearch = 'forceSearch' in data and data['forceSearch'] return self.__search(where, what.encode('utf8'), forceSearch) @rest.restrict('POST') def remove(self): if not config.get('enable_song_removal'): log.error("REMOVE: Disabled") abort(403, _('Song removal disabled')) try: data = json.load(request.environ['wsgi.input']) except ValueError: log.error('REMOVE: Could not parse JSON data') abort(400, _('Malformed JSON data')) id = data.get('id') if not id: log.error('REMOVE: No id specified in JSON data') abort(400, _('Malformed request')) jukebox = Jukebox() jukebox.remove(id) jukebox.close() abort(204) # no content @rest.restrict('POST') def control(self): if not config.get('enable_controls'): log.error('CONTROL: Disabled') abort(403, _('Controls disabled')) try: data = json.load(request.environ['wsgi.input']) except ValueError: log.error('CONTROL: Could not parse JSON data') abort(400, _('Malformed JSON data')) action = data.get('action') if not action: log.error('CONTROL: No action specified in JSON data') abort(400, _('Malformed request')) log.debug('CONTROL: Action=%s' % action) jukebox = Jukebox() commands = { 'play': jukebox.play, 'pause': jukebox.pause, 'prev': jukebox.previous, 'next': jukebox.next, 'voldown': jukebox.volumeDown, 'volup': jukebox.volumeUp, 'rebuild': jukebox.refreshDB, } if action not in commands: log.error('CONTROL: Invalid command') jukebox.close() abort(400, _('Invalid command')) try: commands[action]() except: log.error('Command %s failed' % action) abort(500, _('Command failed')) finally: jukebox.close() abort(204) # no content @rest.restrict('POST') @jsonify def findcover(self): try: data = json.load(request.environ['wsgi.input']) except ValueError: log.error('FINDCOVER: Could not parse JSON data') abort(400, _('Malformed JSON data')) artist = data.get('artist') album = data.get('album') album = Album(artist, album) if album.hasCover(): return {'uri': album.getCoverURI()} abort(404, 'No cover') @rest.restrict('GET') def cover(self, artist, album): try: artist = base64.urlsafe_b64decode(artist.encode('utf8')) album = base64.urlsafe_b64decode(album.encode('utf8')) except: log.error("COVER: Failed to decode base64 data") abort(400, _('Malformed base64 encoding')) album = Album(artist.decode('utf8'), album.decode('utf8')) art = AlbumArt(album) path = art.get() if not path: log.error("COVER: missing for %s/%s" % (artist, album.name)) abort(404, _('No cover found for this album')) file = open(path.encode('utf8'), 'r') data = file.read() file.close() response.headers['content-type'] = 'image/jpeg' return data @rest.restrict('GET') def disabled(self): return self.__render('/disabled.tpl', extra_vars={ 'config': config, 'base_url': request.url.replace('disabled', ''), }) fookebox-0.6.1/fookebox/controllers/program.py0000644000175000017500000001035711743150160022323 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2012 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import logging import json from datetime import time, datetime from pylons import request, response, config, app_globals as g from pylons.controllers.util import abort from pylons.decorators import jsonify, rest from fookebox.lib.base import BaseController, render from fookebox.model import meta from fookebox.model.jukebox import Jukebox from fookebox.model.mpdconn import Track from fookebox.model.schedule import Event, EVENT_TYPE_JUKEBOX log = logging.getLogger(__name__) class ProgramController(BaseController): @rest.restrict('GET') def index(self): jukebox = Jukebox() artists = jukebox.getArtists() genres = jukebox.getGenres() jukebox.close() return render('/program.tpl') @rest.restrict('GET') @jsonify def status(self): jukebox = Jukebox() event = jukebox.getCurrentEvent() next = jukebox.getNextEvent() now = datetime.now() if now.second % 2 > 0: format = "%H %M" else: format = "%H:%M" event = jukebox.getCurrentEvent() currentEvent = { 'type': event.type, 'title': event.name } if event.type == EVENT_TYPE_JUKEBOX: track = jukebox.getCurrentSong() if (track.artist == Track.NO_ARTIST and track.title == Track.NO_TITLE): track.artist = '' track.title = '' currentEvent['tracks'] = [{ 'artist': track.artist, 'title': track.title, }] playlist = jukebox.getPlaylist() if len(playlist) > 1: track = Track() track.load(playlist[1]) currentEvent['tracks'].append({ 'artist': track.artist, 'title': track.title, }) events = {'current': currentEvent} next = jukebox.getNextEvent() jukebox.close() if next: events['next'] = { 'type': next.type, 'title': next.name, 'time': next.time.strftime("%H:%M") } return { 'events': events, 'time': now.strftime(format), } @rest.restrict('POST') def _edit_post(self): name = request.params['name'] type = int(request.params['type']) hour = request.params['hour'] minute = request.params['minute'] dateTime = datetime.strptime("%s:%s" % (hour, minute), "%H:%M") if 'id' in request.params: id = request.params['id'] Event.update(id, name, type, dateTime.time()) else: Event.add(name, type, dateTime.time()) return render('/program-edit.tpl', { 'events': Event.all(), 'current': Event.getCurrent() }) @rest.dispatch_on(POST='_edit_post') @rest.restrict('GET') def edit(self): #if request.method == 'POST': # pass event_q = meta.Session.query(Event) return render('/program-edit.tpl', { 'events': Event.all(), 'current': Event.getCurrent(), 'edit': int(request.params.get('edit', 0)) }) @rest.restrict('POST') def current(self): try: post = json.load(request.environ['wsgi.input']) except ValueError: log.error("QUEUE: Could not parse JSON data") abort(400, 'Malformed JSON data') id = post.get('id') g.eventID = int(id) abort(204) # no content @rest.restrict('POST') def delete(self): try: post = json.load(request.environ['wsgi.input']) except ValueError: log.error("QUEUE: Could not parse JSON data") abort(400, 'Malformed JSON data') id = post.get('id') Event.delete(int(id)) abort(204) # no content @rest.restrict('POST') def move(self): try: post = json.load(request.environ['wsgi.input']) except ValueError: log.error("QUEUE: Could not parse JSON data") abort(400, 'Malformed JSON data') id = post.get('id') direction = post.get('direction') if direction == 'up': Event.up(id) else: Event.down(id) abort(204) # no content fookebox-0.6.1/fookebox/i18n/0000755000175000017500000000000011743153607016516 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/i18n/de/0000755000175000017500000000000011743153607017106 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/i18n/de/LC_MESSAGES/0000755000175000017500000000000011743153607020673 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/i18n/de/LC_MESSAGES/fookebox.mo0000644000175000017500000000371111556665241023052 0ustar stefanstefan00000000000000$<\]djnu}#5S frx    %  !* :DK^u ) 4GM]el (none)AlbumAnyArtistArtistsCommand failedControls disabledErrorFailed to get the current songFilenameGenresInvalid commandMalformed JSON dataMalformed base64 encodingMalformed requestMissing file nameNo cover found for this albumNo files specifiedNow playingQueueSearchSong removal disabledThe queue is fullTitleVarious Artistsbackcoming upenjoy our live artistnextnow playingpauseplayrebuild databasevolume downvolume upProject-Id-Version: fookebox 0.5.0 Report-Msgid-Bugs-To: stefan@ott.net POT-Creation-Date: 2010-06-30 06:22+0200 PO-Revision-Date: 2011-04-30 03:40+0200 Last-Translator: Stefan Ott Language-Team: de Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel 0.9.4 (kein)AlbumBeliebigKünstlerKünstlerFehlgeschlagenSteuerelemente wurden deaktiviertFehlerAktueller Song konnte nicht geladen werdenDateinameGenresUngültiger BefehlFehlerhafte JSON-DatenFehlerhaftes base64-EncodingFehlerhafte AnfrageDateiname fehltKein Albumcover gefundenKeine Dateien angegebenAktueller SongWarteschlangeSucheDas Entfernen von Songs wurde deaktiviertDie Queue ist vollTitelVarious Artistszurückdanachenjoy our live artistweiterzur zeitpausewiedergabedatenbank aktualisierenleiserlauterfookebox-0.6.1/fookebox/i18n/de/LC_MESSAGES/fookebox.po0000644000175000017500000000740611556665242023063 0ustar stefanstefan00000000000000# German translations for fookebox. # Copyright (C) 2010 Stefan Ott # This file is distributed under the same license as the fookebox project. # Stefan Ott , 2010. # msgid "" msgstr "" "Project-Id-Version: fookebox 0.5.0\n" "Report-Msgid-Bugs-To: stefan@ott.net\n" "POT-Creation-Date: 2010-06-30 06:22+0200\n" "PO-Revision-Date: 2011-04-30 03:36+0200\n" "Last-Translator: Stefan Ott \n" "Language-Team: de \n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 0.9.4\n" #: fookebox/controllers/jukebox.py:111 msgid "Failed to get the current song" msgstr "Aktueller Song konnte nicht geladen werden" #: fookebox/controllers/jukebox.py:146 fookebox/controllers/jukebox.py:213 #: fookebox/controllers/jukebox.py:303 msgid "Malformed JSON data" msgstr "Fehlerhafte JSON-Daten" #: fookebox/controllers/jukebox.py:152 msgid "No files specified" msgstr "Keine Dateien angegeben" #: fookebox/controllers/jukebox.py:159 msgid "Missing file name" msgstr "Dateiname fehlt" #: fookebox/controllers/jukebox.py:166 msgid "The queue is full" msgstr "Die Queue ist voll" #: fookebox/controllers/jukebox.py:190 fookebox/controllers/jukebox.py:202 #: fookebox/controllers/jukebox.py:220 fookebox/controllers/jukebox.py:242 #: fookebox/controllers/jukebox.py:266 msgid "Malformed request" msgstr "Fehlerhafte Anfrage" #: fookebox/controllers/jukebox.py:230 msgid "Song removal disabled" msgstr "Das Entfernen von Songs wurde deaktiviert" #: fookebox/controllers/jukebox.py:254 msgid "Controls disabled" msgstr "Steuerelemente wurden deaktiviert" #: fookebox/controllers/jukebox.py:284 msgid "Invalid command" msgstr "Ungültiger Befehl" #: fookebox/controllers/jukebox.py:290 msgid "Command failed" msgstr "Fehlgeschlagen" #: fookebox/controllers/jukebox.py:323 msgid "Malformed base64 encoding" msgstr "Fehlerhaftes base64-Encoding" #: fookebox/controllers/jukebox.py:332 msgid "No cover found for this album" msgstr "Kein Albumcover gefunden" #: fookebox/model/mpdconn.py:93 msgid "Various Artists" msgstr "Various Artists" #: fookebox/templates/browse-menu.tpl:3 msgid "Artists" msgstr "Künstler" #: fookebox/templates/browse-menu.tpl:4 msgid "Genres" msgstr "Genres" #: fookebox/templates/browse-menu.tpl:6 msgid "Search" msgstr "Suche" #: fookebox/templates/browse-menu.tpl:33 fookebox/templates/browse-menu.tpl:48 msgid "(none)" msgstr "(kein)" #: fookebox/templates/browse-menu.tpl:56 msgid "Artist" msgstr "Künstler" #: fookebox/templates/browse-menu.tpl:57 msgid "Album" msgstr "Album" #: fookebox/templates/browse-menu.tpl:58 msgid "Title" msgstr "Titel" #: fookebox/templates/browse-menu.tpl:59 msgid "Filename" msgstr "Dateiname" #: fookebox/templates/browse-menu.tpl:60 msgid "Any" msgstr "Beliebig" #: fookebox/templates/disabled.tpl:9 msgid "enjoy our live artist" msgstr "" #: fookebox/templates/error.tpl:8 msgid "Error" msgstr "Fehler" #: fookebox/templates/playing.tpl:2 msgid "Now playing" msgstr "Aktueller Song" #: fookebox/templates/playing.tpl:9 msgid "back" msgstr "zurück" #: fookebox/templates/playing.tpl:10 msgid "pause" msgstr "pause" #: fookebox/templates/playing.tpl:11 msgid "play" msgstr "wiedergabe" #: fookebox/templates/playing.tpl:12 msgid "next" msgstr "weiter" #: fookebox/templates/playing.tpl:13 msgid "volume down" msgstr "leiser" #: fookebox/templates/playing.tpl:14 msgid "volume up" msgstr "lauter" #: fookebox/templates/playing.tpl:15 msgid "rebuild database" msgstr "datenbank aktualisieren" #: fookebox/templates/playlist.tpl:2 msgid "Queue" msgstr "Warteschlange" #: fookebox/templates/program.tpl:8 msgid "now playing" msgstr "zur zeit" #: fookebox/templates/program.tpl:17 msgid "coming up" msgstr "danach" fookebox-0.6.1/fookebox/i18n/fookebox.pot0000644000175000017500000000640011556665243021064 0ustar stefanstefan00000000000000# Translations template for fookebox. # Copyright (C) 2011 ORGANIZATION # This file is distributed under the same license as the fookebox project. # FIRST AUTHOR , 2011. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: fookebox 0.6.0\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2011-04-30 03:36+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 0.9.4\n" #: fookebox/controllers/jukebox.py:111 msgid "Failed to get the current song" msgstr "" #: fookebox/controllers/jukebox.py:146 fookebox/controllers/jukebox.py:213 #: fookebox/controllers/jukebox.py:303 msgid "Malformed JSON data" msgstr "" #: fookebox/controllers/jukebox.py:152 msgid "No files specified" msgstr "" #: fookebox/controllers/jukebox.py:159 msgid "Missing file name" msgstr "" #: fookebox/controllers/jukebox.py:166 msgid "The queue is full" msgstr "" #: fookebox/controllers/jukebox.py:190 fookebox/controllers/jukebox.py:202 #: fookebox/controllers/jukebox.py:220 fookebox/controllers/jukebox.py:242 #: fookebox/controllers/jukebox.py:266 msgid "Malformed request" msgstr "" #: fookebox/controllers/jukebox.py:230 msgid "Song removal disabled" msgstr "" #: fookebox/controllers/jukebox.py:254 msgid "Controls disabled" msgstr "" #: fookebox/controllers/jukebox.py:284 msgid "Invalid command" msgstr "" #: fookebox/controllers/jukebox.py:290 msgid "Command failed" msgstr "" #: fookebox/controllers/jukebox.py:323 msgid "Malformed base64 encoding" msgstr "" #: fookebox/controllers/jukebox.py:332 msgid "No cover found for this album" msgstr "" #: fookebox/model/mpdconn.py:93 msgid "Various Artists" msgstr "" #: fookebox/templates/browse-menu.tpl:3 msgid "Artists" msgstr "" #: fookebox/templates/browse-menu.tpl:4 msgid "Genres" msgstr "" #: fookebox/templates/browse-menu.tpl:6 msgid "Search" msgstr "" #: fookebox/templates/browse-menu.tpl:33 fookebox/templates/browse-menu.tpl:48 msgid "(none)" msgstr "" #: fookebox/templates/browse-menu.tpl:56 msgid "Artist" msgstr "" #: fookebox/templates/browse-menu.tpl:57 msgid "Album" msgstr "" #: fookebox/templates/browse-menu.tpl:58 msgid "Title" msgstr "" #: fookebox/templates/browse-menu.tpl:59 msgid "Filename" msgstr "" #: fookebox/templates/browse-menu.tpl:60 msgid "Any" msgstr "" #: fookebox/templates/disabled.tpl:9 msgid "enjoy our live artist" msgstr "" #: fookebox/templates/error.tpl:8 msgid "Error" msgstr "" #: fookebox/templates/playing.tpl:2 msgid "Now playing" msgstr "" #: fookebox/templates/playing.tpl:9 msgid "back" msgstr "" #: fookebox/templates/playing.tpl:10 msgid "pause" msgstr "" #: fookebox/templates/playing.tpl:11 msgid "play" msgstr "" #: fookebox/templates/playing.tpl:12 msgid "next" msgstr "" #: fookebox/templates/playing.tpl:13 msgid "volume down" msgstr "" #: fookebox/templates/playing.tpl:14 msgid "volume up" msgstr "" #: fookebox/templates/playing.tpl:15 msgid "rebuild database" msgstr "" #: fookebox/templates/playlist.tpl:2 msgid "Queue" msgstr "" #: fookebox/templates/program.tpl:8 msgid "now playing" msgstr "" #: fookebox/templates/program.tpl:17 msgid "coming up" msgstr "" fookebox-0.6.1/fookebox/lib/0000755000175000017500000000000011743153607016505 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/lib/__init__.py0000644000175000017500000000000011525403055020575 0ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/lib/app_globals.py0000644000175000017500000000103111525403171021325 0ustar stefanstefan00000000000000"""The application's Globals object""" from beaker.cache import CacheManager from beaker.util import parse_cache_config_options class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self, config): """One instance of Globals is created during application initialization and is available during requests via the 'app_globals' variable """ self.cache = CacheManager(**parse_cache_config_options(config)) self.eventID = None self.mpd = None fookebox-0.6.1/fookebox/lib/base.py0000644000175000017500000000113611525403055017763 0ustar stefanstefan00000000000000"""The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_mako as render from fookebox.model import meta class BaseController(WSGIController): def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] try: return WSGIController.__call__(self, environ, start_response) finally: meta.Session.remove() fookebox-0.6.1/fookebox/lib/helpers.py0000644000175000017500000000056511525403055020520 0ustar stefanstefan00000000000000"""Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as 'h'. """ # Import helpers as desired, or define your own, ie: #from webhelpers.html.tags import checkbox, password def event_type_name(event_type): names = ['Jukebox', 'Live band', 'DJ'] return names[event_type] fookebox-0.6.1/fookebox/lib/util.py0000644000175000017500000000176511556665251020052 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # copyright (c) 2007-2011 stefan ott. all rights reserved. # # this program is free software: you can redistribute it and/or modify # it under the terms of the gnu general public license as published by # the free software foundation, either version 3 of the license, or # (at your option) any later version. # # this program is distributed in the hope that it will be useful, # but without any warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. see the # gnu general public license for more details. # # you should have received a copy of the gnu general public license # along with this program. if not, see . import os class FileSystem(object): @staticmethod def exists(path): return os.path.exists(path.encode('utf8')) @staticmethod def isdir(path): return os.path.isdir(path.encode('utf8')) @staticmethod def listdir(path): return os.listdir(path.encode('utf8')) fookebox-0.6.1/fookebox/model/0000755000175000017500000000000011743153607017037 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/model/__init__.py0000644000175000017500000000061111525403055021137 0ustar stefanstefan00000000000000import sqlalchemy as sa from sqlalchemy import orm from fookebox.model import meta, schedule def init_model(engine): """Call me before using any of the tables or classes in the model.""" #sm = orm.sessionmaker(autoflush=True, autocommit=True, bind=engine) sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine) meta.engine = engine meta.Session = orm.scoped_session(sm) fookebox-0.6.1/fookebox/model/albumart.py0000644000175000017500000000630711556665250021232 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re import os import base64 import logging from datetime import datetime from threading import BoundedSemaphore from pylons import config, cache from fookebox.lib.util import FileSystem as fs log = logging.getLogger(__name__) class AlbumArt(object): def __init__(self, album): self.album = album def _getRockboxPath(self, compilation=False): pattern = re.compile('[\/:<>\?*|]') album = pattern.sub('_', self.album.name) if compilation: artist = pattern.sub('_', config.get( 'compliations_name')) else: artist = pattern.sub('_', self.album.artist) return "%s/%s-%s.jpg" % (config.get('album_cover_path'), artist, album) def _getRhythmboxPath(self, compilation=False): album = self.album.name.replace('/', '-') if compilation: artist = config.get('compliations_name').replace( '/', '-') else: artist = self.album.artist.replace('/', '-') return "%s/%s - %s.jpg" % (config.get('album_cover_path'), artist, album) def _getInDirCover(self): path_cache = cache.get_cache('album_path', type='memory') key = self.album.key() dirname = path_cache.get_value(key=key, createfunc=self.album.getPath, expiretime=60) if dirname == None: return None def best_image(x, y): pattern = '(cover|album|front)' if re.match(pattern, x, re.I): return x else: return y if not (fs.exists(dirname) and fs.isdir(dirname)): return None dir = fs.listdir(dirname) dir = filter(lambda x: x.endswith( ('jpg', 'JPG', 'jpeg', 'JPEG')), dir) if len(dir) < 1: return None bestmatch = reduce(best_image, dir) return os.path.join(dirname, bestmatch) def get(self): if config.get('cache_cover_art'): cover_path_cache = cache.get_cache('cover_path') song = "%s - %s" % (str(self.album.artist), str(self.album.name)) path = cover_path_cache.get_value(key=song, createfunc=self._getCover, expiretime=300) if path == None: cover_path_cache.remove_value(song) else: path = self._getCover() return path def _getCover(self): if not config.get('show_cover_art'): return None if config.get('album_cover_path'): path = self._getRockboxPath() if fs.exists(path): return path path = self._getRockboxPath(True) if fs.exists(path): return path path = self._getRhythmboxPath() if fs.exists(path): return path path = self._getRhythmboxPath(True) if fs.exists(path): return path if config.get('music_base_path'): return self._getInDirCover() return None fookebox-0.6.1/fookebox/model/jukebox.py0000644000175000017500000001206711743150156021062 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2012 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re import sys import random import logging from pylons import config, app_globals as g from mpdconn import * from schedule import Event, EVENT_TYPE_JUKEBOX log = logging.getLogger(__name__) class QueueFull(Exception): pass class Jukebox(object): client = None lastAutoQueued = -1 def __init__(self, mpd=None): self._connect(mpd) def _connect(self, to=None): if not to == None: self.client = to return mpd = MPD.get() self.client = mpd.getWorker() def close(self): self.client.release() def timeLeft(self): status = self.client.status() if 'time' not in status: return 0 (timePlayed, timeTotal) = status['time'].split(':') timeLeft = int(timeTotal) - int(timePlayed) return timeLeft def queue(self, file): log.info("Queued %s" % file) if self.getQueueLength() >= config.get('max_queue_length'): raise QueueFull() self.client.add(file) # Prevent (or reduce the probability of) a race-condition where # the auto-queue functionality adds a new song *after* the last # one stopped playing (which would re-play the previous song) if not self.isPlaying() and len(self.getPlaylist()) > 1: self.client.delete(0) self.client.play() def _autoQueueRandom(self): genre = config.get('auto_queue_genre') if genre: songs = self.client.search('Genre', str(genre)) else: songs = self.client.listall() if len(songs) < 1: return file = [] while 'file' not in file: # we might have to try several times in case we get # a directory instead of a file index = random.randrange(len(songs)) file = songs[index] self.queue(file['file']) def _autoQueuePlaylist(self, playlist): self.client.load(playlist) if len(playlist) < 1: return if config.get('auto_queue_random'): self.client.shuffle() playlist = self.client.playlist() song = playlist[0] else: playlist = self.client.playlist() index = (Jukebox.lastAutoQueued + 1) % len(playlist) song = playlist[index] Jukebox.lastAutoQueued += 1 self.client.clear() self.queue(song) log.debug(Jukebox.lastAutoQueued) def autoQueue(self): log.info("Auto-queuing") lock = Lock() if not lock.acquire(): return playlist = config.get('auto_queue_playlist') if playlist == None: self._autoQueueRandom() else: self._autoQueuePlaylist(playlist) lock.release() def search(self, where, what, forceSearch = False): if config.get('find_over_search') and not forceSearch: return self.client.find(where, what) return self.client.search(where, what) def getPlaylist(self): playlist = self.client.playlistinfo() return playlist def getGenres(self): genres = sorted(self.client.list('genre')) return [Genre(genre.decode('utf8')) for genre in genres] def getArtists(self): artists = sorted(self.client.list('artist')) return [Artist(artist.decode('utf8')) for artist in artists] def isPlaying(self): status = self.client.status() return status['state'] == 'play' def getCurrentSong(self): current = self.client.currentsong() if current == None: return None status = self.client.status() if 'time' in status: time = status['time'].split(':')[0] else: time = 0 track = Track() track.load(current) track.timePassed = time return track def getQueueLength(self): playlist = self.client.playlist() return max(len(playlist) - 1, 0) def getCurrentEvent(self): event = Event.getCurrent() event.jukebox = self return event def getNextEvent(self): event = Event.getNext() return event def isEnabled(self): event = self.getCurrentEvent() return event.type == EVENT_TYPE_JUKEBOX def remove(self, id): log.info("Removing playlist item #%d" % id) self.client.delete(id) def play(self): self.client.play() def pause(self): self.client.pause() def previous(self): self.client.previous() def next(self): # This is to prevent interruptions in the audio stream # See http://code.google.com/p/fookebox/issues/detail?id=6 if self.getQueueLength() < 1 and config.get('auto_queue'): self.autoQueue() self.client.next() def volumeDown(self): status = self.client.status() volume = int(status.get('volume', 0)) self.client.setvol(max(volume - 5, 0)) def volumeUp(self): status = self.client.status() volume = int(status.get('volume', 0)) self.client.setvol(min(volume + 5, 100)) def refreshDB(self): self.client.update() fookebox-0.6.1/fookebox/model/meta.py0000644000175000017500000000221611525403162020330 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """SQLAlchemy Metadata and Session object""" from sqlalchemy import MetaData __all__ = ['engine', 'metadata', 'Session'] # SQLAlchemy database engine. Updated by model.init_model(). engine = None # SQLAlchemy session manager. Updated by model.init_model(). Session = None # Global metadata. If you have multiple databases with overlapping table # names, you'll need a metadata for each database. metadata = MetaData() fookebox-0.6.1/fookebox/model/mpdconn.py0000644000175000017500000001522511556665245021064 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import re import os import base64 import logging from mpd import MPDClient from datetime import datetime from threading import BoundedSemaphore from pkg_resources import get_distribution, DistributionNotFound from pylons.i18n.translation import _, ungettext from pylons import config, app_globals as g from fookebox.model.albumart import AlbumArt log = logging.getLogger(__name__) class Lock(object): class __impl: def __init__(self): self.semaphore = BoundedSemaphore(value=1) def acquire(self): return self.semaphore.acquire(False) def release(self): return self.semaphore.release() __instance = None def __init__(self): if Lock.__instance is None: Lock.__instance = Lock.__impl() self.__dict__['_Lock__instance'] = Lock.__instance def __getattr__(self, attr): return getattr(self.__instance, attr) class Genre(object): def __init__(self, name): self.name = name self.base64 = base64.urlsafe_b64encode(name.encode('utf8')) class Artist(object): def __init__(self, name): self.name = name self.base64 = base64.urlsafe_b64encode(name.encode('utf8')) class Album(object): def __init__(self, artist, albumName, disc=None): self.isCompilation = False if albumName == None: self.name = '' else: self.name = albumName if artist == None: self.artist = '' else: self.artist = artist self.disc = disc self.tracks = [] def add(self, track): if track.artist != self.artist and not ( track.artist.startswith(self.artist) or self.artist.startswith(track.artist)): self.isCompilation = True self.artist = _('Various Artists').decode('utf8') self.tracks.append(track) def load(self): try: mpd = MPD.get() client = mpd.getWorker() data = client.find( 'Artist', self.artist.encode('utf8'), 'Album', self.name.encode('utf8')) client.release() except: client.release() raise for file in data: track = Track() track.load(file) self.add(track) def hasCover(self): art = AlbumArt(self) return art.get() != None def getCoverURI(self): artist = base64.urlsafe_b64encode(self.artist.encode('utf8')) name = base64.urlsafe_b64encode(self.name.encode('utf8')) return "%s/%s" % (artist, name) def getPath(self): basepath = config.get('music_base_path') if basepath == None: return None if len(self.tracks) > 0: track = self.tracks[0] else: self.load() if len(self.tracks) < 1: return None track = self.tracks[0] fullpath = os.path.join(basepath, track.file) return os.path.dirname(fullpath) def key(self): return "%s-%s" % (self.artist, self.name) class Track(object): NO_ARTIST = 'Unknown artist' NO_TITLE = 'Unnamed track' track = 0 def load(self, song): def __set(key, default): val = song.get(key, default) if val is None: return val if isinstance(val, list): val = val[0] if isinstance(val, int): return val else: return val.decode('utf8') self.artist = __set('artist', Track.NO_ARTIST) self.title = __set('title', Track.NO_TITLE) self.file = __set('file', '') self.disc = __set('disc', 0) self.album = __set('album', None) self.queuePosition = int(__set('pos', 0)) self.time = int(__set('time', 0)) if 'track' in song: # possible formats: # - '12' # - '12/21' # - ['12', '21'] t = song['track'] if '/' in t: tnum = t.split('/')[0] self.track = int(tnum) elif isinstance(t, list): self.track = int(t[0]) else: self.track = int(t) def __str__(self): return "%s - %s" % (self.artist, self.title) class FookeboxMPDClient(MPDClient): def consume(self, do): self._docommand('consume', [do], self._getnone) class MPDWorker(object): def __init__(self, num): self.num = num host = config.get('mpd_host') port = config.get('mpd_port') password = config.get('mpd_pass') try: pkg = get_distribution('python-mpd') if pkg.version < '0.3.0': self.mpd = FookeboxMPDClient() else: self.mpd = MPDClient() except DistributionNotFound: self.mpd = MPDClient() self.mpd.connect(host, port) if password: self.mpd.password(password) # enable consume on mpd in the first worker if num == 0: self.mpd.consume(1) self.atime = datetime.now() self.free = True def __del__(self): self.mpd.close() self.mpd.disconnect() def __str__(self): return "MPDWorker %d (last used: %s)" % (self.num, self.atime) def grab(self): self.free = False self.atime = datetime.now() def release(self): self.atime = datetime.now() self.free = True #log.debug("Worker %s released" % self) def __getattr__(self, attr): self.atime = datetime.now() return getattr(self.mpd, attr) class MPDPool(object): lock = None def __init__(self): self.lock = BoundedSemaphore(value=1) self._workers = [] def getWorker(self): self.lock.acquire() log.debug("Pool contains %d workers" % len(self._workers)) for worker in self._workers: if worker.free: log.debug("Re-using worker %s" % worker) worker.grab() self._cleanup() self.lock.release() return worker else: log.debug("Worker %s is busy" % worker) now = datetime.now() diff = (now - worker.atime).seconds # TODO: here we manipulate the collection that # we are iterating over - probably a bad idea if diff > 30: log.warn("Terminating stale worker") worker.release() self._workers.remove(worker) try: worker = MPDWorker(len(self._workers)) log.debug("Created new worker %s" % worker) worker.grab() self._workers.append(worker) self.lock.release() return worker except Exception: log.fatal('Could not connect to MPD') self.lock.release() raise def _cleanup(self): now = datetime.now() for worker in self._workers: if worker.free: if (now - worker.atime).seconds > 10: log.debug("Removing idle worker %s" % worker) self._workers.remove(worker) class MPD(object): @staticmethod def get(): if g.mpd == None: g.mpd = MPDPool() return g.mpd fookebox-0.6.1/fookebox/model/schedule.py0000644000175000017500000000677311525403160021210 0ustar stefanstefan00000000000000# fookebox, http://fookebox.googlecode.com/ # # Copyright (C) 2007-2011 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import logging import sqlalchemy as sa from sqlalchemy import orm from fookebox.model import meta from pylons import app_globals as g log = logging.getLogger(__name__) t_event = sa.Table("Events", meta.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("index", sa.types.Integer, primary_key=False), sa.Column("type", sa.types.Integer, nullable=False), sa.Column("name", sa.types.String(100), nullable=False), sa.Column("time", sa.types.Time, nullable=False), ) EVENT_TYPE_JUKEBOX = 0 EVENT_TYPE_BAND = 1 EVENT_TYPE_DJ = 2 class Event(object): def __str__(self): return "[type %s] %s @ %s (index=%d)" % ( self.type, self.name, self.time, self.index) @staticmethod def currentID(): id = g.eventID; if id == None: events = Event.all() if len(events) > 0: g.eventID = events[0].id else: return -1 return g.eventID @staticmethod def all(): event_q = meta.Session.query(Event) return event_q.order_by(Event.index.asc()).all() @staticmethod def get(id): event_q = meta.Session.query(Event) return event_q.get(id) @staticmethod def getCurrent(): event_q = meta.Session.query(Event) event = event_q.get(Event.currentID()) if event == None: event = Event() event.name = 'fookebox jukebox' event.type = EVENT_TYPE_JUKEBOX event.index = 0 return event @staticmethod def getNext(): event_q = meta.Session.query(Event) current = Event.getCurrent() events = event_q.filter(Event.index > current.index) return events.order_by(Event.index.asc()).first() @staticmethod def delete(id): event_q = meta.Session.query(Event) event = event_q.get(id) log.info("Deleting event %s" % event) meta.Session.delete(event) meta.Session.commit() @staticmethod def add(name, type, time): event = Event() event.name = name event.type = type event.time = time meta.Session.add(event) meta.Session.commit() event.index = event.id meta.Session.commit() log.info("Created event %s" % event) @staticmethod def update(id, name, type, time): event_q = meta.Session.query(Event) event = event_q.get(id) event.name = name event.type = type event.time = time meta.Session.commit() @staticmethod def up(id): event_q = meta.Session.query(Event) event = event_q.get(id) prev = event_q.filter(Event.index < event.index).order_by( Event.index.desc()).first() if prev != None: tmp = prev.index prev.index = event.index event.index = tmp meta.Session.commit() @staticmethod def down(id): event_q = meta.Session.query(Event) event = event_q.get(id) next = event_q.filter(Event.index > event.index).order_by( Event.index.asc()).first() if next != None: tmp = next.index next.index = event.index event.index = tmp meta.Session.commit() orm.mapper(Event, t_event) fookebox-0.6.1/fookebox/public/0000755000175000017500000000000011743153607017215 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/public/css/0000755000175000017500000000000011743153607020005 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/public/css/style-mobile.css0000644000175000017500000000060011540550326023112 0ustar stefanstefan00000000000000#artistList, #genreList { position: relative; top: 0; } #browse-menu { position: relative; top: 0; } #letterSelector { padding: 0 10px 20px 10px; position: relative; top: 0; } #searchResult { position: relative; left: 26px; top: 8px; margin-right: 50px; } #meta { display: none; } #status { float: right; position: relative; top: 0; } h1 { margin-bottom: 1px; } fookebox-0.6.1/fookebox/public/css/style.css0000644000175000017500000001345111525403215021652 0ustar stefanstefan00000000000000body { padding: 0; border: 0; margin: 0; color: white; background: black; } body, input { font-family: Arial, sans-serif; } img { border: 0; vertical-align: middle; } h1 { color: white; border-bottom: 1px #789193 solid; margin: 0; font-size: 80px; padding-left: 9px; text-align: center; font-weight: bold; height: 90px; } #browse-menu { border: 1px white solid; margin: 25px 0 0 2px; float: left; width: 300px; position: fixed; top: 92px; bottom: 10px; } #browse-menu, #selectType li { background: #282828; } #selectType { padding: 0 2px 0 0; margin: 0; list-style-type: none; position: relative; top: -21px; left: -1px; } #selectType li { border: 1px white solid; display: inline; padding: 1px 4px 2px 4px; } #selectType li.active { border-bottom: none; padding-bottom: 3px; } #selectType li.inactive:hover { background: #999999; } #artistList, #genreList { margin-top: 0; overflow: auto; position: absolute; top: 20px; bottom: 0px; right: 0px; left: 10px; } #artistList ul, #genreList { margin-top: 0; list-style-type: decimal; list-style-image: url(../img/li.png); padding: 0 1em 0 1em; } #letterSelector { font-size: x-small; position: fixed; top: 121px; width: 280px; } #letterSelector a { font-weight: normal; text-decoration: underline; } #status { position: absolute; overflow: auto; top: 92px; right: 1px; bottom: 0px; width: 200px; } #nowPlaying, #playlist { border: 1px white solid; border-right: 1px #777777 solid; border-bottom: 1px #777777 solid; padding-bottom: 1em; margin: 25px 0 2px 0; color: white; } #nowPlaying ol { padding-left: 10px; margin: 0; } #nowPlaying #artist, #nowPlaying #track, #nowPlaying #time, #nowPlaying #control { margin-left: 1em; padding-bottom: 2px; } #nowPlaying #artist { list-style-image: url(../img/artist.png); } #nowPlaying #track { list-style-image: url(../img/music.png); } #nowPlaying #time { list-style-image: url(../img/time.png); } #nowPlaying #control { list-style-type: none; } #nowPlaying, #nowPlaying h2 { background: #ffae00; color: black; } #playlist, #playlist h2 { background: #282828; } #nowPlaying h2, #playlist h2 { border: 1px white solid; border-right: 1px #777777 solid; color: white; border-bottom: 0; position: relative; top: -21px; left: -1px; font-size: medium; padding: 1px 4px 2px 4px; margin: 0; display: inline; } #playlist ul { list-style-type: none; padding: 0; margin-top: 0; } #playlist ol { margin-top: 0; padding-left: 2em; } #playlist li { padding: 0 1em 0 0; } h1 a:hover { color: #ffffff; } a { font-weight: bold; text-decoration: none; color: white; } a:hover { color: #cccccc; } a:focus { outline: none; } #message { position: absolute; top: 38px; left: 2px; padding: 2px 2em 2px 2em; font-size: large; background-color: #ffcf28; color: black; } #message .corner { position: absolute; background-color: black; height: 4px; width: 4px; } #message .tl { top: 0; left: 0; background-image: url(../img/msg-tl.png); } #message .tr { top: 0; right: 0; background-image: url(../img/msg-tr.png); } #message .bl { bottom: 0; left: 0; background-image: url(../img/msg-bl.png); } #message .br { bottom: 0; right: 0; background-image: url(../img/msg-br.png); } .freeSlot { font-style: italic; color: #bbbbbb; font-size: small; } #searchResult { position: fixed; top: 99px; left: 330px; right: 230px; bottom: 10px; color: white; overflow: auto; } #searchResultList { list-style-type: none; padding-left: 0 } li.searchResultItem { overflow: auto; width: 99%; background: #222222; margin: 2px; } ul.trackList { padding-bottom: 10px; } #searchResult h3 { padding-left: 16px; } #searchResult li.track { list-style-image: url(../img/music.png); } #searchResult li.track a { font-weight: normal; } #searchResult li.album { list-style-image: url(../img/folder.png); } #searchResult img.coverArt { float: right; clear: both; margin: 10px; } #searchResult h2 { padding-top: 0; margin: 0; border-bottom: 1px white solid; } #progress { position: absolute; right: 30px; top: 40px; padding: 5px; color: black; } #progress #icon { height: 16px; width: 16px; background-image: url(../img/progress.gif); margin: 2px; } #progress #text { display: inline; } li.seperator { border-top: 1px #999999 solid; } #now { margin-top: 120px; border: 1px #555555 solid; border-left: none; border-right: none; font-size: 40px; text-align: center; height: 140px; background: #000a00; background-repeat: no-repeat; } .state { text-align: center; } .state span { font-size: 18px; position: relative; top: -12px; background: black; border: 1px #555555 solid; color: white; padding-left: 1em; padding-right: 1em; } #next { margin-top: 105px; border: 1px #555555 solid; border-left: none; border-right: none; padding-top: 10px; font-size: 25px; text-align: center; height: 130px; background: #050500; background-repeat: no-repeat; } #now .label, #next .label { font-size: small; position: relative; background-color: black; padding: 5px 10px 5px 10px; } #now .label { top: -33px; border: 1px #555555 solid; } #next .label { top: -30px; border: 1px #555555 solid; } #next .time { font-size: 18px; position: relative; top: 8px; color: white; padding-left: 1em; padding-right: 1em; } #clock { position: fixed; padding: 10px; font-size: xx-large; font-family: monospace; color: white; right: 0; top: 0; } #meta { position: fixed; top: 0px; right: 0px; font-size: x-small; } table.schedule { margin: 0 auto; border-collapse: collapse; } table.schedule td { padding: 5px 10px; } table.schedule tr.drop { background-color: blue; } .currentEvent { background-color: green; } #disabled-main { text-align: center; padding-top: 150px; } #disabled-title { font-size: 150pt; } #disabled-text { font-size: 30pt; } fookebox-0.6.1/fookebox/public/img/0000755000175000017500000000000011743153607017771 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/public/img/arrow_down.png0000644000175000017500000000057311525403056022657 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe< IDAT8˥?KQi H*.EA!XX vc!v{;,ӻ\}Ï7Ibc0u2B^h gw`4+@jɥ s5"H hPǁh"H.EBFݜ& 5EɃZn+;l8r9~c$ h>*k>hLLjƳRwUd:<$hݸIENDB`fookebox-0.6.1/fookebox/public/img/arrow_up.png0000644000175000017500000000056411525403056022334 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥?/Qϲhg5j%'F,[ LH 3(vw=fcoN{O~9VM4Q7ܿ)v/WQ=&bpSO ^'&^:\˨6eND!& 9꒣_|?\ srx,g*,(F#d[OaAA*P p1O+C$`)*w`A#0$ *?b&NRIENDB`fookebox-0.6.1/fookebox/public/img/artist.png0000644000175000017500000000134511525403056022002 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<wIDAT8˥mHQ *ֶVj)_OХ9]m*Y떩e-h-QJiLF2LJE8\9r~s)k­PiP.I$"EwDtR][)t$ҐB 4BtTPMjq1s M*nFj 4#/8A>PSPΞ S}|뺆y=9{sܔ:`;3evq/# ;us fEf q<^ք(ss7(`%|< ǗiXD%/X`a6.05 V);nǁ dN>*^?aW+jza)Zq\M9=Y[ ZR (mDV2’Jb 26TD]HCpލ C<^28;+Cu f5 7n:eF`Q( >%C%s2٥hid3@ A+YaU,Z1<@UZ%ձc_9]f'ɳ;fMj ޻ݎLӤ$AP(|^&U6Gk2 Cb0z0x&Q¯l6di(ɫՊVz=2P2ԟY ($.`~OBX%ݮ)P 4kJdN' CXprH$b<Ęʇ QMH[3/Jq؀OIFZ(zY.rAi\Wr^MsU,1 ! #+@Dm鴚JL ^V3N2!3DzꏫH$X,ƅ%=g], "wꯗ)*`P$rt6+>eD1 +IENDB`fookebox-0.6.1/fookebox/public/img/control_pause.png0000644000175000017500000000112611525403056023346 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥S=kA((r6ՁXhamt^ Mig!`k'݁ j!wY͙&Yfo{] c _FQAI ^*-hg`yN$tn5f>bXY4p8TŌ3Mng͆u:n+Fgp dZyv nR`&FsPJ*WVI 2I 0AZ no Rm ~8(aft~4\s<t:Jl;>[3I]. "/$߃r`A5$1QAQ2dn|1mDDjNAxlA A{߮r^WP[.ˁ@fhR>'0hDt]glVxu:?) x\ J4[C:N<@D"vۀY^ȸZ8rjJLn7F-$P `Uu{Ԯ"ц+O&1pHp)|.UE4~SX`02U* `!"+Ìv2NMѮ !A_^d2)q[-cdGgbR( kpHw7kFF?EE IENDB`fookebox-0.6.1/fookebox/public/img/control_prev.png0000644000175000017500000000114611525403056023207 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥Ɋ"A #Zj" /BV*m)nX,@UUө|>/^/ANXQC&!:7"bV@d2(xl6JhZ*6 , `fCF`ہMl6 m6L&ͧX,u2%\n^ f LQ0dDg |M#2buB CnP,!?* %BfGh4B|b|bCzH\Nf x8eh @ {鴜L&/Iƞ`8w~y DH(`P*QK1m4($IENDB`fookebox-0.6.1/fookebox/public/img/control_rebuild.png0000644000175000017500000000140211525403056023654 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˅S]HQ~Mї4+4\!҅DDE]2ʫ../. &Aw276 [9+s;Gd2VW -aԐ&Dz BY_"t#IR]YYl6 766L&>^b|eYf2`0yXk0rZNt:RNU"ELӰ%%%XI.kehM,,-uo_`S`u" 9qeA7tOҗ=oZnVf-,(MC >}$~LEX UQQ^TC}ÈP8!80D|{ 럿jsrh\4v:?]9 ýC9Q4EG؝<Ū9_ǘA &!~AhLLGP~Q GR6]Q4v6Q?8,HxfK.>@Pq j&8,<'B.VYY Apmڭ\Z]?:k#{H: nR+gP~=LhOF@OV{£`twws</ꚭo;AM#@#*IENDB`fookebox-0.6.1/fookebox/public/img/control_voldown.png0000644000175000017500000000117211525403056023722 0ustar stefanstefan00000000000000PNG  IHDRabKGD pHYs  tIME  +ֲolIDAT8˥KTQ?S#iF J!rQZ!F6Wj 'iig{Ϲ-qFA(pp|9|=95{{8E C2i{++xOE䑪bUϿ ~{El6by;Zx$^?f^ C!2Cll4HH[Q$]- AU묬,1001I-VBڭ9amm_*Il6 l`Ţ^vlP0h4g`ja0I6(T8UNL7-VZw4MT~\kEù9 QUn9՟9UvQ6![;^?N[o|^;;z!,ϹB LW xH@ϱA﹡Esr6L]X*\zr_ox؂wmr;SF"IENDB`fookebox-0.6.1/fookebox/public/img/control_volup.png0000644000175000017500000000121211525403056023372 0ustar stefanstefan00000000000000PNG  IHDRabKGD pHYs  tIME  <IDAT8˥KTaƟ{N &s'Jim#hQ8*vm"Bg"}El-PhrtBg}?9oqHz]Ï<&]!"ekpP,NiCt `Y&ΐ !$;R0 Zc_>}H$cg 4M_e:_+0ʜ~| r@DPTnma! b\^@)Z`6 ,[cePUQ*`AZEEf e@B`M_aFO0(BEƢ-,_5 "诓}" Ai1R8'2T[[{e;ù"WOQ|/1xH@j۾O;z` 5UnӷN9 &w @;atzIENDB`fookebox-0.6.1/fookebox/public/img/delete.png0000644000175000017500000000131311525403056021731 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<]IDAT8˥KSa[nQP2wܦγL[,biaA\Cv_2MlZFjסNMjmkʷ`&.#z<ϓ bVPT3%I{GqRivȅ tz#E6EddJ`DR2<]N ;4Ѿ;m>78ɀQe6LIt殷cq!z |v j/Xi@ %1|hl !|! Y#uUNw]˼ H3u t]E>k%IfoRD:0`~ | (r on3oG0!$V *[W0_-+ dW&2ZfMFVJpiF&B > Rg- ~ CmڴER ឫ p5ްy+21Kawh` #aZ񽞆TZoLѓ`"(?'ˎJvKކ|:G9[aw82 Jw f'ymzsӘTsw__ιIrIENDB`fookebox-0.6.1/fookebox/public/img/edit.png0000644000175000017500000000115211525403056021415 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8ˍKSaWEDBԅЍ}a? P3B ]t +$aA IX^ns\[sKp;;gɦps6qt w`԰U]|^)JrL+:Nsb&\.u,Ld2iIYBӗ)v>)iR(D4E!J߰EYyZ,ǽM!a*?fH>>ƧG9Q7&h޳|}+ n $jcM}w+U;}92XͶ$jxw?Y=“g~Z\-32L>vEdi/ e{;^D tT߈]v5Jh.Az{Cp (1{888:q(yE13W|KL L EL""bx1Euh:)m~%NKE^C84)E#iuQ`厇4u"3z4yIZHG%tf0aD'*&rn#mQ 'I$Y=37Q0`ܽIENDB`fookebox-0.6.1/fookebox/public/img/nocover.png0000644000175000017500000000053211525403217022143 0ustar stefanstefan00000000000000PNG  IHDRXsRGBbKGD pHYs  tIME .;$tEXtCommentCreated with The GIMPd%nIDATx nH@|qIENDB`fookebox-0.6.1/fookebox/public/img/progress.gif0000644000175000017500000000124111525403056022314 0ustar stefanstefan00000000000000GIF89a<<<|||lll!Created with ajaxload.info! ! NETSCAPE2.0,30Ikc:Nf E1º.`q-[9ݦ9 JkH! ,4N!  DqBQT`1 `LE[|ua C%$*! ,62#+AȐ̔V/cNIBap ̳ƨ+Y2d! ,3b%+2V_ ! 1DaFbR]=08,Ȥr9L! ,2r'+JdL &v`\bThYB)@<&,ȤR! ,3 9tڞ0!.BW1  sa50 m)J! ,2 ٜU]qp`a4AF0` @1Α! ,20IeBԜ) q10ʰPaVڥ ub[;fookebox-0.6.1/fookebox/public/img/pylons-logo.gif0000644000175000017500000000453711525403056022745 0ustar stefanstefan00000000000000GIF89a;Dzyu)))ZZZHHH%%%2!!!Yna(,<<;޾9{.©A 221(('LD&##"'''&&&"""  (((###$$%'(($##$$$(''***+++onn0!,;DpH,Ȥrl:ШtJZجvzxLl$͆Rn+4||2dC lezxq?=N v n? =pwӗ pڣŒb\eMY,[# ‹S&0܈gP0S6ȑG1 Cj;/*sQز/1e&f):ٳ0A@ҫ1؀hp ޼֖/ -w$% oΫw$x%AT^bd_5;RNR`[ =0 P{,f ""QVz +`Pi@O2,+u*P w@%2'@H" bwaUu.Md%i3QfE{H`L}jEQEAV^1(m UBKti@6T@c\D4-PD>+W64@64"N=xDiRExLY@!gQr/U᧍B EDdIj*: DI:U 5EDaN^[bD99N: :J}cR`kN)Gi)F JZ$a@:DJbgN{붲 A+m;bp.q-&;BXnO2WDJ;%6ZVFN D@JpöʂpxD˶JRuy"A/Zos| n3pL S@bW@]4< T26/k q(:7{F/xnKRYDfv-M`/@5?L$[76Q(#%A1_F(Պ)Ƹt&>w٠] w( y桼7(Gd 5{e x@cn\֋Xڢx|(A>(˞ ΄] pz@D>"x x?0xy#XS9z8]bq6$hGs~7EI@Ji'sяqѓ6X\?=z6 UUFdB&88y+툗@)_?d9>ZPSWy;E&#ʞ˓ ߛ_3uE[qzrcS iGkD́0zv(Ja-.[.$ihurz<ʪ*~+*Gw ":l&HW Enf]v\>}ײrz Z #=n*6.eO9GFĕ5 "(Y<)"=mXRlVUVN.UqUX2ZIB&%HAUk(J^L+Cij(l X_b+MDþ;wvԫJ Ak! 8O'D䏅NDQl>sU12ٻcp k/Lcrh&Vbnz)OY!lj?}矪Kc{ZIENDB`fookebox-0.6.1/fookebox/public/img/setcurrentevent.png0000644000175000017500000000141511525403056023732 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥KSa;vvl dD!P{$; ż,Kݽ6cL2r^H)-jsNm֔2qQB̽BatoL#z {q' r=)La8,u%2Rg>ݾW ϛJ߸Pd makD|=G Vn6[Įd桚(Pm.0Q`'Fb#&ܧ6aP׏Q12[+zi; ]C17оpI9̾jD}›?7ayze,hXAK^3*bk @+wQ=!}uXzq:g쯺n= :d+_GTA;Ր Jƣ.!P)5!H:epր"݂"Kyw|{H2!i~3z_X;okBZK* ^R:O(jF*^ȰS诿_ gЬycIENDB`fookebox-0.6.1/fookebox/public/img/sound.png0000644000175000017500000000114211525403056021617 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8K`Ncc0V!s8ۘ%iŵY61ad!_ZoZ,Lax/=ͣ0/a\~1XƆ_yr6TZ۶rNJ-DZO-k H3d~ժ|VRyVms/X\x \DKPVGlja{{ fYީn$wZ:ky_tnl6aY0rs|蠷1^3_rl q`6" `OH58QD ٪Sj4֡( (DQD0%YB3 <~W(Xif M@ ؤ澞=3H<9rϲbk9x+J rolHl>9YN{rJ7*3h|Uo<>IENDB`fookebox-0.6.1/fookebox/public/img/time.png0000644000175000017500000000143111525403056021426 0ustar stefanstefan00000000000000PNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDAT8˥OzS/=Y.k[nZ $K,̮fP r5 /D%L@+Fk9[Ἔ9ۀm?MW/K:|nYx0ϖT\9ڥX x6?C$FC|<ʨGW 6ze^g?Ls@eGM^F<:jϠS K:_ʤТ5Gk7!cep=3^[|vG xT12&(2u$bPʋ"WS@w94qu,"UZ,ئD44RRd8,&$« UZۑ_S`L0+ Xy8:kN'CfP\$(7C~M5J;8C4Qw9r?73fFcr7-2@T ?@C2>Ϧ'l]Q=ECpD!? zhdM)EGze%,KHnau'2b-"'-Y. */ var QueueView = Class.create(AjaxView, { initialize: function(songRemoval) { this.songRemoval = songRemoval; this.queueLength = -1; this.queueView = $('playlist'); this.template = new Template('#{artist} - #{title} '); }, sync: function() { this.get('queue', this.update.bind(this)); }, update: function(transport) { var data = transport.responseJSON; var queue = data.queue; this.queueLength = queue.length; var playlist = this.queueView.select('li'); playlist.each(function(li, index) { var item = queue[index]; if (item) { this.updateSlot(li, index, item); } else { li.update('-- ' + _('empty') + ' --'); } }.bind(this)); }, updateSlot: function(element, position, track) { if (!track.artist || track.artist.blank()) track.artist = _('Unknown artist'); if (!track.title || track.title.blank()) track.title = _('Unnamed track'); element.update(this.template.evaluate(track)); if (this.songRemoval) { var link = new Element('a', {'href': '#'}); link.onclick = function() { this.unqueue(position + 1); return false; }.bind(this); var img = new Element('img', { 'alt': 'x', 'src': 'img/delete.png', 'title': _('Remove from the queue'), }); link.appendChild(img); element.appendChild(link); } }, setLength: function(length) { if (length != this.queueLength) this.sync(); }, unqueue: function(id) { var data = $H({'id': id}); this.post('remove', data, this.sync.bind(this)); }, }); var TrackView = Class.create(AjaxView, { initialize: function() { this.artist = ""; this.track = ""; this.timeTotal = "00:00"; this.playing = false; this.time = new Date(0, 0, 0); }, attach: function(jukebox) { this.artistView = $('artist'); this.trackView = $('track'); this.timeView = $('timeTotal'); this.timePassedView = $('timePassed'); function addControl(key) { $('control-' + key).onclick = function() { jukebox.control(key); return false }; } if ($('control')) { addControl('prev'); addControl('pause'); addControl('play'); addControl('next'); addControl('voldown'); addControl('volup'); addControl('rebuild'); } }, updateTime: function() { var seconds = this.time.getSeconds(); var minutes = this.time.getMinutes(); if (seconds < 10) seconds = "0" + seconds; if (minutes < 10) minutes = "0" + minutes; this.timePassedView.update(minutes + ":" + seconds); }, tick: function() { if (this.playing) this.time.setSeconds(this.time.getSeconds() + 1); this.updateTime(); }, adjustTime: function(time) { // sync our client-side track time with the one from the // server. update the seconds only if we differ by more than // one second (force-update the display in that case). // // this should fix the 'jumpy' track time display var parts = time.split(':'); if (parts.length == 2) { var minutes = parts[0]; var seconds = parts[1]; var diff = seconds - this.time.getSeconds(); this.time.setMinutes(minutes); if (diff > 1 || diff < -1) { this.time.setSeconds(seconds); this.updateTime(); } } }, update: function(artist, track, timeTotal, playing) { this.artist = artist; this.track = track; this.timeTotal = timeTotal; this.playing = playing; if (!this.playing) { Effect.Pulsate('timePassed', {pulses: 1, duration: 1}); } if (this.artist != this.artistView.innerHTML) this.artistView.update(this.artist); if (this.track != this.trackView.innerHTML) this.trackView.update(this.track); if (this.timeTotal != this.timeView.innerHTML) this.timeView.update(this.timeTotal); }, }); var CoverView = Class.create(AjaxView, { setCover: function(hasCover, coverURI) { var img = $('nowPlayingCover'); if (hasCover) { img.src = 'cover/' + coverURI; img.show(); } else { img.hide(); } } }); var MusicView = Class.create(AjaxView, { initialize: function(jukebox) { this.jukebox = jukebox; }, attach: function() { $$('.artistLink').each(function(link) { link.onclick = function() { var target = event.target; var artist = target.id.substring(7, target.id.length); this.showArtist(artist); return false; }.bind(this); }.bind(this)); $$('.genreLink').each(function(link) { link.onclick = function() { var target = event.target; var genre = target.id.substring(6, target.id.length); this.showGenre(genre); return false; }.bind(this); }.bind(this)); $('searchForm').onsubmit = function(event) { var form = event.target; this.search(form); return false; }.bind(this); }, showArtist: function(artist) { this.showProgressbar(); // TODO: the page control should actually do this window.location = "#artist=" + artist; this.jukebox.page.url = window.location.href; this.get('artist/' + artist, this.showSearchResult.bind(this)); }, showGenre: function(genre) { this.showProgressbar(); // TODO: the page control should actually do this window.location = "#genre=" + genre; this.jukebox.page.url = window.location.href; this.get('genre/' + genre, this.showSearchResult.bind(this)); }, search: function(form) { this.showProgressbar(); var type = $F(form.searchType); var term = $F(form.searchTerm); var data = $H({ 'where': type, 'what': term, 'forceSearch': true }); this.post('search', data, this.showSearchResult.bind(this)); }, showSearchResult: function(transport) { var result = new SearchResult(this.jukebox, transport); result.show(); this.hideProgressbar(); } }); var AlbumCover = Class.create(AjaxView, { initialize: function(album, target) { this.album = album; this.target = target; }, load: function() { var data = $H({ 'artist': this.album.artist, 'album': this.album.name }); this.post('findcover', data, this.loaded.bind(this), this.hide.bind(this)); }, loaded: function(transport) { var response = transport.responseJSON; this.target.src = 'cover/' + response.uri; }, hide: function(transport) { this.target.style.display = 'None'; } }); var SearchResult = Class.create( { initialize: function(jukebox, transport) { this.jukebox = jukebox; this.tracks = transport.responseJSON.tracks; this.what = transport.responseJSON.meta.what; if (!this.what || this.what.blank()) this.what = _('(none)'); this.albums = new Hash(); this.trackTemplate = new Template ('#{track} - #{artist} - #{title}'); this.albumTemplate = new Template ('#{artist} - #{name}'); this.albumDiscTemplate = new Template ('#{artist} - #{name} (Disc #{disc})'); this.parseAlbums(); }, parseAlbums: function() { this.tracks.each(function(track) { // Yes, this sucks: python-mpd enjoys returning arrays // when multiple tags are present. We need to unpack // them here. if (Object.isArray(track.album)) track.album = track.album[0]; if (Object.isArray(track.artist)) track.artist = track.artist[0]; if (Object.isArray(track.title)) track.title = track.title[0]; if (Object.isArray(track.track)) track.track = track.track[0]; var key = track.album + "-" + track.disc; var album = this.albums.get(key); if (album == null) { album = new Album(track.artist, track.album, track.disc); this.albums.set(key, album); } album.add(track); }, this); }, showTrack: function(track) { var node = new Element('li', {'class': 'track'}); var link = new Element('a', {'href': '#'}); link.update(this.trackTemplate.evaluate(track)); link.onclick = function(event) { this.jukebox.queue(track); return false; }.bind(this); node.appendChild(link); return node; }, showAlbum: function(album) { var node = new Element('li', {'class': 'searchResultItem'}); var header = new Element('h3', {'class': 'album'}); var tracks = new Element('ul', {'class': 'trackList'}); var coverArt = new Element('img', {'class': 'coverArt', 'width': 200}); if (this.jukebox.config.get('enable_queue_album')) { var link = new Element('a', {'href': '#'}); link.onclick = function(event) { this.jukebox.queueAlbum(album); return false; }.bind(this); var template = album.disc ? this.albumDiscTemplate : this.albumTemplate; link.update(template.evaluate(album)); header.appendChild(link); } else { header.update(this.albumTemplate.evaluate(album)); } album.getTracks().each(function(track) { tracks.appendChild(this.showTrack(track)); }, this); if (this.jukebox.config.get('show_cover_art')) new AlbumCover(album, coverArt).load(); node.appendChild(coverArt); node.appendChild(header); node.appendChild(tracks); return node; }, show: function(transport) { // TODO: this, right $('searchResult').update(''); var header = new Element('h2').update(this.what); var ul = new Element('ul', {'id': 'searchResultList'}); var sorted = this.albums.values().sortBy(function(s) { return s.artist + ' - ' + s.name; }); sorted.each(function(album) { ul.appendChild(this.showAlbum(album)); }, this); $('searchResult').appendChild(header); $('searchResult').appendChild(ul); }, }); var Album = Class.create( { initialize: function(artist, name, disc) { this.artist = artist; this.name = name; this.disc = disc; this.tracks = new Hash(); if (!this.artist || this.artist.blank()) this.artist = _('Unknown artist'); if (!this.name || this.name.blank()) this.name = _('Unnamed album'); }, add: function(track) { if (!track.track) track.track = '00'; if (track.track.include('/')) track.track = track.track.sub(/\/.*/, ''); if (track.track < 10 && track.track.length == 1) track.track = '0' + track.track; if (!track.artist || track.artist.blank()) track.artist = _('Unknown artist'); if (!track.title || track.title.blank()) track.title = _('Unnamed track'); if ((track.artist != this.artist) && !track.artist.startsWith(this.artist)) { if (this.artist.startsWith(track.artist)) this.artist = track.artist; else this.artist = _('Various artists'); } this.tracks.set(track.file, track); }, getTracks: function() { return this.tracks.values().sortBy(function(s) { return s.track; }); } }); var JukeboxView = Class.create(AjaxView, { initialize: function(config) { this.config = new Hash(); this.loadconfig(); this.queueView = new QueueView( this.config.get('enable_song_removal')); this.trackView = new TrackView(); this.coverView = new CoverView(); this.musicView = new MusicView(this); this.page = new PageControl(this); this.page.watch(); }, loadconfig: function() { setbool = function(key, value) { if (Object.isUndefined(value)) this.config.set(key, false); else this.config.set(key, $F(value) == 'True'); }.bind(this); var form = $('config'); setbool('enable_queue_album', form.enable_queue_album); setbool('show_cover_art', form.show_cover_art); setbool('enable_song_removal', form.enable_song_removal); }, attach: function() { this.trackView.attach(this); this.musicView.attach(); }, disable: function() { window.location = 'disabled'; }, readStatus: function(transport) { var data = transport.responseJSON; var enabled = data.jukebox; if (!enabled) { this.disable(); return } this.trackView.update(data.artist, data.track, data.timeTotal, data.playing); this.trackView.adjustTime(data.timePassed); this.coverView.setCover(data.has_cover, data.cover_uri); this.queueView.setLength(data.queueLength); }, sync: function() { window.setTimeout(this.sync.bind(this), 1000); // update time this.trackView.tick(); this.get('status', this.readStatus.bind(this)); }, control: function(action) { var data = $H({'action': action}); this.post('control', data, function(transport) {}); }, queue: function(track) { this.queueAll($A([track.file])); }, queueAlbum: function(album) { this.queueAll(album.getTracks().pluck('file')); }, queueAll: function(tracks) { var data = $H({'files': tracks}); this.post('queue', data, this.queueView.sync.bind(this.queueView)); }, showArtist: function(artist) { // TODO: remove this this.musicView.showArtist(artist); }, showGenre: function(genre) { // TODO: remove this this.musicView.showGenre(genre); }, }); var PageControl = Class.create( { initialize: function(jukebox) { this.tab = 'artist'; this.url = ''; this.jukebox = jukebox; }, watch: function() { this.url = window.location.href; this.apply(); this.update(); this.attachToTab('artist'); this.attachToTab('genre'); this.attachToTab('search'); }, attachToTab: function(tab) { var li = $(tab + 'Tab'); if (!li) return; var a = li.select('a'); if (a.length > 0) { a[0].onclick = function() { this.setTab(tab); return false; }.bind(this); } }, update: function() { setTimeout(this.update.bind(this), 400); var url = window.location.href; if (url != this.url) { this.url = url; this.apply(); } }, apply: function() { url = unescape(this.url); if (url.indexOf("#") > -1) { var parts = url.split('#'); var params = parts[1].split('='); var key = params[0]; var value = parts[1].substring(key.length + 1); if (key == 'artist') { this.setTab(key); this.jukebox.showArtist(value); } else if (key == 'genre') { this.setTab(key); this.jukebox.showGenre(value); } else if (key == 'tab') { this.setTab(value); } } }, setTab: function(name) { if (name == this.tab) return; $(name + 'List').show(); $(this.tab + 'List').hide(); $(name + 'Tab').className = 'active'; $(this.tab + 'Tab').className = 'inactive'; this.tab = name; window.location = "#tab=" + name; this.url = window.location.href; } }); document.observe("dom:loaded", function() { var jukebox = new JukeboxView(); jukebox.attach(); jukebox.sync(); }); fookebox-0.6.1/fookebox/public/js/fookebox/core.js0000644000175000017500000000436511556607064022746 0ustar stefanstefan00000000000000/* * fookebox, http://fookebox.googlecode.com/ * * Copyright (C) 2007-2011 Stefan Ott. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* the base class for all our views */ var AjaxView = Class.create( { get: function(url, onsuccess) { var time = new Date().getTime(); new Ajax.Request(url + '?ms=' + time, { method: 'get', requestHeaders: { 'Accept': 'application/json' }, onSuccess: onsuccess, onFailure: this.transportError.bind(this), }); }, post: function(url, data, onsuccess, onfailure) { if (!onfailure) onfailure = this.transportError.bind(this); var time = new Date().getTime(); new Ajax.Request(url + '?ms=' + time, { method: 'post', requestHeaders: { 'Accept': 'application/json' }, postBody: Object.toJSON(data), contentType: 'application/json', onSuccess: onsuccess, onFailure: onfailure, }); }, transportError: function(transport) { var response = transport.responseText; if (!response) response = 'Something bad happened'; new Message(response).show(); this.hideProgressbar(); }, showProgressbar: function() { $('progress').show(); }, hideProgressbar: function() { if ($('progress')) $('progress').hide(); }, }); /* message class */ var Message = Class.create( { initialize: function(text) { this.text = text; }, show: function() { if ($('messageText').timeout) { clearTimeout($('messageText').timeout); } $('messageText').update(this.text); $('messageText').timeout = setTimeout(this.hide, 3000); Effect.Appear('message', { 'duration' : '0.1' }); }, hide: function() { Effect.Fade('message', { 'duration' : '0.4' }); }, }); fookebox-0.6.1/fookebox/public/js/fookebox/disabled.js0000644000175000017500000000250411525403231023540 0ustar stefanstefan00000000000000/* * fookebox, http://fookebox.googlecode.com/ * * Copyright (C) 2007-2011 Stefan Ott. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ var DisabledJukebox = Class.create(AjaxView, { reload: function(transport) { window.location.reload(); }, parseStatus: function(transport) { var data = transport.responseJSON; var jukebox = data.jukebox; if (jukebox) { var url = window.location.href; var base = url.substring(0, url.length - 8); window.location = base; } }, sync: function(transport) { setTimeout(this.sync.bind(this), 1000); this.get('status', this.parseStatus.bind(this)); } }); document.observe("dom:loaded", function() { jukebox = new DisabledJukebox(); jukebox.sync(); }); fookebox-0.6.1/fookebox/public/js/fookebox/program.js0000644000175000017500000000506211525403231023442 0ustar stefanstefan00000000000000/* * fookebox, http://fookebox.googlecode.com/ * * Copyright (C) 2007-2011 Stefan Ott. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // event types var TYPE_JUKEBOX = 0; var TYPE_BAND = 1; var TYPE_DJ = 2; var ProgramView = Class.create(AjaxView, { sync: function() { setTimeout(this.sync.bind(this), 1000); this.get('program/status', this.applyStatus.bind(this)); }, applyStatus: function(transport) { var data = transport.responseJSON; $('clock').update(data.time); $('currentState').update(data.currentState); $('currentState').show(); //var TYPE_JUKEBOX = 0; var events = data.events; var current = events.current; this.setCurrent(events.current); if (events.next) { this.setNext(events.next); } else { $('next').hide(); } }, setCurrent: function(event) { var name = event.title; switch (event.type) { case TYPE_JUKEBOX: var tracks = event.tracks; var artist = tracks[0].artist; var title = tracks[0].title; $('currentTitle').update(artist +" - "+ title); var box = $('currentState'); if (tracks.length > 1) { var artist = tracks[1].artist; var track = tracks[1].title; box.update('next @ ' + name + ': ' + artist + ' - ' + track); } else { box.update(name); } break; case TYPE_BAND: $('currentTitle').update(name); $('currentState').update('live'); break; case TYPE_DJ: $('currentTitle').update(name + ' [DJ]'); $('currentState').update('live'); break; } }, setNext: function(event) { $('next').show(); var title = event.title; switch (event.type) { case TYPE_JUKEBOX: $('nextTitle').update(title); break; case TYPE_BAND: $('nextTitle').update('LIVE BAND: ' + title); break; case TYPE_DJ: $('nextTitle').update(title + ' [DJ]'); break; } $('nextTime').update(event.time); } }); document.observe("dom:loaded", function() { var prog = new ProgramView(); prog.sync(); }); fookebox-0.6.1/fookebox/public/js/fookebox/schedule.js0000644000175000017500000000301411525403232023563 0ustar stefanstefan00000000000000/* * fookebox, http://fookebox.googlecode.com/ * * Copyright (C) 2007-2011 Stefan Ott. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ var ScheduleView = Class.create(AjaxView, { reload: function(transport) { window.location.reload(); }, setCurrent: function(eventId) { var data = $H({'id': eventId}); this.post('schedule/current', data, this.reload); }, remove: function(eventId) { if (!confirm('Delete this event?')) { return } var data = $H({'id': eventId}); this.post('schedule/delete', data, this.reload); }, moveUp: function(eventId) { var data = $H({ 'id': eventId, 'direction': 'up' }); this.post('schedule/move', data, this.reload); }, moveDown: function(eventId) { var data = $H({ 'id': eventId, 'direction': 'down' }); this.post('schedule/move', data, this.reload); }, }); document.observe("dom:loaded", function() { prog = new ScheduleView(); }); fookebox-0.6.1/fookebox/public/js/prototype/0000755000175000017500000000000011743153607021676 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/public/js/prototype/prototype.js0000644000175000017500000047676011525403231024312 0ustar stefanstefan00000000000000/* Prototype JavaScript framework, version 1.7 * (c) 2005-2010 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.7', Browser: (function(){ var ua = navigator.userAgent; var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; return { IE: !!window.attachEvent && !isOpera, Opera: isOpera, WebKit: ua.indexOf('AppleWebKit/') > -1, Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, MobileSafari: /Apple.*Mobile/.test(ua) } })(), BrowserFeatures: { XPath: !!document.evaluate, SelectorsAPI: !!document.querySelector, ElementExtensions: (function() { var constructor = window.Element || window.HTMLElement; return !!(constructor && constructor.prototype); })(), SpecificElementExtensions: (function() { if (typeof window.HTMLDivElement !== 'undefined') return true; var div = document.createElement('div'), form = document.createElement('form'), isSupported = false; if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { isSupported = true; } div = form = null; return isSupported; })() }, ScriptFragment: ']*>([\\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 = (function() { var IS_DONTENUM_BUGGY = (function(){ for (var p in { toString: 1 }) { if (p === 'toString') return false; } return true; })(); function subclass() {}; function create() { 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) { subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0, length = properties.length; i < length; i++) klass.addMethods(properties[i]); if (!klass.prototype.initialize) klass.prototype.initialize = Prototype.emptyFunction; klass.prototype.constructor = klass; return klass; } function addMethods(source) { var ancestor = this.superclass && this.superclass.prototype, properties = Object.keys(source); if (IS_DONTENUM_BUGGY) { if (source.toString != Object.prototype.toString) properties.push("toString"); if (source.valueOf != Object.prototype.valueOf) properties.push("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()[0] == "$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; } return { create: create, Methods: { addMethods: addMethods } }; })(); (function() { var _toString = Object.prototype.toString, NULL_TYPE = 'Null', UNDEFINED_TYPE = 'Undefined', BOOLEAN_TYPE = 'Boolean', NUMBER_TYPE = 'Number', STRING_TYPE = 'String', OBJECT_TYPE = 'Object', FUNCTION_CLASS = '[object Function]', BOOLEAN_CLASS = '[object Boolean]', NUMBER_CLASS = '[object Number]', STRING_CLASS = '[object String]', ARRAY_CLASS = '[object Array]', DATE_CLASS = '[object Date]', NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON && typeof JSON.stringify === 'function' && JSON.stringify(0) === '0' && typeof JSON.stringify(Prototype.K) === 'undefined'; function Type(o) { switch(o) { case null: return NULL_TYPE; case (void 0): return UNDEFINED_TYPE; } var type = typeof o; switch(type) { case 'boolean': return BOOLEAN_TYPE; case 'number': return NUMBER_TYPE; case 'string': return STRING_TYPE; } return OBJECT_TYPE; } function extend(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } function inspect(object) { try { if (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; } } function toJSON(value) { return Str('', { '': value }, []); } function Str(key, holder, stack) { var value = holder[key], type = typeof value; if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') { value = value.toJSON(key); } var _class = _toString.call(value); switch (_class) { case NUMBER_CLASS: case BOOLEAN_CLASS: case STRING_CLASS: value = value.valueOf(); } switch (value) { case null: return 'null'; case true: return 'true'; case false: return 'false'; } type = typeof value; switch (type) { case 'string': return value.inspect(true); case 'number': return isFinite(value) ? String(value) : 'null'; case 'object': for (var i = 0, length = stack.length; i < length; i++) { if (stack[i] === value) { throw new TypeError(); } } stack.push(value); var partial = []; if (_class === ARRAY_CLASS) { for (var i = 0, length = value.length; i < length; i++) { var str = Str(i, value, stack); partial.push(typeof str === 'undefined' ? 'null' : str); } partial = '[' + partial.join(',') + ']'; } else { var keys = Object.keys(value); for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i], str = Str(key, value, stack); if (typeof str !== "undefined") { partial.push(key.inspect(true)+ ':' + str); } } partial = '{' + partial.join(',') + '}'; } stack.pop(); return partial; } } function stringify(object) { return JSON.stringify(object); } function toQueryString(object) { return $H(object).toQueryString(); } function toHTML(object) { return object && object.toHTML ? object.toHTML() : String.interpret(object); } function keys(object) { if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); } var results = []; for (var property in object) { if (object.hasOwnProperty(property)) { results.push(property); } } return results; } function values(object) { var results = []; for (var property in object) results.push(object[property]); return results; } function clone(object) { return extend({ }, object); } function isElement(object) { return !!(object && object.nodeType == 1); } function isArray(object) { return _toString.call(object) === ARRAY_CLASS; } var hasNativeIsArray = (typeof Array.isArray == 'function') && Array.isArray([]) && !Array.isArray({}); if (hasNativeIsArray) { isArray = Array.isArray; } function isHash(object) { return object instanceof Hash; } function isFunction(object) { return _toString.call(object) === FUNCTION_CLASS; } function isString(object) { return _toString.call(object) === STRING_CLASS; } function isNumber(object) { return _toString.call(object) === NUMBER_CLASS; } function isDate(object) { return _toString.call(object) === DATE_CLASS; } function isUndefined(object) { return typeof object === "undefined"; } extend(Object, { extend: extend, inspect: inspect, toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON, toQueryString: toQueryString, toHTML: toHTML, keys: Object.keys || keys, values: values, clone: clone, isElement: isElement, isArray: isArray, isHash: isHash, isFunction: isFunction, isString: isString, isNumber: isNumber, isDate: isDate, isUndefined: isUndefined }); })(); Object.extend(Function.prototype, (function() { var slice = Array.prototype.slice; function update(array, args) { var arrayLength = array.length, length = args.length; while (length--) array[arrayLength + length] = args[length]; return array; } function merge(array, args) { array = slice.call(array, 0); return update(array, args); } function argumentNames() { var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') .replace(/\s+/g, '').split(','); return names.length == 1 && !names[0] ? [] : names; } function bind(context) { if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; var __method = this, args = slice.call(arguments, 1); return function() { var a = merge(args, arguments); return __method.apply(context, a); } } function bindAsEventListener(context) { var __method = this, args = slice.call(arguments, 1); return function(event) { var a = update([event || window.event], args); return __method.apply(context, a); } } function curry() { if (!arguments.length) return this; var __method = this, args = slice.call(arguments, 0); return function() { var a = merge(args, arguments); return __method.apply(this, a); } } function delay(timeout) { var __method = this, args = slice.call(arguments, 1); timeout = timeout * 1000; return window.setTimeout(function() { return __method.apply(__method, args); }, timeout); } function defer() { var args = update([0.01], arguments); return this.delay.apply(this, args); } function wrap(wrapper) { var __method = this; return function() { var a = update([__method.bind(this)], arguments); return wrapper.apply(this, a); } } function methodize() { if (this._methodized) return this._methodized; var __method = this; return this._methodized = function() { var a = update([this], arguments); return __method.apply(null, a); }; } return { argumentNames: argumentNames, bind: bind, bindAsEventListener: bindAsEventListener, curry: curry, delay: delay, defer: defer, wrap: wrap, methodize: methodize } })()); (function(proto) { function toISOString() { 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'; } function toJSON() { return this.toISOString(); } if (!proto.toISOString) proto.toISOString = toISOString; if (!proto.toJSON) proto.toJSON = toJSON; })(Date.prototype); 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(); this.currentlyExecuting = false; } catch(e) { this.currentlyExecuting = false; throw e; } } } }); 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, (function() { var NATIVE_JSON_PARSE_SUPPORT = window.JSON && typeof JSON.parse === 'function' && JSON.parse('{"test": true}').test; function prepareReplacement(replacement) { if (Object.isFunction(replacement)) return replacement; var template = new Template(replacement); return function(match) { return template.evaluate(match) }; } function gsub(pattern, replacement) { var result = '', source = this, match; replacement = prepareReplacement(replacement); if (Object.isString(pattern)) pattern = RegExp.escape(pattern); if (!(pattern.length || pattern.source)) { replacement = replacement(''); return replacement + source.split('').join(replacement) + 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; } function sub(pattern, replacement, count) { replacement = prepareReplacement(replacement); count = Object.isUndefined(count) ? 1 : count; return this.gsub(pattern, function(match) { if (--count < 0) return match[0]; return replacement(match); }); } function scan(pattern, iterator) { this.gsub(pattern, iterator); return String(this); } function truncate(length, truncation) { length = length || 30; truncation = Object.isUndefined(truncation) ? '...' : truncation; return this.length > length ? this.slice(0, length - truncation.length) + truncation : String(this); } function strip() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); } function stripTags() { return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); } function stripScripts() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); } function extractScripts() { var matchAll = new RegExp(Prototype.ScriptFragment, 'img'), matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return (this.match(matchAll) || []).map(function(scriptTag) { return (scriptTag.match(matchOne) || ['', ''])[1]; }); } function evalScripts() { return this.extractScripts().map(function(script) { return eval(script) }); } function escapeHTML() { return this.replace(/&/g,'&').replace(//g,'>'); } function unescapeHTML() { return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&'); } function toQueryParams(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()), 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; }); } function toArray() { return this.split(''); } function succ() { return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); } function times(count) { return count < 1 ? '' : new Array(count + 1).join(this); } function camelize() { return this.replace(/-+(.)?/g, function(match, chr) { return chr ? chr.toUpperCase() : ''; }); } function capitalize() { return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); } function underscore() { return this.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/-/g, '_') .toLowerCase(); } function dasherize() { return this.replace(/_/g, '-'); } function inspect(useDoubleQuotes) { var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { if (character in String.specialChar) { return String.specialChar[character]; } return '\\u00' + character.charCodeAt().toPaddedString(2, 16); }); if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; return "'" + escapedString.replace(/'/g, '\\\'') + "'"; } function unfilterJSON(filter) { return this.replace(filter || Prototype.JSONFilter, '$1'); } function isJSON() { var str = this; if (str.blank()) return false; str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(str); } function evalJSON(sanitize) { var json = this.unfilterJSON(), cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; if (cx.test(json)) { json = json.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } try { if (!sanitize || json.isJSON()) return eval('(' + json + ')'); } catch (e) { } throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); } function parseJSON() { var json = this.unfilterJSON(); return JSON.parse(json); } function include(pattern) { return this.indexOf(pattern) > -1; } function startsWith(pattern) { return this.lastIndexOf(pattern, 0) === 0; } function endsWith(pattern) { var d = this.length - pattern.length; return d >= 0 && this.indexOf(pattern, d) === d; } function empty() { return this == ''; } function blank() { return /^\s*$/.test(this); } function interpolate(object, pattern) { return new Template(this, pattern).evaluate(object); } return { gsub: gsub, sub: sub, scan: scan, truncate: truncate, strip: String.prototype.trim || strip, stripTags: stripTags, stripScripts: stripScripts, extractScripts: extractScripts, evalScripts: evalScripts, escapeHTML: escapeHTML, unescapeHTML: unescapeHTML, toQueryParams: toQueryParams, parseQuery: toQueryParams, toArray: toArray, succ: succ, times: times, camelize: camelize, capitalize: capitalize, underscore: underscore, dasherize: dasherize, inspect: inspect, unfilterJSON: unfilterJSON, isJSON: isJSON, evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, include: include, startsWith: startsWith, endsWith: endsWith, empty: empty, blank: blank, interpolate: interpolate }; })()); var Template = Class.create({ initialize: function(template, pattern) { this.template = template.toString(); this.pattern = pattern || Template.Pattern; }, evaluate: function(object) { if (object && Object.isFunction(object.toTemplateReplacements)) object = object.toTemplateReplacements(); return this.template.gsub(this.pattern, function(match) { if (object == null) return (match[1] + ''); var before = match[1] || ''; if (before == '\\') return match[2]; var ctx = object, expr = match[3], pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; match = pattern.exec(expr); if (match == null) return before; while (match != null) { var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : 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 = (function() { function each(iterator, context) { var index = 0; try { this._each(function(value) { iterator.call(context, value, index++); }); } catch (e) { if (e != $break) throw e; } return this; } function eachSlice(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); } function all(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; } function any(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; } function collect(iterator, context) { iterator = iterator || Prototype.K; var results = []; this.each(function(value, index) { results.push(iterator.call(context, value, index)); }); return results; } function detect(iterator, context) { var result; this.each(function(value, index) { if (iterator.call(context, value, index)) { result = value; throw $break; } }); return result; } function findAll(iterator, context) { var results = []; this.each(function(value, index) { if (iterator.call(context, value, index)) results.push(value); }); return results; } function grep(filter, iterator, context) { iterator = iterator || Prototype.K; var results = []; if (Object.isString(filter)) filter = new RegExp(RegExp.escape(filter)); this.each(function(value, index) { if (filter.match(value)) results.push(iterator.call(context, value, index)); }); return results; } function include(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; } function inGroupsOf(number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; return this.eachSlice(number, function(slice) { while(slice.length < number) slice.push(fillWith); return slice; }); } function inject(memo, iterator, context) { this.each(function(value, index) { memo = iterator.call(context, memo, value, index); }); return memo; } function invoke(method) { var args = $A(arguments).slice(1); return this.map(function(value) { return value[method].apply(value, args); }); } function max(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; } function min(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; } function partition(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]; } function pluck(property) { var results = []; this.each(function(value) { results.push(value[property]); }); return results; } function reject(iterator, context) { var results = []; this.each(function(value, index) { if (!iterator.call(context, value, index)) results.push(value); }); return results; } function sortBy(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'); } function toArray() { return this.map(); } function zip() { 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)); }); } function size() { return this.toArray().length; } function inspect() { return '#'; } return { each: each, eachSlice: eachSlice, all: all, every: all, any: any, some: any, collect: collect, map: collect, detect: detect, findAll: findAll, select: findAll, filter: findAll, grep: grep, include: include, member: include, inGroupsOf: inGroupsOf, inject: inject, invoke: invoke, max: max, min: min, partition: partition, pluck: pluck, reject: reject, sortBy: sortBy, toArray: toArray, entries: toArray, zip: zip, size: size, inspect: inspect, find: detect }; })(); function $A(iterable) { if (!iterable) return []; if ('toArray' in Object(iterable)) return iterable.toArray(); var length = iterable.length || 0, results = new Array(length); while (length--) results[length] = iterable[length]; return results; } function $w(string) { if (!Object.isString(string)) return []; string = string.strip(); return string ? string.split(/\s+/) : []; } Array.from = $A; (function() { var arrayProto = Array.prototype, slice = arrayProto.slice, _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available function each(iterator, context) { for (var i = 0, length = this.length >>> 0; i < length; i++) { if (i in this) iterator.call(context, this[i], i, this); } } if (!_each) _each = each; function clear() { this.length = 0; return this; } function first() { return this[0]; } function last() { return this[this.length - 1]; } function compact() { return this.select(function(value) { return value != null; }); } function flatten() { return this.inject([], function(array, value) { if (Object.isArray(value)) return array.concat(value.flatten()); array.push(value); return array; }); } function without() { var values = slice.call(arguments, 0); return this.select(function(value) { return !values.include(value); }); } function reverse(inline) { return (inline === false ? this.toArray() : this)._reverse(); } function uniq(sorted) { return this.inject([], function(array, value, index) { if (0 == index || (sorted ? array.last() != value : !array.include(value))) array.push(value); return array; }); } function intersect(array) { return this.uniq().findAll(function(item) { return array.detect(function(value) { return item === value }); }); } function clone() { return slice.call(this, 0); } function size() { return this.length; } function inspect() { return '[' + this.map(Object.inspect).join(', ') + ']'; } function indexOf(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; } function lastIndexOf(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; } function concat() { var array = slice.call(this, 0), item; for (var i = 0, length = arguments.length; i < length; i++) { item = arguments[i]; if (Object.isArray(item) && !('callee' in item)) { for (var j = 0, arrayLength = item.length; j < arrayLength; j++) array.push(item[j]); } else { array.push(item); } } return array; } Object.extend(arrayProto, Enumerable); if (!arrayProto._reverse) arrayProto._reverse = arrayProto.reverse; Object.extend(arrayProto, { _each: _each, clear: clear, first: first, last: last, compact: compact, flatten: flatten, without: without, reverse: reverse, uniq: uniq, intersect: intersect, clone: clone, toArray: clone, size: size, inspect: inspect }); var CONCAT_ARGUMENTS_BUGGY = (function() { return [].concat(arguments)[0][0] !== 1; })(1,2) if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; if (!arrayProto.indexOf) arrayProto.indexOf = indexOf; if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf; })(); function $H(object) { return new Hash(object); }; var Hash = Class.create(Enumerable, (function() { function initialize(object) { this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); } function _each(iterator) { for (var key in this._object) { var value = this._object[key], pair = [key, value]; pair.key = key; pair.value = value; iterator(pair); } } function set(key, value) { return this._object[key] = value; } function get(key) { if (this._object[key] !== Object.prototype[key]) return this._object[key]; } function unset(key) { var value = this._object[key]; delete this._object[key]; return value; } function toObject() { return Object.clone(this._object); } function keys() { return this.pluck('key'); } function values() { return this.pluck('value'); } function index(value) { var match = this.detect(function(pair) { return pair.value === value; }); return match && match.key; } function merge(object) { return this.clone().update(object); } function update(object) { return new Hash(object).inject(this, function(result, pair) { result.set(pair.key, pair.value); return result; }); } function toQueryPair(key, value) { if (Object.isUndefined(value)) return key; return key + '=' + encodeURIComponent(String.interpret(value)); } function toQueryString() { return this.inject([], function(results, pair) { var key = encodeURIComponent(pair.key), values = pair.value; if (values && typeof values == 'object') { if (Object.isArray(values)) { var queryValues = []; for (var i = 0, len = values.length, value; i < len; i++) { value = values[i]; queryValues.push(toQueryPair(key, value)); } return results.concat(queryValues); } } else results.push(toQueryPair(key, values)); return results; }).join('&'); } function inspect() { return '#'; } function clone() { return new Hash(this); } return { initialize: initialize, _each: _each, set: set, get: get, unset: unset, toObject: toObject, toTemplateReplacements: toObject, keys: keys, values: values, index: index, merge: merge, update: update, toQueryString: toQueryString, inspect: inspect, toJSON: toObject, clone: clone }; })()); Hash.from = $H; Object.extend(Number.prototype, (function() { function toColorPart() { return this.toPaddedString(2, 16); } function succ() { return this + 1; } function times(iterator, context) { $R(0, this, true).each(iterator, context); return this; } function toPaddedString(length, radix) { var string = this.toString(radix || 10); return '0'.times(length - string.length) + string; } function abs() { return Math.abs(this); } function round() { return Math.round(this); } function ceil() { return Math.ceil(this); } function floor() { return Math.floor(this); } return { toColorPart: toColorPart, succ: succ, times: times, toPaddedString: toPaddedString, abs: abs, round: round, ceil: ceil, floor: floor }; })()); function $R(start, end, exclusive) { return new ObjectRange(start, end, exclusive); } var ObjectRange = Class.create(Enumerable, (function() { function initialize(start, end, exclusive) { this.start = start; this.end = end; this.exclusive = exclusive; } function _each(iterator) { var value = this.start; while (this.include(value)) { iterator(value); value = value.succ(); } } function include(value) { if (value < this.start) return false; if (this.exclusive) return value < this.end; return value <= this.end; } return { initialize: initialize, _each: _each, include: include }; })()); var Abstract = { }; 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; } }; 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.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.isString(this.options.parameters) ? this.options.parameters : Object.toQueryString(this.options.parameters); if (!['get', 'post'].include(this.method)) { params += (params ? '&' : '') + "_method=" + this.method; this.method = 'post'; } if (params && this.method === 'get') { this.url += (this.url.include('?') ? '&' : '?') + params; } this.parameters = params.toQueryParams(); 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'; } 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) || status == 304; }, getStatus: function() { try { if (this.transport.status === 1223) return 204; 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') { 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 (!Node) var Node = { }; if (!Node.ELEMENT_NODE) { 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(global) { function shouldUseCache(tagName, attributes) { if (tagName === 'select') return false; if ('type' in attributes) return false; return true; } var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ try { var el = document.createElement(''); return el.tagName.toLowerCase() === 'input' && el.name === 'x'; } catch(err) { return false; } })(); var element = global.Element; global.Element = function(tagName, attributes) { attributes = attributes || { }; tagName = tagName.toLowerCase(); var cache = Element.cache; if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && 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)); var node = shouldUseCache(tagName, attributes) ? cache[tagName].cloneNode(false) : document.createElement(tagName); return Element.writeAttribute(node, attributes); }; Object.extend(global.Element, element || { }); if (element) global.Element.prototype = element.prototype; })(this); Element.idCounter = 1; Element.cache = { }; Element._purgeElement = function(element) { var uid = element._prototypeUID; if (uid) { Element.stopObserving(element); element._prototypeUID = void 0; delete Element.Storage[uid]; } } 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(){ var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ var el = document.createElement("select"), isBuggy = true; el.innerHTML = ""; if (el.options && el.options[0]) { isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; } el = null; return isBuggy; })(); var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ try { var el = document.createElement("table"); if (el && el.tBodies) { el.innerHTML = "test"; var isBuggy = typeof el.tBodies[0] == "undefined"; el = null; return isBuggy; } } catch (e) { return true; } })(); var LINK_ELEMENT_INNERHTML_BUGGY = (function() { try { var el = document.createElement('div'); el.innerHTML = ""; var isBuggy = (el.childNodes.length === 0); el = null; return isBuggy; } catch(e) { return true; } })(); var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY; var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { var s = document.createElement("script"), isBuggy = false; try { s.appendChild(document.createTextNode("")); isBuggy = !s.firstChild || s.firstChild && s.firstChild.nodeType !== 3; } catch (e) { isBuggy = true; } s = null; return isBuggy; })(); function update(element, content) { element = $(element); var purgeElement = Element._purgeElement; var descendants = element.getElementsByTagName('*'), i = descendants.length; while (i--) purgeElement(descendants[i]); 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 === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { element.text = content; return element; } if (ANY_INNERHTML_BUGGY) { if (tagName in Element._insertionTranslations.tags) { while (element.firstChild) { element.removeChild(element.firstChild); } Element._getContentFromAnonymousElement(tagName, content.stripScripts()) .each(function(node) { element.appendChild(node) }); } else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf(' -1) { while (element.firstChild) { element.removeChild(element.firstChild); } var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true); nodes.each(function(node) { element.appendChild(node) }); } else { element.innerHTML = content.stripScripts(); } } else { element.innerHTML = content.stripScripts(); } content.evalScripts.bind(content).defer(); return element; } return update; })(), 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(), value = (element[property] || '').toString(); if (value) result += ' ' + attribute + '=' + value.inspect(true); }); return result + '>'; }, recursivelyCollect: function(element, property, maximumLength) { element = $(element); maximumLength = maximumLength || -1; var elements = []; while (element = element[property]) { if (element.nodeType == 1) elements.push(Element.extend(element)); if (elements.length == maximumLength) break; } return elements; }, ancestors: function(element) { return Element.recursivelyCollect(element, 'parentNode'); }, descendants: function(element) { return Element.select(element, "*"); }, firstDescendant: function(element) { element = $(element).firstChild; while (element && element.nodeType != 1) element = element.nextSibling; return $(element); }, immediateDescendants: function(element) { var results = [], child = $(element).firstChild; while (child) { if (child.nodeType === 1) { results.push(Element.extend(child)); } child = child.nextSibling; } return results; }, previousSiblings: function(element, maximumLength) { return Element.recursivelyCollect(element, 'previousSibling'); }, nextSiblings: function(element) { return Element.recursivelyCollect(element, 'nextSibling'); }, siblings: function(element) { element = $(element); return Element.previousSiblings(element).reverse() .concat(Element.nextSiblings(element)); }, match: function(element, selector) { element = $(element); if (Object.isString(selector)) return Prototype.Selector.match(element, selector); return selector.match(element); }, up: function(element, expression, index) { element = $(element); if (arguments.length == 1) return $(element.parentNode); var ancestors = Element.ancestors(element); return Object.isNumber(expression) ? ancestors[expression] : Prototype.Selector.find(ancestors, expression, index); }, down: function(element, expression, index) { element = $(element); if (arguments.length == 1) return Element.firstDescendant(element); return Object.isNumber(expression) ? Element.descendants(element)[expression] : Element.select(element, expression)[index || 0]; }, previous: function(element, expression, index) { element = $(element); if (Object.isNumber(expression)) index = expression, expression = false; if (!Object.isNumber(index)) index = 0; if (expression) { return Prototype.Selector.find(element.previousSiblings(), expression, index); } else { return element.recursivelyCollect("previousSibling", index + 1)[index]; } }, next: function(element, expression, index) { element = $(element); if (Object.isNumber(expression)) index = expression, expression = false; if (!Object.isNumber(index)) index = 0; if (expression) { return Prototype.Selector.find(element.nextSiblings(), expression, index); } else { var maximumLength = Object.isNumber(index) ? index + 1 : 1; return element.recursivelyCollect("nextSibling", index + 1)[index]; } }, select: function(element) { element = $(element); var expressions = Array.prototype.slice.call(arguments, 1).join(', '); return Prototype.Selector.select(expressions, element); }, adjacent: function(element) { element = $(element); var expressions = Array.prototype.slice.call(arguments, 1).join(', '); return Prototype.Selector.select(expressions, element.parentNode).without(element); }, identify: function(element) { element = $(element); var id = Element.readAttribute(element, 'id'); if (id) return id; do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id)); Element.writeAttribute(element, '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(element).height; }, getWidth: function(element) { return Element.getDimensions(element).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(element, 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(element, className) ? 'removeClassName' : 'addClassName'](element, className); }, 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(element); 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; }, makePositioned: function(element) { element = $(element); var pos = Element.getStyle(element, 'position'); if (pos == 'static' || !pos) { element._madePositioned = true; element.style.position = 'relative'; 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; }, clonePosition: function(element, source) { var options = Object.extend({ setLeft: true, setTop: true, setWidth: true, setHeight: true, offsetTop: 0, offsetLeft: 0 }, arguments[2] || { }); source = $(source); var p = Element.viewportOffset(source), delta = [0, 0], parent = null; element = $(element); if (Element.getStyle(element, 'position') == 'absolute') { parent = Element.getOffsetParent(element); delta = Element.viewportOffset(parent); } if (parent == document.body) { delta[0] -= document.body.offsetLeft; delta[1] -= document.body.offsetTop; } 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; } }; 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 'height': case 'width': if (!Element.visible(element)) return null; 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) { 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 = (function(){ var classProp = 'className', forProp = 'for', el = document.createElement('div'); el.setAttribute(classProp, 'x'); if (el.className !== 'x') { el.setAttribute('class', 'x'); if (el.className === 'x') { classProp = 'class'; } } el = null; el = document.createElement('label'); el.setAttribute(forProp, 'x'); if (el.htmlFor !== 'x') { el.setAttribute('htmlFor', 'x'); if (el.htmlFor === 'x') { forProp = 'htmlFor'; } } el = null; return { read: { names: { 'class': classProp, 'className': classProp, 'for': forProp, 'htmlFor': forProp }, values: { _getAttr: function(element, attribute) { return element.getAttribute(attribute); }, _getAttr2: function(element, attribute) { return element.getAttribute(attribute, 2); }, _getAttrNode: function(element, attribute) { var node = element.getAttributeNode(attribute); return node ? node.value : ""; }, _getEv: (function(){ var el = document.createElement('div'), f; el.onclick = Prototype.emptyFunction; var value = el.getAttribute('onclick'); if (String(value).indexOf('{') > -1) { f = function(element, attribute) { attribute = element.getAttribute(attribute); if (!attribute) return null; attribute = attribute.toString(); attribute = attribute.split('{')[1]; attribute = attribute.split('}')[0]; return attribute.strip(); }; } else if (value === '') { f = function(element, attribute) { attribute = element.getAttribute(attribute); if (!attribute) return null; return attribute.strip(); }; } el = null; return f; })(), _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._getAttr2, src: v._getAttr2, 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); if (Prototype.BrowserFeatures.ElementExtensions) { (function() { function _descendants(element) { var nodes = element.getElementsByTagName('*'), results = []; for (var i = 0, node; node = nodes[i]; i++) if (node.tagName !== "!") // Filter out comment nodes. results.push(node); return results; } Element.Methods.down = function(element, expression, index) { element = $(element); if (arguments.length == 1) return element.firstDescendant(); return Object.isNumber(expression) ? _descendants(element)[expression] : Element.select(element, expression)[index || 0]; } })(); } } 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; }; } if ('outerHTML' in document.documentElement) { 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(), 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, force) { var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; var workaround = false; if (t) workaround = true; else if (force) { workaround = true; t = ['', '', 0]; } if (workaround) { div.innerHTML = ' ' + t[0] + html + t[1]; div.removeChild(div.firstChild); for (var i = t[2]; i--; ) { 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: ['', '
', 1], TBODY: ['', '
', 2], TR: ['', '
', 3], TD: ['
', '
', 4], SELECT: ['', 1] } }; (function() { var tags = Element._insertionTranslations.tags; Object.extend(tags, { THEAD: tags.TBODY, TFOOT: tags.TBODY, TH: tags.TD }); })(); 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); (function(div) { if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) { window.HTMLElement = { }; window.HTMLElement.prototype = div['__proto__']; Prototype.BrowserFeatures.ElementExtensions = true; } div = null; })(document.createElement('div')); Element.extend = (function() { function checkDeficiency(tagName) { if (typeof window.Element != 'undefined') { var proto = window.Element.prototype; if (proto) { var id = '_' + (Math.random()+'').slice(2), el = document.createElement(tagName); proto[id] = 'x'; var isBuggy = (el[id] !== 'x'); delete proto[id]; el = null; return isBuggy; } } return false; } function extendElementWith(element, methods) { for (var property in methods) { var value = methods[property]; if (Object.isFunction(value) && !(property in element)) element[property] = value.methodize(); } } var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object'); if (Prototype.BrowserFeatures.SpecificElementExtensions) { if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) { return function(element) { if (element && typeof element._extendedByPrototype == 'undefined') { var t = element.tagName; if (t && (/^(?:object|applet|embed)$/i.test(t))) { extendElementWith(element, Element.Methods); extendElementWith(element, Element.Methods.Simulated); extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]); } } return element; } } return Prototype.K; } var Methods = { }, ByTag = Element.Methods.ByTag; var extend = Object.extend(function(element) { if (!element || typeof element._extendedByPrototype != 'undefined' || element.nodeType != 1 || element == window) return element; var methods = Object.clone(Methods), tagName = element.tagName.toUpperCase(); if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); extendElementWith(element, methods); element._extendedByPrototype = Prototype.emptyFunction; return element; }, { refresh: function() { if (!Prototype.BrowserFeatures.ElementExtensions) { Object.extend(Methods, Element.Methods); Object.extend(Methods, Element.Methods.Simulated); } } }); extend.refresh(); return extend; })(); if (document.documentElement.hasAttribute) { Element.hasAttribute = function(element, attribute) { return element.hasAttribute(attribute); }; } else { Element.hasAttribute = Element.Methods.Simulated.hasAttribute; } 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), "BUTTON": 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]; var element = document.createElement(tagName), proto = element['__proto__'] || element.constructor.prototype; element = null; return proto; } var elementPrototype = window.HTMLElement ? HTMLElement.prototype : Element.prototype; if (F.ElementExtensions) { copy(Element.Methods, elementPrototype); copy(Element.Methods.Simulated, elementPrototype, 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() { return { width: this.getWidth(), height: this.getHeight() }; }, getScrollOffsets: function() { return Element._returnOffset( window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); } }; (function(viewport) { var B = Prototype.Browser, doc = document, element, property = {}; function getRootElement() { if (B.WebKit && !doc.evaluate) return document; if (B.Opera && window.parseFloat(window.opera.version()) < 9.5) return document.body; return document.documentElement; } function define(D) { if (!element) element = getRootElement(); property[D] = 'client' + D; viewport['get' + D] = function() { return element[property[D]] }; return viewport['get' + D](); } viewport.getWidth = define.curry('Width'); viewport.getHeight = define.curry('Height'); })(document.viewport); Element.Storage = { UID: 1 }; Element.addMethods({ getStorage: function(element) { if (!(element = $(element))) return; var uid; if (element === window) { uid = 0; } else { if (typeof element._prototypeUID === "undefined") element._prototypeUID = Element.Storage.UID++; uid = element._prototypeUID; } if (!Element.Storage[uid]) Element.Storage[uid] = $H(); return Element.Storage[uid]; }, store: function(element, key, value) { if (!(element = $(element))) return; if (arguments.length === 2) { Element.getStorage(element).update(key); } else { Element.getStorage(element).set(key, value); } return element; }, retrieve: function(element, key, defaultValue) { if (!(element = $(element))) return; var hash = Element.getStorage(element), value = hash.get(key); if (Object.isUndefined(value)) { hash.set(key, defaultValue); value = defaultValue; } return value; }, clone: function(element, deep) { if (!(element = $(element))) return; var clone = element.cloneNode(deep); clone._prototypeUID = void 0; if (deep) { var descendants = Element.select(clone, '*'), i = descendants.length; while (i--) { descendants[i]._prototypeUID = void 0; } } return Element.extend(clone); }, purge: function(element) { if (!(element = $(element))) return; var purgeElement = Element._purgeElement; purgeElement(element); var descendants = element.getElementsByTagName('*'), i = descendants.length; while (i--) purgeElement(descendants[i]); return null; } }); (function() { function toDecimal(pctString) { var match = pctString.match(/^(\d+)%?$/i); if (!match) return null; return (Number(match[1]) / 100); } function getPixelValue(value, property, context) { var element = null; if (Object.isElement(value)) { element = value; value = element.getStyle(property); } if (value === null) { return null; } if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { return window.parseFloat(value); } var isPercentage = value.include('%'), isViewport = (context === document.viewport); if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) { var style = element.style.left, rStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; element.style.left = value || 0; value = element.style.pixelLeft; element.style.left = style; element.runtimeStyle.left = rStyle; return value; } if (element && isPercentage) { context = context || element.parentNode; var decimal = toDecimal(value); var whole = null; var position = element.getStyle('position'); var isHorizontal = property.include('left') || property.include('right') || property.include('width'); var isVertical = property.include('top') || property.include('bottom') || property.include('height'); if (context === document.viewport) { if (isHorizontal) { whole = document.viewport.getWidth(); } else if (isVertical) { whole = document.viewport.getHeight(); } } else { if (isHorizontal) { whole = $(context).measure('width'); } else if (isVertical) { whole = $(context).measure('height'); } } return (whole === null) ? 0 : whole * decimal; } return 0; } function toCSSPixels(number) { if (Object.isString(number) && number.endsWith('px')) { return number; } return number + 'px'; } function isDisplayed(element) { var originalElement = element; while (element && element.parentNode) { var display = element.getStyle('display'); if (display === 'none') { return false; } element = $(element.parentNode); } return true; } var hasLayout = Prototype.K; if ('currentStyle' in document.documentElement) { hasLayout = function(element) { if (!element.currentStyle.hasLayout) { element.style.zoom = 1; } return element; }; } function cssNameFor(key) { if (key.include('border')) key = key + '-width'; return key.camelize(); } Element.Layout = Class.create(Hash, { initialize: function($super, element, preCompute) { $super(); this.element = $(element); Element.Layout.PROPERTIES.each( function(property) { this._set(property, null); }, this); if (preCompute) { this._preComputing = true; this._begin(); Element.Layout.PROPERTIES.each( this._compute, this ); this._end(); this._preComputing = false; } }, _set: function(property, value) { return Hash.prototype.set.call(this, property, value); }, set: function(property, value) { throw "Properties of Element.Layout are read-only."; }, get: function($super, property) { var value = $super(property); return value === null ? this._compute(property) : value; }, _begin: function() { if (this._prepared) return; var element = this.element; if (isDisplayed(element)) { this._prepared = true; return; } var originalStyles = { position: element.style.position || '', width: element.style.width || '', visibility: element.style.visibility || '', display: element.style.display || '' }; element.store('prototype_original_styles', originalStyles); var position = element.getStyle('position'), width = element.getStyle('width'); if (width === "0px" || width === null) { element.style.display = 'block'; width = element.getStyle('width'); } var context = (position === 'fixed') ? document.viewport : element.parentNode; element.setStyle({ position: 'absolute', visibility: 'hidden', display: 'block' }); var positionedWidth = element.getStyle('width'); var newWidth; if (width && (positionedWidth === width)) { newWidth = getPixelValue(element, 'width', context); } else if (position === 'absolute' || position === 'fixed') { newWidth = getPixelValue(element, 'width', context); } else { var parent = element.parentNode, pLayout = $(parent).getLayout(); newWidth = pLayout.get('width') - this.get('margin-left') - this.get('border-left') - this.get('padding-left') - this.get('padding-right') - this.get('border-right') - this.get('margin-right'); } element.setStyle({ width: newWidth + 'px' }); this._prepared = true; }, _end: function() { var element = this.element; var originalStyles = element.retrieve('prototype_original_styles'); element.store('prototype_original_styles', null); element.setStyle(originalStyles); this._prepared = false; }, _compute: function(property) { var COMPUTATIONS = Element.Layout.COMPUTATIONS; if (!(property in COMPUTATIONS)) { throw "Property not found."; } return this._set(property, COMPUTATIONS[property].call(this, this.element)); }, toObject: function() { var args = $A(arguments); var keys = (args.length === 0) ? Element.Layout.PROPERTIES : args.join(' ').split(' '); var obj = {}; keys.each( function(key) { if (!Element.Layout.PROPERTIES.include(key)) return; var value = this.get(key); if (value != null) obj[key] = value; }, this); return obj; }, toHash: function() { var obj = this.toObject.apply(this, arguments); return new Hash(obj); }, toCSS: function() { var args = $A(arguments); var keys = (args.length === 0) ? Element.Layout.PROPERTIES : args.join(' ').split(' '); var css = {}; keys.each( function(key) { if (!Element.Layout.PROPERTIES.include(key)) return; if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return; var value = this.get(key); if (value != null) css[cssNameFor(key)] = value + 'px'; }, this); return css; }, inspect: function() { return "#"; } }); Object.extend(Element.Layout, { PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'), COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'), COMPUTATIONS: { 'height': function(element) { if (!this._preComputing) this._begin(); var bHeight = this.get('border-box-height'); if (bHeight <= 0) { if (!this._preComputing) this._end(); return 0; } var bTop = this.get('border-top'), bBottom = this.get('border-bottom'); var pTop = this.get('padding-top'), pBottom = this.get('padding-bottom'); if (!this._preComputing) this._end(); return bHeight - bTop - bBottom - pTop - pBottom; }, 'width': function(element) { if (!this._preComputing) this._begin(); var bWidth = this.get('border-box-width'); if (bWidth <= 0) { if (!this._preComputing) this._end(); return 0; } var bLeft = this.get('border-left'), bRight = this.get('border-right'); var pLeft = this.get('padding-left'), pRight = this.get('padding-right'); if (!this._preComputing) this._end(); return bWidth - bLeft - bRight - pLeft - pRight; }, 'padding-box-height': function(element) { var height = this.get('height'), pTop = this.get('padding-top'), pBottom = this.get('padding-bottom'); return height + pTop + pBottom; }, 'padding-box-width': function(element) { var width = this.get('width'), pLeft = this.get('padding-left'), pRight = this.get('padding-right'); return width + pLeft + pRight; }, 'border-box-height': function(element) { if (!this._preComputing) this._begin(); var height = element.offsetHeight; if (!this._preComputing) this._end(); return height; }, 'border-box-width': function(element) { if (!this._preComputing) this._begin(); var width = element.offsetWidth; if (!this._preComputing) this._end(); return width; }, 'margin-box-height': function(element) { var bHeight = this.get('border-box-height'), mTop = this.get('margin-top'), mBottom = this.get('margin-bottom'); if (bHeight <= 0) return 0; return bHeight + mTop + mBottom; }, 'margin-box-width': function(element) { var bWidth = this.get('border-box-width'), mLeft = this.get('margin-left'), mRight = this.get('margin-right'); if (bWidth <= 0) return 0; return bWidth + mLeft + mRight; }, 'top': function(element) { var offset = element.positionedOffset(); return offset.top; }, 'bottom': function(element) { var offset = element.positionedOffset(), parent = element.getOffsetParent(), pHeight = parent.measure('height'); var mHeight = this.get('border-box-height'); return pHeight - mHeight - offset.top; }, 'left': function(element) { var offset = element.positionedOffset(); return offset.left; }, 'right': function(element) { var offset = element.positionedOffset(), parent = element.getOffsetParent(), pWidth = parent.measure('width'); var mWidth = this.get('border-box-width'); return pWidth - mWidth - offset.left; }, 'padding-top': function(element) { return getPixelValue(element, 'paddingTop'); }, 'padding-bottom': function(element) { return getPixelValue(element, 'paddingBottom'); }, 'padding-left': function(element) { return getPixelValue(element, 'paddingLeft'); }, 'padding-right': function(element) { return getPixelValue(element, 'paddingRight'); }, 'border-top': function(element) { return getPixelValue(element, 'borderTopWidth'); }, 'border-bottom': function(element) { return getPixelValue(element, 'borderBottomWidth'); }, 'border-left': function(element) { return getPixelValue(element, 'borderLeftWidth'); }, 'border-right': function(element) { return getPixelValue(element, 'borderRightWidth'); }, 'margin-top': function(element) { return getPixelValue(element, 'marginTop'); }, 'margin-bottom': function(element) { return getPixelValue(element, 'marginBottom'); }, 'margin-left': function(element) { return getPixelValue(element, 'marginLeft'); }, 'margin-right': function(element) { return getPixelValue(element, 'marginRight'); } } }); if ('getBoundingClientRect' in document.documentElement) { Object.extend(Element.Layout.COMPUTATIONS, { 'right': function(element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), pRect = parent.getBoundingClientRect(); return (pRect.right - rect.right).round(); }, 'bottom': function(element) { var parent = hasLayout(element.getOffsetParent()); var rect = element.getBoundingClientRect(), pRect = parent.getBoundingClientRect(); return (pRect.bottom - rect.bottom).round(); } }); } Element.Offset = Class.create({ initialize: function(left, top) { this.left = left.round(); this.top = top.round(); this[0] = this.left; this[1] = this.top; }, relativeTo: function(offset) { return new Element.Offset( this.left - offset.left, this.top - offset.top ); }, inspect: function() { return "#".interpolate(this); }, toString: function() { return "[#{left}, #{top}]".interpolate(this); }, toArray: function() { return [this.left, this.top]; } }); function getLayout(element, preCompute) { return new Element.Layout(element, preCompute); } function measure(element, property) { return $(element).getLayout().get(property); } function getDimensions(element) { element = $(element); var display = Element.getStyle(element, 'display'); if (display && display !== 'none') { return { width: element.offsetWidth, height: element.offsetHeight }; } var style = element.style; var originalStyles = { visibility: style.visibility, position: style.position, display: style.display }; var newStyles = { visibility: 'hidden', display: 'block' }; if (originalStyles.position !== 'fixed') newStyles.position = 'absolute'; Element.setStyle(element, newStyles); var dimensions = { width: element.offsetWidth, height: element.offsetHeight }; Element.setStyle(element, originalStyles); return dimensions; } function getOffsetParent(element) { element = $(element); if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) return $(document.body); var isInline = (Element.getStyle(element, 'display') === 'inline'); if (!isInline && element.offsetParent) return $(element.offsetParent); while ((element = element.parentNode) && element !== document.body) { if (Element.getStyle(element, 'position') !== 'static') { return isHtml(element) ? $(document.body) : $(element); } } return $(document.body); } function cumulativeOffset(element) { element = $(element); var valueT = 0, valueL = 0; if (element.parentNode) { do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); } return new Element.Offset(valueL, valueT); } function positionedOffset(element) { element = $(element); var layout = element.getLayout(); var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; if (element) { if (isBody(element)) break; var p = Element.getStyle(element, 'position'); if (p !== 'static') break; } } while (element); valueL -= layout.get('margin-top'); valueT -= layout.get('margin-left'); return new Element.Offset(valueL, valueT); } function cumulativeScrollOffset(element) { var valueT = 0, valueL = 0; do { valueT += element.scrollTop || 0; valueL += element.scrollLeft || 0; element = element.parentNode; } while (element); return new Element.Offset(valueL, valueT); } function viewportOffset(forElement) { element = $(element); var valueT = 0, valueL = 0, docBody = document.body; var element = forElement; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; if (element.offsetParent == docBody && Element.getStyle(element, 'position') == 'absolute') break; } while (element = element.offsetParent); element = forElement; do { if (element != docBody) { valueT -= element.scrollTop || 0; valueL -= element.scrollLeft || 0; } } while (element = element.parentNode); return new Element.Offset(valueL, valueT); } function absolutize(element) { element = $(element); if (Element.getStyle(element, 'position') === 'absolute') { return element; } var offsetParent = getOffsetParent(element); var eOffset = element.viewportOffset(), pOffset = offsetParent.viewportOffset(); var offset = eOffset.relativeTo(pOffset); var layout = element.getLayout(); element.store('prototype_absolutize_original_styles', { left: element.getStyle('left'), top: element.getStyle('top'), width: element.getStyle('width'), height: element.getStyle('height') }); element.setStyle({ position: 'absolute', top: offset.top + 'px', left: offset.left + 'px', width: layout.get('width') + 'px', height: layout.get('height') + 'px' }); return element; } function relativize(element) { element = $(element); if (Element.getStyle(element, 'position') === 'relative') { return element; } var originalStyles = element.retrieve('prototype_absolutize_original_styles'); if (originalStyles) element.setStyle(originalStyles); return element; } if (Prototype.Browser.IE) { getOffsetParent = getOffsetParent.wrap( function(proceed, element) { element = $(element); if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element)) 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; } ); positionedOffset = positionedOffset.wrap(function(proceed, element) { element = $(element); if (!element.parentNode) return new Element.Offset(0, 0); var position = element.getStyle('position'); if (position !== 'static') return proceed(element); var offsetParent = element.getOffsetParent(); if (offsetParent && offsetParent.getStyle('position') === 'fixed') hasLayout(offsetParent); element.setStyle({ position: 'relative' }); var value = proceed(element); element.setStyle({ position: position }); return value; }); } else if (Prototype.Browser.Webkit) { cumulativeOffset = function(element) { element = $(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 new Element.Offset(valueL, valueT); }; } Element.addMethods({ getLayout: getLayout, measure: measure, getDimensions: getDimensions, getOffsetParent: getOffsetParent, cumulativeOffset: cumulativeOffset, positionedOffset: positionedOffset, cumulativeScrollOffset: cumulativeScrollOffset, viewportOffset: viewportOffset, absolutize: absolutize, relativize: relativize }); function isBody(element) { return element.nodeName.toUpperCase() === 'BODY'; } function isHtml(element) { return element.nodeName.toUpperCase() === 'HTML'; } function isDocument(element) { return element.nodeType === Node.DOCUMENT_NODE; } function isDetached(element) { return element !== document.body && !Element.descendantOf(element, document.body); } if ('getBoundingClientRect' in document.documentElement) { Element.addMethods({ viewportOffset: function(element) { element = $(element); if (isDetached(element)) return new Element.Offset(0, 0); var rect = element.getBoundingClientRect(), docEl = document.documentElement; return new Element.Offset(rect.left - docEl.clientLeft, rect.top - docEl.clientTop); } }); } })(); window.$$ = function() { var expression = $A(arguments).join(', '); return Prototype.Selector.select(expression, document); }; Prototype.Selector = (function() { function select() { throw new Error('Method "Prototype.Selector.select" must be defined.'); } function match() { throw new Error('Method "Prototype.Selector.match" must be defined.'); } function find(elements, expression, index) { index = index || 0; var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i; for (i = 0; i < length; i++) { if (match(elements[i], expression) && index == matchIndex++) { return Element.extend(elements[i]); } } } function extendElements(elements) { for (var i = 0, length = elements.length; i < length; i++) { Element.extend(elements[i]); } return elements; } var K = Prototype.K; return { select: select, match: match, find: find, extendElements: (Element.extend === K) ? K : extendElements, extendElement: Element.extend }; })(); /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context), soFar = selector; while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) selector += parts.shift(); set = posProcess( selector, set ); } } } else { if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { throw "Syntax error, unrecognized expression: " + (cur || selector); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.match[ type ].exec( expr )) != null ) { var filter = Expr.filter[ type ], found, item; anyFound = false; if ( curLoop == result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } if ( expr == old ) { if ( anyFound == null ) { throw "Syntax error, unrecognized expression: " + expr; } else { break; } } old = expr; } return curLoop; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part, isXML){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag && !isXML ) { part = part.toUpperCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part, isXML){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = isXML ? part : part.toUpperCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context, isXML){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { if ( !inplace ) result.push( elem ); } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ for ( var i = 0; curLoop[i] === false; i++ ){} return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); }, CHILD: function(match){ if ( match[1] == "nth" ) { var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 == i; }, eq: function(elem, i, match){ return match[3] - 0 == i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) return false; } if ( type == 'first') return true; node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) return false; } return true; case 'nth': var first = match[2], last = match[3]; if ( first == 1 && last == 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first == 0 ) { return diff == 0; } else { return ( diff % first == 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value != check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; try { Array.prototype.slice.call( document.documentElement.childNodes, 0 ); } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return 0; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } (function(){ var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = ""; var root = document.documentElement; root.insertBefore( form, root.firstChild ); if ( !!document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ var div = document.createElement("div"); div.appendChild( document.createComment("") ); if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } div.innerHTML = ""; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "

"; if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){ var div = document.createElement("div"); div.innerHTML = "
"; if ( div.getElementsByClassName("e").length === 0 ) return; div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) return; Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ){ elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ) { elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return a.compareDocumentPosition(b) & 16; } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; window.Sizzle = Sizzle; })(); Prototype._original_property = window.Sizzle; ;(function(engine) { var extendElements = Prototype.Selector.extendElements; function select(selector, scope) { return extendElements(engine(selector, scope || document)); } function match(element, selector) { return engine.matches(selector, [element]).length == 1; } Prototype.Selector.engine = engine; Prototype.Selector.select = select; Prototype.Selector.match = match; })(Sizzle); window.Sizzle = Prototype._original_property; delete Prototype._original_property; var Form = { reset: function(form) { form = $(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, accumulator, initial; if (options.hash) { initial = {}; accumulator = function(result, key, value) { if (key in result) { if (!Object.isArray(result[key])) result[key] = [result[key]]; result[key].push(value); } else result[key] = value; return result; }; } else { initial = ''; accumulator = function(result, key, value) { return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value); } } return elements.inject(initial, 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)))) { result = accumulator(result, key, value); } } return result; }); } }; Form.Methods = { serialize: function(form, options) { return Form.serializeElements(Form.getElements(form), options); }, getElements: function(form) { var elements = $(form).getElementsByTagName('*'), element, arr = [ ], serializers = Form.Element.Serializers; for (var i = 0; element = elements[i]; i++) { arr.push(element); } return arr.inject([], function(elements, child) { if (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)$/i.test(element.tagName); }); }, focusFirstElement: function(form) { form = $(form); var element = form.findFirstElement(); if (element) element.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)$/i.test(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 = (function() { function input(element, value) { switch (element.type.toLowerCase()) { case 'checkbox': case 'radio': return inputSelector(element, value); default: return valueSelector(element, value); } } function inputSelector(element, value) { if (Object.isUndefined(value)) return element.checked ? element.value : null; else element.checked = !!value; } function valueSelector(element, value) { if (Object.isUndefined(value)) return element.value; else element.value = value; } function select(element, value) { if (Object.isUndefined(value)) return (element.type === 'select-one' ? selectOne : selectMany)(element); 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); } } function selectOne(element) { var index = element.selectedIndex; return index >= 0 ? optionValue(element.options[index]) : null; } function selectMany(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(optionValue(opt)); } return values; } function optionValue(opt) { return Element.hasAttribute(opt, 'value') ? opt.value : opt.text; } return { input: input, inputSelector: inputSelector, textarea: valueSelector, select: select, selectOne: selectOne, selectMany: selectMany, optionValue: optionValue, button: valueSelector }; })(); /*--------------------------------------------------------------------------*/ 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); } }); (function() { var 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: {} }; var docEl = document.documentElement; var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl && 'onmouseleave' in docEl; var isIELegacyEvent = function(event) { return false; }; if (window.attachEvent) { if (window.addEventListener) { isIELegacyEvent = function(event) { return !(event instanceof window.Event); }; } else { isIELegacyEvent = function(event) { return true; }; } } var _isButton; function _isButtonForDOMEvents(event, code) { return event.which ? (event.which === code + 1) : (event.button === code); } var legacyButtonMap = { 0: 1, 1: 4, 2: 2 }; function _isButtonForLegacyEvents(event, code) { return event.button === legacyButtonMap[code]; } function _isButtonForWebKit(event, code) { switch (code) { case 0: return event.which == 1 && !event.metaKey; case 1: return event.which == 2 || (event.which == 1 && event.metaKey); case 2: return event.which == 3; default: return false; } } if (window.attachEvent) { if (!window.addEventListener) { _isButton = _isButtonForLegacyEvents; } else { _isButton = function(event, code) { return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) : _isButtonForDOMEvents(event, code); } } } else if (Prototype.Browser.WebKit) { _isButton = _isButtonForWebKit; } else { _isButton = _isButtonForDOMEvents; } function isLeftClick(event) { return _isButton(event, 0) } function isMiddleClick(event) { return _isButton(event, 1) } function isRightClick(event) { return _isButton(event, 2) } function element(event) { event = Event.extend(event); var node = event.target, type = event.type, currentTarget = event.currentTarget; if (currentTarget && currentTarget.tagName) { 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); } function findElement(event, expression) { var element = Event.element(event); if (!expression) return element; while (element) { if (Object.isElement(element) && Prototype.Selector.match(element, expression)) { return Element.extend(element); } element = element.parentNode; } } function pointer(event) { return { x: pointerX(event), y: pointerY(event) }; } function pointerX(event) { var docElement = document.documentElement, body = document.body || { scrollLeft: 0 }; return event.pageX || (event.clientX + (docElement.scrollLeft || body.scrollLeft) - (docElement.clientLeft || 0)); } function pointerY(event) { var docElement = document.documentElement, body = document.body || { scrollTop: 0 }; return event.pageY || (event.clientY + (docElement.scrollTop || body.scrollTop) - (docElement.clientTop || 0)); } function stop(event) { Event.extend(event); event.preventDefault(); event.stopPropagation(); event.stopped = true; } Event.Methods = { isLeftClick: isLeftClick, isMiddleClick: isMiddleClick, isRightClick: isRightClick, element: element, findElement: findElement, pointer: pointer, pointerX: pointerX, pointerY: pointerY, stop: stop }; var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { m[name] = Event.Methods[name].methodize(); return m; }); if (window.attachEvent) { function _relatedTarget(event) { var element; switch (event.type) { case 'mouseover': case 'mouseenter': element = event.fromElement; break; case 'mouseout': case 'mouseleave': element = event.toElement; break; default: return null; } return Element.extend(element); } var additionalMethods = { stopPropagation: function() { this.cancelBubble = true }, preventDefault: function() { this.returnValue = false }, inspect: function() { return '[object Event]' } }; Event.extend = function(event, element) { if (!event) return false; if (!isIELegacyEvent(event)) return event; if (event._extendedByPrototype) return event; event._extendedByPrototype = Prototype.emptyFunction; var pointer = Event.pointer(event); Object.extend(event, { target: event.srcElement || element, relatedTarget: _relatedTarget(event), pageX: pointer.x, pageY: pointer.y }); Object.extend(event, methods); Object.extend(event, additionalMethods); return event; }; } else { Event.extend = Prototype.K; } if (window.addEventListener) { Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; Object.extend(Event.prototype, methods); } function _createResponder(element, eventName, handler) { var registry = Element.retrieve(element, 'prototype_event_registry'); if (Object.isUndefined(registry)) { CACHE.push(element); registry = Element.retrieve(element, 'prototype_event_registry', $H()); } var respondersForEvent = registry.get(eventName); if (Object.isUndefined(respondersForEvent)) { respondersForEvent = []; registry.set(eventName, respondersForEvent); } if (respondersForEvent.pluck('handler').include(handler)) return false; var responder; if (eventName.include(":")) { responder = function(event) { if (Object.isUndefined(event.eventName)) return false; if (event.eventName !== eventName) return false; Event.extend(event, element); handler.call(element, event); }; } else { if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && (eventName === "mouseenter" || eventName === "mouseleave")) { if (eventName === "mouseenter" || eventName === "mouseleave") { responder = function(event) { Event.extend(event, element); var parent = event.relatedTarget; while (parent && parent !== element) { try { parent = parent.parentNode; } catch(e) { parent = element; } } if (parent === element) return; handler.call(element, event); }; } } else { responder = function(event) { Event.extend(event, element); handler.call(element, event); }; } } responder.handler = handler; respondersForEvent.push(responder); return responder; } function _destroyCache() { for (var i = 0, length = CACHE.length; i < length; i++) { Event.stopObserving(CACHE[i]); CACHE[i] = null; } } var CACHE = []; if (Prototype.Browser.IE) window.attachEvent('onunload', _destroyCache); if (Prototype.Browser.WebKit) window.addEventListener('unload', Prototype.emptyFunction, false); var _getDOMEventName = Prototype.K, translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) { _getDOMEventName = function(eventName) { return (translations[eventName] || eventName); }; } function observe(element, eventName, handler) { element = $(element); var responder = _createResponder(element, eventName, handler); if (!responder) return element; if (eventName.include(':')) { if (element.addEventListener) element.addEventListener("dataavailable", responder, false); else { element.attachEvent("ondataavailable", responder); element.attachEvent("onlosecapture", responder); } } else { var actualEventName = _getDOMEventName(eventName); if (element.addEventListener) element.addEventListener(actualEventName, responder, false); else element.attachEvent("on" + actualEventName, responder); } return element; } function stopObserving(element, eventName, handler) { element = $(element); var registry = Element.retrieve(element, 'prototype_event_registry'); if (!registry) return element; if (!eventName) { registry.each( function(pair) { var eventName = pair.key; stopObserving(element, eventName); }); return element; } var responders = registry.get(eventName); if (!responders) return element; if (!handler) { responders.each(function(r) { stopObserving(element, eventName, r.handler); }); return element; } var i = responders.length, responder; while (i--) { if (responders[i].handler === handler) { responder = responders[i]; break; } } if (!responder) return element; if (eventName.include(':')) { if (element.removeEventListener) element.removeEventListener("dataavailable", responder, false); else { element.detachEvent("ondataavailable", responder); element.detachEvent("onlosecapture", responder); } } else { var actualEventName = _getDOMEventName(eventName); if (element.removeEventListener) element.removeEventListener(actualEventName, responder, false); else element.detachEvent('on' + actualEventName, responder); } registry.set(eventName, responders.without(responder)); return element; } function fire(element, eventName, memo, bubble) { element = $(element); if (Object.isUndefined(bubble)) bubble = true; if (element == document && document.createEvent && !element.dispatchEvent) element = document.documentElement; var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent('dataavailable', bubble, true); } else { event = document.createEventObject(); event.eventType = bubble ? 'ondataavailable' : 'onlosecapture'; } event.eventName = eventName; event.memo = memo || { }; if (document.createEvent) element.dispatchEvent(event); else element.fireEvent(event.eventType, event); return Event.extend(event); } Event.Handler = Class.create({ initialize: function(element, eventName, selector, callback) { this.element = $(element); this.eventName = eventName; this.selector = selector; this.callback = callback; this.handler = this.handleEvent.bind(this); }, start: function() { Event.observe(this.element, this.eventName, this.handler); return this; }, stop: function() { Event.stopObserving(this.element, this.eventName, this.handler); return this; }, handleEvent: function(event) { var element = Event.findElement(event, this.selector); if (element) this.callback.call(this.element, event, element); } }); function on(element, eventName, selector, callback) { element = $(element); if (Object.isFunction(selector) && Object.isUndefined(callback)) { callback = selector, selector = null; } return new Event.Handler(element, eventName, selector, callback).start(); } Object.extend(Event, Event.Methods); Object.extend(Event, { fire: fire, observe: observe, stopObserving: stopObserving, on: on }); Element.addMethods({ fire: fire, observe: observe, stopObserving: stopObserving, on: on }); Object.extend(document, { fire: fire.methodize(), observe: observe.methodize(), stopObserving: stopObserving.methodize(), on: on.methodize(), loaded: false }); if (window.Event) Object.extend(window.Event, Event); else window.Event = Event; })(); (function() { /* Support for the DOMContentLoaded event is based on work by Dan Webb, Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ var timer; function fireContentLoadedEvent() { if (document.loaded) return; if (timer) window.clearTimeout(timer); document.loaded = true; document.fire('dom:loaded'); } function checkReadyState() { if (document.readyState === 'complete') { document.stopObserving('readystatechange', checkReadyState); fireContentLoadedEvent(); } } function pollDoScroll() { try { document.documentElement.doScroll('left'); } catch(e) { timer = pollDoScroll.defer(); return; } fireContentLoadedEvent(); } if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); } else { document.observe('readystatechange', checkReadyState); if (window == top) timer = pollDoScroll.defer(); } Event.observe(window, 'load', fireContentLoadedEvent); })(); Element.addMethods(); /*------------------------------- 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'); var Position = { includeScrollOffsets: false, prepare: function() { this.deltaX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0; this.deltaY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; }, 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); }, 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; }, 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); /*--------------------------------------------------------------------------*/ (function() { window.Selector = Class.create({ initialize: function(expression) { this.expression = expression.strip(); }, findElements: function(rootElement) { return Prototype.Selector.select(this.expression, rootElement); }, match: function(element) { return Prototype.Selector.match(element, this.expression); }, toString: function() { return this.expression; }, inspect: function() { return "#"; } }); Object.extend(Selector, { matchElements: function(elements, expression) { var match = Prototype.Selector.match, results = []; for (var i = 0, length = elements.length; i < length; i++) { var element = elements[i]; if (match(element, expression)) { results.push(Element.extend(element)); } } return results; }, findElement: function(elements, expression, index) { index = index || 0; var matchIndex = 0, element; for (var i = 0, length = elements.length; i < length; i++) { element = elements[i]; if (Prototype.Selector.match(element, expression) && index === matchIndex++) { return Element.extend(element); } } }, findChildElements: function(element, expressions) { var selector = expressions.toArray().join(', '); return Prototype.Selector.select(selector, element || document); } }); })(); fookebox-0.6.1/fookebox/public/js/scriptaculous/0000755000175000017500000000000011743153607022531 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/public/js/scriptaculous/effects.js0000644000175000017500000011310711525403230024475 0ustar stefanstefan00000000000000// script.aculo.us effects.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // Contributors: // Justin Palmer (http://encytemedia.com/) // Mark Pilgrim (http://diveintomark.org/) // Martin Bialasinki // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ // converts rgb() and #xxx to #xxxxxx format, // returns self (or first argument) if not convertable String.prototype.parseColor = function() { var color = '#'; if (this.slice(0,4) == 'rgb(') { var cols = this.slice(4,this.length-1).split(','); var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); } else { if (this.slice(0,1) == '#') { if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); if (this.length==7) color = this.toLowerCase(); } } return (color.length==7 ? color : (arguments[0] || this)); }; /*--------------------------------------------------------------------------*/ Element.collectTextNodes = function(element) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); }).flatten().join(''); }; Element.collectTextNodesIgnoreClass = function(element, className) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? Element.collectTextNodesIgnoreClass(node, className) : '')); }).flatten().join(''); }; Element.setContentZoom = function(element, percent) { element = $(element); element.setStyle({fontSize: (percent/100) + 'em'}); if (Prototype.Browser.WebKit) window.scrollBy(0,0); return element; }; Element.getInlineOpacity = function(element){ return $(element).style.opacity || ''; }; Element.forceRerendering = function(element) { try { element = $(element); var n = document.createTextNode(' '); element.appendChild(n); element.removeChild(n); } catch(e) { } }; /*--------------------------------------------------------------------------*/ var Effect = { _elementDoesNotExistError: { name: 'ElementDoesNotExistError', message: 'The specified DOM element does not exist, but is required for this effect to operate' }, Transitions: { linear: Prototype.K, sinoidal: function(pos) { return (-Math.cos(pos*Math.PI)/2) + .5; }, reverse: function(pos) { return 1-pos; }, flicker: function(pos) { var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4; return pos > 1 ? 1 : pos; }, wobble: function(pos) { return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5; }, pulse: function(pos, pulses) { return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5; }, spring: function(pos) { return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); }, none: function(pos) { return 0; }, full: function(pos) { return 1; } }, DefaultOptions: { duration: 1.0, // seconds fps: 100, // 100= assume 66fps max. sync: false, // true for combining from: 0.0, to: 1.0, delay: 0.0, queue: 'parallel' }, tagifyText: function(element) { var tagifyStyle = 'position:relative'; if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; element = $(element); $A(element.childNodes).each( function(child) { if (child.nodeType==3) { child.nodeValue.toArray().each( function(character) { element.insertBefore( new Element('span', {style: tagifyStyle}).update( character == ' ' ? String.fromCharCode(160) : character), child); }); Element.remove(child); } }); }, multiple: function(element, effect) { var elements; if (((typeof element == 'object') || Object.isFunction(element)) && (element.length)) elements = element; else elements = $(element).childNodes; var options = Object.extend({ speed: 0.1, delay: 0.0 }, arguments[2] || { }); var masterDelay = options.delay; $A(elements).each( function(element, index) { new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); }); }, PAIRS: { 'slide': ['SlideDown','SlideUp'], 'blind': ['BlindDown','BlindUp'], 'appear': ['Appear','Fade'] }, toggle: function(element, effect, options) { element = $(element); effect = (effect || 'appear').toLowerCase(); return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } }, options || {})); } }; Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; /* ------------- core effects ------------- */ Effect.ScopedQueue = Class.create(Enumerable, { initialize: function() { this.effects = []; this.interval = null; }, _each: function(iterator) { this.effects._each(iterator); }, add: function(effect) { var timestamp = new Date().getTime(); var position = Object.isString(effect.options.queue) ? effect.options.queue : effect.options.queue.position; switch(position) { case 'front': // move unstarted effects after this effect this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { e.startOn += effect.finishOn; e.finishOn += effect.finishOn; }); break; case 'with-last': timestamp = this.effects.pluck('startOn').max() || timestamp; break; case 'end': // start effect after last queued effect has finished timestamp = this.effects.pluck('finishOn').max() || timestamp; break; } effect.startOn += timestamp; effect.finishOn += timestamp; if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) this.effects.push(effect); if (!this.interval) this.interval = setInterval(this.loop.bind(this), 15); }, remove: function(effect) { this.effects = this.effects.reject(function(e) { return e==effect }); if (this.effects.length == 0) { clearInterval(this.interval); this.interval = null; } }, loop: function() { var timePos = new Date().getTime(); for(var i=0, len=this.effects.length;i= this.startOn) { if (timePos >= this.finishOn) { this.render(1.0); this.cancel(); this.event('beforeFinish'); if (this.finish) this.finish(); this.event('afterFinish'); return; } var pos = (timePos - this.startOn) / this.totalTime, frame = (pos * this.totalFrames).round(); if (frame > this.currentFrame) { this.render(pos); this.currentFrame = frame; } } }, cancel: function() { if (!this.options.sync) Effect.Queues.get(Object.isString(this.options.queue) ? 'global' : this.options.queue.scope).remove(this); this.state = 'finished'; }, event: function(eventName) { if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); if (this.options[eventName]) this.options[eventName](this); }, inspect: function() { var data = $H(); for(property in this) if (!Object.isFunction(this[property])) data.set(property, this[property]); return '#'; } }); Effect.Parallel = Class.create(Effect.Base, { initialize: function(effects) { this.effects = effects || []; this.start(arguments[1]); }, update: function(position) { this.effects.invoke('render', position); }, finish: function(position) { this.effects.each( function(effect) { effect.render(1.0); effect.cancel(); effect.event('beforeFinish'); if (effect.finish) effect.finish(position); effect.event('afterFinish'); }); } }); Effect.Tween = Class.create(Effect.Base, { initialize: function(object, from, to) { object = Object.isString(object) ? $(object) : object; var args = $A(arguments), method = args.last(), options = args.length == 5 ? args[3] : null; this.method = Object.isFunction(method) ? method.bind(object) : Object.isFunction(object[method]) ? object[method].bind(object) : function(value) { object[method] = value }; this.start(Object.extend({ from: from, to: to }, options || { })); }, update: function(position) { this.method(position); } }); Effect.Event = Class.create(Effect.Base, { initialize: function() { this.start(Object.extend({ duration: 0 }, arguments[0] || { })); }, update: Prototype.emptyFunction }); Effect.Opacity = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); // make this work on IE on elements without 'layout' if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) this.element.setStyle({zoom: 1}); var options = Object.extend({ from: this.element.getOpacity() || 0.0, to: 1.0 }, arguments[1] || { }); this.start(options); }, update: function(position) { this.element.setOpacity(position); } }); Effect.Move = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ x: 0, y: 0, mode: 'relative' }, arguments[1] || { }); this.start(options); }, setup: function() { this.element.makePositioned(); this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); this.originalTop = parseFloat(this.element.getStyle('top') || '0'); if (this.options.mode == 'absolute') { this.options.x = this.options.x - this.originalLeft; this.options.y = this.options.y - this.originalTop; } }, update: function(position) { this.element.setStyle({ left: (this.options.x * position + this.originalLeft).round() + 'px', top: (this.options.y * position + this.originalTop).round() + 'px' }); } }); // for backwards compatibility Effect.MoveBy = function(element, toTop, toLeft) { return new Effect.Move(element, Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); }; Effect.Scale = Class.create(Effect.Base, { initialize: function(element, percent) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ scaleX: true, scaleY: true, scaleContent: true, scaleFromCenter: false, scaleMode: 'box', // 'box' or 'contents' or { } with provided values scaleFrom: 100.0, scaleTo: percent }, arguments[2] || { }); this.start(options); }, setup: function() { this.restoreAfterFinish = this.options.restoreAfterFinish || false; this.elementPositioning = this.element.getStyle('position'); this.originalStyle = { }; ['top','left','width','height','fontSize'].each( function(k) { this.originalStyle[k] = this.element.style[k]; }.bind(this)); this.originalTop = this.element.offsetTop; this.originalLeft = this.element.offsetLeft; var fontSize = this.element.getStyle('font-size') || '100%'; ['em','px','%','pt'].each( function(fontSizeType) { if (fontSize.indexOf(fontSizeType)>0) { this.fontSize = parseFloat(fontSize); this.fontSizeType = fontSizeType; } }.bind(this)); this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; this.dims = null; if (this.options.scaleMode=='box') this.dims = [this.element.offsetHeight, this.element.offsetWidth]; if (/^content/.test(this.options.scaleMode)) this.dims = [this.element.scrollHeight, this.element.scrollWidth]; if (!this.dims) this.dims = [this.options.scaleMode.originalHeight, this.options.scaleMode.originalWidth]; }, update: function(position) { var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); if (this.options.scaleContent && this.fontSize) this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); }, finish: function(position) { if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); }, setDimensions: function(height, width) { var d = { }; if (this.options.scaleX) d.width = width.round() + 'px'; if (this.options.scaleY) d.height = height.round() + 'px'; if (this.options.scaleFromCenter) { var topd = (height - this.dims[0])/2; var leftd = (width - this.dims[1])/2; if (this.elementPositioning == 'absolute') { if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; } else { if (this.options.scaleY) d.top = -topd + 'px'; if (this.options.scaleX) d.left = -leftd + 'px'; } } this.element.setStyle(d); } }); Effect.Highlight = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); this.start(options); }, setup: function() { // Prevent executing on elements not in the layout flow if (this.element.getStyle('display')=='none') { this.cancel(); return; } // Disable background image during the effect this.oldStyle = { }; if (!this.options.keepBackgroundImage) { this.oldStyle.backgroundImage = this.element.getStyle('background-image'); this.element.setStyle({backgroundImage: 'none'}); } if (!this.options.endcolor) this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); if (!this.options.restorecolor) this.options.restorecolor = this.element.getStyle('background-color'); // init color calculations this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); }, update: function(position) { this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); }, finish: function() { this.element.setStyle(Object.extend(this.oldStyle, { backgroundColor: this.options.restorecolor })); } }); Effect.ScrollTo = function(element) { var options = arguments[1] || { }, scrollOffsets = document.viewport.getScrollOffsets(), elementOffsets = $(element).cumulativeOffset(); if (options.offset) elementOffsets[1] += options.offset; return new Effect.Tween(null, scrollOffsets.top, elementOffsets[1], options, function(p){ scrollTo(scrollOffsets.left, p.round()); } ); }; /* ------------- combination effects ------------- */ Effect.Fade = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); var options = Object.extend({ from: element.getOpacity() || 1.0, to: 0.0, afterFinishInternal: function(effect) { if (effect.options.to!=0) return; effect.element.hide().setStyle({opacity: oldOpacity}); } }, arguments[1] || { }); return new Effect.Opacity(element,options); }; Effect.Appear = function(element) { element = $(element); var options = Object.extend({ from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), to: 1.0, // force Safari to render floated elements properly afterFinishInternal: function(effect) { effect.element.forceRerendering(); }, beforeSetup: function(effect) { effect.element.setOpacity(effect.options.from).show(); }}, arguments[1] || { }); return new Effect.Opacity(element,options); }; Effect.Puff = function(element) { element = $(element); var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position'), top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; return new Effect.Parallel( [ new Effect.Scale(element, 200, { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], Object.extend({ duration: 1.0, beforeSetupInternal: function(effect) { Position.absolutize(effect.effects[0].element); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().setStyle(oldStyle); } }, arguments[1] || { }) ); }; Effect.BlindUp = function(element) { element = $(element); element.makeClipping(); return new Effect.Scale(element, 0, Object.extend({ scaleContent: false, scaleX: false, restoreAfterFinish: true, afterFinishInternal: function(effect) { effect.element.hide().undoClipping(); } }, arguments[1] || { }) ); }; Effect.BlindDown = function(element) { element = $(element); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({ scaleContent: false, scaleX: false, scaleFrom: 0, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makeClipping().setStyle({height: '0px'}).show(); }, afterFinishInternal: function(effect) { effect.element.undoClipping(); } }, arguments[1] || { })); }; Effect.SwitchOff = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); return new Effect.Appear(element, Object.extend({ duration: 0.4, from: 0, transition: Effect.Transitions.flicker, afterFinishInternal: function(effect) { new Effect.Scale(effect.element, 1, { duration: 0.3, scaleFromCenter: true, scaleX: false, scaleContent: false, restoreAfterFinish: true, beforeSetup: function(effect) { effect.element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); } }); } }, arguments[1] || { })); }; Effect.DropOut = function(element) { element = $(element); var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left'), opacity: element.getInlineOpacity() }; return new Effect.Parallel( [ new Effect.Move(element, {x: 0, y: 100, sync: true }), new Effect.Opacity(element, { sync: true, to: 0.0 }) ], Object.extend( { duration: 0.5, beforeSetup: function(effect) { effect.effects[0].element.makePositioned(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); } }, arguments[1] || { })); }; Effect.Shake = function(element) { element = $(element); var options = Object.extend({ distance: 20, duration: 0.5 }, arguments[1] || {}); var distance = parseFloat(options.distance); var split = parseFloat(options.duration) / 10.0; var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left') }; return new Effect.Move(element, { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { effect.element.undoPositioned().setStyle(oldStyle); }}); }}); }}); }}); }}); }}); }; Effect.SlideDown = function(element) { element = $(element).cleanWhitespace(); // SlideDown need to have the content of the element wrapped in a container element with fixed height! var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({ scaleContent: false, scaleX: false, scaleFrom: window.opera ? 0 : 1, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makePositioned(); effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping().setStyle({height: '0px'}).show(); }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.undoClipping().undoPositioned(); effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } }, arguments[1] || { }) ); }; Effect.SlideUp = function(element) { element = $(element).cleanWhitespace(); var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, window.opera ? 0 : 1, Object.extend({ scaleContent: false, scaleX: false, scaleMode: 'box', scaleFrom: 100, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makePositioned(); effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping().show(); }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().undoPositioned(); effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } }, arguments[1] || { }) ); }; // Bug in opera makes the TD containing this element expand for a instance after finish Effect.Squish = function(element) { return new Effect.Scale(element, window.opera ? 1 : 0, { restoreAfterFinish: true, beforeSetup: function(effect) { effect.element.makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping(); } }); }; Effect.Grow = function(element) { element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.full }, arguments[1] || { }); var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() }; var dims = element.getDimensions(); var initialMoveX, initialMoveY; var moveX, moveY; switch (options.direction) { case 'top-left': initialMoveX = initialMoveY = moveX = moveY = 0; break; case 'top-right': initialMoveX = dims.width; initialMoveY = moveY = 0; moveX = -dims.width; break; case 'bottom-left': initialMoveX = moveX = 0; initialMoveY = dims.height; moveY = -dims.height; break; case 'bottom-right': initialMoveX = dims.width; initialMoveY = dims.height; moveX = -dims.width; moveY = -dims.height; break; case 'center': initialMoveX = dims.width / 2; initialMoveY = dims.height / 2; moveX = -dims.width / 2; moveY = -dims.height / 2; break; } return new Effect.Move(element, { x: initialMoveX, y: initialMoveY, duration: 0.01, beforeSetup: function(effect) { effect.element.hide().makeClipping().makePositioned(); }, afterFinishInternal: function(effect) { new Effect.Parallel( [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), new Effect.Scale(effect.element, 100, { scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) ], Object.extend({ beforeSetup: function(effect) { effect.effects[0].element.setStyle({height: '0px'}).show(); }, afterFinishInternal: function(effect) { effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); } }, options) ); } }); }; Effect.Shrink = function(element) { element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.none }, arguments[1] || { }); var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() }; var dims = element.getDimensions(); var moveX, moveY; switch (options.direction) { case 'top-left': moveX = moveY = 0; break; case 'top-right': moveX = dims.width; moveY = 0; break; case 'bottom-left': moveX = 0; moveY = dims.height; break; case 'bottom-right': moveX = dims.width; moveY = dims.height; break; case 'center': moveX = dims.width / 2; moveY = dims.height / 2; break; } return new Effect.Parallel( [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) ], Object.extend({ beforeStartInternal: function(effect) { effect.effects[0].element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } }, options) ); }; Effect.Pulsate = function(element) { element = $(element); var options = arguments[1] || { }, oldOpacity = element.getInlineOpacity(), transition = options.transition || Effect.Transitions.linear, reverser = function(pos){ return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5); }; return new Effect.Opacity(element, Object.extend(Object.extend({ duration: 2.0, from: 0, afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } }, options), {transition: reverser})); }; Effect.Fold = function(element) { element = $(element); var oldStyle = { top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; element.makeClipping(); return new Effect.Scale(element, 5, Object.extend({ scaleContent: false, scaleX: false, afterFinishInternal: function(effect) { new Effect.Scale(element, 1, { scaleContent: false, scaleY: false, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().setStyle(oldStyle); } }); }}, arguments[1] || { })); }; Effect.Morph = Class.create(Effect.Base, { initialize: function(element) { this.element = $(element); if (!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ style: { } }, arguments[1] || { }); if (!Object.isString(options.style)) this.style = $H(options.style); else { if (options.style.include(':')) this.style = options.style.parseStyle(); else { this.element.addClassName(options.style); this.style = $H(this.element.getStyles()); this.element.removeClassName(options.style); var css = this.element.getStyles(); this.style = this.style.reject(function(style) { return style.value == css[style.key]; }); options.afterFinishInternal = function(effect) { effect.element.addClassName(effect.options.style); effect.transforms.each(function(transform) { effect.element.style[transform.style] = ''; }); }; } } this.start(options); }, setup: function(){ function parseColor(color){ if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; color = color.parseColor(); return $R(0,2).map(function(i){ return parseInt( color.slice(i*2+1,i*2+3), 16 ); }); } this.transforms = this.style.map(function(pair){ var property = pair[0], value = pair[1], unit = null; if (value.parseColor('#zzzzzz') != '#zzzzzz') { value = value.parseColor(); unit = 'color'; } else if (property == 'opacity') { value = parseFloat(value); if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) this.element.setStyle({zoom: 1}); } else if (Element.CSS_LENGTH.test(value)) { var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); value = parseFloat(components[1]); unit = (components.length == 3) ? components[2] : null; } var originalValue = this.element.getStyle(property); return { style: property.camelize(), originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), targetValue: unit=='color' ? parseColor(value) : value, unit: unit }; }.bind(this)).reject(function(transform){ return ( (transform.originalValue == transform.targetValue) || ( transform.unit != 'color' && (isNaN(transform.originalValue) || isNaN(transform.targetValue)) ) ); }); }, update: function(position) { var style = { }, transform, i = this.transforms.length; while(i--) style[(transform = this.transforms[i]).style] = transform.unit=='color' ? '#'+ (Math.round(transform.originalValue[0]+ (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + (Math.round(transform.originalValue[1]+ (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + (Math.round(transform.originalValue[2]+ (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : (transform.originalValue + (transform.targetValue - transform.originalValue) * position).toFixed(3) + (transform.unit === null ? '' : transform.unit); this.element.setStyle(style, true); } }); Effect.Transform = Class.create({ initialize: function(tracks){ this.tracks = []; this.options = arguments[1] || { }; this.addTracks(tracks); }, addTracks: function(tracks){ tracks.each(function(track){ track = $H(track); var data = track.values().first(); this.tracks.push($H({ ids: track.keys().first(), effect: Effect.Morph, options: { style: data } })); }.bind(this)); return this; }, play: function(){ return new Effect.Parallel( this.tracks.map(function(track){ var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); var elements = [$(ids) || $$(ids)].flatten(); return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) }); }).flatten(), this.options ); } }); Element.CSS_PROPERTIES = $w( 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + 'fontSize fontWeight height left letterSpacing lineHeight ' + 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + 'right textIndent top width wordSpacing zIndex'); Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; String.__parseStyleElement = document.createElement('div'); String.prototype.parseStyle = function(){ var style, styleRules = $H(); if (Prototype.Browser.WebKit) style = new Element('div',{style:this}).style; else { String.__parseStyleElement.innerHTML = '
'; style = String.__parseStyleElement.childNodes[0].style; } Element.CSS_PROPERTIES.each(function(property){ if (style[property]) styleRules.set(property, style[property]); }); if (Prototype.Browser.IE && this.include('opacity')) styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); return styleRules; }; if (document.defaultView && document.defaultView.getComputedStyle) { Element.getStyles = function(element) { var css = document.defaultView.getComputedStyle($(element), null); return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { styles[property] = css[property]; return styles; }); }; } else { Element.getStyles = function(element) { element = $(element); var css = element.currentStyle, styles; styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) { results[property] = css[property]; return results; }); if (!styles.opacity) styles.opacity = element.getOpacity(); return styles; }; } Effect.Methods = { morph: function(element, style) { element = $(element); new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); return element; }, visualEffect: function(element, effect, options) { element = $(element); var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); new Effect[klass](element, options); return element; }, highlight: function(element, options) { element = $(element); new Effect.Highlight(element, options); return element; } }; $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ 'pulsate shake puff squish switchOff dropOut').each( function(effect) { Effect.Methods[effect] = function(element, options){ element = $(element); Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); return element; }; } ); $w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( function(f) { Effect.Methods[f] = Element[f]; } ); Element.addMethods(Effect.Methods);fookebox-0.6.1/fookebox/public/js/scriptaculous/scriptaculous.js0000644000175000017500000000556311525403230025764 0ustar stefanstefan00000000000000// script.aculo.us scriptaculous.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // 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. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.9.0', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write(' % if config.get('lang'): % endif ${self.headers()} ${next.body()} fookebox-0.6.1/fookebox/templates/browse-menu.tpl0000644000175000017500000000402411525403233022710 0ustar stefanstefan00000000000000
% for char in range(ord('A'), ord('Z') + 1): <% key = chr(char) %> ${key} % endfor
    <% prev = '' char = '' %> % for artist in artists: % if len(artist.name) > 0: <% char = artist.name[0].upper() %> % endif % if prev != char:
  • ${artist.name} % else:
  • % if len(artist.name) > 0: ${artist.name} % else: ${_('(none)')} % endif % endif
  • % if len(artist.name) > 0: <% prev = char %> % endif % endfor
% if config.get('show_search_tab'): % endif
fookebox-0.6.1/fookebox/templates/client.tpl0000644000175000017500000000224611743150170021730 0ustar stefanstefan00000000000000<%inherit file="base.tpl"/> <%def name="headers()">

${config.get('site_name')}

% if not config.get('hide_credits'):
fookebox ${config.get('version')}
© 2007-2012 Stefan Ott
% endif <%include file="browse-menu.tpl"/>
<%include file="status.tpl"/>
fookebox-0.6.1/fookebox/templates/disabled.tpl0000644000175000017500000000043611525403237022223 0ustar stefanstefan00000000000000<%inherit file="base.tpl"/> <%def name="headers()">
${config.get('site_name')}
${_('enjoy our live artist')}
fookebox-0.6.1/fookebox/templates/error.tpl0000644000175000017500000000055411743150166021610 0ustar stefanstefan00000000000000<%inherit file="base.tpl"/>

${config.get('site_name')}

fookebox ${config.get('version')}
© 2007-2012 Stefan Ott
${_('Error')}: ${ error }
fookebox-0.6.1/fookebox/templates/playing.tpl0000644000175000017500000000226111525403235022113 0ustar stefanstefan00000000000000

${_('Now playing')}

  1. /
  2. % if config.get('enable_controls'):
  3. back pause play next volume down volume up rebuild database
  4. % endif
fookebox-0.6.1/fookebox/templates/playlist.tpl0000644000175000017500000000026111525403056022310 0ustar stefanstefan00000000000000

${_('Queue')}

    % for i in range(0, int(config.get('max_queue_length'))):
  1.  
  2. % endfor
fookebox-0.6.1/fookebox/templates/program-edit-events.tpl0000644000175000017500000000355511525403244024353 0ustar stefanstefan00000000000000% for event in events: % if edit == event.id:
: % else: ${event.time.strftime('%H:%M')} % endif % if edit == event.id: % else: ${event.name} % endif % if edit == event.id: % else: ${h.event_type_name(event.type)} % endif % if edit == event.id:
% else: edit % if event != current: % if event != events[len(events) - 1]: down % endif % if event != events[0]: up % endif set current delete % endif % endif % endfor fookebox-0.6.1/fookebox/templates/program-edit.tpl0000644000175000017500000000304711743150167023052 0ustar stefanstefan00000000000000<%inherit file="base.tpl"/> <%def name="headers()">

${config.get('site_name')}

fookebox ${config.get('version')}
© 2007-2012 Stefan Ott
<%include file="program-edit-events.tpl"/>
time event name event type
» Add an event
fookebox-0.6.1/fookebox/templates/program.tpl0000644000175000017500000000114711525403241022116 0ustar stefanstefan00000000000000<%inherit file="base.tpl"/> <%def name="headers()">
${_('now playing')}
fookebox-0.6.1/fookebox/templates/status.tpl0000644000175000017500000000007711525403234021775 0ustar stefanstefan00000000000000<%include file="playing.tpl"/> <%include file="playlist.tpl"/> fookebox-0.6.1/fookebox/tests/0000755000175000017500000000000011743153607017101 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/tests/functional/0000755000175000017500000000000011743153607021243 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/tests/functional/__init__.py0000644000175000017500000000000011525403055023333 0ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/tests/functional/test_jukebox.py0000644000175000017500000000030311525403055024310 0ustar stefanstefan00000000000000from fookebox.tests import * class TestJukeboxController(TestController): def test_status(self): response = self.app.get( url(controller='jukebox', action='status')) # Test response... fookebox-0.6.1/fookebox/tests/__init__.py0000644000175000017500000000177211525403055021212 0ustar stefanstefan00000000000000"""Pylons application test package This package assumes the Pylons environment is already loaded, such as when this script is imported from the `nosetests --with-pylons=test.ini` command. This module initializes the application via ``websetup`` (`paster setup-app`) and provides the base testing objects. """ from unittest import TestCase from paste.deploy import loadapp from paste.script.appinstall import SetupCommand from pylons import url from routes.util import URLGenerator from webtest import TestApp import pylons.test __all__ = ['environ', 'url', 'TestController'] # Invoke websetup with the current config file SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']]) environ = {} class TestController(TestCase): def __init__(self, *args, **kwargs): wsgiapp = pylons.test.pylonsapp config = wsgiapp.config self.app = TestApp(wsgiapp) url._push_object(URLGenerator(config['routes.map'], environ)) TestCase.__init__(self, *args, **kwargs) fookebox-0.6.1/fookebox/tests/test_models.py0000644000175000017500000001011211525403055021761 0ustar stefanstefan00000000000000import unittest from fookebox.model.jukebox import * class FakeMPD(object): def __init__(self): self.db = [] self.fillDB() self.stop() self.queue = [] self._pos = 0 def fillDB(self): self.db.append({ 'file': '/tmp/dummy1.mp3', 'time': '120', 'album': 'Fake Album 1', 'title': 'Fake Title 1', 'track': '1', 'genre': 'Fake Genre 1', 'artist': 'Fake Artist 1', 'date': '2005', }) self.db.append({ 'file': '/tmp/dummy2.sid', 'artist': 'Fake Artist 2', 'title': 'Fake Title 2', }) self.db.append({ 'file': '/tmp/dummy3.mp3', 'time': '144', 'album': 'Fake Album 1', 'title': 'Fake Title 2', 'track': '2/4', 'genre': 'Fake Genre 1', 'artist': 'Fake Artist 1', 'date': '2005', }) self.db.append({ 'file': '/tmp/dummy4.ogg', 'time': '123', 'album': 'Fake Album 2', 'title': 'Fake Title 3', 'track': ['11', '12'], 'genre': 'Fake Genre 1', 'artist': 'Fake Artist 1', 'date': '2005', }) def stop(self): #self._song = None self._status = { 'playlistlength': '0', 'playlist': '5', 'state': 'stop', 'volume': '100', } def play(self): if not self.queue[0] == None: self._status = { 'playlistlength': '1', 'playlist': '5', 'state': 'play', 'volume': '100', } song = self.queue[self._pos] if 'time' in song: self._status['time'] = '0:%s' % song['time'] else: self._status['time'] = '0:0' def status(self): return self._status def playDummy(self, index): self.queue = [self.db[index]] self._pos = 0 self.play() def close(self): pass def disconnect(self): pass def skipTime(self, interval): (time, total) = self._status['time'].split(':') time = int(time) time = min(time + interval, int(total)) self._status['time'] = "%s:%s" % (time, total) def add(self, file): for song in self.db: if song['file'] == file: self.queue.append(song) def delete(self, index): self.queue.remove(self.queue[index]) if self._pos > index: self._pos -= 1 if len(self.queue) < 1: self.stop() def playlistinfo(self): return self.queue def currentsong(self): song = self.queue[self._pos] if song != None: song['pos'] = self._pos return song def next(self): self._pos += 1 def search(self, field, value): result = [] for song in self.db: if field in song and song[field] == value: result.append(song) return result class TestJukebox(unittest.TestCase): def setUp(self): self.mpd = FakeMPD() self.jukebox = Jukebox(self.mpd) def test_timeLeft(self): assert self.jukebox.timeLeft() == 0 self.mpd.playDummy(0) self.mpd.skipTime(30) assert self.jukebox.timeLeft() == 90 self.mpd.playDummy(1) assert self.jukebox.timeLeft() == 0 self.mpd.skipTime(30) assert self.jukebox.timeLeft() == 0 def test_queue(self): assert self.jukebox.isPlaying() == False self.jukebox.queue(self.mpd.db[0]['file']) assert len(self.jukebox.getPlaylist()) == 1 assert self.jukebox.isPlaying() == True self.jukebox.queue(self.mpd.db[1]['file']) assert len(self.jukebox.getPlaylist()) == 2 assert self.jukebox.isPlaying() == True def test_cleanQueue(self): self.jukebox.queue(self.mpd.db[0]['file']) self.jukebox.queue(self.mpd.db[1]['file']) assert self.jukebox.getCurrentSong()['title'] == 'Fake Title 1' self.jukebox.next() assert self.jukebox.getCurrentSong()['title'] == 'Fake Title 2' assert len(self.jukebox.getPlaylist()) == 2 self.jukebox.cleanQueue() assert self.jukebox.getCurrentSong()['title'] == 'Fake Title 2' assert len(self.jukebox.getPlaylist()) == 1 def test_searchArtist(self): albums = self.jukebox.search('artist', 'Fake Artist 1') assert len(albums) == 2 assert len(albums['Fake Album 1'].tracks) == 2 assert len(albums['Fake Album 2'].tracks) == 1 class TestTrack(unittest.TestCase): def setUp(self): self.mpd = FakeMPD() def test_trackNum(self): track = Track() track.load(self.mpd.db[0]) assert track.track == 1 track = Track() track.load(self.mpd.db[2]) assert track.track == 2 track = Track() track.load(self.mpd.db[3]) assert track.track == 11 fookebox-0.6.1/fookebox/__init__.py0000644000175000017500000000000011525403056020030 0ustar stefanstefan00000000000000fookebox-0.6.1/fookebox/websetup.py0000644000175000017500000000104211525403056020136 0ustar stefanstefan00000000000000"""Setup the fookebox application""" import logging import pylons.test from fookebox.config.environment import load_environment log = logging.getLogger(__name__) def setup_app(command, conf, vars): """Place any commands to setup fookebox here""" # Don't reload the app if it was loaded under the testing environment if not pylons.test.pylonsapp: load_environment(conf.global_conf, conf.local_conf) from fookebox.model import meta log.info("Creating tables") meta.metadata.create_all(bind=meta.engine) log.info("Successfully setup") fookebox-0.6.1/fookebox.egg-info/0000755000175000017500000000000011743153607017431 5ustar stefanstefan00000000000000fookebox-0.6.1/fookebox.egg-info/PKG-INFO0000644000175000017500000000173611743153607020535 0ustar stefanstefan00000000000000Metadata-Version: 1.1 Name: fookebox Version: 0.6.1 Summary: A jukebox-style web-frontend to mpd Home-page: http://fookebox.googlecode.com/ Author: Stefan Ott Author-email: stefan@ott.net License: GPLv3 Description: fookebox is a jukebox-style web-frontend to mpd. It can be used as a keyboard-less jukebox, as a powerful mpd control frontend or as anything in between. Keywords: mpd jukebox web music party Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Framework :: Pylons Classifier: Intended Audience :: End Users/Desktop Classifier: License :: DFSG approved Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Natural Language :: German Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Multimedia Classifier: Topic :: Multimedia :: Sound/Audio fookebox-0.6.1/fookebox.egg-info/SOURCES.txt0000644000175000017500000000602711743153607021322 0ustar stefanstefan00000000000000COPYING CREDITS.txt MANIFEST.in README.txt ez_setup.py setup.cfg setup.py docs/changes.txt docs/config.txt docs/i18n.txt docs/examples/apache/apache-fcgi.conf docs/examples/apache/apache-wsgi.conf docs/examples/apache/fookebox.fcgi docs/examples/apache/fookebox.wsgi fookebox/__init__.py fookebox/websetup.py fookebox.egg-info/PKG-INFO fookebox.egg-info/SOURCES.txt fookebox.egg-info/dependency_links.txt fookebox.egg-info/entry_points.txt fookebox.egg-info/not-zip-safe fookebox.egg-info/paster_plugins.txt fookebox.egg-info/requires.txt fookebox.egg-info/top_level.txt fookebox/config/__init__.py fookebox/config/deployment.ini_tmpl fookebox/config/environment.py fookebox/config/middleware.py fookebox/config/routing.py fookebox/controllers/__init__.py fookebox/controllers/error.py fookebox/controllers/jukebox.py fookebox/controllers/program.py fookebox/i18n/fookebox.pot fookebox/i18n/de/LC_MESSAGES/fookebox.mo fookebox/i18n/de/LC_MESSAGES/fookebox.po fookebox/lib/__init__.py fookebox/lib/app_globals.py fookebox/lib/base.py fookebox/lib/helpers.py fookebox/lib/util.py fookebox/model/__init__.py fookebox/model/albumart.py fookebox/model/jukebox.py fookebox/model/meta.py fookebox/model/mpdconn.py fookebox/model/schedule.py fookebox/public/favicon.ico fookebox/public/css/style-mobile.css fookebox/public/css/style.css fookebox/public/img/arrow_down.png fookebox/public/img/arrow_up.png fookebox/public/img/artist.png fookebox/public/img/bg.png fookebox/public/img/control_next.png fookebox/public/img/control_pause.png fookebox/public/img/control_play.png fookebox/public/img/control_prev.png fookebox/public/img/control_rebuild.png fookebox/public/img/control_voldown.png fookebox/public/img/control_volup.png fookebox/public/img/delete.png fookebox/public/img/edit.png fookebox/public/img/li.png fookebox/public/img/msg-bl.png fookebox/public/img/msg-br.png fookebox/public/img/msg-tl.png fookebox/public/img/msg-tr.png fookebox/public/img/music.png fookebox/public/img/nocover.png fookebox/public/img/progress.gif fookebox/public/img/pylons-logo.gif fookebox/public/img/queue.png fookebox/public/img/setcurrentevent.png fookebox/public/img/sound.png fookebox/public/img/time.png fookebox/public/js/fookebox/client.js fookebox/public/js/fookebox/core.js fookebox/public/js/fookebox/disabled.js fookebox/public/js/fookebox/program.js fookebox/public/js/fookebox/schedule.js fookebox/public/js/fookebox/i18n/de.js fookebox/public/js/fookebox/i18n/i18n.js fookebox/public/js/prototype/prototype.js fookebox/public/js/scriptaculous/effects.js fookebox/public/js/scriptaculous/scriptaculous.js fookebox/templates/base.tpl fookebox/templates/browse-menu.tpl fookebox/templates/client.tpl fookebox/templates/disabled.tpl fookebox/templates/error.tpl fookebox/templates/playing.tpl fookebox/templates/playlist.tpl fookebox/templates/program-edit-events.tpl fookebox/templates/program-edit.tpl fookebox/templates/program.tpl fookebox/templates/status.tpl fookebox/tests/__init__.py fookebox/tests/test_models.py fookebox/tests/functional/__init__.py fookebox/tests/functional/test_jukebox.pyfookebox-0.6.1/fookebox.egg-info/dependency_links.txt0000644000175000017500000000000111743153607023477 0ustar stefanstefan00000000000000 fookebox-0.6.1/fookebox.egg-info/entry_points.txt0000644000175000017500000000017511743153607022732 0ustar stefanstefan00000000000000 [paste.app_factory] main = fookebox.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller fookebox-0.6.1/fookebox.egg-info/not-zip-safe0000644000175000017500000000000111525405100021641 0ustar stefanstefan00000000000000 fookebox-0.6.1/fookebox.egg-info/paster_plugins.txt0000644000175000017500000000002311743153607023224 0ustar stefanstefan00000000000000PasteScript Pylons fookebox-0.6.1/fookebox.egg-info/requires.txt0000644000175000017500000000002711743153607022030 0ustar stefanstefan00000000000000Pylons>=0.10 python-mpdfookebox-0.6.1/fookebox.egg-info/top_level.txt0000644000175000017500000000001111743153607022153 0ustar stefanstefan00000000000000fookebox fookebox-0.6.1/COPYING0000644000175000017500000010451311525403056015154 0ustar stefanstefan00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . fookebox-0.6.1/CREDITS.txt0000644000175000017500000000020011525403056015743 0ustar stefanstefan00000000000000fookebox written by Stefan Ott Icons by Mark James (taken from the "Silk" icon set, http://www.famfamfam.com/lab/icons/silk/) fookebox-0.6.1/MANIFEST.in0000644000175000017500000000031411525403056015651 0ustar stefanstefan00000000000000include fookebox/config/deployment.ini_tmpl include docs/config.txt include docs/changes.txt exclude docs/index.txt recursive-include fookebox/public * recursive-include fookebox/templates * exclude *ini fookebox-0.6.1/README.txt0000644000175000017500000000047311525403056015617 0ustar stefanstefan00000000000000Installation and Setup ====================== Install ``fookebox`` using easy_install:: easy_install fookebox Make a config file as follows:: paster make-config fookebox config.ini Tweak the config file as appropriate and then setup the application:: paster setup-app config.ini Then you are ready to go. fookebox-0.6.1/ez_setup.py0000644000175000017500000002276411525403056016340 0ustar stefanstefan00000000000000#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import sys DEFAULT_VERSION = "0.6c9" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:]) fookebox-0.6.1/setup.py0000644000175000017500000000324611743150142015631 0ustar stefanstefan00000000000000try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fookebox', version='0.6.1', description='A jukebox-style web-frontend to mpd', long_description="""fookebox is a jukebox-style web-frontend to mpd. It can be used as a keyboard-less jukebox, as a powerful mpd control frontend or as anything in between.""", author='Stefan Ott', author_email='stefan@ott.net', url='http://fookebox.googlecode.com/', install_requires=[ "Pylons>=0.10", 'python-mpd', ], keywords='mpd jukebox web music party', setup_requires=["PasteScript>=1.6.3"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'fookebox': ['i18n/*/LC_MESSAGES/*.mo']}, license='GPLv3', message_extractors={'fookebox': [ ('**.py', 'python', None), ('templates/**.tpl', 'mako', {'input_encoding': 'utf-8'}), ('public/**', 'ignore', None)]}, zip_safe=False, paster_plugins=['PasteScript', 'Pylons'], entry_points=""" [paste.app_factory] main = fookebox.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Pylons', 'Intended Audience :: End Users/Desktop', 'License :: DFSG approved', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Natural Language :: German', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Multimedia', 'Topic :: Multimedia :: Sound/Audio', ], ) fookebox-0.6.1/PKG-INFO0000644000175000017500000000173611743153607015227 0ustar stefanstefan00000000000000Metadata-Version: 1.1 Name: fookebox Version: 0.6.1 Summary: A jukebox-style web-frontend to mpd Home-page: http://fookebox.googlecode.com/ Author: Stefan Ott Author-email: stefan@ott.net License: GPLv3 Description: fookebox is a jukebox-style web-frontend to mpd. It can be used as a keyboard-less jukebox, as a powerful mpd control frontend or as anything in between. Keywords: mpd jukebox web music party Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Framework :: Pylons Classifier: Intended Audience :: End Users/Desktop Classifier: License :: DFSG approved Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Natural Language :: German Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Multimedia Classifier: Topic :: Multimedia :: Sound/Audio fookebox-0.6.1/setup.cfg0000644000175000017500000000105711743153607015747 0ustar stefanstefan00000000000000[egg_info] tag_build = tag_svn_revision = 0 tag_date = 0 [easy_install] find_links = http://www.pylonshq.com/download/ [nosetests] with-pylons = test.ini [compile_catalog] domain = fookebox directory = fookebox/i18n statistics = true [extract_messages] add_comments = TRANSLATORS: output_file = fookebox/i18n/fookebox.pot width = 80 [init_catalog] domain = fookebox input_file = fookebox/i18n/fookebox.pot output_dir = fookebox/i18n [update_catalog] domain = fookebox input_file = fookebox/i18n/fookebox.pot output_dir = fookebox/i18n previous = true