/*!
   SoundManager 2: Javascript Sound for the Web
   --------------------------------------------
   http://schillmania.com/projects/soundmanager2/

   Copyright (c) 2008, Scott Schiller. All rights reserved.
   Code licensed under the BSD License:
   http://schillmania.com/projects/soundmanager2/license.txt

   V2.94a.20090206
*/

var soundManager = null;

function SoundManager(smURL,smID) {
 
  this.flashVersion = 9;           // version of flash to require, either 8 or 9. Some API features require Flash 9.
  this.debugMode = false;           // enable debugging output (div#soundmanager-debug, OR console if available + configured)
  this.useConsole = true;          // use firebug/safari console.log()-type debug console if available
  this.consoleOnly = true;        // if console is being used, do not create/write to #soundmanager-debug
  this.waitForWindowLoad = true;  // force SM2 to wait for window.onload() before trying to call soundManager.onload()
  this.nullURL = 'null.mp3';       // path to "null" (empty) MP3 file, used to unload sounds (Flash 8 only)
  this.allowPolling = true;        // allow flash to poll for status update (required for "while playing", peak, sound spectrum functions to work.)
  this.useMovieStar = false;	   // enable support for Flash 9.0r115+ (codename "MovieStar") MPEG4 audio + video formats (AAC, M4V, FLV, MOV etc.)
  this.bgColor = '#ffffff';	   // movie (.swf) background color, useful if showing on-screen for video etc.
  this.useHighPerformance = false; // position:fixed flash movie gives increased js/flash speed
  this.flashLoadTimeout = 2000; //750;     // ms to wait for flash movie to load before failing (0 = infinity)

  this.defaultOptions = {
    '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)
    'stream': true,                // allows playing before entire file has loaded (recommended)
    'autoPlay': false,             // enable playing of file as soon as possible (much faster if "stream" is true)
    'onid3': null,                 // callback function for "ID3 data is added/available"
    'onload': null,                // callback function for "load finished"
    'whileloading': null,          // callback function for "download progress update" (X of Y bytes received)
    'onplay': null,                // callback for "play" start
    'onpause': null,               // callback for "pause"
    'onresume': null,              // callback for "resume" (pause toggle)
    'whileplaying': null,          // callback during play (position update)
    'onstop': null,                // callback for "user stop"
    'onfinish': null,              // callback function for "sound finished playing"
    'onbeforefinish': null,        // callback for "before sound finished playing (at [time])"
    'onbeforefinishtime': 5000,    // offset (milliseconds) before end of sound to trigger beforefinish (eg. 1000 msec = 1 second)
    'onbeforefinishcomplete':null, // function to call when said sound finishes playing
    'onjustbeforefinish':null,     // callback for [n] msec before end of current sound
    'onjustbeforefinishtime':200,  // [n] - if not using, set to 0 (or null handler) and event will not fire.
    'multiShot': true,             // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time
    'position': null,              // offset (milliseconds) to seek to within loaded sound data.
    'pan': 0,                      // "pan" settings, left-to-right, -100 to 100
    'volume': 100                  // self-explanatory. 0-100, the latter being the max.
  };

  this.flash9Options = {           // flash 9-only options, merged into defaultOptions if flash 9 is being used
    'onbufferchange': null,	   // callback for "isBuffering" property change
    'isMovieStar': null,	   // "MovieStar" MPEG4 audio/video mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL
    'usePeakData': false,          // enable left/right channel peak (level) data
    'useWaveformData': false,      // enable sound spectrum (raw waveform data) - WARNING: CPU-INTENSIVE: may set CPUs on fire.
    'useEQData': false             // enable sound EQ (frequency spectrum data) - WARNING: Also CPU-intensive.
  };

  this.movieStarOptions = {        // flash 9.0r115+ MPEG4 audio/video options, merged into defaultOptions if flash 9 + movieStar mode is enabled
    'onmetadata': null,		   // callback for when video width/height etc. are received
    'useVideo': false		   // if loading movieStar content, whether to show video
  };

  // jslint global declarations
  /*global sm2Debugger, alert, console, document, navigator, setTimeout, window */

  var SMSound = null; // defined later

  var _s = this;
  this.version = null;
  this.versionNumber = 'V2.94a.20090206';
  this.movieURL = null;
  this.url = null;
  this.altURL = null;
  this.swfLoaded = false;
  this.enabled = false;
  this.o = null;
  this.id = (smID||'sm2movie');
  this.oMC = null;
  this.sounds = {};
  this.soundIDs = [];
  this.muted = false;
  this.wmode = null;
  this.isIE = (navigator.userAgent.match(/MSIE/i));
  this.isSafari = (navigator.userAgent.match(/safari/i));
  this.isGecko = (navigator.userAgent.match(/gecko/i));
  this.debugID = 'soundmanager-debug';
  this._debugOpen = true;
  this._didAppend = false;
  this._appendSuccess = false;
  this._didInit = false;
  this._disabled = false;
  this._windowLoaded = false;
  this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');
  this._debugLevels = ['log','info','warn','error'];
  this._defaultFlashVersion = 8;
  this._oRemoved = null;
  this._oRemovedHTML = null;

  var _$ = function(sID) {
    return document.getElementById(sID);
  };

  this.filePatterns = {
	flash8: /\.mp3(\?.*)?$/i,
	flash9: /\.mp3(\?.*)?$/i
  };

  this.netStreamTypes = ['aac','flv','mov','mp4','m4v','f4v','m4a','mp4v','3gp','3g2']; // Flash v9.0r115+ "moviestar" formats
  this.netStreamPattern = new RegExp('\\.('+this.netStreamTypes.join('|')+')(\\?.*)?$','i');

  this.filePattern = null;
  this.features = {
	buffering: false,
    peakData: false,
    waveformData: false,
    eqData: false,
    movieStar: false
  };

  this.sandbox = {
    'type': null,
    'types': {
      'remote': 'remote (domain-based) rules',
      'localWithFile': 'local with file access (no internet access)',
      'localWithNetwork': 'local with network (internet access only, no local access)',
      'localTrusted': 'local, trusted (local + internet access)'
    },
    'description': null,
    'noRemote': null,
    'noLocal': null
  };

  this._setVersionInfo = function() {
    if (_s.flashVersion != 8 && _s.flashVersion != 9) {
      alert('soundManager.flashVersion must be 8 or 9. "'+_s.flashVersion+'" is invalid. Reverting to '+_s._defaultFlashVersion+'.');
      _s.flashVersion = _s._defaultFlashVersion;
    }
    _s.version = _s.versionNumber+(_s.flashVersion==9?' (AS3/Flash 9)':' (AS2/Flash 8)');
    // set up default options
	if (_s.flashVersion > 8) {
	  _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.flash9Options);
	  _s.features.buffering = true;
	}
    if (_s.flashVersion > 8 && _s.useMovieStar) {
      // flash 9+ support for movieStar formats as well as MP3
      _s.defaultOptions = _s._mergeObjects(_s.defaultOptions,_s.movieStarOptions);
      _s.filePatterns.flash9 = new RegExp('\\.(mp3|'+_s.netStreamTypes.join('|')+')(\\?.*)?$','i');
      _s.features.movieStar = true;
    } else {
      _s.useMovieStar = false;
      _s.features.movieStar = false;
    }
    _s.filePattern = _s.filePatterns[(_s.flashVersion!=8?'flash9':'flash8')];
    _s.movieURL = (_s.flashVersion==8?'soundmanager2.swf':'soundmanager2_flash9.swf');
    _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_s.flashVersion==9);
  };

  this._overHTTP = (document.location?document.location.protocol.match(/http/i):null);
  this._waitingforEI = false;
  this._initPending = false;
  this._tryInitOnFocus = (this.isSafari && typeof document.hasFocus == 'undefined');
  this._isFocused = (typeof document.hasFocus != 'undefined'?document.hasFocus():null);
  this._okToDisable = !this._tryInitOnFocus;

  this.useAltURL = !this._overHTTP; // use altURL if not "online"

  var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';

  // --- public methods ---
  
  this.supported = function() {
    return (_s._didInit && !_s._disabled);
  };

  this.getMovie = function(smID) {
    return _s.isIE?window[smID]:(_s.isSafari?_$(smID)||document[smID]:_$(smID));
  };

  this.loadFromXML = function(sXmlUrl) {
    try {
      _s.o._loadFromXML(sXmlUrl);
    } catch(e) {
      _s._failSafely();
      return true;
    }
  };

  this.createSound = function(oOptions) {
    if (!_s._didInit) {
	  throw new Error('soundManager.createSound(): Not loaded yet - wait for soundManager.onload() before calling sound-related methods');
	}
    if (arguments.length == 2) {
      // function overloading in JS! :) ..assume simple createSound(id,url) use case
      oOptions = {'id':arguments[0],'url':arguments[1]};
    }
    var thisOptions = _s._mergeObjects(oOptions); // inherit SM2 defaults
    var _tO = thisOptions; // alias
    _s._wD('soundManager.createSound(): '+_tO.id+' ('+_tO.url+')',1);
    if (_s._idCheck(_tO.id,true)) {
      _s._wD('soundManager.createSound(): '+_tO.id+' exists',1);
      return _s.sounds[_tO.id];
    }
    if (_s.flashVersion > 8 && _s.useMovieStar) {
	  if (_tO.isMovieStar === null) {
	    _tO.isMovieStar = (_tO.url.match(_s.netStreamPattern)?true:false);
	  }
	  if (_tO.isMovieStar) {
	    _s._wD('soundManager.createSound(): using MovieStar handling');
	  }
	  if (_tO.isMovieStar && (_tO.usePeakData || _tO.useWaveformData || _tO.useEQData)) {
	    _s._wD('Warning: peak/waveform/eqData features unsupported for non-MP3 formats');
	    _tO.usePeakData = false;
		_tO.useWaveformData = false;
		_tO.useEQData = false;
	  }
    }
    _s.sounds[_tO.id] = new SMSound(_tO);
    _s.soundIDs[_s.soundIDs.length] = _tO.id;
    // AS2:
    if (_s.flashVersion == 8) {
      _s.o._createSound(_tO.id,_tO.onjustbeforefinishtime);
    } else {
      _s.o._createSound(_tO.id,_tO.url,_tO.onjustbeforefinishtime,_tO.usePeakData,_tO.useWaveformData,_tO.useEQData,_tO.isMovieStar,(_tO.isMovieStar?_tO.useVideo:false));
    }
    if (_tO.autoLoad || _tO.autoPlay) {
      // TODO: does removing timeout here cause problems?
        if (_s.sounds[_tO.id]) {
          _s.sounds[_tO.id].load(_tO);
        }
    }
    if (_tO.autoPlay) {
	  _s.sounds[_tO.id].play();
	}
    return _s.sounds[_tO.id];
  };

  this.createVideo = function(oOptions) {
    if (arguments.length==2) {
      oOptions = {'id':arguments[0],'url':arguments[1]};
    }
    if (_s.flashVersion >= 9) {
      oOptions.isMovieStar = true;
      oOptions.useVideo = true;
    } else {
      _s._wD('soundManager.createVideo(): flash 9 required for video. Exiting.',2);
      return false;
    }
    if (!_s.useMovieStar) {
      _s._wD('soundManager.createVideo(): MovieStar mode not enabled. Exiting.',2);
    }
    return _s.createSound(oOptions);
  };

  this.destroySound = function(sID,bFromSound) {
    // explicitly destroy a sound before normal page unload, etc.
    if (!_s._idCheck(sID)) {
      return false;
    }
    for (var i=0; i<_s.soundIDs.length; i++) {
      if (_s.soundIDs[i] == sID) {
	    _s.soundIDs.splice(i,1);
        continue;
      }
    }
    // conservative option: avoid crash with ze flash 8
    // calling destroySound() within a sound onload() might crash firefox, certain flavours of winXP + flash 8??
    // if (_s.flashVersion != 8) {
      _s.sounds[sID].unload();
    // }
    if (!bFromSound) {
      // ignore if being called from SMSound instance
      _s.sounds[sID].destruct();
    }
    delete _s.sounds[sID];
  };

  this.destroyVideo = this.destroySound;

  this.load = function(sID,oOptions) {
    if (!_s._idCheck(sID)) {
      return false;
    }
    _s.sounds[sID].load(oOptions);
  };

  this.unload = function(sID) {
    if (!_s._idCheck(sID)) {
      return false;
    }
    _s.sounds[sID].unload();
  };

  this.play = function(sID,oOptions) {
    if (!_s._idCheck(sID)) {
      if (typeof oOptions != 'Object') {
		oOptions = {url:oOptions}; // overloading use case: play('mySound','/path/to/some.mp3');
	  }
      if (oOptions && oOptions.url) {
        // overloading use case, creation + playing of sound: .play('someID',{url:'/path/to.mp3'});
        _s._wD('soundController.play(): attempting to create "'+sID+'"',1);
        oOptions.id = sID;
        _s.createSound(oOptions);
      } else {
        return false;
      }
    }
    _s.sounds[sID].play(oOptions);
  };

  this.start = this.play; // just for convenience

  this.setPosition = function(sID,nMsecOffset) {
    if (!_s._idCheck(sID)) {
      return false;
    }
    _s.sounds[sID].setPosition(nMsecOffset);
  };

  this.stop = function(sID) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s._wD('soundManager.stop('+sID+')',1);
    _s.sounds[sID].stop(); 
  };

  this.stopAll = function() {
    _s._wD('soundManager.stopAll()',1);
    for (var oSound in _s.sounds) {
      if (_s.sounds[oSound] instanceof SMSound) {
		_s.sounds[oSound].stop(); // apply only to sound objects
	  }
    }
  };

  this.pause = function(sID) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s.sounds[sID].pause();
  };

  this.pauseAll = function() {
    for (var i=_s.soundIDs.length; i--;) {
      _s.sounds[_s.soundIDs[i]].pause();
    }
  };

  this.resume = function(sID) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s.sounds[sID].resume();
  };

  this.resumeAll = function() {
    for (var i=_s.soundIDs.length; i--;) {
      _s.sounds[_s.soundIDs[i]].resume();
    }
  };

  this.togglePause = function(sID) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s.sounds[sID].togglePause();
  };

  this.setPan = function(sID,nPan) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s.sounds[sID].setPan(nPan);
  };

  this.setVolume = function(sID,nVol) {
    if (!_s._idCheck(sID)) {
	  return false;
	}
    _s.sounds[sID].setVolume(nVol);
  };

  this.mute = function(sID) {
	if (typeof sID != 'string') {
	  sID = null;
	}
    if (!sID) {
      _s._wD('soundManager.mute(): Muting all sounds');
      for (var i=_s.soundIDs.length; i--;) {
        _s.sounds[_s.soundIDs[i]].mute();
      }
      _s.muted = true;
    } else {
      if (!_s._idCheck(sID)) {
	    return false;
	  }
      _s._wD('soundManager.mute(): Muting "'+sID+'"');
      _s.sounds[sID].mute();
    }
  };

  this.muteAll = function() {
    _s.mute();
  };

  this.unmute = function(sID) {
    if (typeof sID != 'string') {
	  sID = null;
	}
    if (!sID) {
      _s._wD('soundManager.unmute(): Unmuting all sounds');
      for (var i=_s.soundIDs.length; i--;) {
        _s.sounds[_s.soundIDs[i]].unmute();
      }
      _s.muted = false;
    } else {
      if (!_s._idCheck(sID)) {
		return false;
	  }
      _s._wD('soundManager.unmute(): Unmuting "'+sID+'"');
      _s.sounds[sID].unmute();
    }
  };

  this.unmuteAll = function() {
    _s.unmute();
  };

  this.getMemoryUse = function() {
    if (_s.flashVersion == 8) {
      // not supported in Flash 8
      return 0;
    }
    if (_s.o) {
      return parseInt(_s.o._getMemoryUse(),10);
    }
  };

  this.setPolling = function(bPolling) {
    if (!_s.o || !_s.allowPolling) {
	  return false;
	}
    _s.o._setPolling(bPolling);
  };

  this.disable = function(bNoDisable) {
    // destroy all functions
    if (typeof bNoDisable == 'undefined') {
      bNoDisable = false;
    }
    if (_s._disabled) {
	  return false;
    }
    _s._disabled = true;
    _s._wD('soundManager.disable(): Shutting down',1);
    for (var i=_s.soundIDs.length; i--;) {
      _s._disableObject(_s.sounds[_s.soundIDs[i]]);
    }
    _s.initComplete(bNoDisable); // fire "complete", despite fail
    // _s._disableObject(_s); // taken out to allow reboot()
  };

  this.canPlayURL = function(sURL) {
    return (sURL?(sURL.match(_s.filePattern)?true:false):null);	
  };

  this.getSoundById = function(sID,suppressDebug) {
    if (!sID) {
	  throw new Error('SoundManager.getSoundById(): sID is null/undefined');
	}
    var result = _s.sounds[sID];
    if (!result && !suppressDebug) {
      _s._wD('"'+sID+'" is an invalid sound ID.',2);
      // soundManager._wD('trace: '+arguments.callee.caller);
    }
    return result;
  };

  this.onload = function() {
    // window.onload() equivalent for SM2, ready to create sounds etc.
    // this is a stub - you can override this in your own external script, eg. soundManager.onload = function() {}
    soundManager._wD('<em>Warning</em>: soundManager.onload() is undefined.',2);
  };

  this.onerror = function() {
    // stub for user handler, called when SM2 fails to load/init
  };

  // --- "private" methods ---

  this._idCheck = this.getSoundById;

  var _doNothing = function() {
    return false;
  };
  _doNothing._protected = true;

  this._disableObject = function(o) {
    for (var oProp in o) {
      if (typeof o[oProp] == 'function' && typeof o[oProp]._protected == 'undefined') {
		o[oProp] = _doNothing;
	  }
    }
    oProp = null;
  };

  this._failSafely = function(bNoDisable) {
    // general failure exception handler
    if (typeof bNoDisable == 'undefined') {
      bNoDisable = false;
    }
    if (!_s._disabled || bNoDisable) {
      _s._wD('soundManager: Failed to initialise.',2);
      _s.disable(bNoDisable);
    }
  };
  
  this._normalizeMovieURL = function(smURL) {
    var urlParams = null;
    if (smURL) {
      if (smURL.match(/\.swf(\?.*)?$/i)) {
        urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?')+4);
        if (urlParams) {
          return smURL; // assume user knows what they're doing
        }
      } else if (smURL.lastIndexOf('/') != smURL.length-1) {
        smURL = smURL+'/';
      }
    }
    return(smURL && smURL.lastIndexOf('/')!=-1?smURL.substr(0,smURL.lastIndexOf('/')+1):'./')+_s.movieURL;
  };

  this._getDocument = function() {
    return (document.body?document.body:(document.documentElement?document.documentElement:document.getElementsByTagName('div')[0]));
  };

  this._getDocument._protected = true;

  this._createMovie = function(smID,smURL) {
    if (_s._didAppend && _s._appendSuccess) {
	  return false; // ignore if already succeeded
	}
    if (window.location.href.indexOf('debug=1')+1) {
	  _s.debugMode = true; // allow force of debug mode via URL
	}
    _s._didAppend = true;
	
    // safety check for legacy (change to Flash 9 URL)
    _s._setVersionInfo();
    var remoteURL = (smURL?smURL:_s.url);
    var localURL = (_s.altURL?_s.altURL:remoteURL);
    _s.url = _s._normalizeMovieURL(_s._overHTTP?remoteURL:localURL);
    smURL = _s.url;

    var specialCase = null;

    if (_s.useHighPerformance && _s.useMovieStar) {
      specialCase = 'Note: disabling highPerformance, not applicable with movieStar mode on';
      _s.useHighPerformance = false;
    }

    _s.wmode = (_s.useHighPerformance && !_s.useMovieStar?'transparent':''); // wmode=opaque seems to break firefox/windows.

    var oEmbed = {
      name: smID,
      id: smID,
      src: smURL,
      width: '100%',
      height: '100%',
      quality: 'high',
      allowScriptAccess: 'always',
      bgcolor: _s.bgColor,
      pluginspage: 'http://www.macromedia.com/go/getflashplayer',
      type: 'application/x-shockwave-flash',
      wmode: _s.wmode
    };

    var oObject = {
      id: smID,
      data: smURL,
      type: 'application/x-shockwave-flash',
      width: '100%',
      height: '100%',
      wmode: _s.wmode
    };

    var oObjectParams = {
      movie: smURL,
      AllowScriptAccess: 'always',
      quality: 'high',
      bgcolor: _s.bgColor,
      wmode: _s.wmode
    };

    var oMovie = null;
    var tmp = null;

    if (_s.isIE) {
      // IE is "special".
      oMovie = document.createElement('div');
      var movieHTML = '<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="'+_s.wmode+'" /> ':'')+'<param name="bgcolor" value="'+_s.bgColor+'" /><!-- --></object>';
    } else {
      oMovie = document.createElement('embed');
      for (tmp in oEmbed) {
	if (oEmbed.hasOwnProperty(tmp)) {
          oMovie.setAttribute(tmp,oEmbed[tmp]);
	}
      }
    }

    var oD = document.createElement('div');
    oD.id = _s.debugID+'-toggle';
    var oToggle = {
      position: 'fixed',
      bottom: '0px',
      right: '0px',
      width: '1.2em',
      height: '1.2em',
      lineHeight: '1.2em',
      margin: '2px',
      textAlign: 'center',
      border: '1px solid #999',
      cursor: 'pointer',
      background: '#fff',
      color: '#333',
      zIndex: 10001
    };

    oD.appendChild(document.createTextNode('-'));
    oD.onclick = _s._toggleDebug;
    oD.title = 'Toggle SM2 debug console';

    if (navigator.userAgent.match(/msie 6/i)) {
      oD.style.position = 'absolute';
      oD.style.cursor = 'hand';
    }

    for (tmp in oToggle) {
 	if (oToggle.hasOwnProperty(tmp)) {
          oD.style[tmp] = oToggle[tmp];
	}
    }

    var appXHTML = 'soundManager._createMovie(): appendChild/innerHTML set failed. May be app/xhtml+xml DOM-related.';

    var oTarget = _s._getDocument();

    if (oTarget) {
       
      _s.oMC = _$('sm2-container')?_$('sm2-container'):document.createElement('div');

      if (!_s.oMC.id) {
        _s.oMC.id = 'sm2-container';
        _s.oMC.className = 'movieContainer';
        // "hide" flash movie
        var s = null;
        var oEl = null;
        if (_s.useHighPerformance) {
          s = {
 	    	position: 'fixed',
		    width: '8px',
            height: '8px', // must be at least 6px for flash to run fast. odd? yes.
            bottom: '0px',
            left: '0px'
	    // zIndex:-1 // sit behind everything else - potentially dangerous/buggy?
          };
        } else {
          s = {
            position: 'absolute',
	    width: '1px',
            height: '1px',
            top: '-999px',
            left: '-999px'
          };
        }
        var x = null;
        for (x in s) {
		  if (s.hasOwnProperty(x)) {
            _s.oMC.style[x] = s[x];
		  }
        }
        try {
		  if (!_s.isIE) {
    	    _s.oMC.appendChild(oMovie);
		  }
          oTarget.appendChild(_s.oMC);
		  if (_s.isIE) {
			oEl = _s.oMC.appendChild(document.createElement('div'));
			oEl.className = 'sm2-object-box';
			oEl.innerHTML = movieHTML;
          }
          _s._appendSuccess = true;
        } catch(e) {
          throw new Error(appXHTML);
        }
      } else {
        // it's already in the document.
        _s.oMC.appendChild(oMovie);
		if (_s.isIE) {
		  oEl = _s.oMC.appendChild(document.createElement('div'));
		  oEl.className = 'sm2-object-box';
		  oEl.innerHTML = movieHTML;
        }
        _s._appendSuccess = true;
      }

      if (!_$(_s.debugID) && ((!_s._hasConsole||!_s.useConsole)||(_s.useConsole && _s._hasConsole && !_s.consoleOnly))) {
        var oDebug = document.createElement('div');
        oDebug.id = _s.debugID;
        oDebug.style.display = (_s.debugMode?'block':'none');
        if (_s.debugMode && !_$(oD.id)) {
          try {
            oTarget.appendChild(oD);
          } catch(e2) {
            throw new Error(appXHTML);
          }
          oTarget.appendChild(oDebug);
        }
      }
      oTarget = null;
    }

    if (specialCase) {
      _s._wD(specialCase);
    }

    _s._wD('-- SoundManager 2 '+_s.version+(_s.useMovieStar?', MovieStar mode':'')+(_s.useHighPerformance?', high performance mode':'')+' --',1);
    _s._wD('soundManager._createMovie(): Trying to load '+smURL+(!_s._overHTTP && _s.altURL?'(alternate URL)':''),1);
  };

  // aliased to this._wD()
  this._writeDebug = function(sText,sType,bTimestamp) {
    if (!_s.debugMode) {
	  return false;
	}
    if (typeof bTimestamp != 'undefined' && bTimestamp) {
      sText = sText + ' | '+new Date().getTime();
    }
    if (_s._hasConsole && _s.useConsole) {
      var sMethod = _s._debugLevels[sType];
      if (typeof console[sMethod] != 'undefined') {
	    console[sMethod](sText);
      } else {
        console.log(sText);
      }
      if (_s.useConsoleOnly) {
	return true;
      }
    }
    var sDID = 'soundmanager-debug';
    try {
      var o = _$(sDID);
      if (!o) {
		return false;
	  }
      var oItem = document.createElement('div');
      if (++_s._wdCount%2===0) {
	    oItem.className = 'sm2-alt';
      }
      // sText = sText.replace(/\n/g,'<br />');
      if (typeof sType == 'undefined') {
        sType = 0;
      } else {
        sType = parseInt(sType,10);
      }
      oItem.appendChild(document.createTextNode(sText));
      if (sType) {
        if (sType >= 2) {
		  oItem.style.fontWeight = 'bold';
		}
        if (sType == 3) {
		  oItem.style.color = '#ff3333';
		}
      }
      // o.appendChild(oItem); // top-to-bottom
      o.insertBefore(oItem,o.firstChild); // bottom-to-top
    } catch(e) {
      // oh well
    }
    o = null;
  };
  this._writeDebug._protected = true;
  this._wdCount = 0;
  this._wdCount._protected = true;
  this._wD = this._writeDebug;

  this._wDAlert = function(sText) { alert(sText); };

  if (window.location.href.indexOf('debug=alert')+1 && _s.debugMode) {
    _s._wD = _s._wDAlert;
  }

  this._toggleDebug = function() {
    var o = _$(_s.debugID);
    var oT = _$(_s.debugID+'-toggle');
    if (!o) {
	  return false;
	}
    if (_s._debugOpen) {
      // minimize
      oT.innerHTML = '+';
      o.style.display = 'none';
    } else {
      oT.innerHTML = '-';
      o.style.display = 'block';
    }
    _s._debugOpen = !_s._debugOpen;
  };

  this._toggleDebug._protected = true;

  this._debug = function() {
    _s._wD('--- soundManager._debug(): Current sound objects ---',1);
    for (var i=0,j=_s.soundIDs.length; i<j; i++) {
      _s.sounds[_s.soundIDs[i]]._debug();
    }
  };

  this._debugTS = function(sEventType,bSuccess,sMessage) {
    // troubleshooter debug hooks
    if (typeof sm2Debugger != 'undefined') {
	  try {
	    sm2Debugger.handleEvent(sEventType,bSuccess,sMessage);
	  } catch(e) {
	    // oh well	
	  }
    }
  };

  this._debugTS._protected = true;

  this._mergeObjects = function(oMain,oAdd) {
    // non-destructive merge
    var o1 = {}; // clone o1
    for (var i in oMain) {
	  if (oMain.hasOwnProperty(i)) {
        o1[i] = oMain[i];
	  }
    }
    var o2 = (typeof oAdd == 'undefined'?_s.defaultOptions:oAdd);
    for (var o in o2) {
      if (o2.hasOwnProperty(o) && typeof o1[o] == 'undefined') {
		o1[o] = o2[o];
	  }
    }
    return o1;
  };

  this.createMovie = function(sURL) {
    if (sURL) {
      _s.url = sURL;
    }
    _s._initMovie();
  };

  this.go = this.createMovie; // nice alias

  this._initMovie = function() {
    // attempt to get, or create, movie
    if (_s.o) {
	  return false; // may already exist
    }
    _s.o = _s.getMovie(_s.id); // (inline markup)
    if (!_s.o) {
      if (!_s.oRemoved) {
        // try to create
        _s._createMovie(_s.id,_s.url);
      } else {
        // try to re-append removed movie after reboot()
        if (!_s.isIE) {
          _s.oMC.appendChild(_s.oRemoved);
        } else {
          _s.oMC.innerHTML = _s.oRemovedHTML;
        }
        _s.oRemoved = null;
        _s._didAppend = true;
      }
      _s.o = _s.getMovie(_s.id);
    }
    if (_s.o) {
      _s._wD('soundManager._initMovie(): Got '+_s.o.nodeName+' element ('+(_s._didAppend?'created via JS':'static HTML')+')',1);
      if (_s.flashLoadTimeout>0) {
        _s._wD('soundManager._initMovie(): Waiting for ExternalInterface call from Flash..');
      }
    }
  };

  this.waitForExternalInterface = function() {
    if (_s._waitingForEI) {
	  return false;
	}
    _s._waitingForEI = true;
    if (_s._tryInitOnFocus && !_s._isFocused) {
      _s._wD('soundManager: Special case: Waiting for focus-related event..');
      return false;
    }
    if (_s.flashLoadTimeout>0) {
      if (!_s._didInit) {
        _s._wD('soundManager: Getting impatient, still waiting for Flash.. ;)');
      }
      setTimeout(function() {
        if (!_s._didInit) {
          _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);
          if (!_s._overHTTP) {
          _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);
        }
        _s._debugTS('flashtojs',false,': Timed out'+(_s._overHTTP)?' (Check flash security)':' (No plugin/missing SWF?)');
      }
      // if still not initialized and no other options, give up
      if (!_s._didInit && _s._okToDisable) {
	_s._failSafely(true); // don't disable, for reboot()
      }
    },_s.flashLoadTimeout);
    } else if (!_s.didInit) {
      _s._wD('soundManager: Waiting indefinitely for Flash...');
    }
  };

  this.handleFocus = function() {
    if (_s._isFocused || !_s._tryInitOnFocus) {
	  return true;
	}
    _s._okToDisable = true;
    _s._isFocused = true;
    _s._wD('soundManager.handleFocus()');
    if (_s._tryInitOnFocus) {
      // giant Safari 3.1 hack - assume window in focus if mouse is moving, since document.hasFocus() not currently implemented.
      window.removeEventListener('mousemove',_s.handleFocus,false);
    }
    // allow init to restart
    _s._waitingForEI = false;
    setTimeout(_s.waitForExternalInterface,500);
    // detach event
    if (window.removeEventListener) {
      window.removeEventListener('focus',_s.handleFocus,false);
    } else if (window.detachEvent) {
      window.detachEvent('onfocus',_s.handleFocus);
    }
  };

  this.initComplete = function(bNoDisable) {
    if (_s._didInit) {
	  return false;
	}
    _s._didInit = true;
    _s._wD('-- SoundManager 2 '+(_s._disabled?'failed to load':'loaded')+' ('+(_s._disabled?'security/load error':'OK')+') --',1);
    if (_s._disabled || bNoDisable) {
      _s._wD('soundManager.initComplete(): calling soundManager.onerror()',1);
      _s._debugTS('onload',false);
      _s.onerror.apply(window);
      return false;
    } else {
	  _s._debugTS('onload',true);
    }
    if (_s.waitForWindowLoad && !_s._windowLoaded) {
      _s._wD('soundManager: Waiting for window.onload()');
      if (window.addEventListener) {
        window.addEventListener('load',_s.initUserOnload,false);
      } else if (window.attachEvent) {
        window.attachEvent('onload',_s.initUserOnload);
      }
      return false;
    } else {
      if (_s.waitForWindowLoad && _s._windowLoaded) {
        _s._wD('soundManager: Document already loaded');
      }
      _s.initUserOnload();
    }
  };

  this.initUserOnload = function() {
    _s._wD('soundManager.initComplete(): calling soundManager.onload()',1);
    // call user-defined "onload", scoped to window
    _s.onload.apply(window);
    _s._wD('soundManager.onload() complete',1);
  };

  this.init = function() {
    _s._wD('-- soundManager.init() --');
    // called after onload()
    _s._initMovie();
    if (_s._didInit) {
      _s._wD('soundManager.init(): Already called?');
      return false;
    }
    // event cleanup
    if (window.removeEventListener) {
      window.removeEventListener('load',_s.beginDelayedInit,false);
    } else if (window.detachEvent) {
      window.detachEvent('onload',_s.beginDelayedInit);
    }
    try {
      _s._wD('Attempting to call Flash from JS..');
      _s.o._externalInterfaceTest(false); // attempt to talk to Flash
      // _s._wD('Flash ExternalInterface call (JS-Flash) OK',1);
      if (!_s.allowPolling) {
	    _s._wD('Polling (whileloading/whileplaying support) is disabled.',1);
	  }
      _s.setPolling(true);
	  if (!_s.debugMode) {
		_s.o._disableDebug();
	  }
      _s.enabled = true;
      _s._debugTS('jstoflash',true);
    } catch(e) {
	  _s._debugTS('jstoflash',false);
      _s._failSafely(true); // don't disable, for reboot()
      _s.initComplete();
      return false;
    }
    _s.initComplete();
  };

  this.beginDelayedInit = function() {
    _s._wD('soundManager.beginDelayedInit()');
    _s._windowLoaded = true;
    setTimeout(_s.waitForExternalInterface,500);
    setTimeout(_s.beginInit,20);
  };

  this.beginInit = function() {
    if (_s._initPending) {
	  return false;
	}
    _s.createMovie(); // ensure creation if not already done
    _s._initMovie();
    _s._initPending = true;
    return true;
  };

  this.domContentLoaded = function() {
    _s._wD('soundManager.domContentLoaded()');
    if (document.removeEventListener) {
	  document.removeEventListener('DOMContentLoaded',_s.domContentLoaded,false);
	}
    _s.go();
  };

  this._externalInterfaceOK = function() {
    // callback from flash for confirming that movie loaded, EI is working etc.
    if (_s.swfLoaded) {
	  return false;
	}
    _s._wD('soundManager._externalInterfaceOK()');
    _s._debugTS('swf',true);
    _s._debugTS('flashtojs',true);
    _s.swfLoaded = true;
    _s._tryInitOnFocus = false;
    if (_s.isIE) {
      // IE needs a timeout OR delay until window.onload - may need TODO: investigating
      setTimeout(_s.init,100);
    } else {
      _s.init();
    }
  };

  this._setSandboxType = function(sandboxType) {
    var sb = _s.sandbox;
    sb.type = sandboxType;
    sb.description = sb.types[(typeof sb.types[sandboxType] != 'undefined'?sandboxType:'unknown')];
    _s._wD('Flash security sandbox type: '+sb.type);
    if (sb.type == 'localWithFile') {
      sb.noRemote = true;
      sb.noLocal = false;
      _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);
    } else if (sb.type == 'localWithNetwork') {
      sb.noRemote = false;
      sb.noLocal = true;
    } else if (sb.type == 'localTrusted') {
      sb.noRemote = false;
      sb.noLocal = false;
    }
  };

  this.reboot = function() {
    // attempt to reset and init SM2
    _s._wD('soundManager.reboot()');
    if (_s.soundIDs.length) {
      _s._wD('Destroying '+_s.soundIDs.length+' SMSound objects...');
    }
    for (var i=_s.soundIDs.length; i--;) {
      _s.sounds[_s.soundIDs[i]].destruct();
    }
    // trash ze flash
    try {
      if (_s.isIE) {
        _s.oRemovedHTML = _s.o.innerHTML;
      }
      _s.oRemoved = _s.o.parentNode.removeChild(_s.o);
      _s._wD('Flash movie removed.');
    } catch(e) {
      // uh-oh.
      _s._wD('Warning: Failed to remove flash movie.',2);
    }
    _s.enabled = false;
    _s._didInit = false;
    _s._waitingForEI = false;
    _s._initPending = false;
    _s._didInit = false;
    _s._didAppend = false;
    _s._appendSuccess = false;
    _s._didInit = false;
    _s._disabled = false;
    _s._waitingforEI = true;
    _s.swfLoaded = false;
    _s.soundIDs = {};
    _s.sounds = [];
    _s.o = null;
    _s._wD('soundManager: Rebooting...');
    window.setTimeout(function() {
      soundManager.beginDelayedInit();
    },20);
  };

  this.destruct = function() {
    _s._wD('soundManager.destruct()');
    _s.disable(true);
  };
  
  // SMSound (sound object)
  
  SMSound = function(oOptions) {
  var _t = this;
  this.sID = oOptions.id;
  this.url = oOptions.url;
  this.options = _s._mergeObjects(oOptions);
  this.instanceOptions = this.options; // per-play-instance-specific options
  this._iO = this.instanceOptions; // short alias

  // assign property defaults (volume, pan etc.)
  this.pan = this.options.pan;
  this.volume = this.options.volume;

  this._debug = function() {
    if (_s.debugMode) {
    var stuff = null;
    var msg = [];
    var sF = null;
    var sfBracket = null;
    var maxLength = 64; // # of characters of function code to show before truncating
    for (stuff in _t.options) {
      if (_t.options[stuff] !== null) {
        if (_t.options[stuff] instanceof Function) {
	      // handle functions specially
	      sF = _t.options[stuff].toString();
	      sF = sF.replace(/\s\s+/g,' '); // normalize spaces
	      sfBracket = sF.indexOf('{');
	      msg[msg.length] = ' '+stuff+': {'+sF.substr(sfBracket+1,(Math.min(Math.max(sF.indexOf('\n')-1,maxLength),maxLength))).replace(/\n/g,'')+'... }';
	    } else {
	      msg[msg.length] = ' '+stuff+': '+_t.options[stuff];
	    }
      }
    }
    _s._wD('SMSound() merged options: {\n'+msg.join(', \n')+'\n}');
    }
  };

  this._debug();

  this.id3 = {
   /* 
    Name/value pairs set via Flash when available - see reference for names:
    http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001567.html
    (eg., this.id3.songname or this.id3['songname'])
   */
  };

  this.resetProperties = function(bLoaded) {
    _t.bytesLoaded = null;
    _t.bytesTotal = null;
    _t.position = null;
    _t.duration = null;
    _t.durationEstimate = null;
    _t.loaded = false;
    _t.playState = 0;
    _t.paused = false;
    _t.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
    _t.muted = false;
    _t.didBeforeFinish = false;
    _t.didJustBeforeFinish = false;
    _t.isBuffering = false;
    _t.instanceOptions = {};
    _t.instanceCount = 0;
    _t.peakData = {
      left: 0,
      right: 0
    };
    _t.waveformData = [];
    _t.eqData = [];
  };

  _t.resetProperties();

  // --- public methods ---

  this.load = function(oOptions) {
    if (typeof oOptions != 'undefined') {
      _t._iO = _s._mergeObjects(oOptions);
      _t.instanceOptions = _t._iO;
    } else {
      oOptions = _t.options;
      _t._iO = oOptions;
      _t.instanceOptions = _t._iO;
    } 
    if (typeof _t._iO.url == 'undefined') {
      _t._iO.url = _t.url;
    }
    _s._wD('soundManager.load(): '+_t._iO.url,1);
    if (_t._iO.url == _t.url && _t.readyState !== 0 && _t.readyState != 2) {
      _s._wD('soundManager.load(): current URL already assigned.',1);
      return false;
    }
    _t.loaded = false;
    _t.readyState = 1;
    _t.playState = 0; // (oOptions.autoPlay?1:0); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)
    try {
      if (_s.flashVersion==8) {
        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream,_t._iO.autoPlay,(_t._iO.whileloading?1:0));
      } else {
        _s.o._load(_t.sID,_t._iO.url,_t._iO.stream?true:false,_t._iO.autoPlay?true:false); // ,(_tO.whileloading?true:false)
        if (_t._iO.isMovieStar && _t._iO.autoLoad && !_t._iO.autoPlay) {
          // special case: MPEG4 content must start playing to load, then pause to prevent playing.
          _t.pause();
        }
      }
    } catch(e) {
      _s._wD('SMSound.load(): Exception: JS-Flash communication failed, or JS error.',2);
      _s._debugTS('onload',false);
      _s.onerror();
      _s.disable();
    }

  };

  this.unload = function() {
    // Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3
    // Flash 9/AS3: Close stream, preventing further load
    if (_t.readyState !== 0) {
      _s._wD('SMSound.unload(): "'+_t.sID+'"');
      if (_t.readyState != 2) { // reset if not error
        _t.setPosition(0,true); // reset current sound positioning
      }
      _s.o._unload(_t.sID,_s.nullURL);
      // reset load/status flags
      _t.resetProperties();
    }
  };

  this.destruct = function() {
    // kill sound within Flash
    _s._wD('SMSound.destruct(): "'+_t.sID+'"');
    _s.o._destroySound(_t.sID);
    _s.destroySound(_t.sID,true); // ensure deletion from controller
  };

  this.play = function(oOptions) {
    if (!oOptions) {
	  oOptions = {};
    }
    _t._iO = _s._mergeObjects(oOptions,_t._iO);
    _t._iO = _s._mergeObjects(_t._iO,_t.options);
    _t.instanceOptions = _t._iO;
    if (_t.playState == 1) {
      var allowMulti = _t._iO.multiShot;
      if (!allowMulti) {
        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (one-shot)',1);
        return false;
      } else {
        _s._wD('SMSound.play(): "'+_t.sID+'" already playing (multi-shot)',1);
      }
    }
    if (!_t.loaded) {
      if (_t.readyState === 0) {
        _s._wD('SMSound.play(): Attempting to load "'+_t.sID+'"',1);
        // try to get this sound playing ASAP
        _t._iO.stream = true;
        _t._iO.autoPlay = true;
        // TODO: need to investigate when false, double-playing
        // if (typeof oOptions.autoPlay=='undefined') _tO.autoPlay = true; // only set autoPlay if unspecified here
        _t.load(_t._iO); // try to get this sound playing ASAP
      } else if (_t.readyState == 2) {
        _s._wD('SMSound.play(): Could not load "'+_t.sID+'" - exiting',2);
        return false;
      } else {
        _s._wD('SMSound.play(): "'+_t.sID+'" is loading - attempting to play..',1);
      }
    } else {
      _s._wD('SMSound.play(): "'+_t.sID+'"');
    }
    if (_t.paused) {
      _t.resume();
    } else {
      _t.playState = 1;
      if (!_t.instanceCount || _s.flashVersion == 9) {
		_t.instanceCount++;
	  }
      _t.position = (typeof _t._iO.position != 'undefined' && !isNaN(_t._iO.position)?_t._iO.position:0);
      if (_t._iO.onplay) {
		_t._iO.onplay.apply(_t);
	  }
      _t.setVolume(_t._iO.volume,true); // restrict volume to instance options only
      _t.setPan(_t._iO.pan,true);
      _s.o._start(_t.sID,_t._iO.loop||1,(_s.flashVersion==9?_t.position:_t.position/1000));
    }
  };

  this.start = this.play; // just for convenience

  this.stop = function(bAll) {
    if (_t.playState == 1) {
      _t.playState = 0;
      _t.paused = false;
      // if (_s.defaultOptions.onstop) _s.defaultOptions.onstop.apply(_s);
      if (_t._iO.onstop) {
		_t._iO.onstop.apply(_t);
	  }
      _s.o._stop(_t.sID,bAll);
      _t.instanceCount = 0;
      _t._iO = {};
      // _t.instanceOptions = _t._iO;
    }
  };

  this.setPosition = function(nMsecOffset,bNoDebug) {
    if (typeof nMsecOffset == 'undefined') {
      nMsecOffset = 0;
    }
    var offset = Math.min(_t.duration,Math.max(nMsecOffset,0)); // position >= 0 and <= current available (loaded) duration
    _t._iO.position = offset;
    if (!bNoDebug) {
      _s._wD('SMSound.setPosition('+nMsecOffset+')'+(nMsecOffset != offset?', corrected value: '+offset:''));
    }
    _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)
  };

  this.pause = function() {
    if (_t.paused || _t.playState === 0) {
	  return false;
	}
    _s._wD('SMSound.pause()');
    _t.paused = true;
    _s.o._pause(_t.sID);
    if (_t._iO.onpause) {
	  _t._iO.onpause.apply(_t);
	}
  };

  this.resume = function() {
    if (!_t.paused || _t.playState === 0) {
	  return false;
	}
    _s._wD('SMSound.resume()');
    _t.paused = false;
    _s.o._pause(_t.sID); // flash method is toggle-based (pause/resume)
    if (_t._iO.onresume) {
	  _t._iO.onresume.apply(_t);
	}
  };

  this.togglePause = function() {
    _s._wD('SMSound.togglePause()');
    if (!_t.playState) {
      _t.play({position:(_s.flashVersion==9?_t.position:_t.position/1000)});
      return false;
    }
    if (_t.paused) {
      _t.resume();
    } else {
      _t.pause();
    }
  };

  this.setPan = function(nPan,bInstanceOnly) {
    if (typeof nPan == 'undefined') {
      nPan = 0;
    }
    if (typeof bInstanceOnly == 'undefined') {
      bInstanceOnly = false;
    }
    _s.o._setPan(_t.sID,nPan);
    _t._iO.pan = nPan;
    if (!bInstanceOnly) {
      _t.pan = nPan;
    }
  };

  this.setVolume = function(nVol,bInstanceOnly) {
    if (typeof nVol == 'undefined') {
      nVol = 100;
    }
    if (typeof bInstanceOnly == 'undefined') {
      bInstanceOnly = false;
    }
    _s.o._setVolume(_t.sID,(_s.muted&&!_t.muted)||_t.muted?0:nVol);
    _t._iO.volume = nVol;
    if (!bInstanceOnly) {
      _t.volume = nVol;
    }
  };

  this.mute = function() {
    _t.muted = true;
    _s.o._setVolume(_t.sID,0);
  };

  this.unmute = function() {
    _t.muted = false;
    var hasIO = typeof _t._iO.volume != 'undefined';
    _s.o._setVolume(_t.sID,hasIO?_t._iO.volume:_t.options.volume);
  };

  // --- "private" methods called by Flash ---

  this._whileloading = function(nBytesLoaded,nBytesTotal,nDuration) {
    if (!_t._iO.isMovieStar) {
      _t.bytesLoaded = nBytesLoaded;
      _t.bytesTotal = nBytesTotal;
      _t.duration = Math.floor(nDuration);
      _t.durationEstimate = parseInt((_t.bytesTotal/_t.bytesLoaded)*_t.duration,10); // estimate total time (will only be accurate with CBR MP3s.)
      if (_t.readyState != 3 && _t._iO.whileloading) {
	_t._iO.whileloading.apply(_t);
      }
    } else {
      _t.bytesLoaded = nBytesLoaded;
      _t.bytesTotal = nBytesTotal;
      _t.duration = Math.floor(nDuration);
      _t.durationEstimate = _t.duration;
      if (_t.readyState != 3 && _t._iO.whileloading) {
	_t._iO.whileloading.apply(_t);
      }
    }
  };

  this._onid3 = function(oID3PropNames,oID3Data) {
    // oID3PropNames: string array (names)
    // ID3Data: string array (data)
    _s._wD('SMSound._onid3(): "'+this.sID+'" ID3 data received.');
    var oData = [];
    for (var i=0,j=oID3PropNames.length; i<j; i++) {
      oData[oID3PropNames[i]] = oID3Data[i];
      // _s._wD(oID3PropNames[i]+': '+oID3Data[i]);
    }
    _t.id3 = _s._mergeObjects(_t.id3,oData);
    if (_t._iO.onid3) {
      _t._iO.onid3.apply(_t);
    }
  };

  this._whileplaying = function(nPosition,oPeakData,oWaveformData,oEQData) {
    if (isNaN(nPosition) || nPosition === null) {
      return false; // Flash may return NaN at times
    }
    _t.position = nPosition;
	if (_t._iO.usePeakData && typeof oPeakData != 'undefined' && oPeakData) {
	  _t.peakData = {
	   left: oPeakData.leftPeak,
	   right: oPeakData.rightPeak
	  };
	}
	if (_t._iO.useWaveformData && typeof oWaveformData != 'undefined' && oWaveformData) {
	  _t.waveformData = oWaveformData;
	  /*
	  _t.spectrumData = {
	   left: oSpectrumData.left.split(','),
	   right: oSpectrumData.right.split(',')
	  }
	  */
	}
	if (_t._iO.useEQData && typeof oEQData != 'undefined' && oEQData) {
	  _t.eqData = oEQData;
	}
    if (_t.playState == 1) {
      if (_t._iO.whileplaying) {
	_t._iO.whileplaying.apply(_t); // flash may call after actual finish
      }
      if (_t.loaded && _t._iO.onbeforefinish && _t._iO.onbeforefinishtime && !_t.didBeforeFinish && _t.duration-_t.position <= _t._iO.onbeforefinishtime) {
        _s._wD('duration-position &lt;= onbeforefinishtime: '+_t.duration+' - '+_t.position+' &lt= '+_t._iO.onbeforefinishtime+' ('+(_t.duration-_t.position)+')');
        _t._onbeforefinish();
      }
    }
  };

  this._onload = function(bSuccess) {
    bSuccess = (bSuccess==1?true:false);
    _s._wD('SMSound._onload(): "'+_t.sID+'"'+(bSuccess?' loaded.':' failed to load? - '+_t.url),(bSuccess?1:2));
    if (!bSuccess) {
      if (_s.sandbox.noRemote === true) {
        _s._wD('SMSound._onload(): Reminder: Flash security is denying network/internet access',1);
      }
      if (_s.sandbox.noLocal === true) {
        _s._wD('SMSound._onload(): Reminder: Flash security is denying local access',1);
      }
    }
    _t.loaded = bSuccess;
    _t.readyState = bSuccess?3:2;
    if (_t._iO.onload) {
      _t._iO.onload.apply(_t);
    }
  };

  this._onbeforefinish = function() {
    if (!_t.didBeforeFinish) {
      _t.didBeforeFinish = true;
      if (_t._iO.onbeforefinish) {
        _s._wD('SMSound._onbeforefinish(): "'+_t.sID+'"');
        _t._iO.onbeforefinish.apply(_t);
      }
    }
  };

  this._onjustbeforefinish = function(msOffset) {
    // msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)
    if (!_t.didJustBeforeFinish) {
      _t.didJustBeforeFinish = true;
      if (_t._iO.onjustbeforefinish) {
        _s._wD('SMSound._onjustbeforefinish(): "'+_t.sID+'"');
        _t._iO.onjustbeforefinish.apply(_t);
      }
    }
  };

  this._onfinish = function() {
    // sound has finished playing

    // TODO: calling user-defined onfinish() should happen after setPosition(0)
    // OR: onfinish() and then setPosition(0) is bad.

    if (_t._iO.onbeforefinishcomplete) {
      _t._iO.onbeforefinishcomplete.apply(_t);
    }
    // reset some state items
    _t.didBeforeFinish = false;
    _t.didJustBeforeFinish = false;
    if (_t.instanceCount) {
      _t.instanceCount--;
      if (!_t.instanceCount) {
        // reset instance options
        // _t.setPosition(0);
        _t.playState = 0;
        _t.paused = false;
        _t.instanceCount = 0;
        _t.instanceOptions = {};
        if (_t._iO.onfinish) {
          _s._wD('SMSound._onfinish(): "'+_t.sID+'"');
          _t._iO.onfinish.apply(_t);
        }
      }
    } else {
      // _t.setPosition(0);
    }
  };

  this._onmetadata = function(oMetaData) {
    // movieStar mode only
    _s._wD('SMSound.onmetadata()');
    // Contains a subset of metadata. Note that files may have their own unique metadata.
    // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html
    if (!oMetaData.width && !oMetaData.height) {
	  _s._wD('No width/height given, assuming defaults');
	  oMetaData.width = 320;
	  oMetaData.height = 240;
    }
    _t.metadata = oMetaData; // potentially-large object from flash
    _t.width = oMetaData.width;
    _t.height = oMetaData.height;
    if (_t._iO.onmetadata) {
      _s._wD('SMSound._onmetadata(): "'+_t.sID+'"');
      _t._iO.onmetadata.apply(_t);
    }
    _s._wD('SMSound.onmetadata() complete');
  };

  this._onbufferchange = function(bIsBuffering) {
    if (bIsBuffering == _t.isBuffering) {
      // ignore initial "false" default, if matching
      return false;
    }
    _t.isBuffering = (bIsBuffering==1?true:false);
    if (_t._iO.onbufferchange) {
      _s._wD('SMSound._onbufferchange(): '+bIsBuffering);
      _t._iO.onbufferchange.apply(_t);
    }
  };

  }; // SMSound()

  // register a few event handlers
  if (window.addEventListener) {
    window.addEventListener('focus',_s.handleFocus,false);
    window.addEventListener('load',_s.beginDelayedInit,false);
    window.addEventListener('unload',_s.destruct,false);
    if (_s._tryInitOnFocus) {
      window.addEventListener('mousemove',_s.handleFocus,false); // massive Safari focus hack
    }
  } else if (window.attachEvent) {
    window.attachEvent('onfocus',_s.handleFocus);
    window.attachEvent('onload',_s.beginDelayedInit);
    window.attachEvent('unload',_s.destruct);
  } else {
    // no add/attachevent support - safe to assume no JS -> Flash either.
    _s._debugTS('onload',false);
    soundManager.onerror();
    soundManager.disable();
  }

