]> git.parisson.com Git - timeside.git/commitdiff
make it a real module with a setup
authoryomguy <yomguy@parisson.com>
Thu, 17 Jun 2010 16:54:43 +0000 (16:54 +0000)
committeryomguy <yomguy@parisson.com>
Thu, 17 Jun 2010 16:54:43 +0000 (16:54 +0000)
155 files changed:
__init__.py [deleted file]
analyzer/__init__.py [deleted file]
analyzer/core.py [deleted file]
analyzer/dc.py [deleted file]
analyzer/duration.py [deleted file]
analyzer/max_level.py [deleted file]
analyzer/mean_level.py [deleted file]
analyzer/vamp/__init__.py [deleted file]
analyzer/vamp/core.py [deleted file]
api.py [deleted file]
component.py [deleted file]
core.py [deleted file]
decoder/__init__.py [deleted file]
decoder/core.py [deleted file]
doc/img/timeside_schema.dia [deleted file]
doc/img/timeside_schema.png [deleted file]
encoder/__init__.py [deleted file]
encoder/core.py [deleted file]
encoder/flac.py [deleted file]
encoder/mp3.py [deleted file]
encoder/ogg.py [deleted file]
encoder/wav.py [deleted file]
exceptions.py [deleted file]
grapher/__init__.py [deleted file]
grapher/core.py [deleted file]
grapher/spectrogram.py [deleted file]
grapher/spectrogram_audiolab.py [deleted file]
grapher/waveform.py [deleted file]
grapher/waveform_audiolab.py [deleted file]
metadata.py [deleted file]
setup.py [new file with mode: 0644]
tests/__init__.py [deleted file]
tests/alltests.py [deleted file]
tests/api/__init__.py [deleted file]
tests/api/examples.py [deleted file]
tests/api/gstreamer.py [deleted file]
tests/api/test_lolevel.py [deleted file]
tests/api/test_pipe.py [deleted file]
tests/api/test_pipe_spectrogram.py [deleted file]
tests/api/test_pipe_waveform.py [deleted file]
tests/listprocessors.py [deleted file]
tests/samples/guitar.wav [deleted file]
tests/samples/sweep.flac [deleted file]
tests/samples/sweep.mp3 [deleted file]
tests/samples/sweep.ogg [deleted file]
tests/samples/sweep.wav [deleted file]
tests/samples/sweep_source.wav [deleted file]
tests/testcomponent.py [deleted file]
tests/testinputadapter.py [deleted file]
timeside/__init__.py [new file with mode: 0644]
timeside/analyzer/__init__.py [new file with mode: 0644]
timeside/analyzer/core.py [new file with mode: 0644]
timeside/analyzer/dc.py [new file with mode: 0644]
timeside/analyzer/duration.py [new file with mode: 0644]
timeside/analyzer/max_level.py [new file with mode: 0644]
timeside/analyzer/mean_level.py [new file with mode: 0644]
timeside/analyzer/vamp/__init__.py [new file with mode: 0644]
timeside/analyzer/vamp/core.py [new file with mode: 0644]
timeside/api.py [new file with mode: 0644]
timeside/component.py [new file with mode: 0644]
timeside/core.py [new file with mode: 0644]
timeside/decoder/__init__.py [new file with mode: 0644]
timeside/decoder/core.py [new file with mode: 0644]
timeside/doc/img/timeside_schema.dia [new file with mode: 0644]
timeside/doc/img/timeside_schema.png [new file with mode: 0644]
timeside/encoder/__init__.py [new file with mode: 0644]
timeside/encoder/core.py [new file with mode: 0644]
timeside/encoder/flac.py [new file with mode: 0644]
timeside/encoder/mp3.py [new file with mode: 0644]
timeside/encoder/ogg.py [new file with mode: 0644]
timeside/encoder/wav.py [new file with mode: 0644]
timeside/exceptions.py [new file with mode: 0644]
timeside/grapher/__init__.py [new file with mode: 0644]
timeside/grapher/core.py [new file with mode: 0644]
timeside/grapher/spectrogram.py [new file with mode: 0644]
timeside/grapher/spectrogram_audiolab.py [new file with mode: 0644]
timeside/grapher/waveform.py [new file with mode: 0644]
timeside/grapher/waveform_audiolab.py [new file with mode: 0644]
timeside/metadata.py [new file with mode: 0644]
timeside/tests/__init__.py [new file with mode: 0644]
timeside/tests/alltests.py [new file with mode: 0644]
timeside/tests/api/__init__.py [new file with mode: 0644]
timeside/tests/api/examples.py [new file with mode: 0644]
timeside/tests/api/gstreamer.py [new file with mode: 0644]
timeside/tests/api/test_lolevel.py [new file with mode: 0644]
timeside/tests/api/test_pipe.py [new file with mode: 0644]
timeside/tests/api/test_pipe_spectrogram.py [new file with mode: 0644]
timeside/tests/api/test_pipe_waveform.py [new file with mode: 0644]
timeside/tests/listprocessors.py [new file with mode: 0644]
timeside/tests/samples/guitar.wav [new file with mode: 0644]
timeside/tests/samples/sweep.flac [new file with mode: 0644]
timeside/tests/samples/sweep.mp3 [new file with mode: 0644]
timeside/tests/samples/sweep.ogg [new file with mode: 0644]
timeside/tests/samples/sweep.wav [new file with mode: 0644]
timeside/tests/samples/sweep_source.wav [new file with mode: 0644]
timeside/tests/testcomponent.py [new file with mode: 0644]
timeside/tests/testinputadapter.py [new file with mode: 0644]
timeside/tools/grapher_scheme.py [new file with mode: 0644]
timeside/tools/waveform_batch.py [new file with mode: 0644]
timeside/ui/README [new file with mode: 0644]
timeside/ui/css/timeside.css [new file with mode: 0755]
timeside/ui/demo/index.html [new file with mode: 0755]
timeside/ui/demo/waveform.png [new file with mode: 0755]
timeside/ui/lib/firebug-lite-compressed.js [new file with mode: 0644]
timeside/ui/lib/jquery.js [new file with mode: 0755]
timeside/ui/lib/soundmanager2.js [new file with mode: 0755]
timeside/ui/lib/soundmanager2.swf [new file with mode: 0755]
timeside/ui/lib/soundmanager2_flash9.swf [new file with mode: 0755]
timeside/ui/lib/wz_jsgraphics.js [new file with mode: 0755]
timeside/ui/skins/lab/img/controlbg.png [new file with mode: 0755]
timeside/ui/skins/lab/img/forward.png [new file with mode: 0755]
timeside/ui/skins/lab/img/pause.png [new file with mode: 0755]
timeside/ui/skins/lab/img/play.png [new file with mode: 0755]
timeside/ui/skins/lab/img/rewind.png [new file with mode: 0755]
timeside/ui/skins/lab/img/setmarker.png [new file with mode: 0644]
timeside/ui/skins/lab/style.css [new file with mode: 0755]
timeside/ui/src/controller.js [new file with mode: 0644]
timeside/ui/src/core.js [new file with mode: 0644]
timeside/ui/src/marker.js [new file with mode: 0644]
timeside/ui/src/markerlist.js [new file with mode: 0755]
timeside/ui/src/markermap.js [new file with mode: 0644]
timeside/ui/src/player.js [new file with mode: 0644]
timeside/ui/src/ruler.js [new file with mode: 0644]
timeside/ui/src/soundprovider.js [new file with mode: 0644]
timeside/ui/src/timeside.js [new file with mode: 0644]
timeside/ui/src/util.js [new file with mode: 0755]
tools/grapher_scheme.py [deleted file]
tools/waveform_batch.py [deleted file]
ui/README [deleted file]
ui/css/timeside.css [deleted file]
ui/demo/index.html [deleted file]
ui/demo/waveform.png [deleted file]
ui/lib/firebug-lite-compressed.js [deleted file]
ui/lib/jquery.js [deleted file]
ui/lib/soundmanager2.js [deleted file]
ui/lib/soundmanager2.swf [deleted file]
ui/lib/soundmanager2_flash9.swf [deleted file]
ui/lib/wz_jsgraphics.js [deleted file]
ui/skins/lab/img/controlbg.png [deleted file]
ui/skins/lab/img/forward.png [deleted file]
ui/skins/lab/img/pause.png [deleted file]
ui/skins/lab/img/play.png [deleted file]
ui/skins/lab/img/rewind.png [deleted file]
ui/skins/lab/img/setmarker.png [deleted file]
ui/skins/lab/style.css [deleted file]
ui/src/controller.js [deleted file]
ui/src/core.js [deleted file]
ui/src/marker.js [deleted file]
ui/src/markerlist.js [deleted file]
ui/src/markermap.js [deleted file]
ui/src/player.js [deleted file]
ui/src/ruler.js [deleted file]
ui/src/soundprovider.js [deleted file]
ui/src/timeside.js [deleted file]
ui/src/util.js [deleted file]

diff --git a/__init__.py b/__init__.py
deleted file mode 100644 (file)
index 81ad004..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from core import *
-from metadata import Metadata
-import decoder
-import encoder
-import analyzer
-import grapher
diff --git a/analyzer/__init__.py b/analyzer/__init__.py
deleted file mode 100644 (file)
index 0bd2039..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-from timeside.analyzer.core import *
-from timeside.analyzer.duration import *
-from timeside.analyzer.max_level import *
-#from timeside.analyzer.mean_level import *
-#from timeside.analyzer.dc import *
diff --git a/analyzer/core.py b/analyzer/core.py
deleted file mode 100644 (file)
index cbb9a17..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Authors:
-#   Guillaume Pellerin <yomguy at parisson.com>
-
-pass
-
-
diff --git a/analyzer/dc.py b/analyzer/dc.py
deleted file mode 100644 (file)
index e92cfd5..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.analyzer.core import *
-from timeside.api import IValueAnalyzer
-import numpy
-
-
-class MeanDCShift(Processor):
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(MeanDCShift, self).setup(channels, samplerate, nframes)
-        self.value = 0
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "dc"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Mean DC shift"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        return "%"
-
-    def __str__(self):
-        return "%s %s" % (str(self.value), unit())
-
-    def process(self, frames, eod=False):
-        self.value = numpy.round(100*numpy.mean(samples),4)
-        return frames, eod
-
-    def result(self):
-        return self.value
-
diff --git a/analyzer/duration.py b/analyzer/duration.py
deleted file mode 100644 (file)
index 7c2269c..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
-from timeside.analyzer.core import *
-from timeside.api import IValueAnalyzer
-
-
-class Duration(Processor):
-    """A rather useless duration analyzer. Its only purpose is to test the
-       nframes characteristic."""
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels, samplerate, nframes):
-        if not nframes:
-            raise Exception("nframes argument required")
-        super(Duration, self).setup(channels, samplerate, nframes)
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "duration"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Duration"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        return "seconds"
-
-    def result(self):
-        return self.input_nframes / float(self.input_samplerate)
-    
\ No newline at end of file
diff --git a/analyzer/max_level.py b/analyzer/max_level.py
deleted file mode 100644 (file)
index 9ecc323..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
-from timeside.analyzer.core import *
-from timeside.api import IValueAnalyzer
-
-
-class MaxLevel(Processor):
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(MaxLevel, self).setup(channels, samplerate, nframes)
-        self.max_value = 0
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "maxlevel"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Max level"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        # power? amplitude?
-        return ""
-
-    def process(self, frames, eod=False):
-        max = frames.max()
-        if max > self.max_value:
-            self.max_value = max
-
-        return frames, eod
-
-    def result(self):
-        return self.max_value
-
-
diff --git a/analyzer/mean_level.py b/analyzer/mean_level.py
deleted file mode 100644 (file)
index 8b68324..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.analyzer.core import *
-from timeside.api import IValueAnalyzer
-import numpy
-
-
-class MeanLevel(Processor):
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(MeanLevel, self).setup(channels, samplerate, nframes)
-        self.value = -140
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "meanlevel"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Mean RMS level"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        return "dB"
-
-    def __str__(self):
-        return "%s %s" % (str(self.value), unit())
-
-    def process(self, frames, eod=False):
-        max = numpy.round(20*numpy.log10(numpy.mean(numpy.sqrt(numpy.square(frames.max())))), 2)
-        if max > self.value:
-            self.value = max
-
-        return frames, eod
-
-    def result(self):
-        return self.value
-
diff --git a/analyzer/vamp/__init__.py b/analyzer/vamp/__init__.py
deleted file mode 100644 (file)
index 1ded83d..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from timeside.analyzer.vamp.core import *
diff --git a/analyzer/vamp/core.py b/analyzer/vamp/core.py
deleted file mode 100644 (file)
index 49ae9a0..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import *
-from tempfile import NamedTemporaryFile
-from timeside.exceptions import SubProcessError
-import os
-import random
-import subprocess
-import signal
-import time
-
-class VampCoreAnalyzer:
-    """Parent class for Vamp plugin drivers"""
-
-    def __init__(self):
-        self.vamp_path = '/usr/lib/vamp/'
-        # needs vamp-examples package
-        self.host = 'vamp-simple-host'
-        self.buffer_size = 0xFFFF
-
-    def id(self):
-        return "vamp_plugins"
-
-    def name(self):
-        return "Vamp plugins"
-
-    def unit(self):
-        return ""
-
-    def get_plugins_list(self):
-        if os.path.exists(self.vamp_path):
-            args = ' --list-outputs'
-            command = self.host + args
-            #tmp_file = NamedTemporaryFile()
-            data = self.core_process(command, self.buffer_size)
-            text = ''
-            plugins = []
-            for chunk in data:
-                text = text + chunk
-            lines = text.split('\n')
-            for line in lines:
-                if line != '':
-                    struct = line.split(':')
-                    struct = struct[1:]
-                    plugins.append(struct)
-            return plugins
-        else:
-            return []
-
-    def get_wav_path(self, media_item):
-        return settings.MEDIA_ROOT + '/' + media_item.file
-        #return media_item
-
-    def render(self, plugin, media_item):
-        self.wavFile = self.get_wav_path(media_item)
-        args = ' -s ' + ':'.join(plugin) + ' ' + str(self.wavFile)
-        command = command = self.host + args
-        data = self.core_process(command, self.buffer_size)
-        string = ''
-        values = {}
-        for chunk in data:
-            string = string + chunk
-        lines = string.split('\n')
-        for line in lines:
-            if line != '':
-                struct = line.split(':')
-                values[struct[0]] = struct[1]
-        return values
-
-    def core_process(self, command, buffer_size):
-        """Encode and stream audio data through a generator"""
-
-        __chunk = 0
-
-        try:
-            proc = subprocess.Popen(command,
-                    shell = True,
-                    bufsize = buffer_size,
-                    stdin = subprocess.PIPE,
-                    stdout = subprocess.PIPE,
-                    close_fds = True)
-        except:
-            raise SubProcessError('Command failure:', command, proc)
-
-        # Core processing
-        while True:
-            __chunk = proc.stdout.read(buffer_size)
-            status = proc.poll()
-            if status != None and status != 0:
-                raise SubProcessError('Command failure:', command, proc)
-            if len(__chunk) == 0:
-                break
-            yield __chunk
-
-
diff --git a/api.py b/api.py
deleted file mode 100644 (file)
index 7ceaecf..0000000
--- a/api.py
+++ /dev/null
@@ -1,214 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007-2009 Parisson
-# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
-# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-from timeside.component import Interface
-
-class IProcessor(Interface):
-    """Common processor interface"""
-
-    @staticmethod
-    def id():
-        """Short alphanumeric, lower-case string which uniquely identify this 
-        processor, suitable for use as an HTTP/GET argument value, in filenames, 
-        etc..."""
-
-        # implementation: only letters and digits are allowed. An exception will
-        # be raised by MetaProcessor if the id is malformed or not unique amongst
-        # registered processors.
-
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        """Allocate internal resources and reset state, so that this processor is
-        ready for a new run. 
-        
-        The channels, samplerate and/or nframes arguments may be required by 
-        processors which accept input. An error will occur if any of
-        these arguments is passed to an output-only processor such as a decoder.
-        """
-
-        # implementations should always call the parent method
-
-    def channels(self):
-        """Number of channels in the data returned by process(). May be different from
-        the number of channels passed to setup()"""
-
-    def samplerate(self):
-        """Samplerate of the data returned by process(). May be different from
-        the samplerate passed to setup()"""
-
-    def nframes():
-        """The total number of frames that this processor can output, or None if
-        the duration is unknown."""
-
-    def process(self, frames=None, eod=False):
-        """Process input frames and return a (output_frames, eod) tuple.
-        Both input and output frames are 2D numpy arrays, where columns are 
-        channels, and containing an undetermined number of frames.  eod=True 
-        means that the end-of-data has been reached.
-        
-        Output-only processors (such as decoders) will raise an exception if the
-        frames argument is not None. All processors (even encoders) return data,
-        even if that means returning the input unchanged.
-        
-        Warning: it is required to call setup() before this method."""
-
-    def release(self):
-        """Release resources owned by this processor. The processor cannot
-        be used anymore after calling this method."""
-
-        # implementations should always call the parent method
-
-class IEncoder(IProcessor):
-    """Encoder driver interface. Each encoder is expected to support a specific
-    format."""
-
-    def __init__(self, output):
-        """Create a new encoder. output can either be a filename or a python callback 
-        function/method for streaming mode.
-
-        The streaming callback prototype is: callback(data, eod)
-        Where data is a block of binary data of an undetermined size, and eod
-        True when end-of-data is reached."""
-
-        # implementation: the constructor must always accept the output argument. It may 
-        # accept extra arguments such as bitrate, depth, etc.., but these must be optionnal 
-
-    @staticmethod
-    def format():
-        """Return the encode/encoding format as a short string
-        Example: "MP3", "OGG", "AVI", ...
-        """
-
-    @staticmethod
-    def description():
-        """Return a string describing what this encode format provides, is good
-        for, etc... The description is meant to help the end user decide what
-        format is good for him/her
-        """
-
-    @staticmethod
-    def file_extension():
-        """Return the filename extension corresponding to this encode format"""
-
-    @staticmethod
-    def mime_type():
-        """Return the mime type corresponding to this encode format"""
-
-    def set_metadata(self, metadata):
-        """Set the metadata to be embedded in the encoded output.
-        
-        In non-streaming mode, this method updates the metadata directly into the 
-        output file, without re-encoding the audio data, provided this file already 
-        exists.
-        
-        It isn't required to call this method, but if called, it must be before 
-        process()."""
-
-class IDecoder(IProcessor):
-    """Decoder driver interface. Decoders are different of encoders in that
-    a given driver may support several input formats, hence this interface doesn't
-    export any static method, all informations are dynamic."""
-
-    def __init__(self, filename):
-        """Create a new decoder for filename."""
-        # implementation: additional optionnal arguments are allowed 
-
-    def format():
-        """Return a user-friendly file format string"""
-   
-    def encoding():
-        """Return a user-friendly encoding string"""
-
-    def resolution():
-        """Return the sample width (8, 16, etc..) of original audio file/stream,
-           or None if not applicable/known"""
-
-    def metadata(self):
-        """Return the metadata embedded into the encoded stream, if any."""
-
-class IGrapher(IProcessor):
-    """Media item visualizer driver interface"""
-
-    # implementation: graphers which need to know the total number of frames
-    # should raise an exception in setup() if the nframes argument is None 
-
-    def __init__(self, width, height):
-        """Create a new grapher. width and height are generally
-        in pixels but could be something else for eg. svg rendering, etc.. """
-
-        # implementation: additional optionnal arguments are allowed 
-
-    @staticmethod
-    def name():
-        """Return the graph name, such as "Waveform", "Spectral view",
-        etc..  """
-
-    def set_colors(self, background=None, scheme=None):
-        """Set the colors used for image generation. background is a RGB tuple,
-        and scheme a a predefined color theme name"""
-
-    def render(self):
-        """Return a PIL Image object visually representing all of the data passed
-        by repeatedly calling process()"""
-
-class IAnalyzer(IProcessor):
-    """Media item analyzer driver interface. This interface is abstract, it doesn't
-    describe a particular type of analyzer but is rather meant to group analyzers.
-    In particular, the way the result is returned may greatly vary from sub-interface
-    to sub-interface. For example the IValueAnalyzer returns a final single numeric
-    result at the end of the whole analysis. But some other analyzers may return
-    numpy arrays, and this, either at the end of the analysis, or from process()
-    for each block of data (as in Vamp)."""
-
-    def __init__(self):
-        """Create a new analyzer."""
-        # implementation: additional optionnal arguments are allowed 
-
-    @staticmethod
-    def name():
-        """Return the analyzer name, such as "Mean Level", "Max level",
-        "Total length, etc..  """
-
-    @staticmethod
-    def unit():
-        """Return the unit of the data such as "dB", "seconds", etc...  """
-
-class IValueAnalyzer(IAnalyzer):
-    """Interface for analyzers which return a single numeric value from result()"""
-
-    def result():
-        """Return the final result of the analysis performed over the data passed by
-        repeatedly calling process()"""
-
-    def __str__(self):
-        """Return a human readable string containing both result and unit 
-        ('5.30dB', '4.2s', etc...)"""
-
-class IEffect(IProcessor):
-    """Effect processor interface"""
-
-    def __init__(self):
-        """Create a new effect."""
-        # implementation: additional optionnal arguments are allowed 
-
-    @staticmethod
-    def name():
-        """Return the effect name"""
-
diff --git a/component.py b/component.py
deleted file mode 100644 (file)
index ff20670..0000000
+++ /dev/null
@@ -1,142 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-
-# This file defines a generic object interface mechanism and 
-# a way to determine which components implements a given interface.
-#
-# For example, the following defines the Music class as implementing the
-# listenable interface.
-#
-# class Listenable(Interface):
-#     pass
-#
-# class Music(Component):
-#    implements(Listenable)
-#
-# Several class can implements a such interface, and it is possible to 
-# discover which class implements it with implementations():
-#
-# list_of_classes = implementations(Listenable)
-#
-# This mechanism support inheritance of interfaces: a class implementing a given 
-# interface is also considered to implement all the ascendants of this interface.
-#
-# However, inheritance is not supported for components. The descendants of a class 
-# implementing a given interface are not automatically considered to implement this 
-# interface too. 
-
-__all__ = ['Component', 'MetaComponent', 'implements', 'abstract', 
-           'interfacedoc', 'Interface', 'implementations', 'ComponentError']
-
-class Interface(object):
-    """Marker base class for interfaces."""
-
-def implements(*interfaces):
-    """Registers the interfaces implemented by a component when placed in the
-    class header"""
-    MetaComponent.implements.extend(interfaces)
-
-def abstract():
-    """Declare a component as abstract when placed in the class header"""
-    MetaComponent.abstract = True
-
-def implementations(interface, recurse=True, abstract=False):
-    """Returns the components implementing interface, and if recurse, any of 
-    the descendants of interface. If abstract is True, also return the 
-    abstract implementations."""
-    result = []
-    find_implementations(interface, recurse, abstract, result)
-    return result
-
-def interfacedoc(func):
-    if isinstance(func, staticmethod):
-        raise ComponentError("@interfacedoc can't handle staticmethod (try to put @staticmethod above @interfacedoc)")
-
-    if not func.__doc__:
-        func.__doc__ = "@interfacedoc"
-        func._interfacedoc = True
-    return func
-
-class MetaComponent(type):
-    """Metaclass of the Component class, used mainly to register the interface
-    declared to be implemented by a component."""
-
-    implementations     = []
-    implements          = []
-    abstract            = False
-
-    def __new__(cls, name, bases, d):
-        new_class = type.__new__(cls, name, bases, d)
-
-        # Register implementations
-        if MetaComponent.implements:
-            for i in MetaComponent.implements:
-                MetaComponent.implementations.append({
-                    'interface': i, 
-                    'class':     new_class,
-                    'abstract':  MetaComponent.abstract})
-
-        # Propagate @interfacedoc
-        for name in new_class.__dict__:
-            member = new_class.__dict__[name]
-            if isinstance(member, staticmethod):
-                member = getattr(new_class, name)
-
-            if member.__doc__ == "@interfacedoc":
-                if_member = None
-                for i in MetaComponent.implements:
-                    if hasattr(i, name):
-                        if_member = getattr(i, name)
-                if not if_member:
-                    raise ComponentError("@interfacedoc: %s.%s: no such member in implemented interfaces: %s"
-                                         % (new_class.__name__, name, str(MetaComponent.implements)))
-                member.__doc__ = if_member.__doc__
-                
-        MetaComponent.implements = []
-        MetaComponent.abstract   = False
-
-        return new_class
-
-class Component(object):
-    """Base class of all components"""
-    __metaclass__ = MetaComponent
-
-def extend_unique(list1, list2):
-    """Extend list1 with list2 as list.extend(), but doesn't append duplicates
-    to list1"""
-    for item in list2:
-        if item not in list1:
-            list1.append(item)
-
-def find_implementations(interface, recurse, abstract, result):
-    """Find implementations of an interface or of one of its descendants and
-    extend result with the classes found."""
-    for item in MetaComponent.implementations:
-        if (item['interface'] == interface and (abstract or not item['abstract'])):
-            extend_unique(result, [item['class']])
-
-    if recurse:
-        subinterfaces = interface.__subclasses__()
-        if subinterfaces:
-            for i in subinterfaces:
-                find_implementations(i, recurse, abstract, result)
-
-class ComponentError(Exception):
-    pass
diff --git a/core.py b/core.py
deleted file mode 100644 (file)
index f5b3c31..0000000
--- a/core.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-from timeside.component import *
-from timeside.api import IProcessor
-from timeside.exceptions import Error, ApiError
-import re
-import numpy
-
-__all__ = ['Processor', 'MetaProcessor', 'implements', 'abstract', 
-           'interfacedoc', 'processors', 'get_processor', 'ProcessPipe',
-           'FixedSizeInputAdapter']
-
-_processors = {}
-
-class MetaProcessor(MetaComponent):
-    """Metaclass of the Processor class, used mainly for ensuring that processor
-    id's are wellformed and unique"""
-
-    valid_id = re.compile("^[a-z][_a-z0-9]*$")
-
-    def __new__(cls, name, bases, d):
-        new_class = MetaComponent.__new__(cls, name, bases, d)
-        if new_class in implementations(IProcessor):
-            id = str(new_class.id())
-            if _processors.has_key(id):
-                raise ApiError("%s and %s have the same id: '%s'"
-                    % (new_class.__name__, _processors[id].__name__, id))
-            if not MetaProcessor.valid_id.match(id):
-                raise ApiError("%s has a malformed id: '%s'"
-                    % (new_class.__name__, id))
-
-            _processors[id] = new_class
-
-        return new_class
-
-class Processor(Component):
-    """Base component class of all processors"""
-    __metaclass__ = MetaProcessor
-
-    abstract()
-    implements(IProcessor)
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        self.input_channels   = channels
-        self.input_samplerate = samplerate
-        self.input_nframes    = nframes
-
-    # default channels(), samplerate() and nframes() implementations returns 
-    # the input characteristics, but processors may change this behaviour by 
-    # overloading those methods
-    @interfacedoc
-    def channels(self):
-        return self.input_channels
-
-    @interfacedoc
-    def samplerate(self):
-        return self.input_samplerate
-
-    @interfacedoc
-    def nframes(self):
-        return self.input_nframes
-
-    @interfacedoc
-    def process(self, frames, eod):
-        return frames, eod
-
-    @interfacedoc
-    def release(self):
-        pass
-
-    def __del__(self):
-        self.release()
-
-    def __or__(self, other):
-        return ProcessPipe(self, other)
-
-class FixedSizeInputAdapter(object):
-    """Utility to make it easier to write processors which require fixed-sized
-    input buffers."""
-
-    def __init__(self, buffer_size, channels, pad=False):
-        """Construct a new adapter: buffer_size is the desired buffer size in frames,
-        channels the number of channels, and pad indicates whether the last block should 
-        be padded with zeros."""
-
-        self.buffer      = numpy.empty((buffer_size, channels))
-        self.buffer_size = buffer_size
-        self.len         = 0
-        self.pad         = pad
-
-    def nframes(self, input_nframes):
-        """Return the total number of frames that this adapter will output according to the
-        input_nframes argument"""
-
-        nframes = input_nframes
-        if self.pad:
-            mod = input_nframes % self.buffer_size
-            if mod:
-                nframes += self.buffer_size - mod
-
-        return nframes                
-
-
-    def process(self, frames, eod):
-        """Returns an iterator over tuples of the form (buffer, eod) where buffer is a 
-        fixed-sized block of data, and eod indicates whether this is the last block.
-        In case padding is deactivated the last block may be smaller than the buffer size.
-        """
-        src_index = 0
-        remaining = len(frames)
-
-        while remaining:
-            space   = self.buffer_size - self.len
-            copylen = remaining < space and remaining or space
-            src     = frames[src_index:src_index + copylen]
-            if self.len == 0 and copylen == self.buffer_size:
-                # avoid unnecessary copy
-                buffer = src
-            else:
-                buffer = self.buffer
-                buffer[self.len:self.len + copylen] = src
-
-            remaining -= copylen
-            src_index += copylen
-            self.len  += copylen
-
-            if self.len == self.buffer_size:
-                yield buffer, (eod and not remaining)
-                self.len = 0
-
-        if eod and self.len:
-            block = self.buffer
-            if self.pad:
-                self.buffer[self.len:self.buffer_size] = 0
-            else:
-                block = self.buffer[0:self.len]
-
-            yield block, True
-            self.len = 0
-                            
-def processors(interface=IProcessor, recurse=True):
-    """Returns the processors implementing a given interface and, if recurse,
-    any of the descendants of this interface."""
-    return implementations(interface, recurse)
-    
-
-def get_processor(processor_id):
-    """Return a processor by its id"""
-    if not _processors.has_key(processor_id):
-        raise Error("No processor registered with id: '%s'" 
-              % processor_id)
-
-    return _processors[processor_id]
-
-class ProcessPipe(object):
-    """Handle a pipe of processors"""
-
-    def __init__(self, *others):
-        self.processors = []
-        self |= others
-
-    def __or__(self, other):
-        return ProcessPipe(self, other)
-
-    def __ior__(self, other):
-        if isinstance(other, Processor):
-            self.processors.append(other)
-        elif isinstance(other, ProcessPipe):
-            self.processors.extend(other.processors)
-        else:
-            try:
-                iter(other)
-            except TypeError:
-                raise Error("Can not add this type of object to a pipe: %s", str(other))
-
-            for item in other:
-                self |= item
-
-        return self            
-
-    def run(self):
-        """Setup/reset all processors in cascade and stream audio data along
-        the pipe. Also returns the pipe itself."""
-
-        source = self.processors[0]
-        items  = self.processors[1:]
-
-        # setup/reset processors and configure channels and samplerate throughout the pipe
-        source.setup()
-        last = source
-        for item in items:
-            item.setup(last.channels(), last.samplerate(), last.nframes())
-            last = item
-
-        # now stream audio data along the pipe
-        eod = False
-        while not eod:
-            frames, eod = source.process()
-            for item in items:
-                frames, eod = item.process(frames, eod)
-
-        return self                
-       
diff --git a/decoder/__init__.py b/decoder/__init__.py
deleted file mode 100644 (file)
index 9f37f75..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from timeside.decoder.core import *
diff --git a/decoder/core.py b/decoder/core.py
deleted file mode 100644 (file)
index 08d6e94..0000000
+++ /dev/null
@@ -1,243 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import *
-import subprocess
-
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007-2009 Parisson
-# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
-# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Paul Brossier <piem@piem.org>
-
-from timeside.core import Processor, implements, interfacedoc
-from timeside.api import IDecoder
-from numpy import array, frombuffer, getbuffer, float32
-
-import pygst
-pygst.require('0.10')
-import gst
-import gobject
-gobject.threads_init ()
-
-
-class FileDecoder(Processor):
-    """ gstreamer-based decoder """
-    implements(IDecoder)
-
-    # duration ms, before discovery process times out
-    MAX_DISCOVERY_TIME = 3000
-
-    audioformat = None
-    audiochannels = None
-    audiorate = None
-    audionframes = None
-    mimetype = ''
-
-    # IProcessor methods
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "gstreamerdec"
-
-    def setup(self, channels = None, samplerate = None, nframes = None):
-        # the output data format we want
-        caps = "audio/x-raw-float, width=32"
-        pipeline = gst.parse_launch('''uridecodebin uri=%s
-            ! audioconvert
-            ! %s
-            ! appsink name=sink sync=False ''' % (self.uri, caps))
-        # store a pointer to appsink in our decoder object 
-        self.sink = pipeline.get_by_name('sink')
-        # adjust length of emitted buffers
-        # self.sink.set_property('blocksize', 0x10000)
-        # start pipeline
-        pipeline.set_state(gst.STATE_PLAYING)
-
-    @interfacedoc
-    def channels(self):
-        return  self.audiochannels
-
-    @interfacedoc
-    def samplerate(self):
-        return self.audiorate 
-
-    @interfacedoc
-    def nframes(self):
-        return self.audionframes
-
-    @interfacedoc
-    def process(self, frames = None, eod = False):
-        try:
-            buf = self.sink.emit('pull-buffer')
-        except SystemError, e:
-            # should never happen
-            print 'SystemError', e
-            return array([0.]), True
-        if buf == None:
-            return array([0.]), True
-        return self.gst_buffer_to_numpy_array(buf), False
-
-    @interfacedoc
-    def release(self):
-        # nothing to do for now 
-        pass
-
-    ## IDecoder methods
-
-    @interfacedoc
-    def __init__(self, uri):
-
-        # is this a file? 
-        import os.path
-        if os.path.exists(uri):
-            # get the absolute path
-            uri = os.path.abspath(uri)
-            # first run the file/uri through the discover pipeline
-            self.discover(uri)
-            # and make a uri of it
-            from urllib import quote
-            self.uri = 'file://'+quote(uri)
-
-    @interfacedoc
-    def format(self):
-        # TODO check
-        return self.mimetype
-
-    @interfacedoc
-    def encoding(self):
-        # TODO check
-        return self.mimetype.split('/')[-1]
-
-    @interfacedoc
-    def resolution(self):
-        # TODO check: width or depth?
-        return self.audiowidth 
-
-    @interfacedoc
-    def metadata(self):
-        # TODO check
-        return self.tags
-
-    ## gst.extend discoverer
-
-    def discover(self, path):
-        """ gstreamer based helper function to get file attributes """
-        from gst.extend import discoverer
-        d = discoverer.Discoverer(path, timeout = self.MAX_DISCOVERY_TIME)
-        d.connect('discovered', self.discovered)
-        self.mainloop = gobject.MainLoop()
-        d.discover()
-        self.mainloop.run()
-
-    def discovered(self, d, is_media):
-        """ gstreamer based helper executed upon discover() completion """
-        if is_media and d.is_audio:
-            # copy the discoverer attributes to self
-            self.audiorate = d.audiorate
-            self.mimetype= d.mimetype
-            self.audiochannels = d.audiochannels
-            self.audiowidth = d.audiowidth
-            # conversion from time in nanoseconds to frames 
-            from math import ceil
-            duration = d.audiorate * d.audiolength * 1.e-9
-            self.audionframes = int (ceil ( duration ) )
-            self.tags = d.tags
-        elif not d.is_audio:
-            print "error, no audio found!"
-        else:
-            print "fail", path
-        self.mainloop.quit()
-
-    def gst_buffer_to_numpy_array(self, buf):
-        """ gstreamer buffer to numpy array conversion """
-        chan = self.audiochannels
-        samples = frombuffer(buf.data, dtype=float32) 
-        samples.resize([len(samples)/chan, chan])
-        return samples
-
-
-class SubProcessPipe:
-
-    def __init__(self, command, stdin=None):
-        """Read media and stream data through a generator.
-        Taken from Telemeta (see http://telemeta.org)"""
-
-        self.buffer_size = 0xFFFF
-
-        if not stdin:
-            stdin =  subprocess.PIPE
-
-        self.proc = subprocess.Popen(command.encode('utf-8'),
-                    shell = True,
-                    bufsize = self.buffer_size,
-                    stdin = stdin,
-                    stdout = subprocess.PIPE,
-                    close_fds = True)
-
-        self.input = self.proc.stdin
-        self.output = self.proc.stdout
-
-
-class DecoderSubProcessCore(Processor):
-    """Defines the main parts of the decoding tools :
-    paths, metadata parsing, data streaming thru system command"""
-
-    def __init__(self):
-        self.command = 'ffmpeg -i "%s" -f wav - '
-
-    def process(self, source, options=None):
-        """Encode and stream audio data through a generator"""
-
-        command = self.command % source
-        proc = SubProcessPipe(command)
-        return proc.output
-
-        #while True:
-            #__chunk = proc.output.read(self.proc.buffer_size)
-            #status = proc.poll()
-            #if status != None and status != 0:
-                #raise ExportProcessError('Command failure:', command, proc)
-            #if len(__chunk) == 0:
-                #break
-            #yield __chunk
-
-
-
diff --git a/doc/img/timeside_schema.dia b/doc/img/timeside_schema.dia
deleted file mode 100644 (file)
index 6431955..0000000
Binary files a/doc/img/timeside_schema.dia and /dev/null differ
diff --git a/doc/img/timeside_schema.png b/doc/img/timeside_schema.png
deleted file mode 100644 (file)
index 29f4bcb..0000000
Binary files a/doc/img/timeside_schema.png and /dev/null differ
diff --git a/encoder/__init__.py b/encoder/__init__.py
deleted file mode 100644 (file)
index 7eadf71..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from timeside.encoder.core import *
-#from timeside.encoder.ogg import *
-from timeside.encoder.wav import *
-#from timeside.encoder.mp3 import *
-#from timeside.encoder.flac import *
diff --git a/encoder/core.py b/encoder/core.py
deleted file mode 100644 (file)
index 9786de1..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import *
-import subprocess
-
-class SubProcessPipe:
-    """Read media and stream data through a generator.
-    Taken from Telemeta (see http://telemeta.org)"""
-
-    def __init__(self, command, stdin=None):
-        self.buffer_size = 0xFFFF
-        if not stdin:
-            stdin =  subprocess.PIPE
-
-        self.proc = subprocess.Popen(command.encode('utf-8'),
-                    shell = True,
-                    bufsize = self.buffer_size,
-                    stdin = stdin,
-                    stdout = subprocess.PIPE,
-                    close_fds = True)
-
-        self.input = self.proc.stdin
-        self.output = self.proc.stdout
-
-class EncoderSubProcessCore(Processor):
-    """Defines the main parts of the encoding tools :
-    paths, metadata parsing, data streaming thru system command"""
-
-    def core_process(self, command, stdin):
-        """Encode and stream audio data through a generator"""
-
-        proc = SubProcessPipe(command, stdin)
-
-        while True:
-            __chunk = proc.output.read(proc.buffer_size)
-            #status = proc.poll()
-            #if status != None and status != 0:
-                #raise EncodeProcessError('Command failure:', command, proc)
-            if len(__chunk) == 0:
-                break
-            yield __chunk
-
-
-
diff --git a/encoder/flac.py b/encoder/flac.py
deleted file mode 100644 (file)
index 0753441..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-import os
-import string
-import subprocess
-
-from timeside.encoder.core import *
-from timeside.api import IEncoder
-from tempfile import NamedTemporaryFile
-
-class FlacEncoder(EncoderCore):
-    """Defines methods to encode to FLAC"""
-
-    implements(IEncoder)
-
-    def __init__(self):
-        self.quality_default = '-5'
-        self.dub2args_dict = {'creator': 'artist',
-                             'relation': 'album'
-                             }
-
-    @staticmethod
-    def id():
-        return "flacenc"
-
-    def format(self):
-        return 'FLAC'
-
-    def file_extension(self):
-        return 'flac'
-
-    def mime_type(self):
-        return 'audio/x-flac'
-
-    def description(self):
-        return """
-        Free Lossless Audio Codec (FLAC) is a file format for lossless audio
-        data compression.
-        """
-
-    def get_file_info(self):
-        try:
-            file1, file2 = os.popen4('metaflac --list "'+self.dest+'"')
-            info = []
-            for line in file2.readlines():
-                info.append(clean_word(line[:-1]))
-            self.info = info
-            return self.info
-        except:
-            raise IOError('EncoderError: metaflac is not installed or ' + \
-                           'file does not exist.')
-
-    def write_tags(self, file):
-        from mutagen.flac import FLAC
-        media = FLAC(file)
-        for tag in self.metadata:
-            name = tag[0]
-            value = clean_word(tag[1])
-            if name in self.dub2args_dict.keys():
-                name = self.dub2args_dict[name]
-            if name == 'comment':
-                media['DESCRIPTION'] = unicode(value)
-            else:
-                media[name] = unicode(value)
-        try:
-            media.save()
-        except:
-            raise IOError('EncoderError: cannot write tags.')
-
-
-    def get_args(self,options=None):
-        """Get process options and return arguments for the encoder"""
-        args = []
-        if not options is None:
-            self.options = options
-            if not ('verbose' in self.options and self.options['verbose'] != '0'):
-                args.append('-s')
-            if 'flac_quality' in self.options:
-                args.append('-f ' + self.options['flac_quality'])
-            else:
-                args.append('-f ' + self.quality_default)
-        else:
-            args.append('-s -f ' + self.quality_default)
-
-        #for tag in self.metadata.keys():
-            #value = clean_word(self.metadata[tag])
-            #args.append('-c %s="%s"' % (tag, value))
-            #if tag in self.dub2args_dict.keys():
-                #arg = self.dub2args_dict[tag]
-                #args.append('-c %s="%s"' % (arg, value))
-
-        return args
-
-    def process(self, source, metadata, options=None):
-        buffer_size = 0xFFFF
-        self.metadata= metadata
-        self.options = options
-        args = self.get_args()
-        args = ' '.join(args)
-        ext = self.file_extension()
-        temp_file = NamedTemporaryFile()
-        command = 'flac %s - -o %s ' % (args, temp_file.name)
-
-        stream = self.core_process(command, source)
-
-        for __chunk in stream:
-            #temp_file.write(__chunk)
-            #temp_file.flush()
-            pass
-
-        #self.write_tags(temp_file.name)
-
-        while True:
-            __chunk = temp_file.read(buffer_size)
-            if len(__chunk) == 0:
-                break
-            yield __chunk
-
-        temp_file.close()
-
-
diff --git a/encoder/mp3.py b/encoder/mp3.py
deleted file mode 100644 (file)
index 70f6dfb..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007 Parisson SARL
-# Copyright (c) 2006-2007 Guillaume Pellerin <pellerin@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-import os
-import string
-import subprocess
-
-from timeside.encoder.core import *
-from timeside.api import IEncoder
-
-
-class Mp3Encoder(EncoderCore):
-    """Defines methods to encode to MP3"""
-
-    implements(IEncoder)
-
-    def __init__(self):
-        self.bitrate_default = '192'
-        self.dub2id3_dict = {'title': 'TIT2', #title2
-                             'creator': 'TCOM', #composer
-                             'creator': 'TPE1', #lead
-                             'identifier': 'UFID', #Unique ID...
-                             'identifier': 'TALB', #album
-                             'type': 'TCON', #genre
-                             'publisher': 'TPUB', #comment
-                             #'date': 'TYER', #year
-                             }
-        self.dub2args_dict = {'title': 'tt', #title2
-                             'creator': 'ta', #composerS
-                             'relation': 'tl', #album
-                             #'type': 'tg', #genre
-                             'publisher': 'tc', #comment
-                             'date': 'ty', #year
-                             }
-
-    @staticmethod
-    def id():
-        return "mp3enc"
-
-    def format(self):
-        return 'MP3'
-
-    def file_extension(self):
-        return 'mp3'
-
-    def mime_type(self):
-        return 'audio/mpeg'
-
-    def description(self):
-        return """
-        MPEG-1 Audio Layer 3, more commonly referred to as MP3, is a patented
-        digital audio encoding format using a form of lossy data compression.
-        """
-
-    def get_file_info(self):
-        try:
-            file_out1, file_out2 = os.popen4('mp3info "'+self.dest+'"')
-            info = []
-            for line in file_out2.readlines():
-                info.append(clean_word(line[:-1]))
-            self.info = info
-            return self.info
-        except:
-            raise IOError('EncoderError: file does not exist.')
-
-    def write_tags(self):
-        """Write all ID3v2.4 tags by mapping dub2id3_dict dictionnary with the
-            respect of mutagen classes and methods"""
-        from mutagen import id3
-        id3 = id3.ID3(self.dest)
-        for tag in self.metadata.keys():
-            if tag in self.dub2id3_dict.keys():
-                frame_text = self.dub2id3_dict[tag]
-                value = self.metadata[tag]
-                frame = mutagen.id3.Frames[frame_text](3,value)
-                try:
-                    id3.add(frame)
-                except:
-                    raise IOError('EncoderError: cannot tag "'+tag+'"')
-        try:
-            id3.save()
-        except:
-            raise IOError('EncoderError: cannot write tags')
-
-    def get_args(self):
-        """Get process options and return arguments for the encoder"""
-        args = []
-        if not self.options is None:
-            if not ( 'verbose' in self.options and self.options['verbose'] != '0' ):
-                args.append('-S')
-            if 'mp3_bitrate' in self.options:
-                args.append('-b ' + self.options['mp3_bitrate'])
-            else:
-                args.append('-b '+self.bitrate_default)
-            #Copyrights, etc..
-            args.append('-c -o')
-        else:
-            args.append('-S -c --tt "unknown" -o')
-
-        for tag in self.metadata:
-            name = tag[0]
-            value = clean_word(tag[1])
-            if name in self.dub2args_dict.keys():
-                arg = self.dub2args_dict[name]
-                args.append('--' + arg + ' "' + value + '"')
-        return args
-
-    def process(self, source, metadata, options=None):
-        self.metadata = metadata
-        self.options = options
-        args = self.get_args()
-        args = ' '.join(args)
-        command = 'lame %s - -' % args
-
-        stream = self.core_process(command, source)
-        for __chunk in stream:
-            yield __chunk
-
diff --git a/encoder/ogg.py b/encoder/ogg.py
deleted file mode 100644 (file)
index 566c529..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-import os
-import string
-import subprocess
-
-from timeside.encoder.core import *
-from timeside.api import IEncoder
-
-class OggVorbisEncoder(EncoderCore):
-    """Defines methods to encode to OGG Vorbis"""
-
-    implements(IEncoder)
-
-    def __init__(self):
-        self.bitrate_default = '192'
-        self.dub2args_dict = {'creator': 'artist',
-                             'relation': 'album'
-                             }
-
-    @staticmethod
-    def id():
-        return "oggenc"
-
-    def format(self):
-        return 'OggVorbis'
-
-    def file_extension(self):
-        return 'ogg'
-
-    def mime_type(self):
-        return 'application/ogg'
-
-    def description(self):
-        return """
-        Vorbis is a free software / open source project headed by the Xiph.Org
-        Foundation (formerly Xiphophorus company). The project produces an audio
-        format specification and software implementation (codec) for lossy audio
-        compression. Vorbis is most commonly used in conjunction with the Ogg
-        container format and it is therefore often referred to as Ogg Vorbis.
-        (source Wikipedia)
-        """
-
-    def get_file_info(self, file):
-        try:
-            file_out1, file_out2 = os.popen4('ogginfo "' + file + '"')
-            info = []
-            for line in file_out2.readlines():
-                info.append(clean_word(line[:-1]))
-            self.info = info
-            return self.info
-        except:
-            raise IOError('EncoderError: file does not exist.')
-
-    def write_tags(self, file):
-        from mutagen.oggvorbis import OggVorbis
-        media = OggVorbis(file)
-        for tag in self.metadata.keys():
-            media[tag] = str(self.metadata[tag])
-        media.save()
-
-    def get_args(self):
-        """Get process options and return arguments for the encoder"""
-        args = []
-        if not self.options is None:
-            if not ('verbose' in self.options and self.options['verbose'] != '0'):
-                args.append('-Q ')
-            if 'ogg_bitrate' in self.options:
-                args.append('-b '+self.options['ogg_bitrate'])
-            elif 'ogg_quality' in self.options:
-                args.append('-q '+self.options['ogg_quality'])
-            else:
-                args.append('-b '+self.bitrate_default)
-        else:
-            args.append('-Q -b '+self.bitrate_default)
-
-        for tag in self.metadata:
-            name = tag[0]
-            value = clean_word(tag[1])
-            args.append('-c %s="%s"' % (name, value))
-            if name in self.dub2args_dict.keys():
-                arg = self.dub2args_dict[name]
-                args.append('-c %s="%s"' % (arg, value))
-        return args
-
-    def process(self, source, metadata, options=None):
-        self.metadata = metadata
-        self.options = options
-        args = self.get_args()
-        args = ' '.join(args)
-        command = 'oggenc %s -' % args
-
-        stream = self.core_process(command, source)
-        for __chunk in stream:
-            yield __chunk
-
-
diff --git a/encoder/wav.py b/encoder/wav.py
deleted file mode 100644 (file)
index d790aaa..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007-2009 Parisson
-# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
-# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Paul Brossier <piem@piem.org>
-
-from timeside.core import Processor, implements, interfacedoc
-from timeside.api import IEncoder
-from numpy import array, frombuffer, getbuffer, float32
-
-import pygst
-pygst.require('0.10')
-import gst
-import gobject
-gobject.threads_init ()
-
-
-class WavEncoder(Processor):
-    """ gstreamer-based encoder """
-    implements(IEncoder)
-
-    def __init__(self, output):
-        self.file = None
-        if isinstance(output, basestring):
-            self.filename = output
-        else:
-            raise Exception("Streaming not supported")
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(WavEncoder, self).setup(channels, samplerate, nframes)
-        # TODO open file for writing
-        # the output data format we want
-        pipeline = gst.parse_launch(''' appsrc name=src
-            ! audioconvert
-            ! wavenc
-            ! filesink location=%s ''' % self.filename)
-        # store a pointer to appsink in our encoder object 
-        self.src = pipeline.get_by_name('src')
-        srccaps = gst.Caps("""audio/x-raw-float,
-            endianness=(int)1234,
-            channels=(int)%s,
-            width=(int)32,
-            rate=(int)%d""" % (int(channels), int(samplerate)))
-        self.src.set_property("caps", srccaps)
-
-        # start pipeline
-        pipeline.set_state(gst.STATE_PLAYING)
-        self.pipeline = pipeline
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "gstreamerenc"
-
-    @staticmethod
-    @interfacedoc
-    def description():
-        return "Gstreamer based encoder"
-
-    @staticmethod
-    @interfacedoc
-    def file_extension():
-        return "wav"
-
-    @staticmethod
-    @interfacedoc
-    def mime_type():
-        return "audio/x-wav"
-
-    @interfacedoc
-    def set_metadata(self, metadata):
-        #TODO
-        pass
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        buf = self.numpy_array_to_gst_buffer(frames)
-        self.src.emit('push-buffer', buf)
-        if eod: self.src.emit('end-of-stream')
-        return frames, eod
-
-    def numpy_array_to_gst_buffer(self, frames):
-        """ gstreamer buffer to numpy array conversion """
-        buf = gst.Buffer(getbuffer(frames))
-        return buf
diff --git a/exceptions.py b/exceptions.py
deleted file mode 100644 (file)
index 40b4dcd..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-class Error(Exception):
-    """Exception base class for errors in TimeSide."""
-
-class ApiError(Exception):
-    """Exception base class for errors in TimeSide."""
-
-class SubProcessError(Error):
-    """Exception for reporting errors from a subprocess"""
-
-    def __init__(self, message, command, subprocess):
-        self.message = message
-        self.command = str(command)
-        self.subprocess = subprocess
-
-    def __str__(self):
-        if self.subprocess.stderr != None:
-            error = self.subprocess.stderr.read()
-        else:
-            error = ''
-        return "%s ; command: %s; error: %s" % (self.message,
-                                                self.command,
-                                                error)
diff --git a/grapher/__init__.py b/grapher/__init__.py
deleted file mode 100644 (file)
index 616ebf6..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from timeside.grapher.core import *
-from timeside.grapher.waveform import *
-from timeside.grapher.spectrogram import *
diff --git a/grapher/core.py b/grapher/core.py
deleted file mode 100644 (file)
index 36bc0bd..0000000
+++ /dev/null
@@ -1,362 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-# wav2png.py -- converts wave files to wave file and spectrogram images
-# Copyright (C) 2008 MUSIC TECHNOLOGY GROUP (MTG)
-#                    UNIVERSITAT POMPEU FABRA
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero 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 Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-#
-# Authors:
-#   Bram de Jong <bram.dejong at domain.com where domain in gmail>
-#   Guillaume Pellerin <yomguy@parisson.com>
-
-
-import optparse, math, sys
-import ImageFilter, ImageChops, Image, ImageDraw, ImageColor
-import numpy
-from timeside.core import FixedSizeInputAdapter
-
-
-color_schemes = {
-    'default': {
-        'waveform': [(50,0,200), (0,220,80), (255,224,0), (255,0,0)],
-        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
-                      (224,224,44), (255,60,30), (255,255,255)]
-    },
-    'iso': {
-        'waveform': [(0,0,255), (0,255,255), (255,255,0), (255,0,0)],
-        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
-                      (224,224,44), (255,60,30), (255,255,255)]
-    },
-    'purple': {
-        'waveform': [(173,173,173), (147,149,196), (77,80,138), (108,66,0)],
-        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
-                      (224,224,44), (255,60,30), (255,255,255)]
-    }
-}
-
-
-class Spectrum(object):
-    """ FFT based frequency analysis of audio frames."""
-
-    def __init__(self, fft_size, nframes, samplerate, lower, higher, window_function=numpy.ones):
-        self.fft_size = fft_size
-        self.window = window_function(self.fft_size)
-        self.spectrum_range = None
-        self.lower = lower
-        self.higher = higher
-        self.lower_log = math.log10(self.lower)
-        self.higher_log = math.log10(self.higher)
-        self.clip = lambda val, low, high: min(high, max(low, val))
-        self.nframes = nframes
-        self.samplerate = samplerate
-        self.spectrum_adapter = FixedSizeInputAdapter(self.fft_size, 1, pad=True)
-
-    def process(self, frames, eod, spec_range=120.0):
-        """ Returns a tuple containing the spectral centroid and the spectrum (dB scales) of the input audio frames.
-            An adapter is used to fix the buffer length and then provide fixed FFT window sizes."""
-
-        for buffer, end in self.spectrum_adapter.process(frames, eod):
-            samples = buffer[:,0].copy()
-            if end:
-                break
-
-        #samples = numpy.concatenate((numpy.zeros(self.fft_size/2), samples), axis=1)
-        samples *= self.window
-        fft = numpy.fft.fft(samples)
-        spectrum = numpy.abs(fft[:fft.shape[0] / 2 + 1]) / float(self.fft_size) # normalized abs(FFT) between 0 and 1
-        length = numpy.float64(spectrum.shape[0])
-
-        # scale the db spectrum from [- spec_range db ... 0 db] > [0..1]
-        db_spectrum = ((20*(numpy.log10(spectrum + 1e-30))).clip(-spec_range, 0.0) + spec_range)/spec_range
-        energy = spectrum.sum()
-        spectral_centroid = 0
-
-        if energy > 1e-20:
-            # calculate the spectral centroid
-            if self.spectrum_range == None:
-                self.spectrum_range = numpy.arange(length)
-
-            spectral_centroid = (spectrum * self.spectrum_range).sum() / (energy * (length - 1)) * self.samplerate * 0.5
-            # clip > log10 > scale between 0 and 1
-            spectral_centroid = (math.log10(self.clip(spectral_centroid, self.lower, self.higher)) - self.lower_log) / (self.higher_log - self.lower_log)
-
-        return (spectral_centroid, db_spectrum)
-
-
-def interpolate_colors(colors, flat=False, num_colors=256):
-    """ Given a list of colors, create a larger list of colors interpolating
-    the first one. If flatten is True a list of numers will be returned. If
-    False, a list of (r,g,b) tuples. num_colors is the number of colors wanted
-    in the final list """
-
-    palette = []
-
-    for i in range(num_colors):
-        index = (i * (len(colors) - 1))/(num_colors - 1.0)
-        index_int = int(index)
-        alpha = index - float(index_int)
-
-        if alpha > 0:
-            r = (1.0 - alpha) * colors[index_int][0] + alpha * colors[index_int + 1][0]
-            g = (1.0 - alpha) * colors[index_int][1] + alpha * colors[index_int + 1][1]
-            b = (1.0 - alpha) * colors[index_int][2] + alpha * colors[index_int + 1][2]
-        else:
-            r = (1.0 - alpha) * colors[index_int][0]
-            g = (1.0 - alpha) * colors[index_int][1]
-            b = (1.0 - alpha) * colors[index_int][2]
-
-        if flat:
-            palette.extend((int(r), int(g), int(b)))
-        else:
-            palette.append((int(r), int(g), int(b)))
-
-    return palette
-
-
-class WaveformImage(object):
-    """ Builds a PIL image representing a waveform of the audio stream.
-    Adds pixels iteratively thanks to the adapter providing fixed size frame buffers.
-    Peaks are colored relative to the spectral centroids of each frame packet. """
-
-    def __init__(self, image_width, image_height, nframes, samplerate, fft_size, bg_color=(0,0,0), color_scheme='default', filename=None):
-        self.image_width = image_width
-        self.image_height = image_height
-        self.nframes = nframes
-        self.samplerate = samplerate
-        self.fft_size = fft_size
-        self.filename = filename
-
-        self.bg_color = bg_color
-        self.color_scheme = color_scheme
-
-        if isinstance(color_scheme, dict):
-            colors = color_scheme['waveform']
-        else:
-            colors = color_schemes[self.color_scheme]['waveform']
-
-        self.color_lookup = interpolate_colors(colors)
-
-        self.samples_per_pixel = self.nframes / float(self.image_width)
-        self.buffer_size = int(round(self.samples_per_pixel, 0))
-        self.pixels_adapter = FixedSizeInputAdapter(self.buffer_size, 1, pad=False)
-        self.pixels_adapter_nframes = self.pixels_adapter.nframes(self.nframes)
-
-        self.lower = 800
-        self.higher = 12000
-        self.spectrum = Spectrum(self.fft_size, self.nframes, self.samplerate, self.lower, self.higher, numpy.hanning)
-
-        self.image = Image.new("RGB", (self.image_width, self.image_height), self.bg_color)
-        self.pixel = self.image.load()
-        self.draw = ImageDraw.Draw(self.image)
-        self.previous_x, self.previous_y = None, None
-        self.frame_cursor = 0
-        self.pixel_cursor = 0
-
-    def peaks(self, samples):
-        """ Find the minimum and maximum peak of the samples.
-        Returns that pair in the order they were found.
-        So if min was found first, it returns (min, max) else the other way around. """
-
-        max_index = numpy.argmax(samples)
-        max_value = samples[max_index]
-
-        min_index = numpy.argmin(samples)
-        min_value = samples[min_index]
-
-        if min_index < max_index:
-            return (min_value, max_value)
-        else:
-            return (max_value, min_value)
-
-    def color_from_value(self, value):
-        """ given a value between 0 and 1, return an (r,g,b) tuple """
-
-        return ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (int( (1.0 - value) * 360 ), 80, 50))
-
-    def draw_peaks(self, x, peaks, spectral_centroid):
-        """ draw 2 peaks at x using the spectral_centroid for color """
-
-        y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
-        y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
-
-        line_color = self.color_lookup[int(spectral_centroid*255.0)]
-
-        if self.previous_y != None:
-            self.draw.line([self.previous_x, self.previous_y, x, y1, x, y2], line_color)
-        else:
-            self.draw.line([x, y1, x, y2], line_color)
-
-        self.previous_x, self.previous_y = x, y2
-
-        self.draw_anti_aliased_pixels(x, y1, y2, line_color)
-
-    def draw_anti_aliased_pixels(self, x, y1, y2, color):
-        """ vertical anti-aliasing at y1 and y2 """
-
-        y_max = max(y1, y2)
-        y_max_int = int(y_max)
-        alpha = y_max - y_max_int
-
-        if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
-            current_pix = self.pixel[x, y_max_int + 1]
-
-            r = int((1-alpha)*current_pix[0] + alpha*color[0])
-            g = int((1-alpha)*current_pix[1] + alpha*color[1])
-            b = int((1-alpha)*current_pix[2] + alpha*color[2])
-
-            self.pixel[x, y_max_int + 1] = (r,g,b)
-
-        y_min = min(y1, y2)
-        y_min_int = int(y_min)
-        alpha = 1.0 - (y_min - y_min_int)
-
-        if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0:
-            current_pix = self.pixel[x, y_min_int - 1]
-
-            r = int((1-alpha)*current_pix[0] + alpha*color[0])
-            g = int((1-alpha)*current_pix[1] + alpha*color[1])
-            b = int((1-alpha)*current_pix[2] + alpha*color[2])
-
-            self.pixel[x, y_min_int - 1] = (r,g,b)
-
-    def process(self, frames, eod):
-        if len(frames) != 1:
-            buffer = frames[:,0].copy()
-            buffer.shape = (len(buffer),1)
-            (spectral_centroid, db_spectrum) = self.spectrum.process(buffer, True)
-            for samples, end in self.pixels_adapter.process(buffer, eod):
-                if self.pixel_cursor < self.image_width:
-                    peaks = self.peaks(samples)
-                    self.draw_peaks(self.pixel_cursor, peaks, spectral_centroid)
-                    self.pixel_cursor += 1
-
-    def save(self):
-        """ Apply last 2D transforms and write all pixels to the file. """
-
-        # middle line (0 for none)
-        a = 1
-
-        for x in range(self.image_width):
-            self.pixel[x, self.image_height/2] = tuple(map(lambda p: p+a, self.pixel[x, self.image_height/2]))
-        self.image.save(self.filename)
-
-
-class SpectrogramImage(object):
-    """ Builds a PIL image representing a spectrogram of the audio stream (level vs. frequency vs. time).
-    Adds pixels iteratively thanks to the adapter providing fixed size frame buffers."""
-
-    def __init__(self, image_width, image_height, nframes, samplerate, fft_size, bg_color=None, color_scheme='default', filename=None):
-        self.image_width = image_width
-        self.image_height = image_height
-        self.nframes = nframes
-        self.samplerate = samplerate
-        self.fft_size = fft_size
-        self.filename = filename
-        self.color_scheme = color_scheme
-
-        self.image = Image.new("P", (self.image_height, self.image_width))
-        colors = color_schemes[self.color_scheme]['spectrogram']
-        self.image.putpalette(interpolate_colors(colors, True))
-
-        self.samples_per_pixel = self.nframes / float(self.image_width)
-        self.buffer_size = int(round(self.samples_per_pixel, 0))
-        self.pixels_adapter = FixedSizeInputAdapter(self.buffer_size, 1, pad=False)
-        self.pixels_adapter_nframes = self.pixels_adapter.nframes(self.nframes)
-
-        self.lower = 100
-        self.higher = 22050
-        self.spectrum = Spectrum(self.fft_size, self.nframes, self.samplerate, self.lower, self.higher, numpy.hanning)
-
-        # generate the lookup which translates y-coordinate to fft-bin
-        self.y_to_bin = []
-        f_min = float(self.lower)
-        f_max = float(self.higher)
-        y_min = math.log10(f_min)
-        y_max = math.log10(f_max)
-        for y in range(self.image_height):
-            freq = math.pow(10.0, y_min + y / (image_height - 1.0) *(y_max - y_min))
-            bin = freq / 22050.0 * (self.fft_size/2 + 1)
-
-            if bin < self.fft_size/2:
-                alpha = bin - int(bin)
-
-                self.y_to_bin.append((int(bin), alpha * 255))
-
-        # this is a bit strange, but using image.load()[x,y] = ... is
-        # a lot slower than using image.putadata and then rotating the image
-        # so we store all the pixels in an array and then create the image when saving
-        self.pixels = []
-        self.pixel_cursor = 0
-
-    def draw_spectrum(self, x, spectrum):
-        for (index, alpha) in self.y_to_bin:
-            self.pixels.append( int( ((255.0-alpha) * spectrum[index] + alpha * spectrum[index + 1] )) )
-
-        for y in range(len(self.y_to_bin), self.image_height):
-            self.pixels.append(0)
-
-    def process(self, frames, eod):
-        if len(frames) != 1:
-            buffer = frames[:,0].copy()
-            buffer.shape = (len(buffer),1)
-
-            # FIXME : breaks spectrum linearity
-            for samples, end in self.pixels_adapter.process(buffer, eod):
-                if self.pixel_cursor < self.image_width:
-                    (spectral_centroid, db_spectrum) = self.spectrum.process(samples, True)
-                    self.draw_spectrum(self.pixel_cursor, db_spectrum)
-                    self.pixel_cursor += 1
-
-    def save(self):
-        """ Apply last 2D transforms and write all pixels to the file. """
-        self.image.putdata(self.pixels)
-        self.image.transpose(Image.ROTATE_90).save(self.filename)
-
-
-class Noise(object):
-    """A class that mimics audiolab.sndfile but generates noise instead of reading
-    a wave file. Additionally it can be told to have a "broken" header and thus crashing
-    in the middle of the file. Also useful for testing ultra-short files of 20 samples."""
-
-    def __init__(self, num_frames, has_broken_header=False):
-        self.seekpoint = 0
-        self.num_frames = num_frames
-        self.has_broken_header = has_broken_header
-
-    def seek(self, seekpoint):
-        self.seekpoint = seekpoint
-
-    def get_nframes(self):
-        return self.num_frames
-
-    def get_samplerate(self):
-        return 44100
-
-    def get_channels(self):
-        return 1
-
-    def read_frames(self, frames_to_read):
-        if self.has_broken_header and self.seekpoint + frames_to_read > self.num_frames / 2:
-            raise IOError()
-
-        num_frames_left = self.num_frames - self.seekpoint
-        if num_frames_left < frames_to_read:
-            will_read = num_frames_left
-        else:
-            will_read = frames_to_read
-        self.seekpoint += will_read
-        return numpy.random.random(will_read)*2 - 1
-
diff --git a/grapher/spectrogram.py b/grapher/spectrogram.py
deleted file mode 100644 (file)
index 0962842..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2010 Guillaume Pellerin <yomguy@parisson.com>
-# Copyright (c) 2010 Olivier Guilyardi <olivier@samalyse.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-
-from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
-from timeside.api import IGrapher
-from timeside.grapher import *
-
-
-class Spectrogram(Processor):
-    implements(IGrapher)
-
-    FFT_SIZE = 0x400
-
-    @interfacedoc
-    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
-        if width:
-            self.width = width
-        else:
-            self.width = 1500
-        if height:
-            self.height = height
-        else:
-            self.height = 200
-        self.bg_color = bg_color
-        self.color_scheme = color_scheme
-        self.filename = output
-        self.graph = None
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "spectrogram"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Spectrogram"
-
-    @interfacedoc
-    def set_colors(self, background, scheme):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(Spectrogram, self).setup(channels, samplerate, nframes)
-        if self.graph:
-            self.graph = None
-        self.graph = SpectrogramImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
-                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        self.graph.process(frames, eod)
-        return frames, eod
-
-    @interfacedoc
-    def render(self):
-        if self.filename:
-            self.graph.save()
-        return self.graph.image
-
diff --git a/grapher/spectrogram_audiolab.py b/grapher/spectrogram_audiolab.py
deleted file mode 100644 (file)
index be7143c..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import *
-from timeside.api import IGrapher
-from tempfile import NamedTemporaryFile
-from timeside.grapher.core import *
-
-class SpectrogramGrapherAudiolab(Processor):
-    """Spectrogram graph driver (python style thanks to wav2png.py and scikits.audiolab)"""
-
-    implements(IGrapher)
-
-    bg_color = None
-    color_scheme = None
-
-    @staticmethod
-    def id():
-        return "spectrogram"
-
-    def name(self):
-        return "Spectrogram (audiolab)"
-
-    def set_colors(self, background=None, scheme=None):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    def render(self, media_item, width=None, height=None, options=None):
-        """Generator that streams the spectrogram as a PNG image with a python method"""
-
-        wav_file = media_item
-        pngFile = NamedTemporaryFile(suffix='.png')
-
-        if not width == None:
-            image_width = width
-        else:
-            image_width = 1500
-        if not height == None:
-            image_height = height
-        else:
-            image_height = 200
-
-        fft_size = 2048
-        args = (wav_file, pngFile.name, image_width, image_height, fft_size,
-                self.bg_color, self.color_scheme)
-        create_spectrogram_png(*args)
-
-        buffer = pngFile.read(0xFFFF)
-        while buffer:
-            yield buffer
-            buffer = pngFile.read(0xFFFF)
-
-        pngFile.close()
diff --git a/grapher/waveform.py b/grapher/waveform.py
deleted file mode 100644 (file)
index 982192c..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2010 Guillaume Pellerin <yomguy@parisson.com>
-# Copyright (c) 2010 Olivier Guilyardi <olivier@samalyse.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-
-from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
-from timeside.api import IGrapher
-from timeside.grapher import *
-
-
-class Waveform(Processor):
-    implements(IGrapher)
-
-    FFT_SIZE = 0x400
-
-    @interfacedoc
-    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
-        if width:
-            self.width = width
-        else:
-            self.width = 1500
-        if height:
-            self.height = height
-        else:
-            self.height = 200
-        self.bg_color = bg_color
-        self.color_scheme = color_scheme
-        self.filename = output
-        self.graph = None
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "waveform"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Waveform"
-
-    @interfacedoc
-    def set_colors(self, background, scheme):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(Waveform, self).setup(channels, samplerate, nframes)
-        if self.graph:
-            self.graph = None
-        self.graph = WaveformImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
-                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        self.graph.process(frames, eod)
-        return frames, eod
-
-    @interfacedoc
-    def render(self):
-        if self.filename:
-            self.graph.save()
-        return self.graph.image
diff --git a/grapher/waveform_audiolab.py b/grapher/waveform_audiolab.py
deleted file mode 100644 (file)
index ac07330..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-from timeside.core import *
-from timeside.api import IGrapher
-from tempfile import NamedTemporaryFile
-from timeside.grapher.core import *
-
-class WaveFormGrapherAudiolab(Processor):
-    """WaveForm graph driver (python style thanks to wav2png.py and scikits.audiolab)"""
-
-    implements(IGrapher)
-
-    bg_color = None
-    color_scheme = None
-
-    @staticmethod
-    def id():
-        return "waveform"
-
-    def name(self):
-        return "Waveform (audiolab)"
-
-    def set_colors(self, background=None, scheme=None):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    def render(self, media_item, width=None, height=None, options=None):
-        """Generator that streams the waveform as a PNG image with a python method"""
-
-        wav_file = media_item
-        pngFile = NamedTemporaryFile(suffix='.png')
-
-        if not width == None:
-            image_width = width
-        else:
-            image_width = 1500
-        if not height == None:
-            image_height = height
-        else:
-            image_height = 200
-
-        fft_size = 2048
-        args = (wav_file, pngFile.name, image_width, image_height, fft_size,
-                self.bg_color, self.color_scheme)
-        create_wavform_png(*args)
-
-        buffer = pngFile.read(0xFFFF)
-        while buffer:
-            yield buffer
-            buffer = pngFile.read(0xFFFF)
-
-        pngFile.close()
-
diff --git a/metadata.py b/metadata.py
deleted file mode 100644 (file)
index 86abf87..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007-2009 Parisson
-# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
-# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-class Metadata(object):
-    pass
-        
-        
diff --git a/setup.py b/setup.py
new file mode 100644 (file)
index 0000000..a4936d5
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+
+'''The setup and build script for the python-twitter library.'''
+
+__author__ = 'yomguy@parisson.com'
+__version__ = '0.1-beta'
+
+
+# The base package metadata to be used by both distutils and setuptools
+METADATA = dict(
+  name = "timeside",
+  version = __version__,
+  py_modules = ['timeside'],
+  description='Web Audio Components',
+  author='Olivier Guilyardi, Paul Brossier, Guillaume Pellerin',
+  author_email='yomguy@parisson.com',
+  license='Gnu Public License V2',
+  url='http://code.google.com/p/timeside',
+  packages=['timeside'],
+  keywords='audio analyze transcode graph',
+  install_requires = ['setuptools',]
+  include_package_data = True,
+)
+
+
+def Main():
+  # Use setuptools if available, otherwise fallback and use distutils
+  try:
+    import setuptools
+    setuptools.setup(**METADATA)
+  except ImportError:
+    import distutils.core
+    distutils.core.setup(**METADATA)
+
+
+if __name__ == '__main__':
+  Main()
diff --git a/tests/__init__.py b/tests/__init__.py
deleted file mode 100644 (file)
index 2a6b9db..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-
-import unittest
-import sys
-import time
-
-class TestCase(unittest.TestCase):
-
-    def assertSameList(self, list1, list2):
-        "Test that two lists contain the same elements, in any order"
-        if len(list1) != len(list2):
-            self.fail("Lists length differ : %d != %d" % (len(list1), len(list2)))
-
-        for item in list1:
-            if not item in list2:
-                self.fail("%s is not in list2" % str(item))
-
-        for item in list2:
-            if not item in list1:
-                self.fail("%s is not in list1" % str(item))
-        
-class _TextTestResult(unittest.TestResult):
-    """A test result class that can print formatted text results to a stream.
-
-    Used by TextTestRunner.
-    """
-    separator1 = '=' * 70
-    separator2 = '-' * 70
-
-    def __init__(self, stream, descriptions, verbosity):
-        unittest.TestResult.__init__(self)
-        self.stream = stream
-        self.showAll = verbosity > 1
-        self.dots = verbosity == 1
-        self.descriptions = descriptions
-        self.currentTestCase = None
-
-    def getDescription(self, test):
-        if self.descriptions:
-            return test.shortDescription() or str(test)
-        else:
-            return str(test)
-
-    def startTest(self, test):
-        unittest.TestResult.startTest(self, test)
-        if self.showAll:
-            if self.currentTestCase != test.__class__:
-                self.currentTestCase = test.__class__
-                self.stream.writeln()
-                self.stream.writeln("[%s]" % self.currentTestCase.__name__)
-            self.stream.write("  " + self.getDescription(test))
-            self.stream.write(" ... ")
-
-    def addSuccess(self, test):
-        unittest.TestResult.addSuccess(self, test)
-        if self.showAll:
-            self.stream.writeln("ok")
-        elif self.dots:
-            self.stream.write('.')
-
-    def addError(self, test, err):
-        unittest.TestResult.addError(self, test, err)
-        if self.showAll:
-            self.stream.writeln("ERROR")
-        elif self.dots:
-            self.stream.write('E')
-
-    def addFailure(self, test, err):
-        unittest.TestResult.addFailure(self, test, err)
-        if self.showAll:
-            self.stream.writeln("FAIL")
-        elif self.dots:
-            self.stream.write('F')
-
-    def printErrors(self):
-        if self.dots or self.showAll:
-            self.stream.writeln()
-        self.printErrorList('ERROR', self.errors)
-        self.printErrorList('FAIL', self.failures)
-
-    def printErrorList(self, flavour, errors):
-        for test, err in errors:
-            self.stream.writeln(self.separator1)
-            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
-            self.stream.writeln(self.separator2)
-            self.stream.writeln("%s" % err)
-
-
-class _WritelnDecorator:
-    """Used to decorate file-like objects with a handy 'writeln' method"""
-    def __init__(self,stream):
-        self.stream = stream
-
-    def __getattr__(self, attr):
-        return getattr(self.stream,attr)
-
-    def writeln(self, arg=None):
-        if arg: self.write(arg)
-        self.write('\n') # text-mode streams translate to \r\n if needed
-
-class TestRunner:
-    """A test runner class that displays results in textual form.
-
-    It prints out the names of tests as they are run, errors as they
-    occur, and a summary of the results at the end of the test run.
-    """
-    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=2):
-        self.stream = _WritelnDecorator(stream)
-        self.descriptions = descriptions
-        self.verbosity = verbosity
-
-    def _makeResult(self):
-        return _TextTestResult(self.stream, self.descriptions, self.verbosity)
-
-    def run(self, test):
-        "Run the given test case or test suite."
-        result = self._makeResult()
-        startTime = time.time()
-        test(result)
-        stopTime = time.time()
-        timeTaken = stopTime - startTime
-        result.printErrors()
-        self.stream.writeln(result.separator2)
-        run = result.testsRun
-        self.stream.writeln("Ran %d test%s in %.3fs" %
-                            (run, run != 1 and "s" or "", timeTaken))
-        self.stream.writeln()
-        if not result.wasSuccessful():
-            self.stream.write("FAILED (")
-            failed, errored = map(len, (result.failures, result.errors))
-            if failed:
-                self.stream.write("failures=%d" % failed)
-            if errored:
-                if failed: self.stream.write(", ")
-                self.stream.write("errors=%d" % errored)
-            self.stream.writeln(")")
-        else:
-            self.stream.writeln("OK")
-        return result
-
-
diff --git a/tests/alltests.py b/tests/alltests.py
deleted file mode 100644 (file)
index e368939..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-from timeside.tests.testcomponent import *
-from timeside.tests.testinputadapter import *
-from timeside.tests import TestRunner
-
-unittest.main(testRunner=TestRunner())
diff --git a/tests/api/__init__.py b/tests/api/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/tests/api/examples.py b/tests/api/examples.py
deleted file mode 100644 (file)
index 418d2ca..0000000
+++ /dev/null
@@ -1,379 +0,0 @@
-# -*- coding: utf-8 -*-
-from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
-from timeside.api import *
-from timeside.grapher import *
-from timeside import Metadata
-from scikits import audiolab
-import numpy
-
-class FileDecoder(Processor):
-    """A simple audiolab-based example decoder"""
-    implements(IDecoder)
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_audiolabdec"
-
-    @interfacedoc
-    def __init__(self, filename):
-        self.filename = filename
-        # The file has to be opened here so that nframes(), samplerate(),
-        # etc.. work before setup() is called.
-        self.file     = audiolab.Sndfile(self.filename, 'r')
-        self.position = 0
-
-    @interfacedoc
-    def setup(self):
-        super(FileDecoder, self).setup()
-        if self.position != 0:
-            self.file.seek(0);
-            self.position = 0
-
-    def release(self):
-        super(FileDecoder, self).release()
-        if self.file:
-            self.file.close()
-            self.file = None
-
-    @interfacedoc
-    def channels(self):
-        return self.file.channels
-
-    @interfacedoc
-    def samplerate(self):
-        return self.file.samplerate
-
-    @interfacedoc
-    def nframes(self):
-        return self.file.nframes
-
-    @interfacedoc
-    def format(self):
-        return self.file.file_format
-
-    @interfacedoc
-    def encoding(self):
-        return self.file.encoding
-    @interfacedoc
-    def resolution(self):
-        resolution = None
-        encoding = self.file.encoding
-
-        if encoding == "pcm8":
-            resolution = 8
-
-        elif encoding == "pcm16":
-            resolution = 16
-        elif encoding == "pcm32":
-            resolution = 32
-
-        return resolution
-
-    @interfacedoc
-    def metadata(self):
-        #TODO
-        return Metadata()
-
-    @interfacedoc
-    def process(self, frames=None, eod=False):
-        if frames:
-            raise Exception("Decoder doesn't accept input frames")
-
-        buffersize = 0x10000
-
-        # Need this because audiolab raises a bogus exception when asked
-        # to read passed the end of the file
-        toread = self.nframes() - self.position
-        if toread > buffersize:
-            toread = buffersize
-
-        frames         = self.file.read_frames(toread)
-        eod            = (toread < buffersize)
-        self.position += toread
-
-        # audiolab returns a 1D array for 1 channel, need to reshape to 2D:
-        if frames.ndim == 1:
-            frames = frames.reshape(len(frames), 1)
-
-        return frames, eod
-
-class MaxLevel(Processor):
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(MaxLevel, self).setup(channels, samplerate, nframes)
-        self.max_value = 0
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_maxlevel"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Max level test analyzer"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        # power? amplitude?
-        return ""
-
-    def process(self, frames, eod=False):
-        max = frames.max()
-        if max > self.max_value:
-            self.max_value = max
-
-        return frames, eod
-
-    def result(self):
-        return self.max_value
-
-class Gain(Processor):
-    implements(IEffect)
-
-    @interfacedoc
-    def __init__(self, gain=1.0):
-        self.gain = gain
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_gain"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Gain test effect"
-
-    def process(self, frames, eod=False):
-        return numpy.multiply(frames, self.gain), eod
-
-class WavEncoder(Processor):
-    implements(IEncoder)
-
-    def __init__(self, output):
-        self.file = None
-        if isinstance(output, basestring):
-            self.filename = output
-        else:
-            raise Exception("Streaming not supported")
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(WavEncoder, self).setup(channels, samplerate, nframes)
-        if self.file:
-            self.file.close()
-
-        format = audiolab.Format("wav", "pcm16")
-        self.file = audiolab.Sndfile(self.filename, 'w', format=format, channels=channels,
-                                     samplerate=samplerate)
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_wavenc"
-
-    @staticmethod
-    @interfacedoc
-    def description():
-        return "Hackish wave encoder"
-
-    @staticmethod
-    @interfacedoc
-    def file_extension():
-        return "wav"
-
-    @staticmethod
-    @interfacedoc
-    def mime_type():
-        return "audio/x-wav"
-
-    @interfacedoc
-    def set_metadata(self, metadata):
-        #TODO
-        pass
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        self.file.write_frames(frames)
-        if eod:
-            self.file.close()
-            self.file = None
-
-        return frames, eod
-
-
-class Waveform(Processor):
-    implements(IGrapher)
-
-    FFT_SIZE = 0x400
-
-    @interfacedoc
-    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
-        if width:
-            self.width = width
-        else:
-            self.width = 1500
-        if height:
-            self.height = height
-        else:
-            self.height = 200
-        self.bg_color = bg_color
-        self.color_scheme = color_scheme
-        self.filename = output
-        self.graph = None
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_waveform"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Waveform test"
-
-    @interfacedoc
-    def set_colors(self, background, scheme):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(Waveform, self).setup(channels, samplerate, nframes)
-        if self.graph:
-            self.graph = None
-        self.graph = WaveformImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
-                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        self.graph.process(frames, eod)
-        return frames, eod
-
-    @interfacedoc
-    def render(self):
-        if self.filename:
-            self.graph.save()
-        return self.graph.image
-
-
-class Spectrogram(Processor):
-    implements(IGrapher)
-
-    FFT_SIZE = 0x400
-
-    @interfacedoc
-    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
-        if width:
-            self.width = width
-        else:
-            self.width = 1500
-        if height:
-            self.height = height
-        else:
-            self.height = 200
-        self.bg_color = bg_color
-        self.color_scheme = color_scheme
-        self.filename = output
-        self.graph = None
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_spectrogram"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Spectrogram test"
-
-    @interfacedoc
-    def set_colors(self, background, scheme):
-        self.bg_color = background
-        self.color_scheme = scheme
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(Spectrogram, self).setup(channels, samplerate, nframes)
-        if self.graph:
-            self.graph = None
-        self.graph = SpectrogramImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
-                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        self.graph.process(frames, eod)
-        return frames, eod
-
-    @interfacedoc
-    def render(self):
-        if self.filename:
-            self.graph.save()
-        return self.graph.image
-
-
-class Duration(Processor):
-    """A rather useless duration analyzer. Its only purpose is to test the
-       nframes characteristic."""
-    implements(IValueAnalyzer)
-
-    @interfacedoc
-    def setup(self, channels, samplerate, nframes):
-        if not nframes:
-            raise Exception("nframes argument required")
-        super(Duration, self).setup(channels, samplerate, nframes)
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_duration"
-
-    @staticmethod
-    @interfacedoc
-    def name():
-        return "Duration analyzer"
-
-    @staticmethod
-    @interfacedoc
-    def unit():
-        return "seconds"
-
-    def result(self):
-        return self.input_nframes / float(self.input_samplerate)
-
-class FixedInputProcessor(Processor):
-    """Processor which does absolutely nothing except illustrating the use
-    of the FixedInputSizeAdapter. It also tests things a bit."""
-
-    implements(IProcessor)
-
-    BUFFER_SIZE = 1024
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_fixed"
-
-    @interfacedoc
-    def setup(self, channels, samplerate, nframes):
-        super(FixedInputProcessor, self).setup(channels, samplerate, nframes)
-        self.adapter = FixedSizeInputAdapter(self.BUFFER_SIZE, channels, pad=True)
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        for buffer, end in self.adapter.process(frames, eod):
-            # Test that the adapter is actually doing the job:
-            if len(buffer) != self.BUFFER_SIZE:
-                raise Exception("Bad buffer size from adapter")
-
-        return frames, eod
-
-
-
-
-
diff --git a/tests/api/gstreamer.py b/tests/api/gstreamer.py
deleted file mode 100644 (file)
index 897ac42..0000000
+++ /dev/null
@@ -1,238 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright (C) 2007-2009 Parisson
-# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
-# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
-#
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Paul Brossier <piem@piem.org>
-
-from timeside.core import Processor, implements, interfacedoc
-from timeside.api import IDecoder, IEncoder
-from numpy import array, frombuffer, getbuffer, float32
-
-import pygst
-pygst.require('0.10')
-import gst
-import gobject
-gobject.threads_init ()
-
-class FileDecoder(Processor):
-    """ gstreamer-based decoder """
-    implements(IDecoder)
-
-    # duration ms, before discovery process times out
-    MAX_DISCOVERY_TIME = 3000
-
-    audioformat = None
-    audiochannels = None
-    audiorate = None
-    audionframes = None
-    mimetype = ''
-
-    # IProcessor methods
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_gstreamerdec"
-
-    def setup(self, channels = None, samplerate = None, nframes = None):
-        # the output data format we want
-        caps = "audio/x-raw-float, width=32"
-        pipeline = gst.parse_launch('''uridecodebin uri=%s
-            ! audioconvert
-            ! %s
-            ! appsink name=sink sync=False ''' % (self.uri, caps))
-        # store a pointer to appsink in our decoder object 
-        self.sink = pipeline.get_by_name('sink')
-        # adjust length of emitted buffers
-        # self.sink.set_property('blocksize', 0x10000)
-        # start pipeline
-        pipeline.set_state(gst.STATE_PLAYING)
-
-    @interfacedoc
-    def channels(self):
-        return  self.audiochannels
-
-    @interfacedoc
-    def samplerate(self):
-        return self.audiorate 
-
-    @interfacedoc
-    def nframes(self):
-        return self.audionframes
-
-    @interfacedoc
-    def process(self, frames = None, eod = False):
-        try:
-            buf = self.sink.emit('pull-buffer')
-        except SystemError, e:
-            # should never happen
-            print 'SystemError', e
-            return array([0.]), True
-        if buf == None:
-            return array([0.]), True
-        return self.gst_buffer_to_numpy_array(buf), False
-
-    @interfacedoc
-    def release(self):
-        # nothing to do for now 
-        pass
-
-    ## IDecoder methods
-
-    @interfacedoc
-    def __init__(self, uri):
-
-        # is this a file? 
-        import os.path
-        if os.path.exists(uri):
-            # get the absolute path
-            uri = os.path.abspath(uri)
-            # first run the file/uri through the discover pipeline
-            self.discover(uri)
-            # and make a uri of it
-            from urllib import quote
-            self.uri = 'file://'+quote(uri)
-
-    @interfacedoc
-    def format(self):
-        # TODO check
-        return self.mimetype
-
-    @interfacedoc
-    def encoding(self):
-        # TODO check
-        return self.mimetype.split('/')[-1]
-
-    @interfacedoc
-    def resolution(self):
-        # TODO check: width or depth?
-        return self.audiowidth 
-
-    @interfacedoc
-    def metadata(self):
-        # TODO check
-        return self.tags
-
-    ## gst.extend discoverer
-
-    def discover(self, path):
-        """ gstreamer based helper function to get file attributes """
-        from gst.extend import discoverer
-        d = discoverer.Discoverer(path, timeout = self.MAX_DISCOVERY_TIME)
-        d.connect('discovered', self.discovered)
-        self.mainloop = gobject.MainLoop()
-        d.discover()
-        self.mainloop.run()
-
-    def discovered(self, d, is_media):
-        """ gstreamer based helper executed upon discover() completion """
-        if is_media and d.is_audio:
-            # copy the discoverer attributes to self
-            self.audiorate = d.audiorate
-            self.mimetype= d.mimetype
-            self.audiochannels = d.audiochannels
-            self.audiowidth = d.audiowidth
-            # conversion from time in nanoseconds to frames 
-            from math import ceil
-            duration = d.audiorate * d.audiolength * 1.e-9
-            self.audionframes = int (ceil ( duration ) )
-            self.tags = d.tags
-        elif not d.is_audio:
-            print "error, no audio found!"
-        else:
-            print "fail", path
-        self.mainloop.quit()
-
-    def gst_buffer_to_numpy_array(self, buf):
-        """ gstreamer buffer to numpy array conversion """
-        chan = self.audiochannels
-        samples = frombuffer(buf.data, dtype=float32) 
-        samples.resize([len(samples)/chan, chan])
-        return samples
-
-class WavEncoder(Processor):
-    """ gstreamer-based encoder """
-    implements(IEncoder)
-
-    def __init__(self, output):
-        self.file = None
-        if isinstance(output, basestring):
-            self.filename = output
-        else:
-            raise Exception("Streaming not supported")
-
-    @interfacedoc
-    def setup(self, channels=None, samplerate=None, nframes=None):
-        super(WavEncoder, self).setup(channels, samplerate, nframes)
-        # TODO open file for writing
-        # the output data format we want
-        pipeline = gst.parse_launch(''' appsrc name=src
-            ! audioconvert
-            ! wavenc
-            ! filesink location=%s ''' % self.filename)
-        # store a pointer to appsink in our encoder object 
-        self.src = pipeline.get_by_name('src')
-        srccaps = gst.Caps("""audio/x-raw-float,
-            endianness=(int)1234,
-            channels=(int)%s,
-            width=(int)32,
-            rate=(int)%d""" % (int(channels), int(samplerate)))
-        self.src.set_property("caps", srccaps)
-
-        # start pipeline
-        pipeline.set_state(gst.STATE_PLAYING)
-        self.pipeline = pipeline
-
-    @staticmethod
-    @interfacedoc
-    def id():
-        return "test_gstreamerenc"
-
-    @staticmethod
-    @interfacedoc
-    def description():
-        return "Gstreamer based encoder"
-
-    @staticmethod
-    @interfacedoc
-    def file_extension():
-        return "wav"
-
-    @staticmethod
-    @interfacedoc
-    def mime_type():
-        return "audio/x-wav"
-
-    @interfacedoc
-    def set_metadata(self, metadata):
-        #TODO
-        pass
-
-    @interfacedoc
-    def process(self, frames, eod=False):
-        buf = self.numpy_array_to_gst_buffer(frames)
-        self.src.emit('push-buffer', buf)
-        if eod: self.src.emit('end-of-stream')
-        return frames, eod
-
-    def numpy_array_to_gst_buffer(self, frames):
-        """ gstreamer buffer to numpy array conversion """
-        buf = gst.Buffer(getbuffer(frames))
-        return buf
diff --git a/tests/api/test_lolevel.py b/tests/api/test_lolevel.py
deleted file mode 100644 (file)
index 786b141..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-from timeside.tests.api import examples
-
-use_gst = 0
-if use_gst:
-    from timeside.tests.api.gstreamer import FileDecoder, WavEncoder
-else:
-    from timeside.tests.api.examples import FileDecoder, WavEncoder
-
-import sys
-if len(sys.argv) > 1:
-    source = sys.argv[1]
-else:
-    import os.path
-    source= os.path.join (os.path.dirname(__file__),  "../samples/guitar.wav")
-
-Decoder = FileDecoder
-print "Creating decoder with id=%s for: %s" % (Decoder.id(), source)
-decoder    = Decoder(source)
-analyzer = examples.MaxLevel()
-decoder.setup()
-nchannels  = decoder.channels()
-samplerate = decoder.samplerate()
-nframes = decoder.nframes()
-analyzer.setup(nchannels, samplerate)
-
-print "Stats: duration=%f, nframes=%d, nchannels=%d, samplerate=%d, resolution=%d" % (
-        nframes / float(samplerate), nframes, nchannels, samplerate, decoder.resolution())
-
-while True:
-    frames, eod = decoder.process()
-    analyzer.process(frames, eod)
-    if eod:
-        break
-
-max_level = analyzer.result()
-print "Max level: %f" % max_level
-
-destination = "normalized.wav"
-Encoder = WavEncoder
-print "Creating encoder with id=%s for: %s" % (Encoder.id(), destination)
-encoder = Encoder(destination)
-
-gain = 1
-if max_level > 0:
-    gain = 0.9 / max_level
-
-effect = examples.Gain(gain)
-
-decoder.setup()
-effect.setup(decoder.channels(), decoder.samplerate())
-encoder.setup(effect.channels(), effect.samplerate())
-
-print "Applying effect id=%s with gain=%f" % (effect.id(), gain)
-
-while True:
-    frames, eod = decoder.process()
-    encoder.process(*effect.process(frames, eod))
-    if eod:
-        break
-
diff --git a/tests/api/test_pipe.py b/tests/api/test_pipe.py
deleted file mode 100644 (file)
index eaa0850..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- coding: utf-8 -*-
-from timeside.tests.api.examples import Gain
-from timeside.core import *
-from timeside.decoder import *
-from timeside.analyzer import *
-from timeside.encoder import *
-from timeside.api import *
-from sys import stdout
-
-import os.path
-source = os.path.join(os.path.dirname(__file__),  "../samples/guitar.wav")
-
-print "Normalizing %s" % source
-decoder  = FileDecoder(source)
-maxlevel = MaxLevel()
-duration = Duration()
-
-(decoder | maxlevel | duration).run()
-
-gain = 1
-if maxlevel.result() > 0:
-    gain = 0.9 / maxlevel.result()
-
-print "input maxlevel: %f" % maxlevel.result()
-print "gain: %f" % gain
-print "duration: %f %s" % (duration.result(), duration.unit())
-
-gain     = Gain(gain)
-encoder  = WavEncoder("normalized.wav")
-
-subpipe  = gain | maxlevel
-
-(decoder | subpipe | encoder).run()
-
-print "output maxlevel: %f" % maxlevel.result()
-
-
diff --git a/tests/api/test_pipe_spectrogram.py b/tests/api/test_pipe_spectrogram.py
deleted file mode 100644 (file)
index 5ba90eb..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-# -*- coding: utf-8 -*-
-
-import os
-from timeside.core import *
-from timeside.api import *
-from timeside.decoder import *
-from timeside.grapher import *
-
-image_file = '../results/img/spectrogram.png'
-source = os.path.join(os.path.dirname(__file__), "../samples/sweep.wav")
-
-decoder  = FileDecoder(source)
-spectrogram = Spectrogram(width=1024, height=256, output=image_file, bg_color=(0,0,0), color_scheme='default')
-
-(decoder | spectrogram).run()
-
-print 'frames per pixel = ', spectrogram.graph.samples_per_pixel
-print "render spectrogram to: %s" % image_file
-spectrogram.render()
-
-
diff --git a/tests/api/test_pipe_waveform.py b/tests/api/test_pipe_waveform.py
deleted file mode 100644 (file)
index d21ecdc..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-# -*- coding: utf-8 -*-
-
-import os
-from timeside.core import *
-from timeside.api import *
-from timeside.decoder import *
-from timeside.grapher import *
-
-sample_dir = '../samples'
-img_dir = '../results/img'
-if not os.path.exists(img_dir):
-    os.mkdir(img_dir)
-
-test_dict = {'sweep.wav': 'waveform_wav.png',
-            'sweep.flac': 'waveform_flac.png',
-            'sweep.ogg': 'waveform_ogg.png',
-            'sweep.mp3': 'waveform_mp3.png',
-            }
-
-for source, image in test_dict.iteritems():
-    audio = os.path.join(os.path.dirname(__file__), sample_dir + os.sep + source)
-    image = img_dir + os.sep + image
-    print 'Test : decoder(%s) | waveform (%s)' % (source, image)
-    decoder  = FileDecoder(audio)
-    waveform = Waveform(width=1024, height=256, output=image, bg_color=(0,0,0), color_scheme='default')
-    (decoder | waveform).run()
-    print 'frames per pixel = ', waveform.graph.samples_per_pixel
-    print "render waveform to: %s" %  image
-    waveform.render()
-
-
diff --git a/tests/listprocessors.py b/tests/listprocessors.py
deleted file mode 100644 (file)
index 840c087..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-import timeside
-
-def list_processors(interface, prefix=""):
-    print prefix + interface.__name__
-    subinterfaces = interface.__subclasses__()
-    for i in subinterfaces:
-        list_processors(i, prefix + "  ")
-    processors = timeside.processors(interface, False)
-    for p in processors:
-        print prefix + "  %s [%s]" % (p.__name__, p.id())
-
-list_processors(timeside.api.IProcessor)        
diff --git a/tests/samples/guitar.wav b/tests/samples/guitar.wav
deleted file mode 100644 (file)
index b5a9e80..0000000
Binary files a/tests/samples/guitar.wav and /dev/null differ
diff --git a/tests/samples/sweep.flac b/tests/samples/sweep.flac
deleted file mode 100644 (file)
index decee06..0000000
Binary files a/tests/samples/sweep.flac and /dev/null differ
diff --git a/tests/samples/sweep.mp3 b/tests/samples/sweep.mp3
deleted file mode 100644 (file)
index dc75fe0..0000000
Binary files a/tests/samples/sweep.mp3 and /dev/null differ
diff --git a/tests/samples/sweep.ogg b/tests/samples/sweep.ogg
deleted file mode 100644 (file)
index e30bf99..0000000
Binary files a/tests/samples/sweep.ogg and /dev/null differ
diff --git a/tests/samples/sweep.wav b/tests/samples/sweep.wav
deleted file mode 100644 (file)
index fc28a32..0000000
Binary files a/tests/samples/sweep.wav and /dev/null differ
diff --git a/tests/samples/sweep_source.wav b/tests/samples/sweep_source.wav
deleted file mode 100644 (file)
index 5dcf9ba..0000000
Binary files a/tests/samples/sweep_source.wav and /dev/null differ
diff --git a/tests/testcomponent.py b/tests/testcomponent.py
deleted file mode 100644 (file)
index 6638c30..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-
-from timeside.component import *
-from timeside.tests import TestCase, TestRunner
-import unittest
-
-__all__ = ['TestComponentArchitecture']
-
-class TestComponentArchitecture(TestCase):
-    "Test the component and interface system"
-   
-    def testOneInterface(self):
-        "Test a component implementing one interface"
-        self.assertSameList(implementations(I1), [C1])
-
-    def testTwoInterfaces(self):        
-        "Test a component implementing two interfaces"
-        self.assertSameList(implementations(I2), [C2])
-        self.assertSameList(implementations(I3), [C2])
-
-    def testTwoImplementations(self):
-        "Test an interface implemented by two components"
-        self.assertSameList(implementations(I4), [C3, C4])
-
-    def testInterfaceInheritance(self):
-        "Test whether a component implements an interface's parent"
-        self.assertSameList(implementations(I5), [C5])
-
-    def testImplementationInheritance(self):
-        "Test that a component doesn't implement the interface implemented by its parent" 
-        self.assertSameList(implementations(I7), [C6])
-
-    def testImplementationRedundancy(self):
-        "Test implementation redundancy across inheritance" 
-        self.assertSameList(implementations(I8), [C8, C9])
-
-    def testAbstractImplementation(self):    
-        "Test abstract implementation"
-        self.assertSameList(implementations(I11), [])
-        self.assertSameList(implementations(I11, abstract=True), [C11])
-
-    def testInterfaceDoc(self):        
-        "Test @interfacedoc decorator"
-        self.assertEquals(C10.test.__doc__, "testdoc")
-
-    def testInterfaceDocStatic(self):        
-        "Test @interfacedoc decorator on static method"
-        self.assertEquals(C10.teststatic.__doc__, "teststaticdoc")
-
-    def testIntefaceDocReversed(self):
-        "Test @interfacedoc on static method (decorators reversed)"
-
-        try:
-
-            class BogusDoc1(Component):
-                implements(I10)
-
-                @interfacedoc
-                @staticmethod        
-                def teststatic(self):
-                    pass
-
-            self.fail("No error raised with reversed decorators")
-
-        except ComponentError:
-            pass
-   
-    def testInterfaceDocBadMethod(self):
-        "Test @interfacedoc with unexistant method in interface"
-
-        try:
-            class BogusDoc2(Component):
-                implements(I10)
-
-                @interfacedoc
-                def nosuchmethod(self):
-                    pass
-
-            self.fail("No error raised when decorating an unexistant method")
-
-        except ComponentError:
-            pass
-
-class I1(Interface):
-    pass
-
-class I2(Interface):
-    pass
-
-class I3(Interface):
-    pass
-
-class I4(Interface):
-    pass
-
-class I5(Interface):
-    pass
-
-class I6(I5):
-    pass
-
-class I7(Interface):
-    pass
-
-class I8(Interface):
-    pass
-
-class I9(I8):
-    pass
-
-class I10(Interface):
-    def test(self):
-        """testdoc"""
-
-    @staticmethod        
-    def teststatic(self):
-        """teststaticdoc"""
-
-class I11(Interface):
-    pass
-
-class C1(Component):
-    implements(I1)
-
-class C2(Component):
-    implements(I2, I3)
-
-class C3(Component):
-    implements(I4)
-
-class C4(Component):
-    implements(I4)
-
-class C5(Component):
-    implements(I6)
-
-class C6(Component):
-    implements(I7)
-
-class C7(C6):
-    pass
-
-class C8(Component):
-    implements(I8)
-
-class C9(Component):
-    implements(I8, I9)
-
-class C10(Component):
-    implements(I10)
-
-    @interfacedoc
-    def test(self):
-        pass
-
-    @staticmethod        
-    @interfacedoc
-    def teststatic(self):
-        pass
-
-class C11(Component):
-    abstract()
-    implements(I11)
-
-if __name__ == '__main__':
-    unittest.main(testRunner=TestRunner())
-
diff --git a/tests/testinputadapter.py b/tests/testinputadapter.py
deleted file mode 100644 (file)
index dca0f63..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-from timeside.core import FixedSizeInputAdapter
-from timeside.tests import TestCase, TestRunner
-import numpy
-import unittest
-
-class TestFixedSizeInputAdapter(TestCase):
-    "Test the fixed-sized input adapter"
-
-    def assertIOEquals(self, adapter, input, input_eod, output, output_eod=None):
-        output = output[:]
-        output.reverse()
-        _eod = None
-        for buffer, _eod in adapter.process(input, input_eod):
-            a = output.pop()
-            if not numpy.array_equiv(buffer, a):
-                self.fail("\n-- Actual --\n%s\n -- Expected -- \n%s\n" % (str(buffer), str(a)))
-
-        if _eod != output_eod:
-            self.fail("eod do not match: %s != %s", (str(_eod), str(output_eod)))
-
-        if output:
-            self.fail("trailing expected data: %s" % output)
-
-    def setUp(self):
-        self.data = numpy.arange(44).reshape(2,22).transpose()
-
-    def testTwoChannels(self):
-        "Test simple stream with two channels"
-        adapter = FixedSizeInputAdapter(4, 2)
-
-        self.assertEquals(len(self.data), adapter.nframes(len(self.data)))
-
-        self.assertIOEquals(adapter, self.data[0:1], False, [])
-        self.assertIOEquals(adapter, self.data[1:5], False, [self.data[0:4]], False)
-        self.assertIOEquals(adapter, self.data[5:12], False, [self.data[4:8], self.data[8:12]], False)
-        self.assertIOEquals(adapter, self.data[12:13], False, [])
-        self.assertIOEquals(adapter, self.data[13:14], False, [])
-        self.assertIOEquals(adapter, self.data[14:18], False, [self.data[12:16]], False)
-        self.assertIOEquals(adapter, self.data[18:20], False, [self.data[16:20]], False)
-        self.assertIOEquals(adapter, self.data[20:21], False, [])
-        self.assertIOEquals(adapter, self.data[21:22], True, [self.data[20:22]], True)
-
-    def testPadding(self):
-        "Test automatic padding support"
-        adapter = FixedSizeInputAdapter(4, 2, pad=True)
-
-        self.assertEquals(len(self.data) + 2, adapter.nframes(len(self.data)))
-
-        self.assertIOEquals(adapter, self.data[0:21], False, 
-            [self.data[0:4], self.data[4:8], self.data[8:12], self.data[12:16], self.data[16:20]], 
-            False)
-
-        self.assertIOEquals(adapter, self.data[21:22], True, [[
-            [20, 42],
-            [21, 43],
-            [0, 0],
-            [0, 0]
-        ]], True)
-
-    def testSizeMultiple(self):
-        "Test a stream which contain a multiple number of buffers"
-        adapter = FixedSizeInputAdapter(4, 2)
-
-        self.assertIOEquals(adapter, self.data[0:20], True, 
-            [self.data[0:4], self.data[4:8], self.data[8:12], self.data[12:16], self.data[16:20]], 
-            True)
-
-
-if __name__ == '__main__':
-    unittest.main(testRunner=TestRunner())
-
diff --git a/timeside/__init__.py b/timeside/__init__.py
new file mode 100644 (file)
index 0000000..81ad004
--- /dev/null
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+
+from core import *
+from metadata import Metadata
+import decoder
+import encoder
+import analyzer
+import grapher
diff --git a/timeside/analyzer/__init__.py b/timeside/analyzer/__init__.py
new file mode 100644 (file)
index 0000000..0bd2039
--- /dev/null
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+from timeside.analyzer.core import *
+from timeside.analyzer.duration import *
+from timeside.analyzer.max_level import *
+#from timeside.analyzer.mean_level import *
+#from timeside.analyzer.dc import *
diff --git a/timeside/analyzer/core.py b/timeside/analyzer/core.py
new file mode 100644 (file)
index 0000000..cbb9a17
--- /dev/null
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Authors:
+#   Guillaume Pellerin <yomguy at parisson.com>
+
+pass
+
+
diff --git a/timeside/analyzer/dc.py b/timeside/analyzer/dc.py
new file mode 100644 (file)
index 0000000..e92cfd5
--- /dev/null
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.analyzer.core import *
+from timeside.api import IValueAnalyzer
+import numpy
+
+
+class MeanDCShift(Processor):
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(MeanDCShift, self).setup(channels, samplerate, nframes)
+        self.value = 0
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "dc"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Mean DC shift"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        return "%"
+
+    def __str__(self):
+        return "%s %s" % (str(self.value), unit())
+
+    def process(self, frames, eod=False):
+        self.value = numpy.round(100*numpy.mean(samples),4)
+        return frames, eod
+
+    def result(self):
+        return self.value
+
diff --git a/timeside/analyzer/duration.py b/timeside/analyzer/duration.py
new file mode 100644 (file)
index 0000000..7c2269c
--- /dev/null
@@ -0,0 +1,55 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
+from timeside.analyzer.core import *
+from timeside.api import IValueAnalyzer
+
+
+class Duration(Processor):
+    """A rather useless duration analyzer. Its only purpose is to test the
+       nframes characteristic."""
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels, samplerate, nframes):
+        if not nframes:
+            raise Exception("nframes argument required")
+        super(Duration, self).setup(channels, samplerate, nframes)
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "duration"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Duration"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        return "seconds"
+
+    def result(self):
+        return self.input_nframes / float(self.input_samplerate)
+    
\ No newline at end of file
diff --git a/timeside/analyzer/max_level.py b/timeside/analyzer/max_level.py
new file mode 100644 (file)
index 0000000..9ecc323
--- /dev/null
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
+from timeside.analyzer.core import *
+from timeside.api import IValueAnalyzer
+
+
+class MaxLevel(Processor):
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(MaxLevel, self).setup(channels, samplerate, nframes)
+        self.max_value = 0
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "maxlevel"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Max level"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        # power? amplitude?
+        return ""
+
+    def process(self, frames, eod=False):
+        max = frames.max()
+        if max > self.max_value:
+            self.max_value = max
+
+        return frames, eod
+
+    def result(self):
+        return self.max_value
+
+
diff --git a/timeside/analyzer/mean_level.py b/timeside/analyzer/mean_level.py
new file mode 100644 (file)
index 0000000..8b68324
--- /dev/null
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.analyzer.core import *
+from timeside.api import IValueAnalyzer
+import numpy
+
+
+class MeanLevel(Processor):
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(MeanLevel, self).setup(channels, samplerate, nframes)
+        self.value = -140
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "meanlevel"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Mean RMS level"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        return "dB"
+
+    def __str__(self):
+        return "%s %s" % (str(self.value), unit())
+
+    def process(self, frames, eod=False):
+        max = numpy.round(20*numpy.log10(numpy.mean(numpy.sqrt(numpy.square(frames.max())))), 2)
+        if max > self.value:
+            self.value = max
+
+        return frames, eod
+
+    def result(self):
+        return self.value
+
diff --git a/timeside/analyzer/vamp/__init__.py b/timeside/analyzer/vamp/__init__.py
new file mode 100644 (file)
index 0000000..1ded83d
--- /dev/null
@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+
+from timeside.analyzer.vamp.core import *
diff --git a/timeside/analyzer/vamp/core.py b/timeside/analyzer/vamp/core.py
new file mode 100644 (file)
index 0000000..49ae9a0
--- /dev/null
@@ -0,0 +1,114 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import *
+from tempfile import NamedTemporaryFile
+from timeside.exceptions import SubProcessError
+import os
+import random
+import subprocess
+import signal
+import time
+
+class VampCoreAnalyzer:
+    """Parent class for Vamp plugin drivers"""
+
+    def __init__(self):
+        self.vamp_path = '/usr/lib/vamp/'
+        # needs vamp-examples package
+        self.host = 'vamp-simple-host'
+        self.buffer_size = 0xFFFF
+
+    def id(self):
+        return "vamp_plugins"
+
+    def name(self):
+        return "Vamp plugins"
+
+    def unit(self):
+        return ""
+
+    def get_plugins_list(self):
+        if os.path.exists(self.vamp_path):
+            args = ' --list-outputs'
+            command = self.host + args
+            #tmp_file = NamedTemporaryFile()
+            data = self.core_process(command, self.buffer_size)
+            text = ''
+            plugins = []
+            for chunk in data:
+                text = text + chunk
+            lines = text.split('\n')
+            for line in lines:
+                if line != '':
+                    struct = line.split(':')
+                    struct = struct[1:]
+                    plugins.append(struct)
+            return plugins
+        else:
+            return []
+
+    def get_wav_path(self, media_item):
+        return settings.MEDIA_ROOT + '/' + media_item.file
+        #return media_item
+
+    def render(self, plugin, media_item):
+        self.wavFile = self.get_wav_path(media_item)
+        args = ' -s ' + ':'.join(plugin) + ' ' + str(self.wavFile)
+        command = command = self.host + args
+        data = self.core_process(command, self.buffer_size)
+        string = ''
+        values = {}
+        for chunk in data:
+            string = string + chunk
+        lines = string.split('\n')
+        for line in lines:
+            if line != '':
+                struct = line.split(':')
+                values[struct[0]] = struct[1]
+        return values
+
+    def core_process(self, command, buffer_size):
+        """Encode and stream audio data through a generator"""
+
+        __chunk = 0
+
+        try:
+            proc = subprocess.Popen(command,
+                    shell = True,
+                    bufsize = buffer_size,
+                    stdin = subprocess.PIPE,
+                    stdout = subprocess.PIPE,
+                    close_fds = True)
+        except:
+            raise SubProcessError('Command failure:', command, proc)
+
+        # Core processing
+        while True:
+            __chunk = proc.stdout.read(buffer_size)
+            status = proc.poll()
+            if status != None and status != 0:
+                raise SubProcessError('Command failure:', command, proc)
+            if len(__chunk) == 0:
+                break
+            yield __chunk
+
+
diff --git a/timeside/api.py b/timeside/api.py
new file mode 100644 (file)
index 0000000..7ceaecf
--- /dev/null
@@ -0,0 +1,214 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2009 Parisson
+# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
+# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+from timeside.component import Interface
+
+class IProcessor(Interface):
+    """Common processor interface"""
+
+    @staticmethod
+    def id():
+        """Short alphanumeric, lower-case string which uniquely identify this 
+        processor, suitable for use as an HTTP/GET argument value, in filenames, 
+        etc..."""
+
+        # implementation: only letters and digits are allowed. An exception will
+        # be raised by MetaProcessor if the id is malformed or not unique amongst
+        # registered processors.
+
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        """Allocate internal resources and reset state, so that this processor is
+        ready for a new run. 
+        
+        The channels, samplerate and/or nframes arguments may be required by 
+        processors which accept input. An error will occur if any of
+        these arguments is passed to an output-only processor such as a decoder.
+        """
+
+        # implementations should always call the parent method
+
+    def channels(self):
+        """Number of channels in the data returned by process(). May be different from
+        the number of channels passed to setup()"""
+
+    def samplerate(self):
+        """Samplerate of the data returned by process(). May be different from
+        the samplerate passed to setup()"""
+
+    def nframes():
+        """The total number of frames that this processor can output, or None if
+        the duration is unknown."""
+
+    def process(self, frames=None, eod=False):
+        """Process input frames and return a (output_frames, eod) tuple.
+        Both input and output frames are 2D numpy arrays, where columns are 
+        channels, and containing an undetermined number of frames.  eod=True 
+        means that the end-of-data has been reached.
+        
+        Output-only processors (such as decoders) will raise an exception if the
+        frames argument is not None. All processors (even encoders) return data,
+        even if that means returning the input unchanged.
+        
+        Warning: it is required to call setup() before this method."""
+
+    def release(self):
+        """Release resources owned by this processor. The processor cannot
+        be used anymore after calling this method."""
+
+        # implementations should always call the parent method
+
+class IEncoder(IProcessor):
+    """Encoder driver interface. Each encoder is expected to support a specific
+    format."""
+
+    def __init__(self, output):
+        """Create a new encoder. output can either be a filename or a python callback 
+        function/method for streaming mode.
+
+        The streaming callback prototype is: callback(data, eod)
+        Where data is a block of binary data of an undetermined size, and eod
+        True when end-of-data is reached."""
+
+        # implementation: the constructor must always accept the output argument. It may 
+        # accept extra arguments such as bitrate, depth, etc.., but these must be optionnal 
+
+    @staticmethod
+    def format():
+        """Return the encode/encoding format as a short string
+        Example: "MP3", "OGG", "AVI", ...
+        """
+
+    @staticmethod
+    def description():
+        """Return a string describing what this encode format provides, is good
+        for, etc... The description is meant to help the end user decide what
+        format is good for him/her
+        """
+
+    @staticmethod
+    def file_extension():
+        """Return the filename extension corresponding to this encode format"""
+
+    @staticmethod
+    def mime_type():
+        """Return the mime type corresponding to this encode format"""
+
+    def set_metadata(self, metadata):
+        """Set the metadata to be embedded in the encoded output.
+        
+        In non-streaming mode, this method updates the metadata directly into the 
+        output file, without re-encoding the audio data, provided this file already 
+        exists.
+        
+        It isn't required to call this method, but if called, it must be before 
+        process()."""
+
+class IDecoder(IProcessor):
+    """Decoder driver interface. Decoders are different of encoders in that
+    a given driver may support several input formats, hence this interface doesn't
+    export any static method, all informations are dynamic."""
+
+    def __init__(self, filename):
+        """Create a new decoder for filename."""
+        # implementation: additional optionnal arguments are allowed 
+
+    def format():
+        """Return a user-friendly file format string"""
+   
+    def encoding():
+        """Return a user-friendly encoding string"""
+
+    def resolution():
+        """Return the sample width (8, 16, etc..) of original audio file/stream,
+           or None if not applicable/known"""
+
+    def metadata(self):
+        """Return the metadata embedded into the encoded stream, if any."""
+
+class IGrapher(IProcessor):
+    """Media item visualizer driver interface"""
+
+    # implementation: graphers which need to know the total number of frames
+    # should raise an exception in setup() if the nframes argument is None 
+
+    def __init__(self, width, height):
+        """Create a new grapher. width and height are generally
+        in pixels but could be something else for eg. svg rendering, etc.. """
+
+        # implementation: additional optionnal arguments are allowed 
+
+    @staticmethod
+    def name():
+        """Return the graph name, such as "Waveform", "Spectral view",
+        etc..  """
+
+    def set_colors(self, background=None, scheme=None):
+        """Set the colors used for image generation. background is a RGB tuple,
+        and scheme a a predefined color theme name"""
+
+    def render(self):
+        """Return a PIL Image object visually representing all of the data passed
+        by repeatedly calling process()"""
+
+class IAnalyzer(IProcessor):
+    """Media item analyzer driver interface. This interface is abstract, it doesn't
+    describe a particular type of analyzer but is rather meant to group analyzers.
+    In particular, the way the result is returned may greatly vary from sub-interface
+    to sub-interface. For example the IValueAnalyzer returns a final single numeric
+    result at the end of the whole analysis. But some other analyzers may return
+    numpy arrays, and this, either at the end of the analysis, or from process()
+    for each block of data (as in Vamp)."""
+
+    def __init__(self):
+        """Create a new analyzer."""
+        # implementation: additional optionnal arguments are allowed 
+
+    @staticmethod
+    def name():
+        """Return the analyzer name, such as "Mean Level", "Max level",
+        "Total length, etc..  """
+
+    @staticmethod
+    def unit():
+        """Return the unit of the data such as "dB", "seconds", etc...  """
+
+class IValueAnalyzer(IAnalyzer):
+    """Interface for analyzers which return a single numeric value from result()"""
+
+    def result():
+        """Return the final result of the analysis performed over the data passed by
+        repeatedly calling process()"""
+
+    def __str__(self):
+        """Return a human readable string containing both result and unit 
+        ('5.30dB', '4.2s', etc...)"""
+
+class IEffect(IProcessor):
+    """Effect processor interface"""
+
+    def __init__(self):
+        """Create a new effect."""
+        # implementation: additional optionnal arguments are allowed 
+
+    @staticmethod
+    def name():
+        """Return the effect name"""
+
diff --git a/timeside/component.py b/timeside/component.py
new file mode 100644 (file)
index 0000000..ff20670
--- /dev/null
@@ -0,0 +1,142 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+
+# This file defines a generic object interface mechanism and 
+# a way to determine which components implements a given interface.
+#
+# For example, the following defines the Music class as implementing the
+# listenable interface.
+#
+# class Listenable(Interface):
+#     pass
+#
+# class Music(Component):
+#    implements(Listenable)
+#
+# Several class can implements a such interface, and it is possible to 
+# discover which class implements it with implementations():
+#
+# list_of_classes = implementations(Listenable)
+#
+# This mechanism support inheritance of interfaces: a class implementing a given 
+# interface is also considered to implement all the ascendants of this interface.
+#
+# However, inheritance is not supported for components. The descendants of a class 
+# implementing a given interface are not automatically considered to implement this 
+# interface too. 
+
+__all__ = ['Component', 'MetaComponent', 'implements', 'abstract', 
+           'interfacedoc', 'Interface', 'implementations', 'ComponentError']
+
+class Interface(object):
+    """Marker base class for interfaces."""
+
+def implements(*interfaces):
+    """Registers the interfaces implemented by a component when placed in the
+    class header"""
+    MetaComponent.implements.extend(interfaces)
+
+def abstract():
+    """Declare a component as abstract when placed in the class header"""
+    MetaComponent.abstract = True
+
+def implementations(interface, recurse=True, abstract=False):
+    """Returns the components implementing interface, and if recurse, any of 
+    the descendants of interface. If abstract is True, also return the 
+    abstract implementations."""
+    result = []
+    find_implementations(interface, recurse, abstract, result)
+    return result
+
+def interfacedoc(func):
+    if isinstance(func, staticmethod):
+        raise ComponentError("@interfacedoc can't handle staticmethod (try to put @staticmethod above @interfacedoc)")
+
+    if not func.__doc__:
+        func.__doc__ = "@interfacedoc"
+        func._interfacedoc = True
+    return func
+
+class MetaComponent(type):
+    """Metaclass of the Component class, used mainly to register the interface
+    declared to be implemented by a component."""
+
+    implementations     = []
+    implements          = []
+    abstract            = False
+
+    def __new__(cls, name, bases, d):
+        new_class = type.__new__(cls, name, bases, d)
+
+        # Register implementations
+        if MetaComponent.implements:
+            for i in MetaComponent.implements:
+                MetaComponent.implementations.append({
+                    'interface': i, 
+                    'class':     new_class,
+                    'abstract':  MetaComponent.abstract})
+
+        # Propagate @interfacedoc
+        for name in new_class.__dict__:
+            member = new_class.__dict__[name]
+            if isinstance(member, staticmethod):
+                member = getattr(new_class, name)
+
+            if member.__doc__ == "@interfacedoc":
+                if_member = None
+                for i in MetaComponent.implements:
+                    if hasattr(i, name):
+                        if_member = getattr(i, name)
+                if not if_member:
+                    raise ComponentError("@interfacedoc: %s.%s: no such member in implemented interfaces: %s"
+                                         % (new_class.__name__, name, str(MetaComponent.implements)))
+                member.__doc__ = if_member.__doc__
+                
+        MetaComponent.implements = []
+        MetaComponent.abstract   = False
+
+        return new_class
+
+class Component(object):
+    """Base class of all components"""
+    __metaclass__ = MetaComponent
+
+def extend_unique(list1, list2):
+    """Extend list1 with list2 as list.extend(), but doesn't append duplicates
+    to list1"""
+    for item in list2:
+        if item not in list1:
+            list1.append(item)
+
+def find_implementations(interface, recurse, abstract, result):
+    """Find implementations of an interface or of one of its descendants and
+    extend result with the classes found."""
+    for item in MetaComponent.implementations:
+        if (item['interface'] == interface and (abstract or not item['abstract'])):
+            extend_unique(result, [item['class']])
+
+    if recurse:
+        subinterfaces = interface.__subclasses__()
+        if subinterfaces:
+            for i in subinterfaces:
+                find_implementations(i, recurse, abstract, result)
+
+class ComponentError(Exception):
+    pass
diff --git a/timeside/core.py b/timeside/core.py
new file mode 100644 (file)
index 0000000..f5b3c31
--- /dev/null
@@ -0,0 +1,221 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+from timeside.component import *
+from timeside.api import IProcessor
+from timeside.exceptions import Error, ApiError
+import re
+import numpy
+
+__all__ = ['Processor', 'MetaProcessor', 'implements', 'abstract', 
+           'interfacedoc', 'processors', 'get_processor', 'ProcessPipe',
+           'FixedSizeInputAdapter']
+
+_processors = {}
+
+class MetaProcessor(MetaComponent):
+    """Metaclass of the Processor class, used mainly for ensuring that processor
+    id's are wellformed and unique"""
+
+    valid_id = re.compile("^[a-z][_a-z0-9]*$")
+
+    def __new__(cls, name, bases, d):
+        new_class = MetaComponent.__new__(cls, name, bases, d)
+        if new_class in implementations(IProcessor):
+            id = str(new_class.id())
+            if _processors.has_key(id):
+                raise ApiError("%s and %s have the same id: '%s'"
+                    % (new_class.__name__, _processors[id].__name__, id))
+            if not MetaProcessor.valid_id.match(id):
+                raise ApiError("%s has a malformed id: '%s'"
+                    % (new_class.__name__, id))
+
+            _processors[id] = new_class
+
+        return new_class
+
+class Processor(Component):
+    """Base component class of all processors"""
+    __metaclass__ = MetaProcessor
+
+    abstract()
+    implements(IProcessor)
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        self.input_channels   = channels
+        self.input_samplerate = samplerate
+        self.input_nframes    = nframes
+
+    # default channels(), samplerate() and nframes() implementations returns 
+    # the input characteristics, but processors may change this behaviour by 
+    # overloading those methods
+    @interfacedoc
+    def channels(self):
+        return self.input_channels
+
+    @interfacedoc
+    def samplerate(self):
+        return self.input_samplerate
+
+    @interfacedoc
+    def nframes(self):
+        return self.input_nframes
+
+    @interfacedoc
+    def process(self, frames, eod):
+        return frames, eod
+
+    @interfacedoc
+    def release(self):
+        pass
+
+    def __del__(self):
+        self.release()
+
+    def __or__(self, other):
+        return ProcessPipe(self, other)
+
+class FixedSizeInputAdapter(object):
+    """Utility to make it easier to write processors which require fixed-sized
+    input buffers."""
+
+    def __init__(self, buffer_size, channels, pad=False):
+        """Construct a new adapter: buffer_size is the desired buffer size in frames,
+        channels the number of channels, and pad indicates whether the last block should 
+        be padded with zeros."""
+
+        self.buffer      = numpy.empty((buffer_size, channels))
+        self.buffer_size = buffer_size
+        self.len         = 0
+        self.pad         = pad
+
+    def nframes(self, input_nframes):
+        """Return the total number of frames that this adapter will output according to the
+        input_nframes argument"""
+
+        nframes = input_nframes
+        if self.pad:
+            mod = input_nframes % self.buffer_size
+            if mod:
+                nframes += self.buffer_size - mod
+
+        return nframes                
+
+
+    def process(self, frames, eod):
+        """Returns an iterator over tuples of the form (buffer, eod) where buffer is a 
+        fixed-sized block of data, and eod indicates whether this is the last block.
+        In case padding is deactivated the last block may be smaller than the buffer size.
+        """
+        src_index = 0
+        remaining = len(frames)
+
+        while remaining:
+            space   = self.buffer_size - self.len
+            copylen = remaining < space and remaining or space
+            src     = frames[src_index:src_index + copylen]
+            if self.len == 0 and copylen == self.buffer_size:
+                # avoid unnecessary copy
+                buffer = src
+            else:
+                buffer = self.buffer
+                buffer[self.len:self.len + copylen] = src
+
+            remaining -= copylen
+            src_index += copylen
+            self.len  += copylen
+
+            if self.len == self.buffer_size:
+                yield buffer, (eod and not remaining)
+                self.len = 0
+
+        if eod and self.len:
+            block = self.buffer
+            if self.pad:
+                self.buffer[self.len:self.buffer_size] = 0
+            else:
+                block = self.buffer[0:self.len]
+
+            yield block, True
+            self.len = 0
+                            
+def processors(interface=IProcessor, recurse=True):
+    """Returns the processors implementing a given interface and, if recurse,
+    any of the descendants of this interface."""
+    return implementations(interface, recurse)
+    
+
+def get_processor(processor_id):
+    """Return a processor by its id"""
+    if not _processors.has_key(processor_id):
+        raise Error("No processor registered with id: '%s'" 
+              % processor_id)
+
+    return _processors[processor_id]
+
+class ProcessPipe(object):
+    """Handle a pipe of processors"""
+
+    def __init__(self, *others):
+        self.processors = []
+        self |= others
+
+    def __or__(self, other):
+        return ProcessPipe(self, other)
+
+    def __ior__(self, other):
+        if isinstance(other, Processor):
+            self.processors.append(other)
+        elif isinstance(other, ProcessPipe):
+            self.processors.extend(other.processors)
+        else:
+            try:
+                iter(other)
+            except TypeError:
+                raise Error("Can not add this type of object to a pipe: %s", str(other))
+
+            for item in other:
+                self |= item
+
+        return self            
+
+    def run(self):
+        """Setup/reset all processors in cascade and stream audio data along
+        the pipe. Also returns the pipe itself."""
+
+        source = self.processors[0]
+        items  = self.processors[1:]
+
+        # setup/reset processors and configure channels and samplerate throughout the pipe
+        source.setup()
+        last = source
+        for item in items:
+            item.setup(last.channels(), last.samplerate(), last.nframes())
+            last = item
+
+        # now stream audio data along the pipe
+        eod = False
+        while not eod:
+            frames, eod = source.process()
+            for item in items:
+                frames, eod = item.process(frames, eod)
+
+        return self                
+       
diff --git a/timeside/decoder/__init__.py b/timeside/decoder/__init__.py
new file mode 100644 (file)
index 0000000..9f37f75
--- /dev/null
@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+
+from timeside.decoder.core import *
diff --git a/timeside/decoder/core.py b/timeside/decoder/core.py
new file mode 100644 (file)
index 0000000..08d6e94
--- /dev/null
@@ -0,0 +1,243 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import *
+import subprocess
+
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2009 Parisson
+# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
+# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Paul Brossier <piem@piem.org>
+
+from timeside.core import Processor, implements, interfacedoc
+from timeside.api import IDecoder
+from numpy import array, frombuffer, getbuffer, float32
+
+import pygst
+pygst.require('0.10')
+import gst
+import gobject
+gobject.threads_init ()
+
+
+class FileDecoder(Processor):
+    """ gstreamer-based decoder """
+    implements(IDecoder)
+
+    # duration ms, before discovery process times out
+    MAX_DISCOVERY_TIME = 3000
+
+    audioformat = None
+    audiochannels = None
+    audiorate = None
+    audionframes = None
+    mimetype = ''
+
+    # IProcessor methods
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "gstreamerdec"
+
+    def setup(self, channels = None, samplerate = None, nframes = None):
+        # the output data format we want
+        caps = "audio/x-raw-float, width=32"
+        pipeline = gst.parse_launch('''uridecodebin uri=%s
+            ! audioconvert
+            ! %s
+            ! appsink name=sink sync=False ''' % (self.uri, caps))
+        # store a pointer to appsink in our decoder object 
+        self.sink = pipeline.get_by_name('sink')
+        # adjust length of emitted buffers
+        # self.sink.set_property('blocksize', 0x10000)
+        # start pipeline
+        pipeline.set_state(gst.STATE_PLAYING)
+
+    @interfacedoc
+    def channels(self):
+        return  self.audiochannels
+
+    @interfacedoc
+    def samplerate(self):
+        return self.audiorate 
+
+    @interfacedoc
+    def nframes(self):
+        return self.audionframes
+
+    @interfacedoc
+    def process(self, frames = None, eod = False):
+        try:
+            buf = self.sink.emit('pull-buffer')
+        except SystemError, e:
+            # should never happen
+            print 'SystemError', e
+            return array([0.]), True
+        if buf == None:
+            return array([0.]), True
+        return self.gst_buffer_to_numpy_array(buf), False
+
+    @interfacedoc
+    def release(self):
+        # nothing to do for now 
+        pass
+
+    ## IDecoder methods
+
+    @interfacedoc
+    def __init__(self, uri):
+
+        # is this a file? 
+        import os.path
+        if os.path.exists(uri):
+            # get the absolute path
+            uri = os.path.abspath(uri)
+            # first run the file/uri through the discover pipeline
+            self.discover(uri)
+            # and make a uri of it
+            from urllib import quote
+            self.uri = 'file://'+quote(uri)
+
+    @interfacedoc
+    def format(self):
+        # TODO check
+        return self.mimetype
+
+    @interfacedoc
+    def encoding(self):
+        # TODO check
+        return self.mimetype.split('/')[-1]
+
+    @interfacedoc
+    def resolution(self):
+        # TODO check: width or depth?
+        return self.audiowidth 
+
+    @interfacedoc
+    def metadata(self):
+        # TODO check
+        return self.tags
+
+    ## gst.extend discoverer
+
+    def discover(self, path):
+        """ gstreamer based helper function to get file attributes """
+        from gst.extend import discoverer
+        d = discoverer.Discoverer(path, timeout = self.MAX_DISCOVERY_TIME)
+        d.connect('discovered', self.discovered)
+        self.mainloop = gobject.MainLoop()
+        d.discover()
+        self.mainloop.run()
+
+    def discovered(self, d, is_media):
+        """ gstreamer based helper executed upon discover() completion """
+        if is_media and d.is_audio:
+            # copy the discoverer attributes to self
+            self.audiorate = d.audiorate
+            self.mimetype= d.mimetype
+            self.audiochannels = d.audiochannels
+            self.audiowidth = d.audiowidth
+            # conversion from time in nanoseconds to frames 
+            from math import ceil
+            duration = d.audiorate * d.audiolength * 1.e-9
+            self.audionframes = int (ceil ( duration ) )
+            self.tags = d.tags
+        elif not d.is_audio:
+            print "error, no audio found!"
+        else:
+            print "fail", path
+        self.mainloop.quit()
+
+    def gst_buffer_to_numpy_array(self, buf):
+        """ gstreamer buffer to numpy array conversion """
+        chan = self.audiochannels
+        samples = frombuffer(buf.data, dtype=float32) 
+        samples.resize([len(samples)/chan, chan])
+        return samples
+
+
+class SubProcessPipe:
+
+    def __init__(self, command, stdin=None):
+        """Read media and stream data through a generator.
+        Taken from Telemeta (see http://telemeta.org)"""
+
+        self.buffer_size = 0xFFFF
+
+        if not stdin:
+            stdin =  subprocess.PIPE
+
+        self.proc = subprocess.Popen(command.encode('utf-8'),
+                    shell = True,
+                    bufsize = self.buffer_size,
+                    stdin = stdin,
+                    stdout = subprocess.PIPE,
+                    close_fds = True)
+
+        self.input = self.proc.stdin
+        self.output = self.proc.stdout
+
+
+class DecoderSubProcessCore(Processor):
+    """Defines the main parts of the decoding tools :
+    paths, metadata parsing, data streaming thru system command"""
+
+    def __init__(self):
+        self.command = 'ffmpeg -i "%s" -f wav - '
+
+    def process(self, source, options=None):
+        """Encode and stream audio data through a generator"""
+
+        command = self.command % source
+        proc = SubProcessPipe(command)
+        return proc.output
+
+        #while True:
+            #__chunk = proc.output.read(self.proc.buffer_size)
+            #status = proc.poll()
+            #if status != None and status != 0:
+                #raise ExportProcessError('Command failure:', command, proc)
+            #if len(__chunk) == 0:
+                #break
+            #yield __chunk
+
+
+
diff --git a/timeside/doc/img/timeside_schema.dia b/timeside/doc/img/timeside_schema.dia
new file mode 100644 (file)
index 0000000..6431955
Binary files /dev/null and b/timeside/doc/img/timeside_schema.dia differ
diff --git a/timeside/doc/img/timeside_schema.png b/timeside/doc/img/timeside_schema.png
new file mode 100644 (file)
index 0000000..29f4bcb
Binary files /dev/null and b/timeside/doc/img/timeside_schema.png differ
diff --git a/timeside/encoder/__init__.py b/timeside/encoder/__init__.py
new file mode 100644 (file)
index 0000000..7eadf71
--- /dev/null
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+
+from timeside.encoder.core import *
+#from timeside.encoder.ogg import *
+from timeside.encoder.wav import *
+#from timeside.encoder.mp3 import *
+#from timeside.encoder.flac import *
diff --git a/timeside/encoder/core.py b/timeside/encoder/core.py
new file mode 100644 (file)
index 0000000..9786de1
--- /dev/null
@@ -0,0 +1,64 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import *
+import subprocess
+
+class SubProcessPipe:
+    """Read media and stream data through a generator.
+    Taken from Telemeta (see http://telemeta.org)"""
+
+    def __init__(self, command, stdin=None):
+        self.buffer_size = 0xFFFF
+        if not stdin:
+            stdin =  subprocess.PIPE
+
+        self.proc = subprocess.Popen(command.encode('utf-8'),
+                    shell = True,
+                    bufsize = self.buffer_size,
+                    stdin = stdin,
+                    stdout = subprocess.PIPE,
+                    close_fds = True)
+
+        self.input = self.proc.stdin
+        self.output = self.proc.stdout
+
+class EncoderSubProcessCore(Processor):
+    """Defines the main parts of the encoding tools :
+    paths, metadata parsing, data streaming thru system command"""
+
+    def core_process(self, command, stdin):
+        """Encode and stream audio data through a generator"""
+
+        proc = SubProcessPipe(command, stdin)
+
+        while True:
+            __chunk = proc.output.read(proc.buffer_size)
+            #status = proc.poll()
+            #if status != None and status != 0:
+                #raise EncodeProcessError('Command failure:', command, proc)
+            if len(__chunk) == 0:
+                break
+            yield __chunk
+
+
+
diff --git a/timeside/encoder/flac.py b/timeside/encoder/flac.py
new file mode 100644 (file)
index 0000000..0753441
--- /dev/null
@@ -0,0 +1,140 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+import os
+import string
+import subprocess
+
+from timeside.encoder.core import *
+from timeside.api import IEncoder
+from tempfile import NamedTemporaryFile
+
+class FlacEncoder(EncoderCore):
+    """Defines methods to encode to FLAC"""
+
+    implements(IEncoder)
+
+    def __init__(self):
+        self.quality_default = '-5'
+        self.dub2args_dict = {'creator': 'artist',
+                             'relation': 'album'
+                             }
+
+    @staticmethod
+    def id():
+        return "flacenc"
+
+    def format(self):
+        return 'FLAC'
+
+    def file_extension(self):
+        return 'flac'
+
+    def mime_type(self):
+        return 'audio/x-flac'
+
+    def description(self):
+        return """
+        Free Lossless Audio Codec (FLAC) is a file format for lossless audio
+        data compression.
+        """
+
+    def get_file_info(self):
+        try:
+            file1, file2 = os.popen4('metaflac --list "'+self.dest+'"')
+            info = []
+            for line in file2.readlines():
+                info.append(clean_word(line[:-1]))
+            self.info = info
+            return self.info
+        except:
+            raise IOError('EncoderError: metaflac is not installed or ' + \
+                           'file does not exist.')
+
+    def write_tags(self, file):
+        from mutagen.flac import FLAC
+        media = FLAC(file)
+        for tag in self.metadata:
+            name = tag[0]
+            value = clean_word(tag[1])
+            if name in self.dub2args_dict.keys():
+                name = self.dub2args_dict[name]
+            if name == 'comment':
+                media['DESCRIPTION'] = unicode(value)
+            else:
+                media[name] = unicode(value)
+        try:
+            media.save()
+        except:
+            raise IOError('EncoderError: cannot write tags.')
+
+
+    def get_args(self,options=None):
+        """Get process options and return arguments for the encoder"""
+        args = []
+        if not options is None:
+            self.options = options
+            if not ('verbose' in self.options and self.options['verbose'] != '0'):
+                args.append('-s')
+            if 'flac_quality' in self.options:
+                args.append('-f ' + self.options['flac_quality'])
+            else:
+                args.append('-f ' + self.quality_default)
+        else:
+            args.append('-s -f ' + self.quality_default)
+
+        #for tag in self.metadata.keys():
+            #value = clean_word(self.metadata[tag])
+            #args.append('-c %s="%s"' % (tag, value))
+            #if tag in self.dub2args_dict.keys():
+                #arg = self.dub2args_dict[tag]
+                #args.append('-c %s="%s"' % (arg, value))
+
+        return args
+
+    def process(self, source, metadata, options=None):
+        buffer_size = 0xFFFF
+        self.metadata= metadata
+        self.options = options
+        args = self.get_args()
+        args = ' '.join(args)
+        ext = self.file_extension()
+        temp_file = NamedTemporaryFile()
+        command = 'flac %s - -o %s ' % (args, temp_file.name)
+
+        stream = self.core_process(command, source)
+
+        for __chunk in stream:
+            #temp_file.write(__chunk)
+            #temp_file.flush()
+            pass
+
+        #self.write_tags(temp_file.name)
+
+        while True:
+            __chunk = temp_file.read(buffer_size)
+            if len(__chunk) == 0:
+                break
+            yield __chunk
+
+        temp_file.close()
+
+
diff --git a/timeside/encoder/mp3.py b/timeside/encoder/mp3.py
new file mode 100644 (file)
index 0000000..70f6dfb
--- /dev/null
@@ -0,0 +1,137 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007 Parisson SARL
+# Copyright (c) 2006-2007 Guillaume Pellerin <pellerin@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+import os
+import string
+import subprocess
+
+from timeside.encoder.core import *
+from timeside.api import IEncoder
+
+
+class Mp3Encoder(EncoderCore):
+    """Defines methods to encode to MP3"""
+
+    implements(IEncoder)
+
+    def __init__(self):
+        self.bitrate_default = '192'
+        self.dub2id3_dict = {'title': 'TIT2', #title2
+                             'creator': 'TCOM', #composer
+                             'creator': 'TPE1', #lead
+                             'identifier': 'UFID', #Unique ID...
+                             'identifier': 'TALB', #album
+                             'type': 'TCON', #genre
+                             'publisher': 'TPUB', #comment
+                             #'date': 'TYER', #year
+                             }
+        self.dub2args_dict = {'title': 'tt', #title2
+                             'creator': 'ta', #composerS
+                             'relation': 'tl', #album
+                             #'type': 'tg', #genre
+                             'publisher': 'tc', #comment
+                             'date': 'ty', #year
+                             }
+
+    @staticmethod
+    def id():
+        return "mp3enc"
+
+    def format(self):
+        return 'MP3'
+
+    def file_extension(self):
+        return 'mp3'
+
+    def mime_type(self):
+        return 'audio/mpeg'
+
+    def description(self):
+        return """
+        MPEG-1 Audio Layer 3, more commonly referred to as MP3, is a patented
+        digital audio encoding format using a form of lossy data compression.
+        """
+
+    def get_file_info(self):
+        try:
+            file_out1, file_out2 = os.popen4('mp3info "'+self.dest+'"')
+            info = []
+            for line in file_out2.readlines():
+                info.append(clean_word(line[:-1]))
+            self.info = info
+            return self.info
+        except:
+            raise IOError('EncoderError: file does not exist.')
+
+    def write_tags(self):
+        """Write all ID3v2.4 tags by mapping dub2id3_dict dictionnary with the
+            respect of mutagen classes and methods"""
+        from mutagen import id3
+        id3 = id3.ID3(self.dest)
+        for tag in self.metadata.keys():
+            if tag in self.dub2id3_dict.keys():
+                frame_text = self.dub2id3_dict[tag]
+                value = self.metadata[tag]
+                frame = mutagen.id3.Frames[frame_text](3,value)
+                try:
+                    id3.add(frame)
+                except:
+                    raise IOError('EncoderError: cannot tag "'+tag+'"')
+        try:
+            id3.save()
+        except:
+            raise IOError('EncoderError: cannot write tags')
+
+    def get_args(self):
+        """Get process options and return arguments for the encoder"""
+        args = []
+        if not self.options is None:
+            if not ( 'verbose' in self.options and self.options['verbose'] != '0' ):
+                args.append('-S')
+            if 'mp3_bitrate' in self.options:
+                args.append('-b ' + self.options['mp3_bitrate'])
+            else:
+                args.append('-b '+self.bitrate_default)
+            #Copyrights, etc..
+            args.append('-c -o')
+        else:
+            args.append('-S -c --tt "unknown" -o')
+
+        for tag in self.metadata:
+            name = tag[0]
+            value = clean_word(tag[1])
+            if name in self.dub2args_dict.keys():
+                arg = self.dub2args_dict[name]
+                args.append('--' + arg + ' "' + value + '"')
+        return args
+
+    def process(self, source, metadata, options=None):
+        self.metadata = metadata
+        self.options = options
+        args = self.get_args()
+        args = ' '.join(args)
+        command = 'lame %s - -' % args
+
+        stream = self.core_process(command, source)
+        for __chunk in stream:
+            yield __chunk
+
diff --git a/timeside/encoder/ogg.py b/timeside/encoder/ogg.py
new file mode 100644 (file)
index 0000000..566c529
--- /dev/null
@@ -0,0 +1,116 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+import os
+import string
+import subprocess
+
+from timeside.encoder.core import *
+from timeside.api import IEncoder
+
+class OggVorbisEncoder(EncoderCore):
+    """Defines methods to encode to OGG Vorbis"""
+
+    implements(IEncoder)
+
+    def __init__(self):
+        self.bitrate_default = '192'
+        self.dub2args_dict = {'creator': 'artist',
+                             'relation': 'album'
+                             }
+
+    @staticmethod
+    def id():
+        return "oggenc"
+
+    def format(self):
+        return 'OggVorbis'
+
+    def file_extension(self):
+        return 'ogg'
+
+    def mime_type(self):
+        return 'application/ogg'
+
+    def description(self):
+        return """
+        Vorbis is a free software / open source project headed by the Xiph.Org
+        Foundation (formerly Xiphophorus company). The project produces an audio
+        format specification and software implementation (codec) for lossy audio
+        compression. Vorbis is most commonly used in conjunction with the Ogg
+        container format and it is therefore often referred to as Ogg Vorbis.
+        (source Wikipedia)
+        """
+
+    def get_file_info(self, file):
+        try:
+            file_out1, file_out2 = os.popen4('ogginfo "' + file + '"')
+            info = []
+            for line in file_out2.readlines():
+                info.append(clean_word(line[:-1]))
+            self.info = info
+            return self.info
+        except:
+            raise IOError('EncoderError: file does not exist.')
+
+    def write_tags(self, file):
+        from mutagen.oggvorbis import OggVorbis
+        media = OggVorbis(file)
+        for tag in self.metadata.keys():
+            media[tag] = str(self.metadata[tag])
+        media.save()
+
+    def get_args(self):
+        """Get process options and return arguments for the encoder"""
+        args = []
+        if not self.options is None:
+            if not ('verbose' in self.options and self.options['verbose'] != '0'):
+                args.append('-Q ')
+            if 'ogg_bitrate' in self.options:
+                args.append('-b '+self.options['ogg_bitrate'])
+            elif 'ogg_quality' in self.options:
+                args.append('-q '+self.options['ogg_quality'])
+            else:
+                args.append('-b '+self.bitrate_default)
+        else:
+            args.append('-Q -b '+self.bitrate_default)
+
+        for tag in self.metadata:
+            name = tag[0]
+            value = clean_word(tag[1])
+            args.append('-c %s="%s"' % (name, value))
+            if name in self.dub2args_dict.keys():
+                arg = self.dub2args_dict[name]
+                args.append('-c %s="%s"' % (arg, value))
+        return args
+
+    def process(self, source, metadata, options=None):
+        self.metadata = metadata
+        self.options = options
+        args = self.get_args()
+        args = ' '.join(args)
+        command = 'oggenc %s -' % args
+
+        stream = self.core_process(command, source)
+        for __chunk in stream:
+            yield __chunk
+
+
diff --git a/timeside/encoder/wav.py b/timeside/encoder/wav.py
new file mode 100644 (file)
index 0000000..d790aaa
--- /dev/null
@@ -0,0 +1,124 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2009 Parisson
+# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
+# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Paul Brossier <piem@piem.org>
+
+from timeside.core import Processor, implements, interfacedoc
+from timeside.api import IEncoder
+from numpy import array, frombuffer, getbuffer, float32
+
+import pygst
+pygst.require('0.10')
+import gst
+import gobject
+gobject.threads_init ()
+
+
+class WavEncoder(Processor):
+    """ gstreamer-based encoder """
+    implements(IEncoder)
+
+    def __init__(self, output):
+        self.file = None
+        if isinstance(output, basestring):
+            self.filename = output
+        else:
+            raise Exception("Streaming not supported")
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(WavEncoder, self).setup(channels, samplerate, nframes)
+        # TODO open file for writing
+        # the output data format we want
+        pipeline = gst.parse_launch(''' appsrc name=src
+            ! audioconvert
+            ! wavenc
+            ! filesink location=%s ''' % self.filename)
+        # store a pointer to appsink in our encoder object 
+        self.src = pipeline.get_by_name('src')
+        srccaps = gst.Caps("""audio/x-raw-float,
+            endianness=(int)1234,
+            channels=(int)%s,
+            width=(int)32,
+            rate=(int)%d""" % (int(channels), int(samplerate)))
+        self.src.set_property("caps", srccaps)
+
+        # start pipeline
+        pipeline.set_state(gst.STATE_PLAYING)
+        self.pipeline = pipeline
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "gstreamerenc"
+
+    @staticmethod
+    @interfacedoc
+    def description():
+        return "Gstreamer based encoder"
+
+    @staticmethod
+    @interfacedoc
+    def file_extension():
+        return "wav"
+
+    @staticmethod
+    @interfacedoc
+    def mime_type():
+        return "audio/x-wav"
+
+    @interfacedoc
+    def set_metadata(self, metadata):
+        #TODO
+        pass
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        buf = self.numpy_array_to_gst_buffer(frames)
+        self.src.emit('push-buffer', buf)
+        if eod: self.src.emit('end-of-stream')
+        return frames, eod
+
+    def numpy_array_to_gst_buffer(self, frames):
+        """ gstreamer buffer to numpy array conversion """
+        buf = gst.Buffer(getbuffer(frames))
+        return buf
diff --git a/timeside/exceptions.py b/timeside/exceptions.py
new file mode 100644 (file)
index 0000000..40b4dcd
--- /dev/null
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2009 Olivier Guilyardi <olivier@samalyse.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+class Error(Exception):
+    """Exception base class for errors in TimeSide."""
+
+class ApiError(Exception):
+    """Exception base class for errors in TimeSide."""
+
+class SubProcessError(Error):
+    """Exception for reporting errors from a subprocess"""
+
+    def __init__(self, message, command, subprocess):
+        self.message = message
+        self.command = str(command)
+        self.subprocess = subprocess
+
+    def __str__(self):
+        if self.subprocess.stderr != None:
+            error = self.subprocess.stderr.read()
+        else:
+            error = ''
+        return "%s ; command: %s; error: %s" % (self.message,
+                                                self.command,
+                                                error)
diff --git a/timeside/grapher/__init__.py b/timeside/grapher/__init__.py
new file mode 100644 (file)
index 0000000..616ebf6
--- /dev/null
@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+
+from timeside.grapher.core import *
+from timeside.grapher.waveform import *
+from timeside.grapher.spectrogram import *
diff --git a/timeside/grapher/core.py b/timeside/grapher/core.py
new file mode 100644 (file)
index 0000000..36bc0bd
--- /dev/null
@@ -0,0 +1,362 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# wav2png.py -- converts wave files to wave file and spectrogram images
+# Copyright (C) 2008 MUSIC TECHNOLOGY GROUP (MTG)
+#                    UNIVERSITAT POMPEU FABRA
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+# Authors:
+#   Bram de Jong <bram.dejong at domain.com where domain in gmail>
+#   Guillaume Pellerin <yomguy@parisson.com>
+
+
+import optparse, math, sys
+import ImageFilter, ImageChops, Image, ImageDraw, ImageColor
+import numpy
+from timeside.core import FixedSizeInputAdapter
+
+
+color_schemes = {
+    'default': {
+        'waveform': [(50,0,200), (0,220,80), (255,224,0), (255,0,0)],
+        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
+                      (224,224,44), (255,60,30), (255,255,255)]
+    },
+    'iso': {
+        'waveform': [(0,0,255), (0,255,255), (255,255,0), (255,0,0)],
+        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
+                      (224,224,44), (255,60,30), (255,255,255)]
+    },
+    'purple': {
+        'waveform': [(173,173,173), (147,149,196), (77,80,138), (108,66,0)],
+        'spectrogram': [(0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100),
+                      (224,224,44), (255,60,30), (255,255,255)]
+    }
+}
+
+
+class Spectrum(object):
+    """ FFT based frequency analysis of audio frames."""
+
+    def __init__(self, fft_size, nframes, samplerate, lower, higher, window_function=numpy.ones):
+        self.fft_size = fft_size
+        self.window = window_function(self.fft_size)
+        self.spectrum_range = None
+        self.lower = lower
+        self.higher = higher
+        self.lower_log = math.log10(self.lower)
+        self.higher_log = math.log10(self.higher)
+        self.clip = lambda val, low, high: min(high, max(low, val))
+        self.nframes = nframes
+        self.samplerate = samplerate
+        self.spectrum_adapter = FixedSizeInputAdapter(self.fft_size, 1, pad=True)
+
+    def process(self, frames, eod, spec_range=120.0):
+        """ Returns a tuple containing the spectral centroid and the spectrum (dB scales) of the input audio frames.
+            An adapter is used to fix the buffer length and then provide fixed FFT window sizes."""
+
+        for buffer, end in self.spectrum_adapter.process(frames, eod):
+            samples = buffer[:,0].copy()
+            if end:
+                break
+
+        #samples = numpy.concatenate((numpy.zeros(self.fft_size/2), samples), axis=1)
+        samples *= self.window
+        fft = numpy.fft.fft(samples)
+        spectrum = numpy.abs(fft[:fft.shape[0] / 2 + 1]) / float(self.fft_size) # normalized abs(FFT) between 0 and 1
+        length = numpy.float64(spectrum.shape[0])
+
+        # scale the db spectrum from [- spec_range db ... 0 db] > [0..1]
+        db_spectrum = ((20*(numpy.log10(spectrum + 1e-30))).clip(-spec_range, 0.0) + spec_range)/spec_range
+        energy = spectrum.sum()
+        spectral_centroid = 0
+
+        if energy > 1e-20:
+            # calculate the spectral centroid
+            if self.spectrum_range == None:
+                self.spectrum_range = numpy.arange(length)
+
+            spectral_centroid = (spectrum * self.spectrum_range).sum() / (energy * (length - 1)) * self.samplerate * 0.5
+            # clip > log10 > scale between 0 and 1
+            spectral_centroid = (math.log10(self.clip(spectral_centroid, self.lower, self.higher)) - self.lower_log) / (self.higher_log - self.lower_log)
+
+        return (spectral_centroid, db_spectrum)
+
+
+def interpolate_colors(colors, flat=False, num_colors=256):
+    """ Given a list of colors, create a larger list of colors interpolating
+    the first one. If flatten is True a list of numers will be returned. If
+    False, a list of (r,g,b) tuples. num_colors is the number of colors wanted
+    in the final list """
+
+    palette = []
+
+    for i in range(num_colors):
+        index = (i * (len(colors) - 1))/(num_colors - 1.0)
+        index_int = int(index)
+        alpha = index - float(index_int)
+
+        if alpha > 0:
+            r = (1.0 - alpha) * colors[index_int][0] + alpha * colors[index_int + 1][0]
+            g = (1.0 - alpha) * colors[index_int][1] + alpha * colors[index_int + 1][1]
+            b = (1.0 - alpha) * colors[index_int][2] + alpha * colors[index_int + 1][2]
+        else:
+            r = (1.0 - alpha) * colors[index_int][0]
+            g = (1.0 - alpha) * colors[index_int][1]
+            b = (1.0 - alpha) * colors[index_int][2]
+
+        if flat:
+            palette.extend((int(r), int(g), int(b)))
+        else:
+            palette.append((int(r), int(g), int(b)))
+
+    return palette
+
+
+class WaveformImage(object):
+    """ Builds a PIL image representing a waveform of the audio stream.
+    Adds pixels iteratively thanks to the adapter providing fixed size frame buffers.
+    Peaks are colored relative to the spectral centroids of each frame packet. """
+
+    def __init__(self, image_width, image_height, nframes, samplerate, fft_size, bg_color=(0,0,0), color_scheme='default', filename=None):
+        self.image_width = image_width
+        self.image_height = image_height
+        self.nframes = nframes
+        self.samplerate = samplerate
+        self.fft_size = fft_size
+        self.filename = filename
+
+        self.bg_color = bg_color
+        self.color_scheme = color_scheme
+
+        if isinstance(color_scheme, dict):
+            colors = color_scheme['waveform']
+        else:
+            colors = color_schemes[self.color_scheme]['waveform']
+
+        self.color_lookup = interpolate_colors(colors)
+
+        self.samples_per_pixel = self.nframes / float(self.image_width)
+        self.buffer_size = int(round(self.samples_per_pixel, 0))
+        self.pixels_adapter = FixedSizeInputAdapter(self.buffer_size, 1, pad=False)
+        self.pixels_adapter_nframes = self.pixels_adapter.nframes(self.nframes)
+
+        self.lower = 800
+        self.higher = 12000
+        self.spectrum = Spectrum(self.fft_size, self.nframes, self.samplerate, self.lower, self.higher, numpy.hanning)
+
+        self.image = Image.new("RGB", (self.image_width, self.image_height), self.bg_color)
+        self.pixel = self.image.load()
+        self.draw = ImageDraw.Draw(self.image)
+        self.previous_x, self.previous_y = None, None
+        self.frame_cursor = 0
+        self.pixel_cursor = 0
+
+    def peaks(self, samples):
+        """ Find the minimum and maximum peak of the samples.
+        Returns that pair in the order they were found.
+        So if min was found first, it returns (min, max) else the other way around. """
+
+        max_index = numpy.argmax(samples)
+        max_value = samples[max_index]
+
+        min_index = numpy.argmin(samples)
+        min_value = samples[min_index]
+
+        if min_index < max_index:
+            return (min_value, max_value)
+        else:
+            return (max_value, min_value)
+
+    def color_from_value(self, value):
+        """ given a value between 0 and 1, return an (r,g,b) tuple """
+
+        return ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (int( (1.0 - value) * 360 ), 80, 50))
+
+    def draw_peaks(self, x, peaks, spectral_centroid):
+        """ draw 2 peaks at x using the spectral_centroid for color """
+
+        y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
+        y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
+
+        line_color = self.color_lookup[int(spectral_centroid*255.0)]
+
+        if self.previous_y != None:
+            self.draw.line([self.previous_x, self.previous_y, x, y1, x, y2], line_color)
+        else:
+            self.draw.line([x, y1, x, y2], line_color)
+
+        self.previous_x, self.previous_y = x, y2
+
+        self.draw_anti_aliased_pixels(x, y1, y2, line_color)
+
+    def draw_anti_aliased_pixels(self, x, y1, y2, color):
+        """ vertical anti-aliasing at y1 and y2 """
+
+        y_max = max(y1, y2)
+        y_max_int = int(y_max)
+        alpha = y_max - y_max_int
+
+        if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
+            current_pix = self.pixel[x, y_max_int + 1]
+
+            r = int((1-alpha)*current_pix[0] + alpha*color[0])
+            g = int((1-alpha)*current_pix[1] + alpha*color[1])
+            b = int((1-alpha)*current_pix[2] + alpha*color[2])
+
+            self.pixel[x, y_max_int + 1] = (r,g,b)
+
+        y_min = min(y1, y2)
+        y_min_int = int(y_min)
+        alpha = 1.0 - (y_min - y_min_int)
+
+        if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0:
+            current_pix = self.pixel[x, y_min_int - 1]
+
+            r = int((1-alpha)*current_pix[0] + alpha*color[0])
+            g = int((1-alpha)*current_pix[1] + alpha*color[1])
+            b = int((1-alpha)*current_pix[2] + alpha*color[2])
+
+            self.pixel[x, y_min_int - 1] = (r,g,b)
+
+    def process(self, frames, eod):
+        if len(frames) != 1:
+            buffer = frames[:,0].copy()
+            buffer.shape = (len(buffer),1)
+            (spectral_centroid, db_spectrum) = self.spectrum.process(buffer, True)
+            for samples, end in self.pixels_adapter.process(buffer, eod):
+                if self.pixel_cursor < self.image_width:
+                    peaks = self.peaks(samples)
+                    self.draw_peaks(self.pixel_cursor, peaks, spectral_centroid)
+                    self.pixel_cursor += 1
+
+    def save(self):
+        """ Apply last 2D transforms and write all pixels to the file. """
+
+        # middle line (0 for none)
+        a = 1
+
+        for x in range(self.image_width):
+            self.pixel[x, self.image_height/2] = tuple(map(lambda p: p+a, self.pixel[x, self.image_height/2]))
+        self.image.save(self.filename)
+
+
+class SpectrogramImage(object):
+    """ Builds a PIL image representing a spectrogram of the audio stream (level vs. frequency vs. time).
+    Adds pixels iteratively thanks to the adapter providing fixed size frame buffers."""
+
+    def __init__(self, image_width, image_height, nframes, samplerate, fft_size, bg_color=None, color_scheme='default', filename=None):
+        self.image_width = image_width
+        self.image_height = image_height
+        self.nframes = nframes
+        self.samplerate = samplerate
+        self.fft_size = fft_size
+        self.filename = filename
+        self.color_scheme = color_scheme
+
+        self.image = Image.new("P", (self.image_height, self.image_width))
+        colors = color_schemes[self.color_scheme]['spectrogram']
+        self.image.putpalette(interpolate_colors(colors, True))
+
+        self.samples_per_pixel = self.nframes / float(self.image_width)
+        self.buffer_size = int(round(self.samples_per_pixel, 0))
+        self.pixels_adapter = FixedSizeInputAdapter(self.buffer_size, 1, pad=False)
+        self.pixels_adapter_nframes = self.pixels_adapter.nframes(self.nframes)
+
+        self.lower = 100
+        self.higher = 22050
+        self.spectrum = Spectrum(self.fft_size, self.nframes, self.samplerate, self.lower, self.higher, numpy.hanning)
+
+        # generate the lookup which translates y-coordinate to fft-bin
+        self.y_to_bin = []
+        f_min = float(self.lower)
+        f_max = float(self.higher)
+        y_min = math.log10(f_min)
+        y_max = math.log10(f_max)
+        for y in range(self.image_height):
+            freq = math.pow(10.0, y_min + y / (image_height - 1.0) *(y_max - y_min))
+            bin = freq / 22050.0 * (self.fft_size/2 + 1)
+
+            if bin < self.fft_size/2:
+                alpha = bin - int(bin)
+
+                self.y_to_bin.append((int(bin), alpha * 255))
+
+        # this is a bit strange, but using image.load()[x,y] = ... is
+        # a lot slower than using image.putadata and then rotating the image
+        # so we store all the pixels in an array and then create the image when saving
+        self.pixels = []
+        self.pixel_cursor = 0
+
+    def draw_spectrum(self, x, spectrum):
+        for (index, alpha) in self.y_to_bin:
+            self.pixels.append( int( ((255.0-alpha) * spectrum[index] + alpha * spectrum[index + 1] )) )
+
+        for y in range(len(self.y_to_bin), self.image_height):
+            self.pixels.append(0)
+
+    def process(self, frames, eod):
+        if len(frames) != 1:
+            buffer = frames[:,0].copy()
+            buffer.shape = (len(buffer),1)
+
+            # FIXME : breaks spectrum linearity
+            for samples, end in self.pixels_adapter.process(buffer, eod):
+                if self.pixel_cursor < self.image_width:
+                    (spectral_centroid, db_spectrum) = self.spectrum.process(samples, True)
+                    self.draw_spectrum(self.pixel_cursor, db_spectrum)
+                    self.pixel_cursor += 1
+
+    def save(self):
+        """ Apply last 2D transforms and write all pixels to the file. """
+        self.image.putdata(self.pixels)
+        self.image.transpose(Image.ROTATE_90).save(self.filename)
+
+
+class Noise(object):
+    """A class that mimics audiolab.sndfile but generates noise instead of reading
+    a wave file. Additionally it can be told to have a "broken" header and thus crashing
+    in the middle of the file. Also useful for testing ultra-short files of 20 samples."""
+
+    def __init__(self, num_frames, has_broken_header=False):
+        self.seekpoint = 0
+        self.num_frames = num_frames
+        self.has_broken_header = has_broken_header
+
+    def seek(self, seekpoint):
+        self.seekpoint = seekpoint
+
+    def get_nframes(self):
+        return self.num_frames
+
+    def get_samplerate(self):
+        return 44100
+
+    def get_channels(self):
+        return 1
+
+    def read_frames(self, frames_to_read):
+        if self.has_broken_header and self.seekpoint + frames_to_read > self.num_frames / 2:
+            raise IOError()
+
+        num_frames_left = self.num_frames - self.seekpoint
+        if num_frames_left < frames_to_read:
+            will_read = num_frames_left
+        else:
+            will_read = frames_to_read
+        self.seekpoint += will_read
+        return numpy.random.random(will_read)*2 - 1
+
diff --git a/timeside/grapher/spectrogram.py b/timeside/grapher/spectrogram.py
new file mode 100644 (file)
index 0000000..0962842
--- /dev/null
@@ -0,0 +1,80 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2010 Guillaume Pellerin <yomguy@parisson.com>
+# Copyright (c) 2010 Olivier Guilyardi <olivier@samalyse.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+
+from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
+from timeside.api import IGrapher
+from timeside.grapher import *
+
+
+class Spectrogram(Processor):
+    implements(IGrapher)
+
+    FFT_SIZE = 0x400
+
+    @interfacedoc
+    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
+        if width:
+            self.width = width
+        else:
+            self.width = 1500
+        if height:
+            self.height = height
+        else:
+            self.height = 200
+        self.bg_color = bg_color
+        self.color_scheme = color_scheme
+        self.filename = output
+        self.graph = None
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "spectrogram"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Spectrogram"
+
+    @interfacedoc
+    def set_colors(self, background, scheme):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(Spectrogram, self).setup(channels, samplerate, nframes)
+        if self.graph:
+            self.graph = None
+        self.graph = SpectrogramImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
+                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        self.graph.process(frames, eod)
+        return frames, eod
+
+    @interfacedoc
+    def render(self):
+        if self.filename:
+            self.graph.save()
+        return self.graph.image
+
diff --git a/timeside/grapher/spectrogram_audiolab.py b/timeside/grapher/spectrogram_audiolab.py
new file mode 100644 (file)
index 0000000..be7143c
--- /dev/null
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import *
+from timeside.api import IGrapher
+from tempfile import NamedTemporaryFile
+from timeside.grapher.core import *
+
+class SpectrogramGrapherAudiolab(Processor):
+    """Spectrogram graph driver (python style thanks to wav2png.py and scikits.audiolab)"""
+
+    implements(IGrapher)
+
+    bg_color = None
+    color_scheme = None
+
+    @staticmethod
+    def id():
+        return "spectrogram"
+
+    def name(self):
+        return "Spectrogram (audiolab)"
+
+    def set_colors(self, background=None, scheme=None):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    def render(self, media_item, width=None, height=None, options=None):
+        """Generator that streams the spectrogram as a PNG image with a python method"""
+
+        wav_file = media_item
+        pngFile = NamedTemporaryFile(suffix='.png')
+
+        if not width == None:
+            image_width = width
+        else:
+            image_width = 1500
+        if not height == None:
+            image_height = height
+        else:
+            image_height = 200
+
+        fft_size = 2048
+        args = (wav_file, pngFile.name, image_width, image_height, fft_size,
+                self.bg_color, self.color_scheme)
+        create_spectrogram_png(*args)
+
+        buffer = pngFile.read(0xFFFF)
+        while buffer:
+            yield buffer
+            buffer = pngFile.read(0xFFFF)
+
+        pngFile.close()
diff --git a/timeside/grapher/waveform.py b/timeside/grapher/waveform.py
new file mode 100644 (file)
index 0000000..982192c
--- /dev/null
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2010 Guillaume Pellerin <yomguy@parisson.com>
+# Copyright (c) 2010 Olivier Guilyardi <olivier@samalyse.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+
+from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
+from timeside.api import IGrapher
+from timeside.grapher import *
+
+
+class Waveform(Processor):
+    implements(IGrapher)
+
+    FFT_SIZE = 0x400
+
+    @interfacedoc
+    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
+        if width:
+            self.width = width
+        else:
+            self.width = 1500
+        if height:
+            self.height = height
+        else:
+            self.height = 200
+        self.bg_color = bg_color
+        self.color_scheme = color_scheme
+        self.filename = output
+        self.graph = None
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "waveform"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Waveform"
+
+    @interfacedoc
+    def set_colors(self, background, scheme):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(Waveform, self).setup(channels, samplerate, nframes)
+        if self.graph:
+            self.graph = None
+        self.graph = WaveformImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
+                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        self.graph.process(frames, eod)
+        return frames, eod
+
+    @interfacedoc
+    def render(self):
+        if self.filename:
+            self.graph.save()
+        return self.graph.image
diff --git a/timeside/grapher/waveform_audiolab.py b/timeside/grapher/waveform_audiolab.py
new file mode 100644 (file)
index 0000000..ac07330
--- /dev/null
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007-2009 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+from timeside.core import *
+from timeside.api import IGrapher
+from tempfile import NamedTemporaryFile
+from timeside.grapher.core import *
+
+class WaveFormGrapherAudiolab(Processor):
+    """WaveForm graph driver (python style thanks to wav2png.py and scikits.audiolab)"""
+
+    implements(IGrapher)
+
+    bg_color = None
+    color_scheme = None
+
+    @staticmethod
+    def id():
+        return "waveform"
+
+    def name(self):
+        return "Waveform (audiolab)"
+
+    def set_colors(self, background=None, scheme=None):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    def render(self, media_item, width=None, height=None, options=None):
+        """Generator that streams the waveform as a PNG image with a python method"""
+
+        wav_file = media_item
+        pngFile = NamedTemporaryFile(suffix='.png')
+
+        if not width == None:
+            image_width = width
+        else:
+            image_width = 1500
+        if not height == None:
+            image_height = height
+        else:
+            image_height = 200
+
+        fft_size = 2048
+        args = (wav_file, pngFile.name, image_width, image_height, fft_size,
+                self.bg_color, self.color_scheme)
+        create_wavform_png(*args)
+
+        buffer = pngFile.read(0xFFFF)
+        while buffer:
+            yield buffer
+            buffer = pngFile.read(0xFFFF)
+
+        pngFile.close()
+
diff --git a/timeside/metadata.py b/timeside/metadata.py
new file mode 100644 (file)
index 0000000..86abf87
--- /dev/null
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2009 Parisson
+# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
+# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+class Metadata(object):
+    pass
+        
+        
diff --git a/timeside/tests/__init__.py b/timeside/tests/__init__.py
new file mode 100644 (file)
index 0000000..2a6b9db
--- /dev/null
@@ -0,0 +1,140 @@
+
+import unittest
+import sys
+import time
+
+class TestCase(unittest.TestCase):
+
+    def assertSameList(self, list1, list2):
+        "Test that two lists contain the same elements, in any order"
+        if len(list1) != len(list2):
+            self.fail("Lists length differ : %d != %d" % (len(list1), len(list2)))
+
+        for item in list1:
+            if not item in list2:
+                self.fail("%s is not in list2" % str(item))
+
+        for item in list2:
+            if not item in list1:
+                self.fail("%s is not in list1" % str(item))
+        
+class _TextTestResult(unittest.TestResult):
+    """A test result class that can print formatted text results to a stream.
+
+    Used by TextTestRunner.
+    """
+    separator1 = '=' * 70
+    separator2 = '-' * 70
+
+    def __init__(self, stream, descriptions, verbosity):
+        unittest.TestResult.__init__(self)
+        self.stream = stream
+        self.showAll = verbosity > 1
+        self.dots = verbosity == 1
+        self.descriptions = descriptions
+        self.currentTestCase = None
+
+    def getDescription(self, test):
+        if self.descriptions:
+            return test.shortDescription() or str(test)
+        else:
+            return str(test)
+
+    def startTest(self, test):
+        unittest.TestResult.startTest(self, test)
+        if self.showAll:
+            if self.currentTestCase != test.__class__:
+                self.currentTestCase = test.__class__
+                self.stream.writeln()
+                self.stream.writeln("[%s]" % self.currentTestCase.__name__)
+            self.stream.write("  " + self.getDescription(test))
+            self.stream.write(" ... ")
+
+    def addSuccess(self, test):
+        unittest.TestResult.addSuccess(self, test)
+        if self.showAll:
+            self.stream.writeln("ok")
+        elif self.dots:
+            self.stream.write('.')
+
+    def addError(self, test, err):
+        unittest.TestResult.addError(self, test, err)
+        if self.showAll:
+            self.stream.writeln("ERROR")
+        elif self.dots:
+            self.stream.write('E')
+
+    def addFailure(self, test, err):
+        unittest.TestResult.addFailure(self, test, err)
+        if self.showAll:
+            self.stream.writeln("FAIL")
+        elif self.dots:
+            self.stream.write('F')
+
+    def printErrors(self):
+        if self.dots or self.showAll:
+            self.stream.writeln()
+        self.printErrorList('ERROR', self.errors)
+        self.printErrorList('FAIL', self.failures)
+
+    def printErrorList(self, flavour, errors):
+        for test, err in errors:
+            self.stream.writeln(self.separator1)
+            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
+            self.stream.writeln(self.separator2)
+            self.stream.writeln("%s" % err)
+
+
+class _WritelnDecorator:
+    """Used to decorate file-like objects with a handy 'writeln' method"""
+    def __init__(self,stream):
+        self.stream = stream
+
+    def __getattr__(self, attr):
+        return getattr(self.stream,attr)
+
+    def writeln(self, arg=None):
+        if arg: self.write(arg)
+        self.write('\n') # text-mode streams translate to \r\n if needed
+
+class TestRunner:
+    """A test runner class that displays results in textual form.
+
+    It prints out the names of tests as they are run, errors as they
+    occur, and a summary of the results at the end of the test run.
+    """
+    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=2):
+        self.stream = _WritelnDecorator(stream)
+        self.descriptions = descriptions
+        self.verbosity = verbosity
+
+    def _makeResult(self):
+        return _TextTestResult(self.stream, self.descriptions, self.verbosity)
+
+    def run(self, test):
+        "Run the given test case or test suite."
+        result = self._makeResult()
+        startTime = time.time()
+        test(result)
+        stopTime = time.time()
+        timeTaken = stopTime - startTime
+        result.printErrors()
+        self.stream.writeln(result.separator2)
+        run = result.testsRun
+        self.stream.writeln("Ran %d test%s in %.3fs" %
+                            (run, run != 1 and "s" or "", timeTaken))
+        self.stream.writeln()
+        if not result.wasSuccessful():
+            self.stream.write("FAILED (")
+            failed, errored = map(len, (result.failures, result.errors))
+            if failed:
+                self.stream.write("failures=%d" % failed)
+            if errored:
+                if failed: self.stream.write(", ")
+                self.stream.write("errors=%d" % errored)
+            self.stream.writeln(")")
+        else:
+            self.stream.writeln("OK")
+        return result
+
+
diff --git a/timeside/tests/alltests.py b/timeside/tests/alltests.py
new file mode 100644 (file)
index 0000000..e368939
--- /dev/null
@@ -0,0 +1,5 @@
+from timeside.tests.testcomponent import *
+from timeside.tests.testinputadapter import *
+from timeside.tests import TestRunner
+
+unittest.main(testRunner=TestRunner())
diff --git a/timeside/tests/api/__init__.py b/timeside/tests/api/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/timeside/tests/api/examples.py b/timeside/tests/api/examples.py
new file mode 100644 (file)
index 0000000..418d2ca
--- /dev/null
@@ -0,0 +1,379 @@
+# -*- coding: utf-8 -*-
+from timeside.core import Processor, implements, interfacedoc, FixedSizeInputAdapter
+from timeside.api import *
+from timeside.grapher import *
+from timeside import Metadata
+from scikits import audiolab
+import numpy
+
+class FileDecoder(Processor):
+    """A simple audiolab-based example decoder"""
+    implements(IDecoder)
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_audiolabdec"
+
+    @interfacedoc
+    def __init__(self, filename):
+        self.filename = filename
+        # The file has to be opened here so that nframes(), samplerate(),
+        # etc.. work before setup() is called.
+        self.file     = audiolab.Sndfile(self.filename, 'r')
+        self.position = 0
+
+    @interfacedoc
+    def setup(self):
+        super(FileDecoder, self).setup()
+        if self.position != 0:
+            self.file.seek(0);
+            self.position = 0
+
+    def release(self):
+        super(FileDecoder, self).release()
+        if self.file:
+            self.file.close()
+            self.file = None
+
+    @interfacedoc
+    def channels(self):
+        return self.file.channels
+
+    @interfacedoc
+    def samplerate(self):
+        return self.file.samplerate
+
+    @interfacedoc
+    def nframes(self):
+        return self.file.nframes
+
+    @interfacedoc
+    def format(self):
+        return self.file.file_format
+
+    @interfacedoc
+    def encoding(self):
+        return self.file.encoding
+    @interfacedoc
+    def resolution(self):
+        resolution = None
+        encoding = self.file.encoding
+
+        if encoding == "pcm8":
+            resolution = 8
+
+        elif encoding == "pcm16":
+            resolution = 16
+        elif encoding == "pcm32":
+            resolution = 32
+
+        return resolution
+
+    @interfacedoc
+    def metadata(self):
+        #TODO
+        return Metadata()
+
+    @interfacedoc
+    def process(self, frames=None, eod=False):
+        if frames:
+            raise Exception("Decoder doesn't accept input frames")
+
+        buffersize = 0x10000
+
+        # Need this because audiolab raises a bogus exception when asked
+        # to read passed the end of the file
+        toread = self.nframes() - self.position
+        if toread > buffersize:
+            toread = buffersize
+
+        frames         = self.file.read_frames(toread)
+        eod            = (toread < buffersize)
+        self.position += toread
+
+        # audiolab returns a 1D array for 1 channel, need to reshape to 2D:
+        if frames.ndim == 1:
+            frames = frames.reshape(len(frames), 1)
+
+        return frames, eod
+
+class MaxLevel(Processor):
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(MaxLevel, self).setup(channels, samplerate, nframes)
+        self.max_value = 0
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_maxlevel"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Max level test analyzer"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        # power? amplitude?
+        return ""
+
+    def process(self, frames, eod=False):
+        max = frames.max()
+        if max > self.max_value:
+            self.max_value = max
+
+        return frames, eod
+
+    def result(self):
+        return self.max_value
+
+class Gain(Processor):
+    implements(IEffect)
+
+    @interfacedoc
+    def __init__(self, gain=1.0):
+        self.gain = gain
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_gain"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Gain test effect"
+
+    def process(self, frames, eod=False):
+        return numpy.multiply(frames, self.gain), eod
+
+class WavEncoder(Processor):
+    implements(IEncoder)
+
+    def __init__(self, output):
+        self.file = None
+        if isinstance(output, basestring):
+            self.filename = output
+        else:
+            raise Exception("Streaming not supported")
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(WavEncoder, self).setup(channels, samplerate, nframes)
+        if self.file:
+            self.file.close()
+
+        format = audiolab.Format("wav", "pcm16")
+        self.file = audiolab.Sndfile(self.filename, 'w', format=format, channels=channels,
+                                     samplerate=samplerate)
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_wavenc"
+
+    @staticmethod
+    @interfacedoc
+    def description():
+        return "Hackish wave encoder"
+
+    @staticmethod
+    @interfacedoc
+    def file_extension():
+        return "wav"
+
+    @staticmethod
+    @interfacedoc
+    def mime_type():
+        return "audio/x-wav"
+
+    @interfacedoc
+    def set_metadata(self, metadata):
+        #TODO
+        pass
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        self.file.write_frames(frames)
+        if eod:
+            self.file.close()
+            self.file = None
+
+        return frames, eod
+
+
+class Waveform(Processor):
+    implements(IGrapher)
+
+    FFT_SIZE = 0x400
+
+    @interfacedoc
+    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
+        if width:
+            self.width = width
+        else:
+            self.width = 1500
+        if height:
+            self.height = height
+        else:
+            self.height = 200
+        self.bg_color = bg_color
+        self.color_scheme = color_scheme
+        self.filename = output
+        self.graph = None
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_waveform"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Waveform test"
+
+    @interfacedoc
+    def set_colors(self, background, scheme):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(Waveform, self).setup(channels, samplerate, nframes)
+        if self.graph:
+            self.graph = None
+        self.graph = WaveformImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
+                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        self.graph.process(frames, eod)
+        return frames, eod
+
+    @interfacedoc
+    def render(self):
+        if self.filename:
+            self.graph.save()
+        return self.graph.image
+
+
+class Spectrogram(Processor):
+    implements(IGrapher)
+
+    FFT_SIZE = 0x400
+
+    @interfacedoc
+    def __init__(self, width=None, height=None, output=None, bg_color=None, color_scheme=None):
+        if width:
+            self.width = width
+        else:
+            self.width = 1500
+        if height:
+            self.height = height
+        else:
+            self.height = 200
+        self.bg_color = bg_color
+        self.color_scheme = color_scheme
+        self.filename = output
+        self.graph = None
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_spectrogram"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Spectrogram test"
+
+    @interfacedoc
+    def set_colors(self, background, scheme):
+        self.bg_color = background
+        self.color_scheme = scheme
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(Spectrogram, self).setup(channels, samplerate, nframes)
+        if self.graph:
+            self.graph = None
+        self.graph = SpectrogramImage(self.width, self.height, self.nframes(), self.samplerate(), self.FFT_SIZE,
+                                    bg_color=self.bg_color, color_scheme=self.color_scheme, filename=self.filename)
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        self.graph.process(frames, eod)
+        return frames, eod
+
+    @interfacedoc
+    def render(self):
+        if self.filename:
+            self.graph.save()
+        return self.graph.image
+
+
+class Duration(Processor):
+    """A rather useless duration analyzer. Its only purpose is to test the
+       nframes characteristic."""
+    implements(IValueAnalyzer)
+
+    @interfacedoc
+    def setup(self, channels, samplerate, nframes):
+        if not nframes:
+            raise Exception("nframes argument required")
+        super(Duration, self).setup(channels, samplerate, nframes)
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_duration"
+
+    @staticmethod
+    @interfacedoc
+    def name():
+        return "Duration analyzer"
+
+    @staticmethod
+    @interfacedoc
+    def unit():
+        return "seconds"
+
+    def result(self):
+        return self.input_nframes / float(self.input_samplerate)
+
+class FixedInputProcessor(Processor):
+    """Processor which does absolutely nothing except illustrating the use
+    of the FixedInputSizeAdapter. It also tests things a bit."""
+
+    implements(IProcessor)
+
+    BUFFER_SIZE = 1024
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_fixed"
+
+    @interfacedoc
+    def setup(self, channels, samplerate, nframes):
+        super(FixedInputProcessor, self).setup(channels, samplerate, nframes)
+        self.adapter = FixedSizeInputAdapter(self.BUFFER_SIZE, channels, pad=True)
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        for buffer, end in self.adapter.process(frames, eod):
+            # Test that the adapter is actually doing the job:
+            if len(buffer) != self.BUFFER_SIZE:
+                raise Exception("Bad buffer size from adapter")
+
+        return frames, eod
+
+
+
+
+
diff --git a/timeside/tests/api/gstreamer.py b/timeside/tests/api/gstreamer.py
new file mode 100644 (file)
index 0000000..897ac42
--- /dev/null
@@ -0,0 +1,238 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2009 Parisson
+# Copyright (c) 2007 Olivier Guilyardi <olivier@samalyse.com>
+# Copyright (c) 2007-2009 Guillaume Pellerin <pellerin@parisson.com>
+#
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Paul Brossier <piem@piem.org>
+
+from timeside.core import Processor, implements, interfacedoc
+from timeside.api import IDecoder, IEncoder
+from numpy import array, frombuffer, getbuffer, float32
+
+import pygst
+pygst.require('0.10')
+import gst
+import gobject
+gobject.threads_init ()
+
+class FileDecoder(Processor):
+    """ gstreamer-based decoder """
+    implements(IDecoder)
+
+    # duration ms, before discovery process times out
+    MAX_DISCOVERY_TIME = 3000
+
+    audioformat = None
+    audiochannels = None
+    audiorate = None
+    audionframes = None
+    mimetype = ''
+
+    # IProcessor methods
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_gstreamerdec"
+
+    def setup(self, channels = None, samplerate = None, nframes = None):
+        # the output data format we want
+        caps = "audio/x-raw-float, width=32"
+        pipeline = gst.parse_launch('''uridecodebin uri=%s
+            ! audioconvert
+            ! %s
+            ! appsink name=sink sync=False ''' % (self.uri, caps))
+        # store a pointer to appsink in our decoder object 
+        self.sink = pipeline.get_by_name('sink')
+        # adjust length of emitted buffers
+        # self.sink.set_property('blocksize', 0x10000)
+        # start pipeline
+        pipeline.set_state(gst.STATE_PLAYING)
+
+    @interfacedoc
+    def channels(self):
+        return  self.audiochannels
+
+    @interfacedoc
+    def samplerate(self):
+        return self.audiorate 
+
+    @interfacedoc
+    def nframes(self):
+        return self.audionframes
+
+    @interfacedoc
+    def process(self, frames = None, eod = False):
+        try:
+            buf = self.sink.emit('pull-buffer')
+        except SystemError, e:
+            # should never happen
+            print 'SystemError', e
+            return array([0.]), True
+        if buf == None:
+            return array([0.]), True
+        return self.gst_buffer_to_numpy_array(buf), False
+
+    @interfacedoc
+    def release(self):
+        # nothing to do for now 
+        pass
+
+    ## IDecoder methods
+
+    @interfacedoc
+    def __init__(self, uri):
+
+        # is this a file? 
+        import os.path
+        if os.path.exists(uri):
+            # get the absolute path
+            uri = os.path.abspath(uri)
+            # first run the file/uri through the discover pipeline
+            self.discover(uri)
+            # and make a uri of it
+            from urllib import quote
+            self.uri = 'file://'+quote(uri)
+
+    @interfacedoc
+    def format(self):
+        # TODO check
+        return self.mimetype
+
+    @interfacedoc
+    def encoding(self):
+        # TODO check
+        return self.mimetype.split('/')[-1]
+
+    @interfacedoc
+    def resolution(self):
+        # TODO check: width or depth?
+        return self.audiowidth 
+
+    @interfacedoc
+    def metadata(self):
+        # TODO check
+        return self.tags
+
+    ## gst.extend discoverer
+
+    def discover(self, path):
+        """ gstreamer based helper function to get file attributes """
+        from gst.extend import discoverer
+        d = discoverer.Discoverer(path, timeout = self.MAX_DISCOVERY_TIME)
+        d.connect('discovered', self.discovered)
+        self.mainloop = gobject.MainLoop()
+        d.discover()
+        self.mainloop.run()
+
+    def discovered(self, d, is_media):
+        """ gstreamer based helper executed upon discover() completion """
+        if is_media and d.is_audio:
+            # copy the discoverer attributes to self
+            self.audiorate = d.audiorate
+            self.mimetype= d.mimetype
+            self.audiochannels = d.audiochannels
+            self.audiowidth = d.audiowidth
+            # conversion from time in nanoseconds to frames 
+            from math import ceil
+            duration = d.audiorate * d.audiolength * 1.e-9
+            self.audionframes = int (ceil ( duration ) )
+            self.tags = d.tags
+        elif not d.is_audio:
+            print "error, no audio found!"
+        else:
+            print "fail", path
+        self.mainloop.quit()
+
+    def gst_buffer_to_numpy_array(self, buf):
+        """ gstreamer buffer to numpy array conversion """
+        chan = self.audiochannels
+        samples = frombuffer(buf.data, dtype=float32) 
+        samples.resize([len(samples)/chan, chan])
+        return samples
+
+class WavEncoder(Processor):
+    """ gstreamer-based encoder """
+    implements(IEncoder)
+
+    def __init__(self, output):
+        self.file = None
+        if isinstance(output, basestring):
+            self.filename = output
+        else:
+            raise Exception("Streaming not supported")
+
+    @interfacedoc
+    def setup(self, channels=None, samplerate=None, nframes=None):
+        super(WavEncoder, self).setup(channels, samplerate, nframes)
+        # TODO open file for writing
+        # the output data format we want
+        pipeline = gst.parse_launch(''' appsrc name=src
+            ! audioconvert
+            ! wavenc
+            ! filesink location=%s ''' % self.filename)
+        # store a pointer to appsink in our encoder object 
+        self.src = pipeline.get_by_name('src')
+        srccaps = gst.Caps("""audio/x-raw-float,
+            endianness=(int)1234,
+            channels=(int)%s,
+            width=(int)32,
+            rate=(int)%d""" % (int(channels), int(samplerate)))
+        self.src.set_property("caps", srccaps)
+
+        # start pipeline
+        pipeline.set_state(gst.STATE_PLAYING)
+        self.pipeline = pipeline
+
+    @staticmethod
+    @interfacedoc
+    def id():
+        return "test_gstreamerenc"
+
+    @staticmethod
+    @interfacedoc
+    def description():
+        return "Gstreamer based encoder"
+
+    @staticmethod
+    @interfacedoc
+    def file_extension():
+        return "wav"
+
+    @staticmethod
+    @interfacedoc
+    def mime_type():
+        return "audio/x-wav"
+
+    @interfacedoc
+    def set_metadata(self, metadata):
+        #TODO
+        pass
+
+    @interfacedoc
+    def process(self, frames, eod=False):
+        buf = self.numpy_array_to_gst_buffer(frames)
+        self.src.emit('push-buffer', buf)
+        if eod: self.src.emit('end-of-stream')
+        return frames, eod
+
+    def numpy_array_to_gst_buffer(self, frames):
+        """ gstreamer buffer to numpy array conversion """
+        buf = gst.Buffer(getbuffer(frames))
+        return buf
diff --git a/timeside/tests/api/test_lolevel.py b/timeside/tests/api/test_lolevel.py
new file mode 100644 (file)
index 0000000..786b141
--- /dev/null
@@ -0,0 +1,60 @@
+from timeside.tests.api import examples
+
+use_gst = 0
+if use_gst:
+    from timeside.tests.api.gstreamer import FileDecoder, WavEncoder
+else:
+    from timeside.tests.api.examples import FileDecoder, WavEncoder
+
+import sys
+if len(sys.argv) > 1:
+    source = sys.argv[1]
+else:
+    import os.path
+    source= os.path.join (os.path.dirname(__file__),  "../samples/guitar.wav")
+
+Decoder = FileDecoder
+print "Creating decoder with id=%s for: %s" % (Decoder.id(), source)
+decoder    = Decoder(source)
+analyzer = examples.MaxLevel()
+decoder.setup()
+nchannels  = decoder.channels()
+samplerate = decoder.samplerate()
+nframes = decoder.nframes()
+analyzer.setup(nchannels, samplerate)
+
+print "Stats: duration=%f, nframes=%d, nchannels=%d, samplerate=%d, resolution=%d" % (
+        nframes / float(samplerate), nframes, nchannels, samplerate, decoder.resolution())
+
+while True:
+    frames, eod = decoder.process()
+    analyzer.process(frames, eod)
+    if eod:
+        break
+
+max_level = analyzer.result()
+print "Max level: %f" % max_level
+
+destination = "normalized.wav"
+Encoder = WavEncoder
+print "Creating encoder with id=%s for: %s" % (Encoder.id(), destination)
+encoder = Encoder(destination)
+
+gain = 1
+if max_level > 0:
+    gain = 0.9 / max_level
+
+effect = examples.Gain(gain)
+
+decoder.setup()
+effect.setup(decoder.channels(), decoder.samplerate())
+encoder.setup(effect.channels(), effect.samplerate())
+
+print "Applying effect id=%s with gain=%f" % (effect.id(), gain)
+
+while True:
+    frames, eod = decoder.process()
+    encoder.process(*effect.process(frames, eod))
+    if eod:
+        break
+
diff --git a/timeside/tests/api/test_pipe.py b/timeside/tests/api/test_pipe.py
new file mode 100644 (file)
index 0000000..eaa0850
--- /dev/null
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+from timeside.tests.api.examples import Gain
+from timeside.core import *
+from timeside.decoder import *
+from timeside.analyzer import *
+from timeside.encoder import *
+from timeside.api import *
+from sys import stdout
+
+import os.path
+source = os.path.join(os.path.dirname(__file__),  "../samples/guitar.wav")
+
+print "Normalizing %s" % source
+decoder  = FileDecoder(source)
+maxlevel = MaxLevel()
+duration = Duration()
+
+(decoder | maxlevel | duration).run()
+
+gain = 1
+if maxlevel.result() > 0:
+    gain = 0.9 / maxlevel.result()
+
+print "input maxlevel: %f" % maxlevel.result()
+print "gain: %f" % gain
+print "duration: %f %s" % (duration.result(), duration.unit())
+
+gain     = Gain(gain)
+encoder  = WavEncoder("normalized.wav")
+
+subpipe  = gain | maxlevel
+
+(decoder | subpipe | encoder).run()
+
+print "output maxlevel: %f" % maxlevel.result()
+
+
diff --git a/timeside/tests/api/test_pipe_spectrogram.py b/timeside/tests/api/test_pipe_spectrogram.py
new file mode 100644 (file)
index 0000000..5ba90eb
--- /dev/null
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+
+import os
+from timeside.core import *
+from timeside.api import *
+from timeside.decoder import *
+from timeside.grapher import *
+
+image_file = '../results/img/spectrogram.png'
+source = os.path.join(os.path.dirname(__file__), "../samples/sweep.wav")
+
+decoder  = FileDecoder(source)
+spectrogram = Spectrogram(width=1024, height=256, output=image_file, bg_color=(0,0,0), color_scheme='default')
+
+(decoder | spectrogram).run()
+
+print 'frames per pixel = ', spectrogram.graph.samples_per_pixel
+print "render spectrogram to: %s" % image_file
+spectrogram.render()
+
+
diff --git a/timeside/tests/api/test_pipe_waveform.py b/timeside/tests/api/test_pipe_waveform.py
new file mode 100644 (file)
index 0000000..d21ecdc
--- /dev/null
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+
+import os
+from timeside.core import *
+from timeside.api import *
+from timeside.decoder import *
+from timeside.grapher import *
+
+sample_dir = '../samples'
+img_dir = '../results/img'
+if not os.path.exists(img_dir):
+    os.mkdir(img_dir)
+
+test_dict = {'sweep.wav': 'waveform_wav.png',
+            'sweep.flac': 'waveform_flac.png',
+            'sweep.ogg': 'waveform_ogg.png',
+            'sweep.mp3': 'waveform_mp3.png',
+            }
+
+for source, image in test_dict.iteritems():
+    audio = os.path.join(os.path.dirname(__file__), sample_dir + os.sep + source)
+    image = img_dir + os.sep + image
+    print 'Test : decoder(%s) | waveform (%s)' % (source, image)
+    decoder  = FileDecoder(audio)
+    waveform = Waveform(width=1024, height=256, output=image, bg_color=(0,0,0), color_scheme='default')
+    (decoder | waveform).run()
+    print 'frames per pixel = ', waveform.graph.samples_per_pixel
+    print "render waveform to: %s" %  image
+    waveform.render()
+
+
diff --git a/timeside/tests/listprocessors.py b/timeside/tests/listprocessors.py
new file mode 100644 (file)
index 0000000..840c087
--- /dev/null
@@ -0,0 +1,12 @@
+import timeside
+
+def list_processors(interface, prefix=""):
+    print prefix + interface.__name__
+    subinterfaces = interface.__subclasses__()
+    for i in subinterfaces:
+        list_processors(i, prefix + "  ")
+    processors = timeside.processors(interface, False)
+    for p in processors:
+        print prefix + "  %s [%s]" % (p.__name__, p.id())
+
+list_processors(timeside.api.IProcessor)        
diff --git a/timeside/tests/samples/guitar.wav b/timeside/tests/samples/guitar.wav
new file mode 100644 (file)
index 0000000..b5a9e80
Binary files /dev/null and b/timeside/tests/samples/guitar.wav differ
diff --git a/timeside/tests/samples/sweep.flac b/timeside/tests/samples/sweep.flac
new file mode 100644 (file)
index 0000000..decee06
Binary files /dev/null and b/timeside/tests/samples/sweep.flac differ
diff --git a/timeside/tests/samples/sweep.mp3 b/timeside/tests/samples/sweep.mp3
new file mode 100644 (file)
index 0000000..dc75fe0
Binary files /dev/null and b/timeside/tests/samples/sweep.mp3 differ
diff --git a/timeside/tests/samples/sweep.ogg b/timeside/tests/samples/sweep.ogg
new file mode 100644 (file)
index 0000000..e30bf99
Binary files /dev/null and b/timeside/tests/samples/sweep.ogg differ
diff --git a/timeside/tests/samples/sweep.wav b/timeside/tests/samples/sweep.wav
new file mode 100644 (file)
index 0000000..fc28a32
Binary files /dev/null and b/timeside/tests/samples/sweep.wav differ
diff --git a/timeside/tests/samples/sweep_source.wav b/timeside/tests/samples/sweep_source.wav
new file mode 100644 (file)
index 0000000..5dcf9ba
Binary files /dev/null and b/timeside/tests/samples/sweep_source.wav differ
diff --git a/timeside/tests/testcomponent.py b/timeside/tests/testcomponent.py
new file mode 100644 (file)
index 0000000..6638c30
--- /dev/null
@@ -0,0 +1,166 @@
+
+from timeside.component import *
+from timeside.tests import TestCase, TestRunner
+import unittest
+
+__all__ = ['TestComponentArchitecture']
+
+class TestComponentArchitecture(TestCase):
+    "Test the component and interface system"
+   
+    def testOneInterface(self):
+        "Test a component implementing one interface"
+        self.assertSameList(implementations(I1), [C1])
+
+    def testTwoInterfaces(self):        
+        "Test a component implementing two interfaces"
+        self.assertSameList(implementations(I2), [C2])
+        self.assertSameList(implementations(I3), [C2])
+
+    def testTwoImplementations(self):
+        "Test an interface implemented by two components"
+        self.assertSameList(implementations(I4), [C3, C4])
+
+    def testInterfaceInheritance(self):
+        "Test whether a component implements an interface's parent"
+        self.assertSameList(implementations(I5), [C5])
+
+    def testImplementationInheritance(self):
+        "Test that a component doesn't implement the interface implemented by its parent" 
+        self.assertSameList(implementations(I7), [C6])
+
+    def testImplementationRedundancy(self):
+        "Test implementation redundancy across inheritance" 
+        self.assertSameList(implementations(I8), [C8, C9])
+
+    def testAbstractImplementation(self):    
+        "Test abstract implementation"
+        self.assertSameList(implementations(I11), [])
+        self.assertSameList(implementations(I11, abstract=True), [C11])
+
+    def testInterfaceDoc(self):        
+        "Test @interfacedoc decorator"
+        self.assertEquals(C10.test.__doc__, "testdoc")
+
+    def testInterfaceDocStatic(self):        
+        "Test @interfacedoc decorator on static method"
+        self.assertEquals(C10.teststatic.__doc__, "teststaticdoc")
+
+    def testIntefaceDocReversed(self):
+        "Test @interfacedoc on static method (decorators reversed)"
+
+        try:
+
+            class BogusDoc1(Component):
+                implements(I10)
+
+                @interfacedoc
+                @staticmethod        
+                def teststatic(self):
+                    pass
+
+            self.fail("No error raised with reversed decorators")
+
+        except ComponentError:
+            pass
+   
+    def testInterfaceDocBadMethod(self):
+        "Test @interfacedoc with unexistant method in interface"
+
+        try:
+            class BogusDoc2(Component):
+                implements(I10)
+
+                @interfacedoc
+                def nosuchmethod(self):
+                    pass
+
+            self.fail("No error raised when decorating an unexistant method")
+
+        except ComponentError:
+            pass
+
+class I1(Interface):
+    pass
+
+class I2(Interface):
+    pass
+
+class I3(Interface):
+    pass
+
+class I4(Interface):
+    pass
+
+class I5(Interface):
+    pass
+
+class I6(I5):
+    pass
+
+class I7(Interface):
+    pass
+
+class I8(Interface):
+    pass
+
+class I9(I8):
+    pass
+
+class I10(Interface):
+    def test(self):
+        """testdoc"""
+
+    @staticmethod        
+    def teststatic(self):
+        """teststaticdoc"""
+
+class I11(Interface):
+    pass
+
+class C1(Component):
+    implements(I1)
+
+class C2(Component):
+    implements(I2, I3)
+
+class C3(Component):
+    implements(I4)
+
+class C4(Component):
+    implements(I4)
+
+class C5(Component):
+    implements(I6)
+
+class C6(Component):
+    implements(I7)
+
+class C7(C6):
+    pass
+
+class C8(Component):
+    implements(I8)
+
+class C9(Component):
+    implements(I8, I9)
+
+class C10(Component):
+    implements(I10)
+
+    @interfacedoc
+    def test(self):
+        pass
+
+    @staticmethod        
+    @interfacedoc
+    def teststatic(self):
+        pass
+
+class C11(Component):
+    abstract()
+    implements(I11)
+
+if __name__ == '__main__':
+    unittest.main(testRunner=TestRunner())
+
diff --git a/timeside/tests/testinputadapter.py b/timeside/tests/testinputadapter.py
new file mode 100644 (file)
index 0000000..dca0f63
--- /dev/null
@@ -0,0 +1,71 @@
+from timeside.core import FixedSizeInputAdapter
+from timeside.tests import TestCase, TestRunner
+import numpy
+import unittest
+
+class TestFixedSizeInputAdapter(TestCase):
+    "Test the fixed-sized input adapter"
+
+    def assertIOEquals(self, adapter, input, input_eod, output, output_eod=None):
+        output = output[:]
+        output.reverse()
+        _eod = None
+        for buffer, _eod in adapter.process(input, input_eod):
+            a = output.pop()
+            if not numpy.array_equiv(buffer, a):
+                self.fail("\n-- Actual --\n%s\n -- Expected -- \n%s\n" % (str(buffer), str(a)))
+
+        if _eod != output_eod:
+            self.fail("eod do not match: %s != %s", (str(_eod), str(output_eod)))
+
+        if output:
+            self.fail("trailing expected data: %s" % output)
+
+    def setUp(self):
+        self.data = numpy.arange(44).reshape(2,22).transpose()
+
+    def testTwoChannels(self):
+        "Test simple stream with two channels"
+        adapter = FixedSizeInputAdapter(4, 2)
+
+        self.assertEquals(len(self.data), adapter.nframes(len(self.data)))
+
+        self.assertIOEquals(adapter, self.data[0:1], False, [])
+        self.assertIOEquals(adapter, self.data[1:5], False, [self.data[0:4]], False)
+        self.assertIOEquals(adapter, self.data[5:12], False, [self.data[4:8], self.data[8:12]], False)
+        self.assertIOEquals(adapter, self.data[12:13], False, [])
+        self.assertIOEquals(adapter, self.data[13:14], False, [])
+        self.assertIOEquals(adapter, self.data[14:18], False, [self.data[12:16]], False)
+        self.assertIOEquals(adapter, self.data[18:20], False, [self.data[16:20]], False)
+        self.assertIOEquals(adapter, self.data[20:21], False, [])
+        self.assertIOEquals(adapter, self.data[21:22], True, [self.data[20:22]], True)
+
+    def testPadding(self):
+        "Test automatic padding support"
+        adapter = FixedSizeInputAdapter(4, 2, pad=True)
+
+        self.assertEquals(len(self.data) + 2, adapter.nframes(len(self.data)))
+
+        self.assertIOEquals(adapter, self.data[0:21], False, 
+            [self.data[0:4], self.data[4:8], self.data[8:12], self.data[12:16], self.data[16:20]], 
+            False)
+
+        self.assertIOEquals(adapter, self.data[21:22], True, [[
+            [20, 42],
+            [21, 43],
+            [0, 0],
+            [0, 0]
+        ]], True)
+
+    def testSizeMultiple(self):
+        "Test a stream which contain a multiple number of buffers"
+        adapter = FixedSizeInputAdapter(4, 2)
+
+        self.assertIOEquals(adapter, self.data[0:20], True, 
+            [self.data[0:4], self.data[4:8], self.data[8:12], self.data[12:16], self.data[16:20]], 
+            True)
+
+
+if __name__ == '__main__':
+    unittest.main(testRunner=TestRunner())
+
diff --git a/timeside/tools/grapher_scheme.py b/timeside/tools/grapher_scheme.py
new file mode 100644 (file)
index 0000000..4549767
--- /dev/null
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+
+class GrapherScheme:
+
+    def __init__(self):
+
+        self.color_scheme = {
+            'waveform': [
+                        (50,0,200), (0,220,80), (255,224,0), (255,0,0)
+                        ],
+            'spectrogram': [
+                        (0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100), (224,224,44), (255,60,30), (255,255,255)
+                           ]}
+
+        self.width = 2048
+        self.height = 128
+        self.bg_color = (255,255,255)
+        self.force = True
+
diff --git a/timeside/tools/waveform_batch.py b/timeside/tools/waveform_batch.py
new file mode 100644 (file)
index 0000000..bba5036
--- /dev/null
@@ -0,0 +1,93 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2009-2010 Guillaume Pellerin <yomguy@parisson.com>
+
+# This file is part of TimeSide.
+
+# TimeSide 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 2 of the License, or
+# (at your option) any later version.
+
+# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
+
+# Author: Guillaume Pellerin <yomguy@parisson.com>
+
+version = '0.1-beta'
+
+import os
+import sys
+from timeside.core import *
+from timeside.decoder import *
+from timeside.grapher import *
+from grapher_scheme import *
+
+
+class Media2Waveform(object):
+
+    def __init__(self, media_dir, img_dir):
+        self.root_dir = media_dir
+        self.img_dir = img_dir
+        self.scheme = GrapherScheme()
+        self.width = self.scheme.width
+        self.height = self.scheme.height
+        self.bg_color = self.scheme.bg_color
+        self.color_scheme = self.scheme.color_scheme
+        self.force = self.scheme.force
+
+        self.media_list = self.get_media_list()
+        if not os.path.exists(self.img_dir):
+            os.mkdir(self.img_dir)
+        self.path_dict = self.get_path_dict()
+
+    def get_media_list(self):
+        media_list = []
+        for root, dirs, files in os.walk(self.root_dir):
+            if root:
+                for file in files:
+                    ext = file.split('.')[-1]
+                    if ext == 'mp3' or ext == 'MP3':
+                        media_list.append(root+os.sep+file)
+        return media_list
+
+    def get_path_dict(self):
+        path_dict = {}
+        for media in self.media_list:
+            name = os.path.splitext(media)
+            name = name[0].split(os.sep)[-1]
+            path_dict[media] = self.img_dir + os.sep + name + '.png'
+        return path_dict
+
+    def process(self):
+        for source, image in self.path_dict.iteritems():
+            if not os.path.exists(image) or self.force:
+                print 'Rendering ', source, ' to ', image, '...'
+                audio = os.path.join(os.path.dirname(__file__), source)
+                decoder  = FileDecoder(audio)
+                waveform = Waveform(width=self.width, height=self.height, output=image,
+                                            bg_color=self.bg_color, color_scheme=self.color_scheme)
+                (decoder | waveform).run()
+                print 'frames per pixel = ', waveform.graph.samples_per_pixel
+                waveform.render()
+
+
+if __name__ == '__main__':
+    if len(sys.argv) <= 2:
+        print """
+        Usage : python waveform_batch.py /path/to/media_dir /path/to/img_dir
+
+        Dependencies : timeside, python, python-numpy, python-gst0.10, gstreamer0.10-plugins-base
+        See http://code.google.com/p/timeside/ for more information.
+        """
+    else:
+        media_dir = sys.argv[-2]
+        img_dir = sys.argv[-1]
+        m = Media2Waveform(media_dir, img_dir)
+        m.process()
diff --git a/timeside/ui/README b/timeside/ui/README
new file mode 100644 (file)
index 0000000..0f9d21d
--- /dev/null
@@ -0,0 +1,20 @@
+===============================
+TimeSide - Web Audio Components
+===============================
+
+TimeSide UI Dependencies
+========================
+
+* SoundManager 2 >= 2.91 : http://www.schillmania.com/projects/soundmanager2
+* jQuery => 1.2.6 : http://www.jquery.com
+* jsGraphics => 3.03 http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm
+
+Licensing
+=========
+
+Copyright (c) 2008-2009 Samalyse
+Author: Olivier Guilyardi <olivier samalyse com>
+
+TimeSide is released under the terms of the GNU General Public License 
+version 2. Please see the LICENSE file for details.
+
diff --git a/timeside/ui/css/timeside.css b/timeside/ui/css/timeside.css
new file mode 100755 (executable)
index 0000000..cadc79a
--- /dev/null
@@ -0,0 +1,29 @@
+/* FIXME: These CSS styles are essential and non intrusive. They should be 
+ * dynamically assigned in javascript, and this file removed. */
+
+.ts-player .ts-ruler .ts-section .ts-canvas {
+    position: relative;
+}
+
+.ts-player .ts-wave {
+    position: relative;
+    clear: both;
+    overflow: hidden;
+}
+
+.ts-player .ts-wave .ts-image-container {
+    position: relative;
+}
+
+.ts-player .ts-wave .ts-image {
+    position: absolute;
+    left: 0;
+    clear: both;
+}
+
+.ts-player .ts-wave .ts-image-canvas {
+    position: absolute;
+    z-index: 100;
+    overflow: hidden;
+}
+
diff --git a/timeside/ui/demo/index.html b/timeside/ui/demo/index.html
new file mode 100755 (executable)
index 0000000..f3977e2
--- /dev/null
@@ -0,0 +1,141 @@
+<html>
+
+<head>
+<link type="text/css" href="../css/timeside.css" rel="stylesheet" media="screen" />
+<link type="text/css" href="../skins/lab/style.css" rel="stylesheet" media="screen" />
+<style type="text/css">
+.ts-player { width: 360px; }
+</style>
+<!--
+<script type="text/javascript" src="../lib/firebug-lite-compressed.js"></script> 
+-->
+<script type="text/javascript">
+function get_globals() {
+    var g = [];
+    for (var v in window) 
+        g = g.concat([v]);
+    return g;
+}
+function diff_array(a1, a2) {
+    var diff = [];
+    var i, ii = a2.length;
+    for (i = 0; i < ii; i++) {
+        if (a1.indexOf(a2[i]) == -1) {
+            diff = diff.concat([a2[i]]);
+        }
+    }
+    return diff;
+}
+
+function log_globals(label) {
+    var g = get_globals();
+    if (log_globals.cache && label && typeof console != 'undefined') {
+        console.log(label + ':');
+        console.log(diff_array(log_globals.cache, g));
+    }
+    log_globals.cache = g;
+}
+</script>
+<script>log_globals(false);</script>
+<script type="text/javascript" src="../lib/jquery.js"></script> 
+<script type="text/javascript">
+jQuery.noConflict();
+jQuery(window).bind('load', function() {if (jQuery.browser.mozilla) jQuery('#Firebug').hide()});
+log_globals('jquery globals');
+</script>
+
+<!--
+<script type="text/javascript" src="jquery-ui.js"></script> 
+-->
+<script>log_globals('jquery ui globals');</script>
+<script type="text/javascript" src="../lib/wz_jsgraphics.js"></script> 
+<script>log_globals('jsgraphics globals');</script>
+<script type="text/javascript" src="../lib/soundmanager2.js"></script> 
+<script>log_globals('soundmanager globals');</script>
+<script type="text/javascript" src="../src/timeside.js"></script> 
+
+<script type="text/javascript">
+var sound = null;
+var map;
+var provider = null;
+var player = null;
+
+function shiftSize(delta) {
+    jQuery('#player').width(jQuery('#player').width() + delta);
+    player.resize();
+}
+
+function fullSize() {
+    jQuery('#player').css({width: 'auto'});
+    player.resize();
+}
+
+TimeSide.debug(true);
+TimeSide.load(function() {
+    map = new TimeSide.MarkerMap();
+    provider = new TimeSide.SoundProvider({source: sound});
+    player = new TimeSide.Player('#player', {
+        image: 'waveform.png'
+    });
+    controller = new TimeSide.Controller({
+        player: player,
+        soundProvider: provider, 
+        map: map
+    });
+
+    jQuery('#skinner').get(0).className=jQuery('#skin').get(0).value; player.resize(); 
+});
+if (typeof soundManager != 'undefined') {
+    soundManager.url = '../lib/';
+    soundManager.flashVersion = 9;
+    soundManager.consoleOnly = true;
+    if (typeof console == 'undefined') {
+        soundManager.debugMode = false;
+    }
+
+    soundManager.onload = function() {
+        sound = soundManager.createSound({
+            id: 'test',
+            url: 'http://ns22997.ovh.net/tmp/crem.mp3'
+            //autoLoad: true
+        });
+
+        if (provider) {
+            provider.setSource(sound);
+        } else {
+            TimeSide.load(function () {
+                provider.setSource(sound);
+            });
+        }
+    }        
+}    
+
+</script> 
+
+</head>
+
+<body>
+
+<h2>TimeSide Player</h2>
+
+<div id="skinner" class="">
+  <div id="player" class="ts-player">
+  </div>  
+</div>
+
+<p>
+<!--
+  <button onclick="setup()">Setup</button> 
+-->  
+  <button onclick="shiftSize(-10)">Smaller</button> 
+  <button onclick="shiftSize(10)">Bigger</button>
+  <button onclick="fullSize()">Full size</button>
+  <br />
+  Skin:
+  <select id="skin" onchange="jQuery('#skinner').get(0).className=this.value; player.resize(); ">
+    <option selected value="">None</option>
+    <option value="ts-skin-lab">Lab</option>
+  </select>
+</p>
+</body>
+</html>
diff --git a/timeside/ui/demo/waveform.png b/timeside/ui/demo/waveform.png
new file mode 100755 (executable)
index 0000000..75e3f9d
Binary files /dev/null and b/timeside/ui/demo/waveform.png differ
diff --git a/timeside/ui/lib/firebug-lite-compressed.js b/timeside/ui/lib/firebug-lite-compressed.js
new file mode 100644 (file)
index 0000000..df2601c
--- /dev/null
@@ -0,0 +1,2 @@
+(function(_scope){_scope.pi=Object(3.14159265358979323846);var pi=_scope.pi;pi.version=1.0;pi.env={ie:/MSIE/i.test(navigator.userAgent),ie6:/MSIE 6/i.test(navigator.userAgent),ie7:/MSIE 7/i.test(navigator.userAgent),ie8:/MSIE 8/i.test(navigator.userAgent),firefox:/Firefox/i.test(navigator.userAgent),opera:/Opera/i.test(navigator.userAgent),webkit:/Webkit/i.test(navigator.userAgent)};pi.util={IsArray:function(_object){return _object&&_object!=window&&(_object instanceof Array||(typeof _object.length=="number"&&typeof _object.item=="function"))},IsHash:function(_object){return _object&&typeof _object=="object"&&(_object==window||_object instanceof Object)&&!_object.nodeName&&!pi.util.IsArray(_object)},DOMContentLoaded:[],AddEvent:function(_element,_eventName,_fn,_useCapture){_element[pi.env.ie.toggle("attachEvent","addEventListener")](pi.env.ie.toggle("on","")+_eventName,_fn,_useCapture||false);return pi.util.AddEvent.curry(this,_element)},RemoveEvent:function(_element,_eventName,_fn,_useCapture){return _element[pi.env.ie.toggle("detachEvent","removeEventListener")](pi.env.ie.toggle("on","")+_eventName,_fn,_useCapture||false)},GetWindowSize:function(){return{height:pi.env.ie?Math.max(document.documentElement.clientHeight,document.body.clientHeight):window.innerHeight,width:pi.env.ie?Math.max(document.documentElement.clientWidth,document.body.clientWidth):window.innerWidth}},Include:function(_url,_callback){var script=new pi.element("script").attribute.set("src",_url),callback=_callback||new Function,done=false,head=pi.get.byTag("head")[0];script.environment.getElement().onload=script.environment.getElement().onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){callback.call(this);done=true;head.removeChild(script.environment.getElement())}};script.insert(head)},Element:{addClass:function(_element,_class){if(!pi.util.Element.hasClass(_element,_class))pi.util.Element.setClass(_element,pi.util.Element.getClass(_element)+" "+_class)},getClass:function(_element){return _element.getAttribute(pi.env.ie.toggle("className","class"))||""},hasClass:function(_element,_class){return pi.util.Element.getClass(_element).split(" ").indexOf(_class)>-1},removeClass:function(_element,_class){if(pi.util.Element.hasClass(_element,_class))pi.util.Element.setClass(_element,pi.util.Element.getClass(_element,_class).split(" ").removeValue(_class).join(" "))},setClass:function(_element,_value){_element.setAttribute(pi.env.ie.toggle("className","class"),_value)},toggleClass:function(){if(pi.util.Element.hasClass.apply(this,arguments))pi.util.Element.removeClass.apply(this,arguments);else pi.util.Element.addClass.apply(this,arguments)},getOpacity:function(_styleObject){var styleObject=_styleObject;if(!pi.env.ie)return styleObject["opacity"];var alpha=styleObject["filter"].match(/opacity\=(\d+)/i);return alpha?alpha[1]/100:1},setOpacity:function(_element,_value){if(!pi.env.ie)return pi.util.Element.addStyle(_element,{"opacity":_value});_value*=100;pi.util.Element.addStyle(_element,{"filter":"alpha(opacity="+_value+")"});return this._parent_},getPosition:function(_element){var parent=_element,offsetLeft=0,offsetTop=0,view=pi.util.Element.getView(_element);while(parent&&parent!=document.body&&parent!=document.firstChild){offsetLeft+=parseInt(parent.offsetLeft);offsetTop+=parseInt(parent.offsetTop);parent=parent.offsetParent};return{"bottom":view["bottom"],"left":view["left"],"marginTop":view["marginTop"],"marginLeft":view["marginLeft"],"offsetLeft":offsetLeft,"offsetTop":offsetTop,"position":view["position"],"right":view["right"],"top":view["top"],"z-index":view["zIndex"]}},getSize:function(_element){var view=pi.util.Element.getView(_element);return{"height":view["height"],"offsetHeight":_element.offsetHeight,"offsetWidth":_element.offsetWidth,"width":view["width"]}},addStyle:function(_element,_style){for(var key in _style){key=key=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):key;if(key=="opacity"&&pi.env.ie){pi.util.Element.setOpacity(_element,_style[key]);continue}_element.style[key]=_style[key]}},getStyle:function(_element,_property){_property=_property=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):_property;if(_property=="opacity"&&pi.env.ie)return pi.util.Element.getOpacity(_element.style);return typeof _property=="string"?_element.style[_property]:_element.style},getView:function(_element,_property){var view=document.defaultView?document.defaultView.getComputedStyle(_element,null):_element.currentStyle;_property=_property=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):_property;if(_property=="opacity"&&pi.env.ie)return pi.util.Element.getOpacity(_element,view);return typeof _property=="string"?view[_property]:view}},CloneObject:function(_object,_fn){var tmp={};for(var key in _object){if(pi.util.IsArray(_object[key])){tmp[key]=Array.prototype.clone.apply(_object[key])}else if(pi.util.IsHash(_object[key])){tmp[key]=pi.util.CloneObject(_object[key]);if(_fn)_fn.call(tmp,key,_object)}else tmp[key]=_object[key]}return tmp},MergeObjects:function(_object,_source){for(var key in _source){var value=_source[key];if(pi.util.IsArray(_source[key])){if(pi.util.IsArray(_object[key])){Array.prototype.push.apply(_source[key],_object[key])}else value=_source[key].clone()}else if(pi.util.IsHash(_source[key])){if(pi.util.IsHash(_object[key])){value=pi.util.MergeObjects(_object[key],_source[key])}else{value=pi.util.CloneObject(_source[key])}}_object[key]=value};return _object}};pi.get=function(){return document.getElementById(arguments[0])};pi.get.byTag=function(){return document.getElementsByTagName(arguments[0])};pi.get.byClass=function(){return document.getElementsByClassName.apply(document,arguments)};pi.base=function(){this.body={};this.constructor=null;this.build=function(_skipClonning){var base=this,skipClonning=_skipClonning||false,_private={},fn=function(){var _p=pi.util.CloneObject(_private);if(!skipClonning){for(var key in this){if(pi.util.IsArray(this[key])){this[key]=Array.prototype.clone.apply(this[key])}else if(pi.util.IsHash(this[key])){this[key]=pi.util.CloneObject(this[key],function(_key,_object){this[_key]._parent_=this});this[key]._parent_=this}}};base.createAccessors(_p,this);if(base.constructor)return base.constructor.apply(this,arguments);return this};this.movePrivateMembers(this.body,_private);if(this.constructor){fn["$Constructor"]=this.constructor}fn.prototype=this.body;return fn};this.createAccessors=function(_p,_branch){var getter=function(_property){return this[_property]},setter=function(_property,_value){this[_property]=_value;return _branch._parent_||_branch};for(var name in _p){var isPrivate=name.substring(0,1)=="_",title=name.substring(1,2).toUpperCase()+name.substring(2);if(isPrivate){_branch["get"+title]=getter.curry(_p,name);_branch["set"+title]=setter.curry(_p,name)}else if(pi.util.IsHash(_p[name])){if(!_branch[name])_branch[name]={};this.createAccessors(_p[name],_branch[name])}}};this.movePrivateMembers=function(_object,_branch){for(var name in _object){var isPrivate=name.substring(0,1)=="_";if(isPrivate){_branch[name]=_object[name];delete _object[name]}else if(pi.util.IsHash(_object[name])){_branch[name]={};this.movePrivateMembers(_object[name],_branch[name])}}}};Function.prototype.extend=function(_prototype,_skipClonning){var object=new pi.base,superClass=this;if(_prototype["$Constructor"]){object.constructor=_prototype["$Constructor"];delete _prototype["$Constructor"]};object.body=superClass==pi.base?_prototype:pi.util.MergeObjects(_prototype,superClass.prototype,2);object.constructor=object.constructor||function(){if(superClass!=pi.base)superClass.apply(this,arguments)};return object.build(_skipClonning)};Function.prototype.curry=function(_scope){var fn=this,scope=_scope||window,args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(scope,args.concat(Array.prototype.slice.call(arguments,0)))}};pi.element=pi.base.extend({"$Constructor":function(_tag){this.environment.setElement(document.createElement(_tag||"DIV"));this.environment.getElement().pi=this;return this},"clean":function(){var childs=this.child.get();while(childs.length){childs[0].parentNode.removeChild(childs[0])}},"clone":function(_deep){return this.environment.getElement().cloneNode(_deep)},"insert":function(_element){_element=_element.environment?_element.environment.getElement():_element;_element.appendChild(this.environment.getElement());return this},"insertAfter":function(_referenceElement){_referenceElement=_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement;_referenceElement.nextSibling?this.insertBefore(_referenceElement.nextSibling):this.insert(_referenceElement.parentNode);return this},"insertBefore":function(_referenceElement){_referenceElement=_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement;_referenceElement.parentNode.insertBefore(this.environment.getElement(),_referenceElement);return this},"query":function(_expression,_resultType,namespaceResolver,_result){return pi.xpath(_expression,_resultType||"ORDERED_NODE_SNAPSHOT_TYPE",this.environment.getElement(),_namespaceResolver,_result)},"remove":function(){this.environment.getParent().removeChild(this.environment.getElement())},"update":function(_value){["TEXTAREA","INPUT"].indexOf(this.environment.getName())>-1?(this.environment.getElement().value=_value):(this.environment.getElement().innerHTML=_value);return this},"attribute":{"getAll":function(_name){return this._parent_.environment.getElement().attributes},"clear":function(_name){this.set(_name,"");return this._parent_},"get":function(_name){return this._parent_.environment.getElement().getAttribute(_name)},"has":function(_name){return pi.env.ie?(this.get(_name)!=null):this._parent_.environment.getElement().hasAttribute(_name)},"remove":function(_name){this._parent_.environment.getElement().removeAttribute(_name);return this._parent_},"set":function(_name,_value){this._parent_.environment.getElement().setAttribute(_name,_value);return this._parent_},"addClass":function(_classes){for(var i=0;i<arguments.length;i++){pi.util.Element.addClass(this._parent_.environment.getElement(),arguments[i])};return this._parent_},"clearClass":function(){this.setClass("");this._parent_},"getClass":function(){return pi.util.Element.getClass(this._parent_.environment.getElement())},"hasClass":function(_class){return pi.util.Element.hasClass(this._parent_.environment.getElement(),_class)},"setClass":function(_value){return pi.util.Element.setClass(this._parent_.environment.getElement(),_value)},"removeClass":function(_class){pi.util.Element.removeClass(this._parent_.environment.getElement(),_class);return this._parent_},"toggleClass":function(_class){pi.util.Element.toggleClass(this._parent_.environment.getElement(),_class)}},"child":{"get":function(){return this._parent_.environment.getElement().childNodes},"add":function(_elements){for(var i=0;i<arguments.length;i++){var el=arguments[i];this._parent_.environment.getElement().appendChild(el.environment?el.environment.getElement():el)}return this._parent_},"addAfter":function(_element,_referenceElement){this.addBefore(_element.environment?_element.environment.getElement():_element,(_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement).nextSibling);return this._parent_},"addBefore":function(_element,_referenceElement){this._parent_.environment.getElement().insertBefore(_element.environment?_element.environment.getElement():_element,_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement);return this._parent_},"query":function(_tag,_attributeName,_attributeValue){return this._parent_.query("{0}{1}".format((_tag?"{0}".format(_tag):"/*"),_attributeName||_attributeValue?"[contains(concat(' ', @{0}, ' '),' {1} ')]".format(_attributeName||"",_attributeValue||""):""))},"remove":function(_element){this._parent_.environment.getElement().removeChild(_element.environment?_element.environment.getElement():_element)}},"environment":{"_element":null,"getParent":function(){return this.getElement().parentNode},"getPosition":function(){return pi.util.Element.getPosition(this.getElement())},"getSize":function(){return pi.util.Element.getSize(this.getElement())},"addStyle":function(_styleObject){pi.util.Element.addStyle(this.getElement(),_styleObject);return this._parent_},"getStyle":function(_property){return pi.util.Element.getStyle(_property)},"getName":function(){return this.getElement().nodeName},"getType":function(){return this.getElement().nodeType},"getView":function(_property){return pi.util.Element.getView(this.getElement(),_property)}},"event":{"addListener":function(_event,_fn,_useCapture){pi.util.AddEvent(this._parent_.environment.getElement(),_event,_fn,_useCapture);return this._parent_},"removeListener":function(_event,_fn,_useCapture){pi.util.RemoveEvent(this._parent_.environment.getElement(),_event,_fn,_useCapture);return this._parent_}}});pi.xhr=new pi.base;pi.xhr.constructor=function(){var api;if(!window.XMLHttpRequest){var names=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];for(var i=0;i<names.length;i++){try{this.environment.setApi(new ActiveXObject(names[i]));break}catch(e){continue}}}else this.environment.setApi(new XMLHttpRequest());this.environment.getApi().onreadystatechange=this.event.readystatechange.curry(this);return this};pi.xhr.body={"abort":function(){this.environment.getApi().abort()},"send":function(){var url=this.environment.getUrl(),data=this.environment.getData(),dataUrl="";for(var key in data)dataUrl+="{0}={1}&".format(key,data[key]);if(this.environment.getType()=="GET")url+=(url.search("\\?")==-1?"?":"&")+"{0}".format(dataUrl);this.environment.getApi().open(this.environment.getType(),url,this.environment.getAsync());for(var key in this.environment.getHeader())this.environment.getApi().setRequestHeader(key,this.environment.getHeader()[key]);this.environment.getApi().send(this.environment.getType()=="GET"?"":dataUrl)}};pi.xhr.body.environment={"_async":true,"_api":null,"_cache":true,"_callback":[],"_channel":null,"_data":{},"_header":{},"_mimeType":null,"_multipart":false,"_type":"GET","_timeout":0,"_url":"","addCallback":function(_options,_fn){this.getCallback().push({"fn":_fn,"options":_options})},"addHeader":function(_key,_value){this.getHeader()[_key]=_value},"addData":function(_key,_value){this.getData()[_key]=_value},"changeCache":function(_value){if(_value==false){this.addData("forceCache",Math.round(Math.random()*10000))}this.setCache(_value)},"changeType":function(_value){if(_value=="POST"){this.addHeader("Content-Type","application/x-www-form-urlencoded")}this.setType(_value)}};pi.xhr.body.event={"readystatechange":function(){var readyState=this.environment.getApi().readyState;var callback=this.environment.getCallback();for(var i=0;i<callback.length;i++){if(callback[i].options.readyState.indexOf(readyState)>-1)callback[i].fn.apply(this)}}};pi.xhr=pi.xhr.build();pi.xhr.get=function(_url,_returnPiObject){var request=new pi.xhr();request.environment.setAsync(false);request.environment.setUrl(_url);request.send();return _returnPiObject?request:request.environment.getApi()};pi.xpath=function(_expression,_resultType,_contextNode,_namespaceResolver,_result){var contextNode=_contextNode||document,expression=_expression||"",namespaceResolver=_namespaceResolver||null,result=_result||null,resultType=_resultType||"ANY_TYPE";return document.evaluate(expression,contextNode,namespaceResolver,XPathResult[resultType],result)};Array.prototype.clone=function(){var tmp=[];Array.prototype.push.apply(tmp,this);tmp.forEach(function(item,index,object){if(item instanceof Array)object[index]=object[index].clone()});return tmp};Array.prototype.count=function(_value){var count=0;this.forEach(function(){count+=Number(arguments[0]==_value)});return count};Array.prototype.forEach=Array.prototype.forEach||function(_function){for(var i=0;i<this.length;i++)_function.apply(this,[this[i],i,this])};Array.prototype.getLastItem=function(){return this[this.length-1]};Array.prototype.indexOf=Array.prototype.indexOf||function(_value){var index=-1;for(var i=0;i<this.length;i++)if(this[i]==_value){index=i;break}return index};Array.prototype.remove=function(_index){var array=this.slice(0,_index);Array.prototype.push.apply(array,this.slice(_index+1));return array};Array.prototype.removeValue=function(_value){return this.remove(this.indexOf(_value))};Boolean.prototype.toggle=function(){return this==true?arguments[0]:arguments[1]};Number.prototype.base=function(_system){var remain=this%_system;if(this==remain)return String.fromCharCode(this+(this>9?87:48));return((this-remain)/_system).base(_system)+String.fromCharCode(remain+(remain>9?87:48))};Number.prototype.decimal=function(_system){var result=0,digit=String(this).split("");for(var i=0;i<digit.length;i++){digit[i]=parseInt((digit[i].charCodeAt(0)>58)?digit[i].charCodeAt(0)-87:digit[i]);result+=digit[i]*(Math.pow(_system,digit.length-1-i))}return result};Number.prototype.range=function(_pattern){for(var value=String(this),isFloat=/\./i.test(value),i=isFloat.toggle(parseInt(value.split(".")[0]),0),end=parseInt(value.split(".")[isFloat.toggle(1,0)]),array=[];i<end;i++){array.push(Boolean(_pattern)==false?i:(typeof _pattern=="function"?_pattern(i):_pattern[i]))}return array};String.prototype.escape=function(){return escape(this)};String.prototype.format=function(){var values=arguments;return this.replace(/\{(\d)\}/g,function(){return values[arguments[1]]})};String.prototype.leftpad=function(_len,_ch){var str=this;var ch=Boolean(_ch)==false?" ":_ch;while(str.length<_len)str=ch+str;return str};String.prototype.toggle=function(_value,_other){return this==_value?_value:_other};String.prototype.unicode=function(){var str="",obj=this.split("");for(var i=obj.length-1;i>=0;i--)str="\\u{0}{1}".format(String(obj[i].charCodeAt(0).base(16)).leftpad(4,"0"),str);return str};pi.util.AddEvent(pi.env.ie?window:document,pi.env.ie?"load":"DOMContentLoaded",function(){for(var i=0;i<pi.util.DOMContentLoaded.length;i++){pi.util.DOMContentLoaded[i]()}})})(window);
+var firebug={env:{"cache":{},"ctmp":[],"dIndex":"console","init":false,"ml":false,"objCn":[]},init:function(){firebug.el={};firebug.el.content={};with(firebug){document.documentElement.childNodes[0].appendChild(new pi.element("link").attribute.set("rel","stylesheet").attribute.set("href","http://firebuglite.appspot.com/firebug-lite.css").environment.getElement());el.main=new pi.element("DIV").attribute.set("id","Firebug").environment.addStyle({"width":pi.util.GetWindowSize().width+"px"}).insert(document.body);el.header=new pi.element("DIV").attribute.addClass("Header").insert(el.main);el.left={};el.left.container=new pi.element("DIV").attribute.addClass("Left").insert(el.main);el.right={};el.right.container=new pi.element("DIV").attribute.addClass("Right").insert(el.main);el.main.child.add(new pi.element("DIV").environment.addStyle({"clear":"both"}));el.button={};el.button.container=new pi.element("DIV").attribute.addClass("ButtonContainer").insert(el.header);el.button.logo=new pi.element("A").attribute.set("title","Firebug Lite").attribute.set("target","_blank").attribute.set("href","http://getfirebug.com/lite.html").update("&nbsp;").attribute.addClass("Button Logo").insert(el.button.container);el.button.inspect=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.inspector.toggle).update("Inspect").insert(el.button.container);el.button.maximize=new pi.element("A").attribute.addClass("Button Maximize").event.addListener("click",win.maximize).insert(el.button.container);el.button.minimize=new pi.element("A").attribute.addClass("Button Minimize").event.addListener("click",win.minimize).insert(el.button.container);el.button.close=new pi.element("A").attribute.addClass("Button Close").event.addListener("click",win.close).insert(el.button.container);if(pi.env.ie||pi.env.webkit){el.button.container.environment.addStyle({"paddingTop":"12px"})}el.nav={};el.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.left.container);el.nav.console=new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.navigate.curry(window,"console")).update("Console").insert(el.nav.container);el.nav.html=new pi.element("A").attribute.addClass("Tab").update("HTML").event.addListener("click",d.navigate.curry(window,"html")).insert(el.nav.container);el.nav.css=new pi.element("A").attribute.addClass("Tab").update("CSS").event.addListener("click",d.navigate.curry(window,"css")).insert(el.nav.container);el.nav.scripts=new pi.element("A").attribute.addClass("Tab").update("Script").event.addListener("click",d.navigate.curry(window,"scripts")).insert(el.nav.container);el.nav.dom=new pi.element("A").attribute.addClass("Tab").update("DOM").event.addListener("click",d.navigate.curry(window,"dom")).insert(el.nav.container);el.nav.xhr=new pi.element("A").attribute.addClass("Tab").update("XHR").event.addListener("click",d.navigate.curry(window,"xhr")).insert(el.nav.container);el.borderInspector=new pi.element("DIV").attribute.set("id","FirebugBorderInspector").event.addListener("click",listen.inspector).insert(document.body);el.bgInspector=new pi.element("DIV").attribute.set("id","FirebugBGInspector").insert(document.body);el.left.console={};el.left.console.container=new pi.element("DIV").attribute.addClass("Console").insert(el.left.container);el.left.console.mlButton=new pi.element("A").attribute.addClass("MLButton").event.addListener("click",d.console.toggleML).insert(el.left.console.container);el.left.console.monitor=new pi.element("DIV").insert(new pi.element("DIV").attribute.addClass("Monitor").insert(el.left.console.container));el.left.console.container.child.add(new pi.element("DIV").attribute.addClass("InputArrow").update(">>>"));el.left.console.input=new pi.element("INPUT").attribute.set("type","text").attribute.addClass("Input").event.addListener("keydown",listen.consoleTextbox).insert(new pi.element("DIV").attribute.addClass("InputContainer").insert(el.left.console.container));el.right.console={};el.right.console.container=new pi.element("DIV").attribute.addClass("Console Container").insert(el.right.container);el.right.console.mlButton=new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.console.container);el.right.console.input=new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.console.container);el.right.console.run=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runMultiline).update("Run").insert(el.right.console.container);el.right.console.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.console.input)).update("Clear").insert(el.right.console.container);el.button.console={};el.button.console.container=new pi.element("DIV").attribute.addClass("ButtonSet").insert(el.button.container);el.button.console.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.left.console.monitor)).update("Clear").insert(el.button.console.container);el.left.html={};el.left.html.container=new pi.element("DIV").attribute.addClass("HTML").insert(el.left.container);el.right.html={};el.right.html.container=new pi.element("DIV").attribute.addClass("HTML Container").insert(el.right.container);el.right.html.nav={};el.right.html.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.right.html.container);el.right.html.nav.computedStyle=new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.html.navigate.curry(firebug,"computedStyle")).update("Computed Style").insert(el.right.html.nav.container);if(!pi.env.ie6)el.right.html.nav.dom=new pi.element("A").attribute.addClass("Tab").event.addListener("click",d.html.navigate.curry(firebug,"dom")).update("DOM").insert(el.right.html.nav.container);el.right.html.content=new pi.element("DIV").attribute.addClass("Content").insert(el.right.html.container);el.button.html={};el.button.html.container=new pi.element("DIV").attribute.addClass("ButtonSet HTML").insert(el.button.container);el.left.css={};el.left.css.container=new pi.element("DIV").attribute.addClass("CSS").insert(el.left.container);el.right.css={};el.right.css.container=new pi.element("DIV").attribute.addClass("CSS Container").insert(el.right.container);el.right.css.nav={};el.right.css.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.right.css.container);el.right.css.nav.runCSS=new pi.element("A").attribute.addClass("Tab Selected").update("Run CSS").insert(el.right.css.nav.container);el.right.css.mlButton=new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.css.container);el.right.css.input=new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.css.container);el.right.css.run=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runCSS).update("Run").insert(el.right.css.container);el.right.css.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.css.input)).update("Clear").insert(el.right.css.container);el.button.css={};el.button.css.container=new pi.element("DIV").attribute.addClass("ButtonSet CSS").insert(el.button.container);el.button.css.selectbox=new pi.element("SELECT").event.addListener("change",listen.cssSelectbox).insert(el.button.css.container);el.left.scripts={};el.left.scripts.container=new pi.element("DIV").attribute.addClass("Scripts").insert(el.left.container);el.right.scripts={};el.right.scripts.container=new pi.element("DIV").attribute.addClass("Scripts Container").insert(el.right.container);el.button.scripts={};el.button.scripts.container=new pi.element("DIV").attribute.addClass("ButtonSet Scripts").insert(el.button.container);el.button.scripts.selectbox=new pi.element("SELECT").event.addListener("change",listen.scriptsSelectbox).insert(el.button.scripts.container);el.button.scripts.lineNumbers=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.scripts.toggleLineNumbers).update("Show Line Numbers").insert(el.button.scripts.container);el.left.dom={};el.left.dom.container=new pi.element("DIV").attribute.addClass("DOM").insert(el.left.container);el.right.dom={};el.right.dom.container=new pi.element("DIV").attribute.addClass("DOM Container").insert(el.right.container);el.button.dom={};el.button.dom.container=new pi.element("DIV").attribute.addClass("ButtonSet DOM").insert(el.button.container);el.button.dom.label=new pi.element("LABEL").update("Object Path:").insert(el.button.dom.container);el.button.dom.textbox=new pi.element("INPUT").event.addListener("keydown",listen.domTextbox).update("window").insert(el.button.dom.container);el.left.str={};el.left.str.container=new pi.element("DIV").attribute.addClass("STR").insert(el.left.container);el.right.str={};el.right.str.container=new pi.element("DIV").attribute.addClass("STR").insert(el.left.container);el.button.str={};el.button.str.container=new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container);el.button.str.watch=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.navigate.curry(window,"xhr")).update("Back").insert(el.button.str.container);el.left.xhr={};el.left.xhr.container=new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container);el.right.xhr={};el.right.xhr.container=new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container);el.button.xhr={};el.button.xhr.container=new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container);el.button.xhr.label=new pi.element("LABEL").update("XHR Path:").insert(el.button.xhr.container);el.button.xhr.textbox=new pi.element("INPUT").event.addListener("keydown",listen.xhrTextbox).insert(el.button.xhr.container);el.button.xhr.watch=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.addXhrObject).update("Watch").insert(el.button.xhr.container);if(pi.env.ie6){var buttons=[el.button.inspect,el.button.close,el.button.inspect,el.button.console.clear,el.right.console.run,el.right.console.clear,el.right.css.run,el.right.css.clear];for(var i=0;i<buttons.length;i++)buttons[i].attribute.set("href","#")}env.init=true;for(var i=0;i<env.ctmp.length;i++){d.console.log.apply(window,env.ctmp[i])}}},win:{close:function(){with(firebug){el.main.update("");el.main.remove()}},minimize:function(){with(firebug){el.main.environment.addStyle({"height":"35px"});el.button.maximize.environment.addStyle({"display":"block"});el.button.minimize.environment.addStyle({"display":"none"});d.refreshSize()}},maximize:function(){with(firebug){el.main.environment.addStyle({"height":"295px"});el.button.minimize.environment.addStyle({"display":"block"});el.button.maximize.environment.addStyle({"display":"none"});d.refreshSize()}}},watchXHR:function(){with(firebug){d.xhr.addObject.apply(window,arguments);if(env.dIndex!="xhr"){d.navigate("xhr")}}},d:{clean:function(_element){with(firebug){_element.update("")}},console:{dir:function(_value){with(firebug){d.console.addLine().attribute.addClass("Arrow").update(">>> console.dir("+_value+")");d.dom.open(_value,d.console.addLine())}},addLine:function(){with(firebug){return new pi.element("DIV").attribute.addClass("Row").insert(el.left.console.monitor)}},openObject:function(_index){with(firebug){d.dom.open(env.objCn[_index],el.left.dom.container,pi.env.ie);d.navigate("dom")}},historyIndex:0,history:[],log:function(_values){with(firebug){if(env.init==false){env.ctmp.push(arguments);return}var value="";for(var i=0;i<arguments.length;i++){value+=(i>0?" ":"")+d.highlight(arguments[i],false,false,true)}d.console.addLine().update(value);d.console.scroll()}},print:function(_cmd,_text){with(firebug){d.console.addLine().attribute.addClass("Arrow").update(">>> "+_cmd);d.console.addLine().update(d.highlight(_text,false,false,true));d.console.scroll();d.console.historyIndex=d.console.history.push(_cmd)}},run:function(cmd){with(firebug){if(cmd.length==0)return;el.left.console.input.environment.getElement().value="";try{var result=eval.call(window,cmd);d.console.print(cmd,result)}catch(e){d.console.addLine().attribute.addClass("Arrow").update(">>> "+cmd);if(!pi.env.ff){d.console.scroll();return d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+(e.description||e),true)}if(e.fileName==null){d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+e.message,true)}var fileName=e.fileName.split("\/").getLastItem();d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+e.message+" (<em>"+fileName+"</em>,"+e.lineNumber+")",true);d.console.scroll()}d.console.scroll()}},scroll:function(){with(firebug){el.left.console.monitor.environment.getElement().parentNode.scrollTop=Math.abs(el.left.console.monitor.environment.getSize().offsetHeight-200)}},toggleML:function(){with(firebug){var open=!env.ml;env.ml=!env.ml;d.navigateRightColumn("console",open);el[open?"left":"right"].console.mlButton.environment.addStyle({display:"none"});el[!open?"left":"right"].console.mlButton.environment.addStyle({display:"block"});el.left.console.monitor.environment.addStyle({"height":(open?233:210)+"px"});el.left.console.mlButton.attribute[(open?"add":"remove")+"Class"]("CloseML")}}},css:{index:-1,open:function(_index){with(firebug){var item=document.styleSheets[_index];var uri=item.href;if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){el.left.css.container.update("<em>Access to restricted URI denied</em>");return}var rules=item[pi.env.ie?"rules":"cssRules"];var str="";for(var i=0;i<rules.length;i++){var item=rules[i];var selector=item.selectorText;var cssText=pi.env.ie?item.style.cssText:item.cssText.match(/\{(.*)\}/)[1];str+=d.css.printRule(selector,cssText.split(";"),el.left.css.container)}el.left.css.container.update(str)}},printRule:function(_selector,_css,_layer){with(firebug){var str="<div class='Selector'>"+_selector+" {</div>";for(var i=0;i<_css.length;i++){var item=_css[i];str+="<div class='CSSText'>"+item.replace(/(.+\:)(.+)/,"<span class='CSSProperty'>$1</span><span class='CSSValue'>$2;</span>")+"</div>"}str+="<div class='Selector'>}</div>";return str}},refresh:function(){with(firebug){el.button.css.selectbox.update("");var collection=document.styleSheets;for(var i=0;i<collection.length;i++){var uri=collection[i].href;d.css.index=d.css.index<0?i:d.css.index;el.button.css.selectbox.child.add(new pi.element("OPTION").attribute.set("value",i).update(uri))};d.css.open(d.css.index)}}},dom:{open:function(_object,_layer){with(firebug){_layer.clean();var container=new pi.element("DIV").attribute.addClass("DOMContent").insert(_layer);d.dom.print(_object,container)}},print:function(_object,_parent,_inTree){with(firebug){var obj=_object||window,parentElement=_parent;parentElement.update("");if(parentElement.opened&&parentElement!=el.left.dom.container){parentElement.environment.getParent().pi.child.get()[0].pi.child.get()[0].pi.attribute.removeClass("Opened");parentElement.opened=false;parentElement.environment.addStyle({"display":"none"});return}if(_inTree)parentElement.environment.getParent().pi.child.get()[0].pi.child.get()[0].pi.attribute.addClass("Opened");parentElement.opened=true;for(var key in obj){try{var value=obj[key],property=key,container=new pi.element("DIV").attribute.addClass("DOMRow").insert(parentElement),left=new pi.element("DIV").attribute.addClass("DOMRowLeft").insert(container),right=new pi.element("DIV").attribute.addClass("DOMRowRight").insert(container);container.child.add(new pi.element("DIV").environment.addStyle({"clear":"both"}));var link=new pi.element("A").attribute.addClass(typeof value=="object"&&Boolean(value)?"Property Object":"Property").update(property).insert(left);right.update(d.highlight(value,false,true));var subContainer=new pi.element("DIV").attribute.addClass("DOMRowSubContainer").insert(container);if(typeof value!="object"||Boolean(value)==false)continue;link.event.addListener("click",d.dom.print.curry(window,value,subContainer,true))}catch(e){}}parentElement.environment.addStyle({"display":"block"})}}},highlight:function(_value,_inObject,_inArray,_link){with(firebug){var isArray=false,isElement=false;try{isArray=pi.util.IsArray(_value);isElement=_value!=undefined&&Boolean(_value.nodeName)&&Boolean(_value.nodeType)}catch(e){};if(_value==null||["boolean","function","number","string"].indexOf(typeof _value)>-1){if(_value==null){return"<span class='Null'>null</span>"}if(["boolean","number"].indexOf(typeof _value)>-1){return"<span class='DarkBlue'>"+_value+"</span>"}if(typeof _value=="function"){return"<span class='"+(_inObject?"Italic Gray":"Green")+"'>function()</span>"}return"<span class='Red'>\""+(!_inObject&&!_inArray?_value:_value.substring(0,35)).replace(/\n/g,"\\n").replace(/\s/g,"&nbsp;").replace(/>/g,"&#62;").replace(/</g,"&#60;")+"\"</span>"}else if(isElement){if(_value.nodeType==3)return d.highlight(_value.nodeValue);if(_inArray||_inObject){var result="<span class='Blue'>"+_value.nodeName.toLowerCase();if(_value.getAttribute&&_value.getAttribute("id"))result+="<span class='DarkBlue'>#"+_value.getAttribute("id")+"</span>";var elClass=_value.getAttribute?_value.getAttribute(pi.env.ie?"className":"class"):"";if(elClass)result+="<span class='Red'>."+elClass.split(" ")[0]+"</span>";return result+"</span>"}var result="<span class='Blue'>&#60;"+_value.nodeName.toLowerCase()+"";if(_value.attributes)for(var i=0;i<_value.attributes.length;i++){var item=_value.attributes[i];if(pi.env.ie&&Boolean(item.nodeValue)==false)continue;result+=" <span class='DarkBlue'>"+item.nodeName+"=\"<span class='Red'>"+item.nodeValue+"</span>\"</span>"}result+="&#62;</span>";return result}else if(isArray||["object","array"].indexOf(typeof _value)>-1){var result="";if(isArray||_value instanceof Array){if(_inObject)return"<span class='Gray Italic'>["+_value.length+"]</span>";result+="<span class='Strong'>[ ";for(var i=0;i<_value.length;i++){if((_inObject||_inArray)&&pi.env.ie&&i>3)break;result+=(i>0?", ":"")+d.highlight(_value[i],false,true,true)}result+=" ]</span>";return result}if(_inObject)return"<span class='Gray Italic'>Object</span>";result+="<span class='Strong Green"+(!_link?"'":" ObjectLink' onmouseover='this.className=this.className.replace(\"ObjectLink\",\"ObjectLinkHover\")' onmouseout='this.className=this.className.replace(\"ObjectLinkHover\",\"ObjectLink\")' onclick='firebug.d.console.openObject("+(env.objCn.push(_value)-1)+")'")+">Object";var i=0;for(var key in _value){var value=_value[key];if((_inObject||_inArray)&&pi.env.ie&&i>3)break;result+=" "+key+"="+d.highlight(value,true);i++};result+="</span>";return result}else{if(_inObject)return"<span class='Gray Italic'>"+_value+"</span>";return _value}}},html:{nIndex:"computedStyle",current:null,highlight:function(_element,_clear,_event){with(firebug){if(_clear){el.bgInspector.environment.addStyle({"display":"none"});return}d.inspector.inspect(_element,true)}},inspect:function(_element){var el=_element,map=[],parent=_element;while(parent){map.push(parent);if(parent==document.body)break;parent=parent.parentNode}map=map.reverse();with(firebug){d.inspector.toggle();var parentLayer=el.left.html.container.child.get()[1].childNodes[1].pi;for(var t=0;map[t];){if(t==map.length-1){var link=parentLayer.environment.getElement().previousSibling.pi;link.attribute.addClass("Selected");if(d.html.current)d.html.current[1].attribute.removeClass("Selected");d.html.current=[_element,link];return;t}parentLayer=d.html.openHtmlTree(map[t],parentLayer,map[t+1]);t++}}},navigate:function(_index,_element){with(firebug){el.right.html.nav[d.html.nIndex].attribute.removeClass("Selected");el.right.html.nav[_index].attribute.addClass("Selected");d.html.nIndex=_index;d.html.openProperties()}},openHtmlTree:function(_element,_parent,_returnParentElementByElement,_event){with(firebug){var element=_element||document.documentElement,parent=_parent||el.left.html.container,returnParentEl=_returnParentElementByElement||null,returnParentVal=null;if(parent!=el.left.html.container){var nodeLink=parent.environment.getParent().pi.child.get()[0].pi;if(d.html.current)d.html.current[1].attribute.removeClass("Selected");nodeLink.attribute.addClass("Selected");d.html.current=[_element,nodeLink];d.html.openProperties()}if(element.childNodes&&(element.childNodes.length==0||(element.childNodes.length==1&&element.childNodes[0].nodeType==3)))return;parent.clean();if(parent.opened&&Boolean(_returnParentElementByElement)==false){parent.opened=false;parent.environment.getParent().pi.child.get()[0].pi.attribute.removeClass("Open");return}if(parent!=el.left.html.container){parent.environment.getParent().pi.child.get()[0].pi.attribute.addClass("Open");parent.opened=true}for(var i=0;i<element.childNodes.length;i++){var item=element.childNodes[i];if(item.nodeType==3)continue;var container=new pi.element().attribute.addClass("Block").insert(parent);var link=new pi.element("A").attribute.addClass("Link").update(d.highlight(item)).insert(container);var subContainer=new pi.element("DIV").attribute.addClass("SubContainer").insert(container);link.event.addListener("click",d.html.openHtmlTree.curry(window,item,subContainer,false));link.event.addListener("mouseover",d.html.highlight.curry(window,item,false));link.event.addListener("mouseout",d.html.highlight.curry(window,item,true));returnParentVal=returnParentEl==item?subContainer:returnParentVal;if(d.html.current==null&&item==document.body){link.attribute.addClass("Selected");d.html.current=[item,link];d.html.openHtmlTree(item,subContainer)}if(item.childNodes&&item.childNodes.length==1&&item.childNodes[0].nodeType==3){link.child.get()[0].appendChild(document.createTextNode(item.childNodes[0].nodeValue.substring(0,100)));link.child.get()[0].appendChild(document.createTextNode("</"));link.child.get()[0].appendChild(new pi.element("span").attribute.addClass("Blue").update(item.nodeName.toLowerCase()).environment.getElement());link.child.get()[0].appendChild(document.createTextNode(">"));continue}else if(item.childNodes&&item.childNodes.length==0)continue;link.attribute.addClass("ParentLink")}return returnParentVal}},openProperties:function(){with(firebug){var index=d.html.nIndex;var node=d.html.current[0];d.clean(el.right.html.content);var str="";switch(index){case"computedStyle":var property=["opacity","filter","azimuth","background","backgroundAttachment","backgroundColor","backgroundImage","backgroundPosition","backgroundRepeat","border","borderCollapse","borderColor","borderSpacing","borderStyle","borderTop","borderRight","borderBottom","borderLeft","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","borderTopStyle","borderRightStyle","borderBottomStyle","borderLeftStyle","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderWidth","bottom","captionSide","clear","clip","color","content","counterIncrement","counterReset","cue","cueAfter","cueBefore","cursor","direction","display","elevation","emptyCells","cssFloat","font","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","height","left","letterSpacing","lineHeight","listStyle","listStyleImage","listStylePosition","listStyleType","margin","marginTop","marginRight","marginBottom","marginLeft","markerOffset","marks","maxHeight","maxWidth","minHeight","minWidth","orphans","outline","outlineColor","outlineStyle","outlineWidth","overflow","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","page","pageBreakAfter","pageBreakBefore","pageBreakInside","pause","pauseAfter","pauseBefore","pitch","pitchRange","playDuring","position","quotes","richness","right","size","speak","speakHeader","speakNumeral","speakPunctuation","speechRate","stress","tableLayout","textAlign","textDecoration","textIndent","textShadow","textTransform","top","unicodeBidi","verticalAlign","visibility","voiceFamily","volume","whiteSpace","widows","width","wordSpacing","zIndex"].sort();var view=document.defaultView?document.defaultView.getComputedStyle(node,null):node.currentStyle;for(var i=0;i<property.length;i++){var item=property[i];if(!view[item])continue;str+="<div class='CSSItem'><div class='CSSProperty'>"+item+"</div><div class='CSSValue'>"+d.highlight(view[item])+"</div></div>"}el.right.html.content.update(str);break;case"dom":d.dom.open(node,el.right.html.content,pi.env.ie);break}}}},inspector:{enabled:false,el:null,inspect:function(_element,_bgInspector){var el=_element,top=el.offsetTop,left=el.offsetLeft,parent=_element.offsetParent;while(Boolean(parent)&&parent!=document.firstChild){top+=parent.offsetTop;left+=parent.offsetLeft;parent=parent.offsetParent;if(parent==document.body)break};with(firebug){el[_bgInspector?"bgInspector":"borderInspector"].environment.addStyle({"width":_element.offsetWidth+"px","height":_element.offsetHeight+"px","top":top-(_bgInspector?0:2)+"px","left":left-(_bgInspector?0:2)+"px","display":"block"});if(!_bgInspector){d.inspector.el=_element}}},toggle:function(){with(firebug){d.inspector.enabled=!d.inspector.enabled;el.button.inspect.attribute[(d.inspector.enabled?"add":"remove")+"Class"]("Enabled");if(d.inspector.enabled==false){el.borderInspector.environment.addStyle({"display":"none"});d.inspector.el=null}else if(pi.env.dIndex!="html"){d.navigate("html")}}}},scripts:{index:-1,lineNumbers:false,open:function(_index){with(firebug){d.scripts.index=_index;el.left.scripts.container.update("");var script=document.getElementsByTagName("script")[_index],uri=script.src||document.location.href,source;if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){el.left.scripts.container.update("<em>Access to restricted URI denied</em>");return}if(uri!=document.location.href){source=env.cache[uri]||pi.xhr.get(uri).responseText;env.cache[uri]=source}else source=script.innerHTML;source=source.replace(/\n|\t|<|>/g,function(_ch){return({"<":"&#60;",">":"&#62;","\t":"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;","\n":"<br />"})[_ch]});if(!d.scripts.lineNumbers)el.left.scripts.container.child.add(new pi.element("DIV").attribute.addClass("CodeContainer").update(source));else{source=source.split("<br />");for(var i=0;i<source.length;i++){el.left.scripts.container.child.add(new pi.element("DIV").child.add(new pi.element("DIV").attribute.addClass("LineNumber").update(i+1),new pi.element("DIV").attribute.addClass("Code").update("&nbsp;"+source[i]),new pi.element("DIV").environment.addStyle({"clear":"both"})))}}}},toggleLineNumbers:function(){with(firebug){d.scripts.lineNumbers=!d.scripts.lineNumbers;el.button.scripts.lineNumbers.attribute[(d.scripts.lineNumbers?"add":"remove")+"Class"]("Enabled");d.scripts.open(d.scripts.index)}},refresh:function(){with(firebug){el.button.scripts.selectbox.clean();var collection=document.getElementsByTagName("script");for(var i=0;i<collection.length;i++){var item=collection[i];d.scripts.index=d.scripts.index<0?i:d.scripts.index;el.button.scripts.selectbox.child.add(new pi.element("OPTION").attribute.set("value",i).update(item.src||item.baseURI||".."))}d.scripts.open(d.scripts.index)}}},str:{open:function(_str){with(firebug){d.navigate("str");el.left.str.container.update(_str.replace(/\n/g,"<br />"))}}},xhr:{objects:[],addObject:function(){with(firebug){for(var i=0;i<arguments.length;i++){try{var item=arguments[i];var val=eval(item);d.xhr.objects.push([item,val])}catch(e){continue}}}},open:function(){with(firebug){el.left.xhr.container.update("");el.left.xhr.name=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").attribute.addClass("Block").environment.addStyle({"width":"20%"}).insert(el.left.xhr.container));el.left.xhr.nameTitle=new pi.element("STRONG").update("Object Name:").insert(el.left.xhr.name);el.left.xhr.nameContent=new pi.element("DIV").insert(el.left.xhr.name);el.left.xhr.status=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").attribute.addClass("Block").environment.addStyle({"width":"10%"}).insert(el.left.xhr.container));el.left.xhr.statusTitle=new pi.element("STRONG").update("Status:").insert(el.left.xhr.status);el.left.xhr.statusContent=new pi.element("DIV").insert(el.left.xhr.status);el.left.xhr.readystate=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").environment.addStyle({"width":"15%"}).attribute.addClass("Block").insert(el.left.xhr.container));el.left.xhr.readystateTitle=el.left.xhr.nameTitle=new pi.element("STRONG").update("Ready State:").insert(el.left.xhr.readystate);el.left.xhr.readystateContent=new pi.element("DIV").insert(el.left.xhr.readystate);el.left.xhr.response=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").environment.addStyle({"width":(pi.env.ie?"50":"55")+"%"}).attribute.addClass("Block").insert(el.left.xhr.container));el.left.xhr.responseTitle=new pi.element("STRONG").update("Response:").insert(el.left.xhr.response);el.left.xhr.responseContent=new pi.element("DIV").insert(el.left.xhr.response);setTimeout(d.xhr.refresh,500)}},refresh:function(){with(firebug){el.left.xhr.nameContent.update("");el.left.xhr.statusContent.update("");el.left.xhr.readystateContent.update("");el.left.xhr.responseContent.update("");for(var i=0;i<d.xhr.objects.length;i++){var item=d.xhr.objects[i];var response=item[1].responseText;if(Boolean(item[1])==false)continue;el.left.xhr.nameContent.child.add(new pi.element("span").update(item[0]));try{el.left.xhr.statusContent.child.add(new pi.element("span").update(item[1].status))}catch(e){el.left.xhr.statusContent.child.add(new pi.element("span").update("&nbsp;"))}el.left.xhr.readystateContent.child.add(new pi.element("span").update(item[1].readyState));el.left.xhr.responseContent.child.add(new pi.element("span").child.add(new pi.element("A").event.addListener("click",d.str.open.curry(window,response)).update("&nbsp;"+response.substring(0,50))))};if(env.dIndex=="xhr")setTimeout(d.xhr.refresh,500)}}},navigateRightColumn:function(_index,_open){with(firebug){el.left.container.environment.addStyle({"width":_open?"70%":"100%"});el.right.container.environment.addStyle({"display":_open?"block":"none"})}},navigate:function(_index){with(firebug){var open=_index,close=env.dIndex;env.dIndex=open;el.button[close].container.environment.addStyle({"display":"none"});el.left[close].container.environment.addStyle({"display":"none"});el.right[close].container.environment.addStyle({"display":"none"});el.button[open].container.environment.addStyle({"display":"inline"});el.left[open].container.environment.addStyle({"display":"block"});el.right[open].container.environment.addStyle({"display":"block"});if(el.nav[close])el.nav[close].attribute.removeClass("Selected");if(el.nav[open])el.nav[open].attribute.addClass("Selected");switch(open){case"console":d.navigateRightColumn(_index);break;case"html":d.navigateRightColumn(_index,true);d.html.openHtmlTree();break;case"css":d.navigateRightColumn(_index,true);d.css.refresh();break;case"scripts":d.navigateRightColumn(_index);d.scripts.refresh();break;case"dom":d.navigateRightColumn(_index);if(el.left.dom.container.environment.getElement().innerHTML=="")d.dom.open(eval(el.button.dom.textbox.environment.getElement().value),el.left.dom.container);break;case"xhr":d.navigateRightColumn(_index);d.xhr.open();break}}},refreshSize:function(){with(firebug){el.main.environment.addStyle({"width":pi.util.GetWindowSize().width+"px"});if(pi.env.ie6)el.main.environment.addStyle({"top":pi.util.GetWindowSize().height-el.main.environment.getSize().offsetHeight+"px"})}}},getDomain:function(_url){return _url.match(/http:\/\/(www.)?([\.\w]+)/)[2]},listen:{addXhrObject:function(){with(firebug){d.xhr.addObject.apply(window,el.button.xhr.textbox.environment.getElement().value.split(","))}},consoleTextbox:function(_event){with(firebug){if(_event.keyCode==13&&(env.multilinemode==false||_event.shiftKey==false)){d.console.historyIndex=d.console.history.length;d.console.run(el.left.console.input.environment.getElement().value);return false}if([13,38,40].indexOf(_event.keyCode)==-1)return;d.console.historyIndex+=_event.keyCode!=40?0:d.console.historyIndex==d.console.history.length?0:1;d.console.historyIndex-=_event.keyCode!=38?0:d.console.historyIndex==0?0:1;el.left.console.input.update(d.console.history.length>d.console.historyIndex?d.console.history[d.console.historyIndex]:"")}},cssSelectbox:function(){with(firebug){d.css.open(el.button.css.selectbox.environment.getElement().selectedIndex)}},domTextbox:function(_event){with(firebug){if(_event.keyCode==13){d.dom.open(eval(el.button.dom.textbox.environment.getElement().value),el.left.dom.container)}}},inspector:function(){with(firebug){d.html.inspect(d.inspector.el)}},keyboard:function(_event){with(firebug){if(_event.keyCode==27&&d.inspector.enabled)d.inspector.toggle()}},mouse:function(_event){with(firebug){var target=_event[pi.env.ie?"srcElement":"target"];if(d.inspector.enabled&&target!=document.body&&target!=document.firstChild&&target!=document.childNodes[1]&&target!=el.borderInspector.environment.getElement()&&target!=el.main.environment.getElement()&&target.offsetParent!=el.main.environment.getElement())d.inspector.inspect(target)}},runMultiline:function(){with(firebug){d.console.run.call(window,el.right.console.input.environment.getElement().value)}},runCSS:function(){with(firebug){var source=el.right.css.input.environment.getElement().value.replace(/\n|\t/g,"").split("}");for(var i=0;i<source.length;i++){var item=source[i]+"}",rule=!pi.env.ie?item:item.split(/{|}/),collection=document.getElementsByTagName("style"),style=collection.length>0?collection[0]:document.body.appendChild(document.createElement("style"));if(!item.match(/.+\{.+\}/))continue;if(pi.env.ie)style.styleSheet.addRule(rule[0],rule[1]);else style.sheet.insertRule(rule,style.sheet.cssRules.length)}}},scriptsSelectbox:function(){with(firebug){d.scripts.open(parseInt(el.button.scripts.selectbox.environment.getElement().value))}},xhrTextbox:function(_event){with(firebug){if(_event.keyCode==13){d.xhr.addObject.apply(window,el.button.xhr.textbox.environment.getElement().value.split(","))}}}}};window.console=firebug.d.console;pi.util.AddEvent(window,"resize",firebug.d.refreshSize);pi.util.AddEvent(document,"mousemove",firebug.listen.mouse);pi.util.AddEvent(document,"keydown",firebug.listen.keyboard);pi.util.DOMContentLoaded.push(firebug.init);
\ No newline at end of file
diff --git a/timeside/ui/lib/jquery.js b/timeside/ui/lib/jquery.js
new file mode 100755 (executable)
index 0000000..88e661e
--- /dev/null
@@ -0,0 +1,3549 @@
+(function(){
+/*
+ * jQuery 1.2.6 - New Wave Javascript
+ *
+ * Copyright (c) 2008 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
+ * $Rev: 5685 $
+ */
+
+// Map over jQuery in case of overwrite
+var _jQuery = window.jQuery,
+// Map over the $ in case of overwrite
+       _$ = window.$;
+
+var jQuery = window.jQuery = window.$ = function( selector, context ) {
+       // The jQuery object is actually just the init constructor 'enhanced'
+       return new jQuery.fn.init( selector, context );
+};
+
+// A simple way to check for HTML strings or ID strings
+// (both of which we optimize for)
+var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,
+
+// Is it a simple selector
+       isSimple = /^.[^:#\[\.]*$/,
+
+// Will speed up references to undefined, and allows munging its name.
+       undefined;
+
+jQuery.fn = jQuery.prototype = {
+       init: function( selector, context ) {
+               // Make sure that a selection was provided
+               selector = selector || document;
+
+               // Handle $(DOMElement)
+               if ( selector.nodeType ) {
+                       this[0] = selector;
+                       this.length = 1;
+                       return this;
+               }
+               // Handle HTML strings
+               if ( typeof selector == "string" ) {
+                       // Are we dealing with HTML string or an ID?
+                       var match = quickExpr.exec( selector );
+
+                       // Verify a match, and that no context was specified for #id
+                       if ( match && (match[1] || !context) ) {
+
+                               // HANDLE: $(html) -> $(array)
+                               if ( match[1] )
+                                       selector = jQuery.clean( [ match[1] ], context );
+
+                               // HANDLE: $("#id")
+                               else {
+                                       var elem = document.getElementById( match[3] );
+
+                                       // Make sure an element was located
+                                       if ( elem ){
+                                               // Handle the case where IE and Opera return items
+                                               // by name instead of ID
+                                               if ( elem.id != match[3] )
+                                                       return jQuery().find( selector );
+
+                                               // Otherwise, we inject the element directly into the jQuery object
+                                               return jQuery( elem );
+                                       }
+                                       selector = [];
+                               }
+
+                       // HANDLE: $(expr, [context])
+                       // (which is just equivalent to: $(content).find(expr)
+                       } else
+                               return jQuery( context ).find( selector );
+
+               // HANDLE: $(function)
+               // Shortcut for document ready
+               } else if ( jQuery.isFunction( selector ) )
+                       return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );
+
+               return this.setArray(jQuery.makeArray(selector));
+       },
+
+       // The current version of jQuery being used
+       jquery: "1.2.6",
+
+       // The number of elements contained in the matched element set
+       size: function() {
+               return this.length;
+       },
+
+       // The number of elements contained in the matched element set
+       length: 0,
+
+       // Get the Nth element in the matched element set OR
+       // Get the whole matched element set as a clean array
+       get: function( num ) {
+               return num == undefined ?
+
+                       // Return a 'clean' array
+                       jQuery.makeArray( this ) :
+
+                       // Return just the object
+                       this[ num ];
+       },
+
+       // Take an array of elements and push it onto the stack
+       // (returning the new matched element set)
+       pushStack: function( elems ) {
+               // Build a new jQuery matched element set
+               var ret = jQuery( elems );
+
+               // Add the old object onto the stack (as a reference)
+               ret.prevObject = this;
+
+               // Return the newly-formed element set
+               return ret;
+       },
+
+       // Force the current matched set of elements to become
+       // the specified array of elements (destroying the stack in the process)
+       // You should use pushStack() in order to do this, but maintain the stack
+       setArray: function( elems ) {
+               // Resetting the length to 0, then using the native Array push
+               // is a super-fast way to populate an object with array-like properties
+               this.length = 0;
+               Array.prototype.push.apply( this, elems );
+
+               return this;
+       },
+
+       // Execute a callback for every element in the matched set.
+       // (You can seed the arguments with an array of args, but this is
+       // only used internally.)
+       each: function( callback, args ) {
+               return jQuery.each( this, callback, args );
+       },
+
+       // Determine the position of an element within
+       // the matched set of elements
+       index: function( elem ) {
+               var ret = -1;
+
+               // Locate the position of the desired element
+               return jQuery.inArray(
+                       // If it receives a jQuery object, the first element is used
+                       elem && elem.jquery ? elem[0] : elem
+               , this );
+       },
+
+       attr: function( name, value, type ) {
+               var options = name;
+
+               // Look for the case where we're accessing a style value
+               if ( name.constructor == String )
+                       if ( value === undefined )
+                               return this[0] && jQuery[ type || "attr" ]( this[0], name );
+
+                       else {
+                               options = {};
+                               options[ name ] = value;
+                       }
+
+               // Check to see if we're setting style values
+               return this.each(function(i){
+                       // Set all the styles
+                       for ( name in options )
+                               jQuery.attr(
+                                       type ?
+                                               this.style :
+                                               this,
+                                       name, jQuery.prop( this, options[ name ], type, i, name )
+                               );
+               });
+       },
+
+       css: function( key, value ) {
+               // ignore negative width and height values
+               if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
+                       value = undefined;
+               return this.attr( key, value, "curCSS" );
+       },
+
+       text: function( text ) {
+               if ( typeof text != "object" && text != null )
+                       return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+
+               var ret = "";
+
+               jQuery.each( text || this, function(){
+                       jQuery.each( this.childNodes, function(){
+                               if ( this.nodeType != 8 )
+                                       ret += this.nodeType != 1 ?
+                                               this.nodeValue :
+                                               jQuery.fn.text( [ this ] );
+                       });
+               });
+
+               return ret;
+       },
+
+       wrapAll: function( html ) {
+               if ( this[0] )
+                       // The elements to wrap the target around
+                       jQuery( html, this[0].ownerDocument )
+                               .clone()
+                               .insertBefore( this[0] )
+                               .map(function(){
+                                       var elem = this;
+
+                                       while ( elem.firstChild )
+                                               elem = elem.firstChild;
+
+                                       return elem;
+                               })
+                               .append(this);
+
+               return this;
+       },
+
+       wrapInner: function( html ) {
+               return this.each(function(){
+                       jQuery( this ).contents().wrapAll( html );
+               });
+       },
+
+       wrap: function( html ) {
+               return this.each(function(){
+                       jQuery( this ).wrapAll( html );
+               });
+       },
+
+       append: function() {
+               return this.domManip(arguments, true, false, function(elem){
+                       if (this.nodeType == 1)
+                               this.appendChild( elem );
+               });
+       },
+
+       prepend: function() {
+               return this.domManip(arguments, true, true, function(elem){
+                       if (this.nodeType == 1)
+                               this.insertBefore( elem, this.firstChild );
+               });
+       },
+
+       before: function() {
+               return this.domManip(arguments, false, false, function(elem){
+                       this.parentNode.insertBefore( elem, this );
+               });
+       },
+
+       after: function() {
+               return this.domManip(arguments, false, true, function(elem){
+                       this.parentNode.insertBefore( elem, this.nextSibling );
+               });
+       },
+
+       end: function() {
+               return this.prevObject || jQuery( [] );
+       },
+
+       find: function( selector ) {
+               var elems = jQuery.map(this, function(elem){
+                       return jQuery.find( selector, elem );
+               });
+
+               return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ?
+                       jQuery.unique( elems ) :
+                       elems );
+       },
+
+       clone: function( events ) {
+               // Do the clone
+               var ret = this.map(function(){
+                       if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) {
+                               // IE copies events bound via attachEvent when
+                               // using cloneNode. Calling detachEvent on the
+                               // clone will also remove the events from the orignal
+                               // In order to get around this, we use innerHTML.
+                               // Unfortunately, this means some modifications to
+                               // attributes in IE that are actually only stored
+                               // as properties will not be copied (such as the
+                               // the name attribute on an input).
+                               var clone = this.cloneNode(true),
+                                       container = document.createElement("div");
+                               container.appendChild(clone);
+                               return jQuery.clean([container.innerHTML])[0];
+                       } else
+                               return this.cloneNode(true);
+               });
+
+               // Need to set the expando to null on the cloned set if it exists
+               // removeData doesn't work here, IE removes it from the original as well
+               // this is primarily for IE but the data expando shouldn't be copied over in any browser
+               var clone = ret.find("*").andSelf().each(function(){
+                       if ( this[ expando ] != undefined )
+                               this[ expando ] = null;
+               });
+
+               // Copy the events from the original to the clone
+               if ( events === true )
+                       this.find("*").andSelf().each(function(i){
+                               if (this.nodeType == 3)
+                                       return;
+                               var events = jQuery.data( this, "events" );
+
+                               for ( var type in events )
+                                       for ( var handler in events[ type ] )
+                                               jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
+                       });
+
+               // Return the cloned set
+               return ret;
+       },
+
+       filter: function( selector ) {
+               return this.pushStack(
+                       jQuery.isFunction( selector ) &&
+                       jQuery.grep(this, function(elem, i){
+                               return selector.call( elem, i );
+                       }) ||
+
+                       jQuery.multiFilter( selector, this ) );
+       },
+
+       not: function( selector ) {
+               if ( selector.constructor == String )
+                       // test special case where just one selector is passed in
+                       if ( isSimple.test( selector ) )
+                               return this.pushStack( jQuery.multiFilter( selector, this, true ) );
+                       else
+                               selector = jQuery.multiFilter( selector, this );
+
+               var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
+               return this.filter(function() {
+                       return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
+               });
+       },
+
+       add: function( selector ) {
+               return this.pushStack( jQuery.unique( jQuery.merge(
+                       this.get(),
+                       typeof selector == 'string' ?
+                               jQuery( selector ) :
+                               jQuery.makeArray( selector )
+               )));
+       },
+
+       is: function( selector ) {
+               return !!selector && jQuery.multiFilter( selector, this ).length > 0;
+       },
+
+       hasClass: function( selector ) {
+               return this.is( "." + selector );
+       },
+
+       val: function( value ) {
+               if ( value == undefined ) {
+
+                       if ( this.length ) {
+                               var elem = this[0];
+
+                               // We need to handle select boxes special
+                               if ( jQuery.nodeName( elem, "select" ) ) {
+                                       var index = elem.selectedIndex,
+                                               values = [],
+                                               options = elem.options,
+                                               one = elem.type == "select-one";
+
+                                       // Nothing was selected
+                                       if ( index < 0 )
+                                               return null;
+
+                                       // Loop through all the selected options
+                                       for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+                                               var option = options[ i ];
+
+                                               if ( option.selected ) {
+                                                       // Get the specifc value for the option
+                                                       value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;
+
+                                                       // We don't need an array for one selects
+                                                       if ( one )
+                                                               return value;
+
+                                                       // Multi-Selects return an array
+                                                       values.push( value );
+                                               }
+                                       }
+
+                                       return values;
+
+                               // Everything else, we just grab the value
+                               } else
+                                       return (this[0].value || "").replace(/\r/g, "");
+
+                       }
+
+                       return undefined;
+               }
+
+               if( value.constructor == Number )
+                       value += '';
+
+               return this.each(function(){
+                       if ( this.nodeType != 1 )
+                               return;
+
+                       if ( value.constructor == Array && /radio|checkbox/.test( this.type ) )
+                               this.checked = (jQuery.inArray(this.value, value) >= 0 ||
+                                       jQuery.inArray(this.name, value) >= 0);
+
+                       else if ( jQuery.nodeName( this, "select" ) ) {
+                               var values = jQuery.makeArray(value);
+
+                               jQuery( "option", this ).each(function(){
+                                       this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
+                                               jQuery.inArray( this.text, values ) >= 0);
+                               });
+
+                               if ( !values.length )
+                                       this.selectedIndex = -1;
+
+                       } else
+                               this.value = value;
+               });
+       },
+
+       html: function( value ) {
+               return value == undefined ?
+                       (this[0] ?
+                               this[0].innerHTML :
+                               null) :
+                       this.empty().append( value );
+       },
+
+       replaceWith: function( value ) {
+               return this.after( value ).remove();
+       },
+
+       eq: function( i ) {
+               return this.slice( i, i + 1 );
+       },
+
+       slice: function() {
+               return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
+       },
+
+       map: function( callback ) {
+               return this.pushStack( jQuery.map(this, function(elem, i){
+                       return callback.call( elem, i, elem );
+               }));
+       },
+
+       andSelf: function() {
+               return this.add( this.prevObject );
+       },
+
+       data: function( key, value ){
+               var parts = key.split(".");
+               parts[1] = parts[1] ? "." + parts[1] : "";
+
+               if ( value === undefined ) {
+                       var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+                       if ( data === undefined && this.length )
+                               data = jQuery.data( this[0], key );
+
+                       return data === undefined && parts[1] ?
+                               this.data( parts[0] ) :
+                               data;
+               } else
+                       return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
+                               jQuery.data( this, key, value );
+                       });
+       },
+
+       removeData: function( key ){
+               return this.each(function(){
+                       jQuery.removeData( this, key );
+               });
+       },
+
+       domManip: function( args, table, reverse, callback ) {
+               var clone = this.length > 1, elems;
+
+               return this.each(function(){
+                       if ( !elems ) {
+                               elems = jQuery.clean( args, this.ownerDocument );
+
+                               if ( reverse )
+                                       elems.reverse();
+                       }
+
+                       var obj = this;
+
+                       if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) )
+                               obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );
+
+                       var scripts = jQuery( [] );
+
+                       jQuery.each(elems, function(){
+                               var elem = clone ?
+                                       jQuery( this ).clone( true )[0] :
+                                       this;
+
+                               // execute all scripts after the elements have been injected
+                               if ( jQuery.nodeName( elem, "script" ) )
+                                       scripts = scripts.add( elem );
+                               else {
+                                       // Remove any inner scripts for later evaluation
+                                       if ( elem.nodeType == 1 )
+                                               scripts = scripts.add( jQuery( "script", elem ).remove() );
+
+                                       // Inject the elements into the document
+                                       callback.call( obj, elem );
+                               }
+                       });
+
+                       scripts.each( evalScript );
+               });
+       }
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+function evalScript( i, elem ) {
+       if ( elem.src )
+               jQuery.ajax({
+                       url: elem.src,
+                       async: false,
+                       dataType: "script"
+               });
+
+       else
+               jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+
+       if ( elem.parentNode )
+               elem.parentNode.removeChild( elem );
+}
+
+function now(){
+       return +new Date;
+}
+
+jQuery.extend = jQuery.fn.extend = function() {
+       // copy reference to target object
+       var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
+
+       // Handle a deep copy situation
+       if ( target.constructor == Boolean ) {
+               deep = target;
+               target = arguments[1] || {};
+               // skip the boolean and the target
+               i = 2;
+       }
+
+       // Handle case when target is a string or something (possible in deep copy)
+       if ( typeof target != "object" && typeof target != "function" )
+               target = {};
+
+       // extend jQuery itself if only one argument is passed
+       if ( length == i ) {
+               target = this;
+               --i;
+       }
+
+       for ( ; i < length; i++ )
+               // Only deal with non-null/undefined values
+               if ( (options = arguments[ i ]) != null )
+                       // Extend the base object
+                       for ( var name in options ) {
+                               var src = target[ name ], copy = options[ name ];
+
+                               // Prevent never-ending loop
+                               if ( target === copy )
+                                       continue;
+
+                               // Recurse if we're merging object values
+                               if ( deep && copy && typeof copy == "object" && !copy.nodeType )
+                                       target[ name ] = jQuery.extend( deep, 
+                                               // Never move original objects, clone them
+                                               src || ( copy.length != null ? [ ] : { } )
+                                       , copy );
+
+                               // Don't bring in undefined values
+                               else if ( copy !== undefined )
+                                       target[ name ] = copy;
+
+                       }
+
+       // Return the modified object
+       return target;
+};
+
+var expando = "jQuery" + now(), uuid = 0, windowData = {},
+       // exclude the following css properties to add px
+       exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
+       // cache defaultView
+       defaultView = document.defaultView || {};
+
+jQuery.extend({
+       noConflict: function( deep ) {
+               window.$ = _$;
+
+               if ( deep )
+                       window.jQuery = _jQuery;
+
+               return jQuery;
+       },
+
+       // See test/unit/core.js for details concerning this function.
+       isFunction: function( fn ) {
+               return !!fn && typeof fn != "string" && !fn.nodeName &&
+                       fn.constructor != Array && /^[\s[]?function/.test( fn + "" );
+       },
+
+       // check if an element is in a (or is an) XML document
+       isXMLDoc: function( elem ) {
+               return elem.documentElement && !elem.body ||
+                       elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
+       },
+
+       // Evalulates a script in a global context
+       globalEval: function( data ) {
+               data = jQuery.trim( data );
+
+               if ( data ) {
+                       // Inspired by code by Andrea Giammarchi
+                       // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+                       var head = document.getElementsByTagName("head")[0] || document.documentElement,
+                               script = document.createElement("script");
+
+                       script.type = "text/javascript";
+                       if ( jQuery.browser.msie )
+                               script.text = data;
+                       else
+                               script.appendChild( document.createTextNode( data ) );
+
+                       // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
+                       // This arises when a base node is used (#2709).
+                       head.insertBefore( script, head.firstChild );
+                       head.removeChild( script );
+               }
+       },
+
+       nodeName: function( elem, name ) {
+               return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
+       },
+
+       cache: {},
+
+       data: function( elem, name, data ) {
+               elem = elem == window ?
+                       windowData :
+                       elem;
+
+               var id = elem[ expando ];
+
+               // Compute a unique ID for the element
+               if ( !id )
+                       id = elem[ expando ] = ++uuid;
+
+               // Only generate the data cache if we're
+               // trying to access or manipulate it
+               if ( name && !jQuery.cache[ id ] )
+                       jQuery.cache[ id ] = {};
+
+               // Prevent overriding the named cache with undefined values
+               if ( data !== undefined )
+                       jQuery.cache[ id ][ name ] = data;
+
+               // Return the named cache data, or the ID for the element
+               return name ?
+                       jQuery.cache[ id ][ name ] :
+                       id;
+       },
+
+       removeData: function( elem, name ) {
+               elem = elem == window ?
+                       windowData :
+                       elem;
+
+               var id = elem[ expando ];
+
+               // If we want to remove a specific section of the element's data
+               if ( name ) {
+                       if ( jQuery.cache[ id ] ) {
+                               // Remove the section of cache data
+                               delete jQuery.cache[ id ][ name ];
+
+                               // If we've removed all the data, remove the element's cache
+                               name = "";
+
+                               for ( name in jQuery.cache[ id ] )
+                                       break;
+
+                               if ( !name )
+                                       jQuery.removeData( elem );
+                       }
+
+               // Otherwise, we want to remove all of the element's data
+               } else {
+                       // Clean up the element expando
+                       try {
+                               delete elem[ expando ];
+                       } catch(e){
+                               // IE has trouble directly removing the expando
+                               // but it's ok with using removeAttribute
+                               if ( elem.removeAttribute )
+                                       elem.removeAttribute( expando );
+                       }
+
+                       // Completely remove the data cache
+                       delete jQuery.cache[ id ];
+               }
+       },
+
+       // args is for internal usage only
+       each: function( object, callback, args ) {
+               var name, i = 0, length = object.length;
+
+               if ( args ) {
+                       if ( length == undefined ) {
+                               for ( name in object )
+                                       if ( callback.apply( object[ name ], args ) === false )
+                                               break;
+                       } else
+                               for ( ; i < length; )
+                                       if ( callback.apply( object[ i++ ], args ) === false )
+                                               break;
+
+               // A special, fast, case for the most common use of each
+               } else {
+                       if ( length == undefined ) {
+                               for ( name in object )
+                                       if ( callback.call( object[ name ], name, object[ name ] ) === false )
+                                               break;
+                       } else
+                               for ( var value = object[0];
+                                       i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
+               }
+
+               return object;
+       },
+
+       prop: function( elem, value, type, i, name ) {
+               // Handle executable functions
+               if ( jQuery.isFunction( value ) )
+                       value = value.call( elem, i );
+
+               // Handle passing in a number to a CSS property
+               return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ?
+                       value + "px" :
+                       value;
+       },
+
+       className: {
+               // internal only, use addClass("class")
+               add: function( elem, classNames ) {
+                       jQuery.each((classNames || "").split(/\s+/), function(i, className){
+                               if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
+                                       elem.className += (elem.className ? " " : "") + className;
+                       });
+               },
+
+               // internal only, use removeClass("class")
+               remove: function( elem, classNames ) {
+                       if (elem.nodeType == 1)
+                               elem.className = classNames != undefined ?
+                                       jQuery.grep(elem.className.split(/\s+/), function(className){
+                                               return !jQuery.className.has( classNames, className );
+                                       }).join(" ") :
+                                       "";
+               },
+
+               // internal only, use hasClass("class")
+               has: function( elem, className ) {
+                       return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
+               }
+       },
+
+       // A method for quickly swapping in/out CSS properties to get correct calculations
+       swap: function( elem, options, callback ) {
+               var old = {};
+               // Remember the old values, and insert the new ones
+               for ( var name in options ) {
+                       old[ name ] = elem.style[ name ];
+                       elem.style[ name ] = options[ name ];
+               }
+
+               callback.call( elem );
+
+               // Revert the old values
+               for ( var name in options )
+                       elem.style[ name ] = old[ name ];
+       },
+
+       css: function( elem, name, force ) {
+               if ( name == "width" || name == "height" ) {
+                       var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
+
+                       function getWH() {
+                               val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
+                               var padding = 0, border = 0;
+                               jQuery.each( which, function() {
+                                       padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
+                                       border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
+                               });
+                               val -= Math.round(padding + border);
+                       }
+
+                       if ( jQuery(elem).is(":visible") )
+                               getWH();
+                       else
+                               jQuery.swap( elem, props, getWH );
+
+                       return Math.max(0, val);
+               }
+
+               return jQuery.curCSS( elem, name, force );
+       },
+
+       curCSS: function( elem, name, force ) {
+               var ret, style = elem.style;
+
+               // A helper method for determining if an element's values are broken
+               function color( elem ) {
+                       if ( !jQuery.browser.safari )
+                               return false;
+
+                       // defaultView is cached
+                       var ret = defaultView.getComputedStyle( elem, null );
+                       return !ret || ret.getPropertyValue("color") == "";
+               }
+
+               // We need to handle opacity special in IE
+               if ( name == "opacity" && jQuery.browser.msie ) {
+                       ret = jQuery.attr( style, "opacity" );
+
+                       return ret == "" ?
+                               "1" :
+                               ret;
+               }
+               // Opera sometimes will give the wrong display answer, this fixes it, see #2037
+               if ( jQuery.browser.opera && name == "display" ) {
+                       var save = style.outline;
+                       style.outline = "0 solid black";
+                       style.outline = save;
+               }
+
+               // Make sure we're using the right name for getting the float value
+               if ( name.match( /float/i ) )
+                       name = styleFloat;
+
+               if ( !force && style && style[ name ] )
+                       ret = style[ name ];
+
+               else if ( defaultView.getComputedStyle ) {
+
+                       // Only "float" is needed here
+                       if ( name.match( /float/i ) )
+                               name = "float";
+
+                       name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
+
+                       var computedStyle = defaultView.getComputedStyle( elem, null );
+
+                       if ( computedStyle && !color( elem ) )
+                               ret = computedStyle.getPropertyValue( name );
+
+                       // If the element isn't reporting its values properly in Safari
+                       // then some display: none elements are involved
+                       else {
+                               var swap = [], stack = [], a = elem, i = 0;
+
+                               // Locate all of the parent display: none elements
+                               for ( ; a && color(a); a = a.parentNode )
+                                       stack.unshift(a);
+
+                               // Go through and make them visible, but in reverse
+                               // (It would be better if we knew the exact display type that they had)
+                               for ( ; i < stack.length; i++ )
+                                       if ( color( stack[ i ] ) ) {
+                                               swap[ i ] = stack[ i ].style.display;
+                                               stack[ i ].style.display = "block";
+                                       }
+
+                               // Since we flip the display style, we have to handle that
+                               // one special, otherwise get the value
+                               ret = name == "display" && swap[ stack.length - 1 ] != null ?
+                                       "none" :
+                                       ( computedStyle && computedStyle.getPropertyValue( name ) ) || "";
+
+                               // Finally, revert the display styles back
+                               for ( i = 0; i < swap.length; i++ )
+                                       if ( swap[ i ] != null )
+                                               stack[ i ].style.display = swap[ i ];
+                       }
+
+                       // We should always get a number back from opacity
+                       if ( name == "opacity" && ret == "" )
+                               ret = "1";
+
+               } else if ( elem.currentStyle ) {
+                       var camelCase = name.replace(/\-(\w)/g, function(all, letter){
+                               return letter.toUpperCase();
+                       });
+
+                       ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
+
+                       // From the awesome hack by Dean Edwards
+                       // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+                       // If we're not dealing with a regular pixel number
+                       // but a number that has a weird ending, we need to convert it to pixels
+                       if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
+                               // Remember the original values
+                               var left = style.left, rsLeft = elem.runtimeStyle.left;
+
+                               // Put in the new values to get a computed value out
+                               elem.runtimeStyle.left = elem.currentStyle.left;
+                               style.left = ret || 0;
+                               ret = style.pixelLeft + "px";
+
+                               // Revert the changed values
+                               style.left = left;
+                               elem.runtimeStyle.left = rsLeft;
+                       }
+               }
+
+               return ret;
+       },
+
+       clean: function( elems, context ) {
+               var ret = [];
+               context = context || document;
+               // !context.createElement fails in IE with an error but returns typeof 'object'
+               if (typeof context.createElement == 'undefined')
+                       context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+
+               jQuery.each(elems, function(i, elem){
+                       if ( !elem )
+                               return;
+
+                       if ( elem.constructor == Number )
+                               elem += '';
+
+                       // Convert html string into DOM nodes
+                       if ( typeof elem == "string" ) {
+                               // Fix "XHTML"-style tags in all browsers
+                               elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
+                                       return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
+                                               all :
+                                               front + "></" + tag + ">";
+                               });
+
+                               // Trim whitespace, otherwise indexOf won't work as expected
+                               var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div");
+
+                               var wrap =
+                                       // option or optgroup
+                                       !tags.indexOf("<opt") &&
+                                       [ 1, "<select multiple='multiple'>", "</select>" ] ||
+
+                                       !tags.indexOf("<leg") &&
+                                       [ 1, "<fieldset>", "</fieldset>" ] ||
+
+                                       tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
+                                       [ 1, "<table>", "</table>" ] ||
+
+                                       !tags.indexOf("<tr") &&
+                                       [ 2, "<table><tbody>", "</tbody></table>" ] ||
+
+                                       // <thead> matched above
+                                       (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
+                                       [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
+
+                                       !tags.indexOf("<col") &&
+                                       [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
+
+                                       // IE can't serialize <link> and <script> tags normally
+                                       jQuery.browser.msie &&
+                                       [ 1, "div<div>", "</div>" ] ||
+
+                                       [ 0, "", "" ];
+
+                               // Go to html and back, then peel off extra wrappers
+                               div.innerHTML = wrap[1] + elem + wrap[2];
+
+                               // Move to the right depth
+                               while ( wrap[0]-- )
+                                       div = div.lastChild;
+
+                               // Remove IE's autoinserted <tbody> from table fragments
+                               if ( jQuery.browser.msie ) {
+
+                                       // String was a <table>, *may* have spurious <tbody>
+                                       var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
+                                               div.firstChild && div.firstChild.childNodes :
+
+                                               // String was a bare <thead> or <tfoot>
+                                               wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
+                                                       div.childNodes :
+                                                       [];
+
+                                       for ( var j = tbody.length - 1; j >= 0 ; --j )
+                                               if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
+                                                       tbody[ j ].parentNode.removeChild( tbody[ j ] );
+
+                                       // IE completely kills leading whitespace when innerHTML is used
+                                       if ( /^\s/.test( elem ) )
+                                               div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
+
+                               }
+
+                               elem = jQuery.makeArray( div.childNodes );
+                       }
+
+                       if ( elem.length === 0 && (!jQuery.nodeName( elem, "form" ) && !jQuery.nodeName( elem, "select" )) )
+                               return;
+
+                       if ( elem[0] == undefined || jQuery.nodeName( elem, "form" ) || elem.options )
+                               ret.push( elem );
+
+                       else
+                               ret = jQuery.merge( ret, elem );
+
+               });
+
+               return ret;
+       },
+
+       attr: function( elem, name, value ) {
+               // don't set attributes on text and comment nodes
+               if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
+                       return undefined;
+
+               var notxml = !jQuery.isXMLDoc( elem ),
+                       // Whether we are setting (or getting)
+                       set = value !== undefined,
+                       msie = jQuery.browser.msie;
+
+               // Try to normalize/fix the name
+               name = notxml && jQuery.props[ name ] || name;
+
+               // Only do all the following if this is a node (faster for style)
+               // IE elem.getAttribute passes even for style
+               if ( elem.tagName ) {
+
+                       // These attributes require special treatment
+                       var special = /href|src|style/.test( name );
+
+                       // Safari mis-reports the default selected property of a hidden option
+                       // Accessing the parent's selectedIndex property fixes it
+                       if ( name == "selected" && jQuery.browser.safari )
+                               elem.parentNode.selectedIndex;
+
+                       // If applicable, access the attribute via the DOM 0 way
+                       if ( name in elem && notxml && !special ) {
+                               if ( set ){
+                                       // We can't allow the type property to be changed (since it causes problems in IE)
+                                       if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
+                                               throw "type property can't be changed";
+
+                                       elem[ name ] = value;
+                               }
+
+                               // browsers index elements by id/name on forms, give priority to attributes.
+                               if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
+                                       return elem.getAttributeNode( name ).nodeValue;
+
+                               return elem[ name ];
+                       }
+
+                       if ( msie && notxml &&  name == "style" )
+                               return jQuery.attr( elem.style, "cssText", value );
+
+                       if ( set )
+                               // convert the value to a string (all browsers do this but IE) see #1070
+                               elem.setAttribute( name, "" + value );
+
+                       var attr = msie && notxml && special
+                                       // Some attributes require a special call on IE
+                                       ? elem.getAttribute( name, 2 )
+                                       : elem.getAttribute( name );
+
+                       // Non-existent attributes return null, we normalize to undefined
+                       return attr === null ? undefined : attr;
+               }
+
+               // elem is actually elem.style ... set the style
+
+               // IE uses filters for opacity
+               if ( msie && name == "opacity" ) {
+                       if ( set ) {
+                               // IE has trouble with opacity if it does not have layout
+                               // Force it by setting the zoom level
+                               elem.zoom = 1;
+
+                               // Set the alpha filter to set the opacity
+                               elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
+                                       (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
+                       }
+
+                       return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
+                               (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
+                               "";
+               }
+
+               name = name.replace(/-([a-z])/ig, function(all, letter){
+                       return letter.toUpperCase();
+               });
+
+               if ( set )
+                       elem[ name ] = value;
+
+               return elem[ name ];
+       },
+
+       trim: function( text ) {
+               return (text || "").replace( /^\s+|\s+$/g, "" );
+       },
+
+       makeArray: function( array ) {
+               var ret = [];
+
+               if( array != null ){
+                       var i = array.length;
+                       //the window, strings and functions also have 'length'
+                       if( i == null || array.split || array.setInterval || array.call )
+                               ret[0] = array;
+                       else
+                               while( i )
+                                       ret[--i] = array[i];
+               }
+
+               return ret;
+       },
+
+       inArray: function( elem, array ) {
+               for ( var i = 0, length = array.length; i < length; i++ )
+               // Use === because on IE, window == document
+                       if ( array[ i ] === elem )
+                               return i;
+
+               return -1;
+       },
+
+       merge: function( first, second ) {
+               // We have to loop this way because IE & Opera overwrite the length
+               // expando of getElementsByTagName
+               var i = 0, elem, pos = first.length;
+               // Also, we need to make sure that the correct elements are being returned
+               // (IE returns comment nodes in a '*' query)
+               if ( jQuery.browser.msie ) {
+                       while ( elem = second[ i++ ] )
+                               if ( elem.nodeType != 8 )
+                                       first[ pos++ ] = elem;
+
+               } else
+                       while ( elem = second[ i++ ] )
+                               first[ pos++ ] = elem;
+
+               return first;
+       },
+
+       unique: function( array ) {
+               var ret = [], done = {};
+
+               try {
+
+                       for ( var i = 0, length = array.length; i < length; i++ ) {
+                               var id = jQuery.data( array[ i ] );
+
+                               if ( !done[ id ] ) {
+                                       done[ id ] = true;
+                                       ret.push( array[ i ] );
+                               }
+                       }
+
+               } catch( e ) {
+                       ret = array;
+               }
+
+               return ret;
+       },
+
+       grep: function( elems, callback, inv ) {
+               var ret = [];
+
+               // Go through the array, only saving the items
+               // that pass the validator function
+               for ( var i = 0, length = elems.length; i < length; i++ )
+                       if ( !inv != !callback( elems[ i ], i ) )
+                               ret.push( elems[ i ] );
+
+               return ret;
+       },
+
+       map: function( elems, callback ) {
+               var ret = [];
+
+               // Go through the array, translating each of the items to their
+               // new value (or values).
+               for ( var i = 0, length = elems.length; i < length; i++ ) {
+                       var value = callback( elems[ i ], i );
+
+                       if ( value != null )
+                               ret[ ret.length ] = value;
+               }
+
+               return ret.concat.apply( [], ret );
+       }
+});
+
+var userAgent = navigator.userAgent.toLowerCase();
+
+// Figure out what browser is being used
+jQuery.browser = {
+       version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
+       safari: /webkit/.test( userAgent ),
+       opera: /opera/.test( userAgent ),
+       msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
+       mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
+};
+
+var styleFloat = jQuery.browser.msie ?
+       "styleFloat" :
+       "cssFloat";
+
+jQuery.extend({
+       // Check to see if the W3C box model is being used
+       boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",
+
+       props: {
+               "for": "htmlFor",
+               "class": "className",
+               "float": styleFloat,
+               cssFloat: styleFloat,
+               styleFloat: styleFloat,
+               readonly: "readOnly",
+               maxlength: "maxLength",
+               cellspacing: "cellSpacing"
+       }
+});
+
+jQuery.each({
+       parent: function(elem){return elem.parentNode;},
+       parents: function(elem){return jQuery.dir(elem,"parentNode");},
+       next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
+       prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
+       nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
+       prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
+       siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
+       children: function(elem){return jQuery.sibling(elem.firstChild);},
+       contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
+}, function(name, fn){
+       jQuery.fn[ name ] = function( selector ) {
+               var ret = jQuery.map( this, fn );
+
+               if ( selector && typeof selector == "string" )
+                       ret = jQuery.multiFilter( selector, ret );
+
+               return this.pushStack( jQuery.unique( ret ) );
+       };
+});
+
+jQuery.each({
+       appendTo: "append",
+       prependTo: "prepend",
+       insertBefore: "before",
+       insertAfter: "after",
+       replaceAll: "replaceWith"
+}, function(name, original){
+       jQuery.fn[ name ] = function() {
+               var args = arguments;
+
+               return this.each(function(){
+                       for ( var i = 0, length = args.length; i < length; i++ )
+                               jQuery( args[ i ] )[ original ]( this );
+               });
+       };
+});
+
+jQuery.each({
+       removeAttr: function( name ) {
+               jQuery.attr( this, name, "" );
+               if (this.nodeType == 1)
+                       this.removeAttribute( name );
+       },
+
+       addClass: function( classNames ) {
+               jQuery.className.add( this, classNames );
+       },
+
+       removeClass: function( classNames ) {
+               jQuery.className.remove( this, classNames );
+       },
+
+       toggleClass: function( classNames ) {
+               jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
+       },
+
+       remove: function( selector ) {
+               if ( !selector || jQuery.filter( selector, [ this ] ).r.length ) {
+                       // Prevent memory leaks
+                       jQuery( "*", this ).add(this).each(function(){
+                               jQuery.event.remove(this);
+                               jQuery.removeData(this);
+                       });
+                       if (this.parentNode)
+                               this.parentNode.removeChild( this );
+               }
+       },
+
+       empty: function() {
+               // Remove element nodes and prevent memory leaks
+               jQuery( ">*", this ).remove();
+
+               // Remove any remaining nodes
+               while ( this.firstChild )
+                       this.removeChild( this.firstChild );
+       }
+}, function(name, fn){
+       jQuery.fn[ name ] = function(){
+               return this.each( fn, arguments );
+       };
+});
+
+jQuery.each([ "Height", "Width" ], function(i, name){
+       var type = name.toLowerCase();
+
+       jQuery.fn[ type ] = function( size ) {
+               // Get window width or height
+               return this[0] == window ?
+                       // Opera reports document.body.client[Width/Height] properly in both quirks and standards
+                       jQuery.browser.opera && document.body[ "client" + name ] ||
+
+                       // Safari reports inner[Width/Height] just fine (Mozilla and Opera include scroll bar widths)
+                       jQuery.browser.safari && window[ "inner" + name ] ||
+
+                       // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+                       document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] :
+
+                       // Get document width or height
+                       this[0] == document ?
+                               // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+                               Math.max(
+                                       Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
+                                       Math.max(document.body["offset" + name], document.documentElement["offset" + name])
+                               ) :
+
+                               // Get or set width or height on the element
+                               size == undefined ?
+                                       // Get width or height on the element
+                                       (this.length ? jQuery.css( this[0], type ) : null) :
+
+                                       // Set the width or height on the element (default to pixels if value is unitless)
+                                       this.css( type, size.constructor == String ? size : size + "px" );
+       };
+});
+
+// Helper function used by the dimensions and offset modules
+function num(elem, prop) {
+       return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
+}var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
+               "(?:[\\w*_-]|\\\\.)" :
+               "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
+       quickChild = new RegExp("^>\\s*(" + chars + "+)"),
+       quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
+       quickClass = new RegExp("^([#.]?)(" + chars + "*)");
+
+jQuery.extend({
+       expr: {
+               "": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
+               "#": function(a,i,m){return a.getAttribute("id")==m[2];},
+               ":": {
+                       // Position Checks
+                       lt: function(a,i,m){return i<m[3]-0;},
+                       gt: function(a,i,m){return i>m[3]-0;},
+                       nth: function(a,i,m){return m[3]-0==i;},
+                       eq: function(a,i,m){return m[3]-0==i;},
+                       first: function(a,i){return i==0;},
+                       last: function(a,i,m,r){return i==r.length-1;},
+                       even: function(a,i){return i%2==0;},
+                       odd: function(a,i){return i%2;},
+
+                       // Child Checks
+                       "first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
+                       "last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
+                       "only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},
+
+                       // Parent Checks
+                       parent: function(a){return a.firstChild;},
+                       empty: function(a){return !a.firstChild;},
+
+                       // Text Check
+                       contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},
+
+                       // Visibility
+                       visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
+                       hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},
+
+                       // Form attributes
+                       enabled: function(a){return !a.disabled;},
+                       disabled: function(a){return a.disabled;},
+                       checked: function(a){return a.checked;},
+                       selected: function(a){return a.selected||jQuery.attr(a,"selected");},
+
+                       // Form elements
+                       text: function(a){return "text"==a.type;},
+                       radio: function(a){return "radio"==a.type;},
+                       checkbox: function(a){return "checkbox"==a.type;},
+                       file: function(a){return "file"==a.type;},
+                       password: function(a){return "password"==a.type;},
+                       submit: function(a){return "submit"==a.type;},
+                       image: function(a){return "image"==a.type;},
+                       reset: function(a){return "reset"==a.type;},
+                       button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
+                       input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},
+
+                       // :has()
+                       has: function(a,i,m){return jQuery.find(m[3],a).length;},
+
+                       // :header
+                       header: function(a){return /h\d/i.test(a.nodeName);},
+
+                       // :animated
+                       animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
+               }
+       },
+
+       // The regular expressions that power the parsing engine
+       parse: [
+               // Match: [@value='test'], [@foo]
+               /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
+
+               // Match: :contains('foo')
+               /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
+
+               // Match: :even, :last-child, #id, .class
+               new RegExp("^([:.#]*)(" + chars + "+)")
+       ],
+
+       multiFilter: function( expr, elems, not ) {
+               var old, cur = [];
+
+               while ( expr && expr != old ) {
+                       old = expr;
+                       var f = jQuery.filter( expr, elems, not );
+                       expr = f.t.replace(/^\s*,\s*/, "" );
+                       cur = not ? elems = f.r : jQuery.merge( cur, f.r );
+               }
+
+               return cur;
+       },
+
+       find: function( t, context ) {
+               // Quickly handle non-string expressions
+               if ( typeof t != "string" )
+                       return [ t ];
+
+               // check to make sure context is a DOM element or a document
+               if ( context && context.nodeType != 1 && context.nodeType != 9)
+                       return [ ];
+
+               // Set the correct context (if none is provided)
+               context = context || document;
+
+               // Initialize the search
+               var ret = [context], done = [], last, nodeName;
+
+               // Continue while a selector expression exists, and while
+               // we're no longer looping upon ourselves
+               while ( t && last != t ) {
+                       var r = [];
+                       last = t;
+
+                       t = jQuery.trim(t);
+
+                       var foundToken = false,
+
+                       // An attempt at speeding up child selectors that
+                       // point to a specific element tag
+                               re = quickChild,
+
+                               m = re.exec(t);
+
+                       if ( m ) {
+                               nodeName = m[1].toUpperCase();
+
+                               // Perform our own iteration and filter
+                               for ( var i = 0; ret[i]; i++ )
+                                       for ( var c = ret[i].firstChild; c; c = c.nextSibling )
+                                               if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
+                                                       r.push( c );
+
+                               ret = r;
+                               t = t.replace( re, "" );
+                               if ( t.indexOf(" ") == 0 ) continue;
+                               foundToken = true;
+                       } else {
+                               re = /^([>+~])\s*(\w*)/i;
+
+                               if ( (m = re.exec(t)) != null ) {
+                                       r = [];
+
+                                       var merge = {};
+                                       nodeName = m[2].toUpperCase();
+                                       m = m[1];
+
+                                       for ( var j = 0, rl = ret.length; j < rl; j++ ) {
+                                               var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
+                                               for ( ; n; n = n.nextSibling )
+                                                       if ( n.nodeType == 1 ) {
+                                                               var id = jQuery.data(n);
+
+                                                               if ( m == "~" && merge[id] ) break;
+
+                                                               if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
+                                                                       if ( m == "~" ) merge[id] = true;
+                                                                       r.push( n );
+                                                               }
+
+                                                               if ( m == "+" ) break;
+                                                       }
+                                       }
+
+                                       ret = r;
+
+                                       // And remove the token
+                                       t = jQuery.trim( t.replace( re, "" ) );
+                                       foundToken = true;
+                               }
+                       }
+
+                       // See if there's still an expression, and that we haven't already
+                       // matched a token
+                       if ( t && !foundToken ) {
+                               // Handle multiple expressions
+                               if ( !t.indexOf(",") ) {
+                                       // Clean the result set
+                                       if ( context == ret[0] ) ret.shift();
+
+                                       // Merge the result sets
+                                       done = jQuery.merge( done, ret );
+
+                                       // Reset the context
+                                       r = ret = [context];
+
+                                       // Touch up the selector string
+                                       t = " " + t.substr(1,t.length);
+
+                               } else {
+                                       // Optimize for the case nodeName#idName
+                                       var re2 = quickID;
+                                       var m = re2.exec(t);
+
+                                       // Re-organize the results, so that they're consistent
+                                       if ( m ) {
+                                               m = [ 0, m[2], m[3], m[1] ];
+
+                                       } else {
+                                               // Otherwise, do a traditional filter check for
+                                               // ID, class, and element selectors
+                                               re2 = quickClass;
+                                               m = re2.exec(t);
+                                       }
+
+                                       m[2] = m[2].replace(/\\/g, "");
+
+                                       var elem = ret[ret.length-1];
+
+                                       // Try to do a global search by ID, where we can
+                                       if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
+                                               // Optimization for HTML document case
+                                               var oid = elem.getElementById(m[2]);
+
+                                               // Do a quick check for the existence of the actual ID attribute
+                                               // to avoid selecting by the name attribute in IE
+                                               // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
+                                               if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
+                                                       oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
+
+                                               // Do a quick check for node name (where applicable) so
+                                               // that div#foo searches will be really fast
+                                               ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
+                                       } else {
+                                               // We need to find all descendant elements
+                                               for ( var i = 0; ret[i]; i++ ) {
+                                                       // Grab the tag name being searched for
+                                                       var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];
+
+                                                       // Handle IE7 being really dumb about <object>s
+                                                       if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
+                                                               tag = "param";
+
+                                                       r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
+                                               }
+
+                                               // It's faster to filter by class and be done with it
+                                               if ( m[1] == "." )
+                                                       r = jQuery.classFilter( r, m[2] );
+
+                                               // Same with ID filtering
+                                               if ( m[1] == "#" ) {
+                                                       var tmp = [];
+
+                                                       // Try to find the element with the ID
+                                                       for ( var i = 0; r[i]; i++ )
+                                                               if ( r[i].getAttribute("id") == m[2] ) {
+                                                                       tmp = [ r[i] ];
+                                                                       break;
+                                                               }
+
+                                                       r = tmp;
+                                               }
+
+                                               ret = r;
+                                       }
+
+                                       t = t.replace( re2, "" );
+                               }
+
+                       }
+
+                       // If a selector string still exists
+                       if ( t ) {
+                               // Attempt to filter it
+                               var val = jQuery.filter(t,r);
+                               ret = r = val.r;
+                               t = jQuery.trim(val.t);
+                       }
+               }
+
+               // An error occurred with the selector;
+               // just return an empty set instead
+               if ( t )
+                       ret = [];
+
+               // Remove the root context
+               if ( ret && context == ret[0] )
+                       ret.shift();
+
+               // And combine the results
+               done = jQuery.merge( done, ret );
+
+               return done;
+       },
+
+       classFilter: function(r,m,not){
+               m = " " + m + " ";
+               var tmp = [];
+               for ( var i = 0; r[i]; i++ ) {
+                       var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
+                       if ( !not && pass || not && !pass )
+                               tmp.push( r[i] );
+               }
+               return tmp;
+       },
+
+       filter: function(t,r,not) {
+               var last;
+
+               // Look for common filter expressions
+               while ( t && t != last ) {
+                       last = t;
+
+                       var p = jQuery.parse, m;
+
+                       for ( var i = 0; p[i]; i++ ) {
+                               m = p[i].exec( t );
+
+                               if ( m ) {
+                                       // Remove what we just matched
+                                       t = t.substring( m[0].length );
+
+                                       m[2] = m[2].replace(/\\/g, "");
+                                       break;
+                               }
+                       }
+
+                       if ( !m )
+                               break;
+
+                       // :not() is a special case that can be optimized by
+                       // keeping it out of the expression list
+                       if ( m[1] == ":" && m[2] == "not" )
+                               // optimize if only one selector found (most common case)
+                               r = isSimple.test( m[3] ) ?
+                                       jQuery.filter(m[3], r, true).r :
+                                       jQuery( r ).not( m[3] );
+
+                       // We can get a big speed boost by filtering by class here
+                       else if ( m[1] == "." )
+                               r = jQuery.classFilter(r, m[2], not);
+
+                       else if ( m[1] == "[" ) {
+                               var tmp = [], type = m[3];
+
+                               for ( var i = 0, rl = r.length; i < rl; i++ ) {
+                                       var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
+
+                                       if ( z == null || /href|src|selected/.test(m[2]) )
+                                               z = jQuery.attr(a,m[2]) || '';
+
+                                       if ( (type == "" && !!z ||
+                                                type == "=" && z == m[5] ||
+                                                type == "!=" && z != m[5] ||
+                                                type == "^=" && z && !z.indexOf(m[5]) ||
+                                                type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
+                                                (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
+                                                       tmp.push( a );
+                               }
+
+                               r = tmp;
+
+                       // We can get a speed boost by handling nth-child here
+                       } else if ( m[1] == ":" && m[2] == "nth-child" ) {
+                               var merge = {}, tmp = [],
+                                       // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+                                       test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+                                               m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
+                                               !/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
+                                       // calculate the numbers (first)n+(last) including if they are negative
+                                       first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;
+
+                               // loop through all the elements left in the jQuery object
+                               for ( var i = 0, rl = r.length; i < rl; i++ ) {
+                                       var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
+
+                                       if ( !merge[id] ) {
+                                               var c = 1;
+
+                                               for ( var n = parentNode.firstChild; n; n = n.nextSibling )
+                                                       if ( n.nodeType == 1 )
+                                                               n.nodeIndex = c++;
+
+                                               merge[id] = true;
+                                       }
+
+                                       var add = false;
+
+                                       if ( first == 0 ) {
+                                               if ( node.nodeIndex == last )
+                                                       add = true;
+                                       } else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
+                                               add = true;
+
+                                       if ( add ^ not )
+                                               tmp.push( node );
+                               }
+
+                               r = tmp;
+
+                       // Otherwise, find the expression to execute
+                       } else {
+                               var fn = jQuery.expr[ m[1] ];
+                               if ( typeof fn == "object" )
+                                       fn = fn[ m[2] ];
+
+                               if ( typeof fn == "string" )
+                                       fn = eval("false||function(a,i){return " + fn + ";}");
+
+                               // Execute it against the current filter
+                               r = jQuery.grep( r, function(elem, i){
+                                       return fn(elem, i, m, r);
+                               }, not );
+                       }
+               }
+
+               // Return an array of filtered elements (r)
+               // and the modified expression string (t)
+               return { r: r, t: t };
+       },
+
+       dir: function( elem, dir ){
+               var matched = [],
+                       cur = elem[dir];
+               while ( cur && cur != document ) {
+                       if ( cur.nodeType == 1 )
+                               matched.push( cur );
+                       cur = cur[dir];
+               }
+               return matched;
+       },
+
+       nth: function(cur,result,dir,elem){
+               result = result || 1;
+               var num = 0;
+
+               for ( ; cur; cur = cur[dir] )
+                       if ( cur.nodeType == 1 && ++num == result )
+                               break;
+
+               return cur;
+       },
+
+       sibling: function( n, elem ) {
+               var r = [];
+
+               for ( ; n; n = n.nextSibling ) {
+                       if ( n.nodeType == 1 && n != elem )
+                               r.push( n );
+               }
+
+               return r;
+       }
+});
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code orignated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+       // Bind an event to an element
+       // Original by Dean Edwards
+       add: function(elem, types, handler, data) {
+               if ( elem.nodeType == 3 || elem.nodeType == 8 )
+                       return;
+
+               // For whatever reason, IE has trouble passing the window object
+               // around, causing it to be cloned in the process
+               if ( jQuery.browser.msie && elem.setInterval )
+                       elem = window;
+
+               // Make sure that the function being executed has a unique ID
+               if ( !handler.guid )
+                       handler.guid = this.guid++;
+
+               // if data is passed, bind to handler
+               if( data != undefined ) {
+                       // Create temporary function pointer to original handler
+                       var fn = handler;
+
+                       // Create unique handler function, wrapped around original handler
+                       handler = this.proxy( fn, function() {
+                               // Pass arguments and context to original handler
+                               return fn.apply(this, arguments);
+                       });
+
+                       // Store data in unique handler
+                       handler.data = data;
+               }
+
+               // Init the element's event structure
+               var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
+                       handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
+                               // Handle the second event of a trigger and when
+                               // an event is called after a page has unloaded
+                               if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
+                                       return jQuery.event.handle.apply(arguments.callee.elem, arguments);
+                       });
+               // Add elem as a property of the handle function
+               // This is to prevent a memory leak with non-native
+               // event in IE.
+               handle.elem = elem;
+
+               // Handle multiple events separated by a space
+               // jQuery(...).bind("mouseover mouseout", fn);
+               jQuery.each(types.split(/\s+/), function(index, type) {
+                       // Namespaced event handlers
+                       var parts = type.split(".");
+                       type = parts[0];
+                       handler.type = parts[1];
+
+                       // Get the current list of functions bound to this event
+                       var handlers = events[type];
+
+                       // Init the event handler queue
+                       if (!handlers) {
+                               handlers = events[type] = {};
+
+                               // Check for a special event handler
+                               // Only use addEventListener/attachEvent if the special
+                               // events handler returns false
+                               if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
+                                       // Bind the global event handler to the element
+                                       if (elem.addEventListener)
+                                               elem.addEventListener(type, handle, false);
+                                       else if (elem.attachEvent)
+                                               elem.attachEvent("on" + type, handle);
+                               }
+                       }
+
+                       // Add the function to the element's handler list
+                       handlers[handler.guid] = handler;
+
+                       // Keep track of which events have been used, for global triggering
+                       jQuery.event.global[type] = true;
+               });
+
+               // Nullify elem to prevent memory leaks in IE
+               elem = null;
+       },
+
+       guid: 1,
+       global: {},
+
+       // Detach an event or set of events from an element
+       remove: function(elem, types, handler) {
+               // don't do events on text and comment nodes
+               if ( elem.nodeType == 3 || elem.nodeType == 8 )
+                       return;
+
+               var events = jQuery.data(elem, "events"), ret, index;
+
+               if ( events ) {
+                       // Unbind all events for the element
+                       if ( types == undefined || (typeof types == "string" && types.charAt(0) == ".") )
+                               for ( var type in events )
+                                       this.remove( elem, type + (types || "") );
+                       else {
+                               // types is actually an event object here
+                               if ( types.type ) {
+                                       handler = types.handler;
+                                       types = types.type;
+                               }
+
+                               // Handle multiple events seperated by a space
+                               // jQuery(...).unbind("mouseover mouseout", fn);
+                               jQuery.each(types.split(/\s+/), function(index, type){
+                                       // Namespaced event handlers
+                                       var parts = type.split(".");
+                                       type = parts[0];
+
+                                       if ( events[type] ) {
+                                               // remove the given handler for the given type
+                                               if ( handler )
+                                                       delete events[type][handler.guid];
+
+                                               // remove all handlers for the given type
+                                               else
+                                                       for ( handler in events[type] )
+                                                               // Handle the removal of namespaced events
+                                                               if ( !parts[1] || events[type][handler].type == parts[1] )
+                                                                       delete events[type][handler];
+
+                                               // remove generic event handler if no more handlers exist
+                                               for ( ret in events[type] ) break;
+                                               if ( !ret ) {
+                                                       if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
+                                                               if (elem.removeEventListener)
+                                                                       elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
+                                                               else if (elem.detachEvent)
+                                                                       elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
+                                                       }
+                                                       ret = null;
+                                                       delete events[type];
+                                               }
+                                       }
+                               });
+                       }
+
+                       // Remove the expando if it's no longer used
+                       for ( ret in events ) break;
+                       if ( !ret ) {
+                               var handle = jQuery.data( elem, "handle" );
+                               if ( handle ) handle.elem = null;
+                               jQuery.removeData( elem, "events" );
+                               jQuery.removeData( elem, "handle" );
+                       }
+               }
+       },
+
+       trigger: function(type, data, elem, donative, extra) {
+               // Clone the incoming data, if any
+               data = jQuery.makeArray(data);
+
+               if ( type.indexOf("!") >= 0 ) {
+                       type = type.slice(0, -1);
+                       var exclusive = true;
+               }
+
+               // Handle a global trigger
+               if ( !elem ) {
+                       // Only trigger if we've ever bound an event for it
+                       if ( this.global[type] )
+                               jQuery("*").add([window, document]).trigger(type, data);
+
+               // Handle triggering a single element
+               } else {
+                       // don't do events on text and comment nodes
+                       if ( elem.nodeType == 3 || elem.nodeType == 8 )
+                               return undefined;
+
+                       var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
+                               // Check to see if we need to provide a fake event, or not
+                               event = !data[0] || !data[0].preventDefault;
+
+                       // Pass along a fake event
+                       if ( event ) {
+                               data.unshift({
+                                       type: type,
+                                       target: elem,
+                                       preventDefault: function(){},
+                                       stopPropagation: function(){},
+                                       timeStamp: now()
+                               });
+                               data[0][expando] = true; // no need to fix fake event
+                       }
+
+                       // Enforce the right trigger type
+                       data[0].type = type;
+                       if ( exclusive )
+                               data[0].exclusive = true;
+
+                       // Trigger the event, it is assumed that "handle" is a function
+                       var handle = jQuery.data(elem, "handle");
+                       if ( handle )
+                               val = handle.apply( elem, data );
+
+                       // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
+                       if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
+                               val = false;
+
+                       // Extra functions don't get the custom event object
+                       if ( event )
+                               data.shift();
+
+                       // Handle triggering of extra function
+                       if ( extra && jQuery.isFunction( extra ) ) {
+                               // call the extra function and tack the current return value on the end for possible inspection
+                               ret = extra.apply( elem, val == null ? data : data.concat( val ) );
+                               // if anything is returned, give it precedence and have it overwrite the previous value
+                               if (ret !== undefined)
+                                       val = ret;
+                       }
+
+                       // Trigger the native events (except for clicks on links)
+                       if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+                               this.triggered = true;
+                               try {
+                                       elem[ type ]();
+                               // prevent IE from throwing an error for some hidden elements
+                               } catch (e) {}
+                       }
+
+                       this.triggered = false;
+               }
+
+               return val;
+       },
+
+       handle: function(event) {
+               // returned undefined or false
+               var val, ret, namespace, all, handlers;
+
+               event = arguments[0] = jQuery.event.fix( event || window.event );
+
+               // Namespaced event handlers
+               namespace = event.type.split(".");
+               event.type = namespace[0];
+               namespace = namespace[1];
+               // Cache this now, all = true means, any handler
+               all = !namespace && !event.exclusive;
+
+               handlers = ( jQuery.data(this, "events") || {} )[event.type];
+
+               for ( var j in handlers ) {
+                       var handler = handlers[j];
+
+                       // Filter the functions by class
+                       if ( all || handler.type == namespace ) {
+                               // Pass in a reference to the handler function itself
+                               // So that we can later remove it
+                               event.handler = handler;
+                               event.data = handler.data;
+
+                               ret = handler.apply( this, arguments );
+
+                               if ( val !== false )
+                                       val = ret;
+
+                               if ( ret === false ) {
+                                       event.preventDefault();
+                                       event.stopPropagation();
+                               }
+                       }
+               }
+
+               return val;
+       },
+
+       fix: function(event) {
+               if ( event[expando] == true )
+                       return event;
+
+               // store a copy of the original event object
+               // and "clone" to set read-only properties
+               var originalEvent = event;
+               event = { originalEvent: originalEvent };
+               var props = "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");
+               for ( var i=props.length; i; i-- )
+                       event[ props[i] ] = originalEvent[ props[i] ];
+
+               // Mark it as fixed
+               event[expando] = true;
+
+               // add preventDefault and stopPropagation since
+               // they will not work on the clone
+               event.preventDefault = function() {
+                       // if preventDefault exists run it on the original event
+                       if (originalEvent.preventDefault)
+                               originalEvent.preventDefault();
+                       // otherwise set the returnValue property of the original event to false (IE)
+                       originalEvent.returnValue = false;
+               };
+               event.stopPropagation = function() {
+                       // if stopPropagation exists run it on the original event
+                       if (originalEvent.stopPropagation)
+                               originalEvent.stopPropagation();
+                       // otherwise set the cancelBubble property of the original event to true (IE)
+                       originalEvent.cancelBubble = true;
+               };
+
+               // Fix timeStamp
+               event.timeStamp = event.timeStamp || now();
+
+               // Fix target property, if necessary
+               if ( !event.target )
+                       event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+
+               // check if target is a textnode (safari)
+               if ( event.target.nodeType == 3 )
+                       event.target = event.target.parentNode;
+
+               // Add relatedTarget, if necessary
+               if ( !event.relatedTarget && event.fromElement )
+                       event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
+
+               // Calculate pageX/Y if missing and clientX/Y available
+               if ( event.pageX == null && event.clientX != null ) {
+                       var doc = document.documentElement, body = document.body;
+                       event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
+                       event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
+               }
+
+               // Add which for key events
+               if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
+                       event.which = event.charCode || event.keyCode;
+
+               // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+               if ( !event.metaKey && event.ctrlKey )
+                       event.metaKey = event.ctrlKey;
+
+               // Add which for click: 1 == left; 2 == middle; 3 == right
+               // Note: button is not normalized, so don't use it
+               if ( !event.which && event.button )
+                       event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+
+               return event;
+       },
+
+       proxy: function( fn, proxy ){
+               // Set the guid of unique handler to the same of original handler, so it can be removed
+               proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
+               // So proxy can be declared as an argument
+               return proxy;
+       },
+
+       special: {
+               ready: {
+                       setup: function() {
+                               // Make sure the ready event is setup
+                               bindReady();
+                               return;
+                       },
+
+                       teardown: function() { return; }
+               },
+
+               mouseenter: {
+                       setup: function() {
+                               if ( jQuery.browser.msie ) return false;
+                               jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
+                               return true;
+                       },
+
+                       teardown: function() {
+                               if ( jQuery.browser.msie ) return false;
+                               jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
+                               return true;
+                       },
+
+                       handler: function(event) {
+                               // If we actually just moused on to a sub-element, ignore it
+                               if ( withinElement(event, this) ) return true;
+                               // Execute the right handlers by setting the event type to mouseenter
+                               event.type = "mouseenter";
+                               return jQuery.event.handle.apply(this, arguments);
+                       }
+               },
+
+               mouseleave: {
+                       setup: function() {
+                               if ( jQuery.browser.msie ) return false;
+                               jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
+                               return true;
+                       },
+
+                       teardown: function() {
+                               if ( jQuery.browser.msie ) return false;
+                               jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
+                               return true;
+                       },
+
+                       handler: function(event) {
+                               // If we actually just moused on to a sub-element, ignore it
+                               if ( withinElement(event, this) ) return true;
+                               // Execute the right handlers by setting the event type to mouseleave
+                               event.type = "mouseleave";
+                               return jQuery.event.handle.apply(this, arguments);
+                       }
+               }
+       }
+};
+
+jQuery.fn.extend({
+       bind: function( type, data, fn ) {
+               return type == "unload" ? this.one(type, data, fn) : this.each(function(){
+                       jQuery.event.add( this, type, fn || data, fn && data );
+               });
+       },
+
+       one: function( type, data, fn ) {
+               var one = jQuery.event.proxy( fn || data, function(event) {
+                       jQuery(this).unbind(event, one);
+                       return (fn || data).apply( this, arguments );
+               });
+               return this.each(function(){
+                       jQuery.event.add( this, type, one, fn && data);
+               });
+       },
+
+       unbind: function( type, fn ) {
+               return this.each(function(){
+                       jQuery.event.remove( this, type, fn );
+               });
+       },
+
+       trigger: function( type, data, fn ) {
+               return this.each(function(){
+                       jQuery.event.trigger( type, data, this, true, fn );
+               });
+       },
+
+       triggerHandler: function( type, data, fn ) {
+               return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
+       },
+
+       toggle: function( fn ) {
+               // Save reference to arguments for access in closure
+               var args = arguments, i = 1;
+
+               // link all the functions, so any of them can unbind this click handler
+               while( i < args.length )
+                       jQuery.event.proxy( fn, args[i++] );
+
+               return this.click( jQuery.event.proxy( fn, function(event) {
+                       // Figure out which function to execute
+                       this.lastToggle = ( this.lastToggle || 0 ) % i;
+
+                       // Make sure that clicks stop
+                       event.preventDefault();
+
+                       // and execute the function
+                       return args[ this.lastToggle++ ].apply( this, arguments ) || false;
+               }));
+       },
+
+       hover: function(fnOver, fnOut) {
+               return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
+       },
+
+       ready: function(fn) {
+               // Attach the listeners
+               bindReady();
+
+               // If the DOM is already ready
+               if ( jQuery.isReady )
+                       // Execute the function immediately
+                       fn.call( document, jQuery );
+
+               // Otherwise, remember the function for later
+               else
+                       // Add the function to the wait list
+                       jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
+
+               return this;
+       }
+});
+
+jQuery.extend({
+       isReady: false,
+       readyList: [],
+       // Handle when the DOM is ready
+       ready: function() {
+               // Make sure that the DOM is not already loaded
+               if ( !jQuery.isReady ) {
+                       // Remember that the DOM is ready
+                       jQuery.isReady = true;
+
+                       // If there are functions bound, to execute
+                       if ( jQuery.readyList ) {
+                               // Execute all of them
+                               jQuery.each( jQuery.readyList, function(){
+                                       this.call( document );
+                               });
+
+                               // Reset the list of functions
+                               jQuery.readyList = null;
+                       }
+
+                       // Trigger any bound ready events
+                       jQuery(document).triggerHandler("ready");
+               }
+       }
+});
+
+var readyBound = false;
+
+function bindReady(){
+       if ( readyBound ) return;
+       readyBound = true;
+
+       // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
+       if ( document.addEventListener && !jQuery.browser.opera)
+               // Use the handy event callback
+               document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
+
+       // If IE is used and is not in a frame
+       // Continually check to see if the document is ready
+       if ( jQuery.browser.msie && window == top ) (function(){
+               if (jQuery.isReady) return;
+               try {
+                       // If IE is used, use the trick by Diego Perini
+                       // http://javascript.nwbox.com/IEContentLoaded/
+                       document.documentElement.doScroll("left");
+               } catch( error ) {
+                       setTimeout( arguments.callee, 0 );
+                       return;
+               }
+               // and execute any waiting functions
+               jQuery.ready();
+       })();
+
+       if ( jQuery.browser.opera )
+               document.addEventListener( "DOMContentLoaded", function () {
+                       if (jQuery.isReady) return;
+                       for (var i = 0; i < document.styleSheets.length; i++)
+                               if (document.styleSheets[i].disabled) {
+                                       setTimeout( arguments.callee, 0 );
+                                       return;
+                               }
+                       // and execute any waiting functions
+                       jQuery.ready();
+               }, false);
+
+       if ( jQuery.browser.safari ) {
+               var numStyles;
+               (function(){
+                       if (jQuery.isReady) return;
+                       if ( document.readyState != "loaded" && document.readyState != "complete" ) {
+                               setTimeout( arguments.callee, 0 );
+                               return;
+                       }
+                       if ( numStyles === undefined )
+                               numStyles = jQuery("style, link[rel=stylesheet]").length;
+                       if ( document.styleSheets.length != numStyles ) {
+                               setTimeout( arguments.callee, 0 );
+                               return;
+                       }
+                       // and execute any waiting functions
+                       jQuery.ready();
+               })();
+       }
+
+       // A fallback to window.onload, that will always work
+       jQuery.event.add( window, "load", jQuery.ready );
+}
+
+jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
+       "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
+       "submit,keydown,keypress,keyup,error").split(","), function(i, name){
+
+       // Handle event binding
+       jQuery.fn[name] = function(fn){
+               return fn ? this.bind(name, fn) : this.trigger(name);
+       };
+});
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function(event, elem) {
+       // Check if mouse(over|out) are still within the same parent element
+       var parent = event.relatedTarget;
+       // Traverse up the tree
+       while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
+       // Return true if we actually just moused on to a sub-element
+       return parent == elem;
+};
+
+// Prevent memory leaks in IE
+// And prevent errors on refresh with events like mouseover in other browsers
+// Window isn't included so as not to unbind existing unload events
+jQuery(window).bind("unload", function() {
+       jQuery("*").add(document).unbind();
+});
+jQuery.fn.extend({
+       // Keep a copy of the old load
+       _load: jQuery.fn.load,
+
+       load: function( url, params, callback ) {
+               if ( typeof url != 'string' )
+                       return this._load( url );
+
+               var off = url.indexOf(" ");
+               if ( off >= 0 ) {
+                       var selector = url.slice(off, url.length);
+                       url = url.slice(0, off);
+               }
+
+               callback = callback || function(){};
+
+               // Default to a GET request
+               var type = "GET";
+
+               // If the second parameter was provided
+               if ( params )
+                       // If it's a function
+                       if ( jQuery.isFunction( params ) ) {
+                               // We assume that it's the callback
+                               callback = params;
+                               params = null;
+
+                       // Otherwise, build a param string
+                       } else {
+                               params = jQuery.param( params );
+                               type = "POST";
+                       }
+
+               var self = this;
+
+               // Request the remote document
+               jQuery.ajax({
+                       url: url,
+                       type: type,
+                       dataType: "html",
+                       data: params,
+                       complete: function(res, status){
+                               // If successful, inject the HTML into all the matched elements
+                               if ( status == "success" || status == "notmodified" )
+                                       // See if a selector was specified
+                                       self.html( selector ?
+                                               // Create a dummy div to hold the results
+                                               jQuery("<div/>")
+                                                       // inject the contents of the document in, removing the scripts
+                                                       // to avoid any 'Permission Denied' errors in IE
+                                                       .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
+
+                                                       // Locate the specified elements
+                                                       .find(selector) :
+
+                                               // If not, just inject the full result
+                                               res.responseText );
+
+                               self.each( callback, [res.responseText, status, res] );
+                       }
+               });
+               return this;
+       },
+
+       serialize: function() {
+               return jQuery.param(this.serializeArray());
+       },
+       serializeArray: function() {
+               return this.map(function(){
+                       return jQuery.nodeName(this, "form") ?
+                               jQuery.makeArray(this.elements) : this;
+               })
+               .filter(function(){
+                       return this.name && !this.disabled &&
+                               (this.checked || /select|textarea/i.test(this.nodeName) ||
+                                       /text|hidden|password/i.test(this.type));
+               })
+               .map(function(i, elem){
+                       var val = jQuery(this).val();
+                       return val == null ? null :
+                               val.constructor == Array ?
+                                       jQuery.map( val, function(val, i){
+                                               return {name: elem.name, value: val};
+                                       }) :
+                                       {name: elem.name, value: val};
+               }).get();
+       }
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
+       jQuery.fn[o] = function(f){
+               return this.bind(o, f);
+       };
+});
+
+var jsc = now();
+
+jQuery.extend({
+       get: function( url, data, callback, type ) {
+               // shift arguments if data argument was ommited
+               if ( jQuery.isFunction( data ) ) {
+                       callback = data;
+                       data = null;
+               }
+
+               return jQuery.ajax({
+                       type: "GET",
+                       url: url,
+                       data: data,
+                       success: callback,
+                       dataType: type
+               });
+       },
+
+       getScript: function( url, callback ) {
+               return jQuery.get(url, null, callback, "script");
+       },
+
+       getJSON: function( url, data, callback ) {
+               return jQuery.get(url, data, callback, "json");
+       },
+
+       post: function( url, data, callback, type ) {
+               if ( jQuery.isFunction( data ) ) {
+                       callback = data;
+                       data = {};
+               }
+
+               return jQuery.ajax({
+                       type: "POST",
+                       url: url,
+                       data: data,
+                       success: callback,
+                       dataType: type
+               });
+       },
+
+       ajaxSetup: function( settings ) {
+               jQuery.extend( jQuery.ajaxSettings, settings );
+       },
+
+       ajaxSettings: {
+               url: location.href,
+               global: true,
+               type: "GET",
+               timeout: 0,
+               contentType: "application/x-www-form-urlencoded",
+               processData: true,
+               async: true,
+               data: null,
+               username: null,
+               password: null,
+               accepts: {
+                       xml: "application/xml, text/xml",
+                       html: "text/html",
+                       script: "text/javascript, application/javascript",
+                       json: "application/json, text/javascript",
+                       text: "text/plain",
+                       _default: "*/*"
+               }
+       },
+
+       // Last-Modified header cache for next request
+       lastModified: {},
+
+       ajax: function( s ) {
+               // Extend the settings, but re-extend 's' so that it can be
+               // checked again later (in the test suite, specifically)
+               s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
+
+               var jsonp, jsre = /=\?(&|$)/g, status, data,
+                       type = s.type.toUpperCase();
+
+               // convert data if not already a string
+               if ( s.data && s.processData && typeof s.data != "string" )
+                       s.data = jQuery.param(s.data);
+
+               // Handle JSONP Parameter Callbacks
+               if ( s.dataType == "jsonp" ) {
+                       if ( type == "GET" ) {
+                               if ( !s.url.match(jsre) )
+                                       s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
+                       } else if ( !s.data || !s.data.match(jsre) )
+                               s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+                       s.dataType = "json";
+               }
+
+               // Build temporary JSONP function
+               if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
+                       jsonp = "jsonp" + jsc++;
+
+                       // Replace the =? sequence both in the query string and the data
+                       if ( s.data )
+                               s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+                       s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+
+                       // We need to make sure
+                       // that a JSONP style response is executed properly
+                       s.dataType = "script";
+
+                       // Handle JSONP-style loading
+                       window[ jsonp ] = function(tmp){
+                               data = tmp;
+                               success();
+                               complete();
+                               // Garbage collect
+                               window[ jsonp ] = undefined;
+                               try{ delete window[ jsonp ]; } catch(e){}
+                               if ( head )
+                                       head.removeChild( script );
+                       };
+               }
+
+               if ( s.dataType == "script" && s.cache == null )
+                       s.cache = false;
+
+               if ( s.cache === false && type == "GET" ) {
+                       var ts = now();
+                       // try replacing _= if it is there
+                       var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
+                       // if nothing was replaced, add timestamp to the end
+                       s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
+               }
+
+               // If data is available, append data to url for get requests
+               if ( s.data && type == "GET" ) {
+                       s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
+
+                       // IE likes to send both get and post data, prevent this
+                       s.data = null;
+               }
+
+               // Watch for a new set of requests
+               if ( s.global && ! jQuery.active++ )
+                       jQuery.event.trigger( "ajaxStart" );
+
+               // Matches an absolute URL, and saves the domain
+               var remote = /^(?:\w+:)?\/\/([^\/?#]+)/;
+
+               // If we're requesting a remote document
+               // and trying to load JSON or Script with a GET
+               if ( s.dataType == "script" && type == "GET"
+                               && remote.test(s.url) && remote.exec(s.url)[1] != location.host ){
+                       var head = document.getElementsByTagName("head")[0];
+                       var script = document.createElement("script");
+                       script.src = s.url;
+                       if (s.scriptCharset)
+                               script.charset = s.scriptCharset;
+
+                       // Handle Script loading
+                       if ( !jsonp ) {
+                               var done = false;
+
+                               // Attach handlers for all browsers
+                               script.onload = script.onreadystatechange = function(){
+                                       if ( !done && (!this.readyState ||
+                                                       this.readyState == "loaded" || this.readyState == "complete") ) {
+                                               done = true;
+                                               success();
+                                               complete();
+                                               head.removeChild( script );
+                                       }
+                               };
+                       }
+
+                       head.appendChild(script);
+
+                       // We handle everything using the script element injection
+                       return undefined;
+               }
+
+               var requestDone = false;
+
+               // Create the request object; Microsoft failed to properly
+               // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
+               var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
+
+               // Open the socket
+               // Passing null username, generates a login popup on Opera (#2865)
+               if( s.username )
+                       xhr.open(type, s.url, s.async, s.username, s.password);
+               else
+                       xhr.open(type, s.url, s.async);
+
+               // Need an extra try/catch for cross domain requests in Firefox 3
+               try {
+                       // Set the correct header, if data is being sent
+                       if ( s.data )
+                               xhr.setRequestHeader("Content-Type", s.contentType);
+
+                       // Set the If-Modified-Since header, if ifModified mode.
+                       if ( s.ifModified )
+                               xhr.setRequestHeader("If-Modified-Since",
+                                       jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
+
+                       // Set header so the called script knows that it's an XMLHttpRequest
+                       xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+
+                       // Set the Accepts header for the server, depending on the dataType
+                       xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
+                               s.accepts[ s.dataType ] + ", */*" :
+                               s.accepts._default );
+               } catch(e){}
+
+               // Allow custom headers/mimetypes
+               if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
+                       // cleanup active request counter
+                       s.global && jQuery.active--;
+                       // close opended socket
+                       xhr.abort();
+                       return false;
+               }
+
+               if ( s.global )
+                       jQuery.event.trigger("ajaxSend", [xhr, s]);
+
+               // Wait for a response to come back
+               var onreadystatechange = function(isTimeout){
+                       // The transfer is complete and the data is available, or the request timed out
+                       if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
+                               requestDone = true;
+
+                               // clear poll interval
+                               if (ival) {
+                                       clearInterval(ival);
+                                       ival = null;
+                               }
+
+                               status = isTimeout == "timeout" && "timeout" ||
+                                       !jQuery.httpSuccess( xhr ) && "error" ||
+                                       s.ifModified && jQuery.httpNotModified( xhr, s.url ) && "notmodified" ||
+                                       "success";
+
+                               if ( status == "success" ) {
+                                       // Watch for, and catch, XML document parse errors
+                                       try {
+                                               // process the data (runs the xml through httpData regardless of callback)
+                                               data = jQuery.httpData( xhr, s.dataType, s.dataFilter );
+                                       } catch(e) {
+                                               status = "parsererror";
+                                       }
+                               }
+
+                               // Make sure that the request was successful or notmodified
+                               if ( status == "success" ) {
+                                       // Cache Last-Modified header, if ifModified mode.
+                                       var modRes;
+                                       try {
+                                               modRes = xhr.getResponseHeader("Last-Modified");
+                                       } catch(e) {} // swallow exception thrown by FF if header is not available
+
+                                       if ( s.ifModified && modRes )
+                                               jQuery.lastModified[s.url] = modRes;
+
+                                       // JSONP handles its own success callback
+                                       if ( !jsonp )
+                                               success();
+                               } else
+                                       jQuery.handleError(s, xhr, status);
+
+                               // Fire the complete handlers
+                               complete();
+
+                               // Stop memory leaks
+                               if ( s.async )
+                                       xhr = null;
+                       }
+               };
+
+               if ( s.async ) {
+                       // don't attach the handler to the request, just poll it instead
+                       var ival = setInterval(onreadystatechange, 13);
+
+                       // Timeout checker
+                       if ( s.timeout > 0 )
+                               setTimeout(function(){
+                                       // Check to see if the request is still happening
+                                       if ( xhr ) {
+                                               // Cancel the request
+                                               xhr.abort();
+
+                                               if( !requestDone )
+                                                       onreadystatechange( "timeout" );
+                                       }
+                               }, s.timeout);
+               }
+
+               // Send the data
+               try {
+                       xhr.send(s.data);
+               } catch(e) {
+                       jQuery.handleError(s, xhr, null, e);
+               }
+
+               // firefox 1.5 doesn't fire statechange for sync requests
+               if ( !s.async )
+                       onreadystatechange();
+
+               function success(){
+                       // If a local callback was specified, fire it and pass it the data
+                       if ( s.success )
+                               s.success( data, status );
+
+                       // Fire the global callback
+                       if ( s.global )
+                               jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
+               }
+
+               function complete(){
+                       // Process result
+                       if ( s.complete )
+                               s.complete(xhr, status);
+
+                       // The request was completed
+                       if ( s.global )
+                               jQuery.event.trigger( "ajaxComplete", [xhr, s] );
+
+                       // Handle the global AJAX counter
+                       if ( s.global && ! --jQuery.active )
+                               jQuery.event.trigger( "ajaxStop" );
+               }
+
+               // return XMLHttpRequest to allow aborting the request etc.
+               return xhr;
+       },
+
+       handleError: function( s, xhr, status, e ) {
+               // If a local callback was specified, fire it
+               if ( s.error ) s.error( xhr, status, e );
+
+               // Fire the global callback
+               if ( s.global )
+                       jQuery.event.trigger( "ajaxError", [xhr, s, e] );
+       },
+
+       // Counter for holding the number of active queries
+       active: 0,
+
+       // Determines if an XMLHttpRequest was successful or not
+       httpSuccess: function( xhr ) {
+               try {
+                       // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
+                       return !xhr.status && location.protocol == "file:" ||
+                               ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 ||
+                               jQuery.browser.safari && xhr.status == undefined;
+               } catch(e){}
+               return false;
+       },
+
+       // Determines if an XMLHttpRequest returns NotModified
+       httpNotModified: function( xhr, url ) {
+               try {
+                       var xhrRes = xhr.getResponseHeader("Last-Modified");
+
+                       // Firefox always returns 200. check Last-Modified date
+                       return xhr.status == 304 || xhrRes == jQuery.lastModified[url] ||
+                               jQuery.browser.safari && xhr.status == undefined;
+               } catch(e){}
+               return false;
+       },
+
+       httpData: function( xhr, type, filter ) {
+               var ct = xhr.getResponseHeader("content-type"),
+                       xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
+                       data = xml ? xhr.responseXML : xhr.responseText;
+
+               if ( xml && data.documentElement.tagName == "parsererror" )
+                       throw "parsererror";
+                       
+               // Allow a pre-filtering function to sanitize the response
+               if( filter )
+                       data = filter( data, type );
+
+               // If the type is "script", eval it in global context
+               if ( type == "script" )
+                       jQuery.globalEval( data );
+
+               // Get the JavaScript object, if JSON is used.
+               if ( type == "json" )
+                       data = eval("(" + data + ")");
+
+               return data;
+       },
+
+       // Serialize an array of form elements or a set of
+       // key/values into a query string
+       param: function( a ) {
+               var s = [];
+
+               // If an array was passed in, assume that it is an array
+               // of form elements
+               if ( a.constructor == Array || a.jquery )
+                       // Serialize the form elements
+                       jQuery.each( a, function(){
+                               s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
+                       });
+
+               // Otherwise, assume that it's an object of key/value pairs
+               else
+                       // Serialize the key/values
+                       for ( var j in a )
+                               // If the value is an array then the key names need to be repeated
+                               if ( a[j] && a[j].constructor == Array )
+                                       jQuery.each( a[j], function(){
+                                               s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
+                                       });
+                               else
+                                       s.push( encodeURIComponent(j) + "=" + encodeURIComponent( jQuery.isFunction(a[j]) ? a[j]() : a[j] ) );
+
+               // Return the resulting serialization
+               return s.join("&").replace(/%20/g, "+");
+       }
+
+});
+jQuery.fn.extend({
+       show: function(speed,callback){
+               return speed ?
+                       this.animate({
+                               height: "show", width: "show", opacity: "show"
+                       }, speed, callback) :
+
+                       this.filter(":hidden").each(function(){
+                               this.style.display = this.oldblock || "";
+                               if ( jQuery.css(this,"display") == "none" ) {
+                                       var elem = jQuery("<" + this.tagName + " />").appendTo("body");
+                                       this.style.display = elem.css("display");
+                                       // handle an edge condition where css is - div { display:none; } or similar
+                                       if (this.style.display == "none")
+                                               this.style.display = "block";
+                                       elem.remove();
+                               }
+                       }).end();
+       },
+
+       hide: function(speed,callback){
+               return speed ?
+                       this.animate({
+                               height: "hide", width: "hide", opacity: "hide"
+                       }, speed, callback) :
+
+                       this.filter(":visible").each(function(){
+                               this.oldblock = this.oldblock || jQuery.css(this,"display");
+                               this.style.display = "none";
+                       }).end();
+       },
+
+       // Save the old toggle function
+       _toggle: jQuery.fn.toggle,
+
+       toggle: function( fn, fn2 ){
+               return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
+                       this._toggle.apply( this, arguments ) :
+                       fn ?
+                               this.animate({
+                                       height: "toggle", width: "toggle", opacity: "toggle"
+                               }, fn, fn2) :
+                               this.each(function(){
+                                       jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
+                               });
+       },
+
+       slideDown: function(speed,callback){
+               return this.animate({height: "show"}, speed, callback);
+       },
+
+       slideUp: function(speed,callback){
+               return this.animate({height: "hide"}, speed, callback);
+       },
+
+       slideToggle: function(speed, callback){
+               return this.animate({height: "toggle"}, speed, callback);
+       },
+
+       fadeIn: function(speed, callback){
+               return this.animate({opacity: "show"}, speed, callback);
+       },
+
+       fadeOut: function(speed, callback){
+               return this.animate({opacity: "hide"}, speed, callback);
+       },
+
+       fadeTo: function(speed,to,callback){
+               return this.animate({opacity: to}, speed, callback);
+       },
+
+       animate: function( prop, speed, easing, callback ) {
+               var optall = jQuery.speed(speed, easing, callback);
+
+               return this[ optall.queue === false ? "each" : "queue" ](function(){
+                       if ( this.nodeType != 1)
+                               return false;
+
+                       var opt = jQuery.extend({}, optall), p,
+                               hidden = jQuery(this).is(":hidden"), self = this;
+
+                       for ( p in prop ) {
+                               if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
+                                       return opt.complete.call(this);
+
+                               if ( p == "height" || p == "width" ) {
+                                       // Store display property
+                                       opt.display = jQuery.css(this, "display");
+
+                                       // Make sure that nothing sneaks out
+                                       opt.overflow = this.style.overflow;
+                               }
+                       }
+
+                       if ( opt.overflow != null )
+                               this.style.overflow = "hidden";
+
+                       opt.curAnim = jQuery.extend({}, prop);
+
+                       jQuery.each( prop, function(name, val){
+                               var e = new jQuery.fx( self, opt, name );
+
+                               if ( /toggle|show|hide/.test(val) )
+                                       e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+                               else {
+                                       var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
+                                               start = e.cur(true) || 0;
+
+                                       if ( parts ) {
+                                               var end = parseFloat(parts[2]),
+                                                       unit = parts[3] || "px";
+
+                                               // We need to compute starting value
+                                               if ( unit != "px" ) {
+                                                       self.style[ name ] = (end || 1) + unit;
+                                                       start = ((end || 1) / e.cur(true)) * start;
+                                                       self.style[ name ] = start + unit;
+                                               }
+
+                                               // If a +=/-= token was provided, we're doing a relative animation
+                                               if ( parts[1] )
+                                                       end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
+
+                                               e.custom( start, end, unit );
+                                       } else
+                                               e.custom( start, val, "" );
+                               }
+                       });
+
+                       // For JS strict compliance
+                       return true;
+               });
+       },
+
+       queue: function(type, fn){
+               if ( jQuery.isFunction(type) || ( type && type.constructor == Array )) {
+                       fn = type;
+                       type = "fx";
+               }
+
+               if ( !type || (typeof type == "string" && !fn) )
+                       return queue( this[0], type );
+
+               return this.each(function(){
+                       if ( fn.constructor == Array )
+                               queue(this, type, fn);
+                       else {
+                               queue(this, type).push( fn );
+
+                               if ( queue(this, type).length == 1 )
+                                       fn.call(this);
+                       }
+               });
+       },
+
+       stop: function(clearQueue, gotoEnd){
+               var timers = jQuery.timers;
+
+               if (clearQueue)
+                       this.queue([]);
+
+               this.each(function(){
+                       // go in reverse order so anything added to the queue during the loop is ignored
+                       for ( var i = timers.length - 1; i >= 0; i-- )
+                               if ( timers[i].elem == this ) {
+                                       if (gotoEnd)
+                                               // force the next step to be the last
+                                               timers[i](true);
+                                       timers.splice(i, 1);
+                               }
+               });
+
+               // start the next in the queue if the last step wasn't forced
+               if (!gotoEnd)
+                       this.dequeue();
+
+               return this;
+       }
+
+});
+
+var queue = function( elem, type, array ) {
+       if ( elem ){
+
+               type = type || "fx";
+
+               var q = jQuery.data( elem, type + "queue" );
+
+               if ( !q || array )
+                       q = jQuery.data( elem, type + "queue", jQuery.makeArray(array) );
+
+       }
+       return q;
+};
+
+jQuery.fn.dequeue = function(type){
+       type = type || "fx";
+
+       return this.each(function(){
+               var q = queue(this, type);
+
+               q.shift();
+
+               if ( q.length )
+                       q[0].call( this );
+       });
+};
+
+jQuery.extend({
+
+       speed: function(speed, easing, fn) {
+               var opt = speed && speed.constructor == Object ? speed : {
+                       complete: fn || !fn && easing ||
+                               jQuery.isFunction( speed ) && speed,
+                       duration: speed,
+                       easing: fn && easing || easing && easing.constructor != Function && easing
+               };
+
+               opt.duration = (opt.duration && opt.duration.constructor == Number ?
+                       opt.duration :
+                       jQuery.fx.speeds[opt.duration]) || jQuery.fx.speeds.def;
+
+               // Queueing
+               opt.old = opt.complete;
+               opt.complete = function(){
+                       if ( opt.queue !== false )
+                               jQuery(this).dequeue();
+                       if ( jQuery.isFunction( opt.old ) )
+                               opt.old.call( this );
+               };
+
+               return opt;
+       },
+
+       easing: {
+               linear: function( p, n, firstNum, diff ) {
+                       return firstNum + diff * p;
+               },
+               swing: function( p, n, firstNum, diff ) {
+                       return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+               }
+       },
+
+       timers: [],
+       timerId: null,
+
+       fx: function( elem, options, prop ){
+               this.options = options;
+               this.elem = elem;
+               this.prop = prop;
+
+               if ( !options.orig )
+                       options.orig = {};
+       }
+
+});
+
+jQuery.fx.prototype = {
+
+       // Simple function for setting a style value
+       update: function(){
+               if ( this.options.step )
+                       this.options.step.call( this.elem, this.now, this );
+
+               (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+
+               // Set display property to block for height/width animations
+               if ( this.prop == "height" || this.prop == "width" )
+                       this.elem.style.display = "block";
+       },
+
+       // Get the current size
+       cur: function(force){
+               if ( this.elem[this.prop] != null && this.elem.style[this.prop] == null )
+                       return this.elem[ this.prop ];
+
+               var r = parseFloat(jQuery.css(this.elem, this.prop, force));
+               return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
+       },
+
+       // Start an animation from one number to another
+       custom: function(from, to, unit){
+               this.startTime = now();
+               this.start = from;
+               this.end = to;
+               this.unit = unit || this.unit || "px";
+               this.now = this.start;
+               this.pos = this.state = 0;
+               this.update();
+
+               var self = this;
+               function t(gotoEnd){
+                       return self.step(gotoEnd);
+               }
+
+               t.elem = this.elem;
+
+               jQuery.timers.push(t);
+
+               if ( jQuery.timerId == null ) {
+                       jQuery.timerId = setInterval(function(){
+                               var timers = jQuery.timers;
+
+                               for ( var i = 0; i < timers.length; i++ )
+                                       if ( !timers[i]() )
+                                               timers.splice(i--, 1);
+
+                               if ( !timers.length ) {
+                                       clearInterval( jQuery.timerId );
+                                       jQuery.timerId = null;
+                               }
+                       }, 13);
+               }
+       },
+
+       // Simple 'show' function
+       show: function(){
+               // Remember where we started, so that we can go back to it later
+               this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+               this.options.show = true;
+
+               // Begin the animation
+               this.custom(0, this.cur());
+
+               // Make sure that we start at a small width/height to avoid any
+               // flash of content
+               if ( this.prop == "width" || this.prop == "height" )
+                       this.elem.style[this.prop] = "1px";
+
+               // Start by showing the element
+               jQuery(this.elem).show();
+       },
+
+       // Simple 'hide' function
+       hide: function(){
+               // Remember where we started, so that we can go back to it later
+               this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+               this.options.hide = true;
+
+               // Begin the animation
+               this.custom(this.cur(), 0);
+       },
+
+       // Each step of an animation
+       step: function(gotoEnd){
+               var t = now();
+
+               if ( gotoEnd || t > this.options.duration + this.startTime ) {
+                       this.now = this.end;
+                       this.pos = this.state = 1;
+                       this.update();
+
+                       this.options.curAnim[ this.prop ] = true;
+
+                       var done = true;
+                       for ( var i in this.options.curAnim )
+                               if ( this.options.curAnim[i] !== true )
+                                       done = false;
+
+                       if ( done ) {
+                               if ( this.options.display != null ) {
+                                       // Reset the overflow
+                                       this.elem.style.overflow = this.options.overflow;
+
+                                       // Reset the display
+                                       this.elem.style.display = this.options.display;
+                                       if ( jQuery.css(this.elem, "display") == "none" )
+                                               this.elem.style.display = "block";
+                               }
+
+                               // Hide the element if the "hide" operation was done
+                               if ( this.options.hide )
+                                       this.elem.style.display = "none";
+
+                               // Reset the properties, if the item has been hidden or shown
+                               if ( this.options.hide || this.options.show )
+                                       for ( var p in this.options.curAnim )
+                                               jQuery.attr(this.elem.style, p, this.options.orig[p]);
+                       }
+
+                       if ( done )
+                               // Execute the complete function
+                               this.options.complete.call( this.elem );
+
+                       return false;
+               } else {
+                       var n = t - this.startTime;
+                       this.state = n / this.options.duration;
+
+                       // Perform the easing function, defaults to swing
+                       this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
+                       this.now = this.start + ((this.end - this.start) * this.pos);
+
+                       // Perform the next step of the animation
+                       this.update();
+               }
+
+               return true;
+       }
+
+};
+
+jQuery.extend( jQuery.fx, {
+       speeds:{
+               slow: 600,
+               fast: 200,
+               // Default speed
+               def: 400
+       },
+       step: {
+               scrollLeft: function(fx){
+                       fx.elem.scrollLeft = fx.now;
+               },
+
+               scrollTop: function(fx){
+                       fx.elem.scrollTop = fx.now;
+               },
+
+               opacity: function(fx){
+                       jQuery.attr(fx.elem.style, "opacity", fx.now);
+               },
+
+               _default: function(fx){
+                       fx.elem.style[ fx.prop ] = fx.now + fx.unit;
+               }
+       }
+});
+// The Offset Method
+// Originally By Brandon Aaron, part of the Dimension Plugin
+// http://jquery.com/plugins/project/dimensions
+jQuery.fn.offset = function() {
+       var left = 0, top = 0, elem = this[0], results;
+
+       if ( elem ) with ( jQuery.browser ) {
+               var parent       = elem.parentNode,
+                   offsetChild  = elem,
+                   offsetParent = elem.offsetParent,
+                   doc          = elem.ownerDocument,
+                   safari2      = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
+                   css          = jQuery.curCSS,
+                   fixed        = css(elem, "position") == "fixed";
+
+               // Use getBoundingClientRect if available
+               if ( elem.getBoundingClientRect ) {
+                       var box = elem.getBoundingClientRect();
+
+                       // Add the document scroll offsets
+                       add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
+                               box.top  + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
+
+                       // IE adds the HTML element's border, by default it is medium which is 2px
+                       // IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
+                       // IE 7 standards mode, the border is always 2px
+                       // This border/offset is typically represented by the clientLeft and clientTop properties
+                       // However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
+                       // Therefore this method will be off by 2px in IE while in quirksmode
+                       add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );
+
+               // Otherwise loop through the offsetParents and parentNodes
+               } else {
+
+                       // Initial element offsets
+                       add( elem.offsetLeft, elem.offsetTop );
+
+                       // Get parent offsets
+                       while ( offsetParent ) {
+                               // Add offsetParent offsets
+                               add( offsetParent.offsetLeft, offsetParent.offsetTop );
+
+                               // Mozilla and Safari > 2 does not include the border on offset parents
+                               // However Mozilla adds the border for table or table cells
+                               if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
+                                       border( offsetParent );
+
+                               // Add the document scroll offsets if position is fixed on any offsetParent
+                               if ( !fixed && css(offsetParent, "position") == "fixed" )
+                                       fixed = true;
+
+                               // Set offsetChild to previous offsetParent unless it is the body element
+                               offsetChild  = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
+                               // Get next offsetParent
+                               offsetParent = offsetParent.offsetParent;
+                       }
+
+                       // Get parent scroll offsets
+                       while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
+                               // Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
+                               if ( !/^inline|table.*$/i.test(css(parent, "display")) )
+                                       // Subtract parent scroll offsets
+                                       add( -parent.scrollLeft, -parent.scrollTop );
+
+                               // Mozilla does not add the border for a parent that has overflow != visible
+                               if ( mozilla && css(parent, "overflow") != "visible" )
+                                       border( parent );
+
+                               // Get next parent
+                               parent = parent.parentNode;
+                       }
+
+                       // Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
+                       // Mozilla doubles body offsets with a non-absolutely positioned offsetChild
+                       if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
+                               (mozilla && css(offsetChild, "position") != "absolute") )
+                                       add( -doc.body.offsetLeft, -doc.body.offsetTop );
+
+                       // Add the document scroll offsets if position is fixed
+                       if ( fixed )
+                               add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
+                                       Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
+               }
+
+               // Return an object with top and left properties
+               results = { top: top, left: left };
+       }
+
+       function border(elem) {
+               add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
+       }
+
+       function add(l, t) {
+               left += parseInt(l, 10) || 0;
+               top += parseInt(t, 10) || 0;
+       }
+
+       return results;
+};
+
+
+jQuery.fn.extend({
+       position: function() {
+               var left = 0, top = 0, results;
+
+               if ( this[0] ) {
+                       // Get *real* offsetParent
+                       var offsetParent = this.offsetParent(),
+
+                       // Get correct offsets
+                       offset       = this.offset(),
+                       parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+                       // Subtract element margins
+                       // note: when an element has margin: auto the offsetLeft and marginLeft 
+                       // are the same in Safari causing offset.left to incorrectly be 0
+                       offset.top  -= num( this, 'marginTop' );
+                       offset.left -= num( this, 'marginLeft' );
+
+                       // Add offsetParent borders
+                       parentOffset.top  += num( offsetParent, 'borderTopWidth' );
+                       parentOffset.left += num( offsetParent, 'borderLeftWidth' );
+
+                       // Subtract the two offsets
+                       results = {
+                               top:  offset.top  - parentOffset.top,
+                               left: offset.left - parentOffset.left
+                       };
+               }
+
+               return results;
+       },
+
+       offsetParent: function() {
+               var offsetParent = this[0].offsetParent;
+               while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
+                       offsetParent = offsetParent.offsetParent;
+               return jQuery(offsetParent);
+       }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ['Left', 'Top'], function(i, name) {
+       var method = 'scroll' + name;
+       
+       jQuery.fn[ method ] = function(val) {
+               if (!this[0]) return;
+
+               return val != undefined ?
+
+                       // Set the scroll offset
+                       this.each(function() {
+                               this == window || this == document ?
+                                       window.scrollTo(
+                                               !i ? val : jQuery(window).scrollLeft(),
+                                                i ? val : jQuery(window).scrollTop()
+                                       ) :
+                                       this[ method ] = val;
+                       }) :
+
+                       // Return the scroll offset
+                       this[0] == window || this[0] == document ?
+                               self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
+                                       jQuery.boxModel && document.documentElement[ method ] ||
+                                       document.body[ method ] :
+                               this[0][ method ];
+       };
+});
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function(i, name){
+
+       var tl = i ? "Left"  : "Top",  // top or left
+               br = i ? "Right" : "Bottom"; // bottom or right
+
+       // innerHeight and innerWidth
+       jQuery.fn["inner" + name] = function(){
+               return this[ name.toLowerCase() ]() +
+                       num(this, "padding" + tl) +
+                       num(this, "padding" + br);
+       };
+
+       // outerHeight and outerWidth
+       jQuery.fn["outer" + name] = function(margin) {
+               return this["inner" + name]() +
+                       num(this, "border" + tl + "Width") +
+                       num(this, "border" + br + "Width") +
+                       (margin ?
+                               num(this, "margin" + tl) + num(this, "margin" + br) : 0);
+       };
+
+});})();
diff --git a/timeside/ui/lib/soundmanager2.js b/timeside/ui/lib/soundmanager2.js
new file mode 100755 (executable)
index 0000000..216115c
--- /dev/null
@@ -0,0 +1,1247 @@
+/*!\r
+   SoundManager 2: Javascript Sound for the Web\r
+   --------------------------------------------\r
+   http://schillmania.com/projects/soundmanager2/\r
+\r
+   Copyright (c) 2008, Scott Schiller. All rights reserved.\r
+   Code licensed under the BSD License:\r
+   http://schillmania.com/projects/soundmanager2/license.txt\r
+\r
+   V2.90a.20081028\r
+*/\r
+\r
+function SoundManager(smURL,smID) {\r
\r
+  this.flashVersion = 8;           // version of flash to require, either 8 or 9. Some API features require Flash 9.\r
+  this.debugMode = true;           // enable debugging output (div#soundmanager-debug, OR console if available + configured)\r
+  this.useConsole = true;          // use firebug/safari console.log()-type debug console if available\r
+  this.consoleOnly = false;        // if console is being used, do not create/write to #soundmanager-debug\r
+  this.waitForWindowLoad = false;  // force SM2 to wait for window.onload() before trying to call soundManager.onload()\r
+  this.nullURL = 'null.mp3';       // path to "null" (empty) MP3 file, used to unload sounds (Flash 8 only)\r
+  this.allowPolling = true;        // allow flash to poll for status update (required for "while playing", peak, sound spectrum functions to work.)\r
+  this.useMovieStar = false;      // enable support for Flash 9.0r115+ (codename "MovieStar") MPEG4 audio + video formats (AAC, M4V, FLV, MOV etc.)\r
+  this.useHighPerformance = true;  // flash positioning trick, improves JS/flash callback speed, minimizes delay\r
+  this.bgColor = '#ffffff';       // movie (.swf) background color, useful if showing on-screen for video etc.\r
+\r
+  this.defaultOptions = {\r
+    'autoLoad': false,             // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)\r
+    'stream': true,                // allows playing before entire file has loaded (recommended)\r
+    'autoPlay': false,             // enable playing of file as soon as possible (much faster if "stream" is true)\r
+    'onid3': null,                 // callback function for "ID3 data is added/available"\r
+    'onload': null,                // callback function for "load finished"\r
+    'whileloading': null,          // callback function for "download progress update" (X of Y bytes received)\r
+    'onplay': null,                // callback for "play" start\r
+    'onpause': null,               // callback for "pause"\r
+    'onresume': null,              // callback for "resume" (pause toggle)\r
+    'whileplaying': null,          // callback during play (position update)\r
+    'onstop': null,                // callback for "user stop"\r
+    'onfinish': null,              // callback function for "sound finished playing"\r
+    'onbeforefinish': null,        // callback for "before sound finished playing (at [time])"\r
+    'onbeforefinishtime': 5000,    // offset (milliseconds) before end of sound to trigger beforefinish (eg. 1000 msec = 1 second)\r
+    'onbeforefinishcomplete':null, // function to call when said sound finishes playing\r
+    'onjustbeforefinish':null,     // callback for [n] msec before end of current sound\r
+    'onjustbeforefinishtime':200,  // [n] - if not using, set to 0 (or null handler) and event will not fire.\r
+    'multiShot': true,             // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time\r
+    'position': null,              // offset (milliseconds) to seek to within loaded sound data.\r
+    'pan': 0,                      // "pan" settings, left-to-right, -100 to 100\r
+    'volume': 100                  // self-explanatory. 0-100, the latter being the max.\r
+  };\r
+\r
+  this.flash9Options = {           // flash 9-only options, merged into defaultOptions if flash 9 is being used\r
+    'isMovieStar': null,          // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL\r
+    'usePeakData': false,          // enable left/right channel peak (level) data\r
+    'useWaveformData': false,      // enable sound spectrum (raw waveform data) - WARNING: CPU-INTENSIVE: may set CPUs on fire.\r
+    'useEQData': false             // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.\r
+  };\r
+\r
+  this.movieStarOptions = {        // flash 9.0r115+ MPEG4 audio/video options, merged into defaultOptions if flash 9 + movieStar mode is enabled\r
+    'onmetadata': null,                   // callback for when video width/height etc. are received\r
+    'useVideo': false             // if loading movieStar content, whether to show video\r
+  }\r
+\r
+  this.flashBlockHelper = {\r
+    'enabled': false,              // experimental, removed with >v2.80\r
+    'message': []                  // "nag bar" to show when messaging the user, if SM2 fails on firefox etc.\r
+  };\r
+\r
+  var _s = this; \r
+  this.version = null;\r
+  this.versionNumber = 'V2.90a.20081028';\r
+  this.movieURL = null;\r
+  this.url = null;\r
+  this.altURL = null;\r
+  this.swfLoaded = false;\r
+  this.enabled = false;\r
+  this.o = null;\r
+  this.id = (smID||'sm2movie');\r
+  this.oMC = null;\r
+  this.sounds = [];\r
+  this.soundIDs = [];\r
+  this.muted = false;\r
+  this.isIE = (navigator.userAgent.match(/MSIE/i));\r
+  this.isSafari = (navigator.userAgent.match(/safari/i));\r
+  this.isGecko = (navigator.userAgent.match(/gecko/i));\r
+  this.debugID = 'soundmanager-debug';\r
+  this._debugOpen = true;\r
+  this._didAppend = false;\r
+  this._appendSuccess = false;\r
+  this._didInit = false;\r
+  this._disabled = false;\r
+  this._windowLoaded = false;\r
+  this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');\r
+  this._debugLevels = ['log','info','warn','error'];\r
+  this._defaultFlashVersion = 8;\r
+  this.filePatterns = {\r
+    flash8: /\.(mp3)/i,\r
+    flash9: /\.(mp3)/i\r
+  };\r
+  this.netStreamTypes = ['aac','flv','mov','mp4','m4v','f4v','m4a','mp4v','3gp','3g2']; // Flash v9.0r115+ "moviestar" formats\r
+  this.netStreamPattern = new RegExp('.('+this.netStreamTypes.join('|')+')','i');\r
+  this.filePattern = null;\r
+  this.features = {\r
+    peakData: false,\r
+    waveformData: false,\r
+    eqData: false\r
+  };\r
+\r
+  this.sandbox = {\r
+    'type': null,\r
+    'types': {\r
+      'remote': 'remote (domain-based) rules',\r
+      'localWithFile': 'local with file access (no internet access)',\r
+      'localWithNetwork': 'local with network (internet access only, no local access)',\r
+      'localTrusted': 'local, trusted (local + internet access)'\r
+    },\r
+    'description': null,\r
+    'noRemote': null,\r
+    'noLocal': null\r
+  };\r
+\r
+  this._setVersionInfo = function() {\r
+    if (_s.flashVersion != 8 && _s.flashVersion != 9) {\r
+      alert('soundManager.flashVersion must be 8 or 9. "'+_s.flashVersion+'" is invalid. Reverting to '+_s._defaultFlashVersion+'.');\r
+      _s.flashVersion = _s._defaultFlashVersion;\r
+    }\r
+    _s.version = _s.versionNumber+(_s.flashVersion==9?' (AS3/Flash 9)':' (AS2/Flash 8)');\r
+    // set up default options\r
+       if (_s.flashVersion > 8) {\r
+         _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.flash9Options);\r
+       }\r
+    if (_s.flashVersion > 8 && _s.useMovieStar) {\r
+      _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.movieStarOptions);\r
+      _s.filePatterns.flash9 = new RegExp('.(mp3|'+_s.netStreamTypes.join('|')+')','i');\r
+    } else {\r
+         _s.useMovieStar = false;\r
+    }\r
+    _s.filePattern = _s.filePatterns[(_s.flashVersion!=8?'flash9':'flash8')];\r
+    _s.movieURL = (_s.flashVersion==8?'soundmanager2.swf':'soundmanager2_flash9.swf');\r
+    _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_s.flashVersion==9);\r
+  }\r
+\r
+  this._overHTTP = (document.location?document.location.protocol.match(/http/i):null);\r
+  this._waitingforEI = false;\r
+  this._initPending = false;\r
+  this._tryInitOnFocus = (this.isSafari && typeof document.hasFocus == 'undefined');\r
+  this._isFocused = (typeof document.hasFocus != 'undefined'?document.hasFocus():null);\r
+  this._okToDisable = !this._tryInitOnFocus;\r
+\r
+  this.useAltURL = !this._overHTTP; // use altURL if not "online"\r
+\r
+  var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';\r
+\r
+  // --- public methods ---\r
+  \r
+  this.supported = function() {\r
+    return (_s._didInit && !_s._disabled);\r
+  };\r
+\r
+  this.getMovie = function(smID) {\r
+    return _s.isIE?window[smID]:(_s.isSafari?document.getElementById(smID)||document[smID]:document.getElementById(smID));\r
+  };\r
+\r
+  this.loadFromXML = function(sXmlUrl) {\r
+    try {\r
+      _s.o._loadFromXML(sXmlUrl);\r
+    } catch(e) {\r
+      _s._failSafely();\r
+      return true;\r
+    };\r
+  };\r
+\r
+  this.createSound = function(oOptions) {\r
+    if (!_s._didInit) throw new Error('soundManager.createSound(): Not loaded yet - wait for soundManager.onload() before calling sound-related methods');\r
+    if (arguments.length==2) {\r
+      // function overloading in JS! :) ..assume simple createSound(id,url) use case\r
+      var oOptions = {'id':arguments[0],'url':arguments[1]};\r
+    };\r
+    var thisOptions = _s._mergeObjects(oOptions); // inherit SM2 defaults\r
+    var _tO = thisOptions; // alias\r
+    _s._wD('soundManager.createSound(): '+_tO.id+' ('+_tO.url+')',1);\r
+    if (_s._idCheck(_tO.id,true)) {\r
+      _s._wD('soundManager.createSound(): '+_tO.id+' exists',1);\r
+      return _s.sounds[_tO.id];\r
+    };\r
+    if (_s.flashVersion > 8 && _s.useMovieStar) {\r
+         if (_tO.isMovieStar == null) {\r
+           _tO.isMovieStar = (_tO.url.match(_s.netStreamPattern)?true:false);\r
+         }\r
+         if (_tO.isMovieStar) {\r
+           _s._wD('soundManager.createSound(): using MovieStar handling');\r
+         }\r
+         if (_tO.isMovieStar && (_tO.usePeakData || _tO.useWaveformData || _tO.useEQData)) {\r
+           _s._wD('Warning: peak/waveform/eqData features unsupported for non-MP3 formats');\r
+           _tO.usePeakData = false;\r
+               _tO.useWaveformData = false;\r
+               _tO.useEQData = false;\r
+         }\r
+    };\r
+    _s.sounds[_tO.id] = new SMSound(_tO);\r
+    _s.soundIDs[_s.soundIDs.length] = _tO.id;\r
+    // AS2:\r
+    if (_s.flashVersion == 8) {\r
+      _s.o._createSound(_tO.id,_tO.onjustbeforefinishtime);\r
+    } else {\r
+      _s.o._createSound(_tO.id,_tO.url,_tO.onjustbeforefinishtime,_tO.usePeakData,_tO.useWaveformData,_tO.useEQData,_tO.isMovieStar,(_tO.isMovieStar?_tO.useVideo:false));\r
+    };\r
+    if (_tO.autoLoad || _tO.autoPlay) {\r
+      window.setTimeout(function() {\r
+        if (_s.sounds[_tO.id]) {\r
+          _s.sounds[_tO.id].load(_tO);\r
+        }\r
+      },20);\r
+    }\r
+    if (_tO.autoPlay) {\r
+         if (_s.flashVersion == 8) {\r
+           _s.sounds[_tO.id].playState = 1; // we can only assume this sound will be playing soon.\r
+         } else {\r
+           _s.sounds[_tO.id].play();   \r
+         }\r
+       }\r
+    return _s.sounds[_tO.id];\r
+  };\r
+\r
+  this.createVideo = function(oOptions) {\r
+    if (arguments.length==2) {\r
+      var oOptions = {'id':arguments[0],'url':arguments[1]};\r
+    };\r
+    if (_s.flashVersion >= 9) {\r
+      oOptions.isMovieStar = true;\r
+      oOptions.useVideo = true;\r
+    } else {\r
+      _s._wD('soundManager.createVideo(): flash 9 required for video. Exiting.',2);\r
+      return false;\r
+    }\r
+    if (!_s.useMovieStar) {\r
+      _s._wD('soundManager.createVideo(): MovieStar mode not enabled. Exiting.',2);\r
+    }\r
+    return _s.createSound(oOptions);\r
+  }\r
+\r
+  this.destroySound = function(sID,bFromSound) {\r
+    // explicitly destroy a sound before normal page unload, etc.\r
+    if (!_s._idCheck(sID)) return false;\r
+    for (var i=0; i<_s.soundIDs.length; i++) {\r
+      if (_s.soundIDs[i] == sID) {\r
+           _s.soundIDs.splice(i,1);\r
+        continue;\r
+      };\r
+    };\r
+    // conservative option: avoid crash with ze flash 8\r
+    // calling destroySound() within a sound onload() might crash firefox, certain flavours of winXP + flash 8??\r
+    // if (_s.flashVersion != 8) {\r
+      _s.sounds[sID].unload();\r
+    // }\r
+    if (!bFromSound) {\r
+      // ignore if being called from SMSound instance\r
+      _s.sounds[sID].destruct();\r
+    };\r
+    delete _s.sounds[sID];\r
+  };\r
+\r
+  this.destroyVideo = this.destroySound;\r
+\r
+  this.load = function(sID,oOptions) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].load(oOptions);\r
+  };\r
+\r
+  this.unload = function(sID) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].unload();\r
+  };\r
+\r
+  this.play = function(sID,oOptions) {\r
+    if (!_s._idCheck(sID)) {\r
+      if (typeof oOptions != 'Object') oOptions = {url:oOptions}; // overloading use case: play('mySound','/path/to/some.mp3');\r
+      if (oOptions && oOptions.url) {\r
+        // overloading use case, creation + playing of sound: .play('someID',{url:'/path/to.mp3'});\r
+        _s._wD('soundController.play(): attempting to create "'+sID+'"',1);\r
+        oOptions.id = sID;\r
+        _s.createSound(oOptions);\r
+      } else {\r
+        return false;\r
+      };\r
+    };\r
+    _s.sounds[sID].play(oOptions);\r
+  };\r
+\r
+  this.start = this.play; // just for convenience\r
+\r
+  this.setPosition = function(sID,nMsecOffset) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    nMsecOffset = Math.min((nMsecOffset||0),_s.duration); // don't allow seek past loaded duration\r
+    _s.sounds[sID].setPosition(nMsecOffset);\r
+  };\r
+\r
+  this.stop = function(sID) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s._wD('soundManager.stop('+sID+')',1);\r
+    _s.sounds[sID].stop(); \r
+  };\r
+\r
+  this.stopAll = function() {\r
+    _s._wD('soundManager.stopAll()',1);\r
+    for (var oSound in _s.sounds) {\r
+      if (_s.sounds[oSound] instanceof SMSound) _s.sounds[oSound].stop(); // apply only to sound objects\r
+    };\r
+  };\r
+\r
+  this.pause = function(sID) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].pause();\r
+  };\r
+\r
+  this.pauseAll = function() {\r
+    for (var i=_s.soundIDs.length; i--;) {\r
+      _s.sounds[_s.soundIDs[i]].pause();\r
+    }\r
+  };\r
+\r
+  this.resume = function(sID) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].resume();\r
+  };\r
+\r
+  this.resumeAll = function() {\r
+    for (var i=_s.soundIDs.length; i--;) {\r
+      _s.sounds[_s.soundIDs[i]].resume();\r
+    }\r
+  };\r
+\r
+  this.togglePause = function(sID) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].togglePause();\r
+  };\r
+\r
+  this.setPan = function(sID,nPan) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].setPan(nPan);\r
+  };\r
+\r
+  this.setVolume = function(sID,nVol) {\r
+    if (!_s._idCheck(sID)) return false;\r
+    _s.sounds[sID].setVolume(nVol);\r
+  };\r
+\r
+  this.mute = function(sID) {\r
+       if (typeof sID != 'string') sID = null;\r
+    if (!sID) {\r
+      var o = null;\r
+      _s._wD('soundManager.mute(): Muting all sounds');\r
+      for (var i=_s.soundIDs.length; i--;) {\r
+        _s.sounds[_s.soundIDs[i]].mute();\r
+      }\r
+      _s.muted = true;\r
+    } else {\r
+      if (!_s._idCheck(sID)) return false;\r
+      _s._wD('soundManager.mute(): Muting "'+sID+'"');\r
+      _s.sounds[sID].mute();\r
+    }\r
+  };\r
+\r
+  this.muteAll = function() {\r
+    _s.mute();\r
+  };\r
+\r
+  this.unmute = function(sID) {\r
+    if (typeof sID != 'string') sID = null;\r
+    if (!sID) {\r
+      var o = null;\r
+      _s._wD('soundManager.unmute(): Unmuting all sounds');\r
+      for (var i=_s.soundIDs.length; i--;) {\r
+        _s.sounds[_s.soundIDs[i]].unmute();\r
+      }\r
+      _s.muted = false;\r
+    } else {\r
+      if (!_s._idCheck(sID)) return false;\r
+      _s._wD('soundManager.unmute(): Unmuting "'+sID+'"');\r
+      _s.sounds[sID].unmute();\r
+    }\r
+  };\r
+\r
+  this.unmuteAll = function() {\r
+    _s.unmute();\r
+  };\r
+\r
+  this.setPolling = function(bPolling) {\r
+    if (!_s.o || !_s.allowPolling) return false;\r
+    // _s._wD('soundManager.setPolling('+bPolling+')');\r
+    _s.o._setPolling(bPolling);\r
+  };\r
+\r
+  this.disable = function(bUnload) {\r
+    // destroy all functions\r
+    if (_s._disabled) return false;\r
+    _s._disabled = true;\r
+    _s._wD('soundManager.disable(): Disabling all functions - future calls will return false.',1);\r
+    for (var i=_s.soundIDs.length; i--;) {\r
+      _s._disableObject(_s.sounds[_s.soundIDs[i]]);\r
+    };\r
+    _s.initComplete(); // fire "complete", despite fail\r
+    _s._disableObject(_s);\r
+  };\r
+\r
+  this.handleFlashBlock = function(bForce) {\r
+    // experimental, removed with >v2.80.\r
+    return false;\r
+  };\r
+\r
+  this.canPlayURL = function(sURL) {\r
+    return (sURL?(sURL.match(_s.filePattern)?true:false):null);        \r
+  };\r
+\r
+  this.getSoundById = function(sID,suppressDebug) {\r
+    if (!sID) throw new Error('SoundManager.getSoundById(): sID is null/undefined');\r
+    var result = _s.sounds[sID];\r
+    if (!result && !suppressDebug) {\r
+      _s._wD('"'+sID+'" is an invalid sound ID.',2);\r
+      // soundManager._wD('trace: '+arguments.callee.caller);\r
+    };\r
+    return result;\r
+  };\r
+\r
+  this.onload = function() {\r
+    // window.onload() equivalent for SM2, ready to create sounds etc.\r
+    // this is a stub - you can override this in your own external script, eg. soundManager.onload = function() {}\r
+    soundManager._wD('<em>Warning</em>: soundManager.onload() is undefined.',2);\r
+  };\r
+\r
+  this.onerror = function() {\r
+    // stub for user handler, called when SM2 fails to load/init\r
+  };\r
+\r
+  // --- "private" methods ---\r
+\r
+  this._idCheck = this.getSoundById;\r
+\r
+  this._disableObject = function(o) {\r
+    for (var oProp in o) {\r
+      if (typeof o[oProp] == 'function' && typeof o[oProp]._protected == 'undefined') o[oProp] = function(){return false;};\r
+    };\r
+    oProp = null;\r
+  };\r
+\r
+  this._failSafely = function() {\r
+    // exception handler for "object doesn't support this property or method" or general failure\r
+    var fpgssTitle = 'You may need to whitelist this location/domain eg. file:///C:/ or C:/ or mysite.com, or set ALWAYS ALLOW under the Flash Player Global Security Settings page. The latter is probably less-secure.';\r
+    var flashCPL = '<a href="'+flashCPLink+'" title="'+fpgssTitle+'">view/edit</a>';\r
+    var FPGSS = '<a href="'+flashCPLink+'" title="Flash Player Global Security Settings">FPGSS</a>';\r
+    if (!_s._disabled) {\r
+      _s._wD('soundManager: Failed to initialise.',2);\r
+      _s.disable();\r
+    };\r
+  };\r
+  \r
+  this._normalizeMovieURL = function(smURL) {\r
+    if (smURL) {\r
+      if (smURL.match(/\.swf/)) {\r
+        smURL = smURL.substr(0,smURL.lastIndexOf('.swf'));\r
+      }\r
+      if (smURL.lastIndexOf('/') != smURL.length-1) {\r
+        smURL = smURL+'/';\r
+      }\r
+    }\r
+    return(smURL && smURL.lastIndexOf('/')!=-1?smURL.substr(0,smURL.lastIndexOf('/')+1):'./')+_s.movieURL;\r
+  };\r
+\r
+  this._getDocument = function() {\r
+    return (document.body?document.body:(document.documentElement?document.documentElement:document.getElementsByTagName('div')[0]));\r
+  };\r
+\r
+  this._getDocument._protected = true;\r
+\r
+  this._createMovie = function(smID,smURL) {\r
+    if (_s._didAppend && _s._appendSuccess) return false; // ignore if already succeeded\r
+    if (window.location.href.indexOf('debug=1')+1) _s.debugMode = true; // allow force of debug mode via URL\r
+    _s._didAppend = true;\r
+       \r
+    // safety check for legacy (change to Flash 9 URL)\r
+    _s._setVersionInfo();\r
+    var remoteURL = (smURL?smURL:_s.url);\r
+    var localURL = (_s.altURL?_s.altURL:remoteURL);\r
+    _s.url = _s._normalizeMovieURL(_s._overHTTP?remoteURL:localURL);\r
+    smURL = _s.url;\r
+\r
+    var htmlEmbed = '<embed name="'+smID+'" id="'+smID+'" src="'+smURL+'" width="100%" height="100%" quality="high" allowScriptAccess="always" quality="high" '+(_s.useHighPerformance && !_s.useMovieStar?'wmode="transparent" ':'')+'bgcolor="'+_s.bgColor+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>';\r
+    var htmlObject = '<object id="'+smID+'" data="'+smURL+'" type="application/x-shockwave-flash" width="100%" height="100%"><param name="movie" value="'+smURL+'" /><param name="AllowScriptAccess" value="always" /><param name="quality" value="high" />'+(_s.useHighPerformance && !_s.useMovieStar?'<param name="wmode" value="transparent" /> ':'')+'<param name="bgcolor" value="'+_s.bgColor+'" /><!-- --></object>';\r
+    var html = (!_s.isIE?htmlEmbed:htmlObject);\r
+\r
+    var toggleElement = '<div id="'+_s.debugID+'-toggle" style="position:fixed;_position:absolute;right:0px;bottom:0px;_top:0px;width:1.2em;height:1.2em;line-height:1.2em;margin:2px;padding:0px;text-align:center;border:1px solid #999;cursor:pointer;background:#fff;color:#333;z-index:10001" title="Toggle SM2 debug console" onclick="soundManager._toggleDebug()">-</div>';\r
+    var debugHTML = '<div id="'+_s.debugID+'" style="display:'+(_s.debugMode && ((!_s._hasConsole||!_s.useConsole)||(_s.useConsole && _s._hasConsole && !_s.consoleOnly))?'block':'none')+';opacity:0.85"></div>';\r
+    var appXHTML = 'soundManager._createMovie(): appendChild/innerHTML set failed. May be app/xhtml+xml DOM-related.';\r
+\r
+    var oTarget = _s._getDocument();\r
+    if (oTarget) {\r
+       \r
+      _s.oMC = document.getElementById('sm2-container')?document.getElementById('sm2-container'):document.createElement('div');\r
+      if (!_s.oMC.id) {\r
+        _s.oMC.id = 'sm2-container';\r
+        _s.oMC.className = 'movieContainer';\r
+        // "hide" flash movie\r
+        var s = null;\r
+        if (_s.useHighPerformance) {\r
+          s = {\r
+           position: 'fixed',\r
+           width: '8px',\r
+            height: '8px', // must be at least 6px for flash to run fast. odd? yes.\r
+            bottom: '0px',\r
+            left: '0px',\r
+           zIndex:-1 // sit behind everything else\r
+          }\r
+        } else {\r
+          s = {\r
+            position: 'absolute',\r
+           width: '1px',\r
+            height: '1px',\r
+            bottom: '0px',\r
+            left: '0px'\r
+          }\r
+        }\r
+        var x = null;\r
+        for (x in s) {\r
+          _s.oMC.style[x] = s[x];\r
+        }\r
+        try {\r
+          oTarget.appendChild(_s.oMC);\r
+          _s.oMC.innerHTML = html;\r
+          _s._appendSuccess = true;\r
+        } catch(e) {\r
+          throw new Error(appXHTML);\r
+        }\r
+      } else {\r
+        // it's already in the document.\r
+        _s.oMC.innerHTML = html;\r
+        _s._appendSuccess = true;\r
+      }\r
+      if (!document.getElementById(_s.debugID) && ((!_s._hasConsole||!_s.useConsole)||(_s.useConsole && _s._hasConsole && !_s.consoleOnly))) {\r
+        var oDebug = document.createElement('div');\r
+        oDebug.id = _s.debugID;\r
+        oDebug.style.display = (_s.debugMode?'block':'none');\r
+        if (_s.debugMode) {\r
+          try {\r
+            var oD = document.createElement('div');\r
+            oTarget.appendChild(oD);\r
+            oD.innerHTML = toggleElement;\r
+          } catch(e) {\r
+            throw new Error(appXHTML);\r
+          };\r
+        };\r
+        oTarget.appendChild(oDebug);\r
+      };\r
+      oTarget = null;\r
+    };\r
+    _s._wD('-- SoundManager 2 '+_s.version+(_s.useMovieStar?', MovieStar mode':'')+(_s._wD?', high performance mode':'')+' --',1);\r
+    _s._wD('soundManager._createMovie(): Trying to load '+smURL+(!_s._overHTTP && _s.altURL?'(alternate URL)':''),1);\r
+  };\r
+\r
+  // aliased to this._wD()\r
+  this._writeDebug = function(sText,sType,bTimestamp) {\r
+    if (!_s.debugMode) return false;\r
+    if (typeof bTimestamp != 'undefined' && bTimestamp) {\r
+      sText = sText + ' | '+new Date().getTime();\r
+    };\r
+    if (_s._hasConsole && _s.useConsole) {\r
+      var sMethod = _s._debugLevels[sType];\r
+      if (typeof console[sMethod] != 'undefined') {\r
+        console[sMethod](sText);\r
+      } else {\r
+        console.log(sText);\r
+      };\r
+      if (_s.useConsoleOnly) return true;\r
+    };\r
+    var sDID = 'soundmanager-debug';\r
+    try {\r
+      var o = document.getElementById(sDID);\r
+      if (!o) return false;\r
+      var oItem = document.createElement('div');\r
+      sText = sText.replace(/\n/g,'<br />');\r
+      if (typeof sType == 'undefined') {\r
+        var sType = 0;\r
+      } else {\r
+        sType = parseInt(sType);\r
+      };\r
+      oItem.innerHTML = sText;\r
+      if (sType) {\r
+        if (sType >= 2) oItem.style.fontWeight = 'bold';\r
+        if (sType == 3) oItem.style.color = '#ff3333';\r
+      };\r
+      // o.appendChild(oItem); // top-to-bottom\r
+      o.insertBefore(oItem,o.firstChild); // bottom-to-top\r
+    } catch(e) {\r
+      // oh well\r
+    };\r
+    o = null;\r
+  };\r
+  this._writeDebug._protected = true;\r
+  this._wD = this._writeDebug;\r
+\r
+  this._wDAlert = function(sText) { alert(sText); };\r
+\r
+  if (window.location.href.indexOf('debug=alert')+1 && _s.debugMode) {\r
+    _s._wD = _s._wDAlert;\r
+  };\r
+\r
+  this._toggleDebug = function() {\r
+    var o = document.getElementById(_s.debugID);\r
+    var oT = document.getElementById(_s.debugID+'-toggle');\r
+    if (!o) return false;\r
+    if (_s._debugOpen) {\r
+      // minimize\r
+      oT.innerHTML = '+';\r
+      o.style.display = 'none';\r
+    } else {\r
+      oT.innerHTML = '-';\r
+      o.style.display = 'block';\r
+    };\r
+    _s._debugOpen = !_s._debugOpen;\r
+  };\r
+\r
+  this._toggleDebug._protected = true;\r
+\r
+  this._debug = function() {\r
+    _s._wD('--- soundManager._debug(): Current sound objects ---',1);\r
+    for (var i=0,j=_s.soundIDs.length; i<j; i++) {\r
+      _s.sounds[_s.soundIDs[i]]._debug();\r
+    };\r
+  };\r
+\r
+  this._mergeObjects = function(oMain,oAdd) {\r
+    // non-destructive merge\r
+    var o1 = {}; // clone o1\r
+    for (var i in oMain) {\r
+      o1[i] = oMain[i];\r
+    }\r
+    var o2 = (typeof oAdd == 'undefined'?_s.defaultOptions:oAdd);\r
+    for (var o in o2) {\r
+      if (typeof o1[o] == 'undefined') o1[o] = o2[o];\r
+    };\r
+    return o1;\r
+  };\r
+\r
+  this.createMovie = function(sURL) {\r
+    if (sURL) _s.url = sURL;\r
+    _s._initMovie();\r
+  };\r
+\r
+  this.go = this.createMovie; // nice alias\r
+\r
+  this._initMovie = function() {\r
+    // attempt to get, or create, movie\r
+    if (_s.o) return false; // pre-init may have fired this function before window.onload(), may already exist\r
+    _s.o = _s.getMovie(_s.id); // try to get flash movie (inline markup)\r
+    if (!_s.o) {\r
+      // try to create\r
+      _s._createMovie(_s.id,_s.url);\r
+      _s.o = _s.getMovie(_s.id);\r
+    };\r
+    if (_s.o) {\r
+      _s._wD('soundManager._initMovie(): Got '+_s.o.nodeName+' element ('+(_s._didAppend?'created via JS':'static HTML')+')',1);\r
+      _s._wD('soundManager._initMovie(): Waiting for ExternalInterface call from Flash..');\r
+    };\r
+  };\r
+\r
+  this.waitForExternalInterface = function() {\r
+    if (_s._waitingForEI) return false;\r
+    _s._waitingForEI = true;\r
+    if (_s._tryInitOnFocus && !_s._isFocused) {\r
+      _s._wD('soundManager: Special case: Flash may not have started due to non-focused tab (Safari is lame), and/or focus cannot be detected. Waiting for focus-related event..');\r
+      return false;\r
+    };\r
+    if (!_s._didInit) {\r
+      _s._wD('soundManager: Getting impatient, still waiting for Flash.. ;)');\r
+    };\r
+    setTimeout(function() {\r
+      if (!_s._didInit) {\r
+        _s._wD('soundManager: No Flash response within reasonable time after document load.\nPossible causes: Flash version under 8, no support, or Flash security denying JS-Flash communication.',2);\r
+        if (!_s._overHTTP) {\r
+          _s._wD('soundManager: Loading this page from local/network file system (not over HTTP?) Flash security likely restricting JS-Flash access. Consider adding current URL to "trusted locations" in the Flash player security settings manager at '+flashCPLink+', or simply serve this content over HTTP.',2);\r
+        };\r
+      };\r
+      // if still not initialized and no other options, give up\r
+      if (!_s._didInit && _s._okToDisable) _s._failSafely();\r
+    },750);\r
+  };\r
+\r
+  this.handleFocus = function() {\r
+    if (_s._isFocused || !_s._tryInitOnFocus) return true;\r
+    _s._okToDisable = true;\r
+    _s._isFocused = true;\r
+    _s._wD('soundManager.handleFocus()');\r
+    if (_s._tryInitOnFocus) {\r
+      // giant Safari 3.1 hack - assume window in focus if mouse is moving, since document.hasFocus() not currently implemented.\r
+      window.removeEventListener('mousemove',_s.handleFocus,false);\r
+    };\r
+    // allow init to restart\r
+    _s._waitingForEI = false;\r
+    setTimeout(_s.waitForExternalInterface,500);\r
+    // detach event\r
+    if (window.removeEventListener) {\r
+      window.removeEventListener('focus',_s.handleFocus,false);\r
+    } else if (window.detachEvent) {\r
+      window.detachEvent('onfocus',_s.handleFocus);\r
+    };\r
+  };\r
+\r
+  this.initComplete = function() {\r
+    if (_s._didInit) return false;\r
+    _s._didInit = true;\r
+    _s._wD('-- SoundManager 2 '+(_s._disabled?'failed to load':'loaded')+' ('+(_s._disabled?'security/load error':'OK')+') --',1);\r
+    if (_s._disabled) {\r
+      _s._wD('soundManager.initComplete(): calling soundManager.onerror()',1);\r
+      _s.onerror.apply(window);\r
+      return false;\r
+    };\r
+    if (_s.waitForWindowLoad && !_s._windowLoaded) {\r
+      _s._wD('soundManager: Waiting for window.onload()');\r
+      if (window.addEventListener) {\r
+        window.addEventListener('load',_s.initUserOnload,false);\r
+      } else if (window.attachEvent) {\r
+        window.attachEvent('onload',_s.initUserOnload);\r
+      };\r
+      return false;\r
+    } else {\r
+      if (_s.waitForWindowLoad && _s._windowLoaded) {\r
+        _s._wD('soundManager: Document already loaded');\r
+      };\r
+      _s.initUserOnload();\r
+    };\r
+  };\r
+\r
+  this.initUserOnload = function() {\r
+    _s._wD('soundManager.initComplete(): calling soundManager.onload()',1);\r
+    // call user-defined "onload", scoped to window\r
+    //try {\r
+      _s.onload.apply(window);\r
+      /*\r
+    } catch(e) {\r
+      // something broke (likely JS error in user function)\r
+      _s._wD('soundManager.onload() threw an exception: '+e.message,2);\r
+      setTimeout(function(){throw new Error(e)},20);\r
+      return false;\r
+    };\r
+    */\r
+    _s._wD('soundManager.onload() complete',1);\r
+  };\r
+\r
+  this.init = function() {\r
+    _s._wD('-- soundManager.init() --');\r
+    // called after onload()\r
+    _s._initMovie();\r
+    if (_s._didInit) {\r
+      _s._wD('soundManager.init(): Already called?');\r
+      return false;\r
+    };\r
+    // event cleanup\r
+    if (window.removeEventListener) {\r
+      window.removeEventListener('load',_s.beginDelayedInit,false);\r
+    } else if (window.detachEvent) {\r
+      window.detachEvent('onload',_s.beginDelayedInit);\r
+    };\r
+    try {\r
+      _s._wD('Attempting to call JS -&gt; Flash..');\r
+      _s.o._externalInterfaceTest(false); // attempt to talk to Flash\r
+      // _s._wD('Flash ExternalInterface call (JS-Flash) OK',1);\r
+      if (!_s.allowPolling) {\r
+           _s._wD('Polling (whileloading/whileplaying support) is disabled.',1);\r
+         }\r
+      _s.setPolling(true);\r
+         if (!_s.debugMode) _s.o._disableDebug();\r
+      _s.enabled = true;\r
+    } catch(e) {\r
+      _s._failSafely();\r
+      _s.initComplete();\r
+      return false;\r
+    };\r
+    _s.initComplete();\r
+  };\r
+\r
+  this.beginDelayedInit = function() {\r
+    _s._wD('soundManager.beginDelayedInit(): Document loaded');\r
+    _s._windowLoaded = true;\r
+    setTimeout(_s.waitForExternalInterface,500);\r
+    setTimeout(_s.beginInit,20);\r
+  };\r
+\r
+  this.beginInit = function() {\r
+    if (_s._initPending) return false;\r
+    _s.createMovie(); // ensure creation if not already done\r
+    _s._initMovie();\r
+    _s._initPending = true;\r
+    return true;\r
+  };\r
+\r
+  this.domContentLoaded = function() {\r
+    _s._wD('soundManager.domContentLoaded()');\r
+    if (document.removeEventListener) document.removeEventListener('DOMContentLoaded',_s.domContentLoaded,false);\r
+    _s.go();\r
+  };\r
+\r
+  this._externalInterfaceOK = function() {\r
+    // callback from flash for confirming that movie loaded, EI is working etc.\r
+    if (_s.swfLoaded) return false;\r
+    _s._wD('soundManager._externalInterfaceOK()');\r
+    _s.swfLoaded = true;\r
+    _s._tryInitOnFocus = false;\r
+    if (_s.isIE) {\r
+      // IE needs a timeout OR delay until window.onload - may need TODO: investigating\r
+      setTimeout(_s.init,100);\r
+    } else {\r
+      _s.init();\r
+    };\r
+  };\r
+\r
+  this._setSandboxType = function(sandboxType) {\r
+    var sb = _s.sandbox;\r
+    sb.type = sandboxType;\r
+    sb.description = sb.types[(typeof sb.types[sandboxType] != 'undefined'?sandboxType:'unknown')];\r
+    _s._wD('Flash security sandbox type: '+sb.type);\r
+    if (sb.type == 'localWithFile') {\r
+      sb.noRemote = true;\r
+      sb.noLocal = false;\r
+      _s._wD('Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',2);\r
+    } else if (sb.type == 'localWithNetwork') {\r
+      sb.noRemote = false;\r
+      sb.noLocal = true;\r
+    } else if (sb.type == 'localTrusted') {\r
+      sb.noRemote = false;\r
+      sb.noLocal = false;\r
+    };\r
+  };\r
+\r
+  this.destruct = function() {\r
+    _s._wD('soundManager.destruct()');\r
+    _s.disable(true);\r
+  };\r
+  \r
+  // SMSound (sound object)\r
+  \r
+  function SMSound(oOptions) {\r
+  var _t = this;\r
+  this.sID = oOptions.id;\r
+  this.url = oOptions.url;\r
+  this.options = _s._mergeObjects(oOptions);\r
+  this.instanceOptions = this.options; // per-play-instance-specific options\r
+  this._iO = this.instanceOptions; // short alias\r
+\r
+  this._debug = function() {\r
+    if (_s.debugMode) {\r
+    var stuff = null;\r
+    var msg = [];\r
+    var sF = null;\r
+    var sfBracket = null;\r
+    var maxLength = 64; // # of characters of function code to show before truncating\r
+    for (stuff in _t.options) {\r
+      if (_t.options[stuff] != null) {\r
+        if (_t.options[stuff] instanceof Function) {\r
+             // handle functions specially\r
+             sF = _t.options[stuff].toString();\r
+             sF = sF.replace(/\s\s+/g,' '); // normalize spaces\r
+             sfBracket = sF.indexOf('{');\r
+             msg[msg.length] = ' '+stuff+': {'+sF.substr(sfBracket+1,(Math.min(Math.max(sF.indexOf('\n')-1,maxLength),maxLength))).replace(/\n/g,'')+'... }';\r
+           } else {\r
+             msg[msg.length] = ' '+stuff+': '+_t.options[stuff];\r
+           };\r
+      };\r
+    };\r
+    _s._wD('SMSound() merged options: {\n'+msg.join(', \n')+'\n}');\r
+    };\r
+  };\r
+\r
+  this._debug();\r
+\r
+  this.id3 = {\r
+   /* \r
+    Name/value pairs set via Flash when available - see reference for names:\r
+    http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001567.html\r
+    (eg., this.id3.songname or this.id3['songname'])\r
+   */\r
+  };\r
+\r
+  this.resetProperties = function(bLoaded) {\r
+    _t.bytesLoaded = null;\r
+    _t.bytesTotal = null;\r
+    _t.position = null;\r
+    _t.duration = null;\r
+    _t.durationEstimate = null;\r
+    _t.loaded = false;\r
+    _t.playState = 0;\r
+    _t.paused = false;\r
+    _t.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success\r
+    _t.muted = false;\r
+    _t.didBeforeFinish = false;\r
+    _t.didJustBeforeFinish = false;\r
+    _t.instanceOptions = {};\r
+    _t.instanceCount = 0;\r
+    _t.peakData = {\r
+      left: 0,\r
+      right: 0\r
+    };\r
+    _t.waveformData = [];\r
+    _t.eqData = [];\r
+  };\r
+\r
+  _t.resetProperties();\r
+\r
+  // --- public methods ---\r
+\r
+  this.load = function(oOptions) {\r
+    if (typeof oOptions != 'undefined') {\r
+      _t._iO = _s._mergeObjects(oOptions);\r
+      _t.instanceOptions = _t._iO;\r
+    } else {\r
+      var oOptions = _t.options;\r
+      _t._iO = oOptions;\r
+      _t.instanceOptions = _t._iO;\r
+    } \r
+    if (typeof _t._iO.url == 'undefined') _t._iO.url = _t.url;\r
+    _s._wD('soundManager.load(): '+_t._iO.url,1);\r
+    if (_t._iO.url == _t.url && _t.readyState != 0 && _t.readyState != 2) {\r
+      _s._wD('soundManager.load(): current URL already assigned.',1);\r
+      return false;\r
+    }\r
+    _t.loaded = false;\r
+    _t.readyState = 1;\r
+    _t.playState = (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)\r
+    try {\r
+      if (_s.flashVersion==8) {\r
+        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream,_t._iO.autoPlay,(_t._iO.whileloading?1:0));\r
+      } else {\r
+        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream?true:false,_t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)\r
+        if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {\r
+          // special case: MPEG4 content must start playing to load, then pause to prevent playing.\r
+          _t.pause();\r
+        }\r
+      };\r
+    } catch(e) {\r
+      _s._wD('SMSound.load(): Exception: JS-Flash communication failed, or JS error.',2);\r
+      _s.onerror();\r
+      _s.disable();\r
+    };\r
+  };\r
+\r
+  this.unload = function() {\r
+    // Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3\r
+    // Flash 9/AS3: Close stream, preventing further load\r
+    if (_t.readyState != 0) {\r
+      _s._wD('SMSound.unload(): "'+_t.sID+'"');\r
+      if (_t.readyState != 2) { // reset if not error\r
+        _t.setPosition(0); // reset current sound positioning\r
+      }\r
+      _s.o._unload(_t.sID,_s.nullURL);\r
+      // reset load/status flags\r
+      _t.resetProperties();\r
+    }\r
+  };\r
+\r
+  this.destruct = function() {\r
+    // kill sound within Flash\r
+    _s._wD('SMSound.destruct(): "'+_t.sID+'"');\r
+    _s.o._destroySound(_t.sID);\r
+    _s.destroySound(_t.sID,true); // ensure deletion from controller\r
+  }\r
+\r
+  this.play = function(oOptions) {\r
+    if (!oOptions) oOptions = {};\r
+    _t._iO = _s._mergeObjects(oOptions,_t._iO);\r
+    _t._iO = _s._mergeObjects(_t._iO,_t.options);\r
+    _t.instanceOptions = _t._iO;\r
+    if (_t.playState == 1) {\r
+      var allowMulti = _t._iO.multiShot;\r
+      if (!allowMulti) {\r
+        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (one-shot)',1);\r
+        return false;\r
+      } else {\r
+        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (multi-shot)',1);\r
+      };\r
+    };\r
+    if (!_t.loaded) {\r
+      if (_t.readyState == 0) {\r
+        _s._wD('SMSound.play(): Attempting to load "'+_t.sID+'"',1);\r
+        // try to get this sound playing ASAP\r
+        _t._iO.stream = true;\r
+        _t._iO.autoPlay = true;\r
+        // TODO: need to investigate when false, double-playing\r
+        // if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here\r
+        _t.load(_t._iO); // try to get this sound playing ASAP\r
+      } else if (_t.readyState == 2) {\r
+        _s._wD('SMSound.play(): Could not load "'+_t.sID+'" - exiting',2);\r
+        return false;\r
+      } else {\r
+        _s._wD('SMSound.play(): "'+_t.sID+'" is loading - attempting to play..',1);\r
+      };\r
+    } else {\r
+      _s._wD('SMSound.play(): "'+_t.sID+'"');\r
+    };\r
+    if (_t.paused) {\r
+      _t.resume();\r
+    } else {\r
+      _t.playState = 1;\r
+      if (!_t.instanceCount || _s.flashVersion == 9) _t.instanceCount++;\r
+      _t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);\r
+      if (_t._iO.onplay) _t._iO.onplay.apply(_t);\r
+      _t.setVolume(_t._iO.volume);\r
+      _t.setPan(_t._iO.pan);\r
+      _s.o._start(_t.sID,_t._iO.loop||1,(_s.flashVersion==9?_t.position:_t.position/1000));\r
+    };\r
+  };\r
+\r
+  this.start = this.play; // just for convenience\r
+\r
+  this.stop = function(bAll) {\r
+    if (_t.playState == 1) {\r
+      _t.playState = 0;\r
+      _t.paused = false;\r
+      // if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);\r
+      if (_t._iO.onstop) _t._iO.onstop.apply(_t);\r
+      _s.o._stop(_t.sID,bAll);\r
+      _t.instanceCount = 0;\r
+      _t._iO = {};\r
+      // _t.instanceOptions = _t._iO;\r
+    };\r
+  };\r
+\r
+  this.setPosition = function(nMsecOffset) {\r
+    _t._iO.position = nMsecOffset;\r
+    _s._wD('SMSound.setPosition('+nMsecOffset+')');\r
+    _s.o._setPosition(_t.sID,(_s.flashVersion==9?_t._iO.position:_t._iO.position/1000),(_t.paused||!_t.playState)); // if paused or not playing, will not resume (by playing)\r
+  };\r
+\r
+  this.pause = function() {\r
+    if (_t.paused || _t.playState == 0) return false;\r
+    _s._wD('SMSound.pause()');\r
+    _t.paused = true;\r
+    _s.o._pause(_t.sID);\r
+    if (_t._iO.onpause) _t._iO.onpause.apply(_t);\r
+  };\r
+\r
+  this.resume = function() {\r
+    if (!_t.paused || _t.playState == 0) return false;\r
+    _s._wD('SMSound.resume()');\r
+    _t.paused = false;\r
+    _s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)\r
+    if (_t._iO.onresume) _t._iO.onresume.apply(_t);\r
+  };\r
+\r
+  this.togglePause = function() {\r
+    _s._wD('SMSound.togglePause()');\r
+    if (!_t.playState) {\r
+      _t.play({position:(_s.flashVersion==9?_t.position:_t.position/1000)});\r
+      return false;\r
+    };\r
+    if (_t.paused) {\r
+      _t.resume();\r
+    } else {\r
+      _t.pause();\r
+    };\r
+  };\r
+\r
+  this.setPan = function(nPan) {\r
+    if (typeof nPan == 'undefined') nPan = 0;\r
+    _s.o._setPan(_t.sID,nPan);\r
+    _t._iO.pan = nPan;\r
+  };\r
+\r
+  this.setVolume = function(nVol) {\r
+    if (typeof nVol == 'undefined') nVol = 100;\r
+    _s.o._setVolume(_t.sID,(_s.muted&&!_t.muted)||_t.muted?0:nVol);\r
+    _t._iO.volume = nVol;\r
+  };\r
+\r
+  this.mute = function() {\r
+       _t.muted = true;\r
+    _s.o._setVolume(_t.sID,0);\r
+  };\r
+\r
+  this.unmute = function() {\r
+       _t.muted = false;\r
+    _s.o._setVolume(_t.sID,typeof _t._iO.volume != 'undefined'?_t._iO.volume:_t.options.volume);\r
+  };\r
+\r
+  // --- "private" methods called by Flash ---\r
+\r
+  this._whileloading = function(nBytesLoaded,nBytesTotal,nDuration) {\r
+    if (!_t._iO.isMovieStar) {\r
+      _t.bytesLoaded = nBytesLoaded;\r
+      _t.bytesTotal = nBytesTotal;\r
+      _t.duration = Math.floor(nDuration);\r
+      _t.durationEstimate = parseInt((_t.bytesTotal/_t.bytesLoaded)*_t.duration); // estimate total time (will only be accurate with CBR MP3s.)\r
+      if (_t.readyState != 3 && _t._iO.whileloading) _t._iO.whileloading.apply(_t);\r
+    } else {\r
+      _t.bytesLoaded = nBytesLoaded;\r
+      _t.bytesTotal = nBytesTotal;\r
+      _t.duration = Math.floor(nDuration);\r
+      _t.durationEstimate = _t.duration;\r
+      if (_t.readyState != 3 && _t._iO.whileloading) _t._iO.whileloading.apply(_t);\r
+    }\r
+  };\r
+\r
+  this._onid3 = function(oID3PropNames,oID3Data) {\r
+    // oID3PropNames: string array (names)\r
+    // ID3Data: string array (data)\r
+    _s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');\r
+    var oData = [];\r
+    for (var i=0,j=oID3PropNames.length; i<j; i++) {\r
+      oData[oID3PropNames[i]] = oID3Data[i];\r
+      // _s._wD(oID3PropNames[i]+': '+oID3Data[i]);\r
+    };\r
+    _t.id3 = _s._mergeObjects(_t.id3,oData);\r
+    if (_t._iO.onid3) _t._iO.onid3.apply(_t);\r
+  };\r
+\r
+  this._whileplaying = function(nPosition,oPeakData,oWaveformData,oEQData) {\r
+    if (isNaN(nPosition) || nPosition == null) return false; // Flash may return NaN at times\r
+    _t.position = nPosition;\r
+       if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {\r
+         _t.peakData = {\r
+          left: oPeakData.leftPeak,\r
+          right: oPeakData.rightPeak\r
+         };\r
+       };\r
+       if (_t._iO.useWaveformData && typeof oWaveformData != 'undefined' && oWaveformData) {\r
+         _t.waveformData = oWaveformData;\r
+         /*\r
+         _t.spectrumData = {\r
+          left: oSpectrumData.left.split(','),\r
+          right: oSpectrumData.right.split(',')\r
+         }\r
+         */\r
+       };\r
+       if (_t._iO.useEQData && typeof oEQData != 'undefined' && oEQData) {\r
+         _t.eqData = oEQData;\r
+       };\r
+    if (_t.playState == 1) {\r
+      if (_t._iO.whileplaying) {\r
+           _t._iO.whileplaying.apply(_t); // flash may call after actual finish\r
+         };\r
+      if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration-_t.position <= _t._iO.onbeforefinishtime) {\r
+        _s._wD('duration-position &lt;= onbeforefinishtime: '+_t.duration+' - '+_t.position+' &lt= '+_t._iO.onbeforefinishtime+' ('+(_t.duration-_t.position)+')');\r
+        _t._onbeforefinish();\r
+      };\r
+    };\r
+  };\r
+\r
+  this._onload = function(bSuccess) {\r
+    bSuccess = (bSuccess==1?true:false);\r
+    _s._wD('SMSound._onload(): "'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url));\r
+    if (!bSuccess) {\r
+      if (_s.sandbox.noRemote == true) {\r
+        _s._wD('SMSound._onload(): Reminder: Flash security is denying network/internet access',1);\r
+      };\r
+      if (_s.sandbox.noLocal == true) {\r
+        _s._wD('SMSound._onload(): Reminder: Flash security is denying local access',1);\r
+      };\r
+    };\r
+    _t.loaded = bSuccess;\r
+    _t.readyState = bSuccess?3:2;\r
+    if (_t._iO.onload) {\r
+      _t._iO.onload.apply(_t);\r
+    };\r
+  };\r
+\r
+  this._onbeforefinish = function() {\r
+    if (!_t.didBeforeFinish) {\r
+      _t.didBeforeFinish = true;\r
+      if (_t._iO.onbeforefinish) {\r
+        _s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');\r
+        _t._iO.onbeforefinish.apply(_t);\r
+      }\r
+    };\r
+  };\r
+\r
+  this._onjustbeforefinish = function(msOffset) {\r
+    // msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)\r
+    if (!_t.didJustBeforeFinish) {\r
+      _t.didJustBeforeFinish = true;\r
+      if (_t._iO.onjustbeforefinish) {\r
+        _s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');\r
+        _t._iO.onjustbeforefinish.apply(_t);\r
+      }\r
+    };\r
+  };\r
+\r
+  this._onfinish = function() {\r
+    // sound has finished playing\r
+    _t.playState = 0;\r
+    _t.paused = false;\r
+    if (_t._iO.onfinish) {\r
+      _s._wD('SMSound._onfinish(): "'+_t.sID+'"');\r
+      _t._iO.onfinish.apply(_t);\r
+    }\r
+    if (_t._iO.onbeforefinishcomplete) _t._iO.onbeforefinishcomplete.apply(_t);\r
+    // reset some state items\r
+    _t.setPosition(0);\r
+    _t.didBeforeFinish = false;\r
+    _t.didJustBeforeFinish = false;\r
+    if (_t.instanceCount) {\r
+      _t.instanceCount--;\r
+      if (!_t.instanceCount) {\r
+        // reset instance options\r
+        _t.instanceCount = 0;\r
+        _t.instanceOptions = {};\r
+      }\r
+    }\r
+  };\r
+\r
+  this._onmetadata = function(oMetaData) {\r
+    // movieStar mode only\r
+    _s._wD('SMSound.onmetadata()');\r
+    // Contains a subset of metadata. Note that files may have their own unique metadata.\r
+    // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html\r
+    if (!oMetaData.width && !oMetaData.height) {\r
+         _s._wD('No width/height given, assuming defaults');\r
+         oMetaData.width = 320;\r
+         oMetaData.height = 240;\r
+    };\r
+    _t.metadata = oMetaData; // potentially-large object from flash\r
+    _t.width = oMetaData.width;\r
+    _t.height = oMetaData.height;\r
+    if (_t._iO.onmetadata) {\r
+      _s._wD('SMSound._onmetadata(): "'+_t.sID+'"');\r
+      _t._iO.onmetadata.apply(_t);\r
+    }\r
+    _s.wD('SMSound.onmetadata() complete');\r
+  };\r
+\r
+  }; // SMSound()\r
+\r
+  // register a few event handlers\r
+  if (window.addEventListener) {\r
+    window.addEventListener('focus',_s.handleFocus,false);\r
+    window.addEventListener('load',_s.beginDelayedInit,false);\r
+    window.addEventListener('unload',_s.destruct,false);\r
+    if (_s._tryInitOnFocus) window.addEventListener('mousemove',_s.handleFocus,false); // massive Safari focus hack\r
+  } else if (window.attachEvent) {\r
+    window.attachEvent('onfocus',_s.handleFocus);\r
+    window.attachEvent('onload',_s.beginDelayedInit);\r
+    window.attachEvent('unload',_s.destruct);\r
+  } else {\r
+    // no add/attachevent support - safe to assume no JS -> Flash either.\r
+    soundManager.onerror();\r
+    soundManager.disable();\r
+  };\r
+\r
+  if (document.addEventListener) document.addEventListener('DOMContentLoaded',_s.domContentLoaded,false);\r
+\r
+}; // SoundManager()\r
+\r
+var soundManager = new SoundManager();\r
diff --git a/timeside/ui/lib/soundmanager2.swf b/timeside/ui/lib/soundmanager2.swf
new file mode 100755 (executable)
index 0000000..98ed98d
Binary files /dev/null and b/timeside/ui/lib/soundmanager2.swf differ
diff --git a/timeside/ui/lib/soundmanager2_flash9.swf b/timeside/ui/lib/soundmanager2_flash9.swf
new file mode 100755 (executable)
index 0000000..14e4578
Binary files /dev/null and b/timeside/ui/lib/soundmanager2_flash9.swf differ
diff --git a/timeside/ui/lib/wz_jsgraphics.js b/timeside/ui/lib/wz_jsgraphics.js
new file mode 100755 (executable)
index 0000000..b3d1054
--- /dev/null
@@ -0,0 +1,1107 @@
+/* This notice must be untouched at all times.\r
+\r
+wz_jsgraphics.js    v. 3.03\r
+The latest version is available at\r
+http://www.walterzorn.com\r
+or http://www.devira.com\r
+or http://www.walterzorn.de\r
+\r
+Copyright (c) 2002-2004 Walter Zorn. All rights reserved.\r
+Created 3. 11. 2002 by Walter Zorn (Web: http://www.walterzorn.com )\r
+Last modified: 28. 1. 2008\r
+\r
+Performance optimizations for Internet Explorer\r
+by Thomas Frank and John Holdsworth.\r
+fillPolygon method implemented by Matthieu Haller.\r
+\r
+High Performance JavaScript Graphics Library.\r
+Provides methods\r
+- to draw lines, rectangles, ellipses, polygons\r
+       with specifiable line thickness,\r
+- to fill rectangles, polygons, ellipses and arcs\r
+- to draw text.\r
+NOTE: Operations, functions and branching have rather been optimized\r
+to efficiency and speed than to shortness of source code.\r
+\r
+LICENSE: LGPL\r
+\r
+This library is free software; you can redistribute it and/or\r
+modify it under the terms of the GNU Lesser General Public\r
+License (LGPL) as published by the Free Software Foundation; either\r
+version 2.1 of the License, or (at your option) any later version.\r
+\r
+This library is distributed in the hope that it will be useful,\r
+but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
+Lesser General Public License for more details.\r
+\r
+You should have received a copy of the GNU Lesser General Public\r
+License along with this library; if not, write to the Free Software\r
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA,\r
+or see http://www.gnu.org/copyleft/lesser.html\r
+*/\r
+\r
+\r
+var jg_ok, jg_ie, jg_fast, jg_dom, jg_moz;\r
+\r
+\r
+function _chkDHTM(x, i)\r
+{\r
+       x = document.body || null;\r
+       jg_ie = x && typeof x.insertAdjacentHTML != "undefined" && document.createElement;\r
+       jg_dom = (x && !jg_ie &&\r
+               typeof x.appendChild != "undefined" &&\r
+               typeof document.createRange != "undefined" &&\r
+               typeof (i = document.createRange()).setStartBefore != "undefined" &&\r
+               typeof i.createContextualFragment != "undefined");\r
+       jg_fast = jg_ie && document.all && !window.opera;\r
+       jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined";\r
+       jg_ok = !!(jg_ie || jg_dom);\r
+}\r
+\r
+function _pntCnvDom()\r
+{\r
+       var x = this.wnd.document.createRange();\r
+       x.setStartBefore(this.cnv);\r
+       x = x.createContextualFragment(jg_fast? this._htmRpc() : this.htm);\r
+       if(this.cnv) this.cnv.appendChild(x);\r
+       this.htm = "";\r
+}\r
+\r
+function _pntCnvIe()\r
+{\r
+       if(this.cnv) this.cnv.insertAdjacentHTML("BeforeEnd", jg_fast? this._htmRpc() : this.htm);\r
+       this.htm = "";\r
+}\r
+\r
+function _pntDoc()\r
+{\r
+       this.wnd.document.write(jg_fast? this._htmRpc() : this.htm);\r
+       this.htm = '';\r
+}\r
+\r
+function _pntN()\r
+{\r
+       ;\r
+}\r
+\r
+function _mkDiv(x, y, w, h)\r
+{\r
+       this.htm += '<div style="position:absolute;'+\r
+               'left:' + x + 'px;'+\r
+               'top:' + y + 'px;'+\r
+               'width:' + w + 'px;'+\r
+               'height:' + h + 'px;'+\r
+               'clip:rect(0,'+w+'px,'+h+'px,0);'+\r
+               'background-color:' + this.color +\r
+               (!jg_moz? ';overflow:hidden' : '')+\r
+               ';"><\/div>';\r
+}\r
+\r
+function _mkDivIe(x, y, w, h)\r
+{\r
+       this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';\r
+}\r
+\r
+function _mkDivPrt(x, y, w, h)\r
+{\r
+       this.htm += '<div style="position:absolute;'+\r
+               'border-left:' + w + 'px solid ' + this.color + ';'+\r
+               'left:' + x + 'px;'+\r
+               'top:' + y + 'px;'+\r
+               'width:0px;'+\r
+               'height:' + h + 'px;'+\r
+               'clip:rect(0,'+w+'px,'+h+'px,0);'+\r
+               'background-color:' + this.color +\r
+               (!jg_moz? ';overflow:hidden' : '')+\r
+               ';"><\/div>';\r
+}\r
+\r
+var _regex =  /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;\r
+function _htmRpc()\r
+{\r
+       return this.htm.replace(\r
+               _regex,\r
+               '<div style="overflow:hidden;position:absolute;background-color:'+\r
+               '$1;left:$2;top:$3;width:$4;height:$5"></div>\n');\r
+}\r
+\r
+function _htmPrtRpc()\r
+{\r
+       return this.htm.replace(\r
+               _regex,\r
+               '<div style="overflow:hidden;position:absolute;background-color:'+\r
+               '$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');\r
+}\r
+\r
+function _mkLin(x1, y1, x2, y2)\r
+{\r
+       if(x1 > x2)\r
+       {\r
+               var _x2 = x2;\r
+               var _y2 = y2;\r
+               x2 = x1;\r
+               y2 = y1;\r
+               x1 = _x2;\r
+               y1 = _y2;\r
+       }\r
+       var dx = x2-x1, dy = Math.abs(y2-y1),\r
+       x = x1, y = y1,\r
+       yIncr = (y1 > y2)? -1 : 1;\r
+\r
+       if(dx >= dy)\r
+       {\r
+               var pr = dy<<1,\r
+               pru = pr - (dx<<1),\r
+               p = pr-dx,\r
+               ox = x;\r
+               while(dx > 0)\r
+               {--dx;\r
+                       ++x;\r
+                       if(p > 0)\r
+                       {\r
+                               this._mkDiv(ox, y, x-ox, 1);\r
+                               y += yIncr;\r
+                               p += pru;\r
+                               ox = x;\r
+                       }\r
+                       else p += pr;\r
+               }\r
+               this._mkDiv(ox, y, x2-ox+1, 1);\r
+       }\r
+\r
+       else\r
+       {\r
+               var pr = dx<<1,\r
+               pru = pr - (dy<<1),\r
+               p = pr-dy,\r
+               oy = y;\r
+               if(y2 <= y1)\r
+               {\r
+                       while(dy > 0)\r
+                       {--dy;\r
+                               if(p > 0)\r
+                               {\r
+                                       this._mkDiv(x++, y, 1, oy-y+1);\r
+                                       y += yIncr;\r
+                                       p += pru;\r
+                                       oy = y;\r
+                               }\r
+                               else\r
+                               {\r
+                                       y += yIncr;\r
+                                       p += pr;\r
+                               }\r
+                       }\r
+                       this._mkDiv(x2, y2, 1, oy-y2+1);\r
+               }\r
+               else\r
+               {\r
+                       while(dy > 0)\r
+                       {--dy;\r
+                               y += yIncr;\r
+                               if(p > 0)\r
+                               {\r
+                                       this._mkDiv(x++, oy, 1, y-oy);\r
+                                       p += pru;\r
+                                       oy = y;\r
+                               }\r
+                               else p += pr;\r
+                       }\r
+                       this._mkDiv(x2, oy, 1, y2-oy+1);\r
+               }\r
+       }\r
+}\r
+\r
+function _mkLin2D(x1, y1, x2, y2)\r
+{\r
+       if(x1 > x2)\r
+       {\r
+               var _x2 = x2;\r
+               var _y2 = y2;\r
+               x2 = x1;\r
+               y2 = y1;\r
+               x1 = _x2;\r
+               y1 = _y2;\r
+       }\r
+       var dx = x2-x1, dy = Math.abs(y2-y1),\r
+       x = x1, y = y1,\r
+       yIncr = (y1 > y2)? -1 : 1;\r
+\r
+       var s = this.stroke;\r
+       if(dx >= dy)\r
+       {\r
+               if(dx > 0 && s-3 > 0)\r
+               {\r
+                       var _s = (s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy) / dx;\r
+                       _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;\r
+               }\r
+               else var _s = s;\r
+               var ad = Math.ceil(s/2);\r
+\r
+               var pr = dy<<1,\r
+               pru = pr - (dx<<1),\r
+               p = pr-dx,\r
+               ox = x;\r
+               while(dx > 0)\r
+               {--dx;\r
+                       ++x;\r
+                       if(p > 0)\r
+                       {\r
+                               this._mkDiv(ox, y, x-ox+ad, _s);\r
+                               y += yIncr;\r
+                               p += pru;\r
+                               ox = x;\r
+                       }\r
+                       else p += pr;\r
+               }\r
+               this._mkDiv(ox, y, x2-ox+ad+1, _s);\r
+       }\r
+\r
+       else\r
+       {\r
+               if(s-3 > 0)\r
+               {\r
+                       var _s = (s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy) / dy;\r
+                       _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;\r
+               }\r
+               else var _s = s;\r
+               var ad = Math.round(s/2);\r
+\r
+               var pr = dx<<1,\r
+               pru = pr - (dy<<1),\r
+               p = pr-dy,\r
+               oy = y;\r
+               if(y2 <= y1)\r
+               {\r
+                       ++ad;\r
+                       while(dy > 0)\r
+                       {--dy;\r
+                               if(p > 0)\r
+                               {\r
+                                       this._mkDiv(x++, y, _s, oy-y+ad);\r
+                                       y += yIncr;\r
+                                       p += pru;\r
+                                       oy = y;\r
+                               }\r
+                               else\r
+                               {\r
+                                       y += yIncr;\r
+                                       p += pr;\r
+                               }\r
+                       }\r
+                       this._mkDiv(x2, y2, _s, oy-y2+ad);\r
+               }\r
+               else\r
+               {\r
+                       while(dy > 0)\r
+                       {--dy;\r
+                               y += yIncr;\r
+                               if(p > 0)\r
+                               {\r
+                                       this._mkDiv(x++, oy, _s, y-oy+ad);\r
+                                       p += pru;\r
+                                       oy = y;\r
+                               }\r
+                               else p += pr;\r
+                       }\r
+                       this._mkDiv(x2, oy, _s, y2-oy+ad+1);\r
+               }\r
+       }\r
+}\r
+\r
+function _mkLinDott(x1, y1, x2, y2)\r
+{\r
+       if(x1 > x2)\r
+       {\r
+               var _x2 = x2;\r
+               var _y2 = y2;\r
+               x2 = x1;\r
+               y2 = y1;\r
+               x1 = _x2;\r
+               y1 = _y2;\r
+       }\r
+       var dx = x2-x1, dy = Math.abs(y2-y1),\r
+       x = x1, y = y1,\r
+       yIncr = (y1 > y2)? -1 : 1,\r
+       drw = true;\r
+       if(dx >= dy)\r
+       {\r
+               var pr = dy<<1,\r
+               pru = pr - (dx<<1),\r
+               p = pr-dx;\r
+               while(dx > 0)\r
+               {--dx;\r
+                       if(drw) this._mkDiv(x, y, 1, 1);\r
+                       drw = !drw;\r
+                       if(p > 0)\r
+                       {\r
+                               y += yIncr;\r
+                               p += pru;\r
+                       }\r
+                       else p += pr;\r
+                       ++x;\r
+               }\r
+       }\r
+       else\r
+       {\r
+               var pr = dx<<1,\r
+               pru = pr - (dy<<1),\r
+               p = pr-dy;\r
+               while(dy > 0)\r
+               {--dy;\r
+                       if(drw) this._mkDiv(x, y, 1, 1);\r
+                       drw = !drw;\r
+                       y += yIncr;\r
+                       if(p > 0)\r
+                       {\r
+                               ++x;\r
+                               p += pru;\r
+                       }\r
+                       else p += pr;\r
+               }\r
+       }\r
+       if(drw) this._mkDiv(x, y, 1, 1);\r
+}\r
+\r
+function _mkOv(left, top, width, height)\r
+{\r
+       var a = (++width)>>1, b = (++height)>>1,\r
+       wod = width&1, hod = height&1,\r
+       cx = left+a, cy = top+b,\r
+       x = 0, y = b,\r
+       ox = 0, oy = b,\r
+       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
+       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
+       tt = (bb2>>1) - aa2*((b<<1)-1),\r
+       w, h;\r
+       while(y > 0)\r
+       {\r
+               if(st < 0)\r
+               {\r
+                       st += bb2*((x<<1)+3);\r
+                       tt += bb4*(++x);\r
+               }\r
+               else if(tt < 0)\r
+               {\r
+                       st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                       tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+                       w = x-ox;\r
+                       h = oy-y;\r
+                       if((w&2) && (h&2))\r
+                       {\r
+                               this._mkOvQds(cx, cy, x-2, y+2, 1, 1, wod, hod);\r
+                               this._mkOvQds(cx, cy, x-1, y+1, 1, 1, wod, hod);\r
+                       }\r
+                       else this._mkOvQds(cx, cy, x-1, oy, w, h, wod, hod);\r
+                       ox = x;\r
+                       oy = y;\r
+               }\r
+               else\r
+               {\r
+                       tt -= aa2*((y<<1)-3);\r
+                       st -= aa4*(--y);\r
+               }\r
+       }\r
+       w = a-ox+1;\r
+       h = (oy<<1)+hod;\r
+       y = cy-oy;\r
+       this._mkDiv(cx-a, y, w, h);\r
+       this._mkDiv(cx+ox+wod-1, y, w, h);\r
+}\r
+\r
+function _mkOv2D(left, top, width, height)\r
+{\r
+       var s = this.stroke;\r
+       width += s+1;\r
+       height += s+1;\r
+       var a = width>>1, b = height>>1,\r
+       wod = width&1, hod = height&1,\r
+       cx = left+a, cy = top+b,\r
+       x = 0, y = b,\r
+       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
+       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
+       tt = (bb2>>1) - aa2*((b<<1)-1);\r
+\r
+       if(s-4 < 0 && (!(s-2) || width-51 > 0 && height-51 > 0))\r
+       {\r
+               var ox = 0, oy = b,\r
+               w, h,\r
+               pxw;\r
+               while(y > 0)\r
+               {\r
+                       if(st < 0)\r
+                       {\r
+                               st += bb2*((x<<1)+3);\r
+                               tt += bb4*(++x);\r
+                       }\r
+                       else if(tt < 0)\r
+                       {\r
+                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+                               w = x-ox;\r
+                               h = oy-y;\r
+\r
+                               if(w-1)\r
+                               {\r
+                                       pxw = w+1+(s&1);\r
+                                       h = s;\r
+                               }\r
+                               else if(h-1)\r
+                               {\r
+                                       pxw = s;\r
+                                       h += 1+(s&1);\r
+                               }\r
+                               else pxw = h = s;\r
+                               this._mkOvQds(cx, cy, x-1, oy, pxw, h, wod, hod);\r
+                               ox = x;\r
+                               oy = y;\r
+                       }\r
+                       else\r
+                       {\r
+                               tt -= aa2*((y<<1)-3);\r
+                               st -= aa4*(--y);\r
+                       }\r
+               }\r
+               this._mkDiv(cx-a, cy-oy, s, (oy<<1)+hod);\r
+               this._mkDiv(cx+a+wod-s, cy-oy, s, (oy<<1)+hod);\r
+       }\r
+\r
+       else\r
+       {\r
+               var _a = (width-(s<<1))>>1,\r
+               _b = (height-(s<<1))>>1,\r
+               _x = 0, _y = _b,\r
+               _aa2 = (_a*_a)<<1, _aa4 = _aa2<<1, _bb2 = (_b*_b)<<1, _bb4 = _bb2<<1,\r
+               _st = (_aa2>>1)*(1-(_b<<1)) + _bb2,\r
+               _tt = (_bb2>>1) - _aa2*((_b<<1)-1),\r
+\r
+               pxl = new Array(),\r
+               pxt = new Array(),\r
+               _pxb = new Array();\r
+               pxl[0] = 0;\r
+               pxt[0] = b;\r
+               _pxb[0] = _b-1;\r
+               while(y > 0)\r
+               {\r
+                       if(st < 0)\r
+                       {\r
+                               pxl[pxl.length] = x;\r
+                               pxt[pxt.length] = y;\r
+                               st += bb2*((x<<1)+3);\r
+                               tt += bb4*(++x);\r
+                       }\r
+                       else if(tt < 0)\r
+                       {\r
+                               pxl[pxl.length] = x;\r
+                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+                               pxt[pxt.length] = y;\r
+                       }\r
+                       else\r
+                       {\r
+                               tt -= aa2*((y<<1)-3);\r
+                               st -= aa4*(--y);\r
+                       }\r
+\r
+                       if(_y > 0)\r
+                       {\r
+                               if(_st < 0)\r
+                               {\r
+                                       _st += _bb2*((_x<<1)+3);\r
+                                       _tt += _bb4*(++_x);\r
+                                       _pxb[_pxb.length] = _y-1;\r
+                               }\r
+                               else if(_tt < 0)\r
+                               {\r
+                                       _st += _bb2*((_x<<1)+3) - _aa4*(_y-1);\r
+                                       _tt += _bb4*(++_x) - _aa2*(((_y--)<<1)-3);\r
+                                       _pxb[_pxb.length] = _y-1;\r
+                               }\r
+                               else\r
+                               {\r
+                                       _tt -= _aa2*((_y<<1)-3);\r
+                                       _st -= _aa4*(--_y);\r
+                                       _pxb[_pxb.length-1]--;\r
+                               }\r
+                       }\r
+               }\r
+\r
+               var ox = -wod, oy = b,\r
+               _oy = _pxb[0],\r
+               l = pxl.length,\r
+               w, h;\r
+               for(var i = 0; i < l; i++)\r
+               {\r
+                       if(typeof _pxb[i] != "undefined")\r
+                       {\r
+                               if(_pxb[i] < _oy || pxt[i] < oy)\r
+                               {\r
+                                       x = pxl[i];\r
+                                       this._mkOvQds(cx, cy, x, oy, x-ox, oy-_oy, wod, hod);\r
+                                       ox = x;\r
+                                       oy = pxt[i];\r
+                                       _oy = _pxb[i];\r
+                               }\r
+                       }\r
+                       else\r
+                       {\r
+                               x = pxl[i];\r
+                               this._mkDiv(cx-x, cy-oy, 1, (oy<<1)+hod);\r
+                               this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);\r
+                               ox = x;\r
+                               oy = pxt[i];\r
+                       }\r
+               }\r
+               this._mkDiv(cx-a, cy-oy, 1, (oy<<1)+hod);\r
+               this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);\r
+       }\r
+}\r
+\r
+function _mkOvDott(left, top, width, height)\r
+{\r
+       var a = (++width)>>1, b = (++height)>>1,\r
+       wod = width&1, hod = height&1, hodu = hod^1,\r
+       cx = left+a, cy = top+b,\r
+       x = 0, y = b,\r
+       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
+       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
+       tt = (bb2>>1) - aa2*((b<<1)-1),\r
+       drw = true;\r
+       while(y > 0)\r
+       {\r
+               if(st < 0)\r
+               {\r
+                       st += bb2*((x<<1)+3);\r
+                       tt += bb4*(++x);\r
+               }\r
+               else if(tt < 0)\r
+               {\r
+                       st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                       tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+               }\r
+               else\r
+               {\r
+                       tt -= aa2*((y<<1)-3);\r
+                       st -= aa4*(--y);\r
+               }\r
+               if(drw && y >= hodu) this._mkOvQds(cx, cy, x, y, 1, 1, wod, hod);\r
+               drw = !drw;\r
+       }\r
+}\r
+\r
+function _mkRect(x, y, w, h)\r
+{\r
+       var s = this.stroke;\r
+       this._mkDiv(x, y, w, s);\r
+       this._mkDiv(x+w, y, s, h);\r
+       this._mkDiv(x, y+h, w+s, s);\r
+       this._mkDiv(x, y+s, s, h-s);\r
+}\r
+\r
+function _mkRectDott(x, y, w, h)\r
+{\r
+       this.drawLine(x, y, x+w, y);\r
+       this.drawLine(x+w, y, x+w, y+h);\r
+       this.drawLine(x, y+h, x+w, y+h);\r
+       this.drawLine(x, y, x, y+h);\r
+}\r
+\r
+function jsgFont()\r
+{\r
+       this.PLAIN = 'font-weight:normal;';\r
+       this.BOLD = 'font-weight:bold;';\r
+       this.ITALIC = 'font-style:italic;';\r
+       this.ITALIC_BOLD = this.ITALIC + this.BOLD;\r
+       this.BOLD_ITALIC = this.ITALIC_BOLD;\r
+}\r
+var Font = new jsgFont();\r
+\r
+function jsgStroke()\r
+{\r
+       this.DOTTED = -1;\r
+}\r
+var Stroke = new jsgStroke();\r
+\r
+function jsGraphics(cnv, wnd)\r
+{\r
+       this.setColor = function(x)\r
+       {\r
+               this.color = x.toLowerCase();\r
+       };\r
+\r
+       this.setStroke = function(x)\r
+       {\r
+               this.stroke = x;\r
+               if(!(x+1))\r
+               {\r
+                       this.drawLine = _mkLinDott;\r
+                       this._mkOv = _mkOvDott;\r
+                       this.drawRect = _mkRectDott;\r
+               }\r
+               else if(x-1 > 0)\r
+               {\r
+                       this.drawLine = _mkLin2D;\r
+                       this._mkOv = _mkOv2D;\r
+                       this.drawRect = _mkRect;\r
+               }\r
+               else\r
+               {\r
+                       this.drawLine = _mkLin;\r
+                       this._mkOv = _mkOv;\r
+                       this.drawRect = _mkRect;\r
+               }\r
+       };\r
+\r
+       this.setPrintable = function(arg)\r
+       {\r
+               this.printable = arg;\r
+               if(jg_fast)\r
+               {\r
+                       this._mkDiv = _mkDivIe;\r
+                       this._htmRpc = arg? _htmPrtRpc : _htmRpc;\r
+               }\r
+               else this._mkDiv = arg? _mkDivPrt : _mkDiv;\r
+       };\r
+\r
+       this.setFont = function(fam, sz, sty)\r
+       {\r
+               this.ftFam = fam;\r
+               this.ftSz = sz;\r
+               this.ftSty = sty || Font.PLAIN;\r
+       };\r
+\r
+       this.drawPolyline = this.drawPolyLine = function(x, y)\r
+       {\r
+               for (var i=x.length - 1; i;)\r
+               {--i;\r
+                       this.drawLine(x[i], y[i], x[i+1], y[i+1]);\r
+               }\r
+       };\r
+\r
+       this.fillRect = function(x, y, w, h)\r
+       {\r
+               this._mkDiv(x, y, w, h);\r
+       };\r
+\r
+       this.drawPolygon = function(x, y)\r
+       {\r
+               this.drawPolyline(x, y);\r
+               this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]);\r
+       };\r
+\r
+       this.drawEllipse = this.drawOval = function(x, y, w, h)\r
+       {\r
+               this._mkOv(x, y, w, h);\r
+       };\r
+\r
+       this.fillEllipse = this.fillOval = function(left, top, w, h)\r
+       {\r
+               var a = w>>1, b = h>>1,\r
+               wod = w&1, hod = h&1,\r
+               cx = left+a, cy = top+b,\r
+               x = 0, y = b, oy = b,\r
+               aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
+               st = (aa2>>1)*(1-(b<<1)) + bb2,\r
+               tt = (bb2>>1) - aa2*((b<<1)-1),\r
+               xl, dw, dh;\r
+               if(w) while(y > 0)\r
+               {\r
+                       if(st < 0)\r
+                       {\r
+                               st += bb2*((x<<1)+3);\r
+                               tt += bb4*(++x);\r
+                       }\r
+                       else if(tt < 0)\r
+                       {\r
+                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                               xl = cx-x;\r
+                               dw = (x<<1)+wod;\r
+                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+                               dh = oy-y;\r
+                               this._mkDiv(xl, cy-oy, dw, dh);\r
+                               this._mkDiv(xl, cy+y+hod, dw, dh);\r
+                               oy = y;\r
+                       }\r
+                       else\r
+                       {\r
+                               tt -= aa2*((y<<1)-3);\r
+                               st -= aa4*(--y);\r
+                       }\r
+               }\r
+               this._mkDiv(cx-a, cy-oy, w, (oy<<1)+hod);\r
+       };\r
+\r
+       this.fillArc = function(iL, iT, iW, iH, fAngA, fAngZ)\r
+       {\r
+               var a = iW>>1, b = iH>>1,\r
+               iOdds = (iW&1) | ((iH&1) << 16),\r
+               cx = iL+a, cy = iT+b,\r
+               x = 0, y = b, ox = x, oy = y,\r
+               aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
+               st = (aa2>>1)*(1-(b<<1)) + bb2,\r
+               tt = (bb2>>1) - aa2*((b<<1)-1),\r
+               // Vars for radial boundary lines\r
+               xEndA, yEndA, xEndZ, yEndZ,\r
+               iSects = (1 << (Math.floor((fAngA %= 360.0)/180.0) << 3))\r
+                               | (2 << (Math.floor((fAngZ %= 360.0)/180.0) << 3))\r
+                               | ((fAngA >= fAngZ) << 16),\r
+               aBndA = new Array(b+1), aBndZ = new Array(b+1);\r
+               \r
+               // Set up radial boundary lines\r
+               fAngA *= Math.PI/180.0;\r
+               fAngZ *= Math.PI/180.0;\r
+               xEndA = cx+Math.round(a*Math.cos(fAngA));\r
+               yEndA = cy+Math.round(-b*Math.sin(fAngA));\r
+               _mkLinVirt(aBndA, cx, cy, xEndA, yEndA);\r
+               xEndZ = cx+Math.round(a*Math.cos(fAngZ));\r
+               yEndZ = cy+Math.round(-b*Math.sin(fAngZ));\r
+               _mkLinVirt(aBndZ, cx, cy, xEndZ, yEndZ);\r
+\r
+               while(y > 0)\r
+               {\r
+                       if(st < 0) // Advance x\r
+                       {\r
+                               st += bb2*((x<<1)+3);\r
+                               tt += bb4*(++x);\r
+                       }\r
+                       else if(tt < 0) // Advance x and y\r
+                       {\r
+                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
+                               ox = x;\r
+                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
+                               this._mkArcDiv(ox, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
+                               oy = y;\r
+                       }\r
+                       else // Advance y\r
+                       {\r
+                               tt -= aa2*((y<<1)-3);\r
+                               st -= aa4*(--y);\r
+                               if(y && (aBndA[y] != aBndA[y-1] || aBndZ[y] != aBndZ[y-1]))\r
+                               {\r
+                                       this._mkArcDiv(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
+                                       ox = x;\r
+                                       oy = y;\r
+                               }\r
+                       }\r
+               }\r
+               this._mkArcDiv(x, 0, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
+               if(iOdds >> 16) // Odd height\r
+               {\r
+                       if(iSects >> 16) // Start-angle > end-angle\r
+                       {\r
+                               var xl = (yEndA <= cy || yEndZ > cy)? (cx - x) : cx;\r
+                               this._mkDiv(xl, cy, x + cx - xl + (iOdds & 0xffff), 1);\r
+                       }\r
+                       else if((iSects & 0x01) && yEndZ > cy)\r
+                               this._mkDiv(cx - x, cy, x, 1);\r
+               }\r
+       };\r
+\r
+/* fillPolygon method, implemented by Matthieu Haller.\r
+This javascript function is an adaptation of the gdImageFilledPolygon for Walter Zorn lib.\r
+C source of GD 1.8.4 found at http://www.boutell.com/gd/\r
+\r
+THANKS to Kirsten Schulz for the polygon fixes!\r
+\r
+The intersection finding technique of this code could be improved\r
+by remembering the previous intertersection, and by using the slope.\r
+That could help to adjust intersections to produce a nice\r
+interior_extrema. */\r
+       this.fillPolygon = function(array_x, array_y)\r
+       {\r
+               var i;\r
+               var y;\r
+               var miny, maxy;\r
+               var x1, y1;\r
+               var x2, y2;\r
+               var ind1, ind2;\r
+               var ints;\r
+\r
+               var n = array_x.length;\r
+               if(!n) return;\r
+\r
+               miny = array_y[0];\r
+               maxy = array_y[0];\r
+               for(i = 1; i < n; i++)\r
+               {\r
+                       if(array_y[i] < miny)\r
+                               miny = array_y[i];\r
+\r
+                       if(array_y[i] > maxy)\r
+                               maxy = array_y[i];\r
+               }\r
+               for(y = miny; y <= maxy; y++)\r
+               {\r
+                       var polyInts = new Array();\r
+                       ints = 0;\r
+                       for(i = 0; i < n; i++)\r
+                       {\r
+                               if(!i)\r
+                               {\r
+                                       ind1 = n-1;\r
+                                       ind2 = 0;\r
+                               }\r
+                               else\r
+                               {\r
+                                       ind1 = i-1;\r
+                                       ind2 = i;\r
+                               }\r
+                               y1 = array_y[ind1];\r
+                               y2 = array_y[ind2];\r
+                               if(y1 < y2)\r
+                               {\r
+                                       x1 = array_x[ind1];\r
+                                       x2 = array_x[ind2];\r
+                               }\r
+                               else if(y1 > y2)\r
+                               {\r
+                                       y2 = array_y[ind1];\r
+                                       y1 = array_y[ind2];\r
+                                       x2 = array_x[ind1];\r
+                                       x1 = array_x[ind2];\r
+                               }\r
+                               else continue;\r
+\r
+                                //  Modified 11. 2. 2004 Walter Zorn\r
+                               if((y >= y1) && (y < y2))\r
+                                       polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);\r
+\r
+                               else if((y == maxy) && (y > y1) && (y <= y2))\r
+                                       polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);\r
+                       }\r
+                       polyInts.sort(_CompInt);\r
+                       for(i = 0; i < ints; i+=2)\r
+                               this._mkDiv(polyInts[i], y, polyInts[i+1]-polyInts[i]+1, 1);\r
+               }\r
+       };\r
+\r
+       this.drawString = function(txt, x, y)\r
+       {\r
+               this.htm += '<div style="position:absolute;white-space:nowrap;'+\r
+                       'left:' + x + 'px;'+\r
+                       'top:' + y + 'px;'+\r
+                       'font-family:' +  this.ftFam + ';'+\r
+                       'font-size:' + this.ftSz + ';'+\r
+                       'color:' + this.color + ';' + this.ftSty + '">'+\r
+                       txt +\r
+                       '<\/div>';\r
+       };\r
+\r
+/* drawStringRect() added by Rick Blommers.\r
+Allows to specify the size of the text rectangle and to align the\r
+text both horizontally (e.g. right) and vertically within that rectangle */\r
+       this.drawStringRect = function(txt, x, y, width, halign)\r
+       {\r
+               this.htm += '<div style="position:absolute;overflow:hidden;'+\r
+                       'left:' + x + 'px;'+\r
+                       'top:' + y + 'px;'+\r
+                       'width:'+width +'px;'+\r
+                       'text-align:'+halign+';'+\r
+                       'font-family:' +  this.ftFam + ';'+\r
+                       'font-size:' + this.ftSz + ';'+\r
+                       'color:' + this.color + ';' + this.ftSty + '">'+\r
+                       txt +\r
+                       '<\/div>';\r
+       };\r
+\r
+       this.drawImage = function(imgSrc, x, y, w, h, a)\r
+       {\r
+               this.htm += '<div style="position:absolute;'+\r
+                       'left:' + x + 'px;'+\r
+                       'top:' + y + 'px;'+\r
+                       // w (width) and h (height) arguments are now optional.\r
+                       // Added by Mahmut Keygubatli, 14.1.2008\r
+                       (w? ('width:' +  w + 'px;') : '') +\r
+                       (h? ('height:' + h + 'px;'):'')+'">'+\r
+                       '<img src="' + imgSrc +'"'+ (w ? (' width="' + w + '"'):'')+ (h ? (' height="' + h + '"'):'') + (a? (' '+a) : '') + '>'+\r
+                       '<\/div>';\r
+       };\r
+\r
+       this.clear = function()\r
+       {\r
+               this.htm = "";\r
+               if(this.cnv) this.cnv.innerHTML = "";\r
+       };\r
+\r
+       this._mkOvQds = function(cx, cy, x, y, w, h, wod, hod)\r
+       {\r
+               var xl = cx - x, xr = cx + x + wod - w, yt = cy - y, yb = cy + y + hod - h;\r
+               if(xr > xl+w)\r
+               {\r
+                       this._mkDiv(xr, yt, w, h);\r
+                       this._mkDiv(xr, yb, w, h);\r
+               }\r
+               else\r
+                       w = xr - xl + w;\r
+               this._mkDiv(xl, yt, w, h);\r
+               this._mkDiv(xl, yb, w, h);\r
+       };\r
+       \r
+       this._mkArcDiv = function(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects)\r
+       {\r
+               var xrDef = cx + x + (iOdds & 0xffff), y2, h = oy - y, xl, xr, w;\r
+\r
+               if(!h) h = 1;\r
+               x = cx - x;\r
+\r
+               if(iSects & 0xff0000) // Start-angle > end-angle\r
+               {\r
+                       y2 = cy - y - h;\r
+                       if(iSects & 0x00ff)\r
+                       {\r
+                               if(iSects & 0x02)\r
+                               {\r
+                                       xl = Math.max(x, aBndZ[y]);\r
+                                       w = xrDef - xl;\r
+                                       if(w > 0) this._mkDiv(xl, y2, w, h);\r
+                               }\r
+                               if(iSects & 0x01)\r
+                               {\r
+                                       xr = Math.min(xrDef, aBndA[y]);\r
+                                       w = xr - x;\r
+                                       if(w > 0) this._mkDiv(x, y2, w, h);\r
+                               }\r
+                       }\r
+                       else\r
+                               this._mkDiv(x, y2, xrDef - x, h);\r
+                       y2 = cy + y + (iOdds >> 16);\r
+                       if(iSects & 0xff00)\r
+                       {\r
+                               if(iSects & 0x0100)\r
+                               {\r
+                                       xl = Math.max(x, aBndA[y]);\r
+                                       w = xrDef - xl;\r
+                                       if(w > 0) this._mkDiv(xl, y2, w, h);\r
+                               }\r
+                               if(iSects & 0x0200)\r
+                               {\r
+                                       xr = Math.min(xrDef, aBndZ[y]);\r
+                                       w = xr - x;\r
+                                       if(w > 0) this._mkDiv(x, y2, w, h);\r
+                               }\r
+                       }\r
+                       else\r
+                               this._mkDiv(x, y2, xrDef - x, h);\r
+               }\r
+               else\r
+               {\r
+                       if(iSects & 0x00ff)\r
+                       {\r
+                               if(iSects & 0x02)\r
+                                       xl = Math.max(x, aBndZ[y]);\r
+                               else\r
+                                       xl = x;\r
+                               if(iSects & 0x01)\r
+                                       xr = Math.min(xrDef, aBndA[y]);\r
+                               else\r
+                                       xr = xrDef;\r
+                               y2 = cy - y - h;\r
+                               w = xr - xl;\r
+                               if(w > 0) this._mkDiv(xl, y2, w, h);\r
+                       }\r
+                       if(iSects & 0xff00)\r
+                       {\r
+                               if(iSects & 0x0100)\r
+                                       xl = Math.max(x, aBndA[y]);\r
+                               else\r
+                                       xl = x;\r
+                               if(iSects & 0x0200)\r
+                                       xr = Math.min(xrDef, aBndZ[y]);\r
+                               else\r
+                                       xr = xrDef;\r
+                               y2 = cy + y + (iOdds >> 16);\r
+                               w = xr - xl;\r
+                               if(w > 0) this._mkDiv(xl, y2, w, h);\r
+                       }\r
+               }\r
+       };\r
+\r
+       this.setStroke(1);\r
+       this.setFont("verdana,geneva,helvetica,sans-serif", "12px", Font.PLAIN);\r
+       this.color = "#000000";\r
+       this.htm = "";\r
+       this.wnd = wnd || window;\r
+\r
+       if(!jg_ok) _chkDHTM();\r
+       if(jg_ok)\r
+       {\r
+               if(cnv)\r
+               {\r
+                       if(typeof(cnv) == "string")\r
+                               this.cont = document.all? (this.wnd.document.all[cnv] || null)\r
+                                       : document.getElementById? (this.wnd.document.getElementById(cnv) || null)\r
+                                       : null;\r
+                       else if(cnv == window.document)\r
+                               this.cont = document.getElementsByTagName("body")[0];\r
+                       // If cnv is a direct reference to a canvas DOM node\r
+                       // (option suggested by Andreas Luleich)\r
+                       else this.cont = cnv;\r
+                       // Create new canvas inside container DIV. Thus the drawing and clearing\r
+                       // methods won't interfere with the container's inner html.\r
+                       // Solution suggested by Vladimir.\r
+                       this.cnv = this.wnd.document.createElement("div");\r
+                       this.cnv.style.fontSize=0;\r
+                       this.cont.appendChild(this.cnv);\r
+                       this.paint = jg_dom? _pntCnvDom : _pntCnvIe;\r
+               }\r
+               else\r
+                       this.paint = _pntDoc;\r
+       }\r
+       else\r
+               this.paint = _pntN;\r
+\r
+       this.setPrintable(false);\r
+}\r
+\r
+function _mkLinVirt(aLin, x1, y1, x2, y2)\r
+{\r
+       var dx = Math.abs(x2-x1), dy = Math.abs(y2-y1),\r
+       x = x1, y = y1,\r
+       xIncr = (x1 > x2)? -1 : 1,\r
+       yIncr = (y1 > y2)? -1 : 1,\r
+       p,\r
+       i = 0;\r
+       if(dx >= dy)\r
+       {\r
+               var pr = dy<<1,\r
+               pru = pr - (dx<<1);\r
+               p = pr-dx;\r
+               while(dx > 0)\r
+               {--dx;\r
+                       if(p > 0)    //  Increment y\r
+                       {\r
+                               aLin[i++] = x;\r
+                               y += yIncr;\r
+                               p += pru;\r
+                       }\r
+                       else p += pr;\r
+                       x += xIncr;\r
+               }\r
+       }\r
+       else\r
+       {\r
+               var pr = dx<<1,\r
+               pru = pr - (dy<<1);\r
+               p = pr-dy;\r
+               while(dy > 0)\r
+               {--dy;\r
+                       y += yIncr;\r
+                       aLin[i++] = x;\r
+                       if(p > 0)    //  Increment x\r
+                       {\r
+                               x += xIncr;\r
+                               p += pru;\r
+                       }\r
+                       else p += pr;\r
+               }\r
+       }\r
+       for(var len = aLin.length, i = len-i; i;)\r
+               aLin[len-(i--)] = x;\r
+};\r
+\r
+function _CompInt(x, y)\r
+{\r
+       return(x - y);\r
+}\r
+\r
diff --git a/timeside/ui/skins/lab/img/controlbg.png b/timeside/ui/skins/lab/img/controlbg.png
new file mode 100755 (executable)
index 0000000..57840d0
Binary files /dev/null and b/timeside/ui/skins/lab/img/controlbg.png differ
diff --git a/timeside/ui/skins/lab/img/forward.png b/timeside/ui/skins/lab/img/forward.png
new file mode 100755 (executable)
index 0000000..86485d0
Binary files /dev/null and b/timeside/ui/skins/lab/img/forward.png differ
diff --git a/timeside/ui/skins/lab/img/pause.png b/timeside/ui/skins/lab/img/pause.png
new file mode 100755 (executable)
index 0000000..d09ad51
Binary files /dev/null and b/timeside/ui/skins/lab/img/pause.png differ
diff --git a/timeside/ui/skins/lab/img/play.png b/timeside/ui/skins/lab/img/play.png
new file mode 100755 (executable)
index 0000000..ccb87e8
Binary files /dev/null and b/timeside/ui/skins/lab/img/play.png differ
diff --git a/timeside/ui/skins/lab/img/rewind.png b/timeside/ui/skins/lab/img/rewind.png
new file mode 100755 (executable)
index 0000000..ec45b38
Binary files /dev/null and b/timeside/ui/skins/lab/img/rewind.png differ
diff --git a/timeside/ui/skins/lab/img/setmarker.png b/timeside/ui/skins/lab/img/setmarker.png
new file mode 100644 (file)
index 0000000..b642e82
Binary files /dev/null and b/timeside/ui/skins/lab/img/setmarker.png differ
diff --git a/timeside/ui/skins/lab/style.css b/timeside/ui/skins/lab/style.css
new file mode 100755 (executable)
index 0000000..5dcd353
--- /dev/null
@@ -0,0 +1,116 @@
+.ts-skin-lab .ts-player {
+  background: #3c4251;
+  padding-top: 10px;
+  padding-bottom: 10px;
+  border: dotted #b2b2b2 1px;
+}
+
+.ts-skin-lab .ts-player .ts-viewer {
+  margin: 0 12px 10px 12px;
+  border: solid 1px white;
+}
+
+.ts-skin-lab .ts-player .ts-viewer .ts-marker {
+    color: white;
+    background: #7290bc;
+}
+
+.ts-skin-lab .ts-player .ts-viewer a.ts-marker, .ts-skin-lab .ts-player .ts-viewer a.ts-pointer {
+    text-decoration: none;
+    line-height: 13px;
+}
+
+.ts-skin-lab .ts-player .ts-viewer .ts-pointer {
+    color: #3c4251;
+    background: #e7e7e7;
+}
+
+.ts-skin-lab .ts-player .ts-ruler .ts-section .ts-label {
+    color: #c3c2cc;
+    background: #2a3242;
+    padding-bottom: 1px;
+    padding-left: 2px;
+    line-height: 13px;
+}
+
+.ts-skin-lab .ts-player .ts-ruler .ts-section .ts-lines {
+    background: #384051;
+    color: #9498a1;
+    border-bottom: solid 1px white;
+    line-height: 13px;
+}
+
+.ts-skin-lab .ts-player .ts-wave .ts-image {
+    background: #090e0d ;
+}
+
+.ts-skin-lab .ts-player .ts-control {
+    background: url('img/controlbg.png');
+    height: 28px;
+    border-top: dotted #b2b2b2 1px;
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-layout {
+    margin-left: 12px;
+    margin-right: 12px;
+    padding-top: 4px;
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback a {
+    display: block;
+    float: left;
+    width: 21px;
+    padding: 21px 0 0 0;
+    overflow: hidden;
+    height: 0px !important; 
+    height /**/:21px; /* for IE5/Win only */
+    margin-right: 1px;
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback a:hover {
+    background-position: 0 -21px;
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback .ts-play {
+    background-image: url('img/play.png');
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback .ts-pause {
+    background-image: url('img/pause.png');
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback .ts-rewind {
+    background-image: url('img/rewind.png');
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback .ts-forward {
+    background-image: url('img/forward.png');
+}
+
+.ts-skin-lab .ts-player .ts-control .ts-playback .ts-set-marker {
+    background-image: url('img/setmarker.png');
+}
+
+/* unused */
+.ts-skin-lab .ts-player .ts-marker-control .ts-set-marker {
+    display: block;
+    width: 89px;
+    padding: 21px 0 0 0;
+    overflow: hidden;
+    height: 0px !important; 
+    height /**/:21px; /* for IE5/Win only */
+    background-image: url('img/setmarker.gif');
+    margin: 5px auto 0 auto;
+}
+
+/* unused */
+.ts-skin-lab .ts-player .ts-marker-control .ts-set-marker:hover {
+    background-position: 0 -21px;
+}
+
+.ts-skin-lab .ts-player .ts-marker-control {
+    border-top: dotted #b2b2b2 1px;
+    border-bottom: dotted #b2b2b2 1px;
+    height: 30px;
+}
+
diff --git a/timeside/ui/src/controller.js b/timeside/ui/src/controller.js
new file mode 100644 (file)
index 0000000..ba0870b
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N) {
+
+$N.Class.create("Controller", $N.Core, {
+
+    initialize: function($super, cfg) {
+        $super();
+        this.configure(cfg, {
+            player: null,
+            soundProvider: null,
+            map: null
+        });
+        if (this.cfg.player && !$N.isInstanceOf(this.cfg.player, 'Player')) {
+            this.cfg.player = new $N.Player(this.cfg.player);
+        }
+        this._setupPlayer();
+    },
+
+    _setupPlayer: function() {
+        this.cfg.player
+            .setSoundProvider(this.cfg.soundProvider)
+            .setMarkerMap(this.cfg.map)
+            .observe('play', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.play))
+            .observe('pause', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.pause))
+            .observe('move', this.attach(this._onMove))
+            .observe('markeradd', this.attach(this._onMarkerAdd))
+            .observe('markermove', this.attach(this._onMarkerMove))
+            .draw();
+    },
+
+    _onMove: function(e, data) {
+        this.cfg.soundProvider.seek(data.offset);
+    },
+
+    _onMarkerMove: function(e, data) {
+        if (this.cfg.map) {
+            this.cfg.map.move(this.cfg.map.byId(data.id), data.offset);
+        }
+    },
+
+    _onMarkerAdd: function(e, data) {
+        if (this.cfg.map) {
+            this.cfg.map.add(data.offset, 'marker at ' + data.offset);
+        }
+    }
+
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/core.js b/timeside/ui/src/core.js
new file mode 100644 (file)
index 0000000..3f48121
--- /dev/null
@@ -0,0 +1,271 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.extend = function(destination, source) {
+  for (var property in source)
+    destination[property] = source[property];
+  return destination;
+};
+
+$N.objectKeys = function(object) {
+    var keys = [];
+    for (var property in object)
+      keys.push(property);
+    return keys;
+};
+
+$N.argumentNames = function(method) {
+    var names = method.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
+      .replace(/\s+/g, '').split(',');
+    return names.length == 1 && !names[0] ? [] : names;
+};  
+
+$N.argsToArray = function(args) {
+    var length = args.length || 0, result = new Array(length);
+    while (length--) result[length] = args[length];
+    return result;
+};
+
+$N.wrapFunction = function(wrapper, method) {
+    return function() {
+      var args = $N.argsToArray(arguments);
+      return wrapper.apply(this, [$N.attachFunction(this, method)].concat(args)); 
+    }
+};
+$N.attachFunction = function() {
+    if (arguments.length < 3 && (typeof arguments[1] == 'undefined')) return arguments[0];
+    var args = $N.argsToArray(arguments);
+    var object = args.shift();
+    var method = args.shift();
+    return function() {
+      var _args = $N.argsToArray(arguments);
+      return method.apply(object, args.concat(_args));
+    }
+};
+
+$N.attachAsEventListener = function() {
+    var args = $N.argsToArray(arguments), object = args.shift();
+    var method = args.shift();
+    return function(event) {
+      return method.apply(object, [event || window.event].concat(args));
+    }
+};
+
+$N.isInstanceOf = function(obj, className) {
+    if (typeof obj == 'object' && obj.__class__) {
+        var c = obj.__class__;
+        if (c.__name__ == className) {
+            return true;
+        }
+        while (c = c.__super__) {
+            if (c.__name__ == className) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
+$N.Class = {
+  create: function() {
+    var parent = null, className = null;
+    var properties = $N.argsToArray(arguments)
+    if (typeof properties[0] == "string")
+      className = properties.shift();
+    if (typeof properties[0] == "function")
+      parent = properties.shift();
+    
+    function klass() {
+      this.initialize.apply(this, arguments);
+    }
+    
+    $N.extend(klass, $N.Class.Methods);
+    klass.__name__ = className;
+    klass.__super__ = parent;
+    klass.__subclasses__ = [];
+    
+    if (parent) {
+      var subclass = function() { };
+      subclass.prototype = parent.prototype;
+      klass.prototype = new subclass;
+      parent.__subclasses__.push(klass);
+    }
+    
+    klass.prototype.__class__ = klass;
+    for (var i = 0; i < properties.length; i++)
+      klass.addMethods(properties[i]);
+      
+    if (!klass.prototype.initialize)
+      klass.prototype.initialize = function () {};
+    
+    klass.prototype.constructor = klass;
+   
+    if (className) {
+        $N[className] = klass;
+    }
+    return klass;
+  }
+};
+$N.Class.Methods = {
+  addMethods: function(source) {
+    var ancestor   = this.__super__ && this.__super__.prototype;
+    var properties = $N.objectKeys(source);
+    
+    if (!$N.objectKeys({ toString: true }).length)
+      properties.push("toString", "valueOf");
+    
+    for (var i = 0, length = properties.length; i < length; i++) {
+      var property = properties[i], value = source[property];
+      if (ancestor && (typeof value == 'function') &&
+          $N.argumentNames(value)[0] == "$super") {
+        var method = value;
+        value = $N.wrapFunction(method, (function(m) {
+          return function() { return ancestor[m].apply(this, arguments) };
+        })(property));
+        value.valueOf = $N.attachFunction(method, method.valueOf);
+        value.toString = $N.attachFunction(method, method.toString);
+      }
+      this.prototype[property] = value;
+    }
+    
+    return this;
+  }
+};
+$N.Core = $N.Class.create("Core", {
+    eventContainer: null,
+    eventPrefix: '',
+    cfg: {},
+
+    initialize: function() {
+        this.debug("new instance");
+        $N.registerInstance(this);
+        this.eventContainer = $J('<div/>');
+        this.forwardEvent = this.attach(this._forwardEvent);
+    },
+
+    free: function() {
+        this.eventContainer = null;
+    },
+
+    configure: function(config, defaults) {
+        if (!config)
+            config = {};
+        for (k in defaults) {
+            var value = null, flags = [];
+
+            if (defaults[k] && typeof defaults[k][0] !== 'undefined') {
+                value = defaults[k][0];
+                if (defaults[k][1]) {
+                    flags = defaults[k][1].split(",");
+                }
+            } else {
+                value = defaults[k];
+            }
+
+            if (typeof config[k] !== 'undefined') 
+                value = config[k];
+
+            var source = this;
+            $J(flags).each(function(i, flag) {
+                switch (flag) {
+                    case 'required':
+                        if (value === null)
+                            throw new $N.RequiredOptionError(source, k);
+                        break;
+                        /*
+                    case 'element':
+                        value = $J(value);
+                        break;
+                        */
+
+                }
+            });
+
+            this.cfg[k] = value;
+        }
+        return this;
+    },
+
+    observe: function(eventName, handler) {
+        this.eventContainer.bind(this.eventPrefix + eventName, handler);
+        return this;
+    },
+
+    fire: function(eventName, data) {
+        if (!data)
+            data = {};
+        this.eventContainer.trigger(this.eventPrefix + eventName, data);
+        return this;
+    },
+
+    _forwardEvent: function(e, data) {
+        if (!data)
+            data = {};
+        this.eventContainer.trigger(e.type, data);
+        return this;
+    },
+
+    _textWidth: function(text, fontSize) {
+        var ratio = 3/5;
+        return text.length * ratio * fontSize;
+    },
+
+    debug: function(message) {
+        if ($N.debugging && typeof console != 'undefined' && console.log) {
+            console.log('TimeSide.' + this.__class__.__name__ + ': ' + message);
+        }
+    },
+
+    attach: function(method) {
+        return $N.attachFunction(this, method);
+    },
+
+    attachWithEvent: function(method) {
+        return $N.attachAsEventListener(this, method);
+    },
+
+    uniqid: function() {
+        d = new Date();
+        return new String(d.getTime() + '' + Math.floor(Math.random() * 1000000)).substr(0, 18);
+    }
+});
+
+$N.Class.create("Exception", {
+    _source: null,
+    _message: null,
+
+    initialize: function(source, message) {
+        this._source = source;
+        this._message = message;
+    },
+    toString: function() {
+        return this.__class__.__name__ + " from TimeSide." + this._source.__class__.__name__
+            + ": " + this._message;
+    }
+});
+
+$N.Class.create("RequiredOptionError", $N.Exception, {
+    initialize: function($super, source, optionName) {
+        $super(source, "missing '" + optionName + "' required option");
+    }
+});
+
+$N.Class.create("RequiredArgumentError", $N.Exception, {
+    initialize: function($super, source, optionName) {
+        $super(source, "missing '" + optionName + "' required argument");
+    }
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/marker.js b/timeside/ui/src/marker.js
new file mode 100644 (file)
index 0000000..32f7443
--- /dev/null
@@ -0,0 +1,219 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.Class.create("Marker", $N.Core, {
+    id: null,
+    painter: null,
+    visible: false,
+    position: 0,
+    label: null,
+    blinking: false,
+    nodes: null,
+    mouseDown: false,
+    blinkAnimation: null,
+
+    initialize: function($super, cfg) {
+        $super();
+        this.configure(cfg, {
+            rulerLayout: [null, 'required'],
+            viewer: [null, 'required'],
+            fontSize: 10,
+            zIndex: null,
+            className: [null, 'required'],
+            id: null,
+            tooltip: null
+        });
+        this.cfg.rulerLayout = $J(this.cfg.rulerLayout);
+        this.cfg.viewer = $J(this.cfg.viewer);
+
+        this.id = cfg.id;
+        this.width = this.cfg.viewer.width();
+        this.painter = new jsGraphics(this.cfg.viewer.get(0));
+        this._create();
+        this._observeMouseEvents();
+    },
+
+    free: function($super) {
+        this.cfg.rulerLayout = null;
+        this.cfg.viewer = null;
+        $super();
+    },
+
+    clear: function() {
+        this.painter.clear();
+        $J(this.painter.cnv).remove();
+        this.label.remove();
+        return this;
+    },
+
+    _create: function() {
+        this.debug('create marker');
+        var y = this.cfg.rulerLayout.find('.' + $N.cssPrefix + 'label').outerHeight();
+        this.label = $J('<a/>')
+            .css({
+                display: 'block',
+                width: '10px', 
+                textAlign: 'center', 
+                position: 'absolute', 
+                fontSize: this.cfg.fontSize + 'px', 
+                fontFamily: 'monospace', 
+                top: y + 'px'
+            })
+            .attr('href', '#')
+            .addClass($N.cssPrefix + this.cfg.className)
+            .append('<span />')
+            .hide();
+
+        if (this.cfg.tooltip)
+            this.label.attr('title', this.cfg.tooltip);
+
+        this.cfg.rulerLayout.append(this.label);
+
+        var height = this.cfg.viewer.height();
+        var x = 0;
+        this.painter.drawLine(x, 0, x, height);
+        x     = [-4, 4, 0];
+        var y = [0, 0, 4];
+        this.painter.fillPolygon(x, y);
+        this.painter.paint();
+        this.nodes = $J(this.painter.cnv).children();
+
+        var style = {};
+        if (this.cfg.zIndex) {
+            style.zIndex = this.cfg.zIndex;
+            this.label.css(style);
+        }
+        style.backgroundColor = '';
+
+        this.nodes.hide().css(style).addClass($N.cssPrefix + this.cfg.className)
+            .each(function(i, node) {
+                node.originalPosition = parseInt($J(node).css('left'));
+            });
+    },
+
+    setText: function(text) {
+        if (this.label) {
+            text += '';
+            var labelWidth = this._textWidth(text, this.cfg.fontSize) + 10;
+            labelWidth += 'px';
+            if (this.label.css('width') != labelWidth) {
+                this.label.css({ width: labelWidth });
+            }
+            this.label.find('span').html(text);
+        }
+        return this;
+    },
+
+    move: function(pixelOffset) {
+        if (this.position != pixelOffset) {
+            if (pixelOffset < 0) {
+                pixelOffset = 0;
+            } else if (pixelOffset >= this.width) {
+                pixelOffset = this.width - 1;
+            }
+            this.nodes.each(function(i, node) { 
+                $J(node).css('left', Math.round(node.originalPosition + pixelOffset) + 'px');
+            });
+            var labelWidth = this.label.width();
+            var labelPixelOffset = pixelOffset - labelWidth / 2;
+            if (labelPixelOffset < 0)
+                labelPixelOffset = 0;
+            else if (labelPixelOffset + labelWidth > this.width) 
+                labelPixelOffset = this.width - labelWidth;
+            this.label.css({left: Math.round(labelPixelOffset) + 'px'});            
+            this.position = pixelOffset;
+        }
+        return this;
+    },
+
+    show: function(offset) {
+        if (!this.visible) {
+            this.nodes.show();
+            this.label.show();
+            this.visible = true;
+        }
+        return this;
+    },
+
+    hide: function() {
+        this.nodes.hide();
+        this.label.hide();
+        this.visible = false;
+        return this;
+    },
+
+    isVisible: function() {
+        return this.visible;
+    },
+
+    blink: function(state) {
+        var speed = 200;
+        if (this.label && this.blinking != state) {
+            var span = this.label.find('span');
+
+            span.stop();
+
+            function fade(on) {
+                if (on) {
+                    span.animate({opacity: 1}, speed, null, 
+                        function() { fade(false) });
+                } else {
+                    span.animate({opacity: 0.4}, speed, null, 
+                        function() { fade(true) })
+                }
+            }
+
+            if (state) {
+                fade();
+            } else {
+                span.animate({opacity: 1}, speed);
+            }
+
+            this.blinking = state;
+        }
+        return this;
+    },
+
+    _onMouseDown: function(evt) {
+        this.mouseDown = true;
+        this._onMouseMove(evt);
+        return false;
+    },
+
+    _onMouseMove: function(evt) {
+        if (this.mouseDown) {
+            var offset = (evt.pageX - this.cfg.rulerLayout.offset().left);
+            this.move(offset);
+            this.fire('move', {offset: this.position, finish: false});
+            return false;
+        }
+    },
+
+    _onMouseUp: function(evt) {
+        if (this.mouseDown) {
+            this.mouseDown = false;
+            this.fire('move', {id: this.id, offset: this.position, finish: true});
+            return false;
+        }
+    },
+
+    _observeMouseEvents: function() {
+        this.label.mousedown(this.attachWithEvent(this._onMouseDown))
+            .bind('click dragstart', function() {return false;});
+        this.cfg.rulerLayout.mousemove(this.attachWithEvent(this._onMouseMove));
+        this.cfg.rulerLayout.mouseup(this.attachWithEvent(this._onMouseUp));
+        $J(document).mouseup(this.attachWithEvent(this._onMouseUp));
+    }
+
+
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/markerlist.js b/timeside/ui/src/markerlist.js
new file mode 100755 (executable)
index 0000000..52bd1d4
--- /dev/null
@@ -0,0 +1,32 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N) {
+
+$N.Class.create("MarkerList", $N.Core, {
+    initialize: function($super, cfg) {
+        $super();
+        this.cfg = this.configure(cfg, {
+            container: null,
+            map: null
+        });
+    },
+
+    _buildItem: function(marker) {
+        var dt = new Element('dt');
+        var time = $N.Util.makeTimeLabel(marker.offset);
+
+
+    },
+
+    _setupInterface: function() {
+    }
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/markermap.js b/timeside/ui/src/markermap.js
new file mode 100644 (file)
index 0000000..543fb2e
--- /dev/null
@@ -0,0 +1,122 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.Class.create("MarkerMap", $N.Core, {
+    markers: null,
+
+    initialize: function($super, markers) {
+        $super();
+        if (!markers)
+            markers = [];
+        this.markers = markers;
+    },
+
+    toArray: function() {
+        return [].concat(this.markers);
+    },
+
+    byIndex: function(index) {
+        return this.markers[index];
+    },
+
+    byId: function(id) {
+        var marker = null;
+        for (var i in this.markers) {
+            if (this.markers[i].id == id) {
+                marker = this.markers[i];
+                break;
+            }
+        }
+        return marker;
+    },
+
+    indexOf: function(marker) {
+        var index = null;
+        for (var i in this.markers) {
+            if (this.markers[i].id == marker.id) {
+                index = parseInt(i);
+                break;
+            }
+        }
+        return index;
+    },
+
+    _reorder: function() {
+        this.markers.sort(this.compare);
+        for (var i in this.markers) {
+            this.fire('indexchange', {marker: this.markers[i], index: parseInt(i)});
+        }
+    },
+
+    add: function(offset, desc) {
+        var id = this.uniqid();
+        var marker = {id: id, offset: offset, desc: desc};
+        var i = this.markers.push(marker) - 1;
+        this.fire('add', {marker: marker, index: i});
+        this._reorder();
+        return marker;
+    },
+
+    remove: function(marker) {
+        if (marker) {
+            var i = this.indexOf(marker);
+            this.markers.splice(i, 1);
+            this.fire('remove', {marker: marker});
+            this._reorder();
+        }
+        return marker;
+    },
+
+    compare: function(marker1, marker2) {
+        if (marker1.offset > marker2.offset)
+            return 1;
+        if (marker1.offset < marker2.offset)
+            return -1;
+        return 0;
+    },
+
+    move: function(marker, offset) {
+        oldMarkers = [].concat(this.markers);
+        marker.offset = offset;
+        this._reorder();
+    },
+
+    getPrevious: function(offset, skip) {
+        var marker = null;
+        if (!skip) skip = 0;
+        markers = [].concat(this.markers).reverse();
+        $J(markers).each(function(i, m) {
+            if (offset > m.offset && !(skip--)) {
+                marker = m;
+                return false;
+            }
+        });
+        return marker;
+    },
+
+    getNext: function(offset, skip) {
+        var marker = null;
+        if (!skip) skip = 0;
+        $J(this.markers).each(function(i, m) {
+            if (offset < m.offset && !(skip--)) {
+                marker = m;
+                return false;
+            }
+        });
+        return marker;
+    },
+
+    each: function(callback) {
+        $J(this.markers).each(callback);
+    }
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/player.js b/timeside/ui/src/player.js
new file mode 100644 (file)
index 0000000..04df2f6
--- /dev/null
@@ -0,0 +1,222 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.Class.create("Player", $N.Core, {
+    skeleton: {
+        'div.viewer': {
+            'div.ruler': {}, 
+            'div.wave': {
+                'div.image-canvas': {},
+                'div.image-container': ['img.image']
+            }
+        },
+        'div.control': {
+            'div.layout': {
+                'div.playback': ['a.play', 'a.pause', 'a.rewind', 'a.forward', 'a.set-marker']
+            }
+        }/*,
+        'div.marker-control': ['a.set-marker']*/
+    },
+    defaultContents: {
+        play: 'Play',
+        pause: 'Pause',
+        rewind: 'Rewind',
+        forward: 'Forward',
+        'set-marker': 'Set marker'
+    },
+    elements: {},
+    ruler: null,
+    soundProvider: null,
+    map: null,
+    container: null,
+    imageWidth: null,
+    imageHeight: null,
+
+    initialize: function($super, container, cfg) {
+        $super();
+        if (!container)
+            throw new $N.RequiredArgumentError(this, 'container');
+        this.container = $J(container);
+        this.configure(cfg, {
+            image: null
+        });
+    },
+
+    free: function($super) {
+        this.elements = null;
+        this.container = null;
+        $super();
+    },
+
+    setSoundProvider: function(soundProvider) {
+        this.soundProvider = soundProvider;
+        return this;
+    },
+
+    setMarkerMap: function(map) {
+        this.map = map;
+        return this;
+    },
+
+    setImage: function(expr) {
+        this.cfg.image = expr;
+        this.refreshImage();
+    },
+
+    refreshImage: function() {
+        var src = null;
+        if (typeof this.cfg.image == 'function') {
+            src = this.cfg.image(this.imageWidth, this.imageHeight);
+        } else if (typeof this.cfg.image == 'string') {
+            src = this.cfg.image;
+        }
+
+        if (src) 
+            this.elements.image.attr('src', src);
+    },
+
+    draw: function() {
+        this.debug('drawing');
+        $N.domReady(this.attach(this._setupInterface));
+        return this;
+    },
+
+    _setupInterface: function() {
+        this.elements = $N.Util.loadUI(this.container, this.skeleton, this.defaultContents);
+
+        // IE apparently doesn't send the second mousedown on double click:
+        var jump = $J.browser.msie ? 'mousedown dblclick' : 'mousedown';
+        this.elements.rewind.attr('href', '#').bind(jump, this.attach(this._onRewind))
+            .click(function() {return false; });
+        this.elements.forward.attr('href', '#').bind(jump, this.attach(this._onForward))
+            .click(function() {return false; });
+        this.elements.pause.attr('href', '#').bind('click', this.attach(this._onPause));
+        this.elements.play.attr('href', '#').bind('click', this.attach(this._onPlay));
+        this.elements.control.find('a').add(this.elements.setMarker)
+            .attr('href', '#')
+            .each(function(i, a){
+                a = $J(a);
+                if (!a.attr('title'))
+                    a.attr('title', a.text());
+            });
+            
+        //this.elements.markerControl.find('a').attr('href', '#');
+        if (this.map) {
+            this.elements.setMarker.bind('click', this.attach(this._onSetMarker));
+        } else {
+            this.elements.setMarker.remove();
+        }
+        this.ruler = new $N.Ruler({
+            viewer: this.elements.viewer,
+            map: this.map,
+            soundProvider: this.soundProvider
+        });
+        this.ruler
+            .observe('markermove', this.forwardEvent)
+            .observe('markeradd', this.forwardEvent)
+            .observe('move', this.forwardEvent)
+            .draw();
+        this.refreshImage();
+        this.resize();
+        var resizeTimer = null;
+        $J(window).resize(this.attach(function() {
+            if (resizeTimer)
+                clearTimeout(resizeTimer);
+            resizeTimer = setTimeout(this.attach(this.resize), 100);
+        }));
+        //this.container.resize(this.attach(this.resize)); // Can loop ?
+    },
+
+    resize: function(overrideHeight) {
+        this.debug("resizing");
+        var height;
+        if (overrideHeight === true) {
+            this.debug("override height");
+            height = this.elements.image.css('height', 'auto').height();
+        } else {
+            height = this.elements.wave.height();
+            this.debug("wave height:" + height);
+            if (!height) {
+                this.elements.image.one('load', this.attach(function() {
+                    this.resize(true);
+                    this.debug("image loaded");
+                }));
+                height = this.elements.image.height();
+            }
+        }
+
+        var elements = this.elements.image
+            .add(this.elements.imageContainer)
+            .add(this.elements.imageCanvas);
+
+        elements.css('width', 'auto'); // for IE6
+
+        if (!height)
+            height = 200;
+        var style = {
+            width: this.elements.wave.width(),
+            height: height
+        }
+        elements.css(style);
+        this.imageWidth = style.width;
+        this.imageHeight = style.height;
+        this.refreshImage();
+        this.ruler.resize();
+        return this;
+    },
+
+    _onRewind: function() {
+        var offset = 0;
+        if (this.map) {
+            var position = this.soundProvider.getPosition();
+            var marker = this.map.getPrevious(position);
+            if (marker && this.soundProvider.isPlaying() 
+                && position - marker.offset < this.ruler.getUnitDuration())
+                marker = this.map.getPrevious(marker.offset)
+            if (marker) {
+                offset = marker.offset;
+            }
+        }
+        this.fire('move', {offset: offset});
+        return false;
+    },
+
+    _onForward: function() {
+        var offset = this.soundProvider.getDuration();
+        if (this.map) {
+            var marker = this.map.getNext(this.soundProvider.getPosition());
+            if (marker) {
+                offset = marker.offset;
+            }
+        }
+        this.fire('move', {offset: offset});
+        return false;
+    },
+
+    _onPlay: function() {
+        this.fire('play');
+        return false;
+    },
+
+    _onPause: function() {
+        this.fire('pause');
+        return false;
+    },
+
+    _onSetMarker: function() {
+        if (this.map) {
+            this.fire('markeradd', {offset: this.soundProvider.getPosition()});
+        }
+        return false;
+    }
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/ruler.js b/timeside/ui/src/ruler.js
new file mode 100644 (file)
index 0000000..5932c43
--- /dev/null
@@ -0,0 +1,398 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.Class.create("Ruler", $N.Core, {
+
+    fullSectionDuration: 60,
+    sectionSubDivision: 10,
+    sectionSteps: [[5, 1], [10, 1], [20, 2], [30, 5], [60, 10], [120, 20], [300, 30], 
+        [600, 60], [1800, 300], [3600, 600]],
+    sectionsNum: 0,
+    timeLabelWidth: 0,
+    pointerPos: 0,
+    layout: null,
+    width: null,
+    mouseDown: false,
+    pointer: null,
+    markers: new Array(),
+    duration: 0,
+    container: null,
+    waveContainer: null,
+
+    initialize: function($super, cfg) {
+        $super();
+        this.configure(cfg, {
+            viewer: [null, 'required'],
+            fontSize: 10,
+            map: null,
+            soundProvider: [null, 'required']
+        });
+        this.cfg.viewer = $J(this.cfg.viewer);
+        this.container = this.cfg.viewer.find('.' + $N.cssPrefix + 'ruler');
+        this.waveContainer = this.cfg.viewer.find('.' + $N.cssPrefix + 'image-canvas');
+        this._setDuration(this.cfg.soundProvider.getDuration());
+        var imgContainer = this.cfg.viewer.find('.' + $N.cssPrefix + 'image-container'); // for IE
+        this._observeMouseEvents(this.waveContainer.add(imgContainer));
+        if (this.cfg.map) {
+            this.cfg.map
+                .observe('add', this.attach(this._onMapAdd))
+                .observe('remove', this.attach(this._onMapRemove))
+                .observe('indexchange', this.attach(this._onMapIndexChange));
+        }
+        this.cfg.soundProvider.observe('update', this.attach(this._onSoundProviderUpdate));
+    },
+
+    free: function($super) {
+        this.layout = null;
+        this.container = null;
+        this.waveContainer = null;
+        this.cfg.viewer = null;
+        $super();
+    },
+
+    _computeLayout: function() {
+        this.width = this.waveContainer.width();
+                
+        this.debug('container width: ' + this.width);
+        var i, ii = this.sectionSteps.length;
+        this.timeLabelWidth = this._textWidth('00:00', this.cfg.fontSize);
+        for (i = 0; i < ii; i++) {
+            var duration = this.sectionSteps[i][0];
+            var subDivision = this.sectionSteps[i][1];
+            var labelsNum = Math.floor(this.duration / duration);
+            if ((i == ii - 1) || (this.width / labelsNum > this.timeLabelWidth * 2)) {
+                this.fullSectionDuration = duration;
+                this.sectionSubDivision = subDivision;
+                this.sectionsNum = Math.floor(this.duration / this.fullSectionDuration);
+                break;
+            }
+        }
+    },
+
+    getUnitDuration: function() {
+        return this.sectionSubDivision;
+    },
+
+    resize: function() {
+        var pointerVisible = this.pointer && this.pointer.isVisible();
+        this._computeLayout();
+        this.draw();
+        if (pointerVisible) {
+            this.setPosition(this.cfg.soundProvider.getPosition());
+            this.setBuffering(this.cfg.soundProvider.isBuffering() && this.cfg.soundProvider.isPlaying());
+            this.pointer.show();
+        }            
+    },
+
+    _setDuration: function(duration) {
+        this.duration = duration;
+        this._computeLayout();
+    },
+
+    setDuration: function(duration) {
+        if (duration == 0)
+            duration = 60;
+        if (this.duration != duration) {
+            this._setDuration(duration);
+            this.draw();
+        }
+    },
+
+    _createSection: function(timeOffset, pixelWidth) {
+        var section = $J('<div/>')
+            .addClass($N.cssPrefix + 'section')
+            .css({
+                fontSize: this.cfg.fontSize + 'px', 
+                fontFamily: 'monospace',
+                width: pixelWidth,
+                overflow: 'hidden'
+            })
+            .append($J('<div />').addClass($N.cssPrefix + 'canvas'));
+
+        var topDiv = $J('<div/>')
+            .addClass($N.cssPrefix + 'label')
+            .appendTo(section);
+        var bottomDiv = $J('<div/>')
+            .addClass($N.cssPrefix + 'lines')
+            .appendTo(section);
+        var empty = $J('<span/>').css({visibility: 'hidden'}).text('&nbsp;');
+        if (pixelWidth > this.timeLabelWidth) {
+            var text = $J('<span/>')
+                .text($N.Util.makeTimeLabel(timeOffset))
+                .bind('mousedown selectstart', function() {return false;});
+        } else {
+            var text = empty.clone();
+        }
+        topDiv.append(text);
+        bottomDiv.append(empty);
+        return section;
+    },
+
+    _drawSectionRuler: function(section, drawFirstMark) {
+        var j;
+        var jg = new jsGraphics(section.find('.' + $N.cssPrefix + 'canvas').get(0));
+        jg.setColor(this.layout.find('.' + $N.cssPrefix + 'lines').css('color'));
+        var height = section.height();
+        var ypos;
+        for (j = 0; j < section.duration; j += this.sectionSubDivision) {
+            if (j == 0) {
+                if (drawFirstMark) {
+                    ypos = 0;
+                } else {
+                    continue;
+                }
+            } else {
+                ypos = (j == section.duration / 2) ? 1/2 + 1/8 : 3/4;
+            }
+            var x = j / this.duration * this.width;
+            jg.drawLine(x, height * ypos, x, height - 1);
+        }
+        jg.paint();
+    },
+
+    getHeight: function() {
+        return this.container.find('' + $N.cssPrefix + '.section').height();
+    },
+
+    draw: function() {
+        if (!this.duration) {
+            this.debug("Can't draw ruler with a duration of 0");
+            return;
+        }
+        this.debug("draw ruler, duration: " + this.duration);
+        if (this.layout)
+            this.layout.remove();
+        this.layout = $J('<div/>')
+            .addClass($N.cssPrefix + 'layout')
+            .css({position: 'relative'}) // bugs on IE when resizing
+            .bind('dblclick', this.attachWithEvent(this._onDoubleClick))
+            //.bind('resize', this.attachWithEvent(this.resize)) // Can loop ?
+            .appendTo(this.container);
+
+        //this.container.html(this.layout);
+
+        var sections = new Array();
+        var currentWidth = 0;
+        var i;
+        for (i = 0; i <= this.sectionsNum; i++) {
+            if (i < this.sectionsNum) {
+                var duration = this.fullSectionDuration;
+                var width = Math.floor(duration / this.duration * this.width);
+            } else {
+                var duration = this.duration - i * this.fullSectionDuration;
+                var width = this.width - currentWidth;
+
+            }               
+            var section = this._createSection(i * this.fullSectionDuration, width);
+            if (i > 0) {
+                section.css({left: currentWidth, top: 0, position: 'absolute'});
+            }
+            section.duration = duration;
+            this.layout.append(section);
+            currentWidth += section.width();
+            sections[i] = section;
+        }
+
+        for (i = 0; i <= this.sectionsNum; i++) {
+            this._drawSectionRuler(sections[i], (i > 0));
+        }
+
+        this._createPointer();
+        this._drawMarkers();
+    },
+
+    _createPointer: function() {
+        if (this.pointer) {
+            this.pointer.clear();
+        }
+        this.pointer = new $N.Marker({
+            rulerLayout: this.layout.get(0),
+            viewer: this.waveContainer,
+            fontSize: this.cfg.fontSize,
+            zIndex: 1000,
+            className: 'pointer',
+            tooltip: 'Move head'
+        });
+        this.pointer
+            .setText($N.Util.makeTimeLabel(0))
+            .observe('move', this.attach(this._onPointerMove));
+    },
+
+    _drawMarkers: function() {
+        if (this.cfg.map) {
+            $J(this.markers).each(function(i, m) {m.clear();});
+            this.markers = new Array();
+            this.cfg.map.each(this.attach(function(i, m) {
+                this.markers.push(this._drawMarker(m, i));
+            }));
+        }
+    },
+
+    _movePointer: function(offset) {
+        if (offset < 0)
+            offset = 0;
+        else if (offset > this.duration)
+            offset = this.duration;
+            
+        pixelOffset = offset / this.duration * this.width;
+        if (this.pointer) {
+            this.pointer.move(pixelOffset);
+            this.pointer.setText($N.Util.makeTimeLabel(offset));
+        }            
+        this.pointerPos = offset;
+    },
+
+    _setPosition: function(offset) {
+        this._movePointer(offset);
+        if (this.pointer) {
+            this.pointer.show();
+        }            
+    },
+
+    setPosition: function(offset) {
+        if (!this.mouseDown) {
+            this._setPosition(offset);
+        }
+    },
+
+    shiftPosition: function(delta) {
+        this.setPosition(this.pointerPos + delta);
+    },
+
+    hidePointer: function() {
+        if (this.pointer)
+            this.pointer.hide();
+    },
+
+    setBuffering: function(state) {
+        if (this.pointer) {
+            this.pointer.blink(state);
+        }
+    },
+/*
+    _onClick: function(evt) {
+        var offset = (evt.pageX - this.container.offset().left) 
+            / this.width * this.duration;
+        this._setPosition(offset);
+        this.fire('move', {offset: offset});
+    },
+*/
+    _onMouseDown: function(evt) {
+        this.mouseDown = true;
+        this._onMouseMove(evt);
+        evt.preventDefault();
+    },
+
+    _onPointerMove: function(evt, data) {
+        this.mouseDown = true;
+        this._setPosition(data.offset / this.width * this.duration);
+        if(data.finish) {
+            this.fire('move', {offset: this.pointerPos});
+            this.mouseDown = false;
+        }
+        return false;
+    },
+
+    _onMouseMove: function(evt) {
+        if (this.mouseDown) {
+            var pixelOffset = evt.pageX - this.container.offset().left;
+            this._setPosition(pixelOffset / this.width * this.duration);
+            return false;
+        }
+    },
+
+    _onMouseUp: function(evt) {
+        if (this.mouseDown) {
+            this.mouseDown = false;
+            this.fire('move', {offset: this.pointerPos});
+            return false;
+        }
+    },
+
+    _observeMouseEvents: function(element) {
+        element
+            .bind('click dragstart', function() {return false;})
+            .bind('mousedown', this.attachWithEvent(this._onMouseDown))
+            .bind('mousemove', this.attachWithEvent(this._onMouseMove))
+            .bind('mouseup', this.attachWithEvent(this._onMouseUp));
+        $J(document)
+            .bind('mousemove', this.attachWithEvent(this._onMouseMove));
+    },
+
+    _drawMarker: function(marker, index) {
+        if (marker.offset < 0)
+            marker.offset = 0;
+        else if (marker.offset > this.duration)
+            marker.offset = this.duration;
+            
+        pixelOffset = marker.offset / this.duration * this.width;
+
+        m = new $N.Marker({
+            rulerLayout: this.layout.get(0),
+            viewer: this.waveContainer,
+            fontSize: this.cfg.fontSize,
+            className: 'marker',
+            id: marker.id,
+            tooltip: 'Move marker'
+        });
+        m.observe('move', this.attach(this._onMarkerMove))
+            .setText(index + 1)
+            .move(pixelOffset)
+            .show();
+        return m;
+    },
+
+    _onMarkerMove: function(e, data) {
+        if (data.finish) {
+            var offset = data.offset / this.width * this.duration;
+            this.fire('markermove', {id: data.id, offset: offset});
+        }
+    },
+
+    _onMapAdd: function(e, data) {
+        this.markers.push(this._drawMarker(data.marker, data.index));
+    },
+
+
+    _onMapRemove: function(e, data) {
+        $J(this.markers).each(this.attach(function(i, m) {
+            if (m.id == data.marker.id) {
+                m.clear();
+                this.markers.splice(i, 1);
+            }
+        }));
+    },
+
+    _onMapIndexChange: function(e, data) {
+        $J(this.markers).each(this.attach(function(i, m) {
+            if (m.id == data.marker.id) {
+                m.setText(data.index + 1);
+                return false;
+            }
+        }));
+    },
+
+    _onDoubleClick: function(evt) {
+        if (this.cfg.map) {
+            var offset = (evt.pageX - this.container.offset().left) 
+                / this.width * this.duration;
+            this.fire('markeradd', {offset: offset});
+        }
+    },
+
+    _onSoundProviderUpdate: function(e) {
+        this.setDuration(this.cfg.soundProvider.getDuration());
+        this.setPosition(this.cfg.soundProvider.getPosition());
+        this.setBuffering(this.cfg.soundProvider.isBuffering() && this.cfg.soundProvider.isPlaying());
+    }
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/soundprovider.js b/timeside/ui/src/soundprovider.js
new file mode 100644 (file)
index 0000000..b8ac149
--- /dev/null
@@ -0,0 +1,149 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N) {
+
+$N.Class.create("SoundProvider", $N.Core, {
+    sound: null,
+    timer: null,
+    buggyPosition: null,
+    isDurationForced: false,
+    state: {
+        position: null,
+        duration: null,
+        playing: false,
+        buffering: false
+    },
+    lastState: null,
+
+    initialize: function($super, cfg) {
+        $super();
+        this.configure(cfg, {
+            source: null,
+            duration: null
+        });
+        this.sound = this.cfg.source;
+        if (this.cfg.duration) {
+            this.forceDuration(this.cfg.duration);
+        }
+        this.state.position = 0;
+        this.update = this.attach(this._update);
+        this.timer = setInterval(this.update, 43);
+    },
+
+    free: function($super) {
+        this.sound = null;
+        $super();
+    },
+
+    play: function() {
+        if (this.sound) {
+            if (!this.sound.playState) {
+                this.sound.play();
+            } else if (this.sound.paused) {
+                this.sound.resume();
+            }
+        }
+        return this;
+    },
+
+    pause: function() {
+        if (this.sound)
+            this.sound.pause();
+        return this;
+    },
+
+    seek: function(offset) {
+        if (this.sound) {
+            this.sound.setPosition(offset * 1000);
+            if (!this.state.playing) {
+                this.buggyPosition = this.sound.position / 1000;
+                this.state.position = offset;
+            }
+        }
+        return this;
+    },
+
+    isPlaying: function() {
+        return this.state.playing;
+    },
+
+    getPosition: function() {
+        if (this.state.position == null)
+            this._retrieveState();
+        return this.state.position;
+    },
+
+    getDuration: function() {
+        if (this.state.duration == null)
+            this._retrieveState();
+        return this.state.duration;
+    },
+
+    forceDuration: function(duration) {
+        this.state.duration = duration;
+        this.isDurationForced = true;
+    },
+
+    isBuffering: function() {
+        return this.state.buffering;
+    },
+
+    _retrieveState: function() {
+        if (this.sound) {
+            this.state.playing = (this.sound.playState && !this.sound.paused);
+            if (this.state.playing) {
+                var position = this.sound.position / 1000;
+                if (position != this.buggyPosition) {
+                    this.state.position = position;
+                    this.buggyPosition = null;
+                }
+            }
+            if (!this.isDurationForced) {
+                if (this.sound.readyState == 1) {
+                    this.state.duration = this.sound.durationEstimate / 1000;
+                } else {
+                    this.state.duration = this.sound.duration / 1000;
+                }
+            }
+            this.state.buffering = (this.sound.readyState == 1 && this.state.position > this.sound.duration / 1000);
+        }
+    },
+
+    _update: function() {
+        this._retrieveState();
+        var updated = false;
+        if (this.lastState) {
+            for (k in this.state) {
+                if (this.state[k] != this.lastState[k]) {
+                    updated = true;
+                    break;
+                }
+            }
+        } else {
+            this.lastState = {};
+            updated = true;
+        }
+        if (updated) {
+            for (k in this.state) {
+                this.lastState[k] = this.state[k];
+            }
+            this.fire('update');
+        }
+    },
+
+    setSource: function(source) {
+        this.debug("setting source");
+        this.sound = source;
+        return this;
+    }
+
+});
+
+$N.notifyScriptLoad();
+
+});
diff --git a/timeside/ui/src/timeside.js b/timeside/ui/src/timeside.js
new file mode 100644 (file)
index 0000000..95b0f51
--- /dev/null
@@ -0,0 +1,124 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+var TimeSide = function() { 
+    if (arguments[0]) {
+        var toolkit = null;
+        if (typeof jQuery != 'undefined')
+            toolkit = jQuery;
+        (arguments[0])(TimeSide, toolkit)
+    }
+};
+
+TimeSide(function($N, $J) {
+
+$N.isDomLoaded = false;
+$N.isLoaded = false;
+$N.isLoading = false;
+$N.onLoadCallbacks = [];
+$N.cssPrefix = 'ts-';
+$N.debugging = false;
+
+$J(document).ready(function () {
+    $N.isDomLoaded = true;
+});
+
+$N.domReady = function(callback) {
+    // simply calling jQuery.ready() *after* the DOM is loaded doesn't work reliably,
+    // at least with jQuery 1.2.6
+    if ($N.isDomLoaded) 
+        callback();
+    else
+        $J(document).ready(callback);
+}
+
+$N.instances = [];
+$N.registerInstance = function(obj) {
+    $N.instances.push(obj);
+}
+
+$N.free = function() {
+    $J($N.instances).each(function(i, obj) {
+        obj.free();
+    });
+}
+
+$J(window).unload($N.free);
+
+$N.loadScriptsNum = 0;
+$N.loadScriptsCallback = null;
+$N.loadScripts = function(root, scripts, callback) {
+    if ($N.loadScriptsCallback) {
+        throw "Timeside loader error: concurrent script loading";
+    }
+
+    $N.loadScriptsNum = scripts.length;
+    $N.loadScriptsCallback = callback;
+
+    var head= document.getElementsByTagName('head')[0];
+    for (i = 0; i < scripts.length; i++) {
+
+        var script = document.createElement('script');
+        script.type = 'text/javascript';
+        var debug = $N.debugging ? '?rand=' + Math.random() : '';
+        script.src = root + scripts[i] + debug;
+        head.appendChild(script);
+    }
+}
+
+$N.notifyScriptLoad = function() {
+    if (--$N.loadScriptsNum == 0 && $N.loadScriptsCallback) {
+        var callback = $N.loadScriptsCallback;
+        $N.loadScriptsCallback = null;
+        callback();
+    }
+}
+
+$N.debug = function(state) {
+    $N.debugging = state;
+}
+
+$N.load = function(callback) {
+    $N.domReady(function() {
+        if ($N.isLoaded) {
+            if (callback) 
+                callback();
+        } else {
+            if (callback) 
+                $N.onLoadCallbacks.push(callback);
+
+            if (!$N.isLoading) {
+                $N.isLoading = true;
+                var re = /(.*)timeside.js/;
+                var root = '';
+                $J('head script').each(function(i, e) {
+                    if (match = re.exec(e.src)) {
+                        root = match[1];
+                    }
+                });
+
+                $N.loadScripts(root, ['core.js'], function() {
+                    $N.loadScripts(root, ['util.js'], function() {
+                        var scripts = ['controller.js', 'marker.js', 'markerlist.js', 
+                                       'markermap.js', 'player.js', 'ruler.js', 
+                                       'soundprovider.js'];
+                                                       
+                        $N.loadScripts(root, scripts, function() {
+                            $N.isLoaded = true;
+                            $N.isLoading = false;
+                            $J($N.onLoadCallbacks).each(function(i, callback) {
+                                callback();
+                            });
+                        });
+                    });
+                });
+            }
+        }
+    });
+}
+
+});
diff --git a/timeside/ui/src/util.js b/timeside/ui/src/util.js
new file mode 100755 (executable)
index 0000000..94c42dc
--- /dev/null
@@ -0,0 +1,83 @@
+/**
+ * TimeSide - Web Audio Components
+ * Copyright (c) 2008-2009 Samalyse
+ * Author: Olivier Guilyardi <olivier samalyse com>
+ * License: GNU General Public License version 2.0
+ */
+
+TimeSide(function($N, $J) {
+
+$N.Util = {
+    _loadChild: function(container, tag, className, index, contents) {
+        var p = $N.cssPrefix;
+        var element = container.find('.' + p + className);
+        if (!element.length) {
+            element = $J(document.createElement(tag)).addClass(p + className);
+            if (contents[className]) {
+                element.text(contents[className]);
+            }
+            var children = container.children();
+            if (index < children.length) {
+                children.eq(index).before(element);
+            } else {
+                container.append(element);
+            }
+        }
+        return element;
+    },
+
+    _loadUI: function(container, skeleton, contents) {
+        var i = 0;
+        var elements = {};
+        with ($N.Util) {
+            if (skeleton[0]) {
+                $J(skeleton).each((function(i, selector) {
+                    var s = selector.split('.');
+                    elements[$N.Util.camelize(s[1])] = _loadChild(container, s[0], s[1], i++, contents);
+                }));
+            } else {
+                for (key in skeleton) {
+                    var s = key.split('.');
+                    var e = _loadChild(container, s[0], s[1], i++, contents);
+                    elements[$N.Util.camelize(s[1])] = e;
+                    $N.extend(elements, _loadUI(e, skeleton[key], contents));
+                    
+                }
+            }
+        }
+        return elements;
+    },
+
+    loadUI: function(container, skeleton, contents) {
+        return $N.Util._loadUI($J(container), skeleton, contents);
+    },
+
+    makeTimeLabel: function(offset) {
+        var minutes = Math.floor(offset / 60);
+        if (minutes < 10)
+            minutes = '0' + minutes;
+        var seconds = Math.floor(offset % 60);
+        if (seconds < 10)
+            seconds = '0' + seconds;
+        return minutes + ':' + seconds;
+    },
+
+    camelize: function(str) {
+        var parts = str.split('-'), len = parts.length;
+        if (len == 1) return parts[0];
+
+        var camelized = str.charAt(0) == '-'
+          ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
+          : parts[0];
+
+        for (var i = 1; i < len; i++)
+          camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
+
+        return camelized;
+    }
+
+}
+
+$N.notifyScriptLoad();
+
+});
diff --git a/tools/grapher_scheme.py b/tools/grapher_scheme.py
deleted file mode 100644 (file)
index 4549767..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-# -*- coding: utf-8 -*-
-
-class GrapherScheme:
-
-    def __init__(self):
-
-        self.color_scheme = {
-            'waveform': [
-                        (50,0,200), (0,220,80), (255,224,0), (255,0,0)
-                        ],
-            'spectrogram': [
-                        (0, 0, 0), (58/4,68/4,65/4), (80/2,100/2,153/2), (90,180,100), (224,224,44), (255,60,30), (255,255,255)
-                           ]}
-
-        self.width = 2048
-        self.height = 128
-        self.bg_color = (255,255,255)
-        self.force = True
-
diff --git a/tools/waveform_batch.py b/tools/waveform_batch.py
deleted file mode 100644 (file)
index bba5036..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2009-2010 Guillaume Pellerin <yomguy@parisson.com>
-
-# This file is part of TimeSide.
-
-# TimeSide 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 2 of the License, or
-# (at your option) any later version.
-
-# TimeSide 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 TimeSide.  If not, see <http://www.gnu.org/licenses/>.
-
-# Author: Guillaume Pellerin <yomguy@parisson.com>
-
-version = '0.1-beta'
-
-import os
-import sys
-from timeside.core import *
-from timeside.decoder import *
-from timeside.grapher import *
-from grapher_scheme import *
-
-
-class Media2Waveform(object):
-
-    def __init__(self, media_dir, img_dir):
-        self.root_dir = media_dir
-        self.img_dir = img_dir
-        self.scheme = GrapherScheme()
-        self.width = self.scheme.width
-        self.height = self.scheme.height
-        self.bg_color = self.scheme.bg_color
-        self.color_scheme = self.scheme.color_scheme
-        self.force = self.scheme.force
-
-        self.media_list = self.get_media_list()
-        if not os.path.exists(self.img_dir):
-            os.mkdir(self.img_dir)
-        self.path_dict = self.get_path_dict()
-
-    def get_media_list(self):
-        media_list = []
-        for root, dirs, files in os.walk(self.root_dir):
-            if root:
-                for file in files:
-                    ext = file.split('.')[-1]
-                    if ext == 'mp3' or ext == 'MP3':
-                        media_list.append(root+os.sep+file)
-        return media_list
-
-    def get_path_dict(self):
-        path_dict = {}
-        for media in self.media_list:
-            name = os.path.splitext(media)
-            name = name[0].split(os.sep)[-1]
-            path_dict[media] = self.img_dir + os.sep + name + '.png'
-        return path_dict
-
-    def process(self):
-        for source, image in self.path_dict.iteritems():
-            if not os.path.exists(image) or self.force:
-                print 'Rendering ', source, ' to ', image, '...'
-                audio = os.path.join(os.path.dirname(__file__), source)
-                decoder  = FileDecoder(audio)
-                waveform = Waveform(width=self.width, height=self.height, output=image,
-                                            bg_color=self.bg_color, color_scheme=self.color_scheme)
-                (decoder | waveform).run()
-                print 'frames per pixel = ', waveform.graph.samples_per_pixel
-                waveform.render()
-
-
-if __name__ == '__main__':
-    if len(sys.argv) <= 2:
-        print """
-        Usage : python waveform_batch.py /path/to/media_dir /path/to/img_dir
-
-        Dependencies : timeside, python, python-numpy, python-gst0.10, gstreamer0.10-plugins-base
-        See http://code.google.com/p/timeside/ for more information.
-        """
-    else:
-        media_dir = sys.argv[-2]
-        img_dir = sys.argv[-1]
-        m = Media2Waveform(media_dir, img_dir)
-        m.process()
diff --git a/ui/README b/ui/README
deleted file mode 100644 (file)
index 0f9d21d..0000000
--- a/ui/README
+++ /dev/null
@@ -1,20 +0,0 @@
-===============================
-TimeSide - Web Audio Components
-===============================
-
-TimeSide UI Dependencies
-========================
-
-* SoundManager 2 >= 2.91 : http://www.schillmania.com/projects/soundmanager2
-* jQuery => 1.2.6 : http://www.jquery.com
-* jsGraphics => 3.03 http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm
-
-Licensing
-=========
-
-Copyright (c) 2008-2009 Samalyse
-Author: Olivier Guilyardi <olivier samalyse com>
-
-TimeSide is released under the terms of the GNU General Public License 
-version 2. Please see the LICENSE file for details.
-
diff --git a/ui/css/timeside.css b/ui/css/timeside.css
deleted file mode 100755 (executable)
index cadc79a..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/* FIXME: These CSS styles are essential and non intrusive. They should be 
- * dynamically assigned in javascript, and this file removed. */
-
-.ts-player .ts-ruler .ts-section .ts-canvas {
-    position: relative;
-}
-
-.ts-player .ts-wave {
-    position: relative;
-    clear: both;
-    overflow: hidden;
-}
-
-.ts-player .ts-wave .ts-image-container {
-    position: relative;
-}
-
-.ts-player .ts-wave .ts-image {
-    position: absolute;
-    left: 0;
-    clear: both;
-}
-
-.ts-player .ts-wave .ts-image-canvas {
-    position: absolute;
-    z-index: 100;
-    overflow: hidden;
-}
-
diff --git a/ui/demo/index.html b/ui/demo/index.html
deleted file mode 100755 (executable)
index f3977e2..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-<html>
-
-<head>
-<link type="text/css" href="../css/timeside.css" rel="stylesheet" media="screen" />
-<link type="text/css" href="../skins/lab/style.css" rel="stylesheet" media="screen" />
-<style type="text/css">
-.ts-player { width: 360px; }
-</style>
-<!--
-<script type="text/javascript" src="../lib/firebug-lite-compressed.js"></script> 
--->
-<script type="text/javascript">
-function get_globals() {
-    var g = [];
-    for (var v in window) 
-        g = g.concat([v]);
-    return g;
-}
-function diff_array(a1, a2) {
-    var diff = [];
-    var i, ii = a2.length;
-    for (i = 0; i < ii; i++) {
-        if (a1.indexOf(a2[i]) == -1) {
-            diff = diff.concat([a2[i]]);
-        }
-    }
-    return diff;
-}
-
-function log_globals(label) {
-    var g = get_globals();
-    if (log_globals.cache && label && typeof console != 'undefined') {
-        console.log(label + ':');
-        console.log(diff_array(log_globals.cache, g));
-    }
-    log_globals.cache = g;
-}
-</script>
-<script>log_globals(false);</script>
-<script type="text/javascript" src="../lib/jquery.js"></script> 
-<script type="text/javascript">
-jQuery.noConflict();
-jQuery(window).bind('load', function() {if (jQuery.browser.mozilla) jQuery('#Firebug').hide()});
-log_globals('jquery globals');
-</script>
-
-<!--
-<script type="text/javascript" src="jquery-ui.js"></script> 
--->
-<script>log_globals('jquery ui globals');</script>
-<script type="text/javascript" src="../lib/wz_jsgraphics.js"></script> 
-<script>log_globals('jsgraphics globals');</script>
-<script type="text/javascript" src="../lib/soundmanager2.js"></script> 
-<script>log_globals('soundmanager globals');</script>
-<script type="text/javascript" src="../src/timeside.js"></script> 
-
-<script type="text/javascript">
-var sound = null;
-var map;
-var provider = null;
-var player = null;
-
-function shiftSize(delta) {
-    jQuery('#player').width(jQuery('#player').width() + delta);
-    player.resize();
-}
-
-function fullSize() {
-    jQuery('#player').css({width: 'auto'});
-    player.resize();
-}
-
-TimeSide.debug(true);
-TimeSide.load(function() {
-    map = new TimeSide.MarkerMap();
-    provider = new TimeSide.SoundProvider({source: sound});
-    player = new TimeSide.Player('#player', {
-        image: 'waveform.png'
-    });
-    controller = new TimeSide.Controller({
-        player: player,
-        soundProvider: provider, 
-        map: map
-    });
-
-    jQuery('#skinner').get(0).className=jQuery('#skin').get(0).value; player.resize(); 
-});
-if (typeof soundManager != 'undefined') {
-    soundManager.url = '../lib/';
-    soundManager.flashVersion = 9;
-    soundManager.consoleOnly = true;
-    if (typeof console == 'undefined') {
-        soundManager.debugMode = false;
-    }
-
-    soundManager.onload = function() {
-        sound = soundManager.createSound({
-            id: 'test',
-            url: 'http://ns22997.ovh.net/tmp/crem.mp3'
-            //autoLoad: true
-        });
-
-        if (provider) {
-            provider.setSource(sound);
-        } else {
-            TimeSide.load(function () {
-                provider.setSource(sound);
-            });
-        }
-    }        
-}    
-
-</script> 
-
-</head>
-
-<body>
-
-<h2>TimeSide Player</h2>
-
-<div id="skinner" class="">
-  <div id="player" class="ts-player">
-  </div>  
-</div>
-
-<p>
-<!--
-  <button onclick="setup()">Setup</button> 
--->  
-  <button onclick="shiftSize(-10)">Smaller</button> 
-  <button onclick="shiftSize(10)">Bigger</button>
-  <button onclick="fullSize()">Full size</button>
-  <br />
-  Skin:
-  <select id="skin" onchange="jQuery('#skinner').get(0).className=this.value; player.resize(); ">
-    <option selected value="">None</option>
-    <option value="ts-skin-lab">Lab</option>
-  </select>
-</p>
-</body>
-</html>
diff --git a/ui/demo/waveform.png b/ui/demo/waveform.png
deleted file mode 100755 (executable)
index 75e3f9d..0000000
Binary files a/ui/demo/waveform.png and /dev/null differ
diff --git a/ui/lib/firebug-lite-compressed.js b/ui/lib/firebug-lite-compressed.js
deleted file mode 100644 (file)
index df2601c..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-(function(_scope){_scope.pi=Object(3.14159265358979323846);var pi=_scope.pi;pi.version=1.0;pi.env={ie:/MSIE/i.test(navigator.userAgent),ie6:/MSIE 6/i.test(navigator.userAgent),ie7:/MSIE 7/i.test(navigator.userAgent),ie8:/MSIE 8/i.test(navigator.userAgent),firefox:/Firefox/i.test(navigator.userAgent),opera:/Opera/i.test(navigator.userAgent),webkit:/Webkit/i.test(navigator.userAgent)};pi.util={IsArray:function(_object){return _object&&_object!=window&&(_object instanceof Array||(typeof _object.length=="number"&&typeof _object.item=="function"))},IsHash:function(_object){return _object&&typeof _object=="object"&&(_object==window||_object instanceof Object)&&!_object.nodeName&&!pi.util.IsArray(_object)},DOMContentLoaded:[],AddEvent:function(_element,_eventName,_fn,_useCapture){_element[pi.env.ie.toggle("attachEvent","addEventListener")](pi.env.ie.toggle("on","")+_eventName,_fn,_useCapture||false);return pi.util.AddEvent.curry(this,_element)},RemoveEvent:function(_element,_eventName,_fn,_useCapture){return _element[pi.env.ie.toggle("detachEvent","removeEventListener")](pi.env.ie.toggle("on","")+_eventName,_fn,_useCapture||false)},GetWindowSize:function(){return{height:pi.env.ie?Math.max(document.documentElement.clientHeight,document.body.clientHeight):window.innerHeight,width:pi.env.ie?Math.max(document.documentElement.clientWidth,document.body.clientWidth):window.innerWidth}},Include:function(_url,_callback){var script=new pi.element("script").attribute.set("src",_url),callback=_callback||new Function,done=false,head=pi.get.byTag("head")[0];script.environment.getElement().onload=script.environment.getElement().onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){callback.call(this);done=true;head.removeChild(script.environment.getElement())}};script.insert(head)},Element:{addClass:function(_element,_class){if(!pi.util.Element.hasClass(_element,_class))pi.util.Element.setClass(_element,pi.util.Element.getClass(_element)+" "+_class)},getClass:function(_element){return _element.getAttribute(pi.env.ie.toggle("className","class"))||""},hasClass:function(_element,_class){return pi.util.Element.getClass(_element).split(" ").indexOf(_class)>-1},removeClass:function(_element,_class){if(pi.util.Element.hasClass(_element,_class))pi.util.Element.setClass(_element,pi.util.Element.getClass(_element,_class).split(" ").removeValue(_class).join(" "))},setClass:function(_element,_value){_element.setAttribute(pi.env.ie.toggle("className","class"),_value)},toggleClass:function(){if(pi.util.Element.hasClass.apply(this,arguments))pi.util.Element.removeClass.apply(this,arguments);else pi.util.Element.addClass.apply(this,arguments)},getOpacity:function(_styleObject){var styleObject=_styleObject;if(!pi.env.ie)return styleObject["opacity"];var alpha=styleObject["filter"].match(/opacity\=(\d+)/i);return alpha?alpha[1]/100:1},setOpacity:function(_element,_value){if(!pi.env.ie)return pi.util.Element.addStyle(_element,{"opacity":_value});_value*=100;pi.util.Element.addStyle(_element,{"filter":"alpha(opacity="+_value+")"});return this._parent_},getPosition:function(_element){var parent=_element,offsetLeft=0,offsetTop=0,view=pi.util.Element.getView(_element);while(parent&&parent!=document.body&&parent!=document.firstChild){offsetLeft+=parseInt(parent.offsetLeft);offsetTop+=parseInt(parent.offsetTop);parent=parent.offsetParent};return{"bottom":view["bottom"],"left":view["left"],"marginTop":view["marginTop"],"marginLeft":view["marginLeft"],"offsetLeft":offsetLeft,"offsetTop":offsetTop,"position":view["position"],"right":view["right"],"top":view["top"],"z-index":view["zIndex"]}},getSize:function(_element){var view=pi.util.Element.getView(_element);return{"height":view["height"],"offsetHeight":_element.offsetHeight,"offsetWidth":_element.offsetWidth,"width":view["width"]}},addStyle:function(_element,_style){for(var key in _style){key=key=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):key;if(key=="opacity"&&pi.env.ie){pi.util.Element.setOpacity(_element,_style[key]);continue}_element.style[key]=_style[key]}},getStyle:function(_element,_property){_property=_property=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):_property;if(_property=="opacity"&&pi.env.ie)return pi.util.Element.getOpacity(_element.style);return typeof _property=="string"?_element.style[_property]:_element.style},getView:function(_element,_property){var view=document.defaultView?document.defaultView.getComputedStyle(_element,null):_element.currentStyle;_property=_property=="float"?pi.env.ie.toggle("styleFloat","cssFloat"):_property;if(_property=="opacity"&&pi.env.ie)return pi.util.Element.getOpacity(_element,view);return typeof _property=="string"?view[_property]:view}},CloneObject:function(_object,_fn){var tmp={};for(var key in _object){if(pi.util.IsArray(_object[key])){tmp[key]=Array.prototype.clone.apply(_object[key])}else if(pi.util.IsHash(_object[key])){tmp[key]=pi.util.CloneObject(_object[key]);if(_fn)_fn.call(tmp,key,_object)}else tmp[key]=_object[key]}return tmp},MergeObjects:function(_object,_source){for(var key in _source){var value=_source[key];if(pi.util.IsArray(_source[key])){if(pi.util.IsArray(_object[key])){Array.prototype.push.apply(_source[key],_object[key])}else value=_source[key].clone()}else if(pi.util.IsHash(_source[key])){if(pi.util.IsHash(_object[key])){value=pi.util.MergeObjects(_object[key],_source[key])}else{value=pi.util.CloneObject(_source[key])}}_object[key]=value};return _object}};pi.get=function(){return document.getElementById(arguments[0])};pi.get.byTag=function(){return document.getElementsByTagName(arguments[0])};pi.get.byClass=function(){return document.getElementsByClassName.apply(document,arguments)};pi.base=function(){this.body={};this.constructor=null;this.build=function(_skipClonning){var base=this,skipClonning=_skipClonning||false,_private={},fn=function(){var _p=pi.util.CloneObject(_private);if(!skipClonning){for(var key in this){if(pi.util.IsArray(this[key])){this[key]=Array.prototype.clone.apply(this[key])}else if(pi.util.IsHash(this[key])){this[key]=pi.util.CloneObject(this[key],function(_key,_object){this[_key]._parent_=this});this[key]._parent_=this}}};base.createAccessors(_p,this);if(base.constructor)return base.constructor.apply(this,arguments);return this};this.movePrivateMembers(this.body,_private);if(this.constructor){fn["$Constructor"]=this.constructor}fn.prototype=this.body;return fn};this.createAccessors=function(_p,_branch){var getter=function(_property){return this[_property]},setter=function(_property,_value){this[_property]=_value;return _branch._parent_||_branch};for(var name in _p){var isPrivate=name.substring(0,1)=="_",title=name.substring(1,2).toUpperCase()+name.substring(2);if(isPrivate){_branch["get"+title]=getter.curry(_p,name);_branch["set"+title]=setter.curry(_p,name)}else if(pi.util.IsHash(_p[name])){if(!_branch[name])_branch[name]={};this.createAccessors(_p[name],_branch[name])}}};this.movePrivateMembers=function(_object,_branch){for(var name in _object){var isPrivate=name.substring(0,1)=="_";if(isPrivate){_branch[name]=_object[name];delete _object[name]}else if(pi.util.IsHash(_object[name])){_branch[name]={};this.movePrivateMembers(_object[name],_branch[name])}}}};Function.prototype.extend=function(_prototype,_skipClonning){var object=new pi.base,superClass=this;if(_prototype["$Constructor"]){object.constructor=_prototype["$Constructor"];delete _prototype["$Constructor"]};object.body=superClass==pi.base?_prototype:pi.util.MergeObjects(_prototype,superClass.prototype,2);object.constructor=object.constructor||function(){if(superClass!=pi.base)superClass.apply(this,arguments)};return object.build(_skipClonning)};Function.prototype.curry=function(_scope){var fn=this,scope=_scope||window,args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(scope,args.concat(Array.prototype.slice.call(arguments,0)))}};pi.element=pi.base.extend({"$Constructor":function(_tag){this.environment.setElement(document.createElement(_tag||"DIV"));this.environment.getElement().pi=this;return this},"clean":function(){var childs=this.child.get();while(childs.length){childs[0].parentNode.removeChild(childs[0])}},"clone":function(_deep){return this.environment.getElement().cloneNode(_deep)},"insert":function(_element){_element=_element.environment?_element.environment.getElement():_element;_element.appendChild(this.environment.getElement());return this},"insertAfter":function(_referenceElement){_referenceElement=_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement;_referenceElement.nextSibling?this.insertBefore(_referenceElement.nextSibling):this.insert(_referenceElement.parentNode);return this},"insertBefore":function(_referenceElement){_referenceElement=_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement;_referenceElement.parentNode.insertBefore(this.environment.getElement(),_referenceElement);return this},"query":function(_expression,_resultType,namespaceResolver,_result){return pi.xpath(_expression,_resultType||"ORDERED_NODE_SNAPSHOT_TYPE",this.environment.getElement(),_namespaceResolver,_result)},"remove":function(){this.environment.getParent().removeChild(this.environment.getElement())},"update":function(_value){["TEXTAREA","INPUT"].indexOf(this.environment.getName())>-1?(this.environment.getElement().value=_value):(this.environment.getElement().innerHTML=_value);return this},"attribute":{"getAll":function(_name){return this._parent_.environment.getElement().attributes},"clear":function(_name){this.set(_name,"");return this._parent_},"get":function(_name){return this._parent_.environment.getElement().getAttribute(_name)},"has":function(_name){return pi.env.ie?(this.get(_name)!=null):this._parent_.environment.getElement().hasAttribute(_name)},"remove":function(_name){this._parent_.environment.getElement().removeAttribute(_name);return this._parent_},"set":function(_name,_value){this._parent_.environment.getElement().setAttribute(_name,_value);return this._parent_},"addClass":function(_classes){for(var i=0;i<arguments.length;i++){pi.util.Element.addClass(this._parent_.environment.getElement(),arguments[i])};return this._parent_},"clearClass":function(){this.setClass("");this._parent_},"getClass":function(){return pi.util.Element.getClass(this._parent_.environment.getElement())},"hasClass":function(_class){return pi.util.Element.hasClass(this._parent_.environment.getElement(),_class)},"setClass":function(_value){return pi.util.Element.setClass(this._parent_.environment.getElement(),_value)},"removeClass":function(_class){pi.util.Element.removeClass(this._parent_.environment.getElement(),_class);return this._parent_},"toggleClass":function(_class){pi.util.Element.toggleClass(this._parent_.environment.getElement(),_class)}},"child":{"get":function(){return this._parent_.environment.getElement().childNodes},"add":function(_elements){for(var i=0;i<arguments.length;i++){var el=arguments[i];this._parent_.environment.getElement().appendChild(el.environment?el.environment.getElement():el)}return this._parent_},"addAfter":function(_element,_referenceElement){this.addBefore(_element.environment?_element.environment.getElement():_element,(_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement).nextSibling);return this._parent_},"addBefore":function(_element,_referenceElement){this._parent_.environment.getElement().insertBefore(_element.environment?_element.environment.getElement():_element,_referenceElement.environment?_referenceElement.environment.getElement():_referenceElement);return this._parent_},"query":function(_tag,_attributeName,_attributeValue){return this._parent_.query("{0}{1}".format((_tag?"{0}".format(_tag):"/*"),_attributeName||_attributeValue?"[contains(concat(' ', @{0}, ' '),' {1} ')]".format(_attributeName||"",_attributeValue||""):""))},"remove":function(_element){this._parent_.environment.getElement().removeChild(_element.environment?_element.environment.getElement():_element)}},"environment":{"_element":null,"getParent":function(){return this.getElement().parentNode},"getPosition":function(){return pi.util.Element.getPosition(this.getElement())},"getSize":function(){return pi.util.Element.getSize(this.getElement())},"addStyle":function(_styleObject){pi.util.Element.addStyle(this.getElement(),_styleObject);return this._parent_},"getStyle":function(_property){return pi.util.Element.getStyle(_property)},"getName":function(){return this.getElement().nodeName},"getType":function(){return this.getElement().nodeType},"getView":function(_property){return pi.util.Element.getView(this.getElement(),_property)}},"event":{"addListener":function(_event,_fn,_useCapture){pi.util.AddEvent(this._parent_.environment.getElement(),_event,_fn,_useCapture);return this._parent_},"removeListener":function(_event,_fn,_useCapture){pi.util.RemoveEvent(this._parent_.environment.getElement(),_event,_fn,_useCapture);return this._parent_}}});pi.xhr=new pi.base;pi.xhr.constructor=function(){var api;if(!window.XMLHttpRequest){var names=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];for(var i=0;i<names.length;i++){try{this.environment.setApi(new ActiveXObject(names[i]));break}catch(e){continue}}}else this.environment.setApi(new XMLHttpRequest());this.environment.getApi().onreadystatechange=this.event.readystatechange.curry(this);return this};pi.xhr.body={"abort":function(){this.environment.getApi().abort()},"send":function(){var url=this.environment.getUrl(),data=this.environment.getData(),dataUrl="";for(var key in data)dataUrl+="{0}={1}&".format(key,data[key]);if(this.environment.getType()=="GET")url+=(url.search("\\?")==-1?"?":"&")+"{0}".format(dataUrl);this.environment.getApi().open(this.environment.getType(),url,this.environment.getAsync());for(var key in this.environment.getHeader())this.environment.getApi().setRequestHeader(key,this.environment.getHeader()[key]);this.environment.getApi().send(this.environment.getType()=="GET"?"":dataUrl)}};pi.xhr.body.environment={"_async":true,"_api":null,"_cache":true,"_callback":[],"_channel":null,"_data":{},"_header":{},"_mimeType":null,"_multipart":false,"_type":"GET","_timeout":0,"_url":"","addCallback":function(_options,_fn){this.getCallback().push({"fn":_fn,"options":_options})},"addHeader":function(_key,_value){this.getHeader()[_key]=_value},"addData":function(_key,_value){this.getData()[_key]=_value},"changeCache":function(_value){if(_value==false){this.addData("forceCache",Math.round(Math.random()*10000))}this.setCache(_value)},"changeType":function(_value){if(_value=="POST"){this.addHeader("Content-Type","application/x-www-form-urlencoded")}this.setType(_value)}};pi.xhr.body.event={"readystatechange":function(){var readyState=this.environment.getApi().readyState;var callback=this.environment.getCallback();for(var i=0;i<callback.length;i++){if(callback[i].options.readyState.indexOf(readyState)>-1)callback[i].fn.apply(this)}}};pi.xhr=pi.xhr.build();pi.xhr.get=function(_url,_returnPiObject){var request=new pi.xhr();request.environment.setAsync(false);request.environment.setUrl(_url);request.send();return _returnPiObject?request:request.environment.getApi()};pi.xpath=function(_expression,_resultType,_contextNode,_namespaceResolver,_result){var contextNode=_contextNode||document,expression=_expression||"",namespaceResolver=_namespaceResolver||null,result=_result||null,resultType=_resultType||"ANY_TYPE";return document.evaluate(expression,contextNode,namespaceResolver,XPathResult[resultType],result)};Array.prototype.clone=function(){var tmp=[];Array.prototype.push.apply(tmp,this);tmp.forEach(function(item,index,object){if(item instanceof Array)object[index]=object[index].clone()});return tmp};Array.prototype.count=function(_value){var count=0;this.forEach(function(){count+=Number(arguments[0]==_value)});return count};Array.prototype.forEach=Array.prototype.forEach||function(_function){for(var i=0;i<this.length;i++)_function.apply(this,[this[i],i,this])};Array.prototype.getLastItem=function(){return this[this.length-1]};Array.prototype.indexOf=Array.prototype.indexOf||function(_value){var index=-1;for(var i=0;i<this.length;i++)if(this[i]==_value){index=i;break}return index};Array.prototype.remove=function(_index){var array=this.slice(0,_index);Array.prototype.push.apply(array,this.slice(_index+1));return array};Array.prototype.removeValue=function(_value){return this.remove(this.indexOf(_value))};Boolean.prototype.toggle=function(){return this==true?arguments[0]:arguments[1]};Number.prototype.base=function(_system){var remain=this%_system;if(this==remain)return String.fromCharCode(this+(this>9?87:48));return((this-remain)/_system).base(_system)+String.fromCharCode(remain+(remain>9?87:48))};Number.prototype.decimal=function(_system){var result=0,digit=String(this).split("");for(var i=0;i<digit.length;i++){digit[i]=parseInt((digit[i].charCodeAt(0)>58)?digit[i].charCodeAt(0)-87:digit[i]);result+=digit[i]*(Math.pow(_system,digit.length-1-i))}return result};Number.prototype.range=function(_pattern){for(var value=String(this),isFloat=/\./i.test(value),i=isFloat.toggle(parseInt(value.split(".")[0]),0),end=parseInt(value.split(".")[isFloat.toggle(1,0)]),array=[];i<end;i++){array.push(Boolean(_pattern)==false?i:(typeof _pattern=="function"?_pattern(i):_pattern[i]))}return array};String.prototype.escape=function(){return escape(this)};String.prototype.format=function(){var values=arguments;return this.replace(/\{(\d)\}/g,function(){return values[arguments[1]]})};String.prototype.leftpad=function(_len,_ch){var str=this;var ch=Boolean(_ch)==false?" ":_ch;while(str.length<_len)str=ch+str;return str};String.prototype.toggle=function(_value,_other){return this==_value?_value:_other};String.prototype.unicode=function(){var str="",obj=this.split("");for(var i=obj.length-1;i>=0;i--)str="\\u{0}{1}".format(String(obj[i].charCodeAt(0).base(16)).leftpad(4,"0"),str);return str};pi.util.AddEvent(pi.env.ie?window:document,pi.env.ie?"load":"DOMContentLoaded",function(){for(var i=0;i<pi.util.DOMContentLoaded.length;i++){pi.util.DOMContentLoaded[i]()}})})(window);
-var firebug={env:{"cache":{},"ctmp":[],"dIndex":"console","init":false,"ml":false,"objCn":[]},init:function(){firebug.el={};firebug.el.content={};with(firebug){document.documentElement.childNodes[0].appendChild(new pi.element("link").attribute.set("rel","stylesheet").attribute.set("href","http://firebuglite.appspot.com/firebug-lite.css").environment.getElement());el.main=new pi.element("DIV").attribute.set("id","Firebug").environment.addStyle({"width":pi.util.GetWindowSize().width+"px"}).insert(document.body);el.header=new pi.element("DIV").attribute.addClass("Header").insert(el.main);el.left={};el.left.container=new pi.element("DIV").attribute.addClass("Left").insert(el.main);el.right={};el.right.container=new pi.element("DIV").attribute.addClass("Right").insert(el.main);el.main.child.add(new pi.element("DIV").environment.addStyle({"clear":"both"}));el.button={};el.button.container=new pi.element("DIV").attribute.addClass("ButtonContainer").insert(el.header);el.button.logo=new pi.element("A").attribute.set("title","Firebug Lite").attribute.set("target","_blank").attribute.set("href","http://getfirebug.com/lite.html").update("&nbsp;").attribute.addClass("Button Logo").insert(el.button.container);el.button.inspect=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.inspector.toggle).update("Inspect").insert(el.button.container);el.button.maximize=new pi.element("A").attribute.addClass("Button Maximize").event.addListener("click",win.maximize).insert(el.button.container);el.button.minimize=new pi.element("A").attribute.addClass("Button Minimize").event.addListener("click",win.minimize).insert(el.button.container);el.button.close=new pi.element("A").attribute.addClass("Button Close").event.addListener("click",win.close).insert(el.button.container);if(pi.env.ie||pi.env.webkit){el.button.container.environment.addStyle({"paddingTop":"12px"})}el.nav={};el.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.left.container);el.nav.console=new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.navigate.curry(window,"console")).update("Console").insert(el.nav.container);el.nav.html=new pi.element("A").attribute.addClass("Tab").update("HTML").event.addListener("click",d.navigate.curry(window,"html")).insert(el.nav.container);el.nav.css=new pi.element("A").attribute.addClass("Tab").update("CSS").event.addListener("click",d.navigate.curry(window,"css")).insert(el.nav.container);el.nav.scripts=new pi.element("A").attribute.addClass("Tab").update("Script").event.addListener("click",d.navigate.curry(window,"scripts")).insert(el.nav.container);el.nav.dom=new pi.element("A").attribute.addClass("Tab").update("DOM").event.addListener("click",d.navigate.curry(window,"dom")).insert(el.nav.container);el.nav.xhr=new pi.element("A").attribute.addClass("Tab").update("XHR").event.addListener("click",d.navigate.curry(window,"xhr")).insert(el.nav.container);el.borderInspector=new pi.element("DIV").attribute.set("id","FirebugBorderInspector").event.addListener("click",listen.inspector).insert(document.body);el.bgInspector=new pi.element("DIV").attribute.set("id","FirebugBGInspector").insert(document.body);el.left.console={};el.left.console.container=new pi.element("DIV").attribute.addClass("Console").insert(el.left.container);el.left.console.mlButton=new pi.element("A").attribute.addClass("MLButton").event.addListener("click",d.console.toggleML).insert(el.left.console.container);el.left.console.monitor=new pi.element("DIV").insert(new pi.element("DIV").attribute.addClass("Monitor").insert(el.left.console.container));el.left.console.container.child.add(new pi.element("DIV").attribute.addClass("InputArrow").update(">>>"));el.left.console.input=new pi.element("INPUT").attribute.set("type","text").attribute.addClass("Input").event.addListener("keydown",listen.consoleTextbox).insert(new pi.element("DIV").attribute.addClass("InputContainer").insert(el.left.console.container));el.right.console={};el.right.console.container=new pi.element("DIV").attribute.addClass("Console Container").insert(el.right.container);el.right.console.mlButton=new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.console.container);el.right.console.input=new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.console.container);el.right.console.run=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runMultiline).update("Run").insert(el.right.console.container);el.right.console.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.console.input)).update("Clear").insert(el.right.console.container);el.button.console={};el.button.console.container=new pi.element("DIV").attribute.addClass("ButtonSet").insert(el.button.container);el.button.console.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.left.console.monitor)).update("Clear").insert(el.button.console.container);el.left.html={};el.left.html.container=new pi.element("DIV").attribute.addClass("HTML").insert(el.left.container);el.right.html={};el.right.html.container=new pi.element("DIV").attribute.addClass("HTML Container").insert(el.right.container);el.right.html.nav={};el.right.html.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.right.html.container);el.right.html.nav.computedStyle=new pi.element("A").attribute.addClass("Tab Selected").event.addListener("click",d.html.navigate.curry(firebug,"computedStyle")).update("Computed Style").insert(el.right.html.nav.container);if(!pi.env.ie6)el.right.html.nav.dom=new pi.element("A").attribute.addClass("Tab").event.addListener("click",d.html.navigate.curry(firebug,"dom")).update("DOM").insert(el.right.html.nav.container);el.right.html.content=new pi.element("DIV").attribute.addClass("Content").insert(el.right.html.container);el.button.html={};el.button.html.container=new pi.element("DIV").attribute.addClass("ButtonSet HTML").insert(el.button.container);el.left.css={};el.left.css.container=new pi.element("DIV").attribute.addClass("CSS").insert(el.left.container);el.right.css={};el.right.css.container=new pi.element("DIV").attribute.addClass("CSS Container").insert(el.right.container);el.right.css.nav={};el.right.css.nav.container=new pi.element("DIV").attribute.addClass("Nav").insert(el.right.css.container);el.right.css.nav.runCSS=new pi.element("A").attribute.addClass("Tab Selected").update("Run CSS").insert(el.right.css.nav.container);el.right.css.mlButton=new pi.element("A").attribute.addClass("MLButton CloseML").event.addListener("click",d.console.toggleML).insert(el.right.css.container);el.right.css.input=new pi.element("TEXTAREA").attribute.addClass("Input").insert(el.right.css.container);el.right.css.run=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.runCSS).update("Run").insert(el.right.css.container);el.right.css.clear=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.clean.curry(window,el.right.css.input)).update("Clear").insert(el.right.css.container);el.button.css={};el.button.css.container=new pi.element("DIV").attribute.addClass("ButtonSet CSS").insert(el.button.container);el.button.css.selectbox=new pi.element("SELECT").event.addListener("change",listen.cssSelectbox).insert(el.button.css.container);el.left.scripts={};el.left.scripts.container=new pi.element("DIV").attribute.addClass("Scripts").insert(el.left.container);el.right.scripts={};el.right.scripts.container=new pi.element("DIV").attribute.addClass("Scripts Container").insert(el.right.container);el.button.scripts={};el.button.scripts.container=new pi.element("DIV").attribute.addClass("ButtonSet Scripts").insert(el.button.container);el.button.scripts.selectbox=new pi.element("SELECT").event.addListener("change",listen.scriptsSelectbox).insert(el.button.scripts.container);el.button.scripts.lineNumbers=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.scripts.toggleLineNumbers).update("Show Line Numbers").insert(el.button.scripts.container);el.left.dom={};el.left.dom.container=new pi.element("DIV").attribute.addClass("DOM").insert(el.left.container);el.right.dom={};el.right.dom.container=new pi.element("DIV").attribute.addClass("DOM Container").insert(el.right.container);el.button.dom={};el.button.dom.container=new pi.element("DIV").attribute.addClass("ButtonSet DOM").insert(el.button.container);el.button.dom.label=new pi.element("LABEL").update("Object Path:").insert(el.button.dom.container);el.button.dom.textbox=new pi.element("INPUT").event.addListener("keydown",listen.domTextbox).update("window").insert(el.button.dom.container);el.left.str={};el.left.str.container=new pi.element("DIV").attribute.addClass("STR").insert(el.left.container);el.right.str={};el.right.str.container=new pi.element("DIV").attribute.addClass("STR").insert(el.left.container);el.button.str={};el.button.str.container=new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container);el.button.str.watch=new pi.element("A").attribute.addClass("Button").event.addListener("click",d.navigate.curry(window,"xhr")).update("Back").insert(el.button.str.container);el.left.xhr={};el.left.xhr.container=new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container);el.right.xhr={};el.right.xhr.container=new pi.element("DIV").attribute.addClass("XHR").insert(el.left.container);el.button.xhr={};el.button.xhr.container=new pi.element("DIV").attribute.addClass("ButtonSet XHR").insert(el.button.container);el.button.xhr.label=new pi.element("LABEL").update("XHR Path:").insert(el.button.xhr.container);el.button.xhr.textbox=new pi.element("INPUT").event.addListener("keydown",listen.xhrTextbox).insert(el.button.xhr.container);el.button.xhr.watch=new pi.element("A").attribute.addClass("Button").event.addListener("click",listen.addXhrObject).update("Watch").insert(el.button.xhr.container);if(pi.env.ie6){var buttons=[el.button.inspect,el.button.close,el.button.inspect,el.button.console.clear,el.right.console.run,el.right.console.clear,el.right.css.run,el.right.css.clear];for(var i=0;i<buttons.length;i++)buttons[i].attribute.set("href","#")}env.init=true;for(var i=0;i<env.ctmp.length;i++){d.console.log.apply(window,env.ctmp[i])}}},win:{close:function(){with(firebug){el.main.update("");el.main.remove()}},minimize:function(){with(firebug){el.main.environment.addStyle({"height":"35px"});el.button.maximize.environment.addStyle({"display":"block"});el.button.minimize.environment.addStyle({"display":"none"});d.refreshSize()}},maximize:function(){with(firebug){el.main.environment.addStyle({"height":"295px"});el.button.minimize.environment.addStyle({"display":"block"});el.button.maximize.environment.addStyle({"display":"none"});d.refreshSize()}}},watchXHR:function(){with(firebug){d.xhr.addObject.apply(window,arguments);if(env.dIndex!="xhr"){d.navigate("xhr")}}},d:{clean:function(_element){with(firebug){_element.update("")}},console:{dir:function(_value){with(firebug){d.console.addLine().attribute.addClass("Arrow").update(">>> console.dir("+_value+")");d.dom.open(_value,d.console.addLine())}},addLine:function(){with(firebug){return new pi.element("DIV").attribute.addClass("Row").insert(el.left.console.monitor)}},openObject:function(_index){with(firebug){d.dom.open(env.objCn[_index],el.left.dom.container,pi.env.ie);d.navigate("dom")}},historyIndex:0,history:[],log:function(_values){with(firebug){if(env.init==false){env.ctmp.push(arguments);return}var value="";for(var i=0;i<arguments.length;i++){value+=(i>0?" ":"")+d.highlight(arguments[i],false,false,true)}d.console.addLine().update(value);d.console.scroll()}},print:function(_cmd,_text){with(firebug){d.console.addLine().attribute.addClass("Arrow").update(">>> "+_cmd);d.console.addLine().update(d.highlight(_text,false,false,true));d.console.scroll();d.console.historyIndex=d.console.history.push(_cmd)}},run:function(cmd){with(firebug){if(cmd.length==0)return;el.left.console.input.environment.getElement().value="";try{var result=eval.call(window,cmd);d.console.print(cmd,result)}catch(e){d.console.addLine().attribute.addClass("Arrow").update(">>> "+cmd);if(!pi.env.ff){d.console.scroll();return d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+(e.description||e),true)}if(e.fileName==null){d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+e.message,true)}var fileName=e.fileName.split("\/").getLastItem();d.console.addLine().attribute.addClass("Error").update("<strong>Error: </strong>"+e.message+" (<em>"+fileName+"</em>,"+e.lineNumber+")",true);d.console.scroll()}d.console.scroll()}},scroll:function(){with(firebug){el.left.console.monitor.environment.getElement().parentNode.scrollTop=Math.abs(el.left.console.monitor.environment.getSize().offsetHeight-200)}},toggleML:function(){with(firebug){var open=!env.ml;env.ml=!env.ml;d.navigateRightColumn("console",open);el[open?"left":"right"].console.mlButton.environment.addStyle({display:"none"});el[!open?"left":"right"].console.mlButton.environment.addStyle({display:"block"});el.left.console.monitor.environment.addStyle({"height":(open?233:210)+"px"});el.left.console.mlButton.attribute[(open?"add":"remove")+"Class"]("CloseML")}}},css:{index:-1,open:function(_index){with(firebug){var item=document.styleSheets[_index];var uri=item.href;if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){el.left.css.container.update("<em>Access to restricted URI denied</em>");return}var rules=item[pi.env.ie?"rules":"cssRules"];var str="";for(var i=0;i<rules.length;i++){var item=rules[i];var selector=item.selectorText;var cssText=pi.env.ie?item.style.cssText:item.cssText.match(/\{(.*)\}/)[1];str+=d.css.printRule(selector,cssText.split(";"),el.left.css.container)}el.left.css.container.update(str)}},printRule:function(_selector,_css,_layer){with(firebug){var str="<div class='Selector'>"+_selector+" {</div>";for(var i=0;i<_css.length;i++){var item=_css[i];str+="<div class='CSSText'>"+item.replace(/(.+\:)(.+)/,"<span class='CSSProperty'>$1</span><span class='CSSValue'>$2;</span>")+"</div>"}str+="<div class='Selector'>}</div>";return str}},refresh:function(){with(firebug){el.button.css.selectbox.update("");var collection=document.styleSheets;for(var i=0;i<collection.length;i++){var uri=collection[i].href;d.css.index=d.css.index<0?i:d.css.index;el.button.css.selectbox.child.add(new pi.element("OPTION").attribute.set("value",i).update(uri))};d.css.open(d.css.index)}}},dom:{open:function(_object,_layer){with(firebug){_layer.clean();var container=new pi.element("DIV").attribute.addClass("DOMContent").insert(_layer);d.dom.print(_object,container)}},print:function(_object,_parent,_inTree){with(firebug){var obj=_object||window,parentElement=_parent;parentElement.update("");if(parentElement.opened&&parentElement!=el.left.dom.container){parentElement.environment.getParent().pi.child.get()[0].pi.child.get()[0].pi.attribute.removeClass("Opened");parentElement.opened=false;parentElement.environment.addStyle({"display":"none"});return}if(_inTree)parentElement.environment.getParent().pi.child.get()[0].pi.child.get()[0].pi.attribute.addClass("Opened");parentElement.opened=true;for(var key in obj){try{var value=obj[key],property=key,container=new pi.element("DIV").attribute.addClass("DOMRow").insert(parentElement),left=new pi.element("DIV").attribute.addClass("DOMRowLeft").insert(container),right=new pi.element("DIV").attribute.addClass("DOMRowRight").insert(container);container.child.add(new pi.element("DIV").environment.addStyle({"clear":"both"}));var link=new pi.element("A").attribute.addClass(typeof value=="object"&&Boolean(value)?"Property Object":"Property").update(property).insert(left);right.update(d.highlight(value,false,true));var subContainer=new pi.element("DIV").attribute.addClass("DOMRowSubContainer").insert(container);if(typeof value!="object"||Boolean(value)==false)continue;link.event.addListener("click",d.dom.print.curry(window,value,subContainer,true))}catch(e){}}parentElement.environment.addStyle({"display":"block"})}}},highlight:function(_value,_inObject,_inArray,_link){with(firebug){var isArray=false,isElement=false;try{isArray=pi.util.IsArray(_value);isElement=_value!=undefined&&Boolean(_value.nodeName)&&Boolean(_value.nodeType)}catch(e){};if(_value==null||["boolean","function","number","string"].indexOf(typeof _value)>-1){if(_value==null){return"<span class='Null'>null</span>"}if(["boolean","number"].indexOf(typeof _value)>-1){return"<span class='DarkBlue'>"+_value+"</span>"}if(typeof _value=="function"){return"<span class='"+(_inObject?"Italic Gray":"Green")+"'>function()</span>"}return"<span class='Red'>\""+(!_inObject&&!_inArray?_value:_value.substring(0,35)).replace(/\n/g,"\\n").replace(/\s/g,"&nbsp;").replace(/>/g,"&#62;").replace(/</g,"&#60;")+"\"</span>"}else if(isElement){if(_value.nodeType==3)return d.highlight(_value.nodeValue);if(_inArray||_inObject){var result="<span class='Blue'>"+_value.nodeName.toLowerCase();if(_value.getAttribute&&_value.getAttribute("id"))result+="<span class='DarkBlue'>#"+_value.getAttribute("id")+"</span>";var elClass=_value.getAttribute?_value.getAttribute(pi.env.ie?"className":"class"):"";if(elClass)result+="<span class='Red'>."+elClass.split(" ")[0]+"</span>";return result+"</span>"}var result="<span class='Blue'>&#60;"+_value.nodeName.toLowerCase()+"";if(_value.attributes)for(var i=0;i<_value.attributes.length;i++){var item=_value.attributes[i];if(pi.env.ie&&Boolean(item.nodeValue)==false)continue;result+=" <span class='DarkBlue'>"+item.nodeName+"=\"<span class='Red'>"+item.nodeValue+"</span>\"</span>"}result+="&#62;</span>";return result}else if(isArray||["object","array"].indexOf(typeof _value)>-1){var result="";if(isArray||_value instanceof Array){if(_inObject)return"<span class='Gray Italic'>["+_value.length+"]</span>";result+="<span class='Strong'>[ ";for(var i=0;i<_value.length;i++){if((_inObject||_inArray)&&pi.env.ie&&i>3)break;result+=(i>0?", ":"")+d.highlight(_value[i],false,true,true)}result+=" ]</span>";return result}if(_inObject)return"<span class='Gray Italic'>Object</span>";result+="<span class='Strong Green"+(!_link?"'":" ObjectLink' onmouseover='this.className=this.className.replace(\"ObjectLink\",\"ObjectLinkHover\")' onmouseout='this.className=this.className.replace(\"ObjectLinkHover\",\"ObjectLink\")' onclick='firebug.d.console.openObject("+(env.objCn.push(_value)-1)+")'")+">Object";var i=0;for(var key in _value){var value=_value[key];if((_inObject||_inArray)&&pi.env.ie&&i>3)break;result+=" "+key+"="+d.highlight(value,true);i++};result+="</span>";return result}else{if(_inObject)return"<span class='Gray Italic'>"+_value+"</span>";return _value}}},html:{nIndex:"computedStyle",current:null,highlight:function(_element,_clear,_event){with(firebug){if(_clear){el.bgInspector.environment.addStyle({"display":"none"});return}d.inspector.inspect(_element,true)}},inspect:function(_element){var el=_element,map=[],parent=_element;while(parent){map.push(parent);if(parent==document.body)break;parent=parent.parentNode}map=map.reverse();with(firebug){d.inspector.toggle();var parentLayer=el.left.html.container.child.get()[1].childNodes[1].pi;for(var t=0;map[t];){if(t==map.length-1){var link=parentLayer.environment.getElement().previousSibling.pi;link.attribute.addClass("Selected");if(d.html.current)d.html.current[1].attribute.removeClass("Selected");d.html.current=[_element,link];return;t}parentLayer=d.html.openHtmlTree(map[t],parentLayer,map[t+1]);t++}}},navigate:function(_index,_element){with(firebug){el.right.html.nav[d.html.nIndex].attribute.removeClass("Selected");el.right.html.nav[_index].attribute.addClass("Selected");d.html.nIndex=_index;d.html.openProperties()}},openHtmlTree:function(_element,_parent,_returnParentElementByElement,_event){with(firebug){var element=_element||document.documentElement,parent=_parent||el.left.html.container,returnParentEl=_returnParentElementByElement||null,returnParentVal=null;if(parent!=el.left.html.container){var nodeLink=parent.environment.getParent().pi.child.get()[0].pi;if(d.html.current)d.html.current[1].attribute.removeClass("Selected");nodeLink.attribute.addClass("Selected");d.html.current=[_element,nodeLink];d.html.openProperties()}if(element.childNodes&&(element.childNodes.length==0||(element.childNodes.length==1&&element.childNodes[0].nodeType==3)))return;parent.clean();if(parent.opened&&Boolean(_returnParentElementByElement)==false){parent.opened=false;parent.environment.getParent().pi.child.get()[0].pi.attribute.removeClass("Open");return}if(parent!=el.left.html.container){parent.environment.getParent().pi.child.get()[0].pi.attribute.addClass("Open");parent.opened=true}for(var i=0;i<element.childNodes.length;i++){var item=element.childNodes[i];if(item.nodeType==3)continue;var container=new pi.element().attribute.addClass("Block").insert(parent);var link=new pi.element("A").attribute.addClass("Link").update(d.highlight(item)).insert(container);var subContainer=new pi.element("DIV").attribute.addClass("SubContainer").insert(container);link.event.addListener("click",d.html.openHtmlTree.curry(window,item,subContainer,false));link.event.addListener("mouseover",d.html.highlight.curry(window,item,false));link.event.addListener("mouseout",d.html.highlight.curry(window,item,true));returnParentVal=returnParentEl==item?subContainer:returnParentVal;if(d.html.current==null&&item==document.body){link.attribute.addClass("Selected");d.html.current=[item,link];d.html.openHtmlTree(item,subContainer)}if(item.childNodes&&item.childNodes.length==1&&item.childNodes[0].nodeType==3){link.child.get()[0].appendChild(document.createTextNode(item.childNodes[0].nodeValue.substring(0,100)));link.child.get()[0].appendChild(document.createTextNode("</"));link.child.get()[0].appendChild(new pi.element("span").attribute.addClass("Blue").update(item.nodeName.toLowerCase()).environment.getElement());link.child.get()[0].appendChild(document.createTextNode(">"));continue}else if(item.childNodes&&item.childNodes.length==0)continue;link.attribute.addClass("ParentLink")}return returnParentVal}},openProperties:function(){with(firebug){var index=d.html.nIndex;var node=d.html.current[0];d.clean(el.right.html.content);var str="";switch(index){case"computedStyle":var property=["opacity","filter","azimuth","background","backgroundAttachment","backgroundColor","backgroundImage","backgroundPosition","backgroundRepeat","border","borderCollapse","borderColor","borderSpacing","borderStyle","borderTop","borderRight","borderBottom","borderLeft","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","borderTopStyle","borderRightStyle","borderBottomStyle","borderLeftStyle","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderWidth","bottom","captionSide","clear","clip","color","content","counterIncrement","counterReset","cue","cueAfter","cueBefore","cursor","direction","display","elevation","emptyCells","cssFloat","font","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","height","left","letterSpacing","lineHeight","listStyle","listStyleImage","listStylePosition","listStyleType","margin","marginTop","marginRight","marginBottom","marginLeft","markerOffset","marks","maxHeight","maxWidth","minHeight","minWidth","orphans","outline","outlineColor","outlineStyle","outlineWidth","overflow","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","page","pageBreakAfter","pageBreakBefore","pageBreakInside","pause","pauseAfter","pauseBefore","pitch","pitchRange","playDuring","position","quotes","richness","right","size","speak","speakHeader","speakNumeral","speakPunctuation","speechRate","stress","tableLayout","textAlign","textDecoration","textIndent","textShadow","textTransform","top","unicodeBidi","verticalAlign","visibility","voiceFamily","volume","whiteSpace","widows","width","wordSpacing","zIndex"].sort();var view=document.defaultView?document.defaultView.getComputedStyle(node,null):node.currentStyle;for(var i=0;i<property.length;i++){var item=property[i];if(!view[item])continue;str+="<div class='CSSItem'><div class='CSSProperty'>"+item+"</div><div class='CSSValue'>"+d.highlight(view[item])+"</div></div>"}el.right.html.content.update(str);break;case"dom":d.dom.open(node,el.right.html.content,pi.env.ie);break}}}},inspector:{enabled:false,el:null,inspect:function(_element,_bgInspector){var el=_element,top=el.offsetTop,left=el.offsetLeft,parent=_element.offsetParent;while(Boolean(parent)&&parent!=document.firstChild){top+=parent.offsetTop;left+=parent.offsetLeft;parent=parent.offsetParent;if(parent==document.body)break};with(firebug){el[_bgInspector?"bgInspector":"borderInspector"].environment.addStyle({"width":_element.offsetWidth+"px","height":_element.offsetHeight+"px","top":top-(_bgInspector?0:2)+"px","left":left-(_bgInspector?0:2)+"px","display":"block"});if(!_bgInspector){d.inspector.el=_element}}},toggle:function(){with(firebug){d.inspector.enabled=!d.inspector.enabled;el.button.inspect.attribute[(d.inspector.enabled?"add":"remove")+"Class"]("Enabled");if(d.inspector.enabled==false){el.borderInspector.environment.addStyle({"display":"none"});d.inspector.el=null}else if(pi.env.dIndex!="html"){d.navigate("html")}}}},scripts:{index:-1,lineNumbers:false,open:function(_index){with(firebug){d.scripts.index=_index;el.left.scripts.container.update("");var script=document.getElementsByTagName("script")[_index],uri=script.src||document.location.href,source;if(uri.indexOf("http:\/\/")>-1&&getDomain(uri)!=document.domain){el.left.scripts.container.update("<em>Access to restricted URI denied</em>");return}if(uri!=document.location.href){source=env.cache[uri]||pi.xhr.get(uri).responseText;env.cache[uri]=source}else source=script.innerHTML;source=source.replace(/\n|\t|<|>/g,function(_ch){return({"<":"&#60;",">":"&#62;","\t":"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;","\n":"<br />"})[_ch]});if(!d.scripts.lineNumbers)el.left.scripts.container.child.add(new pi.element("DIV").attribute.addClass("CodeContainer").update(source));else{source=source.split("<br />");for(var i=0;i<source.length;i++){el.left.scripts.container.child.add(new pi.element("DIV").child.add(new pi.element("DIV").attribute.addClass("LineNumber").update(i+1),new pi.element("DIV").attribute.addClass("Code").update("&nbsp;"+source[i]),new pi.element("DIV").environment.addStyle({"clear":"both"})))}}}},toggleLineNumbers:function(){with(firebug){d.scripts.lineNumbers=!d.scripts.lineNumbers;el.button.scripts.lineNumbers.attribute[(d.scripts.lineNumbers?"add":"remove")+"Class"]("Enabled");d.scripts.open(d.scripts.index)}},refresh:function(){with(firebug){el.button.scripts.selectbox.clean();var collection=document.getElementsByTagName("script");for(var i=0;i<collection.length;i++){var item=collection[i];d.scripts.index=d.scripts.index<0?i:d.scripts.index;el.button.scripts.selectbox.child.add(new pi.element("OPTION").attribute.set("value",i).update(item.src||item.baseURI||".."))}d.scripts.open(d.scripts.index)}}},str:{open:function(_str){with(firebug){d.navigate("str");el.left.str.container.update(_str.replace(/\n/g,"<br />"))}}},xhr:{objects:[],addObject:function(){with(firebug){for(var i=0;i<arguments.length;i++){try{var item=arguments[i];var val=eval(item);d.xhr.objects.push([item,val])}catch(e){continue}}}},open:function(){with(firebug){el.left.xhr.container.update("");el.left.xhr.name=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").attribute.addClass("Block").environment.addStyle({"width":"20%"}).insert(el.left.xhr.container));el.left.xhr.nameTitle=new pi.element("STRONG").update("Object Name:").insert(el.left.xhr.name);el.left.xhr.nameContent=new pi.element("DIV").insert(el.left.xhr.name);el.left.xhr.status=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").attribute.addClass("Block").environment.addStyle({"width":"10%"}).insert(el.left.xhr.container));el.left.xhr.statusTitle=new pi.element("STRONG").update("Status:").insert(el.left.xhr.status);el.left.xhr.statusContent=new pi.element("DIV").insert(el.left.xhr.status);el.left.xhr.readystate=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").environment.addStyle({"width":"15%"}).attribute.addClass("Block").insert(el.left.xhr.container));el.left.xhr.readystateTitle=el.left.xhr.nameTitle=new pi.element("STRONG").update("Ready State:").insert(el.left.xhr.readystate);el.left.xhr.readystateContent=new pi.element("DIV").insert(el.left.xhr.readystate);el.left.xhr.response=new pi.element("DIV").attribute.addClass("BlockContent").insert(new pi.element("DIV").environment.addStyle({"width":(pi.env.ie?"50":"55")+"%"}).attribute.addClass("Block").insert(el.left.xhr.container));el.left.xhr.responseTitle=new pi.element("STRONG").update("Response:").insert(el.left.xhr.response);el.left.xhr.responseContent=new pi.element("DIV").insert(el.left.xhr.response);setTimeout(d.xhr.refresh,500)}},refresh:function(){with(firebug){el.left.xhr.nameContent.update("");el.left.xhr.statusContent.update("");el.left.xhr.readystateContent.update("");el.left.xhr.responseContent.update("");for(var i=0;i<d.xhr.objects.length;i++){var item=d.xhr.objects[i];var response=item[1].responseText;if(Boolean(item[1])==false)continue;el.left.xhr.nameContent.child.add(new pi.element("span").update(item[0]));try{el.left.xhr.statusContent.child.add(new pi.element("span").update(item[1].status))}catch(e){el.left.xhr.statusContent.child.add(new pi.element("span").update("&nbsp;"))}el.left.xhr.readystateContent.child.add(new pi.element("span").update(item[1].readyState));el.left.xhr.responseContent.child.add(new pi.element("span").child.add(new pi.element("A").event.addListener("click",d.str.open.curry(window,response)).update("&nbsp;"+response.substring(0,50))))};if(env.dIndex=="xhr")setTimeout(d.xhr.refresh,500)}}},navigateRightColumn:function(_index,_open){with(firebug){el.left.container.environment.addStyle({"width":_open?"70%":"100%"});el.right.container.environment.addStyle({"display":_open?"block":"none"})}},navigate:function(_index){with(firebug){var open=_index,close=env.dIndex;env.dIndex=open;el.button[close].container.environment.addStyle({"display":"none"});el.left[close].container.environment.addStyle({"display":"none"});el.right[close].container.environment.addStyle({"display":"none"});el.button[open].container.environment.addStyle({"display":"inline"});el.left[open].container.environment.addStyle({"display":"block"});el.right[open].container.environment.addStyle({"display":"block"});if(el.nav[close])el.nav[close].attribute.removeClass("Selected");if(el.nav[open])el.nav[open].attribute.addClass("Selected");switch(open){case"console":d.navigateRightColumn(_index);break;case"html":d.navigateRightColumn(_index,true);d.html.openHtmlTree();break;case"css":d.navigateRightColumn(_index,true);d.css.refresh();break;case"scripts":d.navigateRightColumn(_index);d.scripts.refresh();break;case"dom":d.navigateRightColumn(_index);if(el.left.dom.container.environment.getElement().innerHTML=="")d.dom.open(eval(el.button.dom.textbox.environment.getElement().value),el.left.dom.container);break;case"xhr":d.navigateRightColumn(_index);d.xhr.open();break}}},refreshSize:function(){with(firebug){el.main.environment.addStyle({"width":pi.util.GetWindowSize().width+"px"});if(pi.env.ie6)el.main.environment.addStyle({"top":pi.util.GetWindowSize().height-el.main.environment.getSize().offsetHeight+"px"})}}},getDomain:function(_url){return _url.match(/http:\/\/(www.)?([\.\w]+)/)[2]},listen:{addXhrObject:function(){with(firebug){d.xhr.addObject.apply(window,el.button.xhr.textbox.environment.getElement().value.split(","))}},consoleTextbox:function(_event){with(firebug){if(_event.keyCode==13&&(env.multilinemode==false||_event.shiftKey==false)){d.console.historyIndex=d.console.history.length;d.console.run(el.left.console.input.environment.getElement().value);return false}if([13,38,40].indexOf(_event.keyCode)==-1)return;d.console.historyIndex+=_event.keyCode!=40?0:d.console.historyIndex==d.console.history.length?0:1;d.console.historyIndex-=_event.keyCode!=38?0:d.console.historyIndex==0?0:1;el.left.console.input.update(d.console.history.length>d.console.historyIndex?d.console.history[d.console.historyIndex]:"")}},cssSelectbox:function(){with(firebug){d.css.open(el.button.css.selectbox.environment.getElement().selectedIndex)}},domTextbox:function(_event){with(firebug){if(_event.keyCode==13){d.dom.open(eval(el.button.dom.textbox.environment.getElement().value),el.left.dom.container)}}},inspector:function(){with(firebug){d.html.inspect(d.inspector.el)}},keyboard:function(_event){with(firebug){if(_event.keyCode==27&&d.inspector.enabled)d.inspector.toggle()}},mouse:function(_event){with(firebug){var target=_event[pi.env.ie?"srcElement":"target"];if(d.inspector.enabled&&target!=document.body&&target!=document.firstChild&&target!=document.childNodes[1]&&target!=el.borderInspector.environment.getElement()&&target!=el.main.environment.getElement()&&target.offsetParent!=el.main.environment.getElement())d.inspector.inspect(target)}},runMultiline:function(){with(firebug){d.console.run.call(window,el.right.console.input.environment.getElement().value)}},runCSS:function(){with(firebug){var source=el.right.css.input.environment.getElement().value.replace(/\n|\t/g,"").split("}");for(var i=0;i<source.length;i++){var item=source[i]+"}",rule=!pi.env.ie?item:item.split(/{|}/),collection=document.getElementsByTagName("style"),style=collection.length>0?collection[0]:document.body.appendChild(document.createElement("style"));if(!item.match(/.+\{.+\}/))continue;if(pi.env.ie)style.styleSheet.addRule(rule[0],rule[1]);else style.sheet.insertRule(rule,style.sheet.cssRules.length)}}},scriptsSelectbox:function(){with(firebug){d.scripts.open(parseInt(el.button.scripts.selectbox.environment.getElement().value))}},xhrTextbox:function(_event){with(firebug){if(_event.keyCode==13){d.xhr.addObject.apply(window,el.button.xhr.textbox.environment.getElement().value.split(","))}}}}};window.console=firebug.d.console;pi.util.AddEvent(window,"resize",firebug.d.refreshSize);pi.util.AddEvent(document,"mousemove",firebug.listen.mouse);pi.util.AddEvent(document,"keydown",firebug.listen.keyboard);pi.util.DOMContentLoaded.push(firebug.init);
\ No newline at end of file
diff --git a/ui/lib/jquery.js b/ui/lib/jquery.js
deleted file mode 100755 (executable)
index 88e661e..0000000
+++ /dev/null
@@ -1,3549 +0,0 @@
-(function(){
-/*
- * jQuery 1.2.6 - New Wave Javascript
- *
- * Copyright (c) 2008 John Resig (jquery.com)
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
- * $Rev: 5685 $
- */
-
-// Map over jQuery in case of overwrite
-var _jQuery = window.jQuery,
-// Map over the $ in case of overwrite
-       _$ = window.$;
-
-var jQuery = window.jQuery = window.$ = function( selector, context ) {
-       // The jQuery object is actually just the init constructor 'enhanced'
-       return new jQuery.fn.init( selector, context );
-};
-
-// A simple way to check for HTML strings or ID strings
-// (both of which we optimize for)
-var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,
-
-// Is it a simple selector
-       isSimple = /^.[^:#\[\.]*$/,
-
-// Will speed up references to undefined, and allows munging its name.
-       undefined;
-
-jQuery.fn = jQuery.prototype = {
-       init: function( selector, context ) {
-               // Make sure that a selection was provided
-               selector = selector || document;
-
-               // Handle $(DOMElement)
-               if ( selector.nodeType ) {
-                       this[0] = selector;
-                       this.length = 1;
-                       return this;
-               }
-               // Handle HTML strings
-               if ( typeof selector == "string" ) {
-                       // Are we dealing with HTML string or an ID?
-                       var match = quickExpr.exec( selector );
-
-                       // Verify a match, and that no context was specified for #id
-                       if ( match && (match[1] || !context) ) {
-
-                               // HANDLE: $(html) -> $(array)
-                               if ( match[1] )
-                                       selector = jQuery.clean( [ match[1] ], context );
-
-                               // HANDLE: $("#id")
-                               else {
-                                       var elem = document.getElementById( match[3] );
-
-                                       // Make sure an element was located
-                                       if ( elem ){
-                                               // Handle the case where IE and Opera return items
-                                               // by name instead of ID
-                                               if ( elem.id != match[3] )
-                                                       return jQuery().find( selector );
-
-                                               // Otherwise, we inject the element directly into the jQuery object
-                                               return jQuery( elem );
-                                       }
-                                       selector = [];
-                               }
-
-                       // HANDLE: $(expr, [context])
-                       // (which is just equivalent to: $(content).find(expr)
-                       } else
-                               return jQuery( context ).find( selector );
-
-               // HANDLE: $(function)
-               // Shortcut for document ready
-               } else if ( jQuery.isFunction( selector ) )
-                       return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );
-
-               return this.setArray(jQuery.makeArray(selector));
-       },
-
-       // The current version of jQuery being used
-       jquery: "1.2.6",
-
-       // The number of elements contained in the matched element set
-       size: function() {
-               return this.length;
-       },
-
-       // The number of elements contained in the matched element set
-       length: 0,
-
-       // Get the Nth element in the matched element set OR
-       // Get the whole matched element set as a clean array
-       get: function( num ) {
-               return num == undefined ?
-
-                       // Return a 'clean' array
-                       jQuery.makeArray( this ) :
-
-                       // Return just the object
-                       this[ num ];
-       },
-
-       // Take an array of elements and push it onto the stack
-       // (returning the new matched element set)
-       pushStack: function( elems ) {
-               // Build a new jQuery matched element set
-               var ret = jQuery( elems );
-
-               // Add the old object onto the stack (as a reference)
-               ret.prevObject = this;
-
-               // Return the newly-formed element set
-               return ret;
-       },
-
-       // Force the current matched set of elements to become
-       // the specified array of elements (destroying the stack in the process)
-       // You should use pushStack() in order to do this, but maintain the stack
-       setArray: function( elems ) {
-               // Resetting the length to 0, then using the native Array push
-               // is a super-fast way to populate an object with array-like properties
-               this.length = 0;
-               Array.prototype.push.apply( this, elems );
-
-               return this;
-       },
-
-       // Execute a callback for every element in the matched set.
-       // (You can seed the arguments with an array of args, but this is
-       // only used internally.)
-       each: function( callback, args ) {
-               return jQuery.each( this, callback, args );
-       },
-
-       // Determine the position of an element within
-       // the matched set of elements
-       index: function( elem ) {
-               var ret = -1;
-
-               // Locate the position of the desired element
-               return jQuery.inArray(
-                       // If it receives a jQuery object, the first element is used
-                       elem && elem.jquery ? elem[0] : elem
-               , this );
-       },
-
-       attr: function( name, value, type ) {
-               var options = name;
-
-               // Look for the case where we're accessing a style value
-               if ( name.constructor == String )
-                       if ( value === undefined )
-                               return this[0] && jQuery[ type || "attr" ]( this[0], name );
-
-                       else {
-                               options = {};
-                               options[ name ] = value;
-                       }
-
-               // Check to see if we're setting style values
-               return this.each(function(i){
-                       // Set all the styles
-                       for ( name in options )
-                               jQuery.attr(
-                                       type ?
-                                               this.style :
-                                               this,
-                                       name, jQuery.prop( this, options[ name ], type, i, name )
-                               );
-               });
-       },
-
-       css: function( key, value ) {
-               // ignore negative width and height values
-               if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
-                       value = undefined;
-               return this.attr( key, value, "curCSS" );
-       },
-
-       text: function( text ) {
-               if ( typeof text != "object" && text != null )
-                       return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
-
-               var ret = "";
-
-               jQuery.each( text || this, function(){
-                       jQuery.each( this.childNodes, function(){
-                               if ( this.nodeType != 8 )
-                                       ret += this.nodeType != 1 ?
-                                               this.nodeValue :
-                                               jQuery.fn.text( [ this ] );
-                       });
-               });
-
-               return ret;
-       },
-
-       wrapAll: function( html ) {
-               if ( this[0] )
-                       // The elements to wrap the target around
-                       jQuery( html, this[0].ownerDocument )
-                               .clone()
-                               .insertBefore( this[0] )
-                               .map(function(){
-                                       var elem = this;
-
-                                       while ( elem.firstChild )
-                                               elem = elem.firstChild;
-
-                                       return elem;
-                               })
-                               .append(this);
-
-               return this;
-       },
-
-       wrapInner: function( html ) {
-               return this.each(function(){
-                       jQuery( this ).contents().wrapAll( html );
-               });
-       },
-
-       wrap: function( html ) {
-               return this.each(function(){
-                       jQuery( this ).wrapAll( html );
-               });
-       },
-
-       append: function() {
-               return this.domManip(arguments, true, false, function(elem){
-                       if (this.nodeType == 1)
-                               this.appendChild( elem );
-               });
-       },
-
-       prepend: function() {
-               return this.domManip(arguments, true, true, function(elem){
-                       if (this.nodeType == 1)
-                               this.insertBefore( elem, this.firstChild );
-               });
-       },
-
-       before: function() {
-               return this.domManip(arguments, false, false, function(elem){
-                       this.parentNode.insertBefore( elem, this );
-               });
-       },
-
-       after: function() {
-               return this.domManip(arguments, false, true, function(elem){
-                       this.parentNode.insertBefore( elem, this.nextSibling );
-               });
-       },
-
-       end: function() {
-               return this.prevObject || jQuery( [] );
-       },
-
-       find: function( selector ) {
-               var elems = jQuery.map(this, function(elem){
-                       return jQuery.find( selector, elem );
-               });
-
-               return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ?
-                       jQuery.unique( elems ) :
-                       elems );
-       },
-
-       clone: function( events ) {
-               // Do the clone
-               var ret = this.map(function(){
-                       if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) {
-                               // IE copies events bound via attachEvent when
-                               // using cloneNode. Calling detachEvent on the
-                               // clone will also remove the events from the orignal
-                               // In order to get around this, we use innerHTML.
-                               // Unfortunately, this means some modifications to
-                               // attributes in IE that are actually only stored
-                               // as properties will not be copied (such as the
-                               // the name attribute on an input).
-                               var clone = this.cloneNode(true),
-                                       container = document.createElement("div");
-                               container.appendChild(clone);
-                               return jQuery.clean([container.innerHTML])[0];
-                       } else
-                               return this.cloneNode(true);
-               });
-
-               // Need to set the expando to null on the cloned set if it exists
-               // removeData doesn't work here, IE removes it from the original as well
-               // this is primarily for IE but the data expando shouldn't be copied over in any browser
-               var clone = ret.find("*").andSelf().each(function(){
-                       if ( this[ expando ] != undefined )
-                               this[ expando ] = null;
-               });
-
-               // Copy the events from the original to the clone
-               if ( events === true )
-                       this.find("*").andSelf().each(function(i){
-                               if (this.nodeType == 3)
-                                       return;
-                               var events = jQuery.data( this, "events" );
-
-                               for ( var type in events )
-                                       for ( var handler in events[ type ] )
-                                               jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
-                       });
-
-               // Return the cloned set
-               return ret;
-       },
-
-       filter: function( selector ) {
-               return this.pushStack(
-                       jQuery.isFunction( selector ) &&
-                       jQuery.grep(this, function(elem, i){
-                               return selector.call( elem, i );
-                       }) ||
-
-                       jQuery.multiFilter( selector, this ) );
-       },
-
-       not: function( selector ) {
-               if ( selector.constructor == String )
-                       // test special case where just one selector is passed in
-                       if ( isSimple.test( selector ) )
-                               return this.pushStack( jQuery.multiFilter( selector, this, true ) );
-                       else
-                               selector = jQuery.multiFilter( selector, this );
-
-               var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
-               return this.filter(function() {
-                       return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
-               });
-       },
-
-       add: function( selector ) {
-               return this.pushStack( jQuery.unique( jQuery.merge(
-                       this.get(),
-                       typeof selector == 'string' ?
-                               jQuery( selector ) :
-                               jQuery.makeArray( selector )
-               )));
-       },
-
-       is: function( selector ) {
-               return !!selector && jQuery.multiFilter( selector, this ).length > 0;
-       },
-
-       hasClass: function( selector ) {
-               return this.is( "." + selector );
-       },
-
-       val: function( value ) {
-               if ( value == undefined ) {
-
-                       if ( this.length ) {
-                               var elem = this[0];
-
-                               // We need to handle select boxes special
-                               if ( jQuery.nodeName( elem, "select" ) ) {
-                                       var index = elem.selectedIndex,
-                                               values = [],
-                                               options = elem.options,
-                                               one = elem.type == "select-one";
-
-                                       // Nothing was selected
-                                       if ( index < 0 )
-                                               return null;
-
-                                       // Loop through all the selected options
-                                       for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
-                                               var option = options[ i ];
-
-                                               if ( option.selected ) {
-                                                       // Get the specifc value for the option
-                                                       value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;
-
-                                                       // We don't need an array for one selects
-                                                       if ( one )
-                                                               return value;
-
-                                                       // Multi-Selects return an array
-                                                       values.push( value );
-                                               }
-                                       }
-
-                                       return values;
-
-                               // Everything else, we just grab the value
-                               } else
-                                       return (this[0].value || "").replace(/\r/g, "");
-
-                       }
-
-                       return undefined;
-               }
-
-               if( value.constructor == Number )
-                       value += '';
-
-               return this.each(function(){
-                       if ( this.nodeType != 1 )
-                               return;
-
-                       if ( value.constructor == Array && /radio|checkbox/.test( this.type ) )
-                               this.checked = (jQuery.inArray(this.value, value) >= 0 ||
-                                       jQuery.inArray(this.name, value) >= 0);
-
-                       else if ( jQuery.nodeName( this, "select" ) ) {
-                               var values = jQuery.makeArray(value);
-
-                               jQuery( "option", this ).each(function(){
-                                       this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
-                                               jQuery.inArray( this.text, values ) >= 0);
-                               });
-
-                               if ( !values.length )
-                                       this.selectedIndex = -1;
-
-                       } else
-                               this.value = value;
-               });
-       },
-
-       html: function( value ) {
-               return value == undefined ?
-                       (this[0] ?
-                               this[0].innerHTML :
-                               null) :
-                       this.empty().append( value );
-       },
-
-       replaceWith: function( value ) {
-               return this.after( value ).remove();
-       },
-
-       eq: function( i ) {
-               return this.slice( i, i + 1 );
-       },
-
-       slice: function() {
-               return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
-       },
-
-       map: function( callback ) {
-               return this.pushStack( jQuery.map(this, function(elem, i){
-                       return callback.call( elem, i, elem );
-               }));
-       },
-
-       andSelf: function() {
-               return this.add( this.prevObject );
-       },
-
-       data: function( key, value ){
-               var parts = key.split(".");
-               parts[1] = parts[1] ? "." + parts[1] : "";
-
-               if ( value === undefined ) {
-                       var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
-
-                       if ( data === undefined && this.length )
-                               data = jQuery.data( this[0], key );
-
-                       return data === undefined && parts[1] ?
-                               this.data( parts[0] ) :
-                               data;
-               } else
-                       return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
-                               jQuery.data( this, key, value );
-                       });
-       },
-
-       removeData: function( key ){
-               return this.each(function(){
-                       jQuery.removeData( this, key );
-               });
-       },
-
-       domManip: function( args, table, reverse, callback ) {
-               var clone = this.length > 1, elems;
-
-               return this.each(function(){
-                       if ( !elems ) {
-                               elems = jQuery.clean( args, this.ownerDocument );
-
-                               if ( reverse )
-                                       elems.reverse();
-                       }
-
-                       var obj = this;
-
-                       if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) )
-                               obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );
-
-                       var scripts = jQuery( [] );
-
-                       jQuery.each(elems, function(){
-                               var elem = clone ?
-                                       jQuery( this ).clone( true )[0] :
-                                       this;
-
-                               // execute all scripts after the elements have been injected
-                               if ( jQuery.nodeName( elem, "script" ) )
-                                       scripts = scripts.add( elem );
-                               else {
-                                       // Remove any inner scripts for later evaluation
-                                       if ( elem.nodeType == 1 )
-                                               scripts = scripts.add( jQuery( "script", elem ).remove() );
-
-                                       // Inject the elements into the document
-                                       callback.call( obj, elem );
-                               }
-                       });
-
-                       scripts.each( evalScript );
-               });
-       }
-};
-
-// Give the init function the jQuery prototype for later instantiation
-jQuery.fn.init.prototype = jQuery.fn;
-
-function evalScript( i, elem ) {
-       if ( elem.src )
-               jQuery.ajax({
-                       url: elem.src,
-                       async: false,
-                       dataType: "script"
-               });
-
-       else
-               jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
-
-       if ( elem.parentNode )
-               elem.parentNode.removeChild( elem );
-}
-
-function now(){
-       return +new Date;
-}
-
-jQuery.extend = jQuery.fn.extend = function() {
-       // copy reference to target object
-       var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
-
-       // Handle a deep copy situation
-       if ( target.constructor == Boolean ) {
-               deep = target;
-               target = arguments[1] || {};
-               // skip the boolean and the target
-               i = 2;
-       }
-
-       // Handle case when target is a string or something (possible in deep copy)
-       if ( typeof target != "object" && typeof target != "function" )
-               target = {};
-
-       // extend jQuery itself if only one argument is passed
-       if ( length == i ) {
-               target = this;
-               --i;
-       }
-
-       for ( ; i < length; i++ )
-               // Only deal with non-null/undefined values
-               if ( (options = arguments[ i ]) != null )
-                       // Extend the base object
-                       for ( var name in options ) {
-                               var src = target[ name ], copy = options[ name ];
-
-                               // Prevent never-ending loop
-                               if ( target === copy )
-                                       continue;
-
-                               // Recurse if we're merging object values
-                               if ( deep && copy && typeof copy == "object" && !copy.nodeType )
-                                       target[ name ] = jQuery.extend( deep, 
-                                               // Never move original objects, clone them
-                                               src || ( copy.length != null ? [ ] : { } )
-                                       , copy );
-
-                               // Don't bring in undefined values
-                               else if ( copy !== undefined )
-                                       target[ name ] = copy;
-
-                       }
-
-       // Return the modified object
-       return target;
-};
-
-var expando = "jQuery" + now(), uuid = 0, windowData = {},
-       // exclude the following css properties to add px
-       exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
-       // cache defaultView
-       defaultView = document.defaultView || {};
-
-jQuery.extend({
-       noConflict: function( deep ) {
-               window.$ = _$;
-
-               if ( deep )
-                       window.jQuery = _jQuery;
-
-               return jQuery;
-       },
-
-       // See test/unit/core.js for details concerning this function.
-       isFunction: function( fn ) {
-               return !!fn && typeof fn != "string" && !fn.nodeName &&
-                       fn.constructor != Array && /^[\s[]?function/.test( fn + "" );
-       },
-
-       // check if an element is in a (or is an) XML document
-       isXMLDoc: function( elem ) {
-               return elem.documentElement && !elem.body ||
-                       elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
-       },
-
-       // Evalulates a script in a global context
-       globalEval: function( data ) {
-               data = jQuery.trim( data );
-
-               if ( data ) {
-                       // Inspired by code by Andrea Giammarchi
-                       // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
-                       var head = document.getElementsByTagName("head")[0] || document.documentElement,
-                               script = document.createElement("script");
-
-                       script.type = "text/javascript";
-                       if ( jQuery.browser.msie )
-                               script.text = data;
-                       else
-                               script.appendChild( document.createTextNode( data ) );
-
-                       // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
-                       // This arises when a base node is used (#2709).
-                       head.insertBefore( script, head.firstChild );
-                       head.removeChild( script );
-               }
-       },
-
-       nodeName: function( elem, name ) {
-               return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
-       },
-
-       cache: {},
-
-       data: function( elem, name, data ) {
-               elem = elem == window ?
-                       windowData :
-                       elem;
-
-               var id = elem[ expando ];
-
-               // Compute a unique ID for the element
-               if ( !id )
-                       id = elem[ expando ] = ++uuid;
-
-               // Only generate the data cache if we're
-               // trying to access or manipulate it
-               if ( name && !jQuery.cache[ id ] )
-                       jQuery.cache[ id ] = {};
-
-               // Prevent overriding the named cache with undefined values
-               if ( data !== undefined )
-                       jQuery.cache[ id ][ name ] = data;
-
-               // Return the named cache data, or the ID for the element
-               return name ?
-                       jQuery.cache[ id ][ name ] :
-                       id;
-       },
-
-       removeData: function( elem, name ) {
-               elem = elem == window ?
-                       windowData :
-                       elem;
-
-               var id = elem[ expando ];
-
-               // If we want to remove a specific section of the element's data
-               if ( name ) {
-                       if ( jQuery.cache[ id ] ) {
-                               // Remove the section of cache data
-                               delete jQuery.cache[ id ][ name ];
-
-                               // If we've removed all the data, remove the element's cache
-                               name = "";
-
-                               for ( name in jQuery.cache[ id ] )
-                                       break;
-
-                               if ( !name )
-                                       jQuery.removeData( elem );
-                       }
-
-               // Otherwise, we want to remove all of the element's data
-               } else {
-                       // Clean up the element expando
-                       try {
-                               delete elem[ expando ];
-                       } catch(e){
-                               // IE has trouble directly removing the expando
-                               // but it's ok with using removeAttribute
-                               if ( elem.removeAttribute )
-                                       elem.removeAttribute( expando );
-                       }
-
-                       // Completely remove the data cache
-                       delete jQuery.cache[ id ];
-               }
-       },
-
-       // args is for internal usage only
-       each: function( object, callback, args ) {
-               var name, i = 0, length = object.length;
-
-               if ( args ) {
-                       if ( length == undefined ) {
-                               for ( name in object )
-                                       if ( callback.apply( object[ name ], args ) === false )
-                                               break;
-                       } else
-                               for ( ; i < length; )
-                                       if ( callback.apply( object[ i++ ], args ) === false )
-                                               break;
-
-               // A special, fast, case for the most common use of each
-               } else {
-                       if ( length == undefined ) {
-                               for ( name in object )
-                                       if ( callback.call( object[ name ], name, object[ name ] ) === false )
-                                               break;
-                       } else
-                               for ( var value = object[0];
-                                       i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
-               }
-
-               return object;
-       },
-
-       prop: function( elem, value, type, i, name ) {
-               // Handle executable functions
-               if ( jQuery.isFunction( value ) )
-                       value = value.call( elem, i );
-
-               // Handle passing in a number to a CSS property
-               return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ?
-                       value + "px" :
-                       value;
-       },
-
-       className: {
-               // internal only, use addClass("class")
-               add: function( elem, classNames ) {
-                       jQuery.each((classNames || "").split(/\s+/), function(i, className){
-                               if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
-                                       elem.className += (elem.className ? " " : "") + className;
-                       });
-               },
-
-               // internal only, use removeClass("class")
-               remove: function( elem, classNames ) {
-                       if (elem.nodeType == 1)
-                               elem.className = classNames != undefined ?
-                                       jQuery.grep(elem.className.split(/\s+/), function(className){
-                                               return !jQuery.className.has( classNames, className );
-                                       }).join(" ") :
-                                       "";
-               },
-
-               // internal only, use hasClass("class")
-               has: function( elem, className ) {
-                       return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
-               }
-       },
-
-       // A method for quickly swapping in/out CSS properties to get correct calculations
-       swap: function( elem, options, callback ) {
-               var old = {};
-               // Remember the old values, and insert the new ones
-               for ( var name in options ) {
-                       old[ name ] = elem.style[ name ];
-                       elem.style[ name ] = options[ name ];
-               }
-
-               callback.call( elem );
-
-               // Revert the old values
-               for ( var name in options )
-                       elem.style[ name ] = old[ name ];
-       },
-
-       css: function( elem, name, force ) {
-               if ( name == "width" || name == "height" ) {
-                       var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
-
-                       function getWH() {
-                               val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
-                               var padding = 0, border = 0;
-                               jQuery.each( which, function() {
-                                       padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
-                                       border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
-                               });
-                               val -= Math.round(padding + border);
-                       }
-
-                       if ( jQuery(elem).is(":visible") )
-                               getWH();
-                       else
-                               jQuery.swap( elem, props, getWH );
-
-                       return Math.max(0, val);
-               }
-
-               return jQuery.curCSS( elem, name, force );
-       },
-
-       curCSS: function( elem, name, force ) {
-               var ret, style = elem.style;
-
-               // A helper method for determining if an element's values are broken
-               function color( elem ) {
-                       if ( !jQuery.browser.safari )
-                               return false;
-
-                       // defaultView is cached
-                       var ret = defaultView.getComputedStyle( elem, null );
-                       return !ret || ret.getPropertyValue("color") == "";
-               }
-
-               // We need to handle opacity special in IE
-               if ( name == "opacity" && jQuery.browser.msie ) {
-                       ret = jQuery.attr( style, "opacity" );
-
-                       return ret == "" ?
-                               "1" :
-                               ret;
-               }
-               // Opera sometimes will give the wrong display answer, this fixes it, see #2037
-               if ( jQuery.browser.opera && name == "display" ) {
-                       var save = style.outline;
-                       style.outline = "0 solid black";
-                       style.outline = save;
-               }
-
-               // Make sure we're using the right name for getting the float value
-               if ( name.match( /float/i ) )
-                       name = styleFloat;
-
-               if ( !force && style && style[ name ] )
-                       ret = style[ name ];
-
-               else if ( defaultView.getComputedStyle ) {
-
-                       // Only "float" is needed here
-                       if ( name.match( /float/i ) )
-                               name = "float";
-
-                       name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
-
-                       var computedStyle = defaultView.getComputedStyle( elem, null );
-
-                       if ( computedStyle && !color( elem ) )
-                               ret = computedStyle.getPropertyValue( name );
-
-                       // If the element isn't reporting its values properly in Safari
-                       // then some display: none elements are involved
-                       else {
-                               var swap = [], stack = [], a = elem, i = 0;
-
-                               // Locate all of the parent display: none elements
-                               for ( ; a && color(a); a = a.parentNode )
-                                       stack.unshift(a);
-
-                               // Go through and make them visible, but in reverse
-                               // (It would be better if we knew the exact display type that they had)
-                               for ( ; i < stack.length; i++ )
-                                       if ( color( stack[ i ] ) ) {
-                                               swap[ i ] = stack[ i ].style.display;
-                                               stack[ i ].style.display = "block";
-                                       }
-
-                               // Since we flip the display style, we have to handle that
-                               // one special, otherwise get the value
-                               ret = name == "display" && swap[ stack.length - 1 ] != null ?
-                                       "none" :
-                                       ( computedStyle && computedStyle.getPropertyValue( name ) ) || "";
-
-                               // Finally, revert the display styles back
-                               for ( i = 0; i < swap.length; i++ )
-                                       if ( swap[ i ] != null )
-                                               stack[ i ].style.display = swap[ i ];
-                       }
-
-                       // We should always get a number back from opacity
-                       if ( name == "opacity" && ret == "" )
-                               ret = "1";
-
-               } else if ( elem.currentStyle ) {
-                       var camelCase = name.replace(/\-(\w)/g, function(all, letter){
-                               return letter.toUpperCase();
-                       });
-
-                       ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
-
-                       // From the awesome hack by Dean Edwards
-                       // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
-
-                       // If we're not dealing with a regular pixel number
-                       // but a number that has a weird ending, we need to convert it to pixels
-                       if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
-                               // Remember the original values
-                               var left = style.left, rsLeft = elem.runtimeStyle.left;
-
-                               // Put in the new values to get a computed value out
-                               elem.runtimeStyle.left = elem.currentStyle.left;
-                               style.left = ret || 0;
-                               ret = style.pixelLeft + "px";
-
-                               // Revert the changed values
-                               style.left = left;
-                               elem.runtimeStyle.left = rsLeft;
-                       }
-               }
-
-               return ret;
-       },
-
-       clean: function( elems, context ) {
-               var ret = [];
-               context = context || document;
-               // !context.createElement fails in IE with an error but returns typeof 'object'
-               if (typeof context.createElement == 'undefined')
-                       context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
-
-               jQuery.each(elems, function(i, elem){
-                       if ( !elem )
-                               return;
-
-                       if ( elem.constructor == Number )
-                               elem += '';
-
-                       // Convert html string into DOM nodes
-                       if ( typeof elem == "string" ) {
-                               // Fix "XHTML"-style tags in all browsers
-                               elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
-                                       return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
-                                               all :
-                                               front + "></" + tag + ">";
-                               });
-
-                               // Trim whitespace, otherwise indexOf won't work as expected
-                               var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div");
-
-                               var wrap =
-                                       // option or optgroup
-                                       !tags.indexOf("<opt") &&
-                                       [ 1, "<select multiple='multiple'>", "</select>" ] ||
-
-                                       !tags.indexOf("<leg") &&
-                                       [ 1, "<fieldset>", "</fieldset>" ] ||
-
-                                       tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
-                                       [ 1, "<table>", "</table>" ] ||
-
-                                       !tags.indexOf("<tr") &&
-                                       [ 2, "<table><tbody>", "</tbody></table>" ] ||
-
-                                       // <thead> matched above
-                                       (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
-                                       [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
-
-                                       !tags.indexOf("<col") &&
-                                       [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
-
-                                       // IE can't serialize <link> and <script> tags normally
-                                       jQuery.browser.msie &&
-                                       [ 1, "div<div>", "</div>" ] ||
-
-                                       [ 0, "", "" ];
-
-                               // Go to html and back, then peel off extra wrappers
-                               div.innerHTML = wrap[1] + elem + wrap[2];
-
-                               // Move to the right depth
-                               while ( wrap[0]-- )
-                                       div = div.lastChild;
-
-                               // Remove IE's autoinserted <tbody> from table fragments
-                               if ( jQuery.browser.msie ) {
-
-                                       // String was a <table>, *may* have spurious <tbody>
-                                       var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
-                                               div.firstChild && div.firstChild.childNodes :
-
-                                               // String was a bare <thead> or <tfoot>
-                                               wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
-                                                       div.childNodes :
-                                                       [];
-
-                                       for ( var j = tbody.length - 1; j >= 0 ; --j )
-                                               if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
-                                                       tbody[ j ].parentNode.removeChild( tbody[ j ] );
-
-                                       // IE completely kills leading whitespace when innerHTML is used
-                                       if ( /^\s/.test( elem ) )
-                                               div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
-
-                               }
-
-                               elem = jQuery.makeArray( div.childNodes );
-                       }
-
-                       if ( elem.length === 0 && (!jQuery.nodeName( elem, "form" ) && !jQuery.nodeName( elem, "select" )) )
-                               return;
-
-                       if ( elem[0] == undefined || jQuery.nodeName( elem, "form" ) || elem.options )
-                               ret.push( elem );
-
-                       else
-                               ret = jQuery.merge( ret, elem );
-
-               });
-
-               return ret;
-       },
-
-       attr: function( elem, name, value ) {
-               // don't set attributes on text and comment nodes
-               if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
-                       return undefined;
-
-               var notxml = !jQuery.isXMLDoc( elem ),
-                       // Whether we are setting (or getting)
-                       set = value !== undefined,
-                       msie = jQuery.browser.msie;
-
-               // Try to normalize/fix the name
-               name = notxml && jQuery.props[ name ] || name;
-
-               // Only do all the following if this is a node (faster for style)
-               // IE elem.getAttribute passes even for style
-               if ( elem.tagName ) {
-
-                       // These attributes require special treatment
-                       var special = /href|src|style/.test( name );
-
-                       // Safari mis-reports the default selected property of a hidden option
-                       // Accessing the parent's selectedIndex property fixes it
-                       if ( name == "selected" && jQuery.browser.safari )
-                               elem.parentNode.selectedIndex;
-
-                       // If applicable, access the attribute via the DOM 0 way
-                       if ( name in elem && notxml && !special ) {
-                               if ( set ){
-                                       // We can't allow the type property to be changed (since it causes problems in IE)
-                                       if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
-                                               throw "type property can't be changed";
-
-                                       elem[ name ] = value;
-                               }
-
-                               // browsers index elements by id/name on forms, give priority to attributes.
-                               if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
-                                       return elem.getAttributeNode( name ).nodeValue;
-
-                               return elem[ name ];
-                       }
-
-                       if ( msie && notxml &&  name == "style" )
-                               return jQuery.attr( elem.style, "cssText", value );
-
-                       if ( set )
-                               // convert the value to a string (all browsers do this but IE) see #1070
-                               elem.setAttribute( name, "" + value );
-
-                       var attr = msie && notxml && special
-                                       // Some attributes require a special call on IE
-                                       ? elem.getAttribute( name, 2 )
-                                       : elem.getAttribute( name );
-
-                       // Non-existent attributes return null, we normalize to undefined
-                       return attr === null ? undefined : attr;
-               }
-
-               // elem is actually elem.style ... set the style
-
-               // IE uses filters for opacity
-               if ( msie && name == "opacity" ) {
-                       if ( set ) {
-                               // IE has trouble with opacity if it does not have layout
-                               // Force it by setting the zoom level
-                               elem.zoom = 1;
-
-                               // Set the alpha filter to set the opacity
-                               elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
-                                       (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
-                       }
-
-                       return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
-                               (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
-                               "";
-               }
-
-               name = name.replace(/-([a-z])/ig, function(all, letter){
-                       return letter.toUpperCase();
-               });
-
-               if ( set )
-                       elem[ name ] = value;
-
-               return elem[ name ];
-       },
-
-       trim: function( text ) {
-               return (text || "").replace( /^\s+|\s+$/g, "" );
-       },
-
-       makeArray: function( array ) {
-               var ret = [];
-
-               if( array != null ){
-                       var i = array.length;
-                       //the window, strings and functions also have 'length'
-                       if( i == null || array.split || array.setInterval || array.call )
-                               ret[0] = array;
-                       else
-                               while( i )
-                                       ret[--i] = array[i];
-               }
-
-               return ret;
-       },
-
-       inArray: function( elem, array ) {
-               for ( var i = 0, length = array.length; i < length; i++ )
-               // Use === because on IE, window == document
-                       if ( array[ i ] === elem )
-                               return i;
-
-               return -1;
-       },
-
-       merge: function( first, second ) {
-               // We have to loop this way because IE & Opera overwrite the length
-               // expando of getElementsByTagName
-               var i = 0, elem, pos = first.length;
-               // Also, we need to make sure that the correct elements are being returned
-               // (IE returns comment nodes in a '*' query)
-               if ( jQuery.browser.msie ) {
-                       while ( elem = second[ i++ ] )
-                               if ( elem.nodeType != 8 )
-                                       first[ pos++ ] = elem;
-
-               } else
-                       while ( elem = second[ i++ ] )
-                               first[ pos++ ] = elem;
-
-               return first;
-       },
-
-       unique: function( array ) {
-               var ret = [], done = {};
-
-               try {
-
-                       for ( var i = 0, length = array.length; i < length; i++ ) {
-                               var id = jQuery.data( array[ i ] );
-
-                               if ( !done[ id ] ) {
-                                       done[ id ] = true;
-                                       ret.push( array[ i ] );
-                               }
-                       }
-
-               } catch( e ) {
-                       ret = array;
-               }
-
-               return ret;
-       },
-
-       grep: function( elems, callback, inv ) {
-               var ret = [];
-
-               // Go through the array, only saving the items
-               // that pass the validator function
-               for ( var i = 0, length = elems.length; i < length; i++ )
-                       if ( !inv != !callback( elems[ i ], i ) )
-                               ret.push( elems[ i ] );
-
-               return ret;
-       },
-
-       map: function( elems, callback ) {
-               var ret = [];
-
-               // Go through the array, translating each of the items to their
-               // new value (or values).
-               for ( var i = 0, length = elems.length; i < length; i++ ) {
-                       var value = callback( elems[ i ], i );
-
-                       if ( value != null )
-                               ret[ ret.length ] = value;
-               }
-
-               return ret.concat.apply( [], ret );
-       }
-});
-
-var userAgent = navigator.userAgent.toLowerCase();
-
-// Figure out what browser is being used
-jQuery.browser = {
-       version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
-       safari: /webkit/.test( userAgent ),
-       opera: /opera/.test( userAgent ),
-       msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
-       mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
-};
-
-var styleFloat = jQuery.browser.msie ?
-       "styleFloat" :
-       "cssFloat";
-
-jQuery.extend({
-       // Check to see if the W3C box model is being used
-       boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",
-
-       props: {
-               "for": "htmlFor",
-               "class": "className",
-               "float": styleFloat,
-               cssFloat: styleFloat,
-               styleFloat: styleFloat,
-               readonly: "readOnly",
-               maxlength: "maxLength",
-               cellspacing: "cellSpacing"
-       }
-});
-
-jQuery.each({
-       parent: function(elem){return elem.parentNode;},
-       parents: function(elem){return jQuery.dir(elem,"parentNode");},
-       next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
-       prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
-       nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
-       prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
-       siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
-       children: function(elem){return jQuery.sibling(elem.firstChild);},
-       contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
-}, function(name, fn){
-       jQuery.fn[ name ] = function( selector ) {
-               var ret = jQuery.map( this, fn );
-
-               if ( selector && typeof selector == "string" )
-                       ret = jQuery.multiFilter( selector, ret );
-
-               return this.pushStack( jQuery.unique( ret ) );
-       };
-});
-
-jQuery.each({
-       appendTo: "append",
-       prependTo: "prepend",
-       insertBefore: "before",
-       insertAfter: "after",
-       replaceAll: "replaceWith"
-}, function(name, original){
-       jQuery.fn[ name ] = function() {
-               var args = arguments;
-
-               return this.each(function(){
-                       for ( var i = 0, length = args.length; i < length; i++ )
-                               jQuery( args[ i ] )[ original ]( this );
-               });
-       };
-});
-
-jQuery.each({
-       removeAttr: function( name ) {
-               jQuery.attr( this, name, "" );
-               if (this.nodeType == 1)
-                       this.removeAttribute( name );
-       },
-
-       addClass: function( classNames ) {
-               jQuery.className.add( this, classNames );
-       },
-
-       removeClass: function( classNames ) {
-               jQuery.className.remove( this, classNames );
-       },
-
-       toggleClass: function( classNames ) {
-               jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
-       },
-
-       remove: function( selector ) {
-               if ( !selector || jQuery.filter( selector, [ this ] ).r.length ) {
-                       // Prevent memory leaks
-                       jQuery( "*", this ).add(this).each(function(){
-                               jQuery.event.remove(this);
-                               jQuery.removeData(this);
-                       });
-                       if (this.parentNode)
-                               this.parentNode.removeChild( this );
-               }
-       },
-
-       empty: function() {
-               // Remove element nodes and prevent memory leaks
-               jQuery( ">*", this ).remove();
-
-               // Remove any remaining nodes
-               while ( this.firstChild )
-                       this.removeChild( this.firstChild );
-       }
-}, function(name, fn){
-       jQuery.fn[ name ] = function(){
-               return this.each( fn, arguments );
-       };
-});
-
-jQuery.each([ "Height", "Width" ], function(i, name){
-       var type = name.toLowerCase();
-
-       jQuery.fn[ type ] = function( size ) {
-               // Get window width or height
-               return this[0] == window ?
-                       // Opera reports document.body.client[Width/Height] properly in both quirks and standards
-                       jQuery.browser.opera && document.body[ "client" + name ] ||
-
-                       // Safari reports inner[Width/Height] just fine (Mozilla and Opera include scroll bar widths)
-                       jQuery.browser.safari && window[ "inner" + name ] ||
-
-                       // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
-                       document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] :
-
-                       // Get document width or height
-                       this[0] == document ?
-                               // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
-                               Math.max(
-                                       Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
-                                       Math.max(document.body["offset" + name], document.documentElement["offset" + name])
-                               ) :
-
-                               // Get or set width or height on the element
-                               size == undefined ?
-                                       // Get width or height on the element
-                                       (this.length ? jQuery.css( this[0], type ) : null) :
-
-                                       // Set the width or height on the element (default to pixels if value is unitless)
-                                       this.css( type, size.constructor == String ? size : size + "px" );
-       };
-});
-
-// Helper function used by the dimensions and offset modules
-function num(elem, prop) {
-       return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
-}var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
-               "(?:[\\w*_-]|\\\\.)" :
-               "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
-       quickChild = new RegExp("^>\\s*(" + chars + "+)"),
-       quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
-       quickClass = new RegExp("^([#.]?)(" + chars + "*)");
-
-jQuery.extend({
-       expr: {
-               "": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
-               "#": function(a,i,m){return a.getAttribute("id")==m[2];},
-               ":": {
-                       // Position Checks
-                       lt: function(a,i,m){return i<m[3]-0;},
-                       gt: function(a,i,m){return i>m[3]-0;},
-                       nth: function(a,i,m){return m[3]-0==i;},
-                       eq: function(a,i,m){return m[3]-0==i;},
-                       first: function(a,i){return i==0;},
-                       last: function(a,i,m,r){return i==r.length-1;},
-                       even: function(a,i){return i%2==0;},
-                       odd: function(a,i){return i%2;},
-
-                       // Child Checks
-                       "first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
-                       "last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
-                       "only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},
-
-                       // Parent Checks
-                       parent: function(a){return a.firstChild;},
-                       empty: function(a){return !a.firstChild;},
-
-                       // Text Check
-                       contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},
-
-                       // Visibility
-                       visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
-                       hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},
-
-                       // Form attributes
-                       enabled: function(a){return !a.disabled;},
-                       disabled: function(a){return a.disabled;},
-                       checked: function(a){return a.checked;},
-                       selected: function(a){return a.selected||jQuery.attr(a,"selected");},
-
-                       // Form elements
-                       text: function(a){return "text"==a.type;},
-                       radio: function(a){return "radio"==a.type;},
-                       checkbox: function(a){return "checkbox"==a.type;},
-                       file: function(a){return "file"==a.type;},
-                       password: function(a){return "password"==a.type;},
-                       submit: function(a){return "submit"==a.type;},
-                       image: function(a){return "image"==a.type;},
-                       reset: function(a){return "reset"==a.type;},
-                       button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
-                       input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},
-
-                       // :has()
-                       has: function(a,i,m){return jQuery.find(m[3],a).length;},
-
-                       // :header
-                       header: function(a){return /h\d/i.test(a.nodeName);},
-
-                       // :animated
-                       animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
-               }
-       },
-
-       // The regular expressions that power the parsing engine
-       parse: [
-               // Match: [@value='test'], [@foo]
-               /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
-
-               // Match: :contains('foo')
-               /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
-
-               // Match: :even, :last-child, #id, .class
-               new RegExp("^([:.#]*)(" + chars + "+)")
-       ],
-
-       multiFilter: function( expr, elems, not ) {
-               var old, cur = [];
-
-               while ( expr && expr != old ) {
-                       old = expr;
-                       var f = jQuery.filter( expr, elems, not );
-                       expr = f.t.replace(/^\s*,\s*/, "" );
-                       cur = not ? elems = f.r : jQuery.merge( cur, f.r );
-               }
-
-               return cur;
-       },
-
-       find: function( t, context ) {
-               // Quickly handle non-string expressions
-               if ( typeof t != "string" )
-                       return [ t ];
-
-               // check to make sure context is a DOM element or a document
-               if ( context && context.nodeType != 1 && context.nodeType != 9)
-                       return [ ];
-
-               // Set the correct context (if none is provided)
-               context = context || document;
-
-               // Initialize the search
-               var ret = [context], done = [], last, nodeName;
-
-               // Continue while a selector expression exists, and while
-               // we're no longer looping upon ourselves
-               while ( t && last != t ) {
-                       var r = [];
-                       last = t;
-
-                       t = jQuery.trim(t);
-
-                       var foundToken = false,
-
-                       // An attempt at speeding up child selectors that
-                       // point to a specific element tag
-                               re = quickChild,
-
-                               m = re.exec(t);
-
-                       if ( m ) {
-                               nodeName = m[1].toUpperCase();
-
-                               // Perform our own iteration and filter
-                               for ( var i = 0; ret[i]; i++ )
-                                       for ( var c = ret[i].firstChild; c; c = c.nextSibling )
-                                               if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
-                                                       r.push( c );
-
-                               ret = r;
-                               t = t.replace( re, "" );
-                               if ( t.indexOf(" ") == 0 ) continue;
-                               foundToken = true;
-                       } else {
-                               re = /^([>+~])\s*(\w*)/i;
-
-                               if ( (m = re.exec(t)) != null ) {
-                                       r = [];
-
-                                       var merge = {};
-                                       nodeName = m[2].toUpperCase();
-                                       m = m[1];
-
-                                       for ( var j = 0, rl = ret.length; j < rl; j++ ) {
-                                               var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
-                                               for ( ; n; n = n.nextSibling )
-                                                       if ( n.nodeType == 1 ) {
-                                                               var id = jQuery.data(n);
-
-                                                               if ( m == "~" && merge[id] ) break;
-
-                                                               if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
-                                                                       if ( m == "~" ) merge[id] = true;
-                                                                       r.push( n );
-                                                               }
-
-                                                               if ( m == "+" ) break;
-                                                       }
-                                       }
-
-                                       ret = r;
-
-                                       // And remove the token
-                                       t = jQuery.trim( t.replace( re, "" ) );
-                                       foundToken = true;
-                               }
-                       }
-
-                       // See if there's still an expression, and that we haven't already
-                       // matched a token
-                       if ( t && !foundToken ) {
-                               // Handle multiple expressions
-                               if ( !t.indexOf(",") ) {
-                                       // Clean the result set
-                                       if ( context == ret[0] ) ret.shift();
-
-                                       // Merge the result sets
-                                       done = jQuery.merge( done, ret );
-
-                                       // Reset the context
-                                       r = ret = [context];
-
-                                       // Touch up the selector string
-                                       t = " " + t.substr(1,t.length);
-
-                               } else {
-                                       // Optimize for the case nodeName#idName
-                                       var re2 = quickID;
-                                       var m = re2.exec(t);
-
-                                       // Re-organize the results, so that they're consistent
-                                       if ( m ) {
-                                               m = [ 0, m[2], m[3], m[1] ];
-
-                                       } else {
-                                               // Otherwise, do a traditional filter check for
-                                               // ID, class, and element selectors
-                                               re2 = quickClass;
-                                               m = re2.exec(t);
-                                       }
-
-                                       m[2] = m[2].replace(/\\/g, "");
-
-                                       var elem = ret[ret.length-1];
-
-                                       // Try to do a global search by ID, where we can
-                                       if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
-                                               // Optimization for HTML document case
-                                               var oid = elem.getElementById(m[2]);
-
-                                               // Do a quick check for the existence of the actual ID attribute
-                                               // to avoid selecting by the name attribute in IE
-                                               // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
-                                               if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
-                                                       oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
-
-                                               // Do a quick check for node name (where applicable) so
-                                               // that div#foo searches will be really fast
-                                               ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
-                                       } else {
-                                               // We need to find all descendant elements
-                                               for ( var i = 0; ret[i]; i++ ) {
-                                                       // Grab the tag name being searched for
-                                                       var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];
-
-                                                       // Handle IE7 being really dumb about <object>s
-                                                       if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
-                                                               tag = "param";
-
-                                                       r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
-                                               }
-
-                                               // It's faster to filter by class and be done with it
-                                               if ( m[1] == "." )
-                                                       r = jQuery.classFilter( r, m[2] );
-
-                                               // Same with ID filtering
-                                               if ( m[1] == "#" ) {
-                                                       var tmp = [];
-
-                                                       // Try to find the element with the ID
-                                                       for ( var i = 0; r[i]; i++ )
-                                                               if ( r[i].getAttribute("id") == m[2] ) {
-                                                                       tmp = [ r[i] ];
-                                                                       break;
-                                                               }
-
-                                                       r = tmp;
-                                               }
-
-                                               ret = r;
-                                       }
-
-                                       t = t.replace( re2, "" );
-                               }
-
-                       }
-
-                       // If a selector string still exists
-                       if ( t ) {
-                               // Attempt to filter it
-                               var val = jQuery.filter(t,r);
-                               ret = r = val.r;
-                               t = jQuery.trim(val.t);
-                       }
-               }
-
-               // An error occurred with the selector;
-               // just return an empty set instead
-               if ( t )
-                       ret = [];
-
-               // Remove the root context
-               if ( ret && context == ret[0] )
-                       ret.shift();
-
-               // And combine the results
-               done = jQuery.merge( done, ret );
-
-               return done;
-       },
-
-       classFilter: function(r,m,not){
-               m = " " + m + " ";
-               var tmp = [];
-               for ( var i = 0; r[i]; i++ ) {
-                       var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
-                       if ( !not && pass || not && !pass )
-                               tmp.push( r[i] );
-               }
-               return tmp;
-       },
-
-       filter: function(t,r,not) {
-               var last;
-
-               // Look for common filter expressions
-               while ( t && t != last ) {
-                       last = t;
-
-                       var p = jQuery.parse, m;
-
-                       for ( var i = 0; p[i]; i++ ) {
-                               m = p[i].exec( t );
-
-                               if ( m ) {
-                                       // Remove what we just matched
-                                       t = t.substring( m[0].length );
-
-                                       m[2] = m[2].replace(/\\/g, "");
-                                       break;
-                               }
-                       }
-
-                       if ( !m )
-                               break;
-
-                       // :not() is a special case that can be optimized by
-                       // keeping it out of the expression list
-                       if ( m[1] == ":" && m[2] == "not" )
-                               // optimize if only one selector found (most common case)
-                               r = isSimple.test( m[3] ) ?
-                                       jQuery.filter(m[3], r, true).r :
-                                       jQuery( r ).not( m[3] );
-
-                       // We can get a big speed boost by filtering by class here
-                       else if ( m[1] == "." )
-                               r = jQuery.classFilter(r, m[2], not);
-
-                       else if ( m[1] == "[" ) {
-                               var tmp = [], type = m[3];
-
-                               for ( var i = 0, rl = r.length; i < rl; i++ ) {
-                                       var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
-
-                                       if ( z == null || /href|src|selected/.test(m[2]) )
-                                               z = jQuery.attr(a,m[2]) || '';
-
-                                       if ( (type == "" && !!z ||
-                                                type == "=" && z == m[5] ||
-                                                type == "!=" && z != m[5] ||
-                                                type == "^=" && z && !z.indexOf(m[5]) ||
-                                                type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
-                                                (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
-                                                       tmp.push( a );
-                               }
-
-                               r = tmp;
-
-                       // We can get a speed boost by handling nth-child here
-                       } else if ( m[1] == ":" && m[2] == "nth-child" ) {
-                               var merge = {}, tmp = [],
-                                       // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
-                                       test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
-                                               m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
-                                               !/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
-                                       // calculate the numbers (first)n+(last) including if they are negative
-                                       first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;
-
-                               // loop through all the elements left in the jQuery object
-                               for ( var i = 0, rl = r.length; i < rl; i++ ) {
-                                       var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
-
-                                       if ( !merge[id] ) {
-                                               var c = 1;
-
-                                               for ( var n = parentNode.firstChild; n; n = n.nextSibling )
-                                                       if ( n.nodeType == 1 )
-                                                               n.nodeIndex = c++;
-
-                                               merge[id] = true;
-                                       }
-
-                                       var add = false;
-
-                                       if ( first == 0 ) {
-                                               if ( node.nodeIndex == last )
-                                                       add = true;
-                                       } else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
-                                               add = true;
-
-                                       if ( add ^ not )
-                                               tmp.push( node );
-                               }
-
-                               r = tmp;
-
-                       // Otherwise, find the expression to execute
-                       } else {
-                               var fn = jQuery.expr[ m[1] ];
-                               if ( typeof fn == "object" )
-                                       fn = fn[ m[2] ];
-
-                               if ( typeof fn == "string" )
-                                       fn = eval("false||function(a,i){return " + fn + ";}");
-
-                               // Execute it against the current filter
-                               r = jQuery.grep( r, function(elem, i){
-                                       return fn(elem, i, m, r);
-                               }, not );
-                       }
-               }
-
-               // Return an array of filtered elements (r)
-               // and the modified expression string (t)
-               return { r: r, t: t };
-       },
-
-       dir: function( elem, dir ){
-               var matched = [],
-                       cur = elem[dir];
-               while ( cur && cur != document ) {
-                       if ( cur.nodeType == 1 )
-                               matched.push( cur );
-                       cur = cur[dir];
-               }
-               return matched;
-       },
-
-       nth: function(cur,result,dir,elem){
-               result = result || 1;
-               var num = 0;
-
-               for ( ; cur; cur = cur[dir] )
-                       if ( cur.nodeType == 1 && ++num == result )
-                               break;
-
-               return cur;
-       },
-
-       sibling: function( n, elem ) {
-               var r = [];
-
-               for ( ; n; n = n.nextSibling ) {
-                       if ( n.nodeType == 1 && n != elem )
-                               r.push( n );
-               }
-
-               return r;
-       }
-});
-/*
- * A number of helper functions used for managing events.
- * Many of the ideas behind this code orignated from
- * Dean Edwards' addEvent library.
- */
-jQuery.event = {
-
-       // Bind an event to an element
-       // Original by Dean Edwards
-       add: function(elem, types, handler, data) {
-               if ( elem.nodeType == 3 || elem.nodeType == 8 )
-                       return;
-
-               // For whatever reason, IE has trouble passing the window object
-               // around, causing it to be cloned in the process
-               if ( jQuery.browser.msie && elem.setInterval )
-                       elem = window;
-
-               // Make sure that the function being executed has a unique ID
-               if ( !handler.guid )
-                       handler.guid = this.guid++;
-
-               // if data is passed, bind to handler
-               if( data != undefined ) {
-                       // Create temporary function pointer to original handler
-                       var fn = handler;
-
-                       // Create unique handler function, wrapped around original handler
-                       handler = this.proxy( fn, function() {
-                               // Pass arguments and context to original handler
-                               return fn.apply(this, arguments);
-                       });
-
-                       // Store data in unique handler
-                       handler.data = data;
-               }
-
-               // Init the element's event structure
-               var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
-                       handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
-                               // Handle the second event of a trigger and when
-                               // an event is called after a page has unloaded
-                               if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
-                                       return jQuery.event.handle.apply(arguments.callee.elem, arguments);
-                       });
-               // Add elem as a property of the handle function
-               // This is to prevent a memory leak with non-native
-               // event in IE.
-               handle.elem = elem;
-
-               // Handle multiple events separated by a space
-               // jQuery(...).bind("mouseover mouseout", fn);
-               jQuery.each(types.split(/\s+/), function(index, type) {
-                       // Namespaced event handlers
-                       var parts = type.split(".");
-                       type = parts[0];
-                       handler.type = parts[1];
-
-                       // Get the current list of functions bound to this event
-                       var handlers = events[type];
-
-                       // Init the event handler queue
-                       if (!handlers) {
-                               handlers = events[type] = {};
-
-                               // Check for a special event handler
-                               // Only use addEventListener/attachEvent if the special
-                               // events handler returns false
-                               if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
-                                       // Bind the global event handler to the element
-                                       if (elem.addEventListener)
-                                               elem.addEventListener(type, handle, false);
-                                       else if (elem.attachEvent)
-                                               elem.attachEvent("on" + type, handle);
-                               }
-                       }
-
-                       // Add the function to the element's handler list
-                       handlers[handler.guid] = handler;
-
-                       // Keep track of which events have been used, for global triggering
-                       jQuery.event.global[type] = true;
-               });
-
-               // Nullify elem to prevent memory leaks in IE
-               elem = null;
-       },
-
-       guid: 1,
-       global: {},
-
-       // Detach an event or set of events from an element
-       remove: function(elem, types, handler) {
-               // don't do events on text and comment nodes
-               if ( elem.nodeType == 3 || elem.nodeType == 8 )
-                       return;
-
-               var events = jQuery.data(elem, "events"), ret, index;
-
-               if ( events ) {
-                       // Unbind all events for the element
-                       if ( types == undefined || (typeof types == "string" && types.charAt(0) == ".") )
-                               for ( var type in events )
-                                       this.remove( elem, type + (types || "") );
-                       else {
-                               // types is actually an event object here
-                               if ( types.type ) {
-                                       handler = types.handler;
-                                       types = types.type;
-                               }
-
-                               // Handle multiple events seperated by a space
-                               // jQuery(...).unbind("mouseover mouseout", fn);
-                               jQuery.each(types.split(/\s+/), function(index, type){
-                                       // Namespaced event handlers
-                                       var parts = type.split(".");
-                                       type = parts[0];
-
-                                       if ( events[type] ) {
-                                               // remove the given handler for the given type
-                                               if ( handler )
-                                                       delete events[type][handler.guid];
-
-                                               // remove all handlers for the given type
-                                               else
-                                                       for ( handler in events[type] )
-                                                               // Handle the removal of namespaced events
-                                                               if ( !parts[1] || events[type][handler].type == parts[1] )
-                                                                       delete events[type][handler];
-
-                                               // remove generic event handler if no more handlers exist
-                                               for ( ret in events[type] ) break;
-                                               if ( !ret ) {
-                                                       if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
-                                                               if (elem.removeEventListener)
-                                                                       elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
-                                                               else if (elem.detachEvent)
-                                                                       elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
-                                                       }
-                                                       ret = null;
-                                                       delete events[type];
-                                               }
-                                       }
-                               });
-                       }
-
-                       // Remove the expando if it's no longer used
-                       for ( ret in events ) break;
-                       if ( !ret ) {
-                               var handle = jQuery.data( elem, "handle" );
-                               if ( handle ) handle.elem = null;
-                               jQuery.removeData( elem, "events" );
-                               jQuery.removeData( elem, "handle" );
-                       }
-               }
-       },
-
-       trigger: function(type, data, elem, donative, extra) {
-               // Clone the incoming data, if any
-               data = jQuery.makeArray(data);
-
-               if ( type.indexOf("!") >= 0 ) {
-                       type = type.slice(0, -1);
-                       var exclusive = true;
-               }
-
-               // Handle a global trigger
-               if ( !elem ) {
-                       // Only trigger if we've ever bound an event for it
-                       if ( this.global[type] )
-                               jQuery("*").add([window, document]).trigger(type, data);
-
-               // Handle triggering a single element
-               } else {
-                       // don't do events on text and comment nodes
-                       if ( elem.nodeType == 3 || elem.nodeType == 8 )
-                               return undefined;
-
-                       var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
-                               // Check to see if we need to provide a fake event, or not
-                               event = !data[0] || !data[0].preventDefault;
-
-                       // Pass along a fake event
-                       if ( event ) {
-                               data.unshift({
-                                       type: type,
-                                       target: elem,
-                                       preventDefault: function(){},
-                                       stopPropagation: function(){},
-                                       timeStamp: now()
-                               });
-                               data[0][expando] = true; // no need to fix fake event
-                       }
-
-                       // Enforce the right trigger type
-                       data[0].type = type;
-                       if ( exclusive )
-                               data[0].exclusive = true;
-
-                       // Trigger the event, it is assumed that "handle" is a function
-                       var handle = jQuery.data(elem, "handle");
-                       if ( handle )
-                               val = handle.apply( elem, data );
-
-                       // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
-                       if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
-                               val = false;
-
-                       // Extra functions don't get the custom event object
-                       if ( event )
-                               data.shift();
-
-                       // Handle triggering of extra function
-                       if ( extra && jQuery.isFunction( extra ) ) {
-                               // call the extra function and tack the current return value on the end for possible inspection
-                               ret = extra.apply( elem, val == null ? data : data.concat( val ) );
-                               // if anything is returned, give it precedence and have it overwrite the previous value
-                               if (ret !== undefined)
-                                       val = ret;
-                       }
-
-                       // Trigger the native events (except for clicks on links)
-                       if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
-                               this.triggered = true;
-                               try {
-                                       elem[ type ]();
-                               // prevent IE from throwing an error for some hidden elements
-                               } catch (e) {}
-                       }
-
-                       this.triggered = false;
-               }
-
-               return val;
-       },
-
-       handle: function(event) {
-               // returned undefined or false
-               var val, ret, namespace, all, handlers;
-
-               event = arguments[0] = jQuery.event.fix( event || window.event );
-
-               // Namespaced event handlers
-               namespace = event.type.split(".");
-               event.type = namespace[0];
-               namespace = namespace[1];
-               // Cache this now, all = true means, any handler
-               all = !namespace && !event.exclusive;
-
-               handlers = ( jQuery.data(this, "events") || {} )[event.type];
-
-               for ( var j in handlers ) {
-                       var handler = handlers[j];
-
-                       // Filter the functions by class
-                       if ( all || handler.type == namespace ) {
-                               // Pass in a reference to the handler function itself
-                               // So that we can later remove it
-                               event.handler = handler;
-                               event.data = handler.data;
-
-                               ret = handler.apply( this, arguments );
-
-                               if ( val !== false )
-                                       val = ret;
-
-                               if ( ret === false ) {
-                                       event.preventDefault();
-                                       event.stopPropagation();
-                               }
-                       }
-               }
-
-               return val;
-       },
-
-       fix: function(event) {
-               if ( event[expando] == true )
-                       return event;
-
-               // store a copy of the original event object
-               // and "clone" to set read-only properties
-               var originalEvent = event;
-               event = { originalEvent: originalEvent };
-               var props = "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");
-               for ( var i=props.length; i; i-- )
-                       event[ props[i] ] = originalEvent[ props[i] ];
-
-               // Mark it as fixed
-               event[expando] = true;
-
-               // add preventDefault and stopPropagation since
-               // they will not work on the clone
-               event.preventDefault = function() {
-                       // if preventDefault exists run it on the original event
-                       if (originalEvent.preventDefault)
-                               originalEvent.preventDefault();
-                       // otherwise set the returnValue property of the original event to false (IE)
-                       originalEvent.returnValue = false;
-               };
-               event.stopPropagation = function() {
-                       // if stopPropagation exists run it on the original event
-                       if (originalEvent.stopPropagation)
-                               originalEvent.stopPropagation();
-                       // otherwise set the cancelBubble property of the original event to true (IE)
-                       originalEvent.cancelBubble = true;
-               };
-
-               // Fix timeStamp
-               event.timeStamp = event.timeStamp || now();
-
-               // Fix target property, if necessary
-               if ( !event.target )
-                       event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
-
-               // check if target is a textnode (safari)
-               if ( event.target.nodeType == 3 )
-                       event.target = event.target.parentNode;
-
-               // Add relatedTarget, if necessary
-               if ( !event.relatedTarget && event.fromElement )
-                       event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
-
-               // Calculate pageX/Y if missing and clientX/Y available
-               if ( event.pageX == null && event.clientX != null ) {
-                       var doc = document.documentElement, body = document.body;
-                       event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
-                       event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
-               }
-
-               // Add which for key events
-               if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
-                       event.which = event.charCode || event.keyCode;
-
-               // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
-               if ( !event.metaKey && event.ctrlKey )
-                       event.metaKey = event.ctrlKey;
-
-               // Add which for click: 1 == left; 2 == middle; 3 == right
-               // Note: button is not normalized, so don't use it
-               if ( !event.which && event.button )
-                       event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
-
-               return event;
-       },
-
-       proxy: function( fn, proxy ){
-               // Set the guid of unique handler to the same of original handler, so it can be removed
-               proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
-               // So proxy can be declared as an argument
-               return proxy;
-       },
-
-       special: {
-               ready: {
-                       setup: function() {
-                               // Make sure the ready event is setup
-                               bindReady();
-                               return;
-                       },
-
-                       teardown: function() { return; }
-               },
-
-               mouseenter: {
-                       setup: function() {
-                               if ( jQuery.browser.msie ) return false;
-                               jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
-                               return true;
-                       },
-
-                       teardown: function() {
-                               if ( jQuery.browser.msie ) return false;
-                               jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
-                               return true;
-                       },
-
-                       handler: function(event) {
-                               // If we actually just moused on to a sub-element, ignore it
-                               if ( withinElement(event, this) ) return true;
-                               // Execute the right handlers by setting the event type to mouseenter
-                               event.type = "mouseenter";
-                               return jQuery.event.handle.apply(this, arguments);
-                       }
-               },
-
-               mouseleave: {
-                       setup: function() {
-                               if ( jQuery.browser.msie ) return false;
-                               jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
-                               return true;
-                       },
-
-                       teardown: function() {
-                               if ( jQuery.browser.msie ) return false;
-                               jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
-                               return true;
-                       },
-
-                       handler: function(event) {
-                               // If we actually just moused on to a sub-element, ignore it
-                               if ( withinElement(event, this) ) return true;
-                               // Execute the right handlers by setting the event type to mouseleave
-                               event.type = "mouseleave";
-                               return jQuery.event.handle.apply(this, arguments);
-                       }
-               }
-       }
-};
-
-jQuery.fn.extend({
-       bind: function( type, data, fn ) {
-               return type == "unload" ? this.one(type, data, fn) : this.each(function(){
-                       jQuery.event.add( this, type, fn || data, fn && data );
-               });
-       },
-
-       one: function( type, data, fn ) {
-               var one = jQuery.event.proxy( fn || data, function(event) {
-                       jQuery(this).unbind(event, one);
-                       return (fn || data).apply( this, arguments );
-               });
-               return this.each(function(){
-                       jQuery.event.add( this, type, one, fn && data);
-               });
-       },
-
-       unbind: function( type, fn ) {
-               return this.each(function(){
-                       jQuery.event.remove( this, type, fn );
-               });
-       },
-
-       trigger: function( type, data, fn ) {
-               return this.each(function(){
-                       jQuery.event.trigger( type, data, this, true, fn );
-               });
-       },
-
-       triggerHandler: function( type, data, fn ) {
-               return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
-       },
-
-       toggle: function( fn ) {
-               // Save reference to arguments for access in closure
-               var args = arguments, i = 1;
-
-               // link all the functions, so any of them can unbind this click handler
-               while( i < args.length )
-                       jQuery.event.proxy( fn, args[i++] );
-
-               return this.click( jQuery.event.proxy( fn, function(event) {
-                       // Figure out which function to execute
-                       this.lastToggle = ( this.lastToggle || 0 ) % i;
-
-                       // Make sure that clicks stop
-                       event.preventDefault();
-
-                       // and execute the function
-                       return args[ this.lastToggle++ ].apply( this, arguments ) || false;
-               }));
-       },
-
-       hover: function(fnOver, fnOut) {
-               return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
-       },
-
-       ready: function(fn) {
-               // Attach the listeners
-               bindReady();
-
-               // If the DOM is already ready
-               if ( jQuery.isReady )
-                       // Execute the function immediately
-                       fn.call( document, jQuery );
-
-               // Otherwise, remember the function for later
-               else
-                       // Add the function to the wait list
-                       jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
-
-               return this;
-       }
-});
-
-jQuery.extend({
-       isReady: false,
-       readyList: [],
-       // Handle when the DOM is ready
-       ready: function() {
-               // Make sure that the DOM is not already loaded
-               if ( !jQuery.isReady ) {
-                       // Remember that the DOM is ready
-                       jQuery.isReady = true;
-
-                       // If there are functions bound, to execute
-                       if ( jQuery.readyList ) {
-                               // Execute all of them
-                               jQuery.each( jQuery.readyList, function(){
-                                       this.call( document );
-                               });
-
-                               // Reset the list of functions
-                               jQuery.readyList = null;
-                       }
-
-                       // Trigger any bound ready events
-                       jQuery(document).triggerHandler("ready");
-               }
-       }
-});
-
-var readyBound = false;
-
-function bindReady(){
-       if ( readyBound ) return;
-       readyBound = true;
-
-       // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
-       if ( document.addEventListener && !jQuery.browser.opera)
-               // Use the handy event callback
-               document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
-
-       // If IE is used and is not in a frame
-       // Continually check to see if the document is ready
-       if ( jQuery.browser.msie && window == top ) (function(){
-               if (jQuery.isReady) return;
-               try {
-                       // If IE is used, use the trick by Diego Perini
-                       // http://javascript.nwbox.com/IEContentLoaded/
-                       document.documentElement.doScroll("left");
-               } catch( error ) {
-                       setTimeout( arguments.callee, 0 );
-                       return;
-               }
-               // and execute any waiting functions
-               jQuery.ready();
-       })();
-
-       if ( jQuery.browser.opera )
-               document.addEventListener( "DOMContentLoaded", function () {
-                       if (jQuery.isReady) return;
-                       for (var i = 0; i < document.styleSheets.length; i++)
-                               if (document.styleSheets[i].disabled) {
-                                       setTimeout( arguments.callee, 0 );
-                                       return;
-                               }
-                       // and execute any waiting functions
-                       jQuery.ready();
-               }, false);
-
-       if ( jQuery.browser.safari ) {
-               var numStyles;
-               (function(){
-                       if (jQuery.isReady) return;
-                       if ( document.readyState != "loaded" && document.readyState != "complete" ) {
-                               setTimeout( arguments.callee, 0 );
-                               return;
-                       }
-                       if ( numStyles === undefined )
-                               numStyles = jQuery("style, link[rel=stylesheet]").length;
-                       if ( document.styleSheets.length != numStyles ) {
-                               setTimeout( arguments.callee, 0 );
-                               return;
-                       }
-                       // and execute any waiting functions
-                       jQuery.ready();
-               })();
-       }
-
-       // A fallback to window.onload, that will always work
-       jQuery.event.add( window, "load", jQuery.ready );
-}
-
-jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
-       "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
-       "submit,keydown,keypress,keyup,error").split(","), function(i, name){
-
-       // Handle event binding
-       jQuery.fn[name] = function(fn){
-               return fn ? this.bind(name, fn) : this.trigger(name);
-       };
-});
-
-// Checks if an event happened on an element within another element
-// Used in jQuery.event.special.mouseenter and mouseleave handlers
-var withinElement = function(event, elem) {
-       // Check if mouse(over|out) are still within the same parent element
-       var parent = event.relatedTarget;
-       // Traverse up the tree
-       while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
-       // Return true if we actually just moused on to a sub-element
-       return parent == elem;
-};
-
-// Prevent memory leaks in IE
-// And prevent errors on refresh with events like mouseover in other browsers
-// Window isn't included so as not to unbind existing unload events
-jQuery(window).bind("unload", function() {
-       jQuery("*").add(document).unbind();
-});
-jQuery.fn.extend({
-       // Keep a copy of the old load
-       _load: jQuery.fn.load,
-
-       load: function( url, params, callback ) {
-               if ( typeof url != 'string' )
-                       return this._load( url );
-
-               var off = url.indexOf(" ");
-               if ( off >= 0 ) {
-                       var selector = url.slice(off, url.length);
-                       url = url.slice(0, off);
-               }
-
-               callback = callback || function(){};
-
-               // Default to a GET request
-               var type = "GET";
-
-               // If the second parameter was provided
-               if ( params )
-                       // If it's a function
-                       if ( jQuery.isFunction( params ) ) {
-                               // We assume that it's the callback
-                               callback = params;
-                               params = null;
-
-                       // Otherwise, build a param string
-                       } else {
-                               params = jQuery.param( params );
-                               type = "POST";
-                       }
-
-               var self = this;
-
-               // Request the remote document
-               jQuery.ajax({
-                       url: url,
-                       type: type,
-                       dataType: "html",
-                       data: params,
-                       complete: function(res, status){
-                               // If successful, inject the HTML into all the matched elements
-                               if ( status == "success" || status == "notmodified" )
-                                       // See if a selector was specified
-                                       self.html( selector ?
-                                               // Create a dummy div to hold the results
-                                               jQuery("<div/>")
-                                                       // inject the contents of the document in, removing the scripts
-                                                       // to avoid any 'Permission Denied' errors in IE
-                                                       .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
-
-                                                       // Locate the specified elements
-                                                       .find(selector) :
-
-                                               // If not, just inject the full result
-                                               res.responseText );
-
-                               self.each( callback, [res.responseText, status, res] );
-                       }
-               });
-               return this;
-       },
-
-       serialize: function() {
-               return jQuery.param(this.serializeArray());
-       },
-       serializeArray: function() {
-               return this.map(function(){
-                       return jQuery.nodeName(this, "form") ?
-                               jQuery.makeArray(this.elements) : this;
-               })
-               .filter(function(){
-                       return this.name && !this.disabled &&
-                               (this.checked || /select|textarea/i.test(this.nodeName) ||
-                                       /text|hidden|password/i.test(this.type));
-               })
-               .map(function(i, elem){
-                       var val = jQuery(this).val();
-                       return val == null ? null :
-                               val.constructor == Array ?
-                                       jQuery.map( val, function(val, i){
-                                               return {name: elem.name, value: val};
-                                       }) :
-                                       {name: elem.name, value: val};
-               }).get();
-       }
-});
-
-// Attach a bunch of functions for handling common AJAX events
-jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
-       jQuery.fn[o] = function(f){
-               return this.bind(o, f);
-       };
-});
-
-var jsc = now();
-
-jQuery.extend({
-       get: function( url, data, callback, type ) {
-               // shift arguments if data argument was ommited
-               if ( jQuery.isFunction( data ) ) {
-                       callback = data;
-                       data = null;
-               }
-
-               return jQuery.ajax({
-                       type: "GET",
-                       url: url,
-                       data: data,
-                       success: callback,
-                       dataType: type
-               });
-       },
-
-       getScript: function( url, callback ) {
-               return jQuery.get(url, null, callback, "script");
-       },
-
-       getJSON: function( url, data, callback ) {
-               return jQuery.get(url, data, callback, "json");
-       },
-
-       post: function( url, data, callback, type ) {
-               if ( jQuery.isFunction( data ) ) {
-                       callback = data;
-                       data = {};
-               }
-
-               return jQuery.ajax({
-                       type: "POST",
-                       url: url,
-                       data: data,
-                       success: callback,
-                       dataType: type
-               });
-       },
-
-       ajaxSetup: function( settings ) {
-               jQuery.extend( jQuery.ajaxSettings, settings );
-       },
-
-       ajaxSettings: {
-               url: location.href,
-               global: true,
-               type: "GET",
-               timeout: 0,
-               contentType: "application/x-www-form-urlencoded",
-               processData: true,
-               async: true,
-               data: null,
-               username: null,
-               password: null,
-               accepts: {
-                       xml: "application/xml, text/xml",
-                       html: "text/html",
-                       script: "text/javascript, application/javascript",
-                       json: "application/json, text/javascript",
-                       text: "text/plain",
-                       _default: "*/*"
-               }
-       },
-
-       // Last-Modified header cache for next request
-       lastModified: {},
-
-       ajax: function( s ) {
-               // Extend the settings, but re-extend 's' so that it can be
-               // checked again later (in the test suite, specifically)
-               s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
-
-               var jsonp, jsre = /=\?(&|$)/g, status, data,
-                       type = s.type.toUpperCase();
-
-               // convert data if not already a string
-               if ( s.data && s.processData && typeof s.data != "string" )
-                       s.data = jQuery.param(s.data);
-
-               // Handle JSONP Parameter Callbacks
-               if ( s.dataType == "jsonp" ) {
-                       if ( type == "GET" ) {
-                               if ( !s.url.match(jsre) )
-                                       s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
-                       } else if ( !s.data || !s.data.match(jsre) )
-                               s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
-                       s.dataType = "json";
-               }
-
-               // Build temporary JSONP function
-               if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
-                       jsonp = "jsonp" + jsc++;
-
-                       // Replace the =? sequence both in the query string and the data
-                       if ( s.data )
-                               s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
-                       s.url = s.url.replace(jsre, "=" + jsonp + "$1");
-
-                       // We need to make sure
-                       // that a JSONP style response is executed properly
-                       s.dataType = "script";
-
-                       // Handle JSONP-style loading
-                       window[ jsonp ] = function(tmp){
-                               data = tmp;
-                               success();
-                               complete();
-                               // Garbage collect
-                               window[ jsonp ] = undefined;
-                               try{ delete window[ jsonp ]; } catch(e){}
-                               if ( head )
-                                       head.removeChild( script );
-                       };
-               }
-
-               if ( s.dataType == "script" && s.cache == null )
-                       s.cache = false;
-
-               if ( s.cache === false && type == "GET" ) {
-                       var ts = now();
-                       // try replacing _= if it is there
-                       var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
-                       // if nothing was replaced, add timestamp to the end
-                       s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
-               }
-
-               // If data is available, append data to url for get requests
-               if ( s.data && type == "GET" ) {
-                       s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
-
-                       // IE likes to send both get and post data, prevent this
-                       s.data = null;
-               }
-
-               // Watch for a new set of requests
-               if ( s.global && ! jQuery.active++ )
-                       jQuery.event.trigger( "ajaxStart" );
-
-               // Matches an absolute URL, and saves the domain
-               var remote = /^(?:\w+:)?\/\/([^\/?#]+)/;
-
-               // If we're requesting a remote document
-               // and trying to load JSON or Script with a GET
-               if ( s.dataType == "script" && type == "GET"
-                               && remote.test(s.url) && remote.exec(s.url)[1] != location.host ){
-                       var head = document.getElementsByTagName("head")[0];
-                       var script = document.createElement("script");
-                       script.src = s.url;
-                       if (s.scriptCharset)
-                               script.charset = s.scriptCharset;
-
-                       // Handle Script loading
-                       if ( !jsonp ) {
-                               var done = false;
-
-                               // Attach handlers for all browsers
-                               script.onload = script.onreadystatechange = function(){
-                                       if ( !done && (!this.readyState ||
-                                                       this.readyState == "loaded" || this.readyState == "complete") ) {
-                                               done = true;
-                                               success();
-                                               complete();
-                                               head.removeChild( script );
-                                       }
-                               };
-                       }
-
-                       head.appendChild(script);
-
-                       // We handle everything using the script element injection
-                       return undefined;
-               }
-
-               var requestDone = false;
-
-               // Create the request object; Microsoft failed to properly
-               // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
-               var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
-
-               // Open the socket
-               // Passing null username, generates a login popup on Opera (#2865)
-               if( s.username )
-                       xhr.open(type, s.url, s.async, s.username, s.password);
-               else
-                       xhr.open(type, s.url, s.async);
-
-               // Need an extra try/catch for cross domain requests in Firefox 3
-               try {
-                       // Set the correct header, if data is being sent
-                       if ( s.data )
-                               xhr.setRequestHeader("Content-Type", s.contentType);
-
-                       // Set the If-Modified-Since header, if ifModified mode.
-                       if ( s.ifModified )
-                               xhr.setRequestHeader("If-Modified-Since",
-                                       jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
-
-                       // Set header so the called script knows that it's an XMLHttpRequest
-                       xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
-
-                       // Set the Accepts header for the server, depending on the dataType
-                       xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
-                               s.accepts[ s.dataType ] + ", */*" :
-                               s.accepts._default );
-               } catch(e){}
-
-               // Allow custom headers/mimetypes
-               if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
-                       // cleanup active request counter
-                       s.global && jQuery.active--;
-                       // close opended socket
-                       xhr.abort();
-                       return false;
-               }
-
-               if ( s.global )
-                       jQuery.event.trigger("ajaxSend", [xhr, s]);
-
-               // Wait for a response to come back
-               var onreadystatechange = function(isTimeout){
-                       // The transfer is complete and the data is available, or the request timed out
-                       if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
-                               requestDone = true;
-
-                               // clear poll interval
-                               if (ival) {
-                                       clearInterval(ival);
-                                       ival = null;
-                               }
-
-                               status = isTimeout == "timeout" && "timeout" ||
-                                       !jQuery.httpSuccess( xhr ) && "error" ||
-                                       s.ifModified && jQuery.httpNotModified( xhr, s.url ) && "notmodified" ||
-                                       "success";
-
-                               if ( status == "success" ) {
-                                       // Watch for, and catch, XML document parse errors
-                                       try {
-                                               // process the data (runs the xml through httpData regardless of callback)
-                                               data = jQuery.httpData( xhr, s.dataType, s.dataFilter );
-                                       } catch(e) {
-                                               status = "parsererror";
-                                       }
-                               }
-
-                               // Make sure that the request was successful or notmodified
-                               if ( status == "success" ) {
-                                       // Cache Last-Modified header, if ifModified mode.
-                                       var modRes;
-                                       try {
-                                               modRes = xhr.getResponseHeader("Last-Modified");
-                                       } catch(e) {} // swallow exception thrown by FF if header is not available
-
-                                       if ( s.ifModified && modRes )
-                                               jQuery.lastModified[s.url] = modRes;
-
-                                       // JSONP handles its own success callback
-                                       if ( !jsonp )
-                                               success();
-                               } else
-                                       jQuery.handleError(s, xhr, status);
-
-                               // Fire the complete handlers
-                               complete();
-
-                               // Stop memory leaks
-                               if ( s.async )
-                                       xhr = null;
-                       }
-               };
-
-               if ( s.async ) {
-                       // don't attach the handler to the request, just poll it instead
-                       var ival = setInterval(onreadystatechange, 13);
-
-                       // Timeout checker
-                       if ( s.timeout > 0 )
-                               setTimeout(function(){
-                                       // Check to see if the request is still happening
-                                       if ( xhr ) {
-                                               // Cancel the request
-                                               xhr.abort();
-
-                                               if( !requestDone )
-                                                       onreadystatechange( "timeout" );
-                                       }
-                               }, s.timeout);
-               }
-
-               // Send the data
-               try {
-                       xhr.send(s.data);
-               } catch(e) {
-                       jQuery.handleError(s, xhr, null, e);
-               }
-
-               // firefox 1.5 doesn't fire statechange for sync requests
-               if ( !s.async )
-                       onreadystatechange();
-
-               function success(){
-                       // If a local callback was specified, fire it and pass it the data
-                       if ( s.success )
-                               s.success( data, status );
-
-                       // Fire the global callback
-                       if ( s.global )
-                               jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
-               }
-
-               function complete(){
-                       // Process result
-                       if ( s.complete )
-                               s.complete(xhr, status);
-
-                       // The request was completed
-                       if ( s.global )
-                               jQuery.event.trigger( "ajaxComplete", [xhr, s] );
-
-                       // Handle the global AJAX counter
-                       if ( s.global && ! --jQuery.active )
-                               jQuery.event.trigger( "ajaxStop" );
-               }
-
-               // return XMLHttpRequest to allow aborting the request etc.
-               return xhr;
-       },
-
-       handleError: function( s, xhr, status, e ) {
-               // If a local callback was specified, fire it
-               if ( s.error ) s.error( xhr, status, e );
-
-               // Fire the global callback
-               if ( s.global )
-                       jQuery.event.trigger( "ajaxError", [xhr, s, e] );
-       },
-
-       // Counter for holding the number of active queries
-       active: 0,
-
-       // Determines if an XMLHttpRequest was successful or not
-       httpSuccess: function( xhr ) {
-               try {
-                       // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
-                       return !xhr.status && location.protocol == "file:" ||
-                               ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 ||
-                               jQuery.browser.safari && xhr.status == undefined;
-               } catch(e){}
-               return false;
-       },
-
-       // Determines if an XMLHttpRequest returns NotModified
-       httpNotModified: function( xhr, url ) {
-               try {
-                       var xhrRes = xhr.getResponseHeader("Last-Modified");
-
-                       // Firefox always returns 200. check Last-Modified date
-                       return xhr.status == 304 || xhrRes == jQuery.lastModified[url] ||
-                               jQuery.browser.safari && xhr.status == undefined;
-               } catch(e){}
-               return false;
-       },
-
-       httpData: function( xhr, type, filter ) {
-               var ct = xhr.getResponseHeader("content-type"),
-                       xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
-                       data = xml ? xhr.responseXML : xhr.responseText;
-
-               if ( xml && data.documentElement.tagName == "parsererror" )
-                       throw "parsererror";
-                       
-               // Allow a pre-filtering function to sanitize the response
-               if( filter )
-                       data = filter( data, type );
-
-               // If the type is "script", eval it in global context
-               if ( type == "script" )
-                       jQuery.globalEval( data );
-
-               // Get the JavaScript object, if JSON is used.
-               if ( type == "json" )
-                       data = eval("(" + data + ")");
-
-               return data;
-       },
-
-       // Serialize an array of form elements or a set of
-       // key/values into a query string
-       param: function( a ) {
-               var s = [];
-
-               // If an array was passed in, assume that it is an array
-               // of form elements
-               if ( a.constructor == Array || a.jquery )
-                       // Serialize the form elements
-                       jQuery.each( a, function(){
-                               s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
-                       });
-
-               // Otherwise, assume that it's an object of key/value pairs
-               else
-                       // Serialize the key/values
-                       for ( var j in a )
-                               // If the value is an array then the key names need to be repeated
-                               if ( a[j] && a[j].constructor == Array )
-                                       jQuery.each( a[j], function(){
-                                               s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
-                                       });
-                               else
-                                       s.push( encodeURIComponent(j) + "=" + encodeURIComponent( jQuery.isFunction(a[j]) ? a[j]() : a[j] ) );
-
-               // Return the resulting serialization
-               return s.join("&").replace(/%20/g, "+");
-       }
-
-});
-jQuery.fn.extend({
-       show: function(speed,callback){
-               return speed ?
-                       this.animate({
-                               height: "show", width: "show", opacity: "show"
-                       }, speed, callback) :
-
-                       this.filter(":hidden").each(function(){
-                               this.style.display = this.oldblock || "";
-                               if ( jQuery.css(this,"display") == "none" ) {
-                                       var elem = jQuery("<" + this.tagName + " />").appendTo("body");
-                                       this.style.display = elem.css("display");
-                                       // handle an edge condition where css is - div { display:none; } or similar
-                                       if (this.style.display == "none")
-                                               this.style.display = "block";
-                                       elem.remove();
-                               }
-                       }).end();
-       },
-
-       hide: function(speed,callback){
-               return speed ?
-                       this.animate({
-                               height: "hide", width: "hide", opacity: "hide"
-                       }, speed, callback) :
-
-                       this.filter(":visible").each(function(){
-                               this.oldblock = this.oldblock || jQuery.css(this,"display");
-                               this.style.display = "none";
-                       }).end();
-       },
-
-       // Save the old toggle function
-       _toggle: jQuery.fn.toggle,
-
-       toggle: function( fn, fn2 ){
-               return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
-                       this._toggle.apply( this, arguments ) :
-                       fn ?
-                               this.animate({
-                                       height: "toggle", width: "toggle", opacity: "toggle"
-                               }, fn, fn2) :
-                               this.each(function(){
-                                       jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
-                               });
-       },
-
-       slideDown: function(speed,callback){
-               return this.animate({height: "show"}, speed, callback);
-       },
-
-       slideUp: function(speed,callback){
-               return this.animate({height: "hide"}, speed, callback);
-       },
-
-       slideToggle: function(speed, callback){
-               return this.animate({height: "toggle"}, speed, callback);
-       },
-
-       fadeIn: function(speed, callback){
-               return this.animate({opacity: "show"}, speed, callback);
-       },
-
-       fadeOut: function(speed, callback){
-               return this.animate({opacity: "hide"}, speed, callback);
-       },
-
-       fadeTo: function(speed,to,callback){
-               return this.animate({opacity: to}, speed, callback);
-       },
-
-       animate: function( prop, speed, easing, callback ) {
-               var optall = jQuery.speed(speed, easing, callback);
-
-               return this[ optall.queue === false ? "each" : "queue" ](function(){
-                       if ( this.nodeType != 1)
-                               return false;
-
-                       var opt = jQuery.extend({}, optall), p,
-                               hidden = jQuery(this).is(":hidden"), self = this;
-
-                       for ( p in prop ) {
-                               if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
-                                       return opt.complete.call(this);
-
-                               if ( p == "height" || p == "width" ) {
-                                       // Store display property
-                                       opt.display = jQuery.css(this, "display");
-
-                                       // Make sure that nothing sneaks out
-                                       opt.overflow = this.style.overflow;
-                               }
-                       }
-
-                       if ( opt.overflow != null )
-                               this.style.overflow = "hidden";
-
-                       opt.curAnim = jQuery.extend({}, prop);
-
-                       jQuery.each( prop, function(name, val){
-                               var e = new jQuery.fx( self, opt, name );
-
-                               if ( /toggle|show|hide/.test(val) )
-                                       e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
-                               else {
-                                       var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
-                                               start = e.cur(true) || 0;
-
-                                       if ( parts ) {
-                                               var end = parseFloat(parts[2]),
-                                                       unit = parts[3] || "px";
-
-                                               // We need to compute starting value
-                                               if ( unit != "px" ) {
-                                                       self.style[ name ] = (end || 1) + unit;
-                                                       start = ((end || 1) / e.cur(true)) * start;
-                                                       self.style[ name ] = start + unit;
-                                               }
-
-                                               // If a +=/-= token was provided, we're doing a relative animation
-                                               if ( parts[1] )
-                                                       end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
-
-                                               e.custom( start, end, unit );
-                                       } else
-                                               e.custom( start, val, "" );
-                               }
-                       });
-
-                       // For JS strict compliance
-                       return true;
-               });
-       },
-
-       queue: function(type, fn){
-               if ( jQuery.isFunction(type) || ( type && type.constructor == Array )) {
-                       fn = type;
-                       type = "fx";
-               }
-
-               if ( !type || (typeof type == "string" && !fn) )
-                       return queue( this[0], type );
-
-               return this.each(function(){
-                       if ( fn.constructor == Array )
-                               queue(this, type, fn);
-                       else {
-                               queue(this, type).push( fn );
-
-                               if ( queue(this, type).length == 1 )
-                                       fn.call(this);
-                       }
-               });
-       },
-
-       stop: function(clearQueue, gotoEnd){
-               var timers = jQuery.timers;
-
-               if (clearQueue)
-                       this.queue([]);
-
-               this.each(function(){
-                       // go in reverse order so anything added to the queue during the loop is ignored
-                       for ( var i = timers.length - 1; i >= 0; i-- )
-                               if ( timers[i].elem == this ) {
-                                       if (gotoEnd)
-                                               // force the next step to be the last
-                                               timers[i](true);
-                                       timers.splice(i, 1);
-                               }
-               });
-
-               // start the next in the queue if the last step wasn't forced
-               if (!gotoEnd)
-                       this.dequeue();
-
-               return this;
-       }
-
-});
-
-var queue = function( elem, type, array ) {
-       if ( elem ){
-
-               type = type || "fx";
-
-               var q = jQuery.data( elem, type + "queue" );
-
-               if ( !q || array )
-                       q = jQuery.data( elem, type + "queue", jQuery.makeArray(array) );
-
-       }
-       return q;
-};
-
-jQuery.fn.dequeue = function(type){
-       type = type || "fx";
-
-       return this.each(function(){
-               var q = queue(this, type);
-
-               q.shift();
-
-               if ( q.length )
-                       q[0].call( this );
-       });
-};
-
-jQuery.extend({
-
-       speed: function(speed, easing, fn) {
-               var opt = speed && speed.constructor == Object ? speed : {
-                       complete: fn || !fn && easing ||
-                               jQuery.isFunction( speed ) && speed,
-                       duration: speed,
-                       easing: fn && easing || easing && easing.constructor != Function && easing
-               };
-
-               opt.duration = (opt.duration && opt.duration.constructor == Number ?
-                       opt.duration :
-                       jQuery.fx.speeds[opt.duration]) || jQuery.fx.speeds.def;
-
-               // Queueing
-               opt.old = opt.complete;
-               opt.complete = function(){
-                       if ( opt.queue !== false )
-                               jQuery(this).dequeue();
-                       if ( jQuery.isFunction( opt.old ) )
-                               opt.old.call( this );
-               };
-
-               return opt;
-       },
-
-       easing: {
-               linear: function( p, n, firstNum, diff ) {
-                       return firstNum + diff * p;
-               },
-               swing: function( p, n, firstNum, diff ) {
-                       return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
-               }
-       },
-
-       timers: [],
-       timerId: null,
-
-       fx: function( elem, options, prop ){
-               this.options = options;
-               this.elem = elem;
-               this.prop = prop;
-
-               if ( !options.orig )
-                       options.orig = {};
-       }
-
-});
-
-jQuery.fx.prototype = {
-
-       // Simple function for setting a style value
-       update: function(){
-               if ( this.options.step )
-                       this.options.step.call( this.elem, this.now, this );
-
-               (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
-
-               // Set display property to block for height/width animations
-               if ( this.prop == "height" || this.prop == "width" )
-                       this.elem.style.display = "block";
-       },
-
-       // Get the current size
-       cur: function(force){
-               if ( this.elem[this.prop] != null && this.elem.style[this.prop] == null )
-                       return this.elem[ this.prop ];
-
-               var r = parseFloat(jQuery.css(this.elem, this.prop, force));
-               return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
-       },
-
-       // Start an animation from one number to another
-       custom: function(from, to, unit){
-               this.startTime = now();
-               this.start = from;
-               this.end = to;
-               this.unit = unit || this.unit || "px";
-               this.now = this.start;
-               this.pos = this.state = 0;
-               this.update();
-
-               var self = this;
-               function t(gotoEnd){
-                       return self.step(gotoEnd);
-               }
-
-               t.elem = this.elem;
-
-               jQuery.timers.push(t);
-
-               if ( jQuery.timerId == null ) {
-                       jQuery.timerId = setInterval(function(){
-                               var timers = jQuery.timers;
-
-                               for ( var i = 0; i < timers.length; i++ )
-                                       if ( !timers[i]() )
-                                               timers.splice(i--, 1);
-
-                               if ( !timers.length ) {
-                                       clearInterval( jQuery.timerId );
-                                       jQuery.timerId = null;
-                               }
-                       }, 13);
-               }
-       },
-
-       // Simple 'show' function
-       show: function(){
-               // Remember where we started, so that we can go back to it later
-               this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
-               this.options.show = true;
-
-               // Begin the animation
-               this.custom(0, this.cur());
-
-               // Make sure that we start at a small width/height to avoid any
-               // flash of content
-               if ( this.prop == "width" || this.prop == "height" )
-                       this.elem.style[this.prop] = "1px";
-
-               // Start by showing the element
-               jQuery(this.elem).show();
-       },
-
-       // Simple 'hide' function
-       hide: function(){
-               // Remember where we started, so that we can go back to it later
-               this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
-               this.options.hide = true;
-
-               // Begin the animation
-               this.custom(this.cur(), 0);
-       },
-
-       // Each step of an animation
-       step: function(gotoEnd){
-               var t = now();
-
-               if ( gotoEnd || t > this.options.duration + this.startTime ) {
-                       this.now = this.end;
-                       this.pos = this.state = 1;
-                       this.update();
-
-                       this.options.curAnim[ this.prop ] = true;
-
-                       var done = true;
-                       for ( var i in this.options.curAnim )
-                               if ( this.options.curAnim[i] !== true )
-                                       done = false;
-
-                       if ( done ) {
-                               if ( this.options.display != null ) {
-                                       // Reset the overflow
-                                       this.elem.style.overflow = this.options.overflow;
-
-                                       // Reset the display
-                                       this.elem.style.display = this.options.display;
-                                       if ( jQuery.css(this.elem, "display") == "none" )
-                                               this.elem.style.display = "block";
-                               }
-
-                               // Hide the element if the "hide" operation was done
-                               if ( this.options.hide )
-                                       this.elem.style.display = "none";
-
-                               // Reset the properties, if the item has been hidden or shown
-                               if ( this.options.hide || this.options.show )
-                                       for ( var p in this.options.curAnim )
-                                               jQuery.attr(this.elem.style, p, this.options.orig[p]);
-                       }
-
-                       if ( done )
-                               // Execute the complete function
-                               this.options.complete.call( this.elem );
-
-                       return false;
-               } else {
-                       var n = t - this.startTime;
-                       this.state = n / this.options.duration;
-
-                       // Perform the easing function, defaults to swing
-                       this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
-                       this.now = this.start + ((this.end - this.start) * this.pos);
-
-                       // Perform the next step of the animation
-                       this.update();
-               }
-
-               return true;
-       }
-
-};
-
-jQuery.extend( jQuery.fx, {
-       speeds:{
-               slow: 600,
-               fast: 200,
-               // Default speed
-               def: 400
-       },
-       step: {
-               scrollLeft: function(fx){
-                       fx.elem.scrollLeft = fx.now;
-               },
-
-               scrollTop: function(fx){
-                       fx.elem.scrollTop = fx.now;
-               },
-
-               opacity: function(fx){
-                       jQuery.attr(fx.elem.style, "opacity", fx.now);
-               },
-
-               _default: function(fx){
-                       fx.elem.style[ fx.prop ] = fx.now + fx.unit;
-               }
-       }
-});
-// The Offset Method
-// Originally By Brandon Aaron, part of the Dimension Plugin
-// http://jquery.com/plugins/project/dimensions
-jQuery.fn.offset = function() {
-       var left = 0, top = 0, elem = this[0], results;
-
-       if ( elem ) with ( jQuery.browser ) {
-               var parent       = elem.parentNode,
-                   offsetChild  = elem,
-                   offsetParent = elem.offsetParent,
-                   doc          = elem.ownerDocument,
-                   safari2      = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
-                   css          = jQuery.curCSS,
-                   fixed        = css(elem, "position") == "fixed";
-
-               // Use getBoundingClientRect if available
-               if ( elem.getBoundingClientRect ) {
-                       var box = elem.getBoundingClientRect();
-
-                       // Add the document scroll offsets
-                       add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
-                               box.top  + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
-
-                       // IE adds the HTML element's border, by default it is medium which is 2px
-                       // IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
-                       // IE 7 standards mode, the border is always 2px
-                       // This border/offset is typically represented by the clientLeft and clientTop properties
-                       // However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
-                       // Therefore this method will be off by 2px in IE while in quirksmode
-                       add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );
-
-               // Otherwise loop through the offsetParents and parentNodes
-               } else {
-
-                       // Initial element offsets
-                       add( elem.offsetLeft, elem.offsetTop );
-
-                       // Get parent offsets
-                       while ( offsetParent ) {
-                               // Add offsetParent offsets
-                               add( offsetParent.offsetLeft, offsetParent.offsetTop );
-
-                               // Mozilla and Safari > 2 does not include the border on offset parents
-                               // However Mozilla adds the border for table or table cells
-                               if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
-                                       border( offsetParent );
-
-                               // Add the document scroll offsets if position is fixed on any offsetParent
-                               if ( !fixed && css(offsetParent, "position") == "fixed" )
-                                       fixed = true;
-
-                               // Set offsetChild to previous offsetParent unless it is the body element
-                               offsetChild  = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
-                               // Get next offsetParent
-                               offsetParent = offsetParent.offsetParent;
-                       }
-
-                       // Get parent scroll offsets
-                       while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
-                               // Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
-                               if ( !/^inline|table.*$/i.test(css(parent, "display")) )
-                                       // Subtract parent scroll offsets
-                                       add( -parent.scrollLeft, -parent.scrollTop );
-
-                               // Mozilla does not add the border for a parent that has overflow != visible
-                               if ( mozilla && css(parent, "overflow") != "visible" )
-                                       border( parent );
-
-                               // Get next parent
-                               parent = parent.parentNode;
-                       }
-
-                       // Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
-                       // Mozilla doubles body offsets with a non-absolutely positioned offsetChild
-                       if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
-                               (mozilla && css(offsetChild, "position") != "absolute") )
-                                       add( -doc.body.offsetLeft, -doc.body.offsetTop );
-
-                       // Add the document scroll offsets if position is fixed
-                       if ( fixed )
-                               add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
-                                       Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
-               }
-
-               // Return an object with top and left properties
-               results = { top: top, left: left };
-       }
-
-       function border(elem) {
-               add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
-       }
-
-       function add(l, t) {
-               left += parseInt(l, 10) || 0;
-               top += parseInt(t, 10) || 0;
-       }
-
-       return results;
-};
-
-
-jQuery.fn.extend({
-       position: function() {
-               var left = 0, top = 0, results;
-
-               if ( this[0] ) {
-                       // Get *real* offsetParent
-                       var offsetParent = this.offsetParent(),
-
-                       // Get correct offsets
-                       offset       = this.offset(),
-                       parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
-
-                       // Subtract element margins
-                       // note: when an element has margin: auto the offsetLeft and marginLeft 
-                       // are the same in Safari causing offset.left to incorrectly be 0
-                       offset.top  -= num( this, 'marginTop' );
-                       offset.left -= num( this, 'marginLeft' );
-
-                       // Add offsetParent borders
-                       parentOffset.top  += num( offsetParent, 'borderTopWidth' );
-                       parentOffset.left += num( offsetParent, 'borderLeftWidth' );
-
-                       // Subtract the two offsets
-                       results = {
-                               top:  offset.top  - parentOffset.top,
-                               left: offset.left - parentOffset.left
-                       };
-               }
-
-               return results;
-       },
-
-       offsetParent: function() {
-               var offsetParent = this[0].offsetParent;
-               while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
-                       offsetParent = offsetParent.offsetParent;
-               return jQuery(offsetParent);
-       }
-});
-
-
-// Create scrollLeft and scrollTop methods
-jQuery.each( ['Left', 'Top'], function(i, name) {
-       var method = 'scroll' + name;
-       
-       jQuery.fn[ method ] = function(val) {
-               if (!this[0]) return;
-
-               return val != undefined ?
-
-                       // Set the scroll offset
-                       this.each(function() {
-                               this == window || this == document ?
-                                       window.scrollTo(
-                                               !i ? val : jQuery(window).scrollLeft(),
-                                                i ? val : jQuery(window).scrollTop()
-                                       ) :
-                                       this[ method ] = val;
-                       }) :
-
-                       // Return the scroll offset
-                       this[0] == window || this[0] == document ?
-                               self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
-                                       jQuery.boxModel && document.documentElement[ method ] ||
-                                       document.body[ method ] :
-                               this[0][ method ];
-       };
-});
-// Create innerHeight, innerWidth, outerHeight and outerWidth methods
-jQuery.each([ "Height", "Width" ], function(i, name){
-
-       var tl = i ? "Left"  : "Top",  // top or left
-               br = i ? "Right" : "Bottom"; // bottom or right
-
-       // innerHeight and innerWidth
-       jQuery.fn["inner" + name] = function(){
-               return this[ name.toLowerCase() ]() +
-                       num(this, "padding" + tl) +
-                       num(this, "padding" + br);
-       };
-
-       // outerHeight and outerWidth
-       jQuery.fn["outer" + name] = function(margin) {
-               return this["inner" + name]() +
-                       num(this, "border" + tl + "Width") +
-                       num(this, "border" + br + "Width") +
-                       (margin ?
-                               num(this, "margin" + tl) + num(this, "margin" + br) : 0);
-       };
-
-});})();
diff --git a/ui/lib/soundmanager2.js b/ui/lib/soundmanager2.js
deleted file mode 100755 (executable)
index 216115c..0000000
+++ /dev/null
@@ -1,1247 +0,0 @@
-/*!\r
-   SoundManager 2: Javascript Sound for the Web\r
-   --------------------------------------------\r
-   http://schillmania.com/projects/soundmanager2/\r
-\r
-   Copyright (c) 2008, Scott Schiller. All rights reserved.\r
-   Code licensed under the BSD License:\r
-   http://schillmania.com/projects/soundmanager2/license.txt\r
-\r
-   V2.90a.20081028\r
-*/\r
-\r
-function SoundManager(smURL,smID) {\r
\r
-  this.flashVersion = 8;           // version of flash to require, either 8 or 9. Some API features require Flash 9.\r
-  this.debugMode = true;           // enable debugging output (div#soundmanager-debug, OR console if available + configured)\r
-  this.useConsole = true;          // use firebug/safari console.log()-type debug console if available\r
-  this.consoleOnly = false;        // if console is being used, do not create/write to #soundmanager-debug\r
-  this.waitForWindowLoad = false;  // force SM2 to wait for window.onload() before trying to call soundManager.onload()\r
-  this.nullURL = 'null.mp3';       // path to "null" (empty) MP3 file, used to unload sounds (Flash 8 only)\r
-  this.allowPolling = true;        // allow flash to poll for status update (required for "while playing", peak, sound spectrum functions to work.)\r
-  this.useMovieStar = false;      // enable support for Flash 9.0r115+ (codename "MovieStar") MPEG4 audio + video formats (AAC, M4V, FLV, MOV etc.)\r
-  this.useHighPerformance = true;  // flash positioning trick, improves JS/flash callback speed, minimizes delay\r
-  this.bgColor = '#ffffff';       // movie (.swf) background color, useful if showing on-screen for video etc.\r
-\r
-  this.defaultOptions = {\r
-    'autoLoad': false,             // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can)\r
-    'stream': true,                // allows playing before entire file has loaded (recommended)\r
-    'autoPlay': false,             // enable playing of file as soon as possible (much faster if "stream" is true)\r
-    'onid3': null,                 // callback function for "ID3 data is added/available"\r
-    'onload': null,                // callback function for "load finished"\r
-    'whileloading': null,          // callback function for "download progress update" (X of Y bytes received)\r
-    'onplay': null,                // callback for "play" start\r
-    'onpause': null,               // callback for "pause"\r
-    'onresume': null,              // callback for "resume" (pause toggle)\r
-    'whileplaying': null,          // callback during play (position update)\r
-    'onstop': null,                // callback for "user stop"\r
-    'onfinish': null,              // callback function for "sound finished playing"\r
-    'onbeforefinish': null,        // callback for "before sound finished playing (at [time])"\r
-    'onbeforefinishtime': 5000,    // offset (milliseconds) before end of sound to trigger beforefinish (eg. 1000 msec = 1 second)\r
-    'onbeforefinishcomplete':null, // function to call when said sound finishes playing\r
-    'onjustbeforefinish':null,     // callback for [n] msec before end of current sound\r
-    'onjustbeforefinishtime':200,  // [n] - if not using, set to 0 (or null handler) and event will not fire.\r
-    'multiShot': true,             // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time\r
-    'position': null,              // offset (milliseconds) to seek to within loaded sound data.\r
-    'pan': 0,                      // "pan" settings, left-to-right, -100 to 100\r
-    'volume': 100                  // self-explanatory. 0-100, the latter being the max.\r
-  };\r
-\r
-  this.flash9Options = {           // flash 9-only options, merged into defaultOptions if flash 9 is being used\r
-    'isMovieStar': null,          // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL\r
-    'usePeakData': false,          // enable left/right channel peak (level) data\r
-    'useWaveformData': false,      // enable sound spectrum (raw waveform data) - WARNING: CPU-INTENSIVE: may set CPUs on fire.\r
-    'useEQData': false             // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.\r
-  };\r
-\r
-  this.movieStarOptions = {        // flash 9.0r115+ MPEG4 audio/video options, merged into defaultOptions if flash 9 + movieStar mode is enabled\r
-    'onmetadata': null,                   // callback for when video width/height etc. are received\r
-    'useVideo': false             // if loading movieStar content, whether to show video\r
-  }\r
-\r
-  this.flashBlockHelper = {\r
-    'enabled': false,              // experimental, removed with >v2.80\r
-    'message': []                  // "nag bar" to show when messaging the user, if SM2 fails on firefox etc.\r
-  };\r
-\r
-  var _s = this; \r
-  this.version = null;\r
-  this.versionNumber = 'V2.90a.20081028';\r
-  this.movieURL = null;\r
-  this.url = null;\r
-  this.altURL = null;\r
-  this.swfLoaded = false;\r
-  this.enabled = false;\r
-  this.o = null;\r
-  this.id = (smID||'sm2movie');\r
-  this.oMC = null;\r
-  this.sounds = [];\r
-  this.soundIDs = [];\r
-  this.muted = false;\r
-  this.isIE = (navigator.userAgent.match(/MSIE/i));\r
-  this.isSafari = (navigator.userAgent.match(/safari/i));\r
-  this.isGecko = (navigator.userAgent.match(/gecko/i));\r
-  this.debugID = 'soundmanager-debug';\r
-  this._debugOpen = true;\r
-  this._didAppend = false;\r
-  this._appendSuccess = false;\r
-  this._didInit = false;\r
-  this._disabled = false;\r
-  this._windowLoaded = false;\r
-  this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');\r
-  this._debugLevels = ['log','info','warn','error'];\r
-  this._defaultFlashVersion = 8;\r
-  this.filePatterns = {\r
-    flash8: /\.(mp3)/i,\r
-    flash9: /\.(mp3)/i\r
-  };\r
-  this.netStreamTypes = ['aac','flv','mov','mp4','m4v','f4v','m4a','mp4v','3gp','3g2']; // Flash v9.0r115+ "moviestar" formats\r
-  this.netStreamPattern = new RegExp('.('+this.netStreamTypes.join('|')+')','i');\r
-  this.filePattern = null;\r
-  this.features = {\r
-    peakData: false,\r
-    waveformData: false,\r
-    eqData: false\r
-  };\r
-\r
-  this.sandbox = {\r
-    'type': null,\r
-    'types': {\r
-      'remote': 'remote (domain-based) rules',\r
-      'localWithFile': 'local with file access (no internet access)',\r
-      'localWithNetwork': 'local with network (internet access only, no local access)',\r
-      'localTrusted': 'local, trusted (local + internet access)'\r
-    },\r
-    'description': null,\r
-    'noRemote': null,\r
-    'noLocal': null\r
-  };\r
-\r
-  this._setVersionInfo = function() {\r
-    if (_s.flashVersion != 8 && _s.flashVersion != 9) {\r
-      alert('soundManager.flashVersion must be 8 or 9. "'+_s.flashVersion+'" is invalid. Reverting to '+_s._defaultFlashVersion+'.');\r
-      _s.flashVersion = _s._defaultFlashVersion;\r
-    }\r
-    _s.version = _s.versionNumber+(_s.flashVersion==9?' (AS3/Flash 9)':' (AS2/Flash 8)');\r
-    // set up default options\r
-       if (_s.flashVersion > 8) {\r
-         _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.flash9Options);\r
-       }\r
-    if (_s.flashVersion > 8 && _s.useMovieStar) {\r
-      _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.movieStarOptions);\r
-      _s.filePatterns.flash9 = new RegExp('.(mp3|'+_s.netStreamTypes.join('|')+')','i');\r
-    } else {\r
-         _s.useMovieStar = false;\r
-    }\r
-    _s.filePattern = _s.filePatterns[(_s.flashVersion!=8?'flash9':'flash8')];\r
-    _s.movieURL = (_s.flashVersion==8?'soundmanager2.swf':'soundmanager2_flash9.swf');\r
-    _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_s.flashVersion==9);\r
-  }\r
-\r
-  this._overHTTP = (document.location?document.location.protocol.match(/http/i):null);\r
-  this._waitingforEI = false;\r
-  this._initPending = false;\r
-  this._tryInitOnFocus = (this.isSafari && typeof document.hasFocus == 'undefined');\r
-  this._isFocused = (typeof document.hasFocus != 'undefined'?document.hasFocus():null);\r
-  this._okToDisable = !this._tryInitOnFocus;\r
-\r
-  this.useAltURL = !this._overHTTP; // use altURL if not "online"\r
-\r
-  var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';\r
-\r
-  // --- public methods ---\r
-  \r
-  this.supported = function() {\r
-    return (_s._didInit && !_s._disabled);\r
-  };\r
-\r
-  this.getMovie = function(smID) {\r
-    return _s.isIE?window[smID]:(_s.isSafari?document.getElementById(smID)||document[smID]:document.getElementById(smID));\r
-  };\r
-\r
-  this.loadFromXML = function(sXmlUrl) {\r
-    try {\r
-      _s.o._loadFromXML(sXmlUrl);\r
-    } catch(e) {\r
-      _s._failSafely();\r
-      return true;\r
-    };\r
-  };\r
-\r
-  this.createSound = function(oOptions) {\r
-    if (!_s._didInit) throw new Error('soundManager.createSound(): Not loaded yet - wait for soundManager.onload() before calling sound-related methods');\r
-    if (arguments.length==2) {\r
-      // function overloading in JS! :) ..assume simple createSound(id,url) use case\r
-      var oOptions = {'id':arguments[0],'url':arguments[1]};\r
-    };\r
-    var thisOptions = _s._mergeObjects(oOptions); // inherit SM2 defaults\r
-    var _tO = thisOptions; // alias\r
-    _s._wD('soundManager.createSound(): '+_tO.id+' ('+_tO.url+')',1);\r
-    if (_s._idCheck(_tO.id,true)) {\r
-      _s._wD('soundManager.createSound(): '+_tO.id+' exists',1);\r
-      return _s.sounds[_tO.id];\r
-    };\r
-    if (_s.flashVersion > 8 && _s.useMovieStar) {\r
-         if (_tO.isMovieStar == null) {\r
-           _tO.isMovieStar = (_tO.url.match(_s.netStreamPattern)?true:false);\r
-         }\r
-         if (_tO.isMovieStar) {\r
-           _s._wD('soundManager.createSound(): using MovieStar handling');\r
-         }\r
-         if (_tO.isMovieStar && (_tO.usePeakData || _tO.useWaveformData || _tO.useEQData)) {\r
-           _s._wD('Warning: peak/waveform/eqData features unsupported for non-MP3 formats');\r
-           _tO.usePeakData = false;\r
-               _tO.useWaveformData = false;\r
-               _tO.useEQData = false;\r
-         }\r
-    };\r
-    _s.sounds[_tO.id] = new SMSound(_tO);\r
-    _s.soundIDs[_s.soundIDs.length] = _tO.id;\r
-    // AS2:\r
-    if (_s.flashVersion == 8) {\r
-      _s.o._createSound(_tO.id,_tO.onjustbeforefinishtime);\r
-    } else {\r
-      _s.o._createSound(_tO.id,_tO.url,_tO.onjustbeforefinishtime,_tO.usePeakData,_tO.useWaveformData,_tO.useEQData,_tO.isMovieStar,(_tO.isMovieStar?_tO.useVideo:false));\r
-    };\r
-    if (_tO.autoLoad || _tO.autoPlay) {\r
-      window.setTimeout(function() {\r
-        if (_s.sounds[_tO.id]) {\r
-          _s.sounds[_tO.id].load(_tO);\r
-        }\r
-      },20);\r
-    }\r
-    if (_tO.autoPlay) {\r
-         if (_s.flashVersion == 8) {\r
-           _s.sounds[_tO.id].playState = 1; // we can only assume this sound will be playing soon.\r
-         } else {\r
-           _s.sounds[_tO.id].play();   \r
-         }\r
-       }\r
-    return _s.sounds[_tO.id];\r
-  };\r
-\r
-  this.createVideo = function(oOptions) {\r
-    if (arguments.length==2) {\r
-      var oOptions = {'id':arguments[0],'url':arguments[1]};\r
-    };\r
-    if (_s.flashVersion >= 9) {\r
-      oOptions.isMovieStar = true;\r
-      oOptions.useVideo = true;\r
-    } else {\r
-      _s._wD('soundManager.createVideo(): flash 9 required for video. Exiting.',2);\r
-      return false;\r
-    }\r
-    if (!_s.useMovieStar) {\r
-      _s._wD('soundManager.createVideo(): MovieStar mode not enabled. Exiting.',2);\r
-    }\r
-    return _s.createSound(oOptions);\r
-  }\r
-\r
-  this.destroySound = function(sID,bFromSound) {\r
-    // explicitly destroy a sound before normal page unload, etc.\r
-    if (!_s._idCheck(sID)) return false;\r
-    for (var i=0; i<_s.soundIDs.length; i++) {\r
-      if (_s.soundIDs[i] == sID) {\r
-           _s.soundIDs.splice(i,1);\r
-        continue;\r
-      };\r
-    };\r
-    // conservative option: avoid crash with ze flash 8\r
-    // calling destroySound() within a sound onload() might crash firefox, certain flavours of winXP + flash 8??\r
-    // if (_s.flashVersion != 8) {\r
-      _s.sounds[sID].unload();\r
-    // }\r
-    if (!bFromSound) {\r
-      // ignore if being called from SMSound instance\r
-      _s.sounds[sID].destruct();\r
-    };\r
-    delete _s.sounds[sID];\r
-  };\r
-\r
-  this.destroyVideo = this.destroySound;\r
-\r
-  this.load = function(sID,oOptions) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].load(oOptions);\r
-  };\r
-\r
-  this.unload = function(sID) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].unload();\r
-  };\r
-\r
-  this.play = function(sID,oOptions) {\r
-    if (!_s._idCheck(sID)) {\r
-      if (typeof oOptions != 'Object') oOptions = {url:oOptions}; // overloading use case: play('mySound','/path/to/some.mp3');\r
-      if (oOptions && oOptions.url) {\r
-        // overloading use case, creation + playing of sound: .play('someID',{url:'/path/to.mp3'});\r
-        _s._wD('soundController.play(): attempting to create "'+sID+'"',1);\r
-        oOptions.id = sID;\r
-        _s.createSound(oOptions);\r
-      } else {\r
-        return false;\r
-      };\r
-    };\r
-    _s.sounds[sID].play(oOptions);\r
-  };\r
-\r
-  this.start = this.play; // just for convenience\r
-\r
-  this.setPosition = function(sID,nMsecOffset) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    nMsecOffset = Math.min((nMsecOffset||0),_s.duration); // don't allow seek past loaded duration\r
-    _s.sounds[sID].setPosition(nMsecOffset);\r
-  };\r
-\r
-  this.stop = function(sID) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s._wD('soundManager.stop('+sID+')',1);\r
-    _s.sounds[sID].stop(); \r
-  };\r
-\r
-  this.stopAll = function() {\r
-    _s._wD('soundManager.stopAll()',1);\r
-    for (var oSound in _s.sounds) {\r
-      if (_s.sounds[oSound] instanceof SMSound) _s.sounds[oSound].stop(); // apply only to sound objects\r
-    };\r
-  };\r
-\r
-  this.pause = function(sID) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].pause();\r
-  };\r
-\r
-  this.pauseAll = function() {\r
-    for (var i=_s.soundIDs.length; i--;) {\r
-      _s.sounds[_s.soundIDs[i]].pause();\r
-    }\r
-  };\r
-\r
-  this.resume = function(sID) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].resume();\r
-  };\r
-\r
-  this.resumeAll = function() {\r
-    for (var i=_s.soundIDs.length; i--;) {\r
-      _s.sounds[_s.soundIDs[i]].resume();\r
-    }\r
-  };\r
-\r
-  this.togglePause = function(sID) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].togglePause();\r
-  };\r
-\r
-  this.setPan = function(sID,nPan) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].setPan(nPan);\r
-  };\r
-\r
-  this.setVolume = function(sID,nVol) {\r
-    if (!_s._idCheck(sID)) return false;\r
-    _s.sounds[sID].setVolume(nVol);\r
-  };\r
-\r
-  this.mute = function(sID) {\r
-       if (typeof sID != 'string') sID = null;\r
-    if (!sID) {\r
-      var o = null;\r
-      _s._wD('soundManager.mute(): Muting all sounds');\r
-      for (var i=_s.soundIDs.length; i--;) {\r
-        _s.sounds[_s.soundIDs[i]].mute();\r
-      }\r
-      _s.muted = true;\r
-    } else {\r
-      if (!_s._idCheck(sID)) return false;\r
-      _s._wD('soundManager.mute(): Muting "'+sID+'"');\r
-      _s.sounds[sID].mute();\r
-    }\r
-  };\r
-\r
-  this.muteAll = function() {\r
-    _s.mute();\r
-  };\r
-\r
-  this.unmute = function(sID) {\r
-    if (typeof sID != 'string') sID = null;\r
-    if (!sID) {\r
-      var o = null;\r
-      _s._wD('soundManager.unmute(): Unmuting all sounds');\r
-      for (var i=_s.soundIDs.length; i--;) {\r
-        _s.sounds[_s.soundIDs[i]].unmute();\r
-      }\r
-      _s.muted = false;\r
-    } else {\r
-      if (!_s._idCheck(sID)) return false;\r
-      _s._wD('soundManager.unmute(): Unmuting "'+sID+'"');\r
-      _s.sounds[sID].unmute();\r
-    }\r
-  };\r
-\r
-  this.unmuteAll = function() {\r
-    _s.unmute();\r
-  };\r
-\r
-  this.setPolling = function(bPolling) {\r
-    if (!_s.o || !_s.allowPolling) return false;\r
-    // _s._wD('soundManager.setPolling('+bPolling+')');\r
-    _s.o._setPolling(bPolling);\r
-  };\r
-\r
-  this.disable = function(bUnload) {\r
-    // destroy all functions\r
-    if (_s._disabled) return false;\r
-    _s._disabled = true;\r
-    _s._wD('soundManager.disable(): Disabling all functions - future calls will return false.',1);\r
-    for (var i=_s.soundIDs.length; i--;) {\r
-      _s._disableObject(_s.sounds[_s.soundIDs[i]]);\r
-    };\r
-    _s.initComplete(); // fire "complete", despite fail\r
-    _s._disableObject(_s);\r
-  };\r
-\r
-  this.handleFlashBlock = function(bForce) {\r
-    // experimental, removed with >v2.80.\r
-    return false;\r
-  };\r
-\r
-  this.canPlayURL = function(sURL) {\r
-    return (sURL?(sURL.match(_s.filePattern)?true:false):null);        \r
-  };\r
-\r
-  this.getSoundById = function(sID,suppressDebug) {\r
-    if (!sID) throw new Error('SoundManager.getSoundById(): sID is null/undefined');\r
-    var result = _s.sounds[sID];\r
-    if (!result && !suppressDebug) {\r
-      _s._wD('"'+sID+'" is an invalid sound ID.',2);\r
-      // soundManager._wD('trace: '+arguments.callee.caller);\r
-    };\r
-    return result;\r
-  };\r
-\r
-  this.onload = function() {\r
-    // window.onload() equivalent for SM2, ready to create sounds etc.\r
-    // this is a stub - you can override this in your own external script, eg. soundManager.onload = function() {}\r
-    soundManager._wD('<em>Warning</em>: soundManager.onload() is undefined.',2);\r
-  };\r
-\r
-  this.onerror = function() {\r
-    // stub for user handler, called when SM2 fails to load/init\r
-  };\r
-\r
-  // --- "private" methods ---\r
-\r
-  this._idCheck = this.getSoundById;\r
-\r
-  this._disableObject = function(o) {\r
-    for (var oProp in o) {\r
-      if (typeof o[oProp] == 'function' && typeof o[oProp]._protected == 'undefined') o[oProp] = function(){return false;};\r
-    };\r
-    oProp = null;\r
-  };\r
-\r
-  this._failSafely = function() {\r
-    // exception handler for "object doesn't support this property or method" or general failure\r
-    var fpgssTitle = 'You may need to whitelist this location/domain eg. file:///C:/ or C:/ or mysite.com, or set ALWAYS ALLOW under the Flash Player Global Security Settings page. The latter is probably less-secure.';\r
-    var flashCPL = '<a href="'+flashCPLink+'" title="'+fpgssTitle+'">view/edit</a>';\r
-    var FPGSS = '<a href="'+flashCPLink+'" title="Flash Player Global Security Settings">FPGSS</a>';\r
-    if (!_s._disabled) {\r
-      _s._wD('soundManager: Failed to initialise.',2);\r
-      _s.disable();\r
-    };\r
-  };\r
-  \r
-  this._normalizeMovieURL = function(smURL) {\r
-    if (smURL) {\r
-      if (smURL.match(/\.swf/)) {\r
-        smURL = smURL.substr(0,smURL.lastIndexOf('.swf'));\r
-      }\r
-      if (smURL.lastIndexOf('/') != smURL.length-1) {\r
-        smURL = smURL+'/';\r
-      }\r
-    }\r
-    return(smURL && smURL.lastIndexOf('/')!=-1?smURL.substr(0,smURL.lastIndexOf('/')+1):'./')+_s.movieURL;\r
-  };\r
-\r
-  this._getDocument = function() {\r
-    return (document.body?document.body:(document.documentElement?document.documentElement:document.getElementsByTagName('div')[0]));\r
-  };\r
-\r
-  this._getDocument._protected = true;\r
-\r
-  this._createMovie = function(smID,smURL) {\r
-    if (_s._didAppend && _s._appendSuccess) return false; // ignore if already succeeded\r
-    if (window.location.href.indexOf('debug=1')+1) _s.debugMode = true; // allow force of debug mode via URL\r
-    _s._didAppend = true;\r
-       \r
-    // safety check for legacy (change to Flash 9 URL)\r
-    _s._setVersionInfo();\r
-    var remoteURL = (smURL?smURL:_s.url);\r
-    var localURL = (_s.altURL?_s.altURL:remoteURL);\r
-    _s.url = _s._normalizeMovieURL(_s._overHTTP?remoteURL:localURL);\r
-    smURL = _s.url;\r
-\r
-    var htmlEmbed = '<embed name="'+smID+'" id="'+smID+'" src="'+smURL+'" width="100%" height="100%" quality="high" allowScriptAccess="always" quality="high" '+(_s.useHighPerformance && !_s.useMovieStar?'wmode="transparent" ':'')+'bgcolor="'+_s.bgColor+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>';\r
-    var htmlObject = '<object id="'+smID+'" data="'+smURL+'" type="application/x-shockwave-flash" width="100%" height="100%"><param name="movie" value="'+smURL+'" /><param name="AllowScriptAccess" value="always" /><param name="quality" value="high" />'+(_s.useHighPerformance && !_s.useMovieStar?'<param name="wmode" value="transparent" /> ':'')+'<param name="bgcolor" value="'+_s.bgColor+'" /><!-- --></object>';\r
-    var html = (!_s.isIE?htmlEmbed:htmlObject);\r
-\r
-    var toggleElement = '<div id="'+_s.debugID+'-toggle" style="position:fixed;_position:absolute;right:0px;bottom:0px;_top:0px;width:1.2em;height:1.2em;line-height:1.2em;margin:2px;padding:0px;text-align:center;border:1px solid #999;cursor:pointer;background:#fff;color:#333;z-index:10001" title="Toggle SM2 debug console" onclick="soundManager._toggleDebug()">-</div>';\r
-    var debugHTML = '<div id="'+_s.debugID+'" style="display:'+(_s.debugMode && ((!_s._hasConsole||!_s.useConsole)||(_s.useConsole && _s._hasConsole && !_s.consoleOnly))?'block':'none')+';opacity:0.85"></div>';\r
-    var appXHTML = 'soundManager._createMovie(): appendChild/innerHTML set failed. May be app/xhtml+xml DOM-related.';\r
-\r
-    var oTarget = _s._getDocument();\r
-    if (oTarget) {\r
-       \r
-      _s.oMC = document.getElementById('sm2-container')?document.getElementById('sm2-container'):document.createElement('div');\r
-      if (!_s.oMC.id) {\r
-        _s.oMC.id = 'sm2-container';\r
-        _s.oMC.className = 'movieContainer';\r
-        // "hide" flash movie\r
-        var s = null;\r
-        if (_s.useHighPerformance) {\r
-          s = {\r
-           position: 'fixed',\r
-           width: '8px',\r
-            height: '8px', // must be at least 6px for flash to run fast. odd? yes.\r
-            bottom: '0px',\r
-            left: '0px',\r
-           zIndex:-1 // sit behind everything else\r
-          }\r
-        } else {\r
-          s = {\r
-            position: 'absolute',\r
-           width: '1px',\r
-            height: '1px',\r
-            bottom: '0px',\r
-            left: '0px'\r
-          }\r
-        }\r
-        var x = null;\r
-        for (x in s) {\r
-          _s.oMC.style[x] = s[x];\r
-        }\r
-        try {\r
-          oTarget.appendChild(_s.oMC);\r
-          _s.oMC.innerHTML = html;\r
-          _s._appendSuccess = true;\r
-        } catch(e) {\r
-          throw new Error(appXHTML);\r
-        }\r
-      } else {\r
-        // it's already in the document.\r
-        _s.oMC.innerHTML = html;\r
-        _s._appendSuccess = true;\r
-      }\r
-      if (!document.getElementById(_s.debugID) && ((!_s._hasConsole||!_s.useConsole)||(_s.useConsole && _s._hasConsole && !_s.consoleOnly))) {\r
-        var oDebug = document.createElement('div');\r
-        oDebug.id = _s.debugID;\r
-        oDebug.style.display = (_s.debugMode?'block':'none');\r
-        if (_s.debugMode) {\r
-          try {\r
-            var oD = document.createElement('div');\r
-            oTarget.appendChild(oD);\r
-            oD.innerHTML = toggleElement;\r
-          } catch(e) {\r
-            throw new Error(appXHTML);\r
-          };\r
-        };\r
-        oTarget.appendChild(oDebug);\r
-      };\r
-      oTarget = null;\r
-    };\r
-    _s._wD('-- SoundManager 2 '+_s.version+(_s.useMovieStar?', MovieStar mode':'')+(_s._wD?', high performance mode':'')+' --',1);\r
-    _s._wD('soundManager._createMovie(): Trying to load '+smURL+(!_s._overHTTP && _s.altURL?'(alternate URL)':''),1);\r
-  };\r
-\r
-  // aliased to this._wD()\r
-  this._writeDebug = function(sText,sType,bTimestamp) {\r
-    if (!_s.debugMode) return false;\r
-    if (typeof bTimestamp != 'undefined' && bTimestamp) {\r
-      sText = sText + ' | '+new Date().getTime();\r
-    };\r
-    if (_s._hasConsole && _s.useConsole) {\r
-      var sMethod = _s._debugLevels[sType];\r
-      if (typeof console[sMethod] != 'undefined') {\r
-        console[sMethod](sText);\r
-      } else {\r
-        console.log(sText);\r
-      };\r
-      if (_s.useConsoleOnly) return true;\r
-    };\r
-    var sDID = 'soundmanager-debug';\r
-    try {\r
-      var o = document.getElementById(sDID);\r
-      if (!o) return false;\r
-      var oItem = document.createElement('div');\r
-      sText = sText.replace(/\n/g,'<br />');\r
-      if (typeof sType == 'undefined') {\r
-        var sType = 0;\r
-      } else {\r
-        sType = parseInt(sType);\r
-      };\r
-      oItem.innerHTML = sText;\r
-      if (sType) {\r
-        if (sType >= 2) oItem.style.fontWeight = 'bold';\r
-        if (sType == 3) oItem.style.color = '#ff3333';\r
-      };\r
-      // o.appendChild(oItem); // top-to-bottom\r
-      o.insertBefore(oItem,o.firstChild); // bottom-to-top\r
-    } catch(e) {\r
-      // oh well\r
-    };\r
-    o = null;\r
-  };\r
-  this._writeDebug._protected = true;\r
-  this._wD = this._writeDebug;\r
-\r
-  this._wDAlert = function(sText) { alert(sText); };\r
-\r
-  if (window.location.href.indexOf('debug=alert')+1 && _s.debugMode) {\r
-    _s._wD = _s._wDAlert;\r
-  };\r
-\r
-  this._toggleDebug = function() {\r
-    var o = document.getElementById(_s.debugID);\r
-    var oT = document.getElementById(_s.debugID+'-toggle');\r
-    if (!o) return false;\r
-    if (_s._debugOpen) {\r
-      // minimize\r
-      oT.innerHTML = '+';\r
-      o.style.display = 'none';\r
-    } else {\r
-      oT.innerHTML = '-';\r
-      o.style.display = 'block';\r
-    };\r
-    _s._debugOpen = !_s._debugOpen;\r
-  };\r
-\r
-  this._toggleDebug._protected = true;\r
-\r
-  this._debug = function() {\r
-    _s._wD('--- soundManager._debug(): Current sound objects ---',1);\r
-    for (var i=0,j=_s.soundIDs.length; i<j; i++) {\r
-      _s.sounds[_s.soundIDs[i]]._debug();\r
-    };\r
-  };\r
-\r
-  this._mergeObjects = function(oMain,oAdd) {\r
-    // non-destructive merge\r
-    var o1 = {}; // clone o1\r
-    for (var i in oMain) {\r
-      o1[i] = oMain[i];\r
-    }\r
-    var o2 = (typeof oAdd == 'undefined'?_s.defaultOptions:oAdd);\r
-    for (var o in o2) {\r
-      if (typeof o1[o] == 'undefined') o1[o] = o2[o];\r
-    };\r
-    return o1;\r
-  };\r
-\r
-  this.createMovie = function(sURL) {\r
-    if (sURL) _s.url = sURL;\r
-    _s._initMovie();\r
-  };\r
-\r
-  this.go = this.createMovie; // nice alias\r
-\r
-  this._initMovie = function() {\r
-    // attempt to get, or create, movie\r
-    if (_s.o) return false; // pre-init may have fired this function before window.onload(), may already exist\r
-    _s.o = _s.getMovie(_s.id); // try to get flash movie (inline markup)\r
-    if (!_s.o) {\r
-      // try to create\r
-      _s._createMovie(_s.id,_s.url);\r
-      _s.o = _s.getMovie(_s.id);\r
-    };\r
-    if (_s.o) {\r
-      _s._wD('soundManager._initMovie(): Got '+_s.o.nodeName+' element ('+(_s._didAppend?'created via JS':'static HTML')+')',1);\r
-      _s._wD('soundManager._initMovie(): Waiting for ExternalInterface call from Flash..');\r
-    };\r
-  };\r
-\r
-  this.waitForExternalInterface = function() {\r
-    if (_s._waitingForEI) return false;\r
-    _s._waitingForEI = true;\r
-    if (_s._tryInitOnFocus && !_s._isFocused) {\r
-      _s._wD('soundManager: Special case: Flash may not have started due to non-focused tab (Safari is lame), and/or focus cannot be detected. Waiting for focus-related event..');\r
-      return false;\r
-    };\r
-    if (!_s._didInit) {\r
-      _s._wD('soundManager: Getting impatient, still waiting for Flash.. ;)');\r
-    };\r
-    setTimeout(function() {\r
-      if (!_s._didInit) {\r
-        _s._wD('soundManager: No Flash response within reasonable time after document load.\nPossible causes: Flash version under 8, no support, or Flash security denying JS-Flash communication.',2);\r
-        if (!_s._overHTTP) {\r
-          _s._wD('soundManager: Loading this page from local/network file system (not over HTTP?) Flash security likely restricting JS-Flash access. Consider adding current URL to "trusted locations" in the Flash player security settings manager at '+flashCPLink+', or simply serve this content over HTTP.',2);\r
-        };\r
-      };\r
-      // if still not initialized and no other options, give up\r
-      if (!_s._didInit && _s._okToDisable) _s._failSafely();\r
-    },750);\r
-  };\r
-\r
-  this.handleFocus = function() {\r
-    if (_s._isFocused || !_s._tryInitOnFocus) return true;\r
-    _s._okToDisable = true;\r
-    _s._isFocused = true;\r
-    _s._wD('soundManager.handleFocus()');\r
-    if (_s._tryInitOnFocus) {\r
-      // giant Safari 3.1 hack - assume window in focus if mouse is moving, since document.hasFocus() not currently implemented.\r
-      window.removeEventListener('mousemove',_s.handleFocus,false);\r
-    };\r
-    // allow init to restart\r
-    _s._waitingForEI = false;\r
-    setTimeout(_s.waitForExternalInterface,500);\r
-    // detach event\r
-    if (window.removeEventListener) {\r
-      window.removeEventListener('focus',_s.handleFocus,false);\r
-    } else if (window.detachEvent) {\r
-      window.detachEvent('onfocus',_s.handleFocus);\r
-    };\r
-  };\r
-\r
-  this.initComplete = function() {\r
-    if (_s._didInit) return false;\r
-    _s._didInit = true;\r
-    _s._wD('-- SoundManager 2 '+(_s._disabled?'failed to load':'loaded')+' ('+(_s._disabled?'security/load error':'OK')+') --',1);\r
-    if (_s._disabled) {\r
-      _s._wD('soundManager.initComplete(): calling soundManager.onerror()',1);\r
-      _s.onerror.apply(window);\r
-      return false;\r
-    };\r
-    if (_s.waitForWindowLoad && !_s._windowLoaded) {\r
-      _s._wD('soundManager: Waiting for window.onload()');\r
-      if (window.addEventListener) {\r
-        window.addEventListener('load',_s.initUserOnload,false);\r
-      } else if (window.attachEvent) {\r
-        window.attachEvent('onload',_s.initUserOnload);\r
-      };\r
-      return false;\r
-    } else {\r
-      if (_s.waitForWindowLoad && _s._windowLoaded) {\r
-        _s._wD('soundManager: Document already loaded');\r
-      };\r
-      _s.initUserOnload();\r
-    };\r
-  };\r
-\r
-  this.initUserOnload = function() {\r
-    _s._wD('soundManager.initComplete(): calling soundManager.onload()',1);\r
-    // call user-defined "onload", scoped to window\r
-    //try {\r
-      _s.onload.apply(window);\r
-      /*\r
-    } catch(e) {\r
-      // something broke (likely JS error in user function)\r
-      _s._wD('soundManager.onload() threw an exception: '+e.message,2);\r
-      setTimeout(function(){throw new Error(e)},20);\r
-      return false;\r
-    };\r
-    */\r
-    _s._wD('soundManager.onload() complete',1);\r
-  };\r
-\r
-  this.init = function() {\r
-    _s._wD('-- soundManager.init() --');\r
-    // called after onload()\r
-    _s._initMovie();\r
-    if (_s._didInit) {\r
-      _s._wD('soundManager.init(): Already called?');\r
-      return false;\r
-    };\r
-    // event cleanup\r
-    if (window.removeEventListener) {\r
-      window.removeEventListener('load',_s.beginDelayedInit,false);\r
-    } else if (window.detachEvent) {\r
-      window.detachEvent('onload',_s.beginDelayedInit);\r
-    };\r
-    try {\r
-      _s._wD('Attempting to call JS -&gt; Flash..');\r
-      _s.o._externalInterfaceTest(false); // attempt to talk to Flash\r
-      // _s._wD('Flash ExternalInterface call (JS-Flash) OK',1);\r
-      if (!_s.allowPolling) {\r
-           _s._wD('Polling (whileloading/whileplaying support) is disabled.',1);\r
-         }\r
-      _s.setPolling(true);\r
-         if (!_s.debugMode) _s.o._disableDebug();\r
-      _s.enabled = true;\r
-    } catch(e) {\r
-      _s._failSafely();\r
-      _s.initComplete();\r
-      return false;\r
-    };\r
-    _s.initComplete();\r
-  };\r
-\r
-  this.beginDelayedInit = function() {\r
-    _s._wD('soundManager.beginDelayedInit(): Document loaded');\r
-    _s._windowLoaded = true;\r
-    setTimeout(_s.waitForExternalInterface,500);\r
-    setTimeout(_s.beginInit,20);\r
-  };\r
-\r
-  this.beginInit = function() {\r
-    if (_s._initPending) return false;\r
-    _s.createMovie(); // ensure creation if not already done\r
-    _s._initMovie();\r
-    _s._initPending = true;\r
-    return true;\r
-  };\r
-\r
-  this.domContentLoaded = function() {\r
-    _s._wD('soundManager.domContentLoaded()');\r
-    if (document.removeEventListener) document.removeEventListener('DOMContentLoaded',_s.domContentLoaded,false);\r
-    _s.go();\r
-  };\r
-\r
-  this._externalInterfaceOK = function() {\r
-    // callback from flash for confirming that movie loaded, EI is working etc.\r
-    if (_s.swfLoaded) return false;\r
-    _s._wD('soundManager._externalInterfaceOK()');\r
-    _s.swfLoaded = true;\r
-    _s._tryInitOnFocus = false;\r
-    if (_s.isIE) {\r
-      // IE needs a timeout OR delay until window.onload - may need TODO: investigating\r
-      setTimeout(_s.init,100);\r
-    } else {\r
-      _s.init();\r
-    };\r
-  };\r
-\r
-  this._setSandboxType = function(sandboxType) {\r
-    var sb = _s.sandbox;\r
-    sb.type = sandboxType;\r
-    sb.description = sb.types[(typeof sb.types[sandboxType] != 'undefined'?sandboxType:'unknown')];\r
-    _s._wD('Flash security sandbox type: '+sb.type);\r
-    if (sb.type == 'localWithFile') {\r
-      sb.noRemote = true;\r
-      sb.noLocal = false;\r
-      _s._wD('Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html',2);\r
-    } else if (sb.type == 'localWithNetwork') {\r
-      sb.noRemote = false;\r
-      sb.noLocal = true;\r
-    } else if (sb.type == 'localTrusted') {\r
-      sb.noRemote = false;\r
-      sb.noLocal = false;\r
-    };\r
-  };\r
-\r
-  this.destruct = function() {\r
-    _s._wD('soundManager.destruct()');\r
-    _s.disable(true);\r
-  };\r
-  \r
-  // SMSound (sound object)\r
-  \r
-  function SMSound(oOptions) {\r
-  var _t = this;\r
-  this.sID = oOptions.id;\r
-  this.url = oOptions.url;\r
-  this.options = _s._mergeObjects(oOptions);\r
-  this.instanceOptions = this.options; // per-play-instance-specific options\r
-  this._iO = this.instanceOptions; // short alias\r
-\r
-  this._debug = function() {\r
-    if (_s.debugMode) {\r
-    var stuff = null;\r
-    var msg = [];\r
-    var sF = null;\r
-    var sfBracket = null;\r
-    var maxLength = 64; // # of characters of function code to show before truncating\r
-    for (stuff in _t.options) {\r
-      if (_t.options[stuff] != null) {\r
-        if (_t.options[stuff] instanceof Function) {\r
-             // handle functions specially\r
-             sF = _t.options[stuff].toString();\r
-             sF = sF.replace(/\s\s+/g,' '); // normalize spaces\r
-             sfBracket = sF.indexOf('{');\r
-             msg[msg.length] = ' '+stuff+': {'+sF.substr(sfBracket+1,(Math.min(Math.max(sF.indexOf('\n')-1,maxLength),maxLength))).replace(/\n/g,'')+'... }';\r
-           } else {\r
-             msg[msg.length] = ' '+stuff+': '+_t.options[stuff];\r
-           };\r
-      };\r
-    };\r
-    _s._wD('SMSound() merged options: {\n'+msg.join(', \n')+'\n}');\r
-    };\r
-  };\r
-\r
-  this._debug();\r
-\r
-  this.id3 = {\r
-   /* \r
-    Name/value pairs set via Flash when available - see reference for names:\r
-    http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001567.html\r
-    (eg., this.id3.songname or this.id3['songname'])\r
-   */\r
-  };\r
-\r
-  this.resetProperties = function(bLoaded) {\r
-    _t.bytesLoaded = null;\r
-    _t.bytesTotal = null;\r
-    _t.position = null;\r
-    _t.duration = null;\r
-    _t.durationEstimate = null;\r
-    _t.loaded = false;\r
-    _t.playState = 0;\r
-    _t.paused = false;\r
-    _t.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success\r
-    _t.muted = false;\r
-    _t.didBeforeFinish = false;\r
-    _t.didJustBeforeFinish = false;\r
-    _t.instanceOptions = {};\r
-    _t.instanceCount = 0;\r
-    _t.peakData = {\r
-      left: 0,\r
-      right: 0\r
-    };\r
-    _t.waveformData = [];\r
-    _t.eqData = [];\r
-  };\r
-\r
-  _t.resetProperties();\r
-\r
-  // --- public methods ---\r
-\r
-  this.load = function(oOptions) {\r
-    if (typeof oOptions != 'undefined') {\r
-      _t._iO = _s._mergeObjects(oOptions);\r
-      _t.instanceOptions = _t._iO;\r
-    } else {\r
-      var oOptions = _t.options;\r
-      _t._iO = oOptions;\r
-      _t.instanceOptions = _t._iO;\r
-    } \r
-    if (typeof _t._iO.url == 'undefined') _t._iO.url = _t.url;\r
-    _s._wD('soundManager.load(): '+_t._iO.url,1);\r
-    if (_t._iO.url == _t.url && _t.readyState != 0 && _t.readyState != 2) {\r
-      _s._wD('soundManager.load(): current URL already assigned.',1);\r
-      return false;\r
-    }\r
-    _t.loaded = false;\r
-    _t.readyState = 1;\r
-    _t.playState = (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)\r
-    try {\r
-      if (_s.flashVersion==8) {\r
-        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream,_t._iO.autoPlay,(_t._iO.whileloading?1:0));\r
-      } else {\r
-        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream?true:false,_t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)\r
-        if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {\r
-          // special case: MPEG4 content must start playing to load, then pause to prevent playing.\r
-          _t.pause();\r
-        }\r
-      };\r
-    } catch(e) {\r
-      _s._wD('SMSound.load(): Exception: JS-Flash communication failed, or JS error.',2);\r
-      _s.onerror();\r
-      _s.disable();\r
-    };\r
-  };\r
-\r
-  this.unload = function() {\r
-    // Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3\r
-    // Flash 9/AS3: Close stream, preventing further load\r
-    if (_t.readyState != 0) {\r
-      _s._wD('SMSound.unload(): "'+_t.sID+'"');\r
-      if (_t.readyState != 2) { // reset if not error\r
-        _t.setPosition(0); // reset current sound positioning\r
-      }\r
-      _s.o._unload(_t.sID,_s.nullURL);\r
-      // reset load/status flags\r
-      _t.resetProperties();\r
-    }\r
-  };\r
-\r
-  this.destruct = function() {\r
-    // kill sound within Flash\r
-    _s._wD('SMSound.destruct(): "'+_t.sID+'"');\r
-    _s.o._destroySound(_t.sID);\r
-    _s.destroySound(_t.sID,true); // ensure deletion from controller\r
-  }\r
-\r
-  this.play = function(oOptions) {\r
-    if (!oOptions) oOptions = {};\r
-    _t._iO = _s._mergeObjects(oOptions,_t._iO);\r
-    _t._iO = _s._mergeObjects(_t._iO,_t.options);\r
-    _t.instanceOptions = _t._iO;\r
-    if (_t.playState == 1) {\r
-      var allowMulti = _t._iO.multiShot;\r
-      if (!allowMulti) {\r
-        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (one-shot)',1);\r
-        return false;\r
-      } else {\r
-        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (multi-shot)',1);\r
-      };\r
-    };\r
-    if (!_t.loaded) {\r
-      if (_t.readyState == 0) {\r
-        _s._wD('SMSound.play(): Attempting to load "'+_t.sID+'"',1);\r
-        // try to get this sound playing ASAP\r
-        _t._iO.stream = true;\r
-        _t._iO.autoPlay = true;\r
-        // TODO: need to investigate when false, double-playing\r
-        // if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here\r
-        _t.load(_t._iO); // try to get this sound playing ASAP\r
-      } else if (_t.readyState == 2) {\r
-        _s._wD('SMSound.play(): Could not load "'+_t.sID+'" - exiting',2);\r
-        return false;\r
-      } else {\r
-        _s._wD('SMSound.play(): "'+_t.sID+'" is loading - attempting to play..',1);\r
-      };\r
-    } else {\r
-      _s._wD('SMSound.play(): "'+_t.sID+'"');\r
-    };\r
-    if (_t.paused) {\r
-      _t.resume();\r
-    } else {\r
-      _t.playState = 1;\r
-      if (!_t.instanceCount || _s.flashVersion == 9) _t.instanceCount++;\r
-      _t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);\r
-      if (_t._iO.onplay) _t._iO.onplay.apply(_t);\r
-      _t.setVolume(_t._iO.volume);\r
-      _t.setPan(_t._iO.pan);\r
-      _s.o._start(_t.sID,_t._iO.loop||1,(_s.flashVersion==9?_t.position:_t.position/1000));\r
-    };\r
-  };\r
-\r
-  this.start = this.play; // just for convenience\r
-\r
-  this.stop = function(bAll) {\r
-    if (_t.playState == 1) {\r
-      _t.playState = 0;\r
-      _t.paused = false;\r
-      // if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);\r
-      if (_t._iO.onstop) _t._iO.onstop.apply(_t);\r
-      _s.o._stop(_t.sID,bAll);\r
-      _t.instanceCount = 0;\r
-      _t._iO = {};\r
-      // _t.instanceOptions = _t._iO;\r
-    };\r
-  };\r
-\r
-  this.setPosition = function(nMsecOffset) {\r
-    _t._iO.position = nMsecOffset;\r
-    _s._wD('SMSound.setPosition('+nMsecOffset+')');\r
-    _s.o._setPosition(_t.sID,(_s.flashVersion==9?_t._iO.position:_t._iO.position/1000),(_t.paused||!_t.playState)); // if paused or not playing, will not resume (by playing)\r
-  };\r
-\r
-  this.pause = function() {\r
-    if (_t.paused || _t.playState == 0) return false;\r
-    _s._wD('SMSound.pause()');\r
-    _t.paused = true;\r
-    _s.o._pause(_t.sID);\r
-    if (_t._iO.onpause) _t._iO.onpause.apply(_t);\r
-  };\r
-\r
-  this.resume = function() {\r
-    if (!_t.paused || _t.playState == 0) return false;\r
-    _s._wD('SMSound.resume()');\r
-    _t.paused = false;\r
-    _s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)\r
-    if (_t._iO.onresume) _t._iO.onresume.apply(_t);\r
-  };\r
-\r
-  this.togglePause = function() {\r
-    _s._wD('SMSound.togglePause()');\r
-    if (!_t.playState) {\r
-      _t.play({position:(_s.flashVersion==9?_t.position:_t.position/1000)});\r
-      return false;\r
-    };\r
-    if (_t.paused) {\r
-      _t.resume();\r
-    } else {\r
-      _t.pause();\r
-    };\r
-  };\r
-\r
-  this.setPan = function(nPan) {\r
-    if (typeof nPan == 'undefined') nPan = 0;\r
-    _s.o._setPan(_t.sID,nPan);\r
-    _t._iO.pan = nPan;\r
-  };\r
-\r
-  this.setVolume = function(nVol) {\r
-    if (typeof nVol == 'undefined') nVol = 100;\r
-    _s.o._setVolume(_t.sID,(_s.muted&&!_t.muted)||_t.muted?0:nVol);\r
-    _t._iO.volume = nVol;\r
-  };\r
-\r
-  this.mute = function() {\r
-       _t.muted = true;\r
-    _s.o._setVolume(_t.sID,0);\r
-  };\r
-\r
-  this.unmute = function() {\r
-       _t.muted = false;\r
-    _s.o._setVolume(_t.sID,typeof _t._iO.volume != 'undefined'?_t._iO.volume:_t.options.volume);\r
-  };\r
-\r
-  // --- "private" methods called by Flash ---\r
-\r
-  this._whileloading = function(nBytesLoaded,nBytesTotal,nDuration) {\r
-    if (!_t._iO.isMovieStar) {\r
-      _t.bytesLoaded = nBytesLoaded;\r
-      _t.bytesTotal = nBytesTotal;\r
-      _t.duration = Math.floor(nDuration);\r
-      _t.durationEstimate = parseInt((_t.bytesTotal/_t.bytesLoaded)*_t.duration); // estimate total time (will only be accurate with CBR MP3s.)\r
-      if (_t.readyState != 3 && _t._iO.whileloading) _t._iO.whileloading.apply(_t);\r
-    } else {\r
-      _t.bytesLoaded = nBytesLoaded;\r
-      _t.bytesTotal = nBytesTotal;\r
-      _t.duration = Math.floor(nDuration);\r
-      _t.durationEstimate = _t.duration;\r
-      if (_t.readyState != 3 && _t._iO.whileloading) _t._iO.whileloading.apply(_t);\r
-    }\r
-  };\r
-\r
-  this._onid3 = function(oID3PropNames,oID3Data) {\r
-    // oID3PropNames: string array (names)\r
-    // ID3Data: string array (data)\r
-    _s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');\r
-    var oData = [];\r
-    for (var i=0,j=oID3PropNames.length; i<j; i++) {\r
-      oData[oID3PropNames[i]] = oID3Data[i];\r
-      // _s._wD(oID3PropNames[i]+': '+oID3Data[i]);\r
-    };\r
-    _t.id3 = _s._mergeObjects(_t.id3,oData);\r
-    if (_t._iO.onid3) _t._iO.onid3.apply(_t);\r
-  };\r
-\r
-  this._whileplaying = function(nPosition,oPeakData,oWaveformData,oEQData) {\r
-    if (isNaN(nPosition) || nPosition == null) return false; // Flash may return NaN at times\r
-    _t.position = nPosition;\r
-       if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {\r
-         _t.peakData = {\r
-          left: oPeakData.leftPeak,\r
-          right: oPeakData.rightPeak\r
-         };\r
-       };\r
-       if (_t._iO.useWaveformData && typeof oWaveformData != 'undefined' && oWaveformData) {\r
-         _t.waveformData = oWaveformData;\r
-         /*\r
-         _t.spectrumData = {\r
-          left: oSpectrumData.left.split(','),\r
-          right: oSpectrumData.right.split(',')\r
-         }\r
-         */\r
-       };\r
-       if (_t._iO.useEQData && typeof oEQData != 'undefined' && oEQData) {\r
-         _t.eqData = oEQData;\r
-       };\r
-    if (_t.playState == 1) {\r
-      if (_t._iO.whileplaying) {\r
-           _t._iO.whileplaying.apply(_t); // flash may call after actual finish\r
-         };\r
-      if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration-_t.position <= _t._iO.onbeforefinishtime) {\r
-        _s._wD('duration-position &lt;= onbeforefinishtime: '+_t.duration+' - '+_t.position+' &lt= '+_t._iO.onbeforefinishtime+' ('+(_t.duration-_t.position)+')');\r
-        _t._onbeforefinish();\r
-      };\r
-    };\r
-  };\r
-\r
-  this._onload = function(bSuccess) {\r
-    bSuccess = (bSuccess==1?true:false);\r
-    _s._wD('SMSound._onload(): "'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url));\r
-    if (!bSuccess) {\r
-      if (_s.sandbox.noRemote == true) {\r
-        _s._wD('SMSound._onload(): Reminder: Flash security is denying network/internet access',1);\r
-      };\r
-      if (_s.sandbox.noLocal == true) {\r
-        _s._wD('SMSound._onload(): Reminder: Flash security is denying local access',1);\r
-      };\r
-    };\r
-    _t.loaded = bSuccess;\r
-    _t.readyState = bSuccess?3:2;\r
-    if (_t._iO.onload) {\r
-      _t._iO.onload.apply(_t);\r
-    };\r
-  };\r
-\r
-  this._onbeforefinish = function() {\r
-    if (!_t.didBeforeFinish) {\r
-      _t.didBeforeFinish = true;\r
-      if (_t._iO.onbeforefinish) {\r
-        _s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');\r
-        _t._iO.onbeforefinish.apply(_t);\r
-      }\r
-    };\r
-  };\r
-\r
-  this._onjustbeforefinish = function(msOffset) {\r
-    // msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)\r
-    if (!_t.didJustBeforeFinish) {\r
-      _t.didJustBeforeFinish = true;\r
-      if (_t._iO.onjustbeforefinish) {\r
-        _s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');\r
-        _t._iO.onjustbeforefinish.apply(_t);\r
-      }\r
-    };\r
-  };\r
-\r
-  this._onfinish = function() {\r
-    // sound has finished playing\r
-    _t.playState = 0;\r
-    _t.paused = false;\r
-    if (_t._iO.onfinish) {\r
-      _s._wD('SMSound._onfinish(): "'+_t.sID+'"');\r
-      _t._iO.onfinish.apply(_t);\r
-    }\r
-    if (_t._iO.onbeforefinishcomplete) _t._iO.onbeforefinishcomplete.apply(_t);\r
-    // reset some state items\r
-    _t.setPosition(0);\r
-    _t.didBeforeFinish = false;\r
-    _t.didJustBeforeFinish = false;\r
-    if (_t.instanceCount) {\r
-      _t.instanceCount--;\r
-      if (!_t.instanceCount) {\r
-        // reset instance options\r
-        _t.instanceCount = 0;\r
-        _t.instanceOptions = {};\r
-      }\r
-    }\r
-  };\r
-\r
-  this._onmetadata = function(oMetaData) {\r
-    // movieStar mode only\r
-    _s._wD('SMSound.onmetadata()');\r
-    // Contains a subset of metadata. Note that files may have their own unique metadata.\r
-    // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html\r
-    if (!oMetaData.width && !oMetaData.height) {\r
-         _s._wD('No width/height given, assuming defaults');\r
-         oMetaData.width = 320;\r
-         oMetaData.height = 240;\r
-    };\r
-    _t.metadata = oMetaData; // potentially-large object from flash\r
-    _t.width = oMetaData.width;\r
-    _t.height = oMetaData.height;\r
-    if (_t._iO.onmetadata) {\r
-      _s._wD('SMSound._onmetadata(): "'+_t.sID+'"');\r
-      _t._iO.onmetadata.apply(_t);\r
-    }\r
-    _s.wD('SMSound.onmetadata() complete');\r
-  };\r
-\r
-  }; // SMSound()\r
-\r
-  // register a few event handlers\r
-  if (window.addEventListener) {\r
-    window.addEventListener('focus',_s.handleFocus,false);\r
-    window.addEventListener('load',_s.beginDelayedInit,false);\r
-    window.addEventListener('unload',_s.destruct,false);\r
-    if (_s._tryInitOnFocus) window.addEventListener('mousemove',_s.handleFocus,false); // massive Safari focus hack\r
-  } else if (window.attachEvent) {\r
-    window.attachEvent('onfocus',_s.handleFocus);\r
-    window.attachEvent('onload',_s.beginDelayedInit);\r
-    window.attachEvent('unload',_s.destruct);\r
-  } else {\r
-    // no add/attachevent support - safe to assume no JS -> Flash either.\r
-    soundManager.onerror();\r
-    soundManager.disable();\r
-  };\r
-\r
-  if (document.addEventListener) document.addEventListener('DOMContentLoaded',_s.domContentLoaded,false);\r
-\r
-}; // SoundManager()\r
-\r
-var soundManager = new SoundManager();\r
diff --git a/ui/lib/soundmanager2.swf b/ui/lib/soundmanager2.swf
deleted file mode 100755 (executable)
index 98ed98d..0000000
Binary files a/ui/lib/soundmanager2.swf and /dev/null differ
diff --git a/ui/lib/soundmanager2_flash9.swf b/ui/lib/soundmanager2_flash9.swf
deleted file mode 100755 (executable)
index 14e4578..0000000
Binary files a/ui/lib/soundmanager2_flash9.swf and /dev/null differ
diff --git a/ui/lib/wz_jsgraphics.js b/ui/lib/wz_jsgraphics.js
deleted file mode 100755 (executable)
index b3d1054..0000000
+++ /dev/null
@@ -1,1107 +0,0 @@
-/* This notice must be untouched at all times.\r
-\r
-wz_jsgraphics.js    v. 3.03\r
-The latest version is available at\r
-http://www.walterzorn.com\r
-or http://www.devira.com\r
-or http://www.walterzorn.de\r
-\r
-Copyright (c) 2002-2004 Walter Zorn. All rights reserved.\r
-Created 3. 11. 2002 by Walter Zorn (Web: http://www.walterzorn.com )\r
-Last modified: 28. 1. 2008\r
-\r
-Performance optimizations for Internet Explorer\r
-by Thomas Frank and John Holdsworth.\r
-fillPolygon method implemented by Matthieu Haller.\r
-\r
-High Performance JavaScript Graphics Library.\r
-Provides methods\r
-- to draw lines, rectangles, ellipses, polygons\r
-       with specifiable line thickness,\r
-- to fill rectangles, polygons, ellipses and arcs\r
-- to draw text.\r
-NOTE: Operations, functions and branching have rather been optimized\r
-to efficiency and speed than to shortness of source code.\r
-\r
-LICENSE: LGPL\r
-\r
-This library is free software; you can redistribute it and/or\r
-modify it under the terms of the GNU Lesser General Public\r
-License (LGPL) as published by the Free Software Foundation; either\r
-version 2.1 of the License, or (at your option) any later version.\r
-\r
-This library is distributed in the hope that it will be useful,\r
-but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-Lesser General Public License for more details.\r
-\r
-You should have received a copy of the GNU Lesser General Public\r
-License along with this library; if not, write to the Free Software\r
-Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA,\r
-or see http://www.gnu.org/copyleft/lesser.html\r
-*/\r
-\r
-\r
-var jg_ok, jg_ie, jg_fast, jg_dom, jg_moz;\r
-\r
-\r
-function _chkDHTM(x, i)\r
-{\r
-       x = document.body || null;\r
-       jg_ie = x && typeof x.insertAdjacentHTML != "undefined" && document.createElement;\r
-       jg_dom = (x && !jg_ie &&\r
-               typeof x.appendChild != "undefined" &&\r
-               typeof document.createRange != "undefined" &&\r
-               typeof (i = document.createRange()).setStartBefore != "undefined" &&\r
-               typeof i.createContextualFragment != "undefined");\r
-       jg_fast = jg_ie && document.all && !window.opera;\r
-       jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined";\r
-       jg_ok = !!(jg_ie || jg_dom);\r
-}\r
-\r
-function _pntCnvDom()\r
-{\r
-       var x = this.wnd.document.createRange();\r
-       x.setStartBefore(this.cnv);\r
-       x = x.createContextualFragment(jg_fast? this._htmRpc() : this.htm);\r
-       if(this.cnv) this.cnv.appendChild(x);\r
-       this.htm = "";\r
-}\r
-\r
-function _pntCnvIe()\r
-{\r
-       if(this.cnv) this.cnv.insertAdjacentHTML("BeforeEnd", jg_fast? this._htmRpc() : this.htm);\r
-       this.htm = "";\r
-}\r
-\r
-function _pntDoc()\r
-{\r
-       this.wnd.document.write(jg_fast? this._htmRpc() : this.htm);\r
-       this.htm = '';\r
-}\r
-\r
-function _pntN()\r
-{\r
-       ;\r
-}\r
-\r
-function _mkDiv(x, y, w, h)\r
-{\r
-       this.htm += '<div style="position:absolute;'+\r
-               'left:' + x + 'px;'+\r
-               'top:' + y + 'px;'+\r
-               'width:' + w + 'px;'+\r
-               'height:' + h + 'px;'+\r
-               'clip:rect(0,'+w+'px,'+h+'px,0);'+\r
-               'background-color:' + this.color +\r
-               (!jg_moz? ';overflow:hidden' : '')+\r
-               ';"><\/div>';\r
-}\r
-\r
-function _mkDivIe(x, y, w, h)\r
-{\r
-       this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';\r
-}\r
-\r
-function _mkDivPrt(x, y, w, h)\r
-{\r
-       this.htm += '<div style="position:absolute;'+\r
-               'border-left:' + w + 'px solid ' + this.color + ';'+\r
-               'left:' + x + 'px;'+\r
-               'top:' + y + 'px;'+\r
-               'width:0px;'+\r
-               'height:' + h + 'px;'+\r
-               'clip:rect(0,'+w+'px,'+h+'px,0);'+\r
-               'background-color:' + this.color +\r
-               (!jg_moz? ';overflow:hidden' : '')+\r
-               ';"><\/div>';\r
-}\r
-\r
-var _regex =  /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;\r
-function _htmRpc()\r
-{\r
-       return this.htm.replace(\r
-               _regex,\r
-               '<div style="overflow:hidden;position:absolute;background-color:'+\r
-               '$1;left:$2;top:$3;width:$4;height:$5"></div>\n');\r
-}\r
-\r
-function _htmPrtRpc()\r
-{\r
-       return this.htm.replace(\r
-               _regex,\r
-               '<div style="overflow:hidden;position:absolute;background-color:'+\r
-               '$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');\r
-}\r
-\r
-function _mkLin(x1, y1, x2, y2)\r
-{\r
-       if(x1 > x2)\r
-       {\r
-               var _x2 = x2;\r
-               var _y2 = y2;\r
-               x2 = x1;\r
-               y2 = y1;\r
-               x1 = _x2;\r
-               y1 = _y2;\r
-       }\r
-       var dx = x2-x1, dy = Math.abs(y2-y1),\r
-       x = x1, y = y1,\r
-       yIncr = (y1 > y2)? -1 : 1;\r
-\r
-       if(dx >= dy)\r
-       {\r
-               var pr = dy<<1,\r
-               pru = pr - (dx<<1),\r
-               p = pr-dx,\r
-               ox = x;\r
-               while(dx > 0)\r
-               {--dx;\r
-                       ++x;\r
-                       if(p > 0)\r
-                       {\r
-                               this._mkDiv(ox, y, x-ox, 1);\r
-                               y += yIncr;\r
-                               p += pru;\r
-                               ox = x;\r
-                       }\r
-                       else p += pr;\r
-               }\r
-               this._mkDiv(ox, y, x2-ox+1, 1);\r
-       }\r
-\r
-       else\r
-       {\r
-               var pr = dx<<1,\r
-               pru = pr - (dy<<1),\r
-               p = pr-dy,\r
-               oy = y;\r
-               if(y2 <= y1)\r
-               {\r
-                       while(dy > 0)\r
-                       {--dy;\r
-                               if(p > 0)\r
-                               {\r
-                                       this._mkDiv(x++, y, 1, oy-y+1);\r
-                                       y += yIncr;\r
-                                       p += pru;\r
-                                       oy = y;\r
-                               }\r
-                               else\r
-                               {\r
-                                       y += yIncr;\r
-                                       p += pr;\r
-                               }\r
-                       }\r
-                       this._mkDiv(x2, y2, 1, oy-y2+1);\r
-               }\r
-               else\r
-               {\r
-                       while(dy > 0)\r
-                       {--dy;\r
-                               y += yIncr;\r
-                               if(p > 0)\r
-                               {\r
-                                       this._mkDiv(x++, oy, 1, y-oy);\r
-                                       p += pru;\r
-                                       oy = y;\r
-                               }\r
-                               else p += pr;\r
-                       }\r
-                       this._mkDiv(x2, oy, 1, y2-oy+1);\r
-               }\r
-       }\r
-}\r
-\r
-function _mkLin2D(x1, y1, x2, y2)\r
-{\r
-       if(x1 > x2)\r
-       {\r
-               var _x2 = x2;\r
-               var _y2 = y2;\r
-               x2 = x1;\r
-               y2 = y1;\r
-               x1 = _x2;\r
-               y1 = _y2;\r
-       }\r
-       var dx = x2-x1, dy = Math.abs(y2-y1),\r
-       x = x1, y = y1,\r
-       yIncr = (y1 > y2)? -1 : 1;\r
-\r
-       var s = this.stroke;\r
-       if(dx >= dy)\r
-       {\r
-               if(dx > 0 && s-3 > 0)\r
-               {\r
-                       var _s = (s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy) / dx;\r
-                       _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;\r
-               }\r
-               else var _s = s;\r
-               var ad = Math.ceil(s/2);\r
-\r
-               var pr = dy<<1,\r
-               pru = pr - (dx<<1),\r
-               p = pr-dx,\r
-               ox = x;\r
-               while(dx > 0)\r
-               {--dx;\r
-                       ++x;\r
-                       if(p > 0)\r
-                       {\r
-                               this._mkDiv(ox, y, x-ox+ad, _s);\r
-                               y += yIncr;\r
-                               p += pru;\r
-                               ox = x;\r
-                       }\r
-                       else p += pr;\r
-               }\r
-               this._mkDiv(ox, y, x2-ox+ad+1, _s);\r
-       }\r
-\r
-       else\r
-       {\r
-               if(s-3 > 0)\r
-               {\r
-                       var _s = (s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy) / dy;\r
-                       _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1;\r
-               }\r
-               else var _s = s;\r
-               var ad = Math.round(s/2);\r
-\r
-               var pr = dx<<1,\r
-               pru = pr - (dy<<1),\r
-               p = pr-dy,\r
-               oy = y;\r
-               if(y2 <= y1)\r
-               {\r
-                       ++ad;\r
-                       while(dy > 0)\r
-                       {--dy;\r
-                               if(p > 0)\r
-                               {\r
-                                       this._mkDiv(x++, y, _s, oy-y+ad);\r
-                                       y += yIncr;\r
-                                       p += pru;\r
-                                       oy = y;\r
-                               }\r
-                               else\r
-                               {\r
-                                       y += yIncr;\r
-                                       p += pr;\r
-                               }\r
-                       }\r
-                       this._mkDiv(x2, y2, _s, oy-y2+ad);\r
-               }\r
-               else\r
-               {\r
-                       while(dy > 0)\r
-                       {--dy;\r
-                               y += yIncr;\r
-                               if(p > 0)\r
-                               {\r
-                                       this._mkDiv(x++, oy, _s, y-oy+ad);\r
-                                       p += pru;\r
-                                       oy = y;\r
-                               }\r
-                               else p += pr;\r
-                       }\r
-                       this._mkDiv(x2, oy, _s, y2-oy+ad+1);\r
-               }\r
-       }\r
-}\r
-\r
-function _mkLinDott(x1, y1, x2, y2)\r
-{\r
-       if(x1 > x2)\r
-       {\r
-               var _x2 = x2;\r
-               var _y2 = y2;\r
-               x2 = x1;\r
-               y2 = y1;\r
-               x1 = _x2;\r
-               y1 = _y2;\r
-       }\r
-       var dx = x2-x1, dy = Math.abs(y2-y1),\r
-       x = x1, y = y1,\r
-       yIncr = (y1 > y2)? -1 : 1,\r
-       drw = true;\r
-       if(dx >= dy)\r
-       {\r
-               var pr = dy<<1,\r
-               pru = pr - (dx<<1),\r
-               p = pr-dx;\r
-               while(dx > 0)\r
-               {--dx;\r
-                       if(drw) this._mkDiv(x, y, 1, 1);\r
-                       drw = !drw;\r
-                       if(p > 0)\r
-                       {\r
-                               y += yIncr;\r
-                               p += pru;\r
-                       }\r
-                       else p += pr;\r
-                       ++x;\r
-               }\r
-       }\r
-       else\r
-       {\r
-               var pr = dx<<1,\r
-               pru = pr - (dy<<1),\r
-               p = pr-dy;\r
-               while(dy > 0)\r
-               {--dy;\r
-                       if(drw) this._mkDiv(x, y, 1, 1);\r
-                       drw = !drw;\r
-                       y += yIncr;\r
-                       if(p > 0)\r
-                       {\r
-                               ++x;\r
-                               p += pru;\r
-                       }\r
-                       else p += pr;\r
-               }\r
-       }\r
-       if(drw) this._mkDiv(x, y, 1, 1);\r
-}\r
-\r
-function _mkOv(left, top, width, height)\r
-{\r
-       var a = (++width)>>1, b = (++height)>>1,\r
-       wod = width&1, hod = height&1,\r
-       cx = left+a, cy = top+b,\r
-       x = 0, y = b,\r
-       ox = 0, oy = b,\r
-       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
-       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
-       tt = (bb2>>1) - aa2*((b<<1)-1),\r
-       w, h;\r
-       while(y > 0)\r
-       {\r
-               if(st < 0)\r
-               {\r
-                       st += bb2*((x<<1)+3);\r
-                       tt += bb4*(++x);\r
-               }\r
-               else if(tt < 0)\r
-               {\r
-                       st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                       tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-                       w = x-ox;\r
-                       h = oy-y;\r
-                       if((w&2) && (h&2))\r
-                       {\r
-                               this._mkOvQds(cx, cy, x-2, y+2, 1, 1, wod, hod);\r
-                               this._mkOvQds(cx, cy, x-1, y+1, 1, 1, wod, hod);\r
-                       }\r
-                       else this._mkOvQds(cx, cy, x-1, oy, w, h, wod, hod);\r
-                       ox = x;\r
-                       oy = y;\r
-               }\r
-               else\r
-               {\r
-                       tt -= aa2*((y<<1)-3);\r
-                       st -= aa4*(--y);\r
-               }\r
-       }\r
-       w = a-ox+1;\r
-       h = (oy<<1)+hod;\r
-       y = cy-oy;\r
-       this._mkDiv(cx-a, y, w, h);\r
-       this._mkDiv(cx+ox+wod-1, y, w, h);\r
-}\r
-\r
-function _mkOv2D(left, top, width, height)\r
-{\r
-       var s = this.stroke;\r
-       width += s+1;\r
-       height += s+1;\r
-       var a = width>>1, b = height>>1,\r
-       wod = width&1, hod = height&1,\r
-       cx = left+a, cy = top+b,\r
-       x = 0, y = b,\r
-       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
-       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
-       tt = (bb2>>1) - aa2*((b<<1)-1);\r
-\r
-       if(s-4 < 0 && (!(s-2) || width-51 > 0 && height-51 > 0))\r
-       {\r
-               var ox = 0, oy = b,\r
-               w, h,\r
-               pxw;\r
-               while(y > 0)\r
-               {\r
-                       if(st < 0)\r
-                       {\r
-                               st += bb2*((x<<1)+3);\r
-                               tt += bb4*(++x);\r
-                       }\r
-                       else if(tt < 0)\r
-                       {\r
-                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-                               w = x-ox;\r
-                               h = oy-y;\r
-\r
-                               if(w-1)\r
-                               {\r
-                                       pxw = w+1+(s&1);\r
-                                       h = s;\r
-                               }\r
-                               else if(h-1)\r
-                               {\r
-                                       pxw = s;\r
-                                       h += 1+(s&1);\r
-                               }\r
-                               else pxw = h = s;\r
-                               this._mkOvQds(cx, cy, x-1, oy, pxw, h, wod, hod);\r
-                               ox = x;\r
-                               oy = y;\r
-                       }\r
-                       else\r
-                       {\r
-                               tt -= aa2*((y<<1)-3);\r
-                               st -= aa4*(--y);\r
-                       }\r
-               }\r
-               this._mkDiv(cx-a, cy-oy, s, (oy<<1)+hod);\r
-               this._mkDiv(cx+a+wod-s, cy-oy, s, (oy<<1)+hod);\r
-       }\r
-\r
-       else\r
-       {\r
-               var _a = (width-(s<<1))>>1,\r
-               _b = (height-(s<<1))>>1,\r
-               _x = 0, _y = _b,\r
-               _aa2 = (_a*_a)<<1, _aa4 = _aa2<<1, _bb2 = (_b*_b)<<1, _bb4 = _bb2<<1,\r
-               _st = (_aa2>>1)*(1-(_b<<1)) + _bb2,\r
-               _tt = (_bb2>>1) - _aa2*((_b<<1)-1),\r
-\r
-               pxl = new Array(),\r
-               pxt = new Array(),\r
-               _pxb = new Array();\r
-               pxl[0] = 0;\r
-               pxt[0] = b;\r
-               _pxb[0] = _b-1;\r
-               while(y > 0)\r
-               {\r
-                       if(st < 0)\r
-                       {\r
-                               pxl[pxl.length] = x;\r
-                               pxt[pxt.length] = y;\r
-                               st += bb2*((x<<1)+3);\r
-                               tt += bb4*(++x);\r
-                       }\r
-                       else if(tt < 0)\r
-                       {\r
-                               pxl[pxl.length] = x;\r
-                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-                               pxt[pxt.length] = y;\r
-                       }\r
-                       else\r
-                       {\r
-                               tt -= aa2*((y<<1)-3);\r
-                               st -= aa4*(--y);\r
-                       }\r
-\r
-                       if(_y > 0)\r
-                       {\r
-                               if(_st < 0)\r
-                               {\r
-                                       _st += _bb2*((_x<<1)+3);\r
-                                       _tt += _bb4*(++_x);\r
-                                       _pxb[_pxb.length] = _y-1;\r
-                               }\r
-                               else if(_tt < 0)\r
-                               {\r
-                                       _st += _bb2*((_x<<1)+3) - _aa4*(_y-1);\r
-                                       _tt += _bb4*(++_x) - _aa2*(((_y--)<<1)-3);\r
-                                       _pxb[_pxb.length] = _y-1;\r
-                               }\r
-                               else\r
-                               {\r
-                                       _tt -= _aa2*((_y<<1)-3);\r
-                                       _st -= _aa4*(--_y);\r
-                                       _pxb[_pxb.length-1]--;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               var ox = -wod, oy = b,\r
-               _oy = _pxb[0],\r
-               l = pxl.length,\r
-               w, h;\r
-               for(var i = 0; i < l; i++)\r
-               {\r
-                       if(typeof _pxb[i] != "undefined")\r
-                       {\r
-                               if(_pxb[i] < _oy || pxt[i] < oy)\r
-                               {\r
-                                       x = pxl[i];\r
-                                       this._mkOvQds(cx, cy, x, oy, x-ox, oy-_oy, wod, hod);\r
-                                       ox = x;\r
-                                       oy = pxt[i];\r
-                                       _oy = _pxb[i];\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               x = pxl[i];\r
-                               this._mkDiv(cx-x, cy-oy, 1, (oy<<1)+hod);\r
-                               this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);\r
-                               ox = x;\r
-                               oy = pxt[i];\r
-                       }\r
-               }\r
-               this._mkDiv(cx-a, cy-oy, 1, (oy<<1)+hod);\r
-               this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod);\r
-       }\r
-}\r
-\r
-function _mkOvDott(left, top, width, height)\r
-{\r
-       var a = (++width)>>1, b = (++height)>>1,\r
-       wod = width&1, hod = height&1, hodu = hod^1,\r
-       cx = left+a, cy = top+b,\r
-       x = 0, y = b,\r
-       aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
-       st = (aa2>>1)*(1-(b<<1)) + bb2,\r
-       tt = (bb2>>1) - aa2*((b<<1)-1),\r
-       drw = true;\r
-       while(y > 0)\r
-       {\r
-               if(st < 0)\r
-               {\r
-                       st += bb2*((x<<1)+3);\r
-                       tt += bb4*(++x);\r
-               }\r
-               else if(tt < 0)\r
-               {\r
-                       st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                       tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-               }\r
-               else\r
-               {\r
-                       tt -= aa2*((y<<1)-3);\r
-                       st -= aa4*(--y);\r
-               }\r
-               if(drw && y >= hodu) this._mkOvQds(cx, cy, x, y, 1, 1, wod, hod);\r
-               drw = !drw;\r
-       }\r
-}\r
-\r
-function _mkRect(x, y, w, h)\r
-{\r
-       var s = this.stroke;\r
-       this._mkDiv(x, y, w, s);\r
-       this._mkDiv(x+w, y, s, h);\r
-       this._mkDiv(x, y+h, w+s, s);\r
-       this._mkDiv(x, y+s, s, h-s);\r
-}\r
-\r
-function _mkRectDott(x, y, w, h)\r
-{\r
-       this.drawLine(x, y, x+w, y);\r
-       this.drawLine(x+w, y, x+w, y+h);\r
-       this.drawLine(x, y+h, x+w, y+h);\r
-       this.drawLine(x, y, x, y+h);\r
-}\r
-\r
-function jsgFont()\r
-{\r
-       this.PLAIN = 'font-weight:normal;';\r
-       this.BOLD = 'font-weight:bold;';\r
-       this.ITALIC = 'font-style:italic;';\r
-       this.ITALIC_BOLD = this.ITALIC + this.BOLD;\r
-       this.BOLD_ITALIC = this.ITALIC_BOLD;\r
-}\r
-var Font = new jsgFont();\r
-\r
-function jsgStroke()\r
-{\r
-       this.DOTTED = -1;\r
-}\r
-var Stroke = new jsgStroke();\r
-\r
-function jsGraphics(cnv, wnd)\r
-{\r
-       this.setColor = function(x)\r
-       {\r
-               this.color = x.toLowerCase();\r
-       };\r
-\r
-       this.setStroke = function(x)\r
-       {\r
-               this.stroke = x;\r
-               if(!(x+1))\r
-               {\r
-                       this.drawLine = _mkLinDott;\r
-                       this._mkOv = _mkOvDott;\r
-                       this.drawRect = _mkRectDott;\r
-               }\r
-               else if(x-1 > 0)\r
-               {\r
-                       this.drawLine = _mkLin2D;\r
-                       this._mkOv = _mkOv2D;\r
-                       this.drawRect = _mkRect;\r
-               }\r
-               else\r
-               {\r
-                       this.drawLine = _mkLin;\r
-                       this._mkOv = _mkOv;\r
-                       this.drawRect = _mkRect;\r
-               }\r
-       };\r
-\r
-       this.setPrintable = function(arg)\r
-       {\r
-               this.printable = arg;\r
-               if(jg_fast)\r
-               {\r
-                       this._mkDiv = _mkDivIe;\r
-                       this._htmRpc = arg? _htmPrtRpc : _htmRpc;\r
-               }\r
-               else this._mkDiv = arg? _mkDivPrt : _mkDiv;\r
-       };\r
-\r
-       this.setFont = function(fam, sz, sty)\r
-       {\r
-               this.ftFam = fam;\r
-               this.ftSz = sz;\r
-               this.ftSty = sty || Font.PLAIN;\r
-       };\r
-\r
-       this.drawPolyline = this.drawPolyLine = function(x, y)\r
-       {\r
-               for (var i=x.length - 1; i;)\r
-               {--i;\r
-                       this.drawLine(x[i], y[i], x[i+1], y[i+1]);\r
-               }\r
-       };\r
-\r
-       this.fillRect = function(x, y, w, h)\r
-       {\r
-               this._mkDiv(x, y, w, h);\r
-       };\r
-\r
-       this.drawPolygon = function(x, y)\r
-       {\r
-               this.drawPolyline(x, y);\r
-               this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]);\r
-       };\r
-\r
-       this.drawEllipse = this.drawOval = function(x, y, w, h)\r
-       {\r
-               this._mkOv(x, y, w, h);\r
-       };\r
-\r
-       this.fillEllipse = this.fillOval = function(left, top, w, h)\r
-       {\r
-               var a = w>>1, b = h>>1,\r
-               wod = w&1, hod = h&1,\r
-               cx = left+a, cy = top+b,\r
-               x = 0, y = b, oy = b,\r
-               aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
-               st = (aa2>>1)*(1-(b<<1)) + bb2,\r
-               tt = (bb2>>1) - aa2*((b<<1)-1),\r
-               xl, dw, dh;\r
-               if(w) while(y > 0)\r
-               {\r
-                       if(st < 0)\r
-                       {\r
-                               st += bb2*((x<<1)+3);\r
-                               tt += bb4*(++x);\r
-                       }\r
-                       else if(tt < 0)\r
-                       {\r
-                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                               xl = cx-x;\r
-                               dw = (x<<1)+wod;\r
-                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-                               dh = oy-y;\r
-                               this._mkDiv(xl, cy-oy, dw, dh);\r
-                               this._mkDiv(xl, cy+y+hod, dw, dh);\r
-                               oy = y;\r
-                       }\r
-                       else\r
-                       {\r
-                               tt -= aa2*((y<<1)-3);\r
-                               st -= aa4*(--y);\r
-                       }\r
-               }\r
-               this._mkDiv(cx-a, cy-oy, w, (oy<<1)+hod);\r
-       };\r
-\r
-       this.fillArc = function(iL, iT, iW, iH, fAngA, fAngZ)\r
-       {\r
-               var a = iW>>1, b = iH>>1,\r
-               iOdds = (iW&1) | ((iH&1) << 16),\r
-               cx = iL+a, cy = iT+b,\r
-               x = 0, y = b, ox = x, oy = y,\r
-               aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1,\r
-               st = (aa2>>1)*(1-(b<<1)) + bb2,\r
-               tt = (bb2>>1) - aa2*((b<<1)-1),\r
-               // Vars for radial boundary lines\r
-               xEndA, yEndA, xEndZ, yEndZ,\r
-               iSects = (1 << (Math.floor((fAngA %= 360.0)/180.0) << 3))\r
-                               | (2 << (Math.floor((fAngZ %= 360.0)/180.0) << 3))\r
-                               | ((fAngA >= fAngZ) << 16),\r
-               aBndA = new Array(b+1), aBndZ = new Array(b+1);\r
-               \r
-               // Set up radial boundary lines\r
-               fAngA *= Math.PI/180.0;\r
-               fAngZ *= Math.PI/180.0;\r
-               xEndA = cx+Math.round(a*Math.cos(fAngA));\r
-               yEndA = cy+Math.round(-b*Math.sin(fAngA));\r
-               _mkLinVirt(aBndA, cx, cy, xEndA, yEndA);\r
-               xEndZ = cx+Math.round(a*Math.cos(fAngZ));\r
-               yEndZ = cy+Math.round(-b*Math.sin(fAngZ));\r
-               _mkLinVirt(aBndZ, cx, cy, xEndZ, yEndZ);\r
-\r
-               while(y > 0)\r
-               {\r
-                       if(st < 0) // Advance x\r
-                       {\r
-                               st += bb2*((x<<1)+3);\r
-                               tt += bb4*(++x);\r
-                       }\r
-                       else if(tt < 0) // Advance x and y\r
-                       {\r
-                               st += bb2*((x<<1)+3) - aa4*(y-1);\r
-                               ox = x;\r
-                               tt += bb4*(++x) - aa2*(((y--)<<1)-3);\r
-                               this._mkArcDiv(ox, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
-                               oy = y;\r
-                       }\r
-                       else // Advance y\r
-                       {\r
-                               tt -= aa2*((y<<1)-3);\r
-                               st -= aa4*(--y);\r
-                               if(y && (aBndA[y] != aBndA[y-1] || aBndZ[y] != aBndZ[y-1]))\r
-                               {\r
-                                       this._mkArcDiv(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
-                                       ox = x;\r
-                                       oy = y;\r
-                               }\r
-                       }\r
-               }\r
-               this._mkArcDiv(x, 0, oy, cx, cy, iOdds, aBndA, aBndZ, iSects);\r
-               if(iOdds >> 16) // Odd height\r
-               {\r
-                       if(iSects >> 16) // Start-angle > end-angle\r
-                       {\r
-                               var xl = (yEndA <= cy || yEndZ > cy)? (cx - x) : cx;\r
-                               this._mkDiv(xl, cy, x + cx - xl + (iOdds & 0xffff), 1);\r
-                       }\r
-                       else if((iSects & 0x01) && yEndZ > cy)\r
-                               this._mkDiv(cx - x, cy, x, 1);\r
-               }\r
-       };\r
-\r
-/* fillPolygon method, implemented by Matthieu Haller.\r
-This javascript function is an adaptation of the gdImageFilledPolygon for Walter Zorn lib.\r
-C source of GD 1.8.4 found at http://www.boutell.com/gd/\r
-\r
-THANKS to Kirsten Schulz for the polygon fixes!\r
-\r
-The intersection finding technique of this code could be improved\r
-by remembering the previous intertersection, and by using the slope.\r
-That could help to adjust intersections to produce a nice\r
-interior_extrema. */\r
-       this.fillPolygon = function(array_x, array_y)\r
-       {\r
-               var i;\r
-               var y;\r
-               var miny, maxy;\r
-               var x1, y1;\r
-               var x2, y2;\r
-               var ind1, ind2;\r
-               var ints;\r
-\r
-               var n = array_x.length;\r
-               if(!n) return;\r
-\r
-               miny = array_y[0];\r
-               maxy = array_y[0];\r
-               for(i = 1; i < n; i++)\r
-               {\r
-                       if(array_y[i] < miny)\r
-                               miny = array_y[i];\r
-\r
-                       if(array_y[i] > maxy)\r
-                               maxy = array_y[i];\r
-               }\r
-               for(y = miny; y <= maxy; y++)\r
-               {\r
-                       var polyInts = new Array();\r
-                       ints = 0;\r
-                       for(i = 0; i < n; i++)\r
-                       {\r
-                               if(!i)\r
-                               {\r
-                                       ind1 = n-1;\r
-                                       ind2 = 0;\r
-                               }\r
-                               else\r
-                               {\r
-                                       ind1 = i-1;\r
-                                       ind2 = i;\r
-                               }\r
-                               y1 = array_y[ind1];\r
-                               y2 = array_y[ind2];\r
-                               if(y1 < y2)\r
-                               {\r
-                                       x1 = array_x[ind1];\r
-                                       x2 = array_x[ind2];\r
-                               }\r
-                               else if(y1 > y2)\r
-                               {\r
-                                       y2 = array_y[ind1];\r
-                                       y1 = array_y[ind2];\r
-                                       x2 = array_x[ind1];\r
-                                       x1 = array_x[ind2];\r
-                               }\r
-                               else continue;\r
-\r
-                                //  Modified 11. 2. 2004 Walter Zorn\r
-                               if((y >= y1) && (y < y2))\r
-                                       polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);\r
-\r
-                               else if((y == maxy) && (y > y1) && (y <= y2))\r
-                                       polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1);\r
-                       }\r
-                       polyInts.sort(_CompInt);\r
-                       for(i = 0; i < ints; i+=2)\r
-                               this._mkDiv(polyInts[i], y, polyInts[i+1]-polyInts[i]+1, 1);\r
-               }\r
-       };\r
-\r
-       this.drawString = function(txt, x, y)\r
-       {\r
-               this.htm += '<div style="position:absolute;white-space:nowrap;'+\r
-                       'left:' + x + 'px;'+\r
-                       'top:' + y + 'px;'+\r
-                       'font-family:' +  this.ftFam + ';'+\r
-                       'font-size:' + this.ftSz + ';'+\r
-                       'color:' + this.color + ';' + this.ftSty + '">'+\r
-                       txt +\r
-                       '<\/div>';\r
-       };\r
-\r
-/* drawStringRect() added by Rick Blommers.\r
-Allows to specify the size of the text rectangle and to align the\r
-text both horizontally (e.g. right) and vertically within that rectangle */\r
-       this.drawStringRect = function(txt, x, y, width, halign)\r
-       {\r
-               this.htm += '<div style="position:absolute;overflow:hidden;'+\r
-                       'left:' + x + 'px;'+\r
-                       'top:' + y + 'px;'+\r
-                       'width:'+width +'px;'+\r
-                       'text-align:'+halign+';'+\r
-                       'font-family:' +  this.ftFam + ';'+\r
-                       'font-size:' + this.ftSz + ';'+\r
-                       'color:' + this.color + ';' + this.ftSty + '">'+\r
-                       txt +\r
-                       '<\/div>';\r
-       };\r
-\r
-       this.drawImage = function(imgSrc, x, y, w, h, a)\r
-       {\r
-               this.htm += '<div style="position:absolute;'+\r
-                       'left:' + x + 'px;'+\r
-                       'top:' + y + 'px;'+\r
-                       // w (width) and h (height) arguments are now optional.\r
-                       // Added by Mahmut Keygubatli, 14.1.2008\r
-                       (w? ('width:' +  w + 'px;') : '') +\r
-                       (h? ('height:' + h + 'px;'):'')+'">'+\r
-                       '<img src="' + imgSrc +'"'+ (w ? (' width="' + w + '"'):'')+ (h ? (' height="' + h + '"'):'') + (a? (' '+a) : '') + '>'+\r
-                       '<\/div>';\r
-       };\r
-\r
-       this.clear = function()\r
-       {\r
-               this.htm = "";\r
-               if(this.cnv) this.cnv.innerHTML = "";\r
-       };\r
-\r
-       this._mkOvQds = function(cx, cy, x, y, w, h, wod, hod)\r
-       {\r
-               var xl = cx - x, xr = cx + x + wod - w, yt = cy - y, yb = cy + y + hod - h;\r
-               if(xr > xl+w)\r
-               {\r
-                       this._mkDiv(xr, yt, w, h);\r
-                       this._mkDiv(xr, yb, w, h);\r
-               }\r
-               else\r
-                       w = xr - xl + w;\r
-               this._mkDiv(xl, yt, w, h);\r
-               this._mkDiv(xl, yb, w, h);\r
-       };\r
-       \r
-       this._mkArcDiv = function(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects)\r
-       {\r
-               var xrDef = cx + x + (iOdds & 0xffff), y2, h = oy - y, xl, xr, w;\r
-\r
-               if(!h) h = 1;\r
-               x = cx - x;\r
-\r
-               if(iSects & 0xff0000) // Start-angle > end-angle\r
-               {\r
-                       y2 = cy - y - h;\r
-                       if(iSects & 0x00ff)\r
-                       {\r
-                               if(iSects & 0x02)\r
-                               {\r
-                                       xl = Math.max(x, aBndZ[y]);\r
-                                       w = xrDef - xl;\r
-                                       if(w > 0) this._mkDiv(xl, y2, w, h);\r
-                               }\r
-                               if(iSects & 0x01)\r
-                               {\r
-                                       xr = Math.min(xrDef, aBndA[y]);\r
-                                       w = xr - x;\r
-                                       if(w > 0) this._mkDiv(x, y2, w, h);\r
-                               }\r
-                       }\r
-                       else\r
-                               this._mkDiv(x, y2, xrDef - x, h);\r
-                       y2 = cy + y + (iOdds >> 16);\r
-                       if(iSects & 0xff00)\r
-                       {\r
-                               if(iSects & 0x0100)\r
-                               {\r
-                                       xl = Math.max(x, aBndA[y]);\r
-                                       w = xrDef - xl;\r
-                                       if(w > 0) this._mkDiv(xl, y2, w, h);\r
-                               }\r
-                               if(iSects & 0x0200)\r
-                               {\r
-                                       xr = Math.min(xrDef, aBndZ[y]);\r
-                                       w = xr - x;\r
-                                       if(w > 0) this._mkDiv(x, y2, w, h);\r
-                               }\r
-                       }\r
-                       else\r
-                               this._mkDiv(x, y2, xrDef - x, h);\r
-               }\r
-               else\r
-               {\r
-                       if(iSects & 0x00ff)\r
-                       {\r
-                               if(iSects & 0x02)\r
-                                       xl = Math.max(x, aBndZ[y]);\r
-                               else\r
-                                       xl = x;\r
-                               if(iSects & 0x01)\r
-                                       xr = Math.min(xrDef, aBndA[y]);\r
-                               else\r
-                                       xr = xrDef;\r
-                               y2 = cy - y - h;\r
-                               w = xr - xl;\r
-                               if(w > 0) this._mkDiv(xl, y2, w, h);\r
-                       }\r
-                       if(iSects & 0xff00)\r
-                       {\r
-                               if(iSects & 0x0100)\r
-                                       xl = Math.max(x, aBndA[y]);\r
-                               else\r
-                                       xl = x;\r
-                               if(iSects & 0x0200)\r
-                                       xr = Math.min(xrDef, aBndZ[y]);\r
-                               else\r
-                                       xr = xrDef;\r
-                               y2 = cy + y + (iOdds >> 16);\r
-                               w = xr - xl;\r
-                               if(w > 0) this._mkDiv(xl, y2, w, h);\r
-                       }\r
-               }\r
-       };\r
-\r
-       this.setStroke(1);\r
-       this.setFont("verdana,geneva,helvetica,sans-serif", "12px", Font.PLAIN);\r
-       this.color = "#000000";\r
-       this.htm = "";\r
-       this.wnd = wnd || window;\r
-\r
-       if(!jg_ok) _chkDHTM();\r
-       if(jg_ok)\r
-       {\r
-               if(cnv)\r
-               {\r
-                       if(typeof(cnv) == "string")\r
-                               this.cont = document.all? (this.wnd.document.all[cnv] || null)\r
-                                       : document.getElementById? (this.wnd.document.getElementById(cnv) || null)\r
-                                       : null;\r
-                       else if(cnv == window.document)\r
-                               this.cont = document.getElementsByTagName("body")[0];\r
-                       // If cnv is a direct reference to a canvas DOM node\r
-                       // (option suggested by Andreas Luleich)\r
-                       else this.cont = cnv;\r
-                       // Create new canvas inside container DIV. Thus the drawing and clearing\r
-                       // methods won't interfere with the container's inner html.\r
-                       // Solution suggested by Vladimir.\r
-                       this.cnv = this.wnd.document.createElement("div");\r
-                       this.cnv.style.fontSize=0;\r
-                       this.cont.appendChild(this.cnv);\r
-                       this.paint = jg_dom? _pntCnvDom : _pntCnvIe;\r
-               }\r
-               else\r
-                       this.paint = _pntDoc;\r
-       }\r
-       else\r
-               this.paint = _pntN;\r
-\r
-       this.setPrintable(false);\r
-}\r
-\r
-function _mkLinVirt(aLin, x1, y1, x2, y2)\r
-{\r
-       var dx = Math.abs(x2-x1), dy = Math.abs(y2-y1),\r
-       x = x1, y = y1,\r
-       xIncr = (x1 > x2)? -1 : 1,\r
-       yIncr = (y1 > y2)? -1 : 1,\r
-       p,\r
-       i = 0;\r
-       if(dx >= dy)\r
-       {\r
-               var pr = dy<<1,\r
-               pru = pr - (dx<<1);\r
-               p = pr-dx;\r
-               while(dx > 0)\r
-               {--dx;\r
-                       if(p > 0)    //  Increment y\r
-                       {\r
-                               aLin[i++] = x;\r
-                               y += yIncr;\r
-                               p += pru;\r
-                       }\r
-                       else p += pr;\r
-                       x += xIncr;\r
-               }\r
-       }\r
-       else\r
-       {\r
-               var pr = dx<<1,\r
-               pru = pr - (dy<<1);\r
-               p = pr-dy;\r
-               while(dy > 0)\r
-               {--dy;\r
-                       y += yIncr;\r
-                       aLin[i++] = x;\r
-                       if(p > 0)    //  Increment x\r
-                       {\r
-                               x += xIncr;\r
-                               p += pru;\r
-                       }\r
-                       else p += pr;\r
-               }\r
-       }\r
-       for(var len = aLin.length, i = len-i; i;)\r
-               aLin[len-(i--)] = x;\r
-};\r
-\r
-function _CompInt(x, y)\r
-{\r
-       return(x - y);\r
-}\r
-\r
diff --git a/ui/skins/lab/img/controlbg.png b/ui/skins/lab/img/controlbg.png
deleted file mode 100755 (executable)
index 57840d0..0000000
Binary files a/ui/skins/lab/img/controlbg.png and /dev/null differ
diff --git a/ui/skins/lab/img/forward.png b/ui/skins/lab/img/forward.png
deleted file mode 100755 (executable)
index 86485d0..0000000
Binary files a/ui/skins/lab/img/forward.png and /dev/null differ
diff --git a/ui/skins/lab/img/pause.png b/ui/skins/lab/img/pause.png
deleted file mode 100755 (executable)
index d09ad51..0000000
Binary files a/ui/skins/lab/img/pause.png and /dev/null differ
diff --git a/ui/skins/lab/img/play.png b/ui/skins/lab/img/play.png
deleted file mode 100755 (executable)
index ccb87e8..0000000
Binary files a/ui/skins/lab/img/play.png and /dev/null differ
diff --git a/ui/skins/lab/img/rewind.png b/ui/skins/lab/img/rewind.png
deleted file mode 100755 (executable)
index ec45b38..0000000
Binary files a/ui/skins/lab/img/rewind.png and /dev/null differ
diff --git a/ui/skins/lab/img/setmarker.png b/ui/skins/lab/img/setmarker.png
deleted file mode 100644 (file)
index b642e82..0000000
Binary files a/ui/skins/lab/img/setmarker.png and /dev/null differ
diff --git a/ui/skins/lab/style.css b/ui/skins/lab/style.css
deleted file mode 100755 (executable)
index 5dcd353..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-.ts-skin-lab .ts-player {
-  background: #3c4251;
-  padding-top: 10px;
-  padding-bottom: 10px;
-  border: dotted #b2b2b2 1px;
-}
-
-.ts-skin-lab .ts-player .ts-viewer {
-  margin: 0 12px 10px 12px;
-  border: solid 1px white;
-}
-
-.ts-skin-lab .ts-player .ts-viewer .ts-marker {
-    color: white;
-    background: #7290bc;
-}
-
-.ts-skin-lab .ts-player .ts-viewer a.ts-marker, .ts-skin-lab .ts-player .ts-viewer a.ts-pointer {
-    text-decoration: none;
-    line-height: 13px;
-}
-
-.ts-skin-lab .ts-player .ts-viewer .ts-pointer {
-    color: #3c4251;
-    background: #e7e7e7;
-}
-
-.ts-skin-lab .ts-player .ts-ruler .ts-section .ts-label {
-    color: #c3c2cc;
-    background: #2a3242;
-    padding-bottom: 1px;
-    padding-left: 2px;
-    line-height: 13px;
-}
-
-.ts-skin-lab .ts-player .ts-ruler .ts-section .ts-lines {
-    background: #384051;
-    color: #9498a1;
-    border-bottom: solid 1px white;
-    line-height: 13px;
-}
-
-.ts-skin-lab .ts-player .ts-wave .ts-image {
-    background: #090e0d ;
-}
-
-.ts-skin-lab .ts-player .ts-control {
-    background: url('img/controlbg.png');
-    height: 28px;
-    border-top: dotted #b2b2b2 1px;
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-layout {
-    margin-left: 12px;
-    margin-right: 12px;
-    padding-top: 4px;
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback a {
-    display: block;
-    float: left;
-    width: 21px;
-    padding: 21px 0 0 0;
-    overflow: hidden;
-    height: 0px !important; 
-    height /**/:21px; /* for IE5/Win only */
-    margin-right: 1px;
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback a:hover {
-    background-position: 0 -21px;
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback .ts-play {
-    background-image: url('img/play.png');
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback .ts-pause {
-    background-image: url('img/pause.png');
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback .ts-rewind {
-    background-image: url('img/rewind.png');
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback .ts-forward {
-    background-image: url('img/forward.png');
-}
-
-.ts-skin-lab .ts-player .ts-control .ts-playback .ts-set-marker {
-    background-image: url('img/setmarker.png');
-}
-
-/* unused */
-.ts-skin-lab .ts-player .ts-marker-control .ts-set-marker {
-    display: block;
-    width: 89px;
-    padding: 21px 0 0 0;
-    overflow: hidden;
-    height: 0px !important; 
-    height /**/:21px; /* for IE5/Win only */
-    background-image: url('img/setmarker.gif');
-    margin: 5px auto 0 auto;
-}
-
-/* unused */
-.ts-skin-lab .ts-player .ts-marker-control .ts-set-marker:hover {
-    background-position: 0 -21px;
-}
-
-.ts-skin-lab .ts-player .ts-marker-control {
-    border-top: dotted #b2b2b2 1px;
-    border-bottom: dotted #b2b2b2 1px;
-    height: 30px;
-}
-
diff --git a/ui/src/controller.js b/ui/src/controller.js
deleted file mode 100644 (file)
index ba0870b..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N) {
-
-$N.Class.create("Controller", $N.Core, {
-
-    initialize: function($super, cfg) {
-        $super();
-        this.configure(cfg, {
-            player: null,
-            soundProvider: null,
-            map: null
-        });
-        if (this.cfg.player && !$N.isInstanceOf(this.cfg.player, 'Player')) {
-            this.cfg.player = new $N.Player(this.cfg.player);
-        }
-        this._setupPlayer();
-    },
-
-    _setupPlayer: function() {
-        this.cfg.player
-            .setSoundProvider(this.cfg.soundProvider)
-            .setMarkerMap(this.cfg.map)
-            .observe('play', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.play))
-            .observe('pause', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.pause))
-            .observe('move', this.attach(this._onMove))
-            .observe('markeradd', this.attach(this._onMarkerAdd))
-            .observe('markermove', this.attach(this._onMarkerMove))
-            .draw();
-    },
-
-    _onMove: function(e, data) {
-        this.cfg.soundProvider.seek(data.offset);
-    },
-
-    _onMarkerMove: function(e, data) {
-        if (this.cfg.map) {
-            this.cfg.map.move(this.cfg.map.byId(data.id), data.offset);
-        }
-    },
-
-    _onMarkerAdd: function(e, data) {
-        if (this.cfg.map) {
-            this.cfg.map.add(data.offset, 'marker at ' + data.offset);
-        }
-    }
-
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/core.js b/ui/src/core.js
deleted file mode 100644 (file)
index 3f48121..0000000
+++ /dev/null
@@ -1,271 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.extend = function(destination, source) {
-  for (var property in source)
-    destination[property] = source[property];
-  return destination;
-};
-
-$N.objectKeys = function(object) {
-    var keys = [];
-    for (var property in object)
-      keys.push(property);
-    return keys;
-};
-
-$N.argumentNames = function(method) {
-    var names = method.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
-      .replace(/\s+/g, '').split(',');
-    return names.length == 1 && !names[0] ? [] : names;
-};  
-
-$N.argsToArray = function(args) {
-    var length = args.length || 0, result = new Array(length);
-    while (length--) result[length] = args[length];
-    return result;
-};
-
-$N.wrapFunction = function(wrapper, method) {
-    return function() {
-      var args = $N.argsToArray(arguments);
-      return wrapper.apply(this, [$N.attachFunction(this, method)].concat(args)); 
-    }
-};
-$N.attachFunction = function() {
-    if (arguments.length < 3 && (typeof arguments[1] == 'undefined')) return arguments[0];
-    var args = $N.argsToArray(arguments);
-    var object = args.shift();
-    var method = args.shift();
-    return function() {
-      var _args = $N.argsToArray(arguments);
-      return method.apply(object, args.concat(_args));
-    }
-};
-
-$N.attachAsEventListener = function() {
-    var args = $N.argsToArray(arguments), object = args.shift();
-    var method = args.shift();
-    return function(event) {
-      return method.apply(object, [event || window.event].concat(args));
-    }
-};
-
-$N.isInstanceOf = function(obj, className) {
-    if (typeof obj == 'object' && obj.__class__) {
-        var c = obj.__class__;
-        if (c.__name__ == className) {
-            return true;
-        }
-        while (c = c.__super__) {
-            if (c.__name__ == className) {
-                return true;
-            }
-        }
-    }
-    return false;
-}
-
-$N.Class = {
-  create: function() {
-    var parent = null, className = null;
-    var properties = $N.argsToArray(arguments)
-    if (typeof properties[0] == "string")
-      className = properties.shift();
-    if (typeof properties[0] == "function")
-      parent = properties.shift();
-    
-    function klass() {
-      this.initialize.apply(this, arguments);
-    }
-    
-    $N.extend(klass, $N.Class.Methods);
-    klass.__name__ = className;
-    klass.__super__ = parent;
-    klass.__subclasses__ = [];
-    
-    if (parent) {
-      var subclass = function() { };
-      subclass.prototype = parent.prototype;
-      klass.prototype = new subclass;
-      parent.__subclasses__.push(klass);
-    }
-    
-    klass.prototype.__class__ = klass;
-    for (var i = 0; i < properties.length; i++)
-      klass.addMethods(properties[i]);
-      
-    if (!klass.prototype.initialize)
-      klass.prototype.initialize = function () {};
-    
-    klass.prototype.constructor = klass;
-   
-    if (className) {
-        $N[className] = klass;
-    }
-    return klass;
-  }
-};
-$N.Class.Methods = {
-  addMethods: function(source) {
-    var ancestor   = this.__super__ && this.__super__.prototype;
-    var properties = $N.objectKeys(source);
-    
-    if (!$N.objectKeys({ toString: true }).length)
-      properties.push("toString", "valueOf");
-    
-    for (var i = 0, length = properties.length; i < length; i++) {
-      var property = properties[i], value = source[property];
-      if (ancestor && (typeof value == 'function') &&
-          $N.argumentNames(value)[0] == "$super") {
-        var method = value;
-        value = $N.wrapFunction(method, (function(m) {
-          return function() { return ancestor[m].apply(this, arguments) };
-        })(property));
-        value.valueOf = $N.attachFunction(method, method.valueOf);
-        value.toString = $N.attachFunction(method, method.toString);
-      }
-      this.prototype[property] = value;
-    }
-    
-    return this;
-  }
-};
-$N.Core = $N.Class.create("Core", {
-    eventContainer: null,
-    eventPrefix: '',
-    cfg: {},
-
-    initialize: function() {
-        this.debug("new instance");
-        $N.registerInstance(this);
-        this.eventContainer = $J('<div/>');
-        this.forwardEvent = this.attach(this._forwardEvent);
-    },
-
-    free: function() {
-        this.eventContainer = null;
-    },
-
-    configure: function(config, defaults) {
-        if (!config)
-            config = {};
-        for (k in defaults) {
-            var value = null, flags = [];
-
-            if (defaults[k] && typeof defaults[k][0] !== 'undefined') {
-                value = defaults[k][0];
-                if (defaults[k][1]) {
-                    flags = defaults[k][1].split(",");
-                }
-            } else {
-                value = defaults[k];
-            }
-
-            if (typeof config[k] !== 'undefined') 
-                value = config[k];
-
-            var source = this;
-            $J(flags).each(function(i, flag) {
-                switch (flag) {
-                    case 'required':
-                        if (value === null)
-                            throw new $N.RequiredOptionError(source, k);
-                        break;
-                        /*
-                    case 'element':
-                        value = $J(value);
-                        break;
-                        */
-
-                }
-            });
-
-            this.cfg[k] = value;
-        }
-        return this;
-    },
-
-    observe: function(eventName, handler) {
-        this.eventContainer.bind(this.eventPrefix + eventName, handler);
-        return this;
-    },
-
-    fire: function(eventName, data) {
-        if (!data)
-            data = {};
-        this.eventContainer.trigger(this.eventPrefix + eventName, data);
-        return this;
-    },
-
-    _forwardEvent: function(e, data) {
-        if (!data)
-            data = {};
-        this.eventContainer.trigger(e.type, data);
-        return this;
-    },
-
-    _textWidth: function(text, fontSize) {
-        var ratio = 3/5;
-        return text.length * ratio * fontSize;
-    },
-
-    debug: function(message) {
-        if ($N.debugging && typeof console != 'undefined' && console.log) {
-            console.log('TimeSide.' + this.__class__.__name__ + ': ' + message);
-        }
-    },
-
-    attach: function(method) {
-        return $N.attachFunction(this, method);
-    },
-
-    attachWithEvent: function(method) {
-        return $N.attachAsEventListener(this, method);
-    },
-
-    uniqid: function() {
-        d = new Date();
-        return new String(d.getTime() + '' + Math.floor(Math.random() * 1000000)).substr(0, 18);
-    }
-});
-
-$N.Class.create("Exception", {
-    _source: null,
-    _message: null,
-
-    initialize: function(source, message) {
-        this._source = source;
-        this._message = message;
-    },
-    toString: function() {
-        return this.__class__.__name__ + " from TimeSide." + this._source.__class__.__name__
-            + ": " + this._message;
-    }
-});
-
-$N.Class.create("RequiredOptionError", $N.Exception, {
-    initialize: function($super, source, optionName) {
-        $super(source, "missing '" + optionName + "' required option");
-    }
-});
-
-$N.Class.create("RequiredArgumentError", $N.Exception, {
-    initialize: function($super, source, optionName) {
-        $super(source, "missing '" + optionName + "' required argument");
-    }
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/marker.js b/ui/src/marker.js
deleted file mode 100644 (file)
index 32f7443..0000000
+++ /dev/null
@@ -1,219 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.Class.create("Marker", $N.Core, {
-    id: null,
-    painter: null,
-    visible: false,
-    position: 0,
-    label: null,
-    blinking: false,
-    nodes: null,
-    mouseDown: false,
-    blinkAnimation: null,
-
-    initialize: function($super, cfg) {
-        $super();
-        this.configure(cfg, {
-            rulerLayout: [null, 'required'],
-            viewer: [null, 'required'],
-            fontSize: 10,
-            zIndex: null,
-            className: [null, 'required'],
-            id: null,
-            tooltip: null
-        });
-        this.cfg.rulerLayout = $J(this.cfg.rulerLayout);
-        this.cfg.viewer = $J(this.cfg.viewer);
-
-        this.id = cfg.id;
-        this.width = this.cfg.viewer.width();
-        this.painter = new jsGraphics(this.cfg.viewer.get(0));
-        this._create();
-        this._observeMouseEvents();
-    },
-
-    free: function($super) {
-        this.cfg.rulerLayout = null;
-        this.cfg.viewer = null;
-        $super();
-    },
-
-    clear: function() {
-        this.painter.clear();
-        $J(this.painter.cnv).remove();
-        this.label.remove();
-        return this;
-    },
-
-    _create: function() {
-        this.debug('create marker');
-        var y = this.cfg.rulerLayout.find('.' + $N.cssPrefix + 'label').outerHeight();
-        this.label = $J('<a/>')
-            .css({
-                display: 'block',
-                width: '10px', 
-                textAlign: 'center', 
-                position: 'absolute', 
-                fontSize: this.cfg.fontSize + 'px', 
-                fontFamily: 'monospace', 
-                top: y + 'px'
-            })
-            .attr('href', '#')
-            .addClass($N.cssPrefix + this.cfg.className)
-            .append('<span />')
-            .hide();
-
-        if (this.cfg.tooltip)
-            this.label.attr('title', this.cfg.tooltip);
-
-        this.cfg.rulerLayout.append(this.label);
-
-        var height = this.cfg.viewer.height();
-        var x = 0;
-        this.painter.drawLine(x, 0, x, height);
-        x     = [-4, 4, 0];
-        var y = [0, 0, 4];
-        this.painter.fillPolygon(x, y);
-        this.painter.paint();
-        this.nodes = $J(this.painter.cnv).children();
-
-        var style = {};
-        if (this.cfg.zIndex) {
-            style.zIndex = this.cfg.zIndex;
-            this.label.css(style);
-        }
-        style.backgroundColor = '';
-
-        this.nodes.hide().css(style).addClass($N.cssPrefix + this.cfg.className)
-            .each(function(i, node) {
-                node.originalPosition = parseInt($J(node).css('left'));
-            });
-    },
-
-    setText: function(text) {
-        if (this.label) {
-            text += '';
-            var labelWidth = this._textWidth(text, this.cfg.fontSize) + 10;
-            labelWidth += 'px';
-            if (this.label.css('width') != labelWidth) {
-                this.label.css({ width: labelWidth });
-            }
-            this.label.find('span').html(text);
-        }
-        return this;
-    },
-
-    move: function(pixelOffset) {
-        if (this.position != pixelOffset) {
-            if (pixelOffset < 0) {
-                pixelOffset = 0;
-            } else if (pixelOffset >= this.width) {
-                pixelOffset = this.width - 1;
-            }
-            this.nodes.each(function(i, node) { 
-                $J(node).css('left', Math.round(node.originalPosition + pixelOffset) + 'px');
-            });
-            var labelWidth = this.label.width();
-            var labelPixelOffset = pixelOffset - labelWidth / 2;
-            if (labelPixelOffset < 0)
-                labelPixelOffset = 0;
-            else if (labelPixelOffset + labelWidth > this.width) 
-                labelPixelOffset = this.width - labelWidth;
-            this.label.css({left: Math.round(labelPixelOffset) + 'px'});            
-            this.position = pixelOffset;
-        }
-        return this;
-    },
-
-    show: function(offset) {
-        if (!this.visible) {
-            this.nodes.show();
-            this.label.show();
-            this.visible = true;
-        }
-        return this;
-    },
-
-    hide: function() {
-        this.nodes.hide();
-        this.label.hide();
-        this.visible = false;
-        return this;
-    },
-
-    isVisible: function() {
-        return this.visible;
-    },
-
-    blink: function(state) {
-        var speed = 200;
-        if (this.label && this.blinking != state) {
-            var span = this.label.find('span');
-
-            span.stop();
-
-            function fade(on) {
-                if (on) {
-                    span.animate({opacity: 1}, speed, null, 
-                        function() { fade(false) });
-                } else {
-                    span.animate({opacity: 0.4}, speed, null, 
-                        function() { fade(true) })
-                }
-            }
-
-            if (state) {
-                fade();
-            } else {
-                span.animate({opacity: 1}, speed);
-            }
-
-            this.blinking = state;
-        }
-        return this;
-    },
-
-    _onMouseDown: function(evt) {
-        this.mouseDown = true;
-        this._onMouseMove(evt);
-        return false;
-    },
-
-    _onMouseMove: function(evt) {
-        if (this.mouseDown) {
-            var offset = (evt.pageX - this.cfg.rulerLayout.offset().left);
-            this.move(offset);
-            this.fire('move', {offset: this.position, finish: false});
-            return false;
-        }
-    },
-
-    _onMouseUp: function(evt) {
-        if (this.mouseDown) {
-            this.mouseDown = false;
-            this.fire('move', {id: this.id, offset: this.position, finish: true});
-            return false;
-        }
-    },
-
-    _observeMouseEvents: function() {
-        this.label.mousedown(this.attachWithEvent(this._onMouseDown))
-            .bind('click dragstart', function() {return false;});
-        this.cfg.rulerLayout.mousemove(this.attachWithEvent(this._onMouseMove));
-        this.cfg.rulerLayout.mouseup(this.attachWithEvent(this._onMouseUp));
-        $J(document).mouseup(this.attachWithEvent(this._onMouseUp));
-    }
-
-
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/markerlist.js b/ui/src/markerlist.js
deleted file mode 100755 (executable)
index 52bd1d4..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N) {
-
-$N.Class.create("MarkerList", $N.Core, {
-    initialize: function($super, cfg) {
-        $super();
-        this.cfg = this.configure(cfg, {
-            container: null,
-            map: null
-        });
-    },
-
-    _buildItem: function(marker) {
-        var dt = new Element('dt');
-        var time = $N.Util.makeTimeLabel(marker.offset);
-
-
-    },
-
-    _setupInterface: function() {
-    }
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/markermap.js b/ui/src/markermap.js
deleted file mode 100644 (file)
index 543fb2e..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.Class.create("MarkerMap", $N.Core, {
-    markers: null,
-
-    initialize: function($super, markers) {
-        $super();
-        if (!markers)
-            markers = [];
-        this.markers = markers;
-    },
-
-    toArray: function() {
-        return [].concat(this.markers);
-    },
-
-    byIndex: function(index) {
-        return this.markers[index];
-    },
-
-    byId: function(id) {
-        var marker = null;
-        for (var i in this.markers) {
-            if (this.markers[i].id == id) {
-                marker = this.markers[i];
-                break;
-            }
-        }
-        return marker;
-    },
-
-    indexOf: function(marker) {
-        var index = null;
-        for (var i in this.markers) {
-            if (this.markers[i].id == marker.id) {
-                index = parseInt(i);
-                break;
-            }
-        }
-        return index;
-    },
-
-    _reorder: function() {
-        this.markers.sort(this.compare);
-        for (var i in this.markers) {
-            this.fire('indexchange', {marker: this.markers[i], index: parseInt(i)});
-        }
-    },
-
-    add: function(offset, desc) {
-        var id = this.uniqid();
-        var marker = {id: id, offset: offset, desc: desc};
-        var i = this.markers.push(marker) - 1;
-        this.fire('add', {marker: marker, index: i});
-        this._reorder();
-        return marker;
-    },
-
-    remove: function(marker) {
-        if (marker) {
-            var i = this.indexOf(marker);
-            this.markers.splice(i, 1);
-            this.fire('remove', {marker: marker});
-            this._reorder();
-        }
-        return marker;
-    },
-
-    compare: function(marker1, marker2) {
-        if (marker1.offset > marker2.offset)
-            return 1;
-        if (marker1.offset < marker2.offset)
-            return -1;
-        return 0;
-    },
-
-    move: function(marker, offset) {
-        oldMarkers = [].concat(this.markers);
-        marker.offset = offset;
-        this._reorder();
-    },
-
-    getPrevious: function(offset, skip) {
-        var marker = null;
-        if (!skip) skip = 0;
-        markers = [].concat(this.markers).reverse();
-        $J(markers).each(function(i, m) {
-            if (offset > m.offset && !(skip--)) {
-                marker = m;
-                return false;
-            }
-        });
-        return marker;
-    },
-
-    getNext: function(offset, skip) {
-        var marker = null;
-        if (!skip) skip = 0;
-        $J(this.markers).each(function(i, m) {
-            if (offset < m.offset && !(skip--)) {
-                marker = m;
-                return false;
-            }
-        });
-        return marker;
-    },
-
-    each: function(callback) {
-        $J(this.markers).each(callback);
-    }
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/player.js b/ui/src/player.js
deleted file mode 100644 (file)
index 04df2f6..0000000
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.Class.create("Player", $N.Core, {
-    skeleton: {
-        'div.viewer': {
-            'div.ruler': {}, 
-            'div.wave': {
-                'div.image-canvas': {},
-                'div.image-container': ['img.image']
-            }
-        },
-        'div.control': {
-            'div.layout': {
-                'div.playback': ['a.play', 'a.pause', 'a.rewind', 'a.forward', 'a.set-marker']
-            }
-        }/*,
-        'div.marker-control': ['a.set-marker']*/
-    },
-    defaultContents: {
-        play: 'Play',
-        pause: 'Pause',
-        rewind: 'Rewind',
-        forward: 'Forward',
-        'set-marker': 'Set marker'
-    },
-    elements: {},
-    ruler: null,
-    soundProvider: null,
-    map: null,
-    container: null,
-    imageWidth: null,
-    imageHeight: null,
-
-    initialize: function($super, container, cfg) {
-        $super();
-        if (!container)
-            throw new $N.RequiredArgumentError(this, 'container');
-        this.container = $J(container);
-        this.configure(cfg, {
-            image: null
-        });
-    },
-
-    free: function($super) {
-        this.elements = null;
-        this.container = null;
-        $super();
-    },
-
-    setSoundProvider: function(soundProvider) {
-        this.soundProvider = soundProvider;
-        return this;
-    },
-
-    setMarkerMap: function(map) {
-        this.map = map;
-        return this;
-    },
-
-    setImage: function(expr) {
-        this.cfg.image = expr;
-        this.refreshImage();
-    },
-
-    refreshImage: function() {
-        var src = null;
-        if (typeof this.cfg.image == 'function') {
-            src = this.cfg.image(this.imageWidth, this.imageHeight);
-        } else if (typeof this.cfg.image == 'string') {
-            src = this.cfg.image;
-        }
-
-        if (src) 
-            this.elements.image.attr('src', src);
-    },
-
-    draw: function() {
-        this.debug('drawing');
-        $N.domReady(this.attach(this._setupInterface));
-        return this;
-    },
-
-    _setupInterface: function() {
-        this.elements = $N.Util.loadUI(this.container, this.skeleton, this.defaultContents);
-
-        // IE apparently doesn't send the second mousedown on double click:
-        var jump = $J.browser.msie ? 'mousedown dblclick' : 'mousedown';
-        this.elements.rewind.attr('href', '#').bind(jump, this.attach(this._onRewind))
-            .click(function() {return false; });
-        this.elements.forward.attr('href', '#').bind(jump, this.attach(this._onForward))
-            .click(function() {return false; });
-        this.elements.pause.attr('href', '#').bind('click', this.attach(this._onPause));
-        this.elements.play.attr('href', '#').bind('click', this.attach(this._onPlay));
-        this.elements.control.find('a').add(this.elements.setMarker)
-            .attr('href', '#')
-            .each(function(i, a){
-                a = $J(a);
-                if (!a.attr('title'))
-                    a.attr('title', a.text());
-            });
-            
-        //this.elements.markerControl.find('a').attr('href', '#');
-        if (this.map) {
-            this.elements.setMarker.bind('click', this.attach(this._onSetMarker));
-        } else {
-            this.elements.setMarker.remove();
-        }
-        this.ruler = new $N.Ruler({
-            viewer: this.elements.viewer,
-            map: this.map,
-            soundProvider: this.soundProvider
-        });
-        this.ruler
-            .observe('markermove', this.forwardEvent)
-            .observe('markeradd', this.forwardEvent)
-            .observe('move', this.forwardEvent)
-            .draw();
-        this.refreshImage();
-        this.resize();
-        var resizeTimer = null;
-        $J(window).resize(this.attach(function() {
-            if (resizeTimer)
-                clearTimeout(resizeTimer);
-            resizeTimer = setTimeout(this.attach(this.resize), 100);
-        }));
-        //this.container.resize(this.attach(this.resize)); // Can loop ?
-    },
-
-    resize: function(overrideHeight) {
-        this.debug("resizing");
-        var height;
-        if (overrideHeight === true) {
-            this.debug("override height");
-            height = this.elements.image.css('height', 'auto').height();
-        } else {
-            height = this.elements.wave.height();
-            this.debug("wave height:" + height);
-            if (!height) {
-                this.elements.image.one('load', this.attach(function() {
-                    this.resize(true);
-                    this.debug("image loaded");
-                }));
-                height = this.elements.image.height();
-            }
-        }
-
-        var elements = this.elements.image
-            .add(this.elements.imageContainer)
-            .add(this.elements.imageCanvas);
-
-        elements.css('width', 'auto'); // for IE6
-
-        if (!height)
-            height = 200;
-        var style = {
-            width: this.elements.wave.width(),
-            height: height
-        }
-        elements.css(style);
-        this.imageWidth = style.width;
-        this.imageHeight = style.height;
-        this.refreshImage();
-        this.ruler.resize();
-        return this;
-    },
-
-    _onRewind: function() {
-        var offset = 0;
-        if (this.map) {
-            var position = this.soundProvider.getPosition();
-            var marker = this.map.getPrevious(position);
-            if (marker && this.soundProvider.isPlaying() 
-                && position - marker.offset < this.ruler.getUnitDuration())
-                marker = this.map.getPrevious(marker.offset)
-            if (marker) {
-                offset = marker.offset;
-            }
-        }
-        this.fire('move', {offset: offset});
-        return false;
-    },
-
-    _onForward: function() {
-        var offset = this.soundProvider.getDuration();
-        if (this.map) {
-            var marker = this.map.getNext(this.soundProvider.getPosition());
-            if (marker) {
-                offset = marker.offset;
-            }
-        }
-        this.fire('move', {offset: offset});
-        return false;
-    },
-
-    _onPlay: function() {
-        this.fire('play');
-        return false;
-    },
-
-    _onPause: function() {
-        this.fire('pause');
-        return false;
-    },
-
-    _onSetMarker: function() {
-        if (this.map) {
-            this.fire('markeradd', {offset: this.soundProvider.getPosition()});
-        }
-        return false;
-    }
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/ruler.js b/ui/src/ruler.js
deleted file mode 100644 (file)
index 5932c43..0000000
+++ /dev/null
@@ -1,398 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.Class.create("Ruler", $N.Core, {
-
-    fullSectionDuration: 60,
-    sectionSubDivision: 10,
-    sectionSteps: [[5, 1], [10, 1], [20, 2], [30, 5], [60, 10], [120, 20], [300, 30], 
-        [600, 60], [1800, 300], [3600, 600]],
-    sectionsNum: 0,
-    timeLabelWidth: 0,
-    pointerPos: 0,
-    layout: null,
-    width: null,
-    mouseDown: false,
-    pointer: null,
-    markers: new Array(),
-    duration: 0,
-    container: null,
-    waveContainer: null,
-
-    initialize: function($super, cfg) {
-        $super();
-        this.configure(cfg, {
-            viewer: [null, 'required'],
-            fontSize: 10,
-            map: null,
-            soundProvider: [null, 'required']
-        });
-        this.cfg.viewer = $J(this.cfg.viewer);
-        this.container = this.cfg.viewer.find('.' + $N.cssPrefix + 'ruler');
-        this.waveContainer = this.cfg.viewer.find('.' + $N.cssPrefix + 'image-canvas');
-        this._setDuration(this.cfg.soundProvider.getDuration());
-        var imgContainer = this.cfg.viewer.find('.' + $N.cssPrefix + 'image-container'); // for IE
-        this._observeMouseEvents(this.waveContainer.add(imgContainer));
-        if (this.cfg.map) {
-            this.cfg.map
-                .observe('add', this.attach(this._onMapAdd))
-                .observe('remove', this.attach(this._onMapRemove))
-                .observe('indexchange', this.attach(this._onMapIndexChange));
-        }
-        this.cfg.soundProvider.observe('update', this.attach(this._onSoundProviderUpdate));
-    },
-
-    free: function($super) {
-        this.layout = null;
-        this.container = null;
-        this.waveContainer = null;
-        this.cfg.viewer = null;
-        $super();
-    },
-
-    _computeLayout: function() {
-        this.width = this.waveContainer.width();
-                
-        this.debug('container width: ' + this.width);
-        var i, ii = this.sectionSteps.length;
-        this.timeLabelWidth = this._textWidth('00:00', this.cfg.fontSize);
-        for (i = 0; i < ii; i++) {
-            var duration = this.sectionSteps[i][0];
-            var subDivision = this.sectionSteps[i][1];
-            var labelsNum = Math.floor(this.duration / duration);
-            if ((i == ii - 1) || (this.width / labelsNum > this.timeLabelWidth * 2)) {
-                this.fullSectionDuration = duration;
-                this.sectionSubDivision = subDivision;
-                this.sectionsNum = Math.floor(this.duration / this.fullSectionDuration);
-                break;
-            }
-        }
-    },
-
-    getUnitDuration: function() {
-        return this.sectionSubDivision;
-    },
-
-    resize: function() {
-        var pointerVisible = this.pointer && this.pointer.isVisible();
-        this._computeLayout();
-        this.draw();
-        if (pointerVisible) {
-            this.setPosition(this.cfg.soundProvider.getPosition());
-            this.setBuffering(this.cfg.soundProvider.isBuffering() && this.cfg.soundProvider.isPlaying());
-            this.pointer.show();
-        }            
-    },
-
-    _setDuration: function(duration) {
-        this.duration = duration;
-        this._computeLayout();
-    },
-
-    setDuration: function(duration) {
-        if (duration == 0)
-            duration = 60;
-        if (this.duration != duration) {
-            this._setDuration(duration);
-            this.draw();
-        }
-    },
-
-    _createSection: function(timeOffset, pixelWidth) {
-        var section = $J('<div/>')
-            .addClass($N.cssPrefix + 'section')
-            .css({
-                fontSize: this.cfg.fontSize + 'px', 
-                fontFamily: 'monospace',
-                width: pixelWidth,
-                overflow: 'hidden'
-            })
-            .append($J('<div />').addClass($N.cssPrefix + 'canvas'));
-
-        var topDiv = $J('<div/>')
-            .addClass($N.cssPrefix + 'label')
-            .appendTo(section);
-        var bottomDiv = $J('<div/>')
-            .addClass($N.cssPrefix + 'lines')
-            .appendTo(section);
-        var empty = $J('<span/>').css({visibility: 'hidden'}).text('&nbsp;');
-        if (pixelWidth > this.timeLabelWidth) {
-            var text = $J('<span/>')
-                .text($N.Util.makeTimeLabel(timeOffset))
-                .bind('mousedown selectstart', function() {return false;});
-        } else {
-            var text = empty.clone();
-        }
-        topDiv.append(text);
-        bottomDiv.append(empty);
-        return section;
-    },
-
-    _drawSectionRuler: function(section, drawFirstMark) {
-        var j;
-        var jg = new jsGraphics(section.find('.' + $N.cssPrefix + 'canvas').get(0));
-        jg.setColor(this.layout.find('.' + $N.cssPrefix + 'lines').css('color'));
-        var height = section.height();
-        var ypos;
-        for (j = 0; j < section.duration; j += this.sectionSubDivision) {
-            if (j == 0) {
-                if (drawFirstMark) {
-                    ypos = 0;
-                } else {
-                    continue;
-                }
-            } else {
-                ypos = (j == section.duration / 2) ? 1/2 + 1/8 : 3/4;
-            }
-            var x = j / this.duration * this.width;
-            jg.drawLine(x, height * ypos, x, height - 1);
-        }
-        jg.paint();
-    },
-
-    getHeight: function() {
-        return this.container.find('' + $N.cssPrefix + '.section').height();
-    },
-
-    draw: function() {
-        if (!this.duration) {
-            this.debug("Can't draw ruler with a duration of 0");
-            return;
-        }
-        this.debug("draw ruler, duration: " + this.duration);
-        if (this.layout)
-            this.layout.remove();
-        this.layout = $J('<div/>')
-            .addClass($N.cssPrefix + 'layout')
-            .css({position: 'relative'}) // bugs on IE when resizing
-            .bind('dblclick', this.attachWithEvent(this._onDoubleClick))
-            //.bind('resize', this.attachWithEvent(this.resize)) // Can loop ?
-            .appendTo(this.container);
-
-        //this.container.html(this.layout);
-
-        var sections = new Array();
-        var currentWidth = 0;
-        var i;
-        for (i = 0; i <= this.sectionsNum; i++) {
-            if (i < this.sectionsNum) {
-                var duration = this.fullSectionDuration;
-                var width = Math.floor(duration / this.duration * this.width);
-            } else {
-                var duration = this.duration - i * this.fullSectionDuration;
-                var width = this.width - currentWidth;
-
-            }               
-            var section = this._createSection(i * this.fullSectionDuration, width);
-            if (i > 0) {
-                section.css({left: currentWidth, top: 0, position: 'absolute'});
-            }
-            section.duration = duration;
-            this.layout.append(section);
-            currentWidth += section.width();
-            sections[i] = section;
-        }
-
-        for (i = 0; i <= this.sectionsNum; i++) {
-            this._drawSectionRuler(sections[i], (i > 0));
-        }
-
-        this._createPointer();
-        this._drawMarkers();
-    },
-
-    _createPointer: function() {
-        if (this.pointer) {
-            this.pointer.clear();
-        }
-        this.pointer = new $N.Marker({
-            rulerLayout: this.layout.get(0),
-            viewer: this.waveContainer,
-            fontSize: this.cfg.fontSize,
-            zIndex: 1000,
-            className: 'pointer',
-            tooltip: 'Move head'
-        });
-        this.pointer
-            .setText($N.Util.makeTimeLabel(0))
-            .observe('move', this.attach(this._onPointerMove));
-    },
-
-    _drawMarkers: function() {
-        if (this.cfg.map) {
-            $J(this.markers).each(function(i, m) {m.clear();});
-            this.markers = new Array();
-            this.cfg.map.each(this.attach(function(i, m) {
-                this.markers.push(this._drawMarker(m, i));
-            }));
-        }
-    },
-
-    _movePointer: function(offset) {
-        if (offset < 0)
-            offset = 0;
-        else if (offset > this.duration)
-            offset = this.duration;
-            
-        pixelOffset = offset / this.duration * this.width;
-        if (this.pointer) {
-            this.pointer.move(pixelOffset);
-            this.pointer.setText($N.Util.makeTimeLabel(offset));
-        }            
-        this.pointerPos = offset;
-    },
-
-    _setPosition: function(offset) {
-        this._movePointer(offset);
-        if (this.pointer) {
-            this.pointer.show();
-        }            
-    },
-
-    setPosition: function(offset) {
-        if (!this.mouseDown) {
-            this._setPosition(offset);
-        }
-    },
-
-    shiftPosition: function(delta) {
-        this.setPosition(this.pointerPos + delta);
-    },
-
-    hidePointer: function() {
-        if (this.pointer)
-            this.pointer.hide();
-    },
-
-    setBuffering: function(state) {
-        if (this.pointer) {
-            this.pointer.blink(state);
-        }
-    },
-/*
-    _onClick: function(evt) {
-        var offset = (evt.pageX - this.container.offset().left) 
-            / this.width * this.duration;
-        this._setPosition(offset);
-        this.fire('move', {offset: offset});
-    },
-*/
-    _onMouseDown: function(evt) {
-        this.mouseDown = true;
-        this._onMouseMove(evt);
-        evt.preventDefault();
-    },
-
-    _onPointerMove: function(evt, data) {
-        this.mouseDown = true;
-        this._setPosition(data.offset / this.width * this.duration);
-        if(data.finish) {
-            this.fire('move', {offset: this.pointerPos});
-            this.mouseDown = false;
-        }
-        return false;
-    },
-
-    _onMouseMove: function(evt) {
-        if (this.mouseDown) {
-            var pixelOffset = evt.pageX - this.container.offset().left;
-            this._setPosition(pixelOffset / this.width * this.duration);
-            return false;
-        }
-    },
-
-    _onMouseUp: function(evt) {
-        if (this.mouseDown) {
-            this.mouseDown = false;
-            this.fire('move', {offset: this.pointerPos});
-            return false;
-        }
-    },
-
-    _observeMouseEvents: function(element) {
-        element
-            .bind('click dragstart', function() {return false;})
-            .bind('mousedown', this.attachWithEvent(this._onMouseDown))
-            .bind('mousemove', this.attachWithEvent(this._onMouseMove))
-            .bind('mouseup', this.attachWithEvent(this._onMouseUp));
-        $J(document)
-            .bind('mousemove', this.attachWithEvent(this._onMouseMove));
-    },
-
-    _drawMarker: function(marker, index) {
-        if (marker.offset < 0)
-            marker.offset = 0;
-        else if (marker.offset > this.duration)
-            marker.offset = this.duration;
-            
-        pixelOffset = marker.offset / this.duration * this.width;
-
-        m = new $N.Marker({
-            rulerLayout: this.layout.get(0),
-            viewer: this.waveContainer,
-            fontSize: this.cfg.fontSize,
-            className: 'marker',
-            id: marker.id,
-            tooltip: 'Move marker'
-        });
-        m.observe('move', this.attach(this._onMarkerMove))
-            .setText(index + 1)
-            .move(pixelOffset)
-            .show();
-        return m;
-    },
-
-    _onMarkerMove: function(e, data) {
-        if (data.finish) {
-            var offset = data.offset / this.width * this.duration;
-            this.fire('markermove', {id: data.id, offset: offset});
-        }
-    },
-
-    _onMapAdd: function(e, data) {
-        this.markers.push(this._drawMarker(data.marker, data.index));
-    },
-
-
-    _onMapRemove: function(e, data) {
-        $J(this.markers).each(this.attach(function(i, m) {
-            if (m.id == data.marker.id) {
-                m.clear();
-                this.markers.splice(i, 1);
-            }
-        }));
-    },
-
-    _onMapIndexChange: function(e, data) {
-        $J(this.markers).each(this.attach(function(i, m) {
-            if (m.id == data.marker.id) {
-                m.setText(data.index + 1);
-                return false;
-            }
-        }));
-    },
-
-    _onDoubleClick: function(evt) {
-        if (this.cfg.map) {
-            var offset = (evt.pageX - this.container.offset().left) 
-                / this.width * this.duration;
-            this.fire('markeradd', {offset: offset});
-        }
-    },
-
-    _onSoundProviderUpdate: function(e) {
-        this.setDuration(this.cfg.soundProvider.getDuration());
-        this.setPosition(this.cfg.soundProvider.getPosition());
-        this.setBuffering(this.cfg.soundProvider.isBuffering() && this.cfg.soundProvider.isPlaying());
-    }
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/soundprovider.js b/ui/src/soundprovider.js
deleted file mode 100644 (file)
index b8ac149..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N) {
-
-$N.Class.create("SoundProvider", $N.Core, {
-    sound: null,
-    timer: null,
-    buggyPosition: null,
-    isDurationForced: false,
-    state: {
-        position: null,
-        duration: null,
-        playing: false,
-        buffering: false
-    },
-    lastState: null,
-
-    initialize: function($super, cfg) {
-        $super();
-        this.configure(cfg, {
-            source: null,
-            duration: null
-        });
-        this.sound = this.cfg.source;
-        if (this.cfg.duration) {
-            this.forceDuration(this.cfg.duration);
-        }
-        this.state.position = 0;
-        this.update = this.attach(this._update);
-        this.timer = setInterval(this.update, 43);
-    },
-
-    free: function($super) {
-        this.sound = null;
-        $super();
-    },
-
-    play: function() {
-        if (this.sound) {
-            if (!this.sound.playState) {
-                this.sound.play();
-            } else if (this.sound.paused) {
-                this.sound.resume();
-            }
-        }
-        return this;
-    },
-
-    pause: function() {
-        if (this.sound)
-            this.sound.pause();
-        return this;
-    },
-
-    seek: function(offset) {
-        if (this.sound) {
-            this.sound.setPosition(offset * 1000);
-            if (!this.state.playing) {
-                this.buggyPosition = this.sound.position / 1000;
-                this.state.position = offset;
-            }
-        }
-        return this;
-    },
-
-    isPlaying: function() {
-        return this.state.playing;
-    },
-
-    getPosition: function() {
-        if (this.state.position == null)
-            this._retrieveState();
-        return this.state.position;
-    },
-
-    getDuration: function() {
-        if (this.state.duration == null)
-            this._retrieveState();
-        return this.state.duration;
-    },
-
-    forceDuration: function(duration) {
-        this.state.duration = duration;
-        this.isDurationForced = true;
-    },
-
-    isBuffering: function() {
-        return this.state.buffering;
-    },
-
-    _retrieveState: function() {
-        if (this.sound) {
-            this.state.playing = (this.sound.playState && !this.sound.paused);
-            if (this.state.playing) {
-                var position = this.sound.position / 1000;
-                if (position != this.buggyPosition) {
-                    this.state.position = position;
-                    this.buggyPosition = null;
-                }
-            }
-            if (!this.isDurationForced) {
-                if (this.sound.readyState == 1) {
-                    this.state.duration = this.sound.durationEstimate / 1000;
-                } else {
-                    this.state.duration = this.sound.duration / 1000;
-                }
-            }
-            this.state.buffering = (this.sound.readyState == 1 && this.state.position > this.sound.duration / 1000);
-        }
-    },
-
-    _update: function() {
-        this._retrieveState();
-        var updated = false;
-        if (this.lastState) {
-            for (k in this.state) {
-                if (this.state[k] != this.lastState[k]) {
-                    updated = true;
-                    break;
-                }
-            }
-        } else {
-            this.lastState = {};
-            updated = true;
-        }
-        if (updated) {
-            for (k in this.state) {
-                this.lastState[k] = this.state[k];
-            }
-            this.fire('update');
-        }
-    },
-
-    setSource: function(source) {
-        this.debug("setting source");
-        this.sound = source;
-        return this;
-    }
-
-});
-
-$N.notifyScriptLoad();
-
-});
diff --git a/ui/src/timeside.js b/ui/src/timeside.js
deleted file mode 100644 (file)
index 95b0f51..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-var TimeSide = function() { 
-    if (arguments[0]) {
-        var toolkit = null;
-        if (typeof jQuery != 'undefined')
-            toolkit = jQuery;
-        (arguments[0])(TimeSide, toolkit)
-    }
-};
-
-TimeSide(function($N, $J) {
-
-$N.isDomLoaded = false;
-$N.isLoaded = false;
-$N.isLoading = false;
-$N.onLoadCallbacks = [];
-$N.cssPrefix = 'ts-';
-$N.debugging = false;
-
-$J(document).ready(function () {
-    $N.isDomLoaded = true;
-});
-
-$N.domReady = function(callback) {
-    // simply calling jQuery.ready() *after* the DOM is loaded doesn't work reliably,
-    // at least with jQuery 1.2.6
-    if ($N.isDomLoaded) 
-        callback();
-    else
-        $J(document).ready(callback);
-}
-
-$N.instances = [];
-$N.registerInstance = function(obj) {
-    $N.instances.push(obj);
-}
-
-$N.free = function() {
-    $J($N.instances).each(function(i, obj) {
-        obj.free();
-    });
-}
-
-$J(window).unload($N.free);
-
-$N.loadScriptsNum = 0;
-$N.loadScriptsCallback = null;
-$N.loadScripts = function(root, scripts, callback) {
-    if ($N.loadScriptsCallback) {
-        throw "Timeside loader error: concurrent script loading";
-    }
-
-    $N.loadScriptsNum = scripts.length;
-    $N.loadScriptsCallback = callback;
-
-    var head= document.getElementsByTagName('head')[0];
-    for (i = 0; i < scripts.length; i++) {
-
-        var script = document.createElement('script');
-        script.type = 'text/javascript';
-        var debug = $N.debugging ? '?rand=' + Math.random() : '';
-        script.src = root + scripts[i] + debug;
-        head.appendChild(script);
-    }
-}
-
-$N.notifyScriptLoad = function() {
-    if (--$N.loadScriptsNum == 0 && $N.loadScriptsCallback) {
-        var callback = $N.loadScriptsCallback;
-        $N.loadScriptsCallback = null;
-        callback();
-    }
-}
-
-$N.debug = function(state) {
-    $N.debugging = state;
-}
-
-$N.load = function(callback) {
-    $N.domReady(function() {
-        if ($N.isLoaded) {
-            if (callback) 
-                callback();
-        } else {
-            if (callback) 
-                $N.onLoadCallbacks.push(callback);
-
-            if (!$N.isLoading) {
-                $N.isLoading = true;
-                var re = /(.*)timeside.js/;
-                var root = '';
-                $J('head script').each(function(i, e) {
-                    if (match = re.exec(e.src)) {
-                        root = match[1];
-                    }
-                });
-
-                $N.loadScripts(root, ['core.js'], function() {
-                    $N.loadScripts(root, ['util.js'], function() {
-                        var scripts = ['controller.js', 'marker.js', 'markerlist.js', 
-                                       'markermap.js', 'player.js', 'ruler.js', 
-                                       'soundprovider.js'];
-                                                       
-                        $N.loadScripts(root, scripts, function() {
-                            $N.isLoaded = true;
-                            $N.isLoading = false;
-                            $J($N.onLoadCallbacks).each(function(i, callback) {
-                                callback();
-                            });
-                        });
-                    });
-                });
-            }
-        }
-    });
-}
-
-});
diff --git a/ui/src/util.js b/ui/src/util.js
deleted file mode 100755 (executable)
index 94c42dc..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * TimeSide - Web Audio Components
- * Copyright (c) 2008-2009 Samalyse
- * Author: Olivier Guilyardi <olivier samalyse com>
- * License: GNU General Public License version 2.0
- */
-
-TimeSide(function($N, $J) {
-
-$N.Util = {
-    _loadChild: function(container, tag, className, index, contents) {
-        var p = $N.cssPrefix;
-        var element = container.find('.' + p + className);
-        if (!element.length) {
-            element = $J(document.createElement(tag)).addClass(p + className);
-            if (contents[className]) {
-                element.text(contents[className]);
-            }
-            var children = container.children();
-            if (index < children.length) {
-                children.eq(index).before(element);
-            } else {
-                container.append(element);
-            }
-        }
-        return element;
-    },
-
-    _loadUI: function(container, skeleton, contents) {
-        var i = 0;
-        var elements = {};
-        with ($N.Util) {
-            if (skeleton[0]) {
-                $J(skeleton).each((function(i, selector) {
-                    var s = selector.split('.');
-                    elements[$N.Util.camelize(s[1])] = _loadChild(container, s[0], s[1], i++, contents);
-                }));
-            } else {
-                for (key in skeleton) {
-                    var s = key.split('.');
-                    var e = _loadChild(container, s[0], s[1], i++, contents);
-                    elements[$N.Util.camelize(s[1])] = e;
-                    $N.extend(elements, _loadUI(e, skeleton[key], contents));
-                    
-                }
-            }
-        }
-        return elements;
-    },
-
-    loadUI: function(container, skeleton, contents) {
-        return $N.Util._loadUI($J(container), skeleton, contents);
-    },
-
-    makeTimeLabel: function(offset) {
-        var minutes = Math.floor(offset / 60);
-        if (minutes < 10)
-            minutes = '0' + minutes;
-        var seconds = Math.floor(offset % 60);
-        if (seconds < 10)
-            seconds = '0' + seconds;
-        return minutes + ':' + seconds;
-    },
-
-    camelize: function(str) {
-        var parts = str.split('-'), len = parts.length;
-        if (len == 1) return parts[0];
-
-        var camelized = str.charAt(0) == '-'
-          ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
-          : parts[0];
-
-        for (var i = 1; i < len; i++)
-          camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
-
-        return camelized;
-    }
-
-}
-
-$N.notifyScriptLoad();
-
-});