//  if (document.addEventListener) {
//	document.addEventListener('DOMContentLoaded',_s.domContentLoaded,false);
//  }

} // SoundManager()

soundManager = new SoundManager();
/*Logging subsystem, used for logging to Firefox Console-like object
 *    Enable/Disable logging controlled by logging members:
 *          debug,
 *          arguments,
 *          whitelist,
 *          backlist
 */
logging = {
    // logging configuration
    // do _never_ check the section below in!!!
    // do not use trailing comas in object definitions ever, that's a syntax error on IE and opera!!!!

    debug: false, 		/*Enabled function calls logging flag*/
    arguments: false,	/*Enable function arguments logging flag*/
    whitelist: {        /*Dictionary of names to be logged*/
    },
    blacklist: {        /*Dictionary of names to be ignored*/
        translator:true
    },

    _keys:function(data){
		/* Fetch data object properties as keys 
         * Copied from util.js due to dependencies conflict
         */
        var result = new Array();
        for(key in data){
            result.push(key);
        }
        return result;
    },

    // logging implementation
    match: function(parts, config, otherwise){
		/* Checks if parst connected by '.' are present in config as keys.
		 * Checked combinations of parts p0, p0.p1, p0.p1.p2, ...
		 * Return true in case of found correspondence.
		 * parts - list of names
		 * config - object whos properties used as dictionary
		 * otherwise - value returned in case of mismatch
		 */
        var keys = logging._keys(config);
        if(keys.length){
            for(var i=0; i<parts.length; i++){
                if(config[parts.slice(0, i+1).join('.')]){
                    return true;
                }
            }
            return false;
        }
        return otherwise;
    },
    decide:function(name){
		/* Checks is name is valid logging.
		 * It must match against not match against blacklist 
		 * and possibly be in whitelist.
		 * Checking performed only when debug flag is True.
		 * name - string with possible indication of parts by '.' separator
		 */
        if(logging.debug){
            if(name.length){ 
                var parts = name.split('.');
                var whitelisted = logging.match(parts, logging.whitelist, true);
                var blacklisted = logging.match(parts, logging.blacklist, false);
                return whitelisted && !blacklisted;
            }
            else{
                return true;
            }
        }
        else{
            return false;
        }
    },
    fun:function(name, fun){
		/* Decorates function if logging of it enabled.
		 * Performs function call with tracing colls and arguments to
		 * console object.
		 * Logs call fail information.
		 */
        if(logging.decide(name)){
            _fun_logger_impl = function(){
                console.group(name);
                try{
                    if(logging.arguments && arguments.length){
                        console.log('arguments:' + $.serializeJSON(arguments));
                    }
                }
                catch(e){}
                try{
                    var result = fun.apply(this, arguments);
                }
                catch(e){
                    console.error(e.name + ': ' + e.message);
                    console.groupEnd();
                    throw e;
                }
                console.groupEnd();
                return result;
            }
            return _fun_logger_impl;
        }
        else{
            return fun;
        }
    },
    ns:function(name){
		/* Creates logging namespace object with pointed name
		 * if logging enabled. Otherwise returns dummy namespace wrapper.
		 * Methods of namespace:
		 * 		fun() - logging function call
		 * 		ns() - creation of child logging namespace
		 * 		leave() - logging namespace finish
		 */
        if(logging.decide(name)){
            console.group(name);
            return {
                fun:function(fun_name, fun){
                    return logging.fun([name, fun_name].join('.'), fun);
                },
                ns:function(sub_name){
                    return logging.ns([name, sub_name].join('.'));
                },
                leave:function(){
                    console.groupEnd();
                }
            }
        }
        else{
            return {
                fun:function(fun_name, fun){
                    return fun;
                },
                ns:function(sub_name){
                    return logging.ns([name, sub_name].join('.'));
                },
                leave:function(){
                }
            }
        }
    }
}


var util_logger = logging.ns('util');

var Try = {
/* Executor of a list of functions without arguments
 * with catching all possible exceptions.
 */
    _exec : function(args, is_try_and_break){
		/* Performs call of array of functions without arguments.
		 * If is_try_and_break == true -> return result of first
		 * successfully executed function.
		 * Otherwise -> return result of last successfully executed
		 * function.
		 * If no function succeeded -> return undefined value
		 */
       	var return_value;

        for (var i = 0, length = args.length; i < length; i++){
            var lambda = args[i];
            try{
                return_value = lambda();
                if(is_try_and_break) break;
            } 
            catch (e){}
        }
        return return_value;
    },

    one: function(){
		/* Call functions without arguments from list of functions
		 * untill first succeessfull execution and return its result.
		 * arguments - list of functions
		 */
        return Try._exec(arguments, true);
    },

    all: function(){
		/* Call all functions without arguments from list of functions
		 * and return the result of last successfully executed function.
		 * arguments - list of functions
		 */
        return Try._exec(arguments, false);
    }   
};

var util =  {
    window_scroll:util_logger.fun('window_scroll', function(){
        if(typeof(window.scrollY) == 'number'){
            return {
                top: window.scrollY,
                left: window.scrollX
            } 
        }
        else if(typeof(window.pageYOffset) == 'number') {
            //Netscape compliant
            return {
                top: window.pageYOffset,
                left: window.pageXOffset
            }
        } else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            return {
                top: document.body.scrollTop,
                left: document.body.scrollLeft
            }
        } else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            return {
                top: document.documentElement.scrollTop,
                left: document.documentElement.scrollLeft
            }
        }
        else{
            return {
                left: 0,
                top: 0
            };
        }
    }),
    keys:util_logger.fun('keys', function(data){
		/*fetch data object properties as keys*/
        var result = new Array();
        for(key in data){
            result.push(key);
        }
        return result;
    }),
    clone:util_logger.fun('clone', function(obj){
		/*creates shallow copy of an object*/
        var result = {};
        for(key in obj){
            result[key] = obj[key];
        }
        return result;
    }),
    datetime: util_logger.fun('datetime', function(data, format){
		/*format string from date object by format description*/
        if(data){
            var result = format.replace('%Y', data.year)
            result = result.replace('%m', data.month);
            result = result.replace('%d', data.day);
            result = result.replace('%H', data.hour);
            result = result.replace('%M', data.minute);
            result = result.replace('%s', data.second);
            return result;
        }
        return ''; /*'<undefined>'*/
    }),
    datetime_long: util_logger.fun('datetime', function(data, format){
		/*format string from date object by format description using special formatting*/
        if(data){
            var months = {
                "01":"Jan",
                "02":"Feb",
                "03":"Mar",
                "04":"Apr",
                "05":"May",
                "06":"Jun",
                "07":"Jul",
                "08":"Aug",
                "09":"Sep",
                "10":"Oct",
                "11":"Nov",
                "12":"Dec"
            }
            var day_suffix = "th";
            if (data.day == 1) day_suffix = 'st';
            if (data.day == 2) day_suffix = 'nd';

            var result = format.replace('%Y', data.year)
            result = result.replace('%m', months[data.month]);
            result = result.replace('%d', parseInt(data.day) + day_suffix);
            result = result.replace('%H', data.hour);
            result = result.replace('%M', data.minute);
            result = result.replace('%s', data.second);
            return result;
        }
        return ''; /*'<undefined>'*/
    }),
    timedelta: util_logger.fun('timedelta', function(seconds){
		/* transforms seconds count in string of minutes 
		 * and seconds by format MM:SS*/
        if(seconds > 60){
            var remainder = seconds % 60;
            var minutes = (seconds - remainder) / 60;
            var seconds = remainder;
        }
        else{
            var minutes = 0;
        }
        return $.sprintf('%02d:%02d', minutes, seconds);
    }),
    find: util_logger.fun('find', function(arr, obj){
		/* Find object in the array of objects by strict equality.*/
        for (var i = 0, len = arr.length; i < len; ++i){
          if (arr[i] === obj){
            return i;
          }
        }
    }),

    post: util_logger.fun('post', function(params){
		/*Performs POST request by creation temporary form and dstroying
		 * it after finish of the operation*/
        var input = $('<input type="hidden"/>').attr({
            name    : 'data',
            value   : $.serializeJSON(params.data)
        });
        $('<form/>')
            .attr({
                action : params.url,
                method : 'POST'
            })
            .append(input)
            .appendTo('body')
            .submit()
            .remove();
    }),

    inherits: util_logger.fun('inherits', function(name, base, impl){
        var _impl = function(){
            var args = $.map(arguments, function(val){return val});
            args.unshift(this);
            this.__name__ = name;
            this.__type__ = _impl;
            
            if(this.__inherited__){
                base.apply(this, arguments);
            }
            else{
                this.__inherited__ = true;
                base.apply(this, arguments);
                this.__inherited__ = false;
            }
            this.__bases__.push(base.__name__);
            this.__init__ = null;
            
            impl.apply(this, args);
            
            if(this.__init__){
                this.__constructors__.push({fun:this.__init__, name:name});
            }
            
            if(!this.__inherited__){
                $.each(this.__constructors__, function(i, constructor){
                    constructor.fun();
                });
            }
        }
        return _impl;
    }),

    klass: util_logger.fun('klass', function(name, impl){
        var _impl = function(){
            var args = $.map(arguments, function(val){return val});
            args.unshift(this);
            this.__name__ = name;
            this.__type__ = impl;
            this.__bases__ = new Array();
            this.__constructors__ = new Array();
            impl.apply(this, args);
            
            if(this.__init__){
                this.__constructors__.push({fun:this.__init__, name:name});
            }
            
            if(!this.__inherited__){
                $.each(this.__constructors__, function(i, constructor){
                    constructor.fun();
                });
            }
        }
        return _impl;
    }),
      
    safe_append: util_logger.fun('safe_append', function(elem, content, callback){
		/* Asyncronious appending content to the element and calling callback 
		 * if it is provided. */
        setTimeout(function(){
            $(elem).append(content);
            if(callback){
                callback();
            }
        }, 0);
    }),
    call : util_logger.fun('call', function(identifier, callable_name){
        var data = genshi2js.slice(list(arguments), 2);
        var hash = callable_name + identifier;
        util.do_call.mapping[hash] = data;
        var result = 'return util.do_call(this, ' + [callable_name, "'" + hash + "'"].join(',') + ')';
        return result;
    }),
    do_call : util_logger.fun('do_call', function(element, callable, hash){
        var data = util.do_call.mapping[hash];
        return callable.apply(element, data);
    }),
    cond_do:util_logger.fun('cond_do', function(condition, then, otherwise){
        return function(){
            if(condition()){
                return then.apply(this, arguments);
            }
            else if(otherwise){
                return otherwise.apply(this, arguments);
            }
        }
    }),
    logjson:util_logger.fun('logjson', function(value){
        console.log($.serializeJSON(value));
    }),
    render_json_url:util_logger.fun('render_json_url', function(path, params){
        var params = params || {};
        if($.browser.msie){
            params['json'] = 'True';
        }
        if(util.keys(params).length){
            var qs = new Array();
            for(key in params){
                qs.push(key + '=' + params[key]);
            }
            qs = '?' + qs.join('&');
        }
        else{
            var qs = '';
        }
        return path + qs;
    }),
    post_json:util_logger.fun('post_json', function(in_params){
        var params = {
            beforeSend  : function(xhr){
                xhr.setRequestHeader('Content-Type', 'application/x-json');
                xhr.setRequestHeader('Accept', 'application/x-json');
            },
            url         : util.render_json_url(in_params.url, in_params.params),
            type        : 'POST',
            success     : in_params.success ? handler(in_params.success) : undefined,
            error       : in_params.error ? handler(in_params.error) : undefined,
            dataType    : 'json'
        };
        if(in_params.data){
            params['data'] = $.serializeJSON(in_params.data);
        }
        $.ajax(params);
    }),
    post_secure_json:util_logger.fun('post_secure_json', function(in_params){
        in_params.data = in_params.data || {};
        if(in_params.cookie_name){
            var cookie_name = in_params.cookie_name;
        }
        else{
            var cookie_name = application.config('user_cookie');
        }

        in_params.data[cookie_name] = new Cookie(cookie_name).read()
        util.post_json({
            url         : in_params.url,
            success     : function(data){
                if(data.result == false){
                    if(in_params.error){
                        in_params.error(data, data.message);
                    }
                }
                else{
                    if(in_params.success){
                        return in_params.success(data);
                    }
                }
            },
            error       : function(data){
                if(in_params.error){
                    in_params.error(data, data.responseText)
                }
            },
            data        : in_params.data
        })
    }),
    get_json:util_logger.fun('get_json', function(in_params){
        var params = {
            beforeSend  : function(xhr){
                xhr.setRequestHeader('Accept', 'application/x-json');
            },
            url         : util.render_json_url(in_params.url, in_params.params),
            type        : 'GET',
            success     : in_params.success ? handler(in_params.success) : undefined,
            error       : in_params.error ? handler(in_params.error) : undefined,
            dataType    : 'json'
        };
        $.ajax(params);
    })
};

util.do_call.mapping = {};

group_pairs = util_logger.fun('group_pairs', function(entries){
    var result = [];
    var data = {};
    $.each(entries, function(i, entry){
        var key = entry[0]
        var value = entry[1]
        var collection = data[key]
        if(collection){
            collection.push(value);
        }
        else{
            collection = [value];
            data[key] = collection;
            result.push([key, collection]);
        }
    });
    return result;
})

handler = util_logger.fun('handler', function(fun){
	/* Calls function with logging error info if call fails 
	 * and rethrowing the error.
	 * Users Firebug console object for logging
	 */
    var handler_fun = function(){
        try{
            return fun.apply(this, arguments);
        }
        catch(e){
            console.group(e.name + ': ' + e.message);
            console.trace();
            console.groupEnd();
            throw e;
        }
    }
    return handler_fun;
})

util_logger.leave();


function Translator(application, trans)
{
    var logger = logging.ns('translator.Translator');
    var self = this;
    self.data = trans;

    self.get = logger.fun('get', function(name){
        if(self.data[name] != undefined){
            return self.data[name]
        }
        else{
            return 'provide translation for: ' + name
        }
    });
    logger.leave();
}
function RemovePopup(application, button, products){
    var logger = logging.ns('remove_popup.RemovePoup');
    var self = this;

    var popup_container = $('#popup_container');
            
    self.close = logger.fun('close', function(){
        popup_container.slideUp('fast', logger.ns('close.slideUp').fun('end', function(){
            popup_container.empty().css('left',  '-500px').unbind();
            application.basket.active_popup = null;
        }));
    });

    self.remove = logger.fun('remove', function(product_id){
        application.basket.remove_product(product_id);
        self.render();
    });

    self.remove_all = logger.fun('remove_all', function(){
        $.each(products, function(i, product){
            application.basket.remove_product(product.product_id);
        });
        self.render();
    });

    self.add = logger.fun('add', function(product_id){
        application.basket.add_product(product_id);
        self.render();
    });

    self.leave = logger.fun('leave', function(){
        if(self.timeout_handle){
            clearTimeout(self.timeout_handle)
        }
        self.timeout_handle = setTimeout(self.close, 250)
    });

    self.enter = logger.fun('enter', function(){
        if(self.timeout_handle){
            clearTimeout(self.timeout_handle)
        }
    });

    self.render = logger.fun('render', function(){
        popup_container.empty().append(web_shop.remove_popup({
            products    : products,
            trans       : application.trans,
            application : application
        }).serialize());
    });

    self.set_position = logger.fun('set_position', function(){
        var elem_pos = button.offset();
        popup_container.css({
            left:elem_pos.left + button.width() - popup_container.width(),
            top:elem_pos.top + button.height()
        });
    });

    popup_container.bind('hover', self.enter, self.leave);
    button.bind('hover', function(){}, self.leave);
    
    self.render();
    self.set_position();
    popup_container.slideDown('fast');
    logger.leave();
}


Tab = util.klass('BaseTab', function(self, application){
    // this is the definition of the tab interface (with defaults)
    self.sub_navigation = $('#sub_navigation');

    self.handle_click = function(element, type, id, tag_type_id, title){
    };
        
    self.update = function(){
    };

    self.render_actions = function(){
        application.actions.empty();
    };

    self.render_breadcrumb = function(){
        application.breadcrumb.empty();
    };
        
    self.render_widget = function(){
    };

    self.render_sub_navigation = function(){
        self.sub_navigation.empty(); 
    };
});


var basket_logger = logging.ns('basket');

var Basket = util.inherits('Basket', Tab, function(self, application)
{
    var logger = basket_logger.ns('Basket');
    
    self.products = {};
   
    self.__init__ = logger.fun('init', function(){
        application.storage.load('basket_content', function(product_ids){
            if(product_ids && product_ids.length > 0){
                application.data.get_products(product_ids, function(data){
                    $.each(data, function(i, product){
                        application.data.add_product(product);
                    });
                    
                    $.each(product_ids, function(i, id){
                        self.products[id] = id;
                    });

                    application.render_widgets();
                    application.render();
                });
            }
        });
        self.update_data();
    });
    
    self.add_product = logger.fun('add_product', function(product_id){
        self.products[product_id] = product_id;
        application.render();
        self.save();
    });
    
    self.remove_product = logger.fun('remove_product', function(product_id){
        delete self.products[product_id];
        application.render();
        self.save();
    });

    self.remove = logger.fun('remove', function(product_ids){
        if(product_ids.length == 1){
            self.remove_product(product_ids[0].product_id);
        }
        else{
            self.remove_popup(this, product_ids);
        }
    });

    self.remove_popup = logger.fun('remove_popup', function(origin, product_ids){
        if(self.active_popup){
            self.active_popup.close();
            self.active_popup = null;
        }
        else{
            self.active_popup = new RemovePopup(application, origin, product_ids);
        }
    });

    self.has_product = logger.fun('has_product', function(product_id){
        return self.products[product_id] ? true : false;
    });

    self.update_data = logger.fun('update_data', function(){
        var songs = {}
        var ordered_songs = [];
        var total_price = 0.0;

        application.calculator = new application.user.PriceCalculator();
        $.each(self.products, function(i, product_id){
            var product_data = application.data.get_product(product_id);
            
            var song_id = product_data.song_id;
            var price = application.calculator.withdraw(product_data.credit_type, product_data.price);
            product_data.basket_price_display = price.display;

            total_price += price.amount; 
            if(songs[song_id]){
                songs[song_id].products.push(product_data);
                songs[song_id].price += price.amount;
            }
            else{
                song_data = {
                    song_id     : product_data.song_id,
                    title       : product_data.song_title,
                    products    : [product_data],
                    price       : price.amount
                }
                songs[product_data.song_id] = song_data;
                ordered_songs.push(song_data);
            }
        });
        var total = total_price * (1 + application.user.tax_percent())
        self.state = {
            application     : application,
            trans           : application.trans,
            songs           : ordered_songs,
            tax             : application.user.tax_display(),
            price_display   : application.format_price(total_price),
            price           : total_price,
            total           : total,
            total_display   : application.format_price(total)
        }

       
    });

    self.save = function(){
        var product_ids = values(self.products);
        if(product_ids.length > 0){
            application.storage.save('basket_content', product_ids);
        }
        else{
            application.storage.remove('basket_content');
        }
    };
    
    // tab interface
        self.update = logger.fun('update', function(){
            self.update_data();
            self.render_widget();
        });

        self.tab_data = logger.fun('tab_data', function(){
            if(self.state.total > 0){
                return {
                    onclick : 'application.show_basket',
                    title   : application.trans('basket') + ': ' + self.state.total_display
                }
            }
            else{
                return {
                    onclick : 'application.show_basket',
                    title   : application.trans('basket')
                }
            }
        });

        self.render_widget = logger.fun('render_widget', function(){
            $('#basket div.songs').empty().append(web_shop.basket(self.state).serialize());
        });

        self.show = logger.fun('show', function(){
            $('#basket').show();
            $('#basket_btn').addClass('active');
        });

        self.hide = logger.fun('hide', function(){
            $('#basket').hide();
            $('#basket_btn').removeClass('active');
        });

    logger.leave();
});

basket_logger.leave();


var drilldown = {
    Level:util.klass('Level', function(self, element, element_producer, filters, prefix){
        var logger = logging.ns('drilldown.drilldown.Level')
        var vscroll = $('<div/>').addClass('vscroll');
        self.__init__ = logger.fun('__init__', function(){
            self.highlight = new drilldown.Highlight()
            self.level = $('<div>').addClass('level').appendTo(element).append(vscroll);
            element.append(self.level);
            self.element_producer = element_producer;
            self.prefix = prefix;
            self.vscroll = vscroll;
            $.browser.mozilla || self.show_scrollbar(true);
            self.scrollpanel = vscroll.scrollpanel({
                    top_load_offset: 100, 
                    chunk_size : 20,
                    onload_callback : function(target_object, index, limit, onloaded_callback){
                        /* Callback, used for data chunk loading.
                           onloaded_callback is called on target_object at
                           data load finish.
                        Callback prototype:
                            onloaded_callback(next-data-index-to-load, recieved-markup)
                        */
                        self._load(index, limit, self.prefix, function(next_index, markup){
                            onloaded_callback.apply(target_object, [markup]);
                        });
                    }
            });
        });

        self._load = logger.fun('_load', function(index, limit, prefix, onloaded_callback){
            /*Calls element_producer for chunk of data.
                Callback called on data load by element_producer finish.
                Callback prototype:
                    onloaded_callback(next-data-index-to-load, recieved-markup)
            */
            element_producer(index, limit, prefix, function(data, markup){
                if(data.entries){
                    onloaded_callback(index + limit, data.entries.length ? markup : '');
                }
                onloaded_callback(index, '');
            });
        });

        self.show_scrollbar = function(do_show){
            /*(Applyes CSS 'overflow-y: auto' by class assigning.*/
            if(do_show){
                self.vscroll.addClass('vscroll-current');
            }
            else{
                self.vscroll.removeClass('vscroll-current');
            }
        }

        self.drilldown_filters = logger.fun('drilldown_filters', function(){
            return filters;
        });

        self.hide = logger.fun('hide', function(){
            self.level.style.visibility = 'hidden';
        });

        self.show = logger.fun('hide', function(){
            self.level.style.visibility = 'visible';
        });

        self.width = logger.fun('width', function(){
            return $(self.level).width();
        });
        logger.leave();
    }),

    Highlight:util.klass('Highlight', function(self){
        var logger = logging.ns('drilldown.drilldown.Highlight');
        self.highlight = logger.fun('highlight', function(element){
            if(self.last_element){
                self.last_element.css('background-color', self.last_color);
            }
            self.last_color = element.css('background-color');
            self.last_element = element;
            element.css('background-color', 'rgb(161, 161, 161)');
        });
        logger.leave();
    }),

    Drilldown:util.klass('Drilldown', function(self, element, element_producer){
        var logger = logging.ns('drilldown.drilldown.Drilldown');
        self.__init__ = logger.fun('__init__', function(){
            self.current_level = 0;
            self.stack = new Array();
            self.target_position = 0;
            self.top = new drilldown.Level(element, element_producer, {});
            self.width = self.top.width();
        });

        self.run_sliding = logger.fun('run_sliding', function(on_finish){
            element.animate({'left' : self.target_position}, 'normal', on_finish);
        });

        self.slide_right = logger.fun('slide_right', function(){
            $.browser.mozilla && self._show_scroll(false);
            var on_finish = function(){
                $.browser.mozilla && self._show_scroll(true);
            };
            self.target_position -= self.width;
            self.run_sliding(on_finish);
        });

        self.slide_left = logger.fun('slide_left', function(){
            if(self.stack.length > 0){
                var tail = self.stack.pop();
                var on_finish = function(){
                    tail.level.remove();
                };
                self.target_position += self.width;
                self.run_sliding(on_finish);
            }
        });

        self.slide_top = logger.fun('slide_top', function(){
            self.target_position = 0;
            var on_finish = function(){
                while(self.stack.length > 0){
                    self.stack.pop().level.remove();
                }
            };
            self.run_sliding(on_finish);
        });

        self.clear_level = logger.fun('clear_level', function(){
            while(self.stack.length > self.current_level){
                self.stack.pop().level.remove();
            }
        });

        self.slide_level = logger.fun('slide_level', function(level){
            $.browser.mozilla && self._show_scroll(false);
            var on_finish = function(){
                $.browser.mozilla && self._show_scroll(true);
            }
            self.target_position = -level * self.width;
            self.current_level = level;
            self.run_sliding(on_finish);
        });

        self._show_scroll = logger.fun('_show_scroll', function(to_show){
            /* Show/Hides scroll for current level.*/
            self.curr_level().show_scrollbar(to_show);
        });

        self.add_level = logger.fun('add_level', function(level_producer, filters){
            $.browser.mozilla &&  self._show_scroll(false);
            var level = new drilldown.Level(element, level_producer, filters);
            self.stack.push(level);
            self.current_level += 1;
            self.slide_right();
        });
    
        self.replace_level = logger.fun('replace_level', function(level){
            self.clear_level()
            if(self.stack.length > 0){
                self.stack.pop().level.remove();
                self.stack.push(level);
            }
            else{
                self.top.level.remove();
                self.top = level;
            }
        });

        self.curr_level = logger.fun('curr_level', function(){
            if(self.current_level > 0){
                return self.stack[self.current_level - 1];
            }
            else{
                return self.top;
            }
        });

        self.tail_level = logger.fun('tail_level', function(){
            if(self.stack.length > 0){
                return self.stack[self.stack.length-1];
            }
            else{
                return self.top;
            }
        });

        self.tail_filters = logger.fun('tail_filters', function(){
            if(self.stack.length > 0){
                return self.stack[self.stack.length-1].drilldown_filters();
            }
            else{
                return self.top.drilldown_filters();
            }
        });
        logger.leave();
    })
};

var Drilldown = util.inherits('Drilldown', Tab, function(self, application){
    var logger = logging.ns('drilldown.Drilldown');
    self.drilldown_breadcrumbs = [application.trans('start')];
    self.drilldown_breadcrumbs_level = 0;
    self.root = $('#drilldown_root');
    self.element = $('#drilldown');
    self.element_height = self.element.height();
    
    self.__init__ = logger.fun('__init__', function(){
        var data_get = application.data.get_drilldown_category({});
        var toplevel_data_producer = make_data_producer(data_get, function(data){
            self.root_data = data;
            self.render_sub_navigation();
        });
        self.drilldown = new drilldown.Drilldown(self.root, toplevel_data_producer);
    });

    var make_data_producer = logger.fun('make_data_producer', function(data_get, super_callback){
        var drilldown_producer = function(offset, amount, prefix, callback){
            data_get(offset, amount, prefix, function(data){
                if(super_callback){
                    super_callback(data);
                }
                data['application'] = application;
                var markup = customer_widgets.drilldown(data).serialize();
                callback(data, markup);
            });
        };
        return drilldown_producer;
    });

    self.handle_obj_click = function(obj_id){
        // pass base implementation
    }
    
    self.handle_click = logger.fun('handle_click', function(element, type, id, tag_type_id, title){
        if(title){
            title = genshi2js.util.unescape(title);
        }
        var element = $(element);
        if(type == 'obj'){
            self.drilldown.tail_level().highlight.highlight(element.parent());
            self.handle_obj_click(id);
            $('#content')[0].scrollTop = 0;
        }
        else if(type == 'attributes'){
            self.stack_drilldown_breadcrumb(title);
            self.drilldown.clear_level();
            self.drilldown.tail_level().highlight.highlight(element.parent());
            var filters = util.clone(self.drilldown.tail_filters());
            var data_get = application.data.get_drilldown_meta(filters, id);
            var drilldown_producer = make_data_producer(data_get);
            self.drilldown.add_level(drilldown_producer, filters);
        }
        else if(type == 'values'){
            self.stack_drilldown_breadcrumb(title);
            self.drilldown.clear_level();
            self.drilldown.tail_level().highlight.highlight(element.parent());
            var filters = util.clone(self.drilldown.tail_filters());
            filters['type'] = tag_type_id;
            filters[tag_type_id] = id;
            var data_get = application.data.get_drilldown_category(filters);
            var drilldown_producer = make_data_producer(data_get);
            self.drilldown.add_level(drilldown_producer, filters);
        }
        else if(type == 'all'){
            self.stack_drilldown_breadcrumb(application.trans('songs'));
            self.drilldown.clear_level();
            self.drilldown.tail_level().highlight.highlight(element.parent());
            var filters = util.clone(self.drilldown.tail_filters());
            var data_get = application.data.get_drilldown(filters, tag_type_id);
            var drilldown_producer = make_data_producer(data_get);
            self.drilldown.add_level(drilldown_producer, filters);
        } 
        else if (type=='prefix'){
            var filters = util.clone(self.drilldown.curr_level().drilldown_filters());
            var drilldown_producer = self.drilldown.curr_level().element_producer
            var level = new drilldown.Level(self.root, drilldown_producer, filters, id)
            level.show_scrollbar(true);
            self.drilldown_breadcrumbs_level = self.drilldown.current_level;
            self.clear_drilldown_breadcrumbs();
            self.render_drilldown_breadcrumb();
            self.drilldown.replace_level(level);
        }
        self.set_height();
    });
    
    self.render_drilldown_breadcrumb = logger.fun('render_drilldown_breadcrumb', function(active){
        if(self.drilldown_breadcrumbs){
            active = active == null ? self.drilldown_breadcrumbs.length - 1 : active;
            var rendered = customer_widgets.drilldown_breadcrumbs({active:active, titles:self.drilldown_breadcrumbs}).serialize();
            application.breadcrumb.empty().append(rendered);
        }
    });
    
    self.stack_drilldown_breadcrumb = logger.fun('stack_drilldown_breadcrumb', function(title){
        self.clear_drilldown_breadcrumbs();
        if($.browser.msie && $.browser.version < 7){
            if(self.drilldown_breadcrumbs_level < 6){
        self.drilldown_breadcrumbs_level++;
        self.drilldown_breadcrumbs.push(title);
            }
        }
        else{
            self.drilldown_breadcrumbs_level++;
            self.drilldown_breadcrumbs.push(title);
        }
        self.render_drilldown_breadcrumb();
    });

    self.clear_drilldown_breadcrumbs = logger.fun('clear_drilldown_breadcrumbs', function(){
        while(self.drilldown_breadcrumbs.length > self.drilldown_breadcrumbs_level + 1){
            self.drilldown_breadcrumbs.pop(self.drilldown_breadcrumbs.length);
        }
    });

    self.goto_drilldown_breadcrumb = logger.fun('goto_drilldown_breadcrumb', function(level){
        self.drilldown_breadcrumbs_level = level;
        self.render_drilldown_breadcrumb(level);
        self.drilldown.slide_level(level);
    });

    self.drilldown_start = logger.fun('drilldown_start', function(){
        self.drilldown.slide_top();
        self.drilldown_breadcrumbs = [application.trans('start')];
    });
        
    // tab interface
        self.tab_data  = logger.fun('tab_data', function(){
            return {
                onclick : 'application.show_browse',
                title   : application.trans('browse')
            }
        });

        self.render_actions = logger.fun('render_actions', function(){
            application.actions.empty().append(
                web_shop.drilldown_alphabet({application:application}).serialize()
            );
        });

        self.render_widget = function(){
            // pass since the button doesn not change
        };

        self.set_height = logger.fun('set_height', function(){
            var height = self.element_height - application.breadcrumb.height();
            self.element.css('height', height);
        });

        self.render_breadcrumb = logger.fun('render_breadcrumb', function(){
            self.render_drilldown_breadcrumb();
            self.set_height();
        });
        
        self.show = logger.fun('show', function(){
            self.element.show();
            $('#drilldown_btn').addClass('active');
        });

        self.hide = logger.fun('hide', function(){
            self.element.hide();
            $('#drilldown_btn').removeClass('active');
        });
    logger.leave();
});


var shortcut_logger = logging.ns('shortcut');

var shortcut = {
    KEY_ESC     : 27,
    KEY_RETURN  : 13,
    KEY_ONE     : 49,
    KEY_TWO     : 50,
    KEY_THREE   : 51,
    KEY_FOUR    : 52,

    keycode : shortcut_logger.fun('keycode', function(event){
        return event.keyCode || event.charCode;
    })
};

shortcut_logger.leave();
 


Search = util.inherits('Search', Tab, function(self, application){
    var logger = logging.ns('search.Search');
    self.term = '';
    self.name = 'search';
  
    self.do_search = logger.fun('do_search', function(term){
        self.term = term || $('#searchbox')[0].value;
        $('#search').empty();
        var level = new drilldown.Level('search', function(offset, amount, prefix, callback){
            application.data.search(self.term, offset, amount, function(data){
                $.each(data.entries, function(i, entry){
                    entry.type = 'song';
                });
                data['application'] = application;
                callback(data, customer_widgets.drilldown(data).serialize());
            });
        });
    });

    self.handle_click = logger.fun('handle_click', function(element, type, id, tag_type_id, title){
        application.show_song(id);
        $('#content')[0].scrollTop = 0;
    });
    
    // tab interface
        self.tab_data = logger.fun('tab_data', function(){
            return {
                onclick : 'application.show_search',
                title   : application.trans('search')
            }
        });

        self.show = logger.fun('show', function(){
            $('#search').show();
            $('#search_btn').addClass('active');
        });

        self.hide = logger.fun('hide', function(){
            $('#search').hide();
            $('#search_btn').removeClass('active');
        });
    logger.leave();
})


var MyProducts = util.inherits('MyProducts', Tab, function(self, application){
    var logger = logging.ns('myproducts.MyProducts');
    var unfolded = null;
    var unfolded_id = null;
    var blocked = false;
    var manage_account_btn = $('#manage_account_btn');
    
    self.__init__ = logger.fun('init', function(){
        self.hide();
    });

    self.toggle = logger.fun('toggle', function(order_id){
        if(order_id != unfolded_id){
            self.unfold(order_id);
        }
        self.fold();
    });

    self.fold = logger.fun('fold', function(){
        if(unfolded_id){
            var to_fold = unfolded;
            unfolded_id = null;
            unfolded    = null;
            to_fold.slideUp('fast', function(){
                to_fold.remove();
            });
        }
    });

    self.unfold = logger.fun('unfold', function(order_id){
        if(!blocked){
            blocked = true;
            var order_div = $('#order_' + order_id, '#my_products');
            util.post_secure_json({
                url     : application.url.user_order_products(order_id),
                success : logger.ns('unfold').fun('success', function(data){
                    unfolded_id = order_id;
                    $.each(data.data, function(i, product){
                        application.data.add_product(product);
                    });
                    unfolded = $(web_shop.my_orders_products({
                        order_id    : order_id,
                        application : application,
                        trans       : application.trans,
                        data        : data.data
                    }).serialize()).hide().appendTo(order_div).slideDown('fast');
                    blocked = false;
                })
            });
        }
    });

    // tab interface
        
        self.tab_data = logger.fun('tab_data', function(){
            return {
                onclick : 'application.show_myproducts',
                title   : application.trans('my_products')
            };
        });

        self.render_widget = logger.fun('render_widget', function(){
            $('#my_products div.orders').empty().append(web_shop.my_products({
                application     : application,
                trans           : application.trans,
                orders          : application.user.orders()
            }).serialize());
        });

        self.show = logger.fun('show', function(){
            $('#my_products').show();
            $('#my_products_btn').addClass('active');
            
            manage_account_btn.show();
        });

        self.hide = logger.fun('hide', function(){
            $('#my_products').hide();
            $('#my_products_btn').removeClass('active');
            
            manage_account_btn.hide();
        });
    
    logger.leave();
});


cookie_logger = logging.ns('cookie');

Cookie = function(name, params){
    var logger = logging.ns('cookie.Cookie');
    var self = this;
    name = name;

    var _modify = logger.fun('_modify', function(value, params){
        var result = new Array();
        result.push(name + '=' + value);

        if(params){
            if(params.days){
                var date = new Date();
                date.setTime(date.getTime() + (params.days*24*60*60*1000));
                result.push('Expires=' + date.toGMTString());
            }

            if(params.domain){
                result.push("Domain=" + params.domain);
            }

            if(params.path){
                result.push('Path=' + params.path);
            }
            else{
                result.push('Path=/');
            }
        }
        else{
            result.push('Path=/');
        }
        var data = result.join(';');
        document.cookie = data;
    });

    self.write = logger.fun('write', function(value){
        _modify(value, params);
    });

    self.erase = logger.fun('erase', function(){
        _modify('', $.extend({}, {days:-1}, params))
    });

    self.read = logger.fun('read', function(){
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    });

    logger.leave();
}

cookie_logger.leave();


var storage_logger = logging.ns('storage');

var storage  = {
    serialize : function(value){
        return serializeJSON(value);
    },

    deserialize : function(json_str){
        return evalJSON(json_str);
    },

    DOMStorage: function() {
        var logger = storage_logger.ns('storage.DOMStorage');
        var self = this;
        
        self.type = 'DOMStorage';
        
        self.save = logger.fun('save', function(key, value){
            var data = storage.serialize(value); 
            sessionStorage[key] = data;
            if(sessionStorage[key] != data){
                throw new Error();
            }
        });
        
        self.load = logger.fun('load', function(key, callback){
            callback(storage.deserialize(sessionStorage[key]));
        });

        self.remove = logger.fun('remove', function(key){
            delete sessionStorage[key];
        });
        
        logger.leave();
    },

    CookieStorage: function() {
        var logger = storage_logger.ns('storage.CookieStorage');
        var self = this;

        var serialize = function(value){
            try{
                return value.join(',');
            }
            catch (e){
                if(typeof value == 'object'){
                    throw new Error('Cannot make a CSV string from Object or Dictionary!');
                }
                return value + '';
            }
        };
        
        var deserialize = function(csv_string){
            return csv_string.split(',');
        };
       
        self.type = 'CookieStorage';
        
        self.save = logger.fun('save', function(key, value){
            var data = serialize(value);
            var cookie = new Cookie(key);
            if((data.length * 2) < 128){
                cookie.write(data);
                if(!cookie.read()){
                    cookie.erase();
                    throw new Error();
                }
            }
            else{
                if(cookie.read(key)) cookie.erase(); //erase the state saved previously
                throw new Error();
            }
        });
        
        self.load = logger.fun('load', function(key, callback){
            var cookie = new Cookie(key);
            var c = cookie.read(); 
            if(c){
                callback(deserialize(c));
            } else {
                throw new Error();
            }
        });

        self.remove = logger.fun('remove', function(key){
            var cookie = new Cookie(key);
            cookie.erase();
        });
 
        logger.leave();
    },
    
    ServerStorage: function(application) {
        var logger = storage_logger.ns('storage.ServerStorage');
        var self = this;
        var cookie = new Cookie('session_id');
         
        self.type = 'ServerStorage';

        self.save = logger.fun('save', function(key, value){
            util.post_json({
                url     : application.url.save_session_state(),
                success : logger.ns('save.post').fun('success', function(data){
                    if(!cookie.read()){
                        cookie.write(data.session_id);
                    }
                }),
                data    : {'key' : key, 'value' : value}
            });               
        });
        
        self.load = logger.fun('load', function(key, callback){
            if(cookie.read()){
                util.post_json({
                    url     : application.url.session_state(),
                    success : logger.ns('load.post').fun('success', function(data){
                        callback(data[key]); 
                    }),
                    data    : {'key' : key}
                });              
            }
        });

        self.remove = logger.fun('remove', function(key){
            if(cookie.read()){
                util.post_json({
                    url     : application.url.remove_session_state(),
                    success : logger.ns('remove.post').fun('success', function(data){
                        if(data.is_empty){
                            cookie.erase();
                        }
                    }),
                    data    : {'key' : key}
                });              
            }
        });

        logger.leave();
    }
};

function Storage(application){
    var logger = storage_logger.ns('Storage');
    var self = this;

    var dom      = new storage.DOMStorage();
    var cookie   = new storage.CookieStorage();
    var server   = new storage.ServerStorage(application);

    var providers = [dom, cookie, server];
    var curr_provider, prev_provider;

    self.type = 'Storage';

    var set_provider = logger.fun('set_provider', function(provider){
        prev_provider = curr_provider;
        curr_provider = provider;
    });

    var remove_from_all = logger.fun('remove_from_all', function(key){
        $.each(providers, function(i, provider){
            if(provider !== curr_provider){
                try{
                    provider.remove(key);
                } 
                catch(e){}            
            }
        });
    });

    var do_save = logger.fun('do_save', function(provider, key, value){
        provider.save(key, value);
        set_provider(provider);
    });

    self.save = logger.fun('save', function(key, value){
        Try.one(
            function(){do_save(dom, key, value);},
            function(){do_save(cookie, key, value);},
            function(){do_save(server, key, value);}
        );
        
        if(curr_provider !== prev_provider){
            remove_from_all(key);
        }
    });

    self.load = logger.fun('load', function(key, callback){
        return Try.one(
            function(){dom.load(key, callback);},
            function(){cookie.load(key, callback);},
            function(){server.load(key, callback);}
        );
    });

    self.remove = logger.fun('remove', function(key){
        return Try.all(
            function(){dom.remove(key);},
            function(){cookie.remove(key);},
            function(){server.remove(key);}
        );
    });

    logger.leave();
}

storage_logger.leave();


var data_logger = logging.ns('data');

Data = util.klass('Data', function(self, application){
    var logger = data_logger.ns('Data');

    self.__init__ = logger.fun('__init__', function(){
        self.content = null;
        self.content_template = null;
        self.sidebar = new Array();
    });

    self.add_content = logger.fun('add_content', function(data){
        self['add_' + data.__type__](data);
        self.content = data;
        self.content_template = eval(data.__view__);
    });

    self.search = logger.fun('search', function(term, offset, amount, sort_by, success){
        var params = {
            term    : term,
            offset  : offset,
            limit   : amount
        };
/*iurii: temporary turn off
        if(sort_by){
            params.sort_by = sort_by
        }*/
            
        util.get_json({
            url     : application.url.search(),
            params  : params,
            success : success
        });
    });
    
    self.get_drilldown_meta = logger.fun('get_drilldown_meta', function(filters, tag_type_id){
        var do_request = logger.ns('get_drilldown_meta').fun('do_request', function(offset, amount, prefix, success){
            var params = $.extend({offset:offset, limit:amount, attr:tag_type_id}, filters);
        if(prefix) params.prefix = prefix;
            util.get_json({
                url     : application.url.drilldown.valuemap(),
                params  : params,
                success : success
            });
        });
        return do_request;
    });

    self.get_drilldown_category = logger.fun('get_drilldown_category', function(filters){
        var do_request = logger.ns('get_drilldown_category').fun('do_request', function(offset, amount, prefix, success){
            var params = $.extend({offset:offset, limit:amount, lang: application.language}, filters);
        if(prefix) params.prefix=prefix;
            util.get_json({
                url     : application.url.drilldown.attrmap(),
                params  : params,
                success : success
            });
        });
        return do_request;
    });

    self.get_drilldown = logger.fun('get_drilldown', function(filters, tag_type_id){
        var do_request = logger.ns('get_drilldown').fun('do_request', function(offset, amount, prefix, success){
            var params = $.extend({offset:offset, limit:amount}, filters);

            if(prefix){
                params.prefix = prefix;
            }

            if(tag_type_id){
                params.has_attr = tag_type_id;
            }

            util.get_json({
                url     : application.url.drilldown(),
                params  : params,
                success : success
            });
        });
        return do_request;
    });

    logger.leave();
});

data_logger.leave();


Modal = util.klass('Modal', function(self, application, alpha){
    var logger = logging.ns('modal.Modal');
    var active = false;
    var alpha = alpha ? alpha : 0.5;

    self.block = function(){
        // pass base implementation
    }

    self.unblock = function(){
        // pass base implementation
    }
    
    self.__init__ = logger.fun('__init__', function(){
        self.dim_screen = $('#dim_screen');
        self.elem = $('#modal');
        self.elem.fadeOut();
        self.dim_screen.fadeTo(0, 0);
        self.dim_screen.hide();
    });
    
    self.show = logger.fun('show', function(params){
        if(params){
            self.unblock();
            self.set_content(params);
        }
        if(!active){
            $(document).bind('scroll', self.center);
            active = true;
            self.dim_screen
                .height(Math.max(
                    $(document).height(),
                    window.outerHeight || $(window).height()
                ))
                .width($(document).width())
                .show()
                .fadeTo('fast', alpha);
            self.elem.fadeIn('fast');
            self.center();
        }
    });

    self.hide = logger.fun('hide', function(){
        if(active){
            $(document).unbind('scroll');
            self.dim_screen.fadeTo('fast', 0, function(){
                self.dim_screen.hide();
            });
            self.elem.fadeOut('fast', function(){
                active = false;
                self.unblock();
            });
        }
    });

    self.center = logger.fun('center', function(){
        var screen = {w:$(window).width(), h:$(window).height()};
        var elemd = {w:self.elem.width(), h:self.elem.height()};
        var top = ((screen.h - elemd.h) / 2) + util.window_scroll().top;
        var left = (screen.w - elemd.w) / 2;
        self.elem.css({top:top, left:left});
    });

    logger.leave();
});


URL = util.klass('URL', function(self, application, language){
    self.complete = function(url, params){
        if(util.keys(params).length){
            var qs = new Array();
            for(key in params){
                if(!(params[key] === undefined)){
                    qs.push(key + '=' + params[key]);
                }
            }
            return url + '?' + qs.join('&');
        }
        else{
            return url;
        }
    };

    self.session_state = function(params){
        return self.complete(base_path + '/json/session_state/', params);
    };

    self.save_session_state = function(params){
        return self.complete(self.session_state() + 'save', params);
    };

    self.customer_css = function(params){
        return base_path + '/customer/css/' + params.css_name;
    }
 
    self.remove_session_state = function(params){
        return self.complete(self.session_state() + 'remove', params);
    };

    self.products = function(params){
         return self.complete(base_path + '/lang/' + language + '/products', params);
    };
   
    self.search = function(){
        return base_path + '/search';
    };
    
    this.user_data = function(){
        return base_path + '/user_data';
    }

    this.download_product = function(order_id, product_id, params){
        return self.complete(base_path + '/order/' + order_id + '/product/' + product_id + '/download.sdcxml', params);
    }

    this.download_order = function(order_id, params){
        return self.complete(base_path + '/order/' + order_id + '/download.sdcxml', params);
    }

    this.authenticate = function(params){
        return self.complete(base_path + '/authenticate', params);
    }

    this.create_licenses = function(order_id){
        return base_path + '/order/' + order_id + '/create_licenses';
    }

    this.create_license = function(order_id, product_id){
        return base_path + '/order/' + order_id + '/product/' + product_id +'/create_license';
    }

   this.purchase = function(params){
        return self.complete(base_path + '/json/purchase', params);
    }

    this.language =function(params){
        return self.complete(base_path + '/lang/' + language + '/json/language', params);
    }

    this.icons = function(){
        return base_path + '/icons'
    }

    this.drilldown = function(params){
        return base_path + '/tags/obj';
    }

    this.drilldown.attrmap = function(params){
        return base_path + '/tags/attr';
    }

    this.drilldown.valuemap =function(params){
        return base_path + '/tags/value';
    }

    this.image = function(name){
        return base_path + '/images/' + name;
    }

    this.customer_image = function(name){
        return base_path + '/customer/images/' + name;
    }

    this.swf = function(name){
        return base_path + '/swf/' + name;
    }

    this.product = function(product_id){
        return base_path + '/product/';
    }

    this.preview = function(product_id){
        return self.product() + product_id + '/preview.sdcxml';
    }

    this.fragment = function(file_name, section_name, params){
        if(section_name){
            fname = file_name + '/' + section_name;
        }else{
            fname = file_name;
        }
        return self.complete(base_path + '/lang/' + language + '/fragment/file/' + fname, params);
    }

    this.static = function(file_name, params){
        return self.complete(base_path + '/lang/' + language + '/static/' + file_name, params);
    }

    this.user_order_products = function(order_id){
        return base_path + '/lang/' + language + '/order/' + order_id + '/products';
    }
});


(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);
	};

});})();

// Copyright (c) 2005-2006 Paul Colton - Please see http://www.aflax.org

function AFLAX(path,trace,enableFlashSettings,localStoreReadyCallback)
{if(path!=null)AFLAX.path=path;if(trace!=null)AFLAX.tracing=trace;if(localStoreReadyCallback==undefined||localStoreReadyCallback==null)localStoreReadyCallback="";this.id="aflax_obj_"+AFLAX.count++;if(enableFlashSettings!=undefined||enableFlashSettings==true)
{if(document.getElementById("flashSettings")==null&&arguments.length>0)
{var flashSettingsStyle="width: 215px; height: 138px; position: absolute; z-index: 100;left: -500px; top: -500px";document.write('<div id="flashSettings" style="'+flashSettingsStyle+'"\>Flash Settings Dialog</div\>\n');AFLAX.settings=new AFLAX();AFLAX.settings.addFlashToElement("flashSettings",215,138,"#FFFFFF",localStoreReadyCallback,true);}}}
AFLAX.version="0.41";AFLAX.tracing=false;AFLAX.count=0;AFLAX.path="aflax.swf";AFLAX.settings=null;AFLAX.prototype.id=null;AFLAX.prototype.flash=null;AFLAX.prototype.root=null;AFLAX.prototype.stage=null;AFLAX.prototype.getHTML=function(width,height,bgcolor,callback,transparent,absolutePosition)
{var requiredVersion=new com.deconcept.PlayerVersion([8,0,0]);var installedVersion=com.deconcept.FlashObjectUtil.getPlayerVersion();if(installedVersion.versionIsValid(requiredVersion)==false)
{return"<div style='border:2px solid #FF0000'>To see this contents you need to install <a target='_blank' href='http://www.macromedia.com/go/getflashplayer'>Flash Player</a> version 8.0 or higher.</div>";}
bgcolor=bgcolor||"#FFFFFF";callback=callback||"_none_";var content='\
<object width="'+width+'" height="'+height+'" id="'+this.id+'" type="application/x-shockwave-flash" data="'+AFLAX.path+'?callback='+callback+'"';if(absolutePosition)
content+='style="position: absolute"';content+='>\
<param name="allowScriptAccess" value="sameDomain" />\
<param name="bgcolor" value="'+bgcolor+'" />\
<param name="movie" value="'+AFLAX.path+'?callback='+callback+'" />\
<param name="scale" value="noscale" />\
<param name="salign" value="lt" />\
';if(transparent)
content+='<param name="wmode" value="transparent" />';content+='</object>';if(AFLAX.tracing)
content+='<div style="border:1px solid #ddd;padding: 4px;background-color: #fafafa;font-size: 8pt;" id="aflaxlogger"></div>';return content;}
AFLAX.prototype.addFlashToElement=function(parentElementOrId,width,height,bgcolor,callback,transparent)
{var parentNode=typeof parentElementOrId=="string"?document.getElementById(parentElementOrId):parentElementOrId;var content=this.getHTML(width,height,bgcolor,callback,transparent);var container=document.createElement("div");container.innerHTML=content;var element=container.removeChild(container.firstChild);while(parentNode.firstChild)
parentNode.removeChild(parentNode.firstChild);parentNode.appendChild(element);return element;}
AFLAX.prototype.insertFlash=function(width,height,bgcolor,callback,transparent,absolutePosition)
{var content=this.getHTML(width,height,bgcolor,callback,transparent,absolutePosition);document.write(content);if(AFLAX.tracing)
AFLAX.trace("AFLAX Logger initialized.");return document.getElementById(this.id);}
AFLAX.prototype.getRoot=function()
{if(this.root==null)
{this.root=new AFLAX.MovieClip(this,null,"_root");}
return this.root;}
AFLAX.prototype.getStage=function()
{if(this.stage==null)
{this.stage=new AFLAX.MovieClip(this,null,"_stage");this.stage.exposeProperty("width",this.stage);this.stage.exposeProperty("height",this.stage);this.stage.exposeProperty("scaleMode",this.stage);this.stage.exposeProperty("showMenu",this.stage);this.stage.exposeProperty("align",this.stage);}
return this.stage;}
AFLAX.prototype.getFlash=function()
{if(this.flash==null)
{this.flash=document[this.id];}
return this.flash;}
AFLAX.returnsHash={"true":true,"false":false,"undefined":undefined,"null":null,"NaN":NaN};AFLAX.prototype.callFunction=function(name)
{var ret=this.getFlash().CallFunction("<invoke name=\""+
name+"\" returntype=\"javascript\">"+
__flash__argumentsToXML(arguments,1)+"</invoke>");if(AFLAX.returnsHash.hasOwnProperty(ret))
{ret=AFLAX.returnsHash[ret];}
else if(ret.charAt(0)=='"')
{if(ret.charAt(ret.length-1)=='"')
ret=ret.substring(1,ret.length-1);}
else
{ret=ret-0;}
return ret;}
AFLAX.prototype.storeValue=function(key,value,statusCallback,serialize)
{if(serialize==true)
value="[JSON]"+JSON.stringify(value);if(statusCallback==undefined||statusCallback==null)
return this.callFunction("aflaxStoreValue",[key,value]);else
return this.callFunction("aflaxStoreValue",[key,value,statusCallback]);}
AFLAX.prototype.getStoredValue=function(key)
{var value=this.callFunction("aflaxGetValue",[key]);value=value.split('\\"').join('"');value=value.split("\\'").join("'");alert(value);if(value.substring(0,6)=="[JSON]")
return JSON.parse(value.substring(6));else
return value;}
AFLAX.hideFlashSettings=function()
{var flashDiv=document.getElementById("flashSettings");flashDiv.style.left=-500+"px";flashDiv.style.top=-500+"px";}
AFLAX.showFlashSettings=function(x,y,mode)
{if(x==undefined)x=100;if(y==undefined)y=100;if(mode==undefined)mode=1;var flashDiv=document.getElementById("flashSettings");flashDiv.style.left=x+"px";flashDiv.style.top=y+"px";AFLAX.settings.callStaticFunction("System","showSettings",mode);}
AFLAX.prototype.callStaticFunction=function(objectName,func)
{var args=new Array();args[0]=objectName;args[1]=func;for(var i=2;i<arguments.length;i++)
{args[i]=arguments[i];}
return this.callFunction("aflaxCallStaticFunction",args);}
AFLAX.prototype.getStaticProperty=function(objectName,property)
{return this.callFunction("aflaxGetStaticProperty",[objectName,property]);}
AFLAX.prototype.attachEventListener=function(obj,event,handler)
{var id=obj;if(obj.id!=undefined)
id=obj.id;this.callFunction("aflaxAttachEventListener",[id,event,handler]);}
AFLAX.prototype.callBulkFunctions=function(funcs)
{var s=new Array(funcs.length);for(var i=0,j=funcs.length;i<j;i++)
{var func=funcs[i];s[i]=func.join("\1");}
var commands=s.join("\2");this.callFunction("aflaxBulkCallFunction",commands);}
AFLAX.prototype.updateAfterEvent=function()
{this.callFunction("aflaxUpdateAfterEvent");}
AFLAX.prototype.createFlashArray=function(elements)
{var _array=new AFLAX.FlashObject(this,"Array")
_array.exposeFunction("push",_array);_array.exposeFunction("reverse",_array);_array.exposeProperty("length",_array);var len=elements.length;for(var i=0;i<len;i++)
_array.push(elements[i]);return _array;}
AFLAX.extend=function(baseClass,newClass)
{var pseudo=function(){};pseudo.prototype=baseClass.prototype;newClass.prototype=new pseudo();newClass.prototype.baseConstructor=baseClass;newClass.prototype.superClass=baseClass.prototype;newClass.prototype._prototype=newClass.prototype;if(baseClass.prototype.superClass==undefined){baseClass.prototype.superClass=Object.prototype;}
return newClass;}
AFLAX.extractArgs=function(args,startIndex)
{var newArgs=new Array();for(var i=startIndex;i<args.length;i++)
{newArgs[i-startIndex]=args[i];}
return newArgs;}
AFLAX.FlashObject=function(aflaxRef,flashObjectName,objectArgs,objectID)
{if(arguments.length==0)return;this.aflax=aflaxRef;this.flash=this.aflax.getFlash();this._prototype=AFLAX.FlashObject.prototype;if(objectArgs==null||objectArgs==undefined)
objectArgs=new Array();if(flashObjectName!=null&&flashObjectName!=undefined)
{var args=new Array();args[0]=flashObjectName;for(i=0;i<objectArgs.length;i++)
{var a=objectArgs[i];if(a.id!=undefined)
{a="ref:"+a.id;}
args[i+1]=a;}
this.id=this.aflax.callFunction("aflaxCreateObject",args);}
else
{if(objectID!=null&&objectID!=undefined)
{this.id=objectID;}}
if(this.bound==false)
{}}
AFLAX.FlashObject.prototype.bound=false;AFLAX.FlashObject.prototype.id=null;AFLAX.FlashObject.prototype._prototype=null;AFLAX.FlashObject.prototype.aflax=null;AFLAX.FlashObject.prototype.flash=null;AFLAX.FlashObject.prototype.callFunction=function(functionName)
{var args=new Array();args[0]=this.id;args[1]=functionName;for(i=1;i<arguments.length;i++)
{var val=arguments[i];if(val==null)
{val="null";}
if(typeof(val)=="string")
{if(val.substring(0,4)=="ref:")
{var varPart=val.substring(4);var restPart=null;if(varPart.indexOf(".")!=-1)
{restPart=varPart.substring(varPart.indexOf("."));varPart=varPart.substring(0,varPart.indexOf("."));}
val="ref:"+eval(varPart).id;if(restPart!=null)
val+=restPart;}}
if(val.id!=undefined)
{val="ref:"+val.id;}
args[i+1]=val;}
var retval=this.aflax.callFunction("aflaxCallFunction",args);return retval;}
AFLAX.FlashObject.prototype.bind=function(properties,functions,mappings)
{if(properties!=null&&properties!=undefined)
{for(var pn=0;pn<properties.length;pn++)
{this.exposeProperty(properties[pn]);}}
if(functions!=null&&functions!=undefined)
{for(var fn=0;fn<functions.length;fn++)
{this.exposeFunction(functions[fn]);}}
if(mappings!=null&&mappings!=undefined)
{for(var mn=0;mn<mappings.length;mn++)
{this.mapFunction(mappings[mn]);}}}
AFLAX.FlashObject.prototype.exposeProperty=function(propertyName,targetPrototype)
{var methodSuffix=propertyName.substring(0,1).toUpperCase()+propertyName.substring(1);var target=this._prototype;if(targetPrototype!=null)
target=targetPrototype;target["get"+methodSuffix]=function()
{var r=this.aflax.callFunction("aflaxGetProperty",[this.id,propertyName]);if(r==null)return null;if(r==undefined)return;if(typeof(r)=="string")
return r.split("\\r").join("\r").split("\\n").join("\n");else
return r;}
target["set"+methodSuffix]=function(val)
{this.aflax.callFunction("aflaxSetProperty",[this.id,propertyName,val]);}}
AFLAX.FlashObject.prototype.exposeFunction=function(functionName,targetPrototype)
{var target=this._prototype;if(targetPrototype!=null)
target=targetPrototype;target[functionName]=function()
{var args=new Array();args[0]=this.id;args[1]=functionName;for(var i=0;i<arguments.length;i++)
args[i+2]=arguments[i];return this.aflax.callFunction("aflaxCallFunction",args);}}
AFLAX.FlashObject.prototype.mapFunction=function(functionName,targetPrototype)
{var target=this._prototype;if(targetPrototype!=null)
target=targetPrototype;target[functionName]=function()
{var args=new Array();args[0]=this.id;for(var i=0;i<arguments.length;i++)
{var a=arguments[i];if(a.id!=undefined)a=a.id;args[i+1]=a;}
var fName="aflax"+functionName.substring(0,1).toUpperCase()+functionName.substring(1);return this.aflax.callFunction(fName,args);}}
AFLAX.MovieClip=function(aflaxRef,parentClipID,clipID)
{if(arguments.length==0)return;arguments.callee.prototype.baseConstructor.call(this,aflaxRef,null,null,clipID);if(clipID==undefined||clipID==null)
{if(parentClipID!=undefined&&parentClipID!=null&&this.flash.aflaxCreateEmptyMovieClip!=undefined&&this.flash.aflaxCreateEmptyMovieClip!=null)
this.id=this.aflax.callFunction("aflaxCreateEmptyMovieClip",[parentClipID]);else
this.id=this.aflax.callFunction("aflaxCreateEmptyMovieClip",["_root"]);}
if(AFLAX.MovieClip.bound==false)
{this.bind(AFLAX.MovieClip.movieClipProperties,AFLAX.MovieClip.movieClipFunctions,AFLAX.MovieClip.movieClipMappings);AFLAX.MovieClip.bound=true;}}
AFLAX.extend(AFLAX.FlashObject,AFLAX.MovieClip);AFLAX.MovieClip.prototype.drawCircle=function(x,y,radius)
{var r=radius;var degToRad=Math.PI/180;var n=8;var theta=45*degToRad;var cr=radius/Math.cos(theta/2);var angle=0;var cangle=angle-theta/2;var commands=new Array(n+1);var commandIndex=0;commands[commandIndex++]=[this.id,"moveTo",x+r,y];for(var i=0;i<n;i++)
{angle+=theta;cangle+=theta;var endX=r*Math.cos(angle);var endY=r*Math.sin(angle);var cX=cr*Math.cos(cangle);var cY=cr*Math.sin(cangle);commands[commandIndex++]=[this.id,"curveTo",x+cX,y+cY,x+endX,y+endY];}
this.aflax.callBulkFunctions(commands);}
AFLAX.MovieClip.bound=false;AFLAX.MovieClip.movieClipProperties=["_x","_y","_height","_width","_rotation","_xmouse","_ymouse","_xscale","_yscale","_alpha","blendMode","_visible","cacheAsBitmap"];AFLAX.MovieClip.movieClipFunctions=["moveTo","lineTo","curveTo","lineStyle","beginFill","endFill","clear","getURL","removeMovieClip"];AFLAX.MovieClip.movieClipMappings=["attachVideo","createTextField","addEventHandler","attachBitmap","applyFilter","loadMovie"];AFLAX.MovieClip.prototype.clone=function()
{var newClip=this.aflax.callFunction("aflaxDuplicateMovieClip",[this.id]);var mc=new AFLAX.MovieClip(this.aflax,null,newClip);return mc;}
AFLAX.CameraClip=function(aflaxRef,parentClipID)
{if(arguments.length==0)return;arguments.callee.prototype.baseConstructor.call(this,aflaxRef,parentClipID,null);if(parentClipID==undefined||parentClipID==null)
{parentClipID="_root";}
this.id=this.aflax.callFunction("aflaxCreateVideoClip",[parentClipID]);var cam=this.aflax.callFunction("aflaxGetCamera");this.attachVideo(cam);}
AFLAX.CameraClip.GetCameras=function(aflaxRef)
{return aflaxRef.getFlash().aflaxGetStaticProperty(["Camera","names"]);}
AFLAX.extend(AFLAX.MovieClip,AFLAX.CameraClip);AFLAX.VideoClip=function(aflaxRef,parentClipID,url,cueCallback,loadCallback)
{if(arguments.length==0)return;arguments.callee.prototype.baseConstructor.call(this,aflaxRef,parentClipID,null);if(parentClipID==undefined||parentClipID==null)
{parentClipID="_root";}
this.id=this.aflax.callFunction("aflaxCreateVideoClip",[parentClipID]);var nc=new AFLAX.FlashObject(this.aflax,"NetConnection");nc.callFunction("connect",null);var ns=new AFLAX.FlashObject(this.aflax,"NetStream",[nc]);ns.exposeProperty("time",ns);this.netStream=ns;this.attachVideo(ns);if(loadCallback!=null&&loadCallback!=undefined)
this.aflax.flash.aflaxAttachVideoStatusEvent([ns.id,loadCallback]);if(cueCallback!=null&&cueCallback!=undefined)
this.aflax.flash.aflaxAttachCuePointEvent([ns.id,cueCallback]);ns.callFunction("setBufferTime",0);ns.callFunction("play",url);}
AFLAX.extend(AFLAX.MovieClip,AFLAX.VideoClip);AFLAX.VideoClip.prototype.netStream=null;AFLAX.VideoClip.GetStatusValue=function(statusString,valueName)
{var s=statusString;var args=s.split(";");var params=new Array();for(var i=0;i<args.length;i++)
{var n=args[i].split("=");if(n[0]!="")
{params[n[0]]=n[1];}}
return params[valueName];}
AFLAX.VideoClip.NetStream_Buffer_Empty="NetStream.Buffer.Empty";AFLAX.VideoClip.NetStream_Buffer_Full="NetStream.Buffer.Full";AFLAX.VideoClip.NetStream_Buffer_Flush="NetStream.Buffer.Flush";AFLAX.VideoClip.NetStream_Play_Start="NetStream.Play.Start";AFLAX.VideoClip.NetStream_Play_Stop="NetStream.Play.Stop";AFLAX.VideoClip.NetStream_Play_StreamNotFound="NetStream.Play.StreamNotFound";AFLAX.VideoClip.NetStream_Seek_InvalidTime="NetStream.Seek.InvalidTime";AFLAX.VideoClip.NetStream_Seek_Notify="NetStream.Seek.Notify";AFLAX.TextField=function(aflaxRef,clipID)
{if(arguments.length==0)return;arguments.callee.prototype.baseConstructor.call(this,aflaxRef,null,clipID);if(AFLAX.TextField.bound==false)
{this.bind(AFLAX.TextField.textFieldProperties,AFLAX.TextField.textFieldFunctions);AFLAX.TextField.bound=true;}}
AFLAX.extend(AFLAX.MovieClip,AFLAX.TextField);AFLAX.TextField.bound=false;AFLAX.TextField.textFieldProperties=["type","multiline","wordWrap","text","htmlText","embedFonts"];AFLAX.TextField.textFieldFunctions=["setTextFormat"];if(AFLAX.tracing==true)
{window.onerror=AFLAX.windowError;}
AFLAX.windowError=function(message,url,line){AFLAX.trace('Error on line '+line+' of document '+url+': '+message);return true;}
AFLAX.trace=function(message)
{if(AFLAX.tracing==true)
{var div=document.getElementById("aflaxlogger");if(div!=null)
{var p=document.createElement('p');p.style.margin=0;p.style.padding=0;p.style.textAlign="left";var text=document.createTextNode(message);p.appendChild(text);div.appendChild(p);}}}
AFLAX.Socket=function(aflax,host,port,onConnectEvent,onDataEvent,onCloseEvent)
{var flash=aflax.getFlash();var connection=new AFLAX.FlashObject(aflax,"XMLSocket");flash.aflaxAttachSocketEvents([connection.id,onConnectEvent,onDataEvent,onCloseEvent]);connection.exposeFunction("connect",connection);connection.exposeFunction("close",connection);connection.exposeFunction("send",connection);connection.connect(host,port);return connection;}
if(typeof com=="undefined")
{var com;com=new Object();}
if(typeof com.deconcept=="undefined")com.deconcept=new Object();if(typeof com.deconcept.util=="undefined")com.deconcept.util=new Object();if(typeof com.deconcept.FlashObjectUtil=="undefined")com.deconcept.FlashObjectUtil=new Object();com.deconcept.FlashObjectUtil.getPlayerVersion=function(){var PlayerVersion=new com.deconcept.PlayerVersion(0,0,0);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){PlayerVersion=new com.deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else if(window.ActiveXObject){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");PlayerVersion=new com.deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}catch(e){}}
return PlayerVersion;}
com.deconcept.PlayerVersion=function(arrVersion){this.major=parseInt(arrVersion[0])||0;this.minor=parseInt(arrVersion[1])||0;this.rev=parseInt(arrVersion[2])||0;}
com.deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major)return false;if(this.major>fv.major)return true;if(this.minor<fv.minor)return false;if(this.minor>fv.minor)return true;if(this.rev<fv.rev)return false;return true;}
Array.prototype.______array='______array';var JSON={org:'http://www.JSON.org',copyright:'(c)2005 JSON.org',license:'http://www.crockford.com/JSON/license.html',stringify:function(arg){var c,i,l,s='',v;switch(typeof arg){case'object':if(arg){if(arg.______array=='______array'){for(i=0;i<arg.length;++i){v=this.stringify(arg[i]);if(s){s+=',';}
s+=v;}
return'['+s+']';}else if(typeof arg.toString!='undefined'){for(i in arg){v=arg[i];if(typeof v!='undefined'&&typeof v!='function'){v=this.stringify(v);if(s){s+=',';}
s+=this.stringify(i)+':'+v;}}
return'{'+s+'}';}}
return'null';case'number':return isFinite(arg)?String(arg):'null';case'string':l=arg.length;s='"';for(i=0;i<l;i+=1){c=arg.charAt(i);if(c>=' '){if(c=='\\'||c=='"'){s+='\\';}
s+=c;}else{switch(c){case'\b':s+='\\b';break;case'\f':s+='\\f';break;case'\n':s+='\\n';break;case'\r':s+='\\r';break;case'\t':s+='\\t';break;default:c=c.charCodeAt();s+='\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);}}}
return s+'"';case'boolean':return String(arg);default:return'null';}},parse:function(text){var at=0;var ch=' ';function error(m){throw{name:'JSONError',message:m,at:at-1,text:text};}
function next(){ch=text.charAt(at);at+=1;return ch;}
function white(){while(ch!=''&&ch<=' '){next();}}
function str(){var i,s='',t,u;if(ch=='"'){outer:while(next()){if(ch=='"'){next();return s;}else if(ch=='\\'){switch(next()){case'b':s+='\b';break;case'f':s+='\f';break;case'n':s+='\n';break;case'r':s+='\r';break;case't':s+='\t';break;case'u':u=0;for(i=0;i<4;i+=1){t=parseInt(next(),16);if(!isFinite(t)){break outer;}
u=u*16+t;}
s+=String.fromCharCode(u);break;default:s+=ch;}}else{s+=ch;}}}
error("Bad string");}
function arr(){var a=[];if(ch=='['){next();white();if(ch==']'){next();return a;}
while(ch){a.push(val());white();if(ch==']'){next();return a;}else if(ch!=','){break;}
next();white();}}
error("Bad array");}
function obj(){var k,o={};if(ch=='{'){next();white();if(ch=='}'){next();return o;}
while(ch){k=str();white();if(ch!=':'){break;}
next();o[k]=val();white();if(ch=='}'){next();return o;}else if(ch!=','){break;}
next();white();}}
error("Bad object");}
function num(){var n='',v;if(ch=='-'){n='-';next();}
while(ch>='0'&&ch<='9'){n+=ch;next();}
if(ch=='.'){n+='.';while(next()&&ch>='0'&&ch<='9'){n+=ch;}}
if(ch=='e'||ch=='E'){n+='e';next();if(ch=='-'||ch=='+'){n+=ch;next();}
while(ch>='0'&&ch<='9'){n+=ch;next();}}
v=+n;if(!isFinite(v)){error("Bad number");}else{return v;}}
function word(){switch(ch){case't':if(next()=='r'&&next()=='u'&&next()=='e'){next();return true;}
break;case'f':if(next()=='a'&&next()=='l'&&next()=='s'&&next()=='e'){next();return false;}
break;case'n':if(next()=='u'&&next()=='l'&&next()=='l'){next();return null;}
break;}
error("Syntax error");}
function val(){white();switch(ch){case'{':return obj();case'[':return arr();case'"':return str();case'-':return num();default:return ch>='0'&&ch<='9'?num():word();}}
return val();}};/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();/*##############################################################################
#    ____________________________________________________________________
#   /                                                                    \
#  |               ____  __      ___          _____  /     ___    ___     |
#  |     ____       /  \/  \  ' /   \      / /      /__   /   \  /   \    |
#  |    / _  \     /   /   / / /    /  ___/  \__   /     /____/ /    /    |
#  |   / |_  /    /   /   / / /    / /   /      \ /     /      /____/     |
#  |   \____/    /   /    \/_/    /  \__/  _____/ \__/  \___/ /           |
#  |                                                         /            |
#  |                                                                      |
#  |   Copyright (c) 2007                             MindStep SCOP SARL  |
#  |   Herve Masson                                                       |
#  |                                                                      |
#  |      www.mindstep.com                              www.mjslib.com    |
#  |   info-oss@mindstep.com                           mjslib@mjslib.com  |
#   \____________________________________________________________________/
#
#  Version: 1.0.0
#
#  (Svn version: $Id: jquery.printf.js 3434 2007-08-27 09:31:20Z herve $)
#
#----------[This product is distributed under a BSD license]-----------------
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in
#        the documentation and/or other materials provided with the
#        distribution.
#
#  THIS SOFTWARE IS PROVIDED BY THE MINDSTEP CORP PROJECT ``AS IS'' AND
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MINDSTEP CORP OR CONTRIBUTORS
#  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
#  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
#  OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
#  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
#  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
#  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#  The views and conclusions contained in the software and documentation
#  are those of the authors and should not be interpreted as representing
#  official policies, either expressed or implied, of MindStep Corp.
#
################################################################################
#
#	This is a jQuery [jquery.com] plugin that implements printf' like functions
#	(Examples and documentation at: http://mjslib.com)
#
#	@author: Herve Masson
#	@version: 1.0.0 (8/27/2007)
#	@requires jQuery v1.1.2 or later
#	
#	(Based on the legacy mjslib.org framework)
#
##############################################################################*/

(function($) {

	/*
	**	Just an equivalent of the corresponding libc function
	**
	**	var str=jQuery.sprintf("%010d %-10s",intvalue,strvalue);
	**
	*/

	$.sprintf=function(fmt)
	{
		return _sprintf_(fmt,arguments,1);
	}


	/*
	**	vsprintf takes an argument list instead of a list of arguments (duh!)
	**	(useful when forwarding parameters from one of your functions to a printf call)
	**
	**	str=jQuery.vsprintf(parameters[,offset]);
	**
	**		The 'offset' value, when present, instructs vprintf to start at the
	**		corresponding index in the parameter list instead, of 0
	**
	**	Example 1:
	**
	**		function myprintf(<printf like arguments>)
	**		{
	**			var str=jQuery.vsprintf(arguments);
	**			..
	**		}
	**		myprintf("illegal value : %s",somevalue);
	**
	**
	**	Example 2:
	**
	**		function logit(level,<the rest is printf like arguments>)
	**		{
	**			var str=jQuery.vsprintf(arguments,1);	// Skip prm #1
	**			..
	**		}
	**		logit("error","illegal value : %s",somevalue);
	**
	*/

	$.vsprintf=function(args,offset)
	{
		if(offset === undefined)
		{
			offset=0;
		}
		return _sprintf_(args[offset],args,offset+1);
	}


	/*
	**	logging using formatted messages
	**	================================
	**
	**	If you _hate_ debugging with alert() as much as I do, you might find the
	**	following routines valuable.
	**
	**	jQuery.alertf("The variable 'str' contains: '%s'",str);
	**		Show an alert message with a printf-like argument.
	**
	**	jQuery.logf("This is a log message, time is: %d",(new Date()).getTime());
	**		Log the message on the console with the info level
	**
	**	jQuery.errorf("The given value (%d) is erroneous",avalue);
	**		Log the message on the console with the error level
	**
	*/

	$.alertf=function()
	{
		return alert($.vsprintf(arguments));
	}

	$.vlogf=function(args)
	{
		if("console" in window)
		{
			console.info($.vsprintf(args));
		}
	}

	$.verrorf=function(args)
	{
		if("console" in window)
		{
			console.error($.vsprintf(args));
		}
	}

	$.errorf=function()
	{
		$.verrorf(arguments);
	}

	$.logf=function()
	{
		$.vlogf(arguments);
	}


	/*-------------------------------------------------------------------------------------------
	**
	**	Following code is private; don't use it directly !
	**
	**-----------------------------------------------------------------------------------------*/

	FREGEXP	= /^([^%]*)%([-+])?(0)?(\d+)?(\.(\d+))?([doxXcsf])(.*)$/;
	HDIGITS	= ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];

	function _empty(str)
	{
		if(str===undefined || str===null)
		{
			return true;
		}
		return (str == "") ? true : false;
	}

	function _int_(val)
	{
		return Math.floor(val);
	}

	function _printf_num_(val,base,pad,sign,width)
	{
		val=parseInt(val,10);
		if(isNaN(val))
		{
			return "NaN";
		}
		aval=(val<0)?-val:val;
		var ret="";

		if(aval==0)
		{
			ret="0";
		}
		else
		{
			while(aval>0)
			{
				ret=HDIGITS[aval%base]+ret;
				aval=_int_(aval/base);
			}
		}
		if(val<0)
		{
			ret="-"+ret;
		}
		if(sign=="-")
		{
			pad=" ";
		}
		return _printf_str_(ret,pad,sign,width,-1);
	}

	function _printf_float_(val,base,pad,sign,prec)
	{
		if(prec==undefined)
		{
			if(parseInt(val) != val)
			{
				// No decimal part and no precision -> use int formatting
				return ""+val;
			}
			prec=5;
		}

		var p10=Math.pow(10,prec);
		var ival=""+Math.round(val*p10);
		var ilen=ival.length-prec;
		if(ilen==0)
		{
			return "0."+ival.substr(ilen,prec);
		}
		return ival.substr(0,ilen)+"."+ival.substr(ilen,prec);
	}

	function _printf_str_(val,pad,sign,width,prec)
	{
		var npad;

		if(val === undefined)
		{
			return "(undefined)";
		}
		if(val === null)
		{
			return "(null)";
		}
		if((npad=width-val.length)>0)
		{
			if(sign=="-")
			{
				while(npad>0)
				{
					val+=pad;
					npad--;
				}
			}
			else
			{
				while(npad>0)
				{
					val=pad+val;
					npad--;
				}
			}
		}
		if(prec>0)
		{
			return val.substr(0,prec);
		}
		return val;
	}

	function _sprintf_(fmt,av,index)
	{
		var output="";
		var i,m,line,match;

		line=fmt.split("\n");
		for(i=0;i<line.length;i++)
		{
			if(i>0)
			{
				output+="\n";
			}
			fmt=line[i];
			while(match=FREGEXP.exec(fmt))
			{
				var sign="";
				var pad=" ";

				if(!_empty(match[1])) // the left part
				{
					// You can't add this blindly because mozilla set the value to <undefined> when
					// there is no match, and we don't want the "undefined" string be returned !
					output+=match[1];
				}
				if(!_empty(match[2])) // the sign (like in %-15s)
				{
					sign=match[2];
				}
				if(!_empty(match[3])) // the "0" char for padding (like in %03d)
				{
					pad="0";
				}

				var width=match[4];	// the with (32 in %032d)
				var prec=match[6];	// the precision (10 in %.10s)
				var type=match[7];	// the parameter type

				fmt=match[8];

				if(index>=av.length)
				{
					output += "[missing parameter for type '"+type+"']";
					continue;
				}

				var val=av[index++];

				switch(type)
				{
				case "d":
					output += _printf_num_(val,10,pad,sign,width);
					break;
				case "o":
					output += _printf_num_(val,8,pad,sign,width);
					break;
				case "x":
					output += _printf_num_(val,16,pad,sign,width);
					break;
				case "X":
					output += _printf_num_(val,16,pad,sign,width).toUpperCase();
					break;
				case "c":
					output += String.fromCharCode(parseInt(val,10));
					break;
				case "s":
					output += _printf_str_(val,pad,sign,width,prec);
					break;
				case "f":
					output += _printf_float_(val,pad,sign,width,prec);
					break;
				default:
					output += "[unknown format '"+type+"']";
					break;
				}
			}
			output+=fmt;
		}
		return output;
	}

})(jQuery);


(function(){
    reprString = function (o) {
        return ('"' + o.replace(/(["\\])/g, '\\$1') + '"'
            ).replace(/[\f]/g, "\\f"
            ).replace(/[\b]/g, "\\b"
            ).replace(/[\n]/g, "\\n"
            ).replace(/[\t]/g, "\\t"
            ).replace(/[\r]/g, "\\r");
    }

    jQuery.serializeJSON = function (o) {
        var objtype = typeof(o);
        if (objtype == 'number' || objtype == 'boolean') {
            return o + '';
        }
        else if(objtype == 'string') {
            return reprString(o);
        }
        else if (o === null) {
            return 'null';
        }
        else if (objtype == "undefined") {
            return 'null';
        }
        else if(typeof(o.length) == "number") {
            var res = [];
            for (var i = 0; i < o.length; i++) {
                var val = jQuery.serializeJSON(o[i]);
                if (typeof(val) != "string") {
                    val = "undefined";
                }
                res.push(val);
            }
            return "[" + res.join(", ") + "]";
        }
        else{
            var res = [];
            for (var k in o) {
                var useKey;
                if (typeof(k) == "number") {
                    useKey = '"' + k + '"';
                } else if (typeof(k) == "string") {
                    useKey = reprString(k);
                } else {
                    // skip non-string or number keys
                    continue;
                }
                val = jQuery.serializeJSON(o[k]);
                if (typeof(val) != "string") {
                    // skip non-serializable values
                    continue;
                }
                res.push(useKey + ":" + val);
            }
            return "{" + res.join(", ") + "}";
        }
    }
})();
/**
 * jQuery.ScrollTo
 * Copyright (c) 2007 Ariel Flesler - aflesler(at)gmail(dot)com
 * Licensed under GPL license (http://www.opensource.org/licenses/gpl-license.php).
 * Date: 11/16/2007
 *
 * @projectDescription Easy element scrolling using jQuery.
 * Compatible with jQuery 1.2.1, tested on Firefox 2.0.0.7, and IE 6, both on Windows.
 *
 * @author Ariel Flesler
 * @version 1.2.4
 *
 * @id jQuery.fn.scrollTo
 * @param {String|Number|DOMElement|jQuery} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Object} settings Hash of settings, optional.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} speed The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object|Number} offset Add/deduct from the end position. One number for both axis or { top:x, left:y }
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example $('div').scrollTo( 340 );
 *
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', { speed:500, easing:'swing', queue:true, axis:'xy' } );
 *
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { speed:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { offset:-20 } );
 *
 * Notes:
 *  - jQuery.scrollTo will make the whole window scroll, it accepts the same parameters as jQuery.fn.scrollTo.
 *  - The plugin no longer requires Dimensions.
 *	- If you are interested in animated "same-page-scrolling" using anchors, check http://jquery.com/plugins/project/LocalScroll.
 *	- The option 'margin' won't be valid, if the target is an absolute position.
 *	- The option 'queue' won't be taken into account, if only 1 axis is given.
 **/
(function( $ ){
		  
	$.scrollTo = function( target, settings ){
		return $('html,body').scrollTo( target, settings );
	};
	
	$.scrollTo.defaults = {
		axis:'y',
		speed:1
	};
	
	$.fn.scrollTo = function( target, settings ){
		settings = $.extend( {}, $.scrollTo.defaults, settings );
		settings.queue = settings.queue && settings.axis.length == 2;//make sure the settings are given right
		if( settings.queue )
			settings.speed = Math.ceil( settings.speed / 2 );//let's keep the overall speed, the same.
		if( typeof settings.offset == 'number' )
			settings.offset = { left: settings.offset, top: settings.offset };
		
		return this.each(function(){
			var $elem = $(this), t = target, toff, attr = {};
			switch( typeof t ){
				case 'number'://will pass the regex
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(t) ){
						t = { top:t, left:t };
						break;//we are done
					}
					t = $(t,this);// relative selector, no break!
				case 'object':
					if( t.is || t.style )//DOM/jQuery
						toff = (t = $(t)).offset();//get the real position of the target 
			}
			$.each( settings.axis.split(''), parse );			
			animate( settings.onAfter );			
			
			function parse( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					act = $elem[0][key];
					
				attr[key] = toff ? toff[pos] + ( $elem.is('html,body') ? 0 : act - $elem.offset()[pos] ) : t[pos];
				
				if( settings.margin && t.css )//if it's a dom element,reduce the margin
					attr[key] -= parseInt( t.css('margin'+Pos) ) || 0;
				
				if( settings.offset && settings.offset[pos] )
					attr[key] += settings.offset[pos];
				
				if( !i && settings.queue ){//queueing each axis is required					
					if( act != attr[key] )//don't waste time animating, if there's no need.
						animate( settings.onAfterFirst );//intermediate animation
					delete attr[key];//don't animate this axis again in the next iteration.
				}
			};
			function animate( callback ){
				$elem.animate( attr, settings.speed, settings.easing, function(){
					if( callback )
						callback.call(this, $elem, attr, t );
				});
			};
		});
	};

})( jQuery );/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
            }

            fx.elem.style[attr] = "rgb(" + [
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }
    
    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery(elem).css(attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break; 

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    jQuery.fn.getColor = function(attr){
        return getColor(this, attr);
    };
    
    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0],
        transparent: [255,255,255]
    };
    
})(jQuery);
(function($){
    var defaults = {        
            duration    : 200,
            times       : 4
        },
        default_color = '#e31';
    $.fn.pulse = function(color, options){
        var options = $.extend({}, defaults, options),
            color = default_color || color,
            highlight = { backgroundColor: color };
            original = this.attr('_originalColor');
        if (!original){
            this.attr('_originaColor', original = this.css('background-color'));
        }
        original = { backgroundColor: original };
        this.queue('fx', [])
            .stop()
            .css('background-color', original);
        for(var i = 0, n = options.times; i !== n; i ++){
            this.animate(highlight, options.duration)
                .animate(original, options.duration);
        }
    };            
})(jQuery);

/*
    sliceExchange plugin

    this plugin exchanges the contents of an element by sliding it left while the new content slides in.

    :example: ``$('#my_element').slideExchange('<div>new content</div>');``
    :copyright: 2007 by Florian Boesch.
    :license: GNU LGPL, see http://www.gnu.org/licenses/lgpl.html for more details.
*/

(function($){
    var defaults = {        
        speed       : 'slow',
        onAfter     : function(){}
    };
    $.fn.slideExchange = function(content, options){
        var container = this;
        if(!$.fn.scrollTo){
            if(console.error){
                console.error('this plugin requires scrollTo http://plugins.jquery.com/project/ScrollTo');
            }
            return container;
        }
        var options = $.extend({}, defaults, options);
        var width = container.width();
        var orig_overflow = container.css('overflow');
        var orig_width = container.css('width');
       
        container
            .css('overflow', 'hidden')
            .width(width);
        var old_elements = container.children().remove();

        var scroller = $('<div/>')
            .width(width * 2)
            .appendTo(container)
            .addClass('clearfix');
        var old_item = $('<div/>')
            .css('float', 'left')
            .width(width)
            .append(old_elements)
            .appendTo(scroller)
    
        var new_elements = $(content)
        var new_item = $('<div/>')
            .css('float', 'left')
            .width(width)
            .append(new_elements)
            .appendTo(scroller);

        container.scrollTo(
            new_item,
            {
                axis    : 'x',
                speed   : options.speed,
                onAfter : function(){
                    old_elements.remove();
                    new_elements.remove().appendTo(container);
                    scroller.remove()
                    container.each(function(){
                        this.scrollLeft = 0;
                    });
                    options.onAfter.apply(container);
                }
            }
        );
        return container;
    };            
})(jQuery);
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name jcarousel-container">
     *   <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *   <div class="jcarousel-next"></div>
     *   <div class="jcarousel-clip">
     *     <ul class="jcarousel-list">
     *       <li class="jcarousel-item-1">First item</li>
     *       <li class="jcarousel-item-2">Second item</li>
     *     </ul>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        rows: 1,
        widthAddSpace: 100,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if ($.className.has(this.container[0].className, 'jcarousel-clip')) {
                if (!$.className.has(this.container[0].parentNode.className, 'jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!$.className.has(this.container[0].className, 'jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();

            // Move skin class over to container
            var split = e.className.split(' ');

            for (var i = 0; i < split.length; i++) {
                if (split[i].indexOf('jcarousel-skin') != -1) {
                    this.list.removeClass(split[i]);
                    this.container.addClass(split[i]);
                    break;
                }
            }
        } else {
            this.container = $(e);
            this.list = $(e).children('ul,ol');
        }

        this.clip = this.list.parent();

        if (!this.clip.length || !$.className.has(this.clip[0].className, 'jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });
            if(self.options.rows > 1){
                wh = wh / self.options.rows + self.options.widthAddSpace;
            }

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size == undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };

        $(window).bind('resize', function() { self.reload(); });

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.2'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '0px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j).get(0);
                if (!e || $.className.has(e, 'jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else{
                if(this.options.rows == 1){
                    this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
                }
                else{
                    this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll / this.options.rows);
                }
            }
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else{
                if(this.options.rows == 1){
                    this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
                }
                else{
                    this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll / this.options.rows);
                }
            }
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        _row_size : function(){
            var rem = this.options.size % this.options.rows;
            return ((this.options.size - rem) / this.options.rows) + rem;
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);

                if (d == 0) {
                    if( ! $.browser.msie ){ //iurii: HACK to smooth handling removed jcarousel in IE
                        alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    }
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }
            /*p('last: ' + last + ',size: ' + this.options.size + ',rows: ' + this.options.rows);*/
            if(this.options.rows > 1){
                var row_size = this._row_size();
                if( last >= row_size){
                    last = row_size;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }
            if(this.options.rows > 1){
                var row_size = this._row_size();
                /*out('buttons:n: ' + n + ', p: ' + p + ', row_size: ' + row_size); */
                if(this.last >= row_size){
                    n = false;
                }
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst != this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast != this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (!(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Sets the global default configuration properties.
         * @type undefined
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            $.extend(defaults, d);
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);
/* Extension to jquery.jcarousel.js which allows to create
 * carousels with scroll page navigation marks.
 * 
 * creates pagination controls in tag specified by 
 * carousel_control_selector option (default: div.jcarousel-control)
 */

jQuery.fn.paging_jcarousel = function(options){
	/* Builds jcarousel control with marks which allow to
	 * navigate by scroll pages
	 */
	var settings = jQuery.extend(
	{
		scroll : 3, // change requires correction of css
		carousel_item_selector : '.jcarousel-item', //used to count amount of scroll pages
		carousel_control_selector : 'div.jcarousel-control', //control use for jcarousel creation
		navigation_mark_id_prefix: 'step-',
		navigation_mark_class : 'step-mark',
		mark_selected_class : 'step-selected',
		mark_not_selected_class : 'step-not-selected',
		page_mark_html : ' X ' //visible content of navigation mark
	}, options);
	
	var s = settings; //shortcutting the name
	
	var toggle_selection_mark = function(all_selector, selected_selector){
		/* Set mark_selected_class just for selected_selector.
         * For all other elements set mark_not_selected_ class.
		 */
		jQuery(all_selector).removeClass(s.mark_selected_class).addClass(s.mark_not_selected_class);
		jQuery(selected_selector).removeClass(s.mark_not_selected_class).addClass(s.mark_selected_class);
	}
	
	var build_mark_id = function(index){
		return s.navigation_mark_id_prefix + index;
	}
	
	var build_mark_html = function(mark_id){
		return '<a id="' + mark_id + 
				'" class="' + s.navigation_mark_class + '">' + 
				s.page_mark_html + '</a>';
	}

	var carousel_init = function(carousel) {
		/* Initialization jcarousel callback.
		 * Creates navigation marks
		 */
		var items_count = jQuery(s.carousel_item_selector).length;
		//console.log(items_count);
		var pages_count = Math.ceil(items_count / s.scroll);
		var control_div = jQuery(s.carousel_control_selector);
        if( pages_count == 1 ){
		    control_div.append('<div class="' + s.navigation_mark_class + ' ' + s.mark_selected_class + '">' + s.page_mark_html + '</div>');
            return;
        };
		for( var i = 0 ; i < pages_count ; ++i )
		{
			var start_item_index = (i * s.scroll) + 1;
			var mark_id = build_mark_id(i);
			control_div.append(build_mark_html(mark_id));
			var ctrl = jQuery('a#' + mark_id, control_div);
			if( i == 0){
				ctrl.addClass(s.mark_selected_class);
			}
            else{
				ctrl.addClass(s.mark_not_selected_class);
            }
			ctrl.bind('click', {page : start_item_index, 
								control_id : mark_id}, function(event){
				//console.log(event.data['page']);
				toggle_selection_mark('.' + s.navigation_mark_class,
									 '#' + event.data.control_id); 
				carousel.scroll(event.data.page);
			});
		}
	}
	
	var carousel_navigation = function(carousel){
		/* jcarousel callback
		 * Updates navigation marks state base on currently first item
		 */
		var page_index = Math.ceil(carousel.last / s.scroll) - 1;
		var mark_selector = 'a#' + build_mark_id(page_index);
		toggle_selection_mark('.' + s.navigation_mark_class, 
							 mark_selector);  
	}
	
	jQuery.extend(s, {
	    initCallback : carousel_init,
		buttonNextCallback: carousel_navigation,
		buttonPrevCallback: carousel_navigation
	});
	
	return this.jcarousel(s);
};

/* jQuery plugin for JavaScript functions calls history handling. */
(function(jQuery) {
	var history_item = function(hash, handler, context){
		/* Separate history item info. */
		var self = this;
		self.hash = hash;
		self.handler = handler;
		self.context = context;
	}
	
	var history = function(){
		/* Container for history of JS function calls and their context. */
		var self = this;
		self._items_list = [];
		self._current_index = -1;

		self.add = function(history_item){
			/* Add new item at the end of history list.
			 * Removes tail of list if current item is not the last.
			 */
			if(self._current_index < self._items_list.length - 1){
				self._items_list.splice(self._current_index + 1, 
										self._items_list.length - (self._current_index + 1));
			}
			self._items_list.push(history_item);
			self._current_index = self._items_list.length - 1; 
		}
		self.select = function(hash){
			/* Search item by it's hash in the history list and makes it current. 
			 * Return the found item or null otherwise. */
			/*TODO: possible optimization by reverce order of array traverse*/
			for(i = 0; i < self._items_list.length ; ++i){
				var item = self._items_list[i];
				if(item.hash == hash){
					self._current_index = i;
					return item;
				}
			}
			return null;
		}
		self.size = function(){
			return self._items_list.length;
		}
	}
	
	var history_controller = function(){
		var self = this;
		self._create_hash = function(counter){
			return '#' + counter;
		}
		self.init = function(callback){
			/* Initializes controller.
			 * callback - callback function which is explicitly called 
			 * 			by the controller on navigation 
			 *  		to a state by browser navigation utilities.
			 *  		Has signature:
			 *  			foo(handler, context)
			 *  		(see detailes on parameters in description of register().)
			 *  		If callback not provided - used implicit calls to registered 
			 *  		state handler functions. 
			 */
			self._callback = callback;
			self._hash_counter = 0;
			self._current_hash = self._create_hash(self._hash_counter);
			self._history = new history();

			if($.browser.msie){
				// add hidden iframe for IE
				$("body").prepend('<iframe id="jQuery_history" style="display: none; z-index: 1;" src="javascript:false"></iframe>');
				var iframe = $("#jQuery_history")[0].contentWindow.document;
				iframe.open();
				iframe.close();
				iframe.location.hash = self._current_hash;
			}
			else{
				location.hash = self._current_hash;	
			}
			setTimeout(self._check, 100);
		}
		self.register = function(handler, context){
			/* Register new system state.
			 * handler - function with signature
			 * 			 foo(context)
			 * 			to be called on navigation to this state 
			 * 			by browser navigation utilities.
			 *  context - any data passed to the handler on navigation 
			 *  		to this state by browser navigation utilities. 
			 */
			self._current_hash = self._create_hash(self._hash_counter);
			if($.browser.msie){
				// On IE, check for location.hash of iframe
				var ihistory = $("#jQuery_history")[0];
				var iframe_doc = ihistory.contentDocument || ihistory.contentWindow.document;
				iframe_doc.open();
				iframe_doc.close();
				iframe_doc.location.hash = self._current_hash;
			}
			else{
				location.hash = self._current_hash;	
			}
			self._hash_counter += 1;
			var item = new history_item(self._current_hash, handler, context);
			self._history.add(item);
		}

        self.register_location = function(url){
            /* Use pointed URL for navigation in history
               HACK: to show first page  */
            self.register(function(){
                location.href = url;
                if(jQuery.browser.mozilla)
                    location.reload(true);
            });
        };

		self._check = function(){
			/* Regulary check for changing location.hash and if it is changed
			 * search in history corresponding item and uses it for calling
			 * corresponding JS handler. */
			if(self._history.size()){
				if ($.browser.msie) {
					// On IE, check for location.hash of iframe
					var ihistory = $("#jQuery_history")[0];
					var iframe_doc = ihistory.contentDocument || ihistory.contentWindow.document;
					var current_hash = iframe_doc.location.hash;
					if (current_hash != self._current_hash) {
						var item = self._history.select(current_hash);
						if (item) {
							if (self._callback) {
								self._callback(item.handler, item.context);
							}
							else {
								item.handler(item.context);
							}
							self._current_hash = item.hash;
						}								
						location.hash = current_hash;
						self._current_hash = current_hash;
					}
				}
				else{
					if (self._current_hash != location.hash) {
						var item = self._history.select(location.hash);
						if (item) {
							if (self._callback) {
								self._callback(item.handler, item.context);
							}
							else {
								item.handler(item.context);
							}
							self._current_hash = item.hash;
							location.hash = self._current_hash;
						}
					}
				}						
			}
			setTimeout(self._check, 100);
		}
	}
	
	jQuery(document).ready(function() {
		jQuery.history = new history_controller(); // singleton instance
	});
	
})(jQuery);
/* Sample of CSS for the scrollpanel:
			div.scrollview{
				position: absolute;
				left: 150px;
				top: 100px;
				width: 300px;
				height: 200px;
				overflow: auto;
				background-color: #999999;
			}
 */

(function($){
	var move_direction = {
		up : 1,
		down : 2
	}
	
	var window_cache = function(parameters){
		/*Cache with scrolled window logic on cached objects.
		 * Has bidirectional queue os constant size with cleanp
		 * of cached objects from opposite side to new added object.
		 * Loading of cached objects delegated to provider of onload_callback.
		 */
		var defaults = {
			cache_size : 3, /* amount of chunks to keep in memory */
			onload_callback : function(index){}, /*called to load data for chunk 
											with specified index. After loading data,
											data provider must call on_data_loaded()
											on the cache object*/ 
			ondestroy_callback : function(object){} /*callback call to destoy 
											cached object. Must be provided in case
											cached object require special cleanup.*/
		};
		
		var self = this;
		self.queue = [];
		self.is_loading = false;
		self.settings = $.extend({}, defaults, parameters || {});
		
		var s = self.settings; //shortcut
			
		self.last_chunk = function(){
			/*NO CHECK for empty queue !*/
			return self.queue[self.queue.length - 1];
		}
		
		self.move = function(direction){
			/*Moving cache window in pointed direction: 'up'/'down'*/
			switch (direction) {
				case move_direction.up: {
					if (self.queue.length == 0 || self.queue[0].index == 0) 
						return;
					self._load_data(self.queue[0].index - 1);
					break;
				}
				case move_direction.down: {
					var index = 0;
					if (self.queue.length > 0){
						var chunk = self.last_chunk();
						if(chunk.is_last){
							return;
						}
						index = chunk.index + 1;
					}
					self._load_data(index);
					break;
				}
				default: {
					throw new Error('window_chache.move(direction): direction "' + direction + '" not recognized');
				}
			}
		}

		self._load_data = function(index){
			if(self.is_loading) //busy
				return;
			self.is_loading = true;
			s.onload_callback(index);
		}
		
		self.on_data_loaded = function(index, loaded_object){
			/*Must be called by client on finishing data portion load*/
            if(loaded_object){
				var chunk = {
					index : index,
					object : loaded_object
				};
				if(self.queue.length == 0){
					self.queue.push(chunk);
				}
				else{
					var is_top_chunk = index < self.queue[0].index;
					if(self.queue.length >= s.cache_size){
						while(self.queue.length >= s.cache_size)
						{
							var chunk_to_remove = is_top_chunk ? self.queue.pop() : self.queue.shift();
							s.ondestroy_callback(chunk_to_remove.object);
							delete chunk_to_remove;
						}						
					}
					if(is_top_chunk){
						self.queue.unshift(chunk);
					}
					else{
						self.queue.push(chunk);
					}
				}
			}
			else{ //no data returned
				if(self.queue.length > 0)
				{
					var chunk = self.last_chunk();
					if(chunk.index < index){
						chunk.is_last = true;
					}
				}
			}
			self.is_loading = false;
		}
	}
	
	var defaults = {
		top_load_offset: 5, /*offset in pexels from top when fired loading data*/
		bottom_load_offset: 5, /*offset in pexels from bottom when fired loading data*/
		loaded_offset_fraction: 0.1, /*scrollTop offset in pexels from top after loading data*/
		chunk_size: 50,		/*chunk size passed to load_data_callback*/
		onload_callback : function(target_object, offset, size, onloaded_callback){}, 
							/*callback used for loading data.
							 * onloaded_callback(data) - must be called on target_object
							 * with loaded data as parameter. */
		is_load_data_on_startup : true /*indicate need to load data at creation time*/
	};

   $.fn.scrollpanel = function(parameters) {
   		var res = [];
        this.each(function() {
            res.push(new $.scrollpanel(this, parameters));
        });
		return this.pushStack(res);
    };

	$.scrollpanel = function(element, parameters){
		var self = this;
		self.container = element;/*conytainer for data (<div>)*/
		self.settings = $.extend({}, defaults, parameters || {});
		var s = self.settings;
		
		self._onload = function(index){
			/*called by cache to load next porion of data*/
			self._current_index = index;
			s.onload_callback(self, index * s.chunk_size, 
									s.chunk_size, self._on_data_loaded);
		}
		
		self._ondestroy = function(object){
			/*called bu cache to destroy poped from cache object*/
			object.remove();
		}

		self.cache = new window_cache({
			onload_callback : self._onload,
			ondestroy_callback : self._ondestroy
		})
		
		self._on_data_loaded = function(data){
			/*callback called by data provider when data porion is ready*/
			if (data.length) {
				var obj = undefined;
				switch(self.direction){
					case move_direction.up: {
						var obj = $(data).prependTo(self.container);
						break;
					}
					case move_direction.down: {
						var obj = $(data).appendTo(self.container);
						break;
					}
                    default:{
					    throw new Error('scrollpanel._on_data_loaded(): self.direction "' + direction + '" not recognized');
                    }
				}
				self.cache.on_data_loaded(self._current_index, obj);
				var scroll_offset = self.container.scrollHeight * s.loaded_offset_fraction;
				self.container.scrollTop += (self.direction == move_direction.up) 
												? scroll_offset : -scroll_offset;
				self.direction = undefined;
			}
            else{
				self.cache.on_data_loaded(self._current_index, undefined);
            }
		}
		
		self._move_cache = function(direction){
			self.direction = direction;
			self.cache.move(direction);
		}
		
		$(self.container).scroll(function(event){
			var t = event.target;
			if(t.scrollTop < s.top_load_offset){
				self._move_cache(move_direction.up);
				return;
			}
			var bottom_offset = (t.scrollHeight - t.offsetHeight) - t.scrollTop;
			if(bottom_offset < s.bottom_load_offset){
				self._move_cache(move_direction.down);
			}
		});
		
		if(s.is_load_data_on_startup){
			self._move_cache(move_direction.down);
		}
		return self;
	};
})(jQuery);

/* application.js
   ~~~~~~~~~~~~~~
*/










var module_logger = logging.ns('application');

function Configuration(data){
    var logger = module_logger.ns('Configuration');
    var self = this;
    self.get = logger.fun('get', function(name){
        return data[name];
    });
    logger.leave();
}

var Application = util.klass('Application', function(self, content, language, trans, config, user, action){
    var logger = module_logger.ns('Application');
    self.tabs_hidden = false;
    
    self.currency = logger.fun('currency', function(){return '$';});
    self.format_price = logger.fun('format_price', function(price){
        if (price) return $.sprintf('%s%.2f', self.currency(), price);
        else return $.sprintf('%s %s', self.currency(), price);
    });

    self.breadcrumb = $('#breadcrumb');
    self.actions = $('#collapse_bar');

    self.__init__ = logger.fun('init', function(){
        
        // translations
        self.translator = new Translator(self, trans);
        self.trans = self.translator.get;
   
        // config
        self.configuration = new Configuration(config);
        self.config = self.configuration.get;
       

        self.user_cookie = new Cookie(self.config('user_cookie'));
        self.init_user();
    
        self.url = new customer.URL(self, language);
        self.language = language;
        
        if($.browser.msie){
            document.createStyleSheet(self.url.customer_css({css_name:'ie.css'}))
        }

   
        self.data    = new customer.Data(self);
        self.storage = new Storage(self);

        self.setup_tabs(); 

        $(window).bind('resize', self.on_resize);
        $('#help_btn').bind('click', function(){
            self.show_static(self.config('help_file'));
        });
        $('#manage_account_btn').click(function(){
            self.navigate(self.config('manage_account_url'));
            return false;
        });
        self.show_content(content);
      
        self.add_shortcuts();
        self.disable_select_all();
    });

    //FIXME: Refactoring is needed!
    self.add_shortcuts = logger.fun('add_shortcuts', function(){
        $(document).keypress(function(event){
            var code = shortcut.keycode(event);
            switch(code){
                case shortcut.KEY_ESC:
                    self.modal.hide();
                    break;
                case shortcut.KEY_ONE:
                    self.show_browse();
                    break;
                case shortcut.KEY_TWO:
                    self.show_basket();
                    break;
                case shortcut.KEY_THREE:
                    self.show_search();
                    break;
                case shortcut.KEY_FOUR:
                    if (self.tabs.length > 3){
                        self.show_myproducts();
                    }
                    break; 
            }
        });
    });

    self.disable_select_all = logger.fun('disable_select_all', function(){
        var event_types = ['mousedown', 'mouseup', 'click'];
        $.each(event_types, function(i, type){
            $(document).bind(type, function(e){
                var target = e.target || this;
                if(target.nodeName == 'BODY'){
                    return false;
                }
            });
        });
    });

    self.product_state = logger.fun('product_state', function(product_id){
        if(self.basket.has_product(product_id)){
            return self.product_state.basket;
        }
        else if(self.user.has_product(product_id)){
            return self.product_state.bought;
        }
    });

    self.product_state.basket = 1
    self.product_state.bought = 2

    self.navigate = logger.fun('navigate', function(url){
        document.location = url;
    });

    self.gotoanchor = logger.fun('gotoanchor', function(anchor){
        url = document.location.href.replace(/#.*/, '') + '#' + anchor;
        document.location = url;
    });
    
    self.download_order = logger.fun('download_order', function(order_id){
        application.navigate(
            application.url.download_order(order_id, {user_cookie:self.user_cookie.read()})
        );
    });
    
    self.download_product = logger.fun('download_product', function(order_id, product_id){
        application.navigate(
            application.url.download_product(order_id, product_id, {user_cookie:self.user_cookie.read()})
        );
    });
    
    self.download_preview = logger.fun('download_preview', function(product_id){
        self.navigate(self.preview_url(product_id));
    });

    self.show_content = logger.fun('show_content', function(content){
        add_handler = self.data['add_' + content.__type__];
        if(add_handler){
            add_handler(content);
        }
        self.set_content(content);
        self.render();
    });

    self.on_resize = logger.fun('on_resize', function(){
        self.adjust_content_height();
        self.modal.center();
    });

    self.adjust_content_height = logger.fun('adjust_content_height', function(){
        // template for those who need it
    });

    self.show_basket = logger.fun('show_basket', function(){
        if(self.basket === self.active_tab && !self.tabs_hidden){
            self.hide_tabs();
        }
        else{
            self.active_tab = self.basket;
            self.show_tabs();
        }
    });
    
    self.show_browse = logger.fun('show_browse', function(){
        if(self.drilldown === self.active_tab && !self.tabs_hidden){
            self.hide_tabs();
        }
        else{
            self.active_tab = self.drilldown;
            self.show_tabs();
        }
    });

    self.show_search = logger.fun('show_search', function(){
        if(self.search === self.active_tab && !self.tabs_hidden){
            self.hide_tabs();
        }
        else{
            self.active_tab = self.search;
            self.show_tabs();
        }
        $('#searchbox').focus();
    });

    self.show_myproducts = logger.fun('show_myproducts', function(){
        if(self.my_products === self.active_tab && !self.tabs_hidden){
            self.hide_tabs();
        }
        else{
            self.active_tab = self.my_products;
            self.show_tabs();
        }
    });
    
    self.add_tab = logger.fun('add_tab', function(tab){
        if (!util.find(self.tabs, tab)){
            self.tabs.push(tab);
        }
    });
    
    self.remove_tab = logger.fun('remove_tab', function(tab){
        var index = util.find(self.tabs, tab)
        if (index){
            if (tab === self.active_tab){
                self.show_browse();
            }
            self.tabs.splice(index, 1);
        }
    });

    self.handle_tab_click = logger.fun('handle_tab_click', function(element, type, id, tag_type_id, title){
        self.active_tab.handle_click(element, type, id, tag_type_id, title)
    });

    self.render_mainnav = logger.fun('render_mainnav', function(){
        $('#main_navigation').empty().append(web_shop.main_navigation({
            application : self
        }).serialize());
    });

    self.render = logger.fun('render', function(){
        self.render_widgets();
        self.render_content();
        self.adjust_content_height();
    });
    
    self.toggle_tabs = logger.fun('toggle_tabs', function(){
        if(self.tabs_hidden){
            self.show_tabs();
        }
        else{
            self.hide_tabs();
        }
    });

    self.hide_tabs = logger.fun('hide_tabs', function(){
        self.tabs_hidden = true;
        $('#widgets').slideUp('fast');
    });

    self.show_tabs = logger.fun('show_tabs', function(){
        self.render_widgets();
        if(self.tabs_hidden){
            self.tabs_hidden = false;
            $('#widgets').slideDown('fast', function(){
                self.adjust_content_height();
                self.active_tab.render_actions();
                self.active_tab.render_sub_navigation();
                if($.browser.msie){
                    self.render_content(true); // IE hack, seems to garble up layout by sliding down content
                }
            });
        }
    });
    
    self.post_secure_json = logger.fun('post_secure_json', function(in_params){
        in_params.data = in_params.data || {};
        cookie_name = self.config('user_cookie');
        in_params.data[cookie_name] = self.user_cookie.read();
        util.post_json({
            url         : in_params.url,
            success     : function(data){
                if(data.result == false){
                    if(in_params.error){
                        in_params.error(data, data.message);
                    }
                }
                else{
                    if(in_params.success){
                        return in_params.success(data);
                    }
                }
            },
            error       : function(data){
                if(in_params.error){
                    in_params.error(data, data.responseText)
                }
            },
            data        : in_params.data
        })
    });

    logger.leave();
});

module_logger.leave();


