/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/cookies.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// This code from http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/jquery.overlabel.js"></script> */
(function($){
$.fn.overlabel = function() {
    this.each(function(index) {
        var label = $(this); var field;
        var id = this.htmlFor || label.attr('for');
        if (id && (field = document.getElementById(id))) {
            var control = $(field);
            label.addClass("overlabel-apply");
            if (field.value !== '') {
                label.css("text-indent", "-1000px");
            }
            control.focus(function () {label.css("text-indent", "-1000px");}).blur(function () {
                if (this.value === '') {
                    label.css("text-indent", "0px");
                }
            });
            label.click(function() {
                var label = $(this); var field;
                var id = this.htmlFor || label.attr('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            });
        }
    });
}
})(jQuery);

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/jquery.spin.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */

(function($) {
    $.fn.spin = function() {
        var prev = this.prev();
        var spinner = $('<div class="spinner">' +
                        '<img src="/static/images/loading.gif" alt="" width="16" height="16" />' +
                        'Loading...</div>');
        if (this.is(':hidden')) {
            spinner.hide()
        }
        this.hide();
        this.before(spinner);
        return this;
    };
    $.fn.stop_spinning = function() {
        var prev = this.prev();
        if (prev.hasClass('spinner')) {
            if (!prev.is(':hidden')) {
                this.show();
            }
            prev.remove();
        }
        return this;
    };
})(jQuery);

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/jquery.simplemodal.js"></script> */
/*
 * SimpleModal 1.1.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://plugins.jquery.com/project/SimpleModal
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Revision: $Id: jquery.simplemodal.js 93 2008-01-15 16:14:20Z emartin24 $
 *
 */
(function($){$.modal=function(data,options){return $.modal.impl.init(data,options);};$.modal.close=function(){$.modal.impl.close(true);};$.fn.modal=function(options){return $.modal.impl.init(this,options);};$.modal.defaults={overlay:50,overlayId:'modalOverlay',overlayCss:{},containerId:'modalContainer',containerCss:{},close:true,closeTitle:'Close',closeClass:'modalClose',persist:false,onOpen:null,onShow:null,onClose:null};$.modal.impl={opts:null,dialog:{},init:function(data,options){if(this.dialog.data){return false;}this.opts=$.extend({},$.modal.defaults,options);if(typeof data=='object'){data=data instanceof jQuery?data:$(data);if(data.parent().parent().size()>0){this.dialog.parentNode=data.parent();if(!this.opts.persist){this.dialog.original=data.clone(true);}}}else if(typeof data=='string'||typeof data=='number'){data=$('<div>').html(data);}else{if(console){console.log('SimpleModal Error: Unsupported data type: '+typeof data);}return false;}this.dialog.data=data.addClass('modalData');data=null;this.create();this.open();if($.isFunction(this.opts.onShow)){this.opts.onShow.apply(this,[this.dialog]);}return this;},create:function(){this.dialog.overlay=$('<div>').attr('id',this.opts.overlayId).addClass('modalOverlay').css($.extend(this.opts.overlayCss,{opacity:this.opts.overlay/100,height:'100%',width:'100%',position:'fixed',left:0,top:0,zIndex:3000})).hide().appendTo('body');this.dialog.container=$('<div>').attr('id',this.opts.containerId).addClass('modalContainer').css($.extend(this.opts.containerCss,{position:'fixed',zIndex:3100})).append(this.opts.close?'<a class="modalCloseImg '+this.opts.closeClass
+'" title="'+this.opts.closeTitle+'"></a>':'').hide().appendTo('body');if($.browser.msie&&($.browser.version<7)){this.fixIE();}this.dialog.container.append(this.dialog.data.hide());},bindEvents:function(){var modal=this;$('.'+this.opts.closeClass).click(function(e){e.preventDefault();modal.close();});},unbindEvents:function(){$('.'+this.opts.closeClass).unbind('click');},fixIE:function(){var wHeight=$(document.body).height()+'px';var wWidth=$(document.body).width()+'px';this.dialog.overlay.css({position:'absolute',height:wHeight,width:wWidth});this.dialog.container.css({position:'absolute'});this.dialog.iframe=$('<iframe src="javascript:false;">').css($.extend(this.opts.iframeCss,{opacity:0,position:'absolute',height:wHeight,width:wWidth,zIndex:1000,width:'100%',top:0,left:0})).hide().appendTo('body');},open:function(){if(this.dialog.iframe){this.dialog.iframe.show();}if($.isFunction(this.opts.onOpen)){this.opts.onOpen.apply(this,[this.dialog]);}else{this.dialog.overlay.show();this.dialog.container.show();this.dialog.data.show();}this.bindEvents();},close:function(external){if(!this.dialog.data){return false;}if($.isFunction(this.opts.onClose)&&!external){this.opts.onClose.apply(this,[this.dialog]);}else{if(this.dialog.parentNode){if(this.opts.persist){this.dialog.data.hide().appendTo(this.dialog.parentNode);}else{this.dialog.data.remove();this.dialog.original.appendTo(this.dialog.parentNode);}}else{this.dialog.data.remove();}this.dialog.container.remove();this.dialog.overlay.remove();if(this.dialog.iframe){this.dialog.iframe.remove();}this.dialog={};}this.unbindEvents();}};})(jQuery);
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/jquery.jreflection.js"></script> */
/**
 * reflection.js v1.6
 *
 * Contributors: Cow http://cow.neondragon.net
 *               Gfx http://www.jroller.com/page/gfx/
 *               Sitharus http://www.sitharus.com
 *               Andreas Linde http://www.andreaslinde.de
 *               Tralala, coder @ http://www.vbulletin.org
 *
 * Freely distributable under MIT-style license.
 */
 
/* From prototype.js */
document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = new Array();
  
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}

var Reflection = {
	defaultHeight : 0.5,
	defaultOpacity: 0.5,
	
	add: function(image, options) {
		Reflection.remove(image);
		
		doptions = { "height" : Reflection.defaultHeight, "opacity" : Reflection.defaultOpacity }
		if (options) {
			for (var i in doptions) {
				if (!options[i]) {
					options[i] = doptions[i];
				}
			}
		} else {
			options = doptions;
		}
	
		try {
			var d = document.createElement('div');
			var p = image;
			
			var classes = p.className.split(' ');
			var newClasses = '';
			for (j=0;j<classes.length;j++) {
				if (classes[j] != "reflect") {
					if (newClasses) {
						newClasses += ' '
					}
					
					newClasses += classes[j];
				}
			}

			var reflectionHeight = Math.floor(p.height*options['height']);
			var divHeight = Math.floor(p.height*(1+options['height']));
			
			var reflectionWidth = p.width;
			
			if (document.all && !window.opera) {
				/* Copy original image's classes & styles to div */
				d.className = newClasses;
				p.className = 'reflected';
				
				d.style.cssText = p.style.cssText;
				p.style.cssText = 'vertical-align: bottom';
			
				var reflection = document.createElement('img');
				reflection.src = p.src;
				reflection.style.width = reflectionWidth+'px';
				
				reflection.style.marginBottom = "-"+(p.height-reflectionHeight)+'px';
				reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';
				
				d.style.width = reflectionWidth+'px';
				d.style.height = divHeight+'px';
				p.parentNode.replaceChild(d, p);
				
				d.appendChild(p);
				d.appendChild(reflection);
			} else {
				var canvas = document.createElement('canvas');
				if (canvas.getContext) {
					/* Copy original image's classes & styles to div */
					d.className = newClasses;
					p.className = 'reflected';
					
					d.style.cssText = p.style.cssText;
					p.style.cssText = 'vertical-align: bottom';
			
					var context = canvas.getContext("2d");
				
					canvas.style.height = reflectionHeight+'px';
					canvas.style.width = reflectionWidth+'px';
					canvas.height = reflectionHeight;
					canvas.width = reflectionWidth;
					
					d.style.width = reflectionWidth+'px';
					d.style.height = divHeight+'px';
					p.parentNode.replaceChild(d, p);
					
					d.appendChild(p);
					d.appendChild(canvas);
					
					context.save();
					
					context.translate(0,image.height-1);
					context.scale(1,-1);
					
					context.drawImage(image, 0, 0, reflectionWidth, image.height);
	
					context.restore();
					
					context.globalCompositeOperation = "destination-out";
					var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
					
					gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
					gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-options['opacity'])+")");
		
					context.fillStyle = gradient;
					if (navigator.appVersion.indexOf('WebKit') != -1) {
						context.fill();
					} else {
						context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
					}
				}
			}
		} catch (e) {
	    }
	},
	
	remove : function(image) {
		if (image.className == "reflected") {
			image.className = image.parentNode.className;
			image.parentNode.parentNode.replaceChild(image, image.parentNode);
		}
	}
}

function addReflections() {
	var rimages = document.getElementsByClassName('reflect');
	for (i=0;i<rimages.length;i++) {
		var rheight = null;
		var ropacity = null;
		
		var classes = rimages[i].className.split(' ');
		for (j=0;j<classes.length;j++) {
			if (classes[j].indexOf("rheight") == 0) {
				var rheight = classes[j].substring(7)/100;
			} else if (classes[j].indexOf("ropacity") == 0) {
				var ropacity = classes[j].substring(8)/100;
			}
		}
		
		Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
	}
}

var previousOnload = window.onload;
window.onload = function () { if(previousOnload) previousOnload(); addReflections(); }

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/soundmanager2.js"></script> */
/*
   SoundManager 2: Javascript Sound for the Web
   --------------------------------------------
   http://www.schillmania.com/projects/soundmanager2/

   Copyright (c) 2007, Scott Schiller. All rights reserved.
   Code licensed under the BSD License:
   http://www.schillmania.com/projects/soundmanager2/license.txt

   V2.0b.20070415

   Changes
   -------
   emcsween@goombah.com:
        - Changed paths
        - Retry the initialization a number of times if it didn't work the first time.
        - Don't destruct on beforeunload, but on unload.
*/

function SoundManager(smURL,smID) {
  var self = this;
  this.version = 'V2.0b.20070415';
  this.url = (smURL||'soundmanager2.swf');

  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 = false;        // if console is being used, do not create/write to #soundmanager-debug
  this.nullURL = '/static/null.mp3';  // path to "null" (empty) MP3 file, used to unload sounds
  this.number_of_init_trials = 0;

  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
    '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
    'pan': 0,                      // "pan" settings, left-to-right, -100 to 100
    'volume': 100                  // self-explanatory. 0-100, the latter being the max.
  }

  this.allowPolling = true;        // allow flash to poll for status update (required for "while playing", "progress" etc. to work.)
  this.enabled = false;
  this.o = null;
  this.id = (smID||'sm2movie');
  this.oMC = null;
  this.sounds = [];
  this.soundIDs = [];
  this.isIE = (navigator.userAgent.match(/MSIE/));
  this.isSafari = (navigator.userAgent.match(/safari/i));
  this.debugID = 'soundmanager-debug';
  this._debugOpen = true;
  this._didAppend = false;
  this._appendSuccess = false;
  this._didInit = false;
  this._disabled = false;
  this._hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');
  this._debugLevels = !self.isSafari?['debug','info','warn','error']:['log','log','log','log'];

  // --- public methods ---

  this.getMovie = function(smID) {
    // return self.isIE?window[smID]:document[smID];
    return self.isIE?window[smID]:(self.isSafari?document[smID+'-embed']:document.getElementById(smID+'-embed'));
  }

  this.loadFromXML = function(sXmlUrl) {
    try {
      self.o._loadFromXML(sXmlUrl);
    } catch(e) {
      self._failSafely();
      return true;
    }
  }

  this.createSound = function(oOptions) {
    if (!self._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 = self._mergeObjects(oOptions);
    self._writeDebug('soundManager.createSound(): "<a href="#" onclick="soundManager.play(\''+thisOptions.id+'\');return false" title="play this sound">'+thisOptions.id+'</a>" ('+thisOptions.url+')',1);
    if (self._idCheck(thisOptions.id,true)) {
      self._writeDebug('sound '+thisOptions.id+' already defined - exiting',2);
      return false;
    }
    self.sounds[thisOptions.id] = new SMSound(self,thisOptions);
    self.soundIDs[self.soundIDs.length] = thisOptions.id;
    try {
      self.o._createSound(thisOptions.id,thisOptions.onjustbeforefinishtime);
    } catch(e) {
      self._failSafely();
      return true;
    }
    if (thisOptions.autoLoad || thisOptions.autoPlay) self.sounds[thisOptions.id].load(thisOptions);
    if (thisOptions.autoPlay) self.sounds[thisOptions.id].playState = 1; // we can only assume this sound will be playing soon.
  }

  this.destroySound = function(sID) {
    // explicitly destroy a sound before normal page unload, etc.
    if (!self._idCheck(sID)) return false;
    for (var i=self.soundIDs.length; i--;) {
      if (self.soundIDs[i] == sID) {
        delete self.soundIDs[i];
        continue;
      }
    }
    self.sounds[sID].unload();
    delete self.sounds[sID];
  }

  this.load = function(sID,oOptions) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].load(oOptions);
  }

  this.unload = function(sID) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].unload();
  }

  this.play = function(sID,oOptions) {
    if (!self._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'});
        self._writeDebug('soundController.play(): attempting to create "'+sID+'"',1);
        oOptions.id = sID;
        self.createSound(oOptions);
      } else {
        return false;
      }
    }
    self.sounds[sID].play(oOptions);
  }

  this.start = this.play; // just for convenience

  this.setPosition = function(sID,nMsecOffset) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].setPosition(nMsecOffset);
  }

  this.stop = function(sID) {
    if (!self._idCheck(sID)) return false;
    self._writeDebug('soundManager.stop('+sID+')',1);
    self.sounds[sID].stop(); 
  }

  this.stopAll = function() {
    self._writeDebug('soundManager.stopAll()',1);
    for (var oSound in self.sounds) {
      if (self.sounds[oSound] instanceof SMSound) self.sounds[oSound].stop(); // apply only to sound objects
    }
  }

  this.pause = function(sID) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].pause();
  }

  this.resume = function(sID) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].resume();
  }

  this.togglePause = function(sID) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].togglePause();
  }

  this.setPan = function(sID,nPan) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].setPan(nPan);
  }

  this.setVolume = function(sID,nVol) {
    if (!self._idCheck(sID)) return false;
    self.sounds[sID].setVolume(nVol);
  }

  this.setPolling = function(bPolling) {
    if (!self.o || !self.allowPolling) return false;
    self._writeDebug('soundManager.setPolling('+bPolling+')');
    self.o._setPolling(bPolling);
  }

  this.disable = function() {
    // destroy all functions
    if (self._disabled) return false;
    self._disabled = true;
    self._writeDebug('soundManager.disable(): Disabling all functions - future calls will return false.',1);
    for (var i=self.soundIDs.length; i--;) {
      self._disableObject(self.sounds[self.soundIDs[i]]);
    }
    self.initComplete(); // fire "complete", despite fail
    self._disableObject(self);
  }

  this.getSoundById = function(sID,suppressDebug) {
    if (!sID) throw new Error('SoundManager.getSoundById(): sID is null/undefined');
    var result = self.sounds[sID];
    if (!result && !suppressDebug) {
      self._writeDebug('"'+sID+'" is an invalid sound ID.',2);
      // soundManager._writeDebug('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._writeDebug('<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;

  this._disableObject = function(o) {
    for (var oProp in o) {
      if (typeof o[oProp] == 'function' && typeof o[oProp]._protected == 'undefined') o[oProp] = function(){return false;}
    }
    oProp = null;
  }

  this._failSafely = function() {
    // exception handler for "object doesn't support this property or method"
    var flashCPLink = 'http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html';
    var fpgssTitle = 'You may need to whitelist this location/domain eg. file:///C:/ or C:/ or mysite.com, or set ALWAYS ALLOW under the Flash Player Global Security Settings page. Note that this seems to apply only to file system viewing.';
    var flashCPL = '<a href="'+flashCPLink+'" title="'+fpgssTitle+'">view/edit</a>';
    var FPGSS = '<a href="'+flashCPLink+'" title="Flash Player Global Security Settings">FPGSS</a>';
    if (!self._disabled) {
      self._writeDebug('soundManager: JS-&gt;Flash communication failed. Possible causes: flash/browser security restrictions ('+flashCPL+'), insufficient browser/plugin support, or .swf not found',2);
      self._writeDebug('Verify that the movie path of <em>'+self.url+'</em> is correct (<a href="'+self.url+'" title="If you get a 404/not found, fix it!">test link</a>)',1);
      if (self._didAppend) {
        if (!document.domain) {
          self._writeDebug('Loading from local file system? (document.domain appears to be null, this URL path may need to be added to \'trusted locations\' in '+FPGSS+')',1);
          self._writeDebug('Possible security/domain restrictions ('+flashCPL+'), should work when served by http on same domain',1);
        }
        // self._writeDebug('Note: Movie added via JS method, static object/embed in-page markup method may work instead.');
      }
      self.disable();
    }
  }

  this._createMovie = function(smID,smURL) {
    if (self._didAppend && self._appendSuccess) return false; // ignore if already succeeded
    if (window.location.href.indexOf('debug=1')+1) self.debugMode = true; // allow force of debug mode via URL
    self._didAppend = true;
    var html = ['<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="16" height="16" id="'+smID+'"><param name="movie" value="'+smURL+'"><param name="quality" value="high"><param name="allowScriptAccess" value="always" /></object>','<embed name="'+smID+'-embed" id="'+smID+'-embed" src="'+smURL+'" width="1" height="1" quality="high" allowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
    var toggleElement = '<div id="'+self.debugID+'-toggle" style="position:fixed;_position:absolute;right:0px;bottom:0px;_top:0px;width:1.2em;height:1.2em;line-height:1.2em;margin:2px;padding:0px;text-align:center;border:1px solid #999;cursor:pointer;background:#fff;color:#333;z-index:706" title="Toggle SM2 debug console" onclick="soundManager._toggleDebug()">-</div>';
    var debugHTML = '<div id="'+self.debugID+'" style="display:'+(self.debugMode && ((!self._hasConsole||!self.useConsole)||(self.useConsole && self._hasConsole && !self.consoleOnly))?'block':'none')+';opacity:0.85"></div>';
    var appXHTML = 'soundManager._createMovie(): appendChild/innerHTML set failed. Serving application/xhtml+xml MIME type? Browser may be enforcing strict rules, not allowing write to innerHTML. (PS: If so, this means your commitment to XML validation is going to break stuff now, because this part isn\'t finished yet. ;))';

    var sHTML = '<div style="position:absolute;left:-256px;top:-256px;width:1px;height:1px" class="movieContainer">'+html[self.isIE?0:1]+'</div>'+(self.debugMode && ((!self._hasConsole||!self.useConsole)||(self.useConsole && self._hasConsole && !self.consoleOnly)) && !document.getElementById(self.debugID)?'x'+debugHTML+toggleElement:'');

    var oTarget = (document.body?document.body:document.getElementsByTagName('div')[0]);
    if (oTarget) {
      self.oMC = document.createElement('div');
      self.oMC.className = 'movieContainer';
      // "hide" flash movie
      self.oMC.style.position = 'absolute';
      self.oMC.style.left = '-256px';
      self.oMC.style.width = '1px';
      self.oMC.style.height = '1px';
      try {
        oTarget.appendChild(self.oMC);
        self.oMC.innerHTML = html[self.isIE?0:1];
        self._appendSuccess = true;
      } catch(e) {
        // may fail under app/xhtml+xml - has yet to be tested
        throw new Error(appXHTML);
      }
      if (!document.getElementById(self.debugID) && ((!self._hasConsole||!self.useConsole)||(self.useConsole && self._hasConsole && !self.consoleOnly))) {
        var oDebug = document.createElement('div');
        oDebug.id = self.debugID;
        oDebug.style.display = (self.debugMode?'block':'none');
        if (self.debugMode) {
          try {
            var oD = document.createElement('div');
            oTarget.appendChild(oD);
            oD.innerHTML = toggleElement;
          } catch(e) {
            throw new Error(appXHTML);
          }
        }
        oTarget.appendChild(oDebug);
      }
      oTarget = null;
    }
    self._writeDebug('-- SoundManager 2 Version '+self.version.substr(1)+' --',1);
    self._writeDebug('soundManager._createMovie(): trying to load <a href="'+smURL+'" title="Test this link (404=bad)">'+smURL+'</a>',1);
  }

  this._writeDebug = function(sText,sType) {
    if (!self.debugMode) return false;
    if (self._hasConsole && self.useConsole) {
      console[self._debugLevels[sType]||'log'](sText); // firebug et al
      if (self.useConsoleOnly) return true;
    }
    var sDID = 'soundmanager-debug';
    try {
      var o = document.getElementById(sDID);
      if (!o) return false;
      var p = document.createElement('div');
      p.innerHTML = sText;
      // o.appendChild(p); // top-to-bottom
      o.insertBefore(p,o.firstChild); // bottom-to-top
    } catch(e) {
      // oh well
    }
    o = null;
  }
  this._writeDebug._protected = true;

  this._writeDebugAlert = function(sText) { alert(sText); }

  if (window.location.href.indexOf('debug=alert')+1) {
    self.debugMode = true;
    self._writeDebug = self._writeDebugAlert;
  }

  this._toggleDebug = function() {
    var o = document.getElementById(self.debugID);
    var oT = document.getElementById(self.debugID+'-toggle');
    if (!o) return false;
    if (self._debugOpen) {
      // minimize
      oT.innerHTML = '+';
      o.style.display = 'none';
    } else {
      oT.innerHTML = '-';
      o.style.display = 'block';
    }
    self._debugOpen = !self._debugOpen;
  }

  this._toggleDebug._protected = true;

  this._debug = function() {
    self._writeDebug('soundManager._debug(): sounds by id/url:',0);
    for (var i=0,j=self.soundIDs.length; i<j; i++) {
      self._writeDebug(self.sounds[self.soundIDs[i]].sID+' | '+self.sounds[self.soundIDs[i]].url,0);
    }
  }

  this._mergeObjects = function(oMain,oAdd) {
    // non-destructive merge
    var o1 = oMain;
    var o2 = (typeof oAdd == 'undefined'?self.defaultOptions:oAdd);
    for (var o in o2) {
      if (typeof o1[o] == 'undefined') o1[o] = o2[o];
    }
    return o1;
  }

  this.createMovie = function(sURL) {
    if (sURL) self.url = sURL;
    self._initMovie();
  }

  this._initMovie = function() {
    // attempt to get, or create, movie
    if (self.o) return false; // pre-init may have fired this function before window.onload(), may already exist
    self.o = self.getMovie(self.id); // try to get flash movie (inline markup)
    if (!self.o) {
      // try to create
      self._createMovie(self.id,self.url);
      self.o = self.getMovie(self.id);
    }
    if (self.o) {
      self._writeDebug('soundManager._initMovie(): Got '+self.o.nodeName+' element ('+(self._didAppend?'created via JS':'static HTML')+')',1);
    }
  }

  this.initComplete = function() {
    if (self._didInit) return false;
    self._didInit = true;
    self._writeDebug('-- SoundManager 2 '+(self._disabled?'failed to load':'loaded')+' ('+(self._disabled?'security/load error':'OK')+') --',1);
    if (self._disabled) {
      self._writeDebug('soundManager.initComplete(): calling soundManager.onerror()',1);
      self.onerror.apply(window);
      return false;
    }
    self._writeDebug('soundManager.initComplete(): calling soundManager.onload()',1);
    try {
      // call user-defined "onload", scoped to window
      self.onload.apply(window);
    } catch(e) {
      // something broke (likely JS error in user function)
      self._writeDebug('soundManager.onload() threw an exception: '+e.message,2);
      throw e; // (so browser/console gets message)
    }
    self._writeDebug('soundManager.onload() complete',1);
  }

  this.init = function() {
    // called after onload()
    // self._initMovie();
    // event cleanup
    self.number_of_init_trials++;
    if (window.removeEventListener) {
      window.removeEventListener('load',self.beginInit,false);
    } else if (window.detachEvent) {
      window.detachEvent('onload',self.beginInit);
    }
    try {
      self.o._externalInterfaceTest(); // attempt to talk to Flash
      self._writeDebug('Flash ExternalInterface call (JS -&gt; Flash) succeeded.',1);
      if (!self.allowPolling) self._writeDebug('Polling (whileloading/whileplaying support) is disabled.',1);
      self.setPolling(true);
      self.enabled = true;
    }  catch(e) {
      if (self.number_of_init_trials < 20) {
        setTimeout(self.init, 1000);
        return false;
      }
      else {
        self._failSafely();
        self.initComplete();
        return false;
      }
    }
    self.initComplete();
  }

  this.beginDelayedInit = function() {
    setTimeout(self.beginInit,200);
  }

  this.beginInit = function() {
    self.createMovie(); // ensure creation if not already done
    self._initMovie();
    setTimeout(self.init,1000); // some delay required, otherwise JS<->Flash/ExternalInterface communication fails under non-IE (?!)
  }

  this.destruct = function() {
    if (self.isSafari) {
      /* --
        Safari 1.3.2 (v312.6)/OSX 10.3.9 and perhaps newer will crash if a sound is actively loading when user exits/refreshes/leaves page
       (Apparently related to ExternalInterface making calls to an unloading/unloaded page?)
       Unloading sounds (detaching handlers and so on) may help to prevent this
      -- */
      for (var i=self.soundIDs.length; i--;) {
        if (self.sounds[self.soundIDs[i]].readyState == 1) self.sounds[self.soundIDs[i]].unload();
      }
    }
    self.disable();
    // self.o = null;
    // self.oMC = null;
  }

}

function SMSound(oSM,oOptions) {
  var self = this;
  var sm = oSM;
  this.sID = oOptions.id;
  this.url = oOptions.url;
  this.options = sm._mergeObjects(oOptions);
  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'])
   */
  }

  self.resetProperties = function(bLoaded) {
    self.bytesLoaded = null;
    self.bytesTotal = null;
    self.position = null;
    self.duration = null;
    self.durationEstimate = null;
    self.loaded = false;
    self.loadSuccess = null;
    self.playState = 0;
    self.paused = false;
    self.readyState = 0; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success
    self.didBeforeFinish = false;
    self.didJustBeforeFinish = false;
  }

  self.resetProperties();

  // --- public methods ---

  this.load = function(oOptions) {
    self.loaded = false;
    self.loadSuccess = null;
    self.readyState = 1;
    self.playState = (oOptions.autoPlay||false); // if autoPlay, assume "playing" is true (no way to detect when it actually starts in Flash unless onPlay is watched?)
    var thisOptions = sm._mergeObjects(oOptions);
    if (typeof thisOptions.url == 'undefined') thisOptions.url = self.url;
    try {
      sm._writeDebug('loading '+thisOptions.url,1);
      sm.o._load(self.sID,thisOptions.url,thisOptions.stream,thisOptions.autoPlay,thisOptions.whileloading?1:0);
    } catch(e) {
      sm._writeDebug('SMSound().load(): JS-&gt;Flash communication failed.',2);
    }
  }

  this.unload = function() {
    // Flash 8/AS2 can't "close" a stream - fake it by loading an empty MP3
    sm._writeDebug('SMSound().unload(): "'+self.sID+'"');
    self.setPosition(0); // reset current sound positioning
    sm.o._unload(self.sID,sm.nullURL);
    // reset load/status flags
    self.resetProperties();
  }

  this.play = function(oOptions) {
    if (!oOptions) oOptions = {};

    // --- TODO: make event handlers specified via oOptions only apply to this instance of play() (eg. onfinish applies but will reset to default on finish)
    if (oOptions.onfinish) self.options.onfinish = oOptions.onfinish;
    if (oOptions.onbeforefinish) self.options.onbeforefinish = oOptions.onbeforefinish;
    if (oOptions.onjustbeforefinish) self.options.onjustbeforefinish = oOptions.onjustbeforefinish;
    if (oOptions.onstop) self.options.onstop = oOptions.onstop;
    if (oOptions.onload) self.options.onload = oOptions.onload;
    if (oOptions.whileloading) self.options.whileloading = oOptions.whileloading;
    if (oOptions.whileplaying) self.options.whileplaying = oOptions.whileplaying;
    // ---

    var thisOptions = sm._mergeObjects(oOptions);
    if (self.playState == 1) {
      // var allowMulti = typeof oOptions.multiShot!='undefined'?oOptions.multiShot:sm.defaultOptions.multiShot;
      var allowMulti = thisOptions.multiShot;
      if (!allowMulti) {
        sm._writeDebug('SMSound.play(): "'+self.sID+'" already playing? (one-shot)',1);
        return false;
      } else {
        sm._writeDebug('SMSound.play(): "'+self.sID+'" already playing (multi-shot)',1);
      }
    }
    if (!self.loaded) {
      if (self.readyState == 0) {
        sm._writeDebug('SMSound.play(): .play() before load request. Attempting to load "'+self.sID+'"',1);
        // try to get this sound playing ASAP
        thisOptions.stream = true;
        thisOptions.autoPlay = true;
        // TODO: need to investigate when false, double-playing
        // if (typeof oOptions.autoPlay=='undefined') thisOptions.autoPlay = true; // only set autoPlay if unspecified here
        self.load(thisOptions); // try to get this sound playing ASAP
      } else if (self.readyState == 2) {
        sm._writeDebug('SMSound.play(): Could not load "'+self.sID+'" - exiting',2);
        return false;
      } else {
        sm._writeDebug('SMSound.play(): "'+self.sID+'" is loading - attempting to play..',1);
      }
    } else {
      sm._writeDebug('SMSound.play(): "'+self.sID+'"');
    }
    if (self.paused) {
      self.resume();
    } else {
      self.playState = 1;
      self.position = (thisOptions.offset||0);
      if (thisOptions.onplay) thisOptions.onplay.apply(self);
      self.setVolume(thisOptions.volume);
      self.setPan(thisOptions.pan);
      if (!thisOptions.autoPlay) {
        // sm._writeDebug('starting sound '+self.sID);
        sm.o._start(self.sID,thisOptions.loop||1,self.position); // TODO: verify !autoPlay doesn't cause issue
      }
    }
  }

  this.start = this.play; // just for convenience

  this.stop = function(bAll) {
    if (self.playState == 1) {
      self.playState = 0;
      self.paused = false;
      if (self.options.onstop) self.options.onstop.apply(self);
      sm.o._stop(self.sID);
    }
  }

  this.setPosition = function(nMsecOffset) {
    // sm._writeDebug('setPosition('+nMsecOffset+')');
    sm.o._setPosition(self.sID,nMsecOffset/1000,self.paused||!self.playState); // if paused or not playing, will not resume (by playing)
  }

  this.pause = function() {
    if (self.paused) return false;
    sm._writeDebug('SMSound.pause()');
    self.paused = true;
    sm.o._pause(self.sID);
  }

  this.resume = function() {
    if (!self.paused) return false;
    sm._writeDebug('SMSound.resume()');
    self.paused = false;
    sm.o._pause(self.sID); // flash method is toggle-based (pause/resume)
  }

  this.togglePause = function() {
    // if playing, pauses - if paused, resumes playing.
    sm._writeDebug('SMSound.togglePause()');
    if (!self.playState) {
      // self.setPosition();
      self.play({offset:self.position/1000});
      return false;
    }
    if (self.paused) {
      sm._writeDebug('SMSound.togglePause(): resuming..');
      self.resume();
    } else {
      sm._writeDebug('SMSound.togglePause(): pausing..');
      self.pause();
    }
  }

  this.setPan = function(nPan) {
    if (typeof nPan == 'undefined') nPan = 0;
    sm.o._setPan(self.sID,nPan);
    self.options.pan = nPan;
  }

  this.setVolume = function(nVol) {
    if (typeof nVol == 'undefined') nVol = 100;
    sm.o._setVolume(self.sID,nVol);
    self.options.volume = nVol;
  }

  // --- "private" methods called by Flash ---

  this._whileloading = function(nBytesLoaded,nBytesTotal,nDuration) {
    self.bytesLoaded = nBytesLoaded;
    self.bytesTotal = nBytesTotal;
    self.duration = nDuration;
    self.durationEstimate = parseInt((self.bytesTotal/self.bytesLoaded)*self.duration); // estimate total time (will only be accurate with CBR MP3s.)
    if (self.readyState != 3 && self.options.whileloading) self.options.whileloading.apply(self);
    // soundManager._writeDebug('duration/durationEst: '+self.duration+' / '+self.durationEstimate);
  }

  this._onid3 = function(oID3PropNames,oID3Data) {
    // oID3PropNames: string array (names)
    // ID3Data: string array (data)
    sm._writeDebug('SMSound()._onid3(): "'+this.sID+'" ID3 data received.');
    var oData = [];
    for (var i=0,j=oID3PropNames.length; i<j; i++) {
      oData[oID3PropNames[i]] = oID3Data[i];
      // sm._writeDebug(oID3PropNames[i]+': '+oID3Data[i]);
    }
    self.id3 = sm._mergeObjects(self.id3,oData);
    if (self.options.onid3) self.options.onid3.apply(self);
  }

  this._whileplaying = function(nPosition) {
    if (isNaN(nPosition) || nPosition == null) return false; // Flash may return NaN at times
    self.position = nPosition;
    if (self.playState == 1) {
      if (self.options.whileplaying) self.options.whileplaying.apply(self); // flash may call after actual finish
      if (self.loaded && self.options.onbeforefinish && self.options.onbeforefinishtime && !self.didBeforeFinish && self.duration-self.position <= self.options.onbeforefinishtime) {
        sm._writeDebug('duration-position &lt;= onbeforefinishtime: '+self.duration+' - '+self.position+' &lt= '+self.options.onbeforefinishtime+' ('+(self.duration-self.position)+')');
        self._onbeforefinish();
      }
    }
  }

  this._onload = function(bSuccess) {
    bSuccess = (bSuccess==1?true:false);
    sm._writeDebug('SMSound._onload(): "'+self.sID+'"'+(bSuccess?' loaded.':' failed to load (or loaded from cache - weird bug) - [<a href="'+self.url+'">test URL</a>]'));
    self.loaded = bSuccess;
    self.loadSuccess = bSuccess;
    self.readyState = bSuccess?3:2;
    if (self.options.onload) self.options.onload.apply(self);
  }

  this._onbeforefinish = function() {
    if (!self.didBeforeFinish) {
      self.didBeforeFinish = true;
      if (self.options.onbeforefinish) self.options.onbeforefinish.apply(self);
    }
  }

  this._onjustbeforefinish = function(msOffset) {
    // msOffset: "end of sound" delay actual value (eg. 200 msec, value at event fire time was 187)
    if (!self.didJustBeforeFinish) {
      self.didJustBeforeFinish = true;
      // soundManager._writeDebug('SMSound._onjustbeforefinish()');
      if (self.options.onjustbeforefinish) self.options.onjustbeforefinish.apply(self);;
    }
  }

  this._onfinish = function() {
    // sound has finished playing
    sm._writeDebug('SMSound._onfinish(): "'+self.sID+'"');
    self.playState = 0;
    self.paused = false;
    if (self.options.onfinish) self.options.onfinish.apply(self);
    if (self.options.onbeforefinishcomplete) self.options.onbeforefinishcomplete.apply(self);
    // reset some state items
    self.setPosition(0);
    self.didBeforeFinish = false;
    self.didJustBeforeFinish = false;
  }

}

var soundManager = new SoundManager('/static/swf/soundmanager2.swf');

// attach onload handler
if (window.addEventListener) {
  window.addEventListener('load',soundManager.beginDelayedInit,false);
  window.addEventListener('unload',soundManager.destruct,false);
} else if (window.attachEvent) {
  window.attachEvent('onload',soundManager.beginInit);
  window.attachEvent('unload',soundManager.destruct);
} else {
  // no add/attachevent support - safe to assume no JS->Flash either.
  soundManager.onerror();
  soundManager.disable();
}

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/interface-1.2.js"></script> */
/**
 * Interface Elements for jQuery
 * 
 * http://interface.eyecon.ro
 * 
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt) 
 * and GPL (GPL-LICENSE.txt) licenses.
 *   
 *
 */
 eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('k.f2={2r:u(M){E q.1E(u(){if(!M.aR||!M.aZ)E;D el=q;el.2l={aq:M.aq||cO,aR:M.aR,aZ:M.aZ,8e:M.8e||\'fV\',aJ:M.aJ||\'fV\',2Y:M.2Y&&2g M.2Y==\'u\'?M.2Y:I,3i:M.2Y&&2g M.3i==\'u\'?M.3i:I,7U:M.7U&&2g M.7U==\'u\'?M.7U:I,as:k(M.aR,q),8f:k(M.aZ,q),H:M.H||8J,67:M.67||0};el.2l.8f.2G().B(\'W\',\'9R\').eq(0).B({W:el.2l.aq+\'U\',19:\'2B\'}).2T();el.2l.as.1E(u(2N){q.7X=2N}).gC(u(){k(q).2R(el.2l.aJ)},u(){k(q).4i(el.2l.aJ)}).1J(\'5h\',u(e){if(el.2l.67==q.7X)E;el.2l.as.eq(el.2l.67).4i(el.2l.8e).2T().eq(q.7X).2R(el.2l.8e).2T();el.2l.8f.eq(el.2l.67).5w({W:0},el.2l.H,u(){q.14.19=\'1o\';if(el.2l.3i){el.2l.3i.1D(el,[q])}}).2T().eq(q.7X).1Y().5w({W:el.2l.aq},el.2l.H,u(){q.14.19=\'2B\';if(el.2l.2Y){el.2l.2Y.1D(el,[q])}}).2T();if(el.2l.7U){el.2l.7U.1D(el,[q,el.2l.8f.K(q.7X),el.2l.as.K(el.2l.67),el.2l.8f.K(el.2l.67)])}el.2l.67=q.7X}).eq(0).2R(el.2l.8e).2T();k(q).B(\'W\',k(q).B(\'W\')).B(\'2U\',\'2K\')})}};k.fn.gN=k.f2.2r;k.aA={2r:u(M){E q.1E(u(){D el=q;D 7E=2*18.2Q/f1;D an=2*18.2Q;if(k(el).B(\'Y\')!=\'2s\'&&k(el).B(\'Y\')!=\'1P\'){k(el).B(\'Y\',\'2s\')}el.1l={1R:k(M.1R,q),2F:M.2F,6q:M.6q,aD:M.aD,an:an,1N:k.1a.2o(q),Y:k.1a.3w(q),26:18.2Q/2,bi:M.bi,8p:M.6r,6r:[],aG:I,7E:2*18.2Q/f1};el.1l.fB=(el.1l.1N.w-el.1l.2F)/2;el.1l.7D=(el.1l.1N.h-el.1l.6q-el.1l.6q*el.1l.8p)/2;el.1l.2D=2*18.2Q/el.1l.1R.1N();el.1l.ba=el.1l.1N.w/2;el.1l.b9=el.1l.1N.h/2-el.1l.6q*el.1l.8p;D ak=1h.3F(\'22\');k(ak).B({Y:\'1P\',3I:1,Q:0,O:0});k(el).1S(ak);el.1l.1R.1E(u(2N){a6=k(\'1T\',q).K(0);W=T(el.1l.6q*el.1l.8p);if(k.3a.4t){3E=1h.3F(\'1T\');k(3E).B(\'Y\',\'1P\');3E.2J=a6.2J;3E.14.5E=\'gE 9n:9w.9y.cC(1G=60, 14=1, gB=0, gA=0, gv=0, gF=0)\'}P{3E=1h.3F(\'3E\');if(3E.fD){4L=3E.fD("2d");3E.14.Y=\'1P\';3E.14.W=W+\'U\';3E.14.Z=el.1l.2F+\'U\';3E.W=W;3E.Z=el.1l.2F;4L.gu();4L.gO(0,W);4L.gk(1,-1);4L.gp(a6,0,0,el.1l.2F,W);4L.6H();4L.gm="gG-4l";D ap=4L.hy(0,0,0,W);ap.fs(1,"fr(1V, 1V, 1V, 1)");ap.fs(0,"fr(1V, 1V, 1V, 0.6)");4L.hx=ap;if(hA.hB.3J(\'hw\')!=-1){4L.hv()}P{4L.hu(0,0,el.1l.2F,W)}}}el.1l.6r[2N]=3E;k(ak).1S(3E)}).1J(\'9z\',u(e){el.1l.aG=1b;el.1l.H=el.1l.7E*0.1*el.1l.H/18.3S(el.1l.H);E I}).1J(\'8B\',u(e){el.1l.aG=I;E I});k.aA.7T(el);el.1l.H=el.1l.7E*0.2;el.1l.ht=1X.6V(u(){el.1l.26+=el.1l.H;if(el.1l.26>an)el.1l.26=0;k.aA.7T(el)},20);k(el).1J(\'8B\',u(){el.1l.H=el.1l.7E*0.2*el.1l.H/18.3S(el.1l.H)}).1J(\'3D\',u(e){if(el.1l.aG==I){1s=k.1a.4a(e);fz=el.1l.1N.w-1s.x+el.1l.Y.x;el.1l.H=el.1l.bi*el.1l.7E*(el.1l.1N.w/2-fz)/(el.1l.1N.w/2)}})})},7T:u(el){el.1l.1R.1E(u(2N){b8=el.1l.26+2N*el.1l.2D;x=el.1l.fB*18.5H(b8);y=el.1l.7D*18.83(b8);f9=T(2a*(el.1l.7D+y)/(2*el.1l.7D));fk=(el.1l.7D+y)/(2*el.1l.7D);Z=T((el.1l.2F-el.1l.aD)*fk+el.1l.aD);W=T(Z*el.1l.6q/el.1l.2F);q.14.Q=el.1l.b9+y-W/2+"U";q.14.O=el.1l.ba+x-Z/2+"U";q.14.Z=Z+"U";q.14.W=W+"U";q.14.3I=f9;el.1l.6r[2N].14.Q=T(el.1l.b9+y+W-1-W/2)+"U";el.1l.6r[2N].14.O=T(el.1l.ba+x-Z/2)+"U";el.1l.6r[2N].14.Z=Z+"U";el.1l.6r[2N].14.W=T(W*el.1l.8p)+"U"})}};k.fn.hI=k.aA.2r;k.23({G:{c8:u(p,n,1W,1H,1m){E((-18.5H(p*18.2Q)/2)+0.5)*1H+1W},hK:u(p,n,1W,1H,1m){E 1H*(n/=1m)*n*n+1W},fl:u(p,n,1W,1H,1m){E-1H*((n=n/1m-1)*n*n*n-1)+1W},hm:u(p,n,1W,1H,1m){if((n/=1m/2)<1)E 1H/2*n*n*n*n+1W;E-1H/2*((n-=2)*n*n*n-2)+1W},8l:u(p,n,1W,1H,1m){if((n/=1m)<(1/2.75)){E 1H*(7.aB*n*n)+1W}P if(n<(2/2.75)){E 1H*(7.aB*(n-=(1.5/2.75))*n+.75)+1W}P if(n<(2.5/2.75)){E 1H*(7.aB*(n-=(2.25/2.75))*n+.gY)+1W}P{E 1H*(7.aB*(n-=(2.h2/2.75))*n+.gX)+1W}},cr:u(p,n,1W,1H,1m){if(k.G.8l)E 1H-k.G.8l(p,1m-n,0,1H,1m)+1W;E 1W+1H},gW:u(p,n,1W,1H,1m){if(k.G.cr&&k.G.8l)if(n<1m/2)E k.G.cr(p,n*2,0,1H,1m)*.5+1W;E k.G.8l(p,n*2-1m,0,1H,1m)*.5+1H*.5+1W;E 1W+1H},gQ:u(p,n,1W,1H,1m){D a,s;if(n==0)E 1W;if((n/=1m)==1)E 1W+1H;a=1H*0.3;p=1m*.3;if(a<18.3S(1H)){a=1H;s=p/4}P{s=p/(2*18.2Q)*18.cb(1H/a)}E-(a*18.6b(2,10*(n-=1))*18.83((n*1m-s)*(2*18.2Q)/p))+1W},gT:u(p,n,1W,1H,1m){D a,s;if(n==0)E 1W;if((n/=1m/2)==2)E 1W+1H;a=1H*0.3;p=1m*.3;if(a<18.3S(1H)){a=1H;s=p/4}P{s=p/(2*18.2Q)*18.cb(1H/a)}E a*18.6b(2,-10*n)*18.83((n*1m-s)*(2*18.2Q)/p)+1H+1W},gV:u(p,n,1W,1H,1m){D a,s;if(n==0)E 1W;if((n/=1m/2)==2)E 1W+1H;a=1H*0.3;p=1m*.3;if(a<18.3S(1H)){a=1H;s=p/4}P{s=p/(2*18.2Q)*18.cb(1H/a)}if(n<1){E-.5*(a*18.6b(2,10*(n-=1))*18.83((n*1m-s)*(2*18.2Q)/p))+1W}E a*18.6b(2,-10*(n-=1))*18.83((n*1m-s)*(2*18.2Q)/p)*.5+1H+1W}}});k.6n={2r:u(M){E q.1E(u(){D el=q;el.1F={1R:k(M.1R,q),1Z:k(M.1Z,q),1M:k.1a.3w(q),2F:M.2F,ax:M.ax,7Y:M.7Y,ge:M.ge,51:M.51,6x:M.6x};k.6n.aH(el,0);k(1X).1J(\'gU\',u(){el.1F.1M=k.1a.3w(el);k.6n.aH(el,0);k.6n.7T(el)});k.6n.7T(el);el.1F.1R.1J(\'9z\',u(){k(el.1F.ax,q).K(0).14.19=\'2B\'}).1J(\'8B\',u(){k(el.1F.ax,q).K(0).14.19=\'1o\'});k(1h).1J(\'3D\',u(e){D 1s=k.1a.4a(e);D 5s=0;if(el.1F.51&&el.1F.51==\'cv\')D aI=1s.x-el.1F.1M.x-(el.4c-el.1F.2F*el.1F.1R.1N())/2-el.1F.2F/2;P if(el.1F.51&&el.1F.51==\'2L\')D aI=1s.x-el.1F.1M.x-el.4c+el.1F.2F*el.1F.1R.1N();P D aI=1s.x-el.1F.1M.x;D fP=18.6b(1s.y-el.1F.1M.y-el.5W/2,2);el.1F.1R.1E(u(2N){45=18.ez(18.6b(aI-2N*el.1F.2F,2)+fP);45-=el.1F.2F/2;45=45<0?0:45;45=45>el.1F.7Y?el.1F.7Y:45;45=el.1F.7Y-45;bB=el.1F.6x*45/el.1F.7Y;q.14.Z=el.1F.2F+bB+\'U\';q.14.O=el.1F.2F*2N+5s+\'U\';5s+=bB});k.6n.aH(el,5s)})})},aH:u(el,5s){if(el.1F.51)if(el.1F.51==\'cv\')el.1F.1Z.K(0).14.O=(el.4c-el.1F.2F*el.1F.1R.1N())/2-5s/2+\'U\';P if(el.1F.51==\'O\')el.1F.1Z.K(0).14.O=-5s/el.1F.1R.1N()+\'U\';P if(el.1F.51==\'2L\')el.1F.1Z.K(0).14.O=(el.4c-el.1F.2F*el.1F.1R.1N())-5s/2+\'U\';el.1F.1Z.K(0).14.Z=el.1F.2F*el.1F.1R.1N()+5s+\'U\'},7T:u(el){el.1F.1R.1E(u(2N){q.14.Z=el.1F.2F+\'U\';q.14.O=el.1F.2F*2N+\'U\'})}};k.fn.hi=k.6n.2r;k.N={1c:S,8R:S,3A:S,2I:S,4y:S,cl:S,1d:S,2h:S,1R:S,5o:u(){k.N.8R.5o();if(k.N.3A){k.N.3A.2G()}},4w:u(){k.N.1R=S;k.N.2h=S;k.N.4y=k.N.1d.2y;if(k.N.1c.B(\'19\')==\'2B\'){if(k.N.1d.1f.fx){3m(k.N.1d.1f.fx.1u){1e\'c6\':k.N.1c.7a(k.N.1d.1f.fx.1m,k.N.5o);1r;1e\'1z\':k.N.1c.fq(k.N.1d.1f.fx.1m,k.N.5o);1r;1e\'a7\':k.N.1c.g3(k.N.1d.1f.fx.1m,k.N.5o);1r}}P{k.N.1c.2G()}if(k.N.1d.1f.3i)k.N.1d.1f.3i.1D(k.N.1d,[k.N.1c,k.N.3A])}P{k.N.5o()}1X.bH(k.N.2I)},dQ:u(){D 1d=k.N.1d;D 4d=k.N.aY(1d);if(1d&&4d.3o!=k.N.4y&&4d.3o.1g>=1d.1f.aL){k.N.4y=4d.3o;k.N.cl=4d.3o;81={2n:k(1d).1p(\'hj\')||\'2n\',2y:4d.3o};k.hl({1u:\'hk\',81:k.hf(81),he:u(fZ){1d.1f.4e=k(\'3o\',fZ);1N=1d.1f.4e.1N();if(1N>0){D 5p=\'\';1d.1f.4e.1E(u(2N){5p+=\'<8P 4I="\'+k(\'2y\',q).3g()+\'" 8K="\'+2N+\'" 14="9b: ad;">\'+k(\'3g\',q).3g()+\'</8P>\'});if(1d.1f.aU){D 3M=k(\'2y\',1d.1f.4e.K(0)).3g();1d.2y=4d.3j+3M+1d.1f.3N+4d.66;k.N.6J(1d,4d.3o.1g!=3M.1g?(4d.3j.1g+4d.3o.1g):3M.1g,4d.3o.1g!=3M.1g?(4d.3j.1g+3M.1g):3M.1g)}if(1N>0){k.N.cj(1d,5p)}P{k.N.4w()}}P{k.N.4w()}},5N:1d.1f.aN})}},cj:u(1d,5p){k.N.8R.3x(5p);k.N.1R=k(\'8P\',k.N.8R.K(0));k.N.1R.9z(k.N.di).1J(\'5h\',k.N.dj);D Y=k.1a.3w(1d);D 1N=k.1a.2o(1d);k.N.1c.B(\'Q\',Y.y+1N.hb+\'U\').B(\'O\',Y.x+\'U\').2R(1d.1f.aM);if(k.N.3A){k.N.3A.B(\'19\',\'2B\').B(\'Q\',Y.y+1N.hb+\'U\').B(\'O\',Y.x+\'U\').B(\'Z\',k.N.1c.B(\'Z\')).B(\'W\',k.N.1c.B(\'W\'))}k.N.2h=0;k.N.1R.K(0).3l=1d.1f.7H;k.N.8Q(1d,1d.1f.4e.K(0),\'7J\');if(k.N.1c.B(\'19\')==\'1o\'){if(1d.1f.bV){D cp=k.1a.aT(1d,1b);D cm=k.1a.6U(1d,1b);k.N.1c.B(\'Z\',1d.4c-(k.dF?(cp.l+cp.r+cm.l+cm.r):0)+\'U\')}if(1d.1f.fx){3m(1d.1f.fx.1u){1e\'c6\':k.N.1c.7f(1d.1f.fx.1m);1r;1e\'1z\':k.N.1c.fo(1d.1f.fx.1m);1r;1e\'a7\':k.N.1c.gb(1d.1f.fx.1m);1r}}P{k.N.1c.1Y()}if(k.N.1d.1f.2Y)k.N.1d.1f.2Y.1D(k.N.1d,[k.N.1c,k.N.3A])}},dO:u(){D 1d=q;if(1d.1f.4e){k.N.4y=1d.2y;k.N.cl=1d.2y;D 5p=\'\';1d.1f.4e.1E(u(2N){2y=k(\'2y\',q).3g().6c();fY=1d.2y.6c();if(2y.3J(fY)==0){5p+=\'<8P 4I="\'+k(\'2y\',q).3g()+\'" 8K="\'+2N+\'" 14="9b: ad;">\'+k(\'3g\',q).3g()+\'</8P>\'}});if(5p!=\'\'){k.N.cj(1d,5p);q.1f.9x=1b;E}}1d.1f.4e=S;q.1f.9x=I},6J:u(2n,26,2T){if(2n.b1){D 6t=2n.b1();6t.hp(1b);6t.dI("ck",26);6t.ha("ck",-2T+26);6t.8C()}P if(2n.aF){2n.aF(26,2T)}P{if(2n.5q){2n.5q=26;2n.dN=2T}}2n.6K()},f0:u(2n){if(2n.5q)E 2n.5q;P if(2n.b1){D 6t=1h.6J.dZ();D eX=6t.h9();E 0-eX.dI(\'ck\',-h6)}},aY:u(2n){D 4P={2y:2n.2y,3j:\'\',66:\'\',3o:\'\'};if(2n.1f.aQ){D 8N=I;D 5q=k.N.f0(2n)||0;D 4T=4P.2y.7C(2n.1f.3N);24(D i=0;i<4T.1g;i++){if((4P.3j.1g+4T[i].1g>=5q||5q==0)&&!8N){if(4P.3j.1g<=5q)4P.3o=4T[i];P 4P.66+=4T[i]+(4T[i]!=\'\'?2n.1f.3N:\'\');8N=1b}P if(8N){4P.66+=4T[i]+(4T[i]!=\'\'?2n.1f.3N:\'\')}if(!8N){4P.3j+=4T[i]+(4T.1g>1?2n.1f.3N:\'\')}}}P{4P.3o=4P.2y}E 4P},bU:u(e){1X.bH(k.N.2I);D 1d=k.N.aY(q);D 3K=e.7L||e.7K||-1;if(/13|27|35|36|38|40|9/.48(3K)&&k.N.1R){if(1X.2k){1X.2k.bT=1b;1X.2k.c0=I}P{e.aP();e.aW()}if(k.N.2h!=S)k.N.1R.K(k.N.2h||0).3l=\'\';P k.N.2h=-1;3m(3K){1e 9:1e 13:if(k.N.2h==-1)k.N.2h=0;D 2h=k.N.1R.K(k.N.2h||0);D 3M=2h.5C(\'4I\');q.2y=1d.3j+3M+q.1f.3N+1d.66;k.N.4y=1d.3o;k.N.6J(q,1d.3j.1g+3M.1g+q.1f.3N.1g,1d.3j.1g+3M.1g+q.1f.3N.1g);k.N.4w();if(q.1f.68){4u=T(2h.5C(\'8K\'))||0;k.N.8Q(q,q.1f.4e.K(4u),\'68\')}if(q.7W)q.7W(I);E 3K!=13;1r;1e 27:q.2y=1d.3j+k.N.4y+q.1f.3N+1d.66;q.1f.4e=S;k.N.4w();if(q.7W)q.7W(I);E I;1r;1e 35:k.N.2h=k.N.1R.1N()-1;1r;1e 36:k.N.2h=0;1r;1e 38:k.N.2h--;if(k.N.2h<0)k.N.2h=k.N.1R.1N()-1;1r;1e 40:k.N.2h++;if(k.N.2h==k.N.1R.1N())k.N.2h=0;1r}k.N.8Q(q,q.1f.4e.K(k.N.2h||0),\'7J\');k.N.1R.K(k.N.2h||0).3l=q.1f.7H;if(k.N.1R.K(k.N.2h||0).7W)k.N.1R.K(k.N.2h||0).7W(I);if(q.1f.aU){D aK=k.N.1R.K(k.N.2h||0).5C(\'4I\');q.2y=1d.3j+aK+q.1f.3N+1d.66;if(k.N.4y.1g!=aK.1g)k.N.6J(q,1d.3j.1g+k.N.4y.1g,1d.3j.1g+aK.1g)}E I}k.N.dO.1D(q);if(q.1f.9x==I){if(1d.3o!=k.N.4y&&1d.3o.1g>=q.1f.aL)k.N.2I=1X.9T(k.N.dQ,q.1f.54);if(k.N.1R){k.N.4w()}}E 1b},8Q:u(2n,3o,1u){if(2n.1f[1u]){D 81={};ar=3o.f3(\'*\');24(i=0;i<ar.1g;i++){81[ar[i].4Y]=ar[i].7c.h4}2n.1f[1u].1D(2n,[81])}},di:u(e){if(k.N.1R){if(k.N.2h!=S)k.N.1R.K(k.N.2h||0).3l=\'\';k.N.1R.K(k.N.2h||0).3l=\'\';k.N.2h=T(q.5C(\'8K\'))||0;k.N.1R.K(k.N.2h||0).3l=k.N.1d.1f.7H}},dj:u(2k){1X.bH(k.N.2I);2k=2k||k.2k.gS(1X.2k);2k.aP();2k.aW();D 1d=k.N.aY(k.N.1d);D 3M=q.5C(\'4I\');k.N.1d.2y=1d.3j+3M+k.N.1d.1f.3N+1d.66;k.N.4y=q.5C(\'4I\');k.N.6J(k.N.1d,1d.3j.1g+3M.1g+k.N.1d.1f.3N.1g,1d.3j.1g+3M.1g+k.N.1d.1f.3N.1g);k.N.4w();if(k.N.1d.1f.68){4u=T(q.5C(\'8K\'))||0;k.N.8Q(k.N.1d,k.N.1d.1f.4e.K(4u),\'68\')}E I},eJ:u(e){3K=e.7L||e.7K||-1;if(/13|27|35|36|38|40/.48(3K)&&k.N.1R){if(1X.2k){1X.2k.bT=1b;1X.2k.c0=I}P{e.aP();e.aW()}E I}},2r:u(M){if(!M.aN||!k.1a){E}if(!k.N.1c){if(k.3a.4t){k(\'2e\',1h).1S(\'<3A 14="19:1o;Y:1P;5E:9n:9w.9y.cC(1G=0);" id="ds" 2J="ek:I;" ej="0" ep="cD"></3A>\');k.N.3A=k(\'#ds\')}k(\'2e\',1h).1S(\'<22 id="dr" 14="Y: 1P; Q: 0; O: 0; z-cZ: h3; 19: 1o;"><9h 14="6w: 0;8F: 0; h1-14: 1o; z-cZ: h0;">&7k;</9h></22>\');k.N.1c=k(\'#dr\');k.N.8R=k(\'9h\',k.N.1c)}E q.1E(u(){if(q.4Y!=\'ch\'&&q.5C(\'1u\')!=\'3g\')E;q.1f={};q.1f.aN=M.aN;q.1f.aL=18.3S(T(M.aL)||1);q.1f.aM=M.aM?M.aM:\'\';q.1f.7H=M.7H?M.7H:\'\';q.1f.68=M.68&&M.68.1K==2A?M.68:S;q.1f.2Y=M.2Y&&M.2Y.1K==2A?M.2Y:S;q.1f.3i=M.3i&&M.3i.1K==2A?M.3i:S;q.1f.7J=M.7J&&M.7J.1K==2A?M.7J:S;q.1f.bV=M.bV||I;q.1f.aQ=M.aQ||I;q.1f.3N=q.1f.aQ?(M.3N||\', \'):\'\';q.1f.aU=M.aU?1b:I;q.1f.54=18.3S(T(M.54)||aC);if(M.fx&&M.fx.1K==7M){if(!M.fx.1u||!/c6|1z|a7/.48(M.fx.1u)){M.fx.1u=\'1z\'}if(M.fx.1u==\'1z\'&&!k.fx.1z)E;if(M.fx.1u==\'a7\'&&!k.fx.61)E;M.fx.1m=18.3S(T(M.fx.1m)||8J);if(M.fx.1m>q.1f.54){M.fx.1m=q.1f.54-2a}q.1f.fx=M.fx}q.1f.4e=S;q.1f.9x=I;k(q).1p(\'bU\',\'eN\').6K(u(){k.N.1d=q;k.N.4y=q.2y}).dH(k.N.eJ).6y(k.N.bU).5B(u(){k.N.2I=1X.9T(k.N.4w,hM)})})}};k.fn.hR=k.N.2r;k.1y={2I:S,4Q:S,29:S,2D:10,26:u(el,4J,2D,eG){k.1y.4Q=el;k.1y.29=4J;k.1y.2D=T(2D)||10;k.1y.2I=1X.6V(k.1y.eF,T(eG)||40)},eF:u(){24(i=0;i<k.1y.29.1g;i++){if(!k.1y.29[i].2X){k.1y.29[i].2X=k.23(k.1a.7G(k.1y.29[i]),k.1a.74(k.1y.29[i]),k.1a.6z(k.1y.29[i]))}P{k.1y.29[i].2X.t=k.1y.29[i].3d;k.1y.29[i].2X.l=k.1y.29[i].3c}if(k.1y.4Q.A&&k.1y.4Q.A.7q==1b){69={x:k.1y.4Q.A.2v,y:k.1y.4Q.A.2q,1C:k.1y.4Q.A.1B.1C,hb:k.1y.4Q.A.1B.hb}}P{69=k.23(k.1a.7G(k.1y.4Q),k.1a.74(k.1y.4Q))}if(k.1y.29[i].2X.t>0&&k.1y.29[i].2X.y+k.1y.29[i].2X.t>69.y){k.1y.29[i].3d-=k.1y.2D}P if(k.1y.29[i].2X.t<=k.1y.29[i].2X.h&&k.1y.29[i].2X.t+k.1y.29[i].2X.hb<69.y+69.hb){k.1y.29[i].3d+=k.1y.2D}if(k.1y.29[i].2X.l>0&&k.1y.29[i].2X.x+k.1y.29[i].2X.l>69.x){k.1y.29[i].3c-=k.1y.2D}P if(k.1y.29[i].2X.l<=k.1y.29[i].2X.hP&&k.1y.29[i].2X.l+k.1y.29[i].2X.1C<69.x+69.1C){k.1y.29[i].3c+=k.1y.2D}}},8o:u(){1X.5T(k.1y.2I);k.1y.4Q=S;k.1y.29=S;24(i in k.1y.29){k.1y.29[i].2X=S}}};k.11={1c:S,F:S,4U:u(){E q.1E(u(){if(q.9I){q.A.5e.3q(\'5v\',k.11.bN);q.A=S;q.9I=I;if(k.3a.4t){q.bE="eN"}P{q.14.hq=\'\';q.14.e1=\'\';q.14.e7=\'\'}}})},bN:u(e){if(k.11.F!=S){k.11.9A(e);E I}D C=q.3U;k(1h).1J(\'3D\',k.11.bX).1J(\'5P\',k.11.9A);C.A.1s=k.1a.4a(e);C.A.4B=C.A.1s;C.A.7q=I;C.A.ho=q!=q.3U;k.11.F=C;if(C.A.5i&&q!=q.3U){bS=k.1a.3w(C.31);bQ=k.1a.2o(C);bR={x:T(k.B(C,\'O\'))||0,y:T(k.B(C,\'Q\'))||0};dx=C.A.4B.x-bS.x-bQ.1C/2-bR.x;dy=C.A.4B.y-bS.y-bQ.hb/2-bR.y;k.3b.5c(C,[dx,dy])}E k.7n||I},ea:u(e){D C=k.11.F;C.A.7q=1b;D 9G=C.14;C.A.7V=k.B(C,\'19\');C.A.4n=k.B(C,\'Y\');if(!C.A.cz)C.A.cz=C.A.4n;C.A.2c={x:T(k.B(C,\'O\'))||0,y:T(k.B(C,\'Q\'))||0};C.A.9B=0;C.A.ai=0;if(k.3a.4t){D bW=k.1a.6U(C,1b);C.A.9B=bW.l||0;C.A.ai=bW.t||0}C.A.1B=k.23(k.1a.3w(C),k.1a.2o(C));if(C.A.4n!=\'2s\'&&C.A.4n!=\'1P\'){9G.Y=\'2s\'}k.11.1c.5o();D 5g=C.fI(1b);k(5g).B({19:\'2B\',O:\'2P\',Q:\'2P\'});5g.14.5K=\'0\';5g.14.5z=\'0\';5g.14.5k=\'0\';5g.14.5j=\'0\';k.11.1c.1S(5g);D 3Y=k.11.1c.K(0).14;if(C.A.bD){3Y.Z=\'9F\';3Y.W=\'9F\'}P{3Y.W=C.A.1B.hb+\'U\';3Y.Z=C.A.1B.1C+\'U\'}3Y.19=\'2B\';3Y.5K=\'2P\';3Y.5z=\'2P\';3Y.5k=\'2P\';3Y.5j=\'2P\';k.23(C.A.1B,k.1a.2o(5g));if(C.A.2V){if(C.A.2V.O){C.A.2c.x+=C.A.1s.x-C.A.1B.x-C.A.2V.O;C.A.1B.x=C.A.1s.x-C.A.2V.O}if(C.A.2V.Q){C.A.2c.y+=C.A.1s.y-C.A.1B.y-C.A.2V.Q;C.A.1B.y=C.A.1s.y-C.A.2V.Q}if(C.A.2V.2L){C.A.2c.x+=C.A.1s.x-C.A.1B.x-C.A.1B.hb+C.A.2V.2L;C.A.1B.x=C.A.1s.x-C.A.1B.1C+C.A.2V.2L}if(C.A.2V.4D){C.A.2c.y+=C.A.1s.y-C.A.1B.y-C.A.1B.hb+C.A.2V.4D;C.A.1B.y=C.A.1s.y-C.A.1B.hb+C.A.2V.4D}}C.A.2v=C.A.2c.x;C.A.2q=C.A.2c.y;if(C.A.8s||C.A.2p==\'94\'){8U=k.1a.6U(C.31,1b);C.A.1B.x=C.8t+(k.3a.4t?0:k.3a.7I?-8U.l:8U.l);C.A.1B.y=C.8G+(k.3a.4t?0:k.3a.7I?-8U.t:8U.t);k(C.31).1S(k.11.1c.K(0))}if(C.A.2p){k.11.c5(C);C.A.5t.2p=k.11.ce}if(C.A.5i){k.3b.ct(C)}3Y.O=C.A.1B.x-C.A.9B+\'U\';3Y.Q=C.A.1B.y-C.A.ai+\'U\';3Y.Z=C.A.1B.1C+\'U\';3Y.W=C.A.1B.hb+\'U\';k.11.F.A.9E=I;if(C.A.gx){C.A.5t.6a=k.11.c7}if(C.A.3I!=I){k.11.1c.B(\'3I\',C.A.3I)}if(C.A.1G){k.11.1c.B(\'1G\',C.A.1G);if(1X.71){k.11.1c.B(\'5E\',\'8V(1G=\'+C.A.1G*2a+\')\')}}if(C.A.7O){k.11.1c.2R(C.A.7O);k.11.1c.K(0).7c.14.19=\'1o\'}if(C.A.4o)C.A.4o.1D(C,[5g,C.A.2c.x,C.A.2c.y]);if(k.1x&&k.1x.8D>0){k.1x.ed(C)}if(C.A.46==I){9G.19=\'1o\'}E I},c5:u(C){if(C.A.2p.1K==b0){if(C.A.2p==\'94\'){C.A.28=k.23({x:0,y:0},k.1a.2o(C.31));D 8S=k.1a.6U(C.31,1b);C.A.28.w=C.A.28.1C-8S.l-8S.r;C.A.28.h=C.A.28.hb-8S.t-8S.b}P if(C.A.2p==\'1h\'){D bY=k.1a.bm();C.A.28={x:0,y:0,w:bY.w,h:bY.h}}}P if(C.A.2p.1K==7F){C.A.28={x:T(C.A.2p[0])||0,y:T(C.A.2p[1])||0,w:T(C.A.2p[2])||0,h:T(C.A.2p[3])||0}}C.A.28.dx=C.A.28.x-C.A.1B.x;C.A.28.dy=C.A.28.y-C.A.1B.y},9H:u(F){if(F.A.8s||F.A.2p==\'94\'){k(\'2e\',1h).1S(k.11.1c.K(0))}k.11.1c.5o().2G().B(\'1G\',1);if(1X.71){k.11.1c.B(\'5E\',\'8V(1G=2a)\')}},9A:u(e){k(1h).3q(\'3D\',k.11.bX).3q(\'5P\',k.11.9A);if(k.11.F==S){E}D F=k.11.F;k.11.F=S;if(F.A.7q==I){E I}if(F.A.44==1b){k(F).B(\'Y\',F.A.4n)}D 9G=F.14;if(F.5i){k.11.1c.B(\'9b\',\'8j\')}if(F.A.7O){k.11.1c.4i(F.A.7O)}if(F.A.6N==I){if(F.A.fx>0){if(!F.A.1O||F.A.1O==\'4j\'){D x=12 k.fx(F,{1m:F.A.fx},\'O\');x.1L(F.A.2c.x,F.A.8y)}if(!F.A.1O||F.A.1O==\'49\'){D y=12 k.fx(F,{1m:F.A.fx},\'Q\');y.1L(F.A.2c.y,F.A.8v)}}P{if(!F.A.1O||F.A.1O==\'4j\')F.14.O=F.A.8y+\'U\';if(!F.A.1O||F.A.1O==\'49\')F.14.Q=F.A.8v+\'U\'}k.11.9H(F);if(F.A.46==I){k(F).B(\'19\',F.A.7V)}}P if(F.A.fx>0){F.A.9E=1b;D dh=I;if(k.1x&&k.1t&&F.A.44){dh=k.1a.3w(k.1t.1c.K(0))}k.11.1c.5w({O:dh?dh.x:F.A.1B.x,Q:dh?dh.y:F.A.1B.y},F.A.fx,u(){F.A.9E=I;if(F.A.46==I){F.14.19=F.A.7V}k.11.9H(F)})}P{k.11.9H(F);if(F.A.46==I){k(F).B(\'19\',F.A.7V)}}if(k.1x&&k.1x.8D>0){k.1x.eO(F)}if(k.1t&&F.A.44){k.1t.fC(F)}if(F.A.2Z&&(F.A.8y!=F.A.2c.x||F.A.8v!=F.A.2c.y)){F.A.2Z.1D(F,F.A.b3||[0,0,F.A.8y,F.A.8v])}if(F.A.3T)F.A.3T.1D(F);E I},c7:u(x,y,dx,dy){if(dx!=0)dx=T((dx+(q.A.gx*dx/18.3S(dx))/2)/q.A.gx)*q.A.gx;if(dy!=0)dy=T((dy+(q.A.gy*dy/18.3S(dy))/2)/q.A.gy)*q.A.gy;E{dx:dx,dy:dy,x:0,y:0}},ce:u(x,y,dx,dy){dx=18.3L(18.3r(dx,q.A.28.dx),q.A.28.w+q.A.28.dx-q.A.1B.1C);dy=18.3L(18.3r(dy,q.A.28.dy),q.A.28.h+q.A.28.dy-q.A.1B.hb);E{dx:dx,dy:dy,x:0,y:0}},bX:u(e){if(k.11.F==S||k.11.F.A.9E==1b){E}D F=k.11.F;F.A.4B=k.1a.4a(e);if(F.A.7q==I){45=18.ez(18.6b(F.A.1s.x-F.A.4B.x,2)+18.6b(F.A.1s.y-F.A.4B.y,2));if(45<F.A.6M){E}P{k.11.ea(e)}}D dx=F.A.4B.x-F.A.1s.x;D dy=F.A.4B.y-F.A.1s.y;24(D i in F.A.5t){D 3y=F.A.5t[i].1D(F,[F.A.2c.x+dx,F.A.2c.y+dy,dx,dy]);if(3y&&3y.1K==7M){dx=i!=\'7R\'?3y.dx:(3y.x-F.A.2c.x);dy=i!=\'7R\'?3y.dy:(3y.y-F.A.2c.y)}}F.A.2v=F.A.1B.x+dx-F.A.9B;F.A.2q=F.A.1B.y+dy-F.A.ai;if(F.A.5i&&(F.A.3H||F.A.2Z)){k.3b.3H(F,F.A.2v,F.A.2q)}if(F.A.4m)F.A.4m.1D(F,[F.A.2c.x+dx,F.A.2c.y+dy]);if(!F.A.1O||F.A.1O==\'4j\'){F.A.8y=F.A.2c.x+dx;k.11.1c.K(0).14.O=F.A.2v+\'U\'}if(!F.A.1O||F.A.1O==\'49\'){F.A.8v=F.A.2c.y+dy;k.11.1c.K(0).14.Q=F.A.2q+\'U\'}if(k.1x&&k.1x.8D>0){k.1x.al(F)}E I},2r:u(o){if(!k.11.1c){k(\'2e\',1h).1S(\'<22 id="e8"></22>\');k.11.1c=k(\'#e8\');D el=k.11.1c.K(0);D 4J=el.14;4J.Y=\'1P\';4J.19=\'1o\';4J.9b=\'8j\';4J.eu=\'1o\';4J.2U=\'2K\';if(1X.71){el.bE="e4"}P{4J.gi=\'1o\';4J.e7=\'1o\';4J.e1=\'1o\'}}if(!o){o={}}E q.1E(u(){if(q.9I||!k.1a)E;if(1X.71){q.gh=u(){E I};q.gj=u(){E I}}D el=q;D 5e=o.3v?k(q).gf(o.3v):k(q);if(k.3a.4t){5e.1E(u(){q.bE="e4"})}P{5e.B(\'-gI-7R-8C\',\'1o\');5e.B(\'7R-8C\',\'1o\');5e.B(\'-gH-7R-8C\',\'1o\')}q.A={5e:5e,6N:o.6N?1b:I,46:o.46?1b:I,44:o.44?o.44:I,5i:o.5i?o.5i:I,8s:o.8s?o.8s:I,3I:o.3I?T(o.3I)||0:I,1G:o.1G?2m(o.1G):I,fx:T(o.fx)||S,6R:o.6R?o.6R:I,5t:{},1s:{},4o:o.4o&&o.4o.1K==2A?o.4o:I,3T:o.3T&&o.3T.1K==2A?o.3T:I,2Z:o.2Z&&o.2Z.1K==2A?o.2Z:I,1O:/49|4j/.48(o.1O)?o.1O:I,6M:o.6M?T(o.6M)||0:0,2V:o.2V?o.2V:I,bD:o.bD?1b:I,7O:o.7O||I};if(o.5t&&o.5t.1K==2A)q.A.5t.7R=o.5t;if(o.4m&&o.4m.1K==2A)q.A.4m=o.4m;if(o.2p&&((o.2p.1K==b0&&(o.2p==\'94\'||o.2p==\'1h\'))||(o.2p.1K==7F&&o.2p.1g==4))){q.A.2p=o.2p}if(o.2O){q.A.2O=o.2O}if(o.6a){if(2g o.6a==\'gz\'){q.A.gx=T(o.6a)||1;q.A.gy=T(o.6a)||1}P if(o.6a.1g==2){q.A.gx=T(o.6a[0])||1;q.A.gy=T(o.6a[1])||1}}if(o.3H&&o.3H.1K==2A){q.A.3H=o.3H}q.9I=1b;5e.1E(u(){q.3U=el});5e.1J(\'5v\',k.11.bN)})}};k.fn.23({aS:k.11.4U,7t:k.11.2r});k.1x={du:u(5J,5G,7Q,7S){E 5J<=k.11.F.A.2v&&(5J+7Q)>=(k.11.F.A.2v+k.11.F.A.1B.w)&&5G<=k.11.F.A.2q&&(5G+7S)>=(k.11.F.A.2q+k.11.F.A.1B.h)?1b:I},cV:u(5J,5G,7Q,7S){E!(5J>(k.11.F.A.2v+k.11.F.A.1B.w)||(5J+7Q)<k.11.F.A.2v||5G>(k.11.F.A.2q+k.11.F.A.1B.h)||(5G+7S)<k.11.F.A.2q)?1b:I},1s:u(5J,5G,7Q,7S){E 5J<k.11.F.A.4B.x&&(5J+7Q)>k.11.F.A.4B.x&&5G<k.11.F.A.4B.y&&(5G+7S)>k.11.F.A.4B.y?1b:I},5r:I,3Q:{},8D:0,3P:{},ed:u(C){if(k.11.F==S){E}D i;k.1x.3Q={};D bJ=I;24(i in k.1x.3P){if(k.1x.3P[i]!=S){D 1j=k.1x.3P[i].K(0);if(k(k.11.F).is(\'.\'+1j.1i.a)){if(1j.1i.m==I){1j.1i.p=k.23(k.1a.7G(1j),k.1a.74(1j));1j.1i.m=1b}if(1j.1i.ac){k.1x.3P[i].2R(1j.1i.ac)}k.1x.3Q[i]=k.1x.3P[i];if(k.1t&&1j.1i.s&&k.11.F.A.44){1j.1i.el=k(\'.\'+1j.1i.a,1j);C.14.19=\'1o\';k.1t.cT(1j);1j.1i.ay=k.1t.8x(k.1p(1j,\'id\')).7l;C.14.19=C.A.7V;bJ=1b}if(1j.1i.9i){1j.1i.9i.1D(k.1x.3P[i].K(0),[k.11.F])}}}}if(bJ){k.1t.26()}},dS:u(){k.1x.3Q={};24(i in k.1x.3P){if(k.1x.3P[i]!=S){D 1j=k.1x.3P[i].K(0);if(k(k.11.F).is(\'.\'+1j.1i.a)){1j.1i.p=k.23(k.1a.7G(1j),k.1a.74(1j));if(1j.1i.ac){k.1x.3P[i].2R(1j.1i.ac)}k.1x.3Q[i]=k.1x.3P[i];if(k.1t&&1j.1i.s&&k.11.F.A.44){1j.1i.el=k(\'.\'+1j.1i.a,1j);C.14.19=\'1o\';k.1t.cT(1j);C.14.19=C.A.7V}}}}},al:u(e){if(k.11.F==S){E}k.1x.5r=I;D i;D bK=I;D eQ=0;24(i in k.1x.3Q){D 1j=k.1x.3Q[i].K(0);if(k.1x.5r==I&&k.1x[1j.1i.t](1j.1i.p.x,1j.1i.p.y,1j.1i.p.1C,1j.1i.p.hb)){if(1j.1i.hc&&1j.1i.h==I){k.1x.3Q[i].2R(1j.1i.hc)}if(1j.1i.h==I&&1j.1i.7x){bK=1b}1j.1i.h=1b;k.1x.5r=1j;if(k.1t&&1j.1i.s&&k.11.F.A.44){k.1t.1c.K(0).3l=1j.1i.eV;k.1t.al(1j)}eQ++}P if(1j.1i.h==1b){if(1j.1i.7y){1j.1i.7y.1D(1j,[e,k.11.1c.K(0).7c,1j.1i.fx])}if(1j.1i.hc){k.1x.3Q[i].4i(1j.1i.hc)}1j.1i.h=I}}if(k.1t&&!k.1x.5r&&k.11.F.44){k.1t.1c.K(0).14.19=\'1o\'}if(bK){k.1x.5r.1i.7x.1D(k.1x.5r,[e,k.11.1c.K(0).7c])}},eO:u(e){D i;24(i in k.1x.3Q){D 1j=k.1x.3Q[i].K(0);if(1j.1i.ac){k.1x.3Q[i].4i(1j.1i.ac)}if(1j.1i.hc){k.1x.3Q[i].4i(1j.1i.hc)}if(1j.1i.s){k.1t.7s[k.1t.7s.1g]=i}if(1j.1i.9l&&1j.1i.h==1b){1j.1i.h=I;1j.1i.9l.1D(1j,[e,1j.1i.fx])}1j.1i.m=I;1j.1i.h=I}k.1x.3Q={}},4U:u(){E q.1E(u(){if(q.9j){if(q.1i.s){id=k.1p(q,\'id\');k.1t.5L[id]=S;k(\'.\'+q.1i.a,q).aS()}k.1x.3P[\'d\'+q.c2]=S;q.9j=I;q.f=S}})},2r:u(o){E q.1E(u(){if(q.9j==1b||!o.3C||!k.1a||!k.11){E}q.1i={a:o.3C,ac:o.9J||I,hc:o.a5||I,eV:o.58||I,9l:o.gq||o.9l||I,7x:o.7x||o.dC||I,7y:o.7y||o.fO||I,9i:o.9i||I,t:o.6I&&(o.6I==\'du\'||o.6I==\'cV\')?o.6I:\'1s\',fx:o.fx?o.fx:I,m:I,h:I};if(o.cQ==1b&&k.1t){id=k.1p(q,\'id\');k.1t.5L[id]=q.1i.a;q.1i.s=1b;if(o.2Z){q.1i.2Z=o.2Z;q.1i.ay=k.1t.8x(id).7l}}q.9j=1b;q.c2=T(18.6o()*c9);k.1x.3P[\'d\'+q.c2]=k(q);k.1x.8D++})}};k.fn.23({dR:k.1x.4U,do:k.1x.2r});k.gD=k.1x.dS;k.3B={1c:S,8L:u(){3g=q.2y;if(!3g)E;14={dz:k(q).B(\'dz\')||\'\',4A:k(q).B(\'4A\')||\'\',8Z:k(q).B(\'8Z\')||\'\',dP:k(q).B(\'dP\')||\'\',dT:k(q).B(\'dT\')||\'\',dU:k(q).B(\'dU\')||\'\',c3:k(q).B(\'c3\')||\'\',dY:k(q).B(\'dY\')||\'\'};k.3B.1c.B(14);3x=k.3B.dX(3g);3x=3x.4E(12 bb("\\\\n","g"),"<br />");k.3B.1c.3x(\'gL\');ci=k.3B.1c.K(0).4c;k.3B.1c.3x(3x);Z=k.3B.1c.K(0).4c+ci;if(q.6l.2M&&Z>q.6l.2M[0]){Z=q.6l.2M[0]}q.14.Z=Z+\'U\';if(q.4Y==\'cf\'){W=k.3B.1c.K(0).5W+ci;if(q.6l.2M&&W>q.6l.2M[1]){W=q.6l.2M[1]}q.14.W=W+\'U\'}},dX:u(3g){cg={\'&\':\'&gK;\',\'<\':\'&gJ;\',\'>\':\'&gt;\',\'"\':\'&gs;\'};24(i in cg){3g=3g.4E(12 bb(i,\'g\'),cg[i])}E 3g},2r:u(2M){if(k.3B.1c==S){k(\'2e\',1h).1S(\'<22 id="dE" 14="Y: 1P; Q: 0; O: 0; 3n: 2K;"></22>\');k.3B.1c=k(\'#dE\')}E q.1E(u(){if(/cf|ch/.48(q.4Y)){if(q.4Y==\'ch\'){dB=q.5C(\'1u\');if(!/3g|gr/.48(dB)){E}}if(2M&&(2M.1K==bn||(2M.1K==7F&&2M.1g==2))){if(2M.1K==bn)2M=[2M,2M];P{2M[0]=T(2M[0])||8J;2M[1]=T(2M[1])||8J}q.6l={2M:2M}}k(q).5B(k.3B.8L).6y(k.3B.8L).dH(k.3B.8L);k.3B.8L.1D(q)}})}};k.fn.kc=k.3B.2r;k.4K=u(e){if(/^kd$|^ke$|^ka$|^6L$|^k9$|^k5$|^k4$|^k6$|^k7$|^2e$|^k8$|^kf$|^kg$|^kn$|^ko$|^kp$|^kq$/i.48(e.9N))E I;P E 1b};k.fx.a0=u(e,65){D c=e.7c;D cs=c.14;cs.Y=65.Y;cs.5K=65.3G.t;cs.5j=65.3G.l;cs.5k=65.3G.b;cs.5z=65.3G.r;cs.Q=65.Q+\'U\';cs.O=65.O+\'U\';e.31.ew(c,e);e.31.km(e)};k.fx.9P=u(e){if(!k.4K(e))E I;D t=k(e);D es=e.14;D 73=I;if(t.B(\'19\')==\'1o\'){5Y=t.B(\'3n\');t.B(\'3n\',\'2K\').1Y();73=1b}D V={};V.Y=t.B(\'Y\');V.1q=k.1a.2o(e);V.3G=k.1a.cy(e);D co=e.4Z?e.4Z.ei:t.B(\'hU\');V.Q=T(t.B(\'Q\'))||0;V.O=T(t.B(\'O\'))||0;D eo=\'kl\'+T(18.6o()*c9);D 6u=1h.3F(/^1T$|^br$|^kh$|^hr$|^8C$|^kj$|^8T$|^3A$|^kk$|^k3$|^k2$|^9h$|^dl$|^jM$/i.48(e.9N)?\'22\':e.9N);k.1p(6u,\'id\',eo);D jN=k(6u).2R(\'jO\');D 4h=6u.14;D Q=0;D O=0;if(V.Y==\'2s\'||V.Y==\'1P\'){Q=V.Q;O=V.O}4h.Q=Q+\'U\';4h.O=O+\'U\';4h.Y=V.Y!=\'2s\'&&V.Y!=\'1P\'?\'2s\':V.Y;4h.W=V.1q.hb+\'U\';4h.Z=V.1q.1C+\'U\';4h.5K=V.3G.t;4h.5z=V.3G.r;4h.5k=V.3G.b;4h.5j=V.3G.l;4h.2U=\'2K\';if(k.3a.4t){4h.ei=co}P{4h.jK=co}if(k.3a=="4t"){es.5E="8V(1G="+0.ex*2a+")"}es.1G=0.ex;e.31.ew(6u,e);6u.jF(e);es.5K=\'2P\';es.5z=\'2P\';es.5k=\'2P\';es.5j=\'2P\';es.Y=\'1P\';es.eu=\'1o\';es.Q=\'2P\';es.O=\'2P\';if(73){t.2G();es.3n=5Y}E{V:V,3p:k(6u)}};k.fx.8E={jE:[0,1V,1V],jG:[eD,1V,1V],jH:[e6,e6,jI],jP:[0,0,0],ks:[0,0,1V],jY:[dv,42,42],jZ:[0,1V,1V],k0:[0,0,7w],k1:[0,7w,7w],jX:[cn,cn,cn],jS:[0,2a,0],jR:[jT,jU,eb],jV:[7w,0,7w],kr:[85,eb,47],kP:[1V,eA,0],kN:[kO,50,kx],kF:[7w,0,0],kD:[ku,f8,kt],ky:[kH,0,9C],kL:[1V,0,1V],kM:[1V,kJ,0],kv:[0,6C,0],kA:[75,0,kE],kC:[eD,eB,eA],kG:[kI,kB,eB],kw:[e0,1V,1V],kz:[eL,kK,eL],kQ:[9C,9C,9C],jC:[1V,iy,iz],iA:[1V,1V,e0],iB:[0,1V,0],ix:[1V,0,1V],iv:[6C,0,0],iq:[0,0,6C],ip:[6C,6C,0],ir:[1V,dv,0],it:[1V,ah,iu],iC:[6C,0,6C],iD:[1V,0,0],iK:[ah,ah,ah],iL:[1V,1V,1V],iM:[1V,1V,0]};k.fx.6D=u(4x,dm){if(k.fx.8E[4x])E{r:k.fx.8E[4x][0],g:k.fx.8E[4x][1],b:k.fx.8E[4x][2]};P if(2W=/^6Y\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)$/.a4(4x))E{r:T(2W[1]),g:T(2W[2]),b:T(2W[3])};P if(2W=/6Y\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)$/.a4(4x))E{r:2m(2W[1])*2.55,g:2m(2W[2])*2.55,b:2m(2W[3])*2.55};P if(2W=/^#([a-fA-79-9])([a-fA-79-9])([a-fA-79-9])$/.a4(4x))E{r:T("77"+2W[1]+2W[1]),g:T("77"+2W[2]+2W[2]),b:T("77"+2W[3]+2W[3])};P if(2W=/^#([a-fA-79-9]{2})([a-fA-79-9]{2})([a-fA-79-9]{2})$/.a4(4x))E{r:T("77"+2W[1]),g:T("77"+2W[2]),b:T("77"+2W[3])};P E dm==1b?I:{r:1V,g:1V,b:1V}};k.fx.dD={5Q:1,5b:1,5O:1,4S:1,4D:1,4A:1,W:1,O:1,c3:1,iI:1,5k:1,5j:1,5z:1,5K:1,8b:1,6x:1,8c:1,av:1,1G:1,iE:1,iF:1,5n:1,4X:1,5U:1,5M:1,2L:1,jD:1,Q:1,Z:1,3I:1};k.fx.dA={7i:1,iG:1,iH:1,io:1,im:1,4x:1,i2:1};k.fx.8A=[\'i3\',\'i4\',\'i5\',\'i1\'];k.fx.cc={\'cd\':[\'2E\',\'dK\'],\'a8\':[\'2E\',\'bh\'],\'6w\':[\'6w\',\'\'],\'8F\':[\'8F\',\'\']};k.fn.23({5w:u(5X,H,G,J){E q.1w(u(){D a1=k.H(H,G,J);D e=12 k.dM(q,a1,5X)})},c4:u(H,J){E q.1w(u(){D a1=k.H(H,J);D e=12 k.c4(q,a1)})},8o:u(2D){E q.1E(u(){if(q.6d)k.by(q,2D)})},i0:u(2D){E q.1E(u(){if(q.6d)k.by(q,2D);if(q.1w&&q.1w[\'fx\'])q.1w.fx=[]})}});k.23({c4:u(2f,M){D z=q,3t;z.2D=u(){if(k.fQ(M.21))M.21.1D(2f)};z.2I=6V(u(){z.2D()},M.1m);2f.6d=z},G:{c8:u(p,n,1W,1H,1m){E((-18.5H(p*18.2Q)/2)+0.5)*1H+1W}},dM:u(2f,M,5X){D z=q,3t;D y=2f.14;D fR=k.B(2f,"2U");D 72=k.B(2f,"19");D 2j={};z.9O=(12 7g()).7z();M.G=M.G&&k.G[M.G]?M.G:\'c8\';z.ag=u(2w,43){if(k.fx.dD[2w]){if(43==\'1Y\'||43==\'2G\'||43==\'3R\'){if(!2f.6v)2f.6v={};D r=2m(k.6E(2f,2w));2f.6v[2w]=r&&r>-c9?r:(2m(k.B(2f,2w))||0);43=43==\'3R\'?(72==\'1o\'?\'1Y\':\'2G\'):43;M[43]=1b;2j[2w]=43==\'1Y\'?[0,2f.6v[2w]]:[2f.6v[2w],0];if(2w!=\'1G\')y[2w]=2j[2w][0]+(2w!=\'3I\'&&2w!=\'8Z\'?\'U\':\'\');P k.1p(y,"1G",2j[2w][0])}P{2j[2w]=[2m(k.6E(2f,2w)),2m(43)||0]}}P if(k.fx.dA[2w])2j[2w]=[k.fx.6D(k.6E(2f,2w)),k.fx.6D(43)];P if(/^6w$|8F$|2E$|a8$|cd$/i.48(2w)){D m=43.4E(/\\s+/g,\' \').4E(/6Y\\s*\\(\\s*/g,\'6Y(\').4E(/\\s*,\\s*/g,\',\').4E(/\\s*\\)/g,\')\').d5(/([^\\s]+)/g);3m(2w){1e\'6w\':1e\'8F\':1e\'cd\':1e\'a8\':m[3]=m[3]||m[1]||m[0];m[2]=m[2]||m[0];m[1]=m[1]||m[0];24(D i=0;i<k.fx.8A.1g;i++){D 64=k.fx.cc[2w][0]+k.fx.8A[i]+k.fx.cc[2w][1];2j[64]=2w==\'a8\'?[k.fx.6D(k.6E(2f,64)),k.fx.6D(m[i])]:[2m(k.6E(2f,64)),2m(m[i])]}1r;1e\'2E\':24(D i=0;i<m.1g;i++){D bd=2m(m[i]);D a9=!hX(bd)?\'dK\':(!/cu|1o|2K|hY|hZ|i6|i7|ii|ij|ik|il/i.48(m[i])?\'bh\':I);if(a9){24(D j=0;j<k.fx.8A.1g;j++){64=\'2E\'+k.fx.8A[j]+a9;2j[64]=a9==\'bh\'?[k.fx.6D(k.6E(2f,64)),k.fx.6D(m[i])]:[2m(k.6E(2f,64)),bd]}}P{y[\'ie\']=m[i]}}1r}}P{y[2w]=43}E I};24(p in 5X){if(p==\'14\'){D 5f=k.bl(5X[p]);24(7A in 5f){q.ag(7A,5f[7A])}}P if(p==\'3l\'){if(1h.af)24(D i=0;i<1h.af.1g;i++){D 7e=1h.af[i].7e||1h.af[i].i9||S;if(7e){24(D j=0;j<7e.1g;j++){if(7e[j].i8==\'.\'+5X[p]){D 6X=12 bb(\'\\.\'+5X[p]+\' {\');D 5Z=7e[j].14.9X;D 5f=k.bl(5Z.4E(6X,\'\').4E(/}/g,\'\'));24(7A in 5f){q.ag(7A,5f[7A])}}}}}}P{q.ag(p,5X[p])}}y.19=72==\'1o\'?\'2B\':72;y.2U=\'2K\';z.2D=u(){D t=(12 7g()).7z();if(t>M.1m+z.9O){5T(z.2I);z.2I=S;24(p in 2j){if(p=="1G")k.1p(y,"1G",2j[p][1]);P if(2g 2j[p][1]==\'8T\')y[p]=\'6Y(\'+2j[p][1].r+\',\'+2j[p][1].g+\',\'+2j[p][1].b+\')\';P y[p]=2j[p][1]+(p!=\'3I\'&&p!=\'8Z\'?\'U\':\'\')}if(M.2G||M.1Y)24(D p in 2f.6v)if(p=="1G")k.1p(y,p,2f.6v[p]);P y[p]="";y.19=M.2G?\'1o\':(72!=\'1o\'?72:\'2B\');y.2U=fR;2f.6d=S;if(k.fQ(M.21))M.21.1D(2f)}P{D n=t-q.9O;D 8w=n/M.1m;24(p in 2j){if(2g 2j[p][1]==\'8T\'){y[p]=\'6Y(\'+T(k.G[M.G](8w,n,2j[p][0].r,(2j[p][1].r-2j[p][0].r),M.1m))+\',\'+T(k.G[M.G](8w,n,2j[p][0].g,(2j[p][1].g-2j[p][0].g),M.1m))+\',\'+T(k.G[M.G](8w,n,2j[p][0].b,(2j[p][1].b-2j[p][0].b),M.1m))+\')\'}P{D bz=k.G[M.G](8w,n,2j[p][0],(2j[p][1]-2j[p][0]),M.1m);if(p=="1G")k.1p(y,"1G",bz);P y[p]=bz+(p!=\'3I\'&&p!=\'8Z\'?\'U\':\'\')}}}};z.2I=6V(u(){z.2D()},13);2f.6d=z},by:u(2f,2D){if(2D)2f.6d.9O-=iO;P{1X.5T(2f.6d.2I);2f.6d=S;k.2H(2f,"fx")}}});k.bl=u(5Z){D 5f={};if(2g 5Z==\'4V\'){5Z=5Z.6c().7C(\';\');24(D i=0;i<5Z.1g;i++){6X=5Z[i].7C(\':\');if(6X.1g==2){5f[k.g6(6X[0].4E(/\\-(\\w)/g,u(m,c){E c.jo()}))]=k.g6(6X[1])}}}E 5f};k.fn.23({g3:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'4F\',G)})},gb:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'4r\',G)})},jl:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'fJ\',G)})},jk:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'O\',G)})},jg:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'2L\',G)})},jf:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.61(q,H,J,\'fh\',G)})}});k.fx.61=u(e,H,J,2S,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;z.el=k(e);z.1N=k.1a.2o(e);z.G=2g J==\'4V\'?J:G||S;if(!e.4s)e.4s=z.el.B(\'19\');if(2S==\'fJ\'){2S=z.el.B(\'19\')==\'1o\'?\'4r\':\'4F\'}P if(2S==\'fh\'){2S=z.el.B(\'19\')==\'1o\'?\'2L\':\'O\'}z.el.1Y();z.H=H;z.J=2g J==\'u\'?J:S;z.fx=k.fx.9P(e);z.2S=2S;z.21=u(){if(z.J&&z.J.1K==2A){z.J.1D(z.el.K(0))}if(z.2S==\'4r\'||z.2S==\'2L\'){z.el.B(\'19\',z.el.K(0).4s==\'1o\'?\'2B\':z.el.K(0).4s)}P{z.el.2G()}k.fx.a0(z.fx.3p.K(0),z.fx.V);k.2H(z.el.K(0),\'1n\')};3m(z.2S){1e\'4F\':63=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'W\');63.1L(z.fx.V.1q.hb,0);1r;1e\'4r\':z.fx.3p.B(\'W\',\'9R\');z.el.1Y();63=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'W\');63.1L(0,z.fx.V.1q.hb);1r;1e\'O\':63=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'Z\');63.1L(z.fx.V.1q.1C,0);1r;1e\'2L\':z.fx.3p.B(\'Z\',\'9R\');z.el.1Y();63=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'Z\');63.1L(0,z.fx.V.1q.1C);1r}};k.fn.ji=u(5D,J){E q.1w(\'1n\',u(){if(!k.4K(q)){k.2H(q,\'1n\');E I}D e=12 k.fx.f4(q,5D,J);e.bp()})};k.fx.f4=u(e,5D,J){D z=q;z.el=k(e);z.el.1Y();z.J=J;z.5D=T(5D)||40;z.V={};z.V.Y=z.el.B(\'Y\');z.V.Q=T(z.el.B(\'Q\'))||0;z.V.O=T(z.el.B(\'O\'))||0;if(z.V.Y!=\'2s\'&&z.V.Y!=\'1P\'){z.el.B(\'Y\',\'2s\')}z.3V=5;z.5y=1;z.bp=u(){z.5y++;z.e=12 k.fx(z.el.K(0),{1m:jj,21:u(){z.e=12 k.fx(z.el.K(0),{1m:80,21:u(){z.5D=T(z.5D/2);if(z.5y<=z.3V)z.bp();P{z.el.B(\'Y\',z.V.Y).B(\'Q\',z.V.Q+\'U\').B(\'O\',z.V.O+\'U\');k.2H(z.el.K(0),\'1n\');if(z.J&&z.J.1K==2A){z.J.1D(z.el.K(0))}}}},\'Q\');z.e.1L(z.V.Q-z.5D,z.V.Q)}},\'Q\');z.e.1L(z.V.Q,z.V.Q-z.5D)}};k.fn.23({jy:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4r\',\'4l\',G)})},jz:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4r\',\'in\',G)})},jA:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4r\',\'3R\',G)})},jB:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4F\',\'4l\',G)})},jx:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4F\',\'in\',G)})},jw:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'4F\',\'3R\',G)})},js:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'O\',\'4l\',G)})},jt:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'O\',\'in\',G)})},ju:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'O\',\'3R\',G)})},jv:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'2L\',\'4l\',G)})},je:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'2L\',\'in\',G)})},jd:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.4f(q,H,J,\'2L\',\'3R\',G)})}});k.fx.4f=u(e,H,J,2S,1u,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;z.el=k(e);z.G=2g J==\'4V\'?J:G||S;z.V={};z.V.Y=z.el.B(\'Y\');z.V.Q=z.el.B(\'Q\');z.V.O=z.el.B(\'O\');if(!e.4s)e.4s=z.el.B(\'19\');if(1u==\'3R\'){1u=z.el.B(\'19\')==\'1o\'?\'in\':\'4l\'}z.el.1Y();if(z.V.Y!=\'2s\'&&z.V.Y!=\'1P\'){z.el.B(\'Y\',\'2s\')}z.1u=1u;J=2g J==\'u\'?J:S;8H=1;3m(2S){1e\'4F\':z.e=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'Q\');z.62=2m(z.V.Q)||0;z.9K=z.fG;8H=-1;1r;1e\'4r\':z.e=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'Q\');z.62=2m(z.V.Q)||0;z.9K=z.fG;1r;1e\'2L\':z.e=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'O\');z.62=2m(z.V.O)||0;z.9K=z.fy;1r;1e\'O\':z.e=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'O\');z.62=2m(z.V.O)||0;z.9K=z.fy;8H=-1;1r}z.e2=12 k.fx(z.el.K(0),k.H(H,z.G,u(){z.el.B(z.V);if(z.1u==\'4l\'){z.el.B(\'19\',\'1o\')}P z.el.B(\'19\',z.el.K(0).4s==\'1o\'?\'2B\':z.el.K(0).4s);k.2H(z.el.K(0),\'1n\')}),\'1G\');if(1u==\'in\'){z.e.1L(z.62+2a*8H,z.62);z.e2.1L(0,1)}P{z.e.1L(z.62,z.62+2a*8H);z.e2.1L(1,0)}};k.fn.23({j0:u(H,W,J,G){E q.1w(\'1n\',u(){12 k.fx.9L(q,H,W,J,\'fp\',G)})},iW:u(H,W,J,G){E q.1w(\'1n\',u(){12 k.fx.9L(q,H,W,J,\'9M\',G)})},iV:u(H,W,J,G){E q.1w(\'1n\',u(){12 k.fx.9L(q,H,W,J,\'3R\',G)})}});k.fx.9L=u(e,H,W,J,1u,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;z.el=k(e);z.G=2g J==\'4V\'?J:G||S;z.J=2g J==\'u\'?J:S;if(1u==\'3R\'){1u=z.el.B(\'19\')==\'1o\'?\'9M\':\'fp\'}z.H=H;z.W=W&&W.1K==bn?W:20;z.fx=k.fx.9P(e);z.1u=1u;z.21=u(){if(z.J&&z.J.1K==2A){z.J.1D(z.el.K(0))}if(z.1u==\'9M\'){z.el.1Y()}P{z.el.2G()}k.fx.a0(z.fx.3p.K(0),z.fx.V);k.2H(z.el.K(0),\'1n\')};if(z.1u==\'9M\'){z.el.1Y();z.fx.3p.B(\'W\',z.W+\'U\').B(\'Z\',\'9R\');z.ef=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,u(){z.ef=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'W\');z.ef.1L(z.W,z.fx.V.1q.hb)}),\'Z\');z.ef.1L(0,z.fx.V.1q.1C)}P{z.ef=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,u(){z.ef=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G,z.21),\'Z\');z.ef.1L(z.fx.V.1q.1C,0)}),\'W\');z.ef.1L(z.fx.V.1q.hb,z.W)}};k.fn.iR=u(H,4x,J,G){E q.1w(\'fv\',u(){q.6W=k(q).1p("14")||\'\';G=2g J==\'4V\'?J:G||S;J=2g J==\'u\'?J:S;D 9S=k(q).B(\'7i\');D 8I=q.31;7d(9S==\'cu\'&&8I){9S=k(8I).B(\'7i\');8I=8I.31}k(q).B(\'7i\',4x);if(2g q.6W==\'8T\')q.6W=q.6W["9X"];k(q).5w({\'7i\':9S},H,G,u(){k.2H(q,\'fv\');if(2g k(q).1p("14")==\'8T\'){k(q).1p("14")["9X"]="";k(q).1p("14")["9X"]=q.6W}P{k(q).1p("14",q.6W)}if(J)J.1D(q)})})};k.fn.23({iT:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.5m(q,H,J,\'49\',\'6g\',G)})},iU:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.5m(q,H,J,\'4j\',\'6g\',G)})},j1:u(H,J,G){E q.1w(\'1n\',u(){if(k.B(q,\'19\')==\'1o\'){12 k.fx.5m(q,H,J,\'4j\',\'6Z\',G)}P{12 k.fx.5m(q,H,J,\'4j\',\'6g\',G)}})},j2:u(H,J,G){E q.1w(\'1n\',u(){if(k.B(q,\'19\')==\'1o\'){12 k.fx.5m(q,H,J,\'49\',\'6Z\',G)}P{12 k.fx.5m(q,H,J,\'49\',\'6g\',G)}})},j9:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.5m(q,H,J,\'49\',\'6Z\',G)})},ja:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.5m(q,H,J,\'4j\',\'6Z\',G)})}});k.fx.5m=u(e,H,J,2S,1u,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;D 73=I;z.el=k(e);z.G=2g J==\'4V\'?J:G||S;z.J=2g J==\'u\'?J:S;z.1u=1u;z.H=H;z.2i=k.1a.2o(e);z.V={};z.V.Y=z.el.B(\'Y\');z.V.19=z.el.B(\'19\');if(z.V.19==\'1o\'){5Y=z.el.B(\'3n\');z.el.1Y();73=1b}z.V.Q=z.el.B(\'Q\');z.V.O=z.el.B(\'O\');if(73){z.el.2G();z.el.B(\'3n\',5Y)}z.V.Z=z.2i.w+\'U\';z.V.W=z.2i.h+\'U\';z.V.2U=z.el.B(\'2U\');z.2i.Q=T(z.V.Q)||0;z.2i.O=T(z.V.O)||0;if(z.V.Y!=\'2s\'&&z.V.Y!=\'1P\'){z.el.B(\'Y\',\'2s\')}z.el.B(\'2U\',\'2K\').B(\'W\',1u==\'6Z\'&&2S==\'49\'?1:z.2i.h+\'U\').B(\'Z\',1u==\'6Z\'&&2S==\'4j\'?1:z.2i.w+\'U\');z.21=u(){z.el.B(z.V);if(z.1u==\'6g\')z.el.2G();P z.el.1Y();k.2H(z.el.K(0),\'1n\')};3m(2S){1e\'49\':z.eh=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'W\');z.et=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'Q\');if(z.1u==\'6g\'){z.eh.1L(z.2i.h,0);z.et.1L(z.2i.Q,z.2i.Q+z.2i.h/2)}P{z.eh.1L(0,z.2i.h);z.et.1L(z.2i.Q+z.2i.h/2,z.2i.Q)}1r;1e\'4j\':z.eh=12 k.fx(z.el.K(0),k.H(H-15,z.G,J),\'Z\');z.et=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'O\');if(z.1u==\'6g\'){z.eh.1L(z.2i.w,0);z.et.1L(z.2i.O,z.2i.O+z.2i.w/2)}P{z.eh.1L(0,z.2i.w);z.et.1L(z.2i.O+z.2i.w/2,z.2i.O)}1r}};k.fn.bg=u(H,3V,J){E q.1w(\'1n\',u(){if(!k.4K(q)){k.2H(q,\'1n\');E I}D fx=12 k.fx.bg(q,H,3V,J);fx.bf()})};k.fx.bg=u(el,H,3V,J){D z=q;z.3V=3V;z.5y=1;z.el=el;z.H=H;z.J=J;k(z.el).1Y();z.bf=u(){z.5y++;z.e=12 k.fx(z.el,k.H(z.H,u(){z.ef=12 k.fx(z.el,k.H(z.H,u(){if(z.5y<=z.3V)z.bf();P{k.2H(z.el,\'1n\');if(z.J&&z.J.1K==2A){z.J.1D(z.el)}}}),\'1G\');z.ef.1L(0,1)}),\'1G\');z.e.1L(1,0)}};k.fn.23({jb:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.6G(q,H,1,2a,1b,J,\'fa\',G)})},jc:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.6G(q,H,2a,1,1b,J,\'b4\',G)})},j8:u(H,J,G){E q.1w(\'1n\',u(){D G=G||\'fl\';12 k.fx.6G(q,H,2a,f8,1b,J,\'6h\',G)})},6G:u(H,57,30,6H,J,G){E q.1w(\'1n\',u(){12 k.fx.6G(q,H,57,30,6H,J,\'6G\',G)})}});k.fx.6G=u(e,H,57,30,6H,J,1u,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;z.el=k(e);z.57=T(57)||2a;z.30=T(30)||2a;z.G=2g J==\'4V\'?J:G||S;z.J=2g J==\'u\'?J:S;z.1m=k.H(H).1m;z.6H=6H||S;z.2i=k.1a.2o(e);z.V={Z:z.el.B(\'Z\'),W:z.el.B(\'W\'),4A:z.el.B(\'4A\')||\'2a%\',Y:z.el.B(\'Y\'),19:z.el.B(\'19\'),Q:z.el.B(\'Q\'),O:z.el.B(\'O\'),2U:z.el.B(\'2U\'),4S:z.el.B(\'4S\'),5O:z.el.B(\'5O\'),5Q:z.el.B(\'5Q\'),5b:z.el.B(\'5b\'),5M:z.el.B(\'5M\'),5U:z.el.B(\'5U\'),5n:z.el.B(\'5n\'),4X:z.el.B(\'4X\')};z.Z=T(z.V.Z)||e.4c||0;z.W=T(z.V.W)||e.5W||0;z.Q=T(z.V.Q)||0;z.O=T(z.V.O)||0;1q=[\'em\',\'U\',\'j7\',\'%\'];24(i in 1q){if(z.V.4A.3J(1q[i])>0){z.fg=1q[i];z.4A=2m(z.V.4A)}if(z.V.4S.3J(1q[i])>0){z.fc=1q[i];z.bw=2m(z.V.4S)||0}if(z.V.5O.3J(1q[i])>0){z.fe=1q[i];z.bc=2m(z.V.5O)||0}if(z.V.5Q.3J(1q[i])>0){z.fL=1q[i];z.bA=2m(z.V.5Q)||0}if(z.V.5b.3J(1q[i])>0){z.g8=1q[i];z.bt=2m(z.V.5b)||0}if(z.V.5M.3J(1q[i])>0){z.g4=1q[i];z.bx=2m(z.V.5M)||0}if(z.V.5U.3J(1q[i])>0){z.g9=1q[i];z.bv=2m(z.V.5U)||0}if(z.V.5n.3J(1q[i])>0){z.gc=1q[i];z.bj=2m(z.V.5n)||0}if(z.V.4X.3J(1q[i])>0){z.fK=1q[i];z.b7=2m(z.V.4X)||0}}if(z.V.Y!=\'2s\'&&z.V.Y!=\'1P\'){z.el.B(\'Y\',\'2s\')}z.el.B(\'2U\',\'2K\');z.1u=1u;3m(z.1u){1e\'fa\':z.4b=z.Q+z.2i.h/2;z.5a=z.Q;z.4k=z.O+z.2i.w/2;z.59=z.O;1r;1e\'b4\':z.5a=z.Q+z.2i.h/2;z.4b=z.Q;z.59=z.O+z.2i.w/2;z.4k=z.O;1r;1e\'6h\':z.5a=z.Q-z.2i.h/4;z.4b=z.Q;z.59=z.O-z.2i.w/4;z.4k=z.O;1r}z.be=I;z.t=(12 7g).7z();z.4w=u(){5T(z.2I);z.2I=S};z.2D=u(){if(z.be==I){z.el.1Y();z.be=1b}D t=(12 7g).7z();D n=t-z.t;D p=n/z.1m;if(t>=z.1m+z.t){9T(u(){o=1;if(z.1u){t=z.5a;l=z.59;if(z.1u==\'6h\')o=0}z.bs(z.30,l,t,1b,o)},13);z.4w()}P{o=1;if(!k.G||!k.G[z.G]){s=((-18.5H(p*18.2Q)/2)+0.5)*(z.30-z.57)+z.57}P{s=k.G[z.G](p,n,z.57,(z.30-z.57),z.1m)}if(z.1u){if(!k.G||!k.G[z.G]){t=((-18.5H(p*18.2Q)/2)+0.5)*(z.5a-z.4b)+z.4b;l=((-18.5H(p*18.2Q)/2)+0.5)*(z.59-z.4k)+z.4k;if(z.1u==\'6h\')o=((-18.5H(p*18.2Q)/2)+0.5)*(-0.9Y)+0.9Y}P{t=k.G[z.G](p,n,z.4b,(z.5a-z.4b),z.1m);l=k.G[z.G](p,n,z.4k,(z.59-z.4k),z.1m);if(z.1u==\'6h\')o=k.G[z.G](p,n,0.9Y,-0.9Y,z.1m)}}z.bs(s,l,t,I,o)}};z.2I=6V(u(){z.2D()},13);z.bs=u(4q,O,Q,fM,1G){z.el.B(\'W\',z.W*4q/2a+\'U\').B(\'Z\',z.Z*4q/2a+\'U\').B(\'O\',O+\'U\').B(\'Q\',Q+\'U\').B(\'4A\',z.4A*4q/2a+z.fg);if(z.bw)z.el.B(\'4S\',z.bw*4q/2a+z.fc);if(z.bc)z.el.B(\'5O\',z.bc*4q/2a+z.fe);if(z.bA)z.el.B(\'5Q\',z.bA*4q/2a+z.fL);if(z.bt)z.el.B(\'5b\',z.bt*4q/2a+z.g8);if(z.bx)z.el.B(\'5M\',z.bx*4q/2a+z.g4);if(z.bv)z.el.B(\'5U\',z.bv*4q/2a+z.g9);if(z.bj)z.el.B(\'5n\',z.bj*4q/2a+z.gc);if(z.b7)z.el.B(\'4X\',z.b7*4q/2a+z.fK);if(z.1u==\'6h\'){if(1X.71)z.el.K(0).14.5E="8V(1G="+1G*2a+")";z.el.K(0).14.1G=1G}if(fM){if(z.6H){z.el.B(z.V)}if(z.1u==\'b4\'||z.1u==\'6h\'){z.el.B(\'19\',\'1o\');if(z.1u==\'6h\'){if(1X.71)z.el.K(0).14.5E="8V(1G="+2a+")";z.el.K(0).14.1G=1}}P z.el.B(\'19\',\'2B\');if(z.J)z.J.1D(z.el.K(0));k.2H(z.el.K(0),\'1n\')}}};k.fn.23({9U:u(H,1O,G){o=k.H(H);E q.1w(\'1n\',u(){12 k.fx.9U(q,o,1O,G)})},j6:u(H,1O,G){E q.1E(u(){k(\'a[@3h*="#"]\',q).5h(u(e){fW=q.3h.7C(\'#\');k(\'#\'+fW[1]).9U(H,1O,G);E I})})}});k.fx.9U=u(e,o,1O,G){D z=q;z.o=o;z.e=e;z.1O=/fT|gd/.48(1O)?1O:I;z.G=G;p=k.1a.3w(e);s=k.1a.6z();z.4w=u(){5T(z.2I);z.2I=S;k.2H(z.e,\'1n\')};z.t=(12 7g).7z();s.h=s.h>s.ih?(s.h-s.ih):s.h;s.w=s.w>s.iw?(s.w-s.iw):s.w;z.5a=p.y>s.h?s.h:p.y;z.59=p.x>s.w?s.w:p.x;z.4b=s.t;z.4k=s.l;z.2D=u(){D t=(12 7g).7z();D n=t-z.t;D p=n/z.o.1m;if(t>=z.o.1m+z.t){z.4w();9T(u(){z.d3(z.5a,z.59)},13)}P{if(!z.1O||z.1O==\'fT\'){if(!k.G||!k.G[z.G]){9V=((-18.5H(p*18.2Q)/2)+0.5)*(z.5a-z.4b)+z.4b}P{9V=k.G[z.G](p,n,z.4b,(z.5a-z.4b),z.o.1m)}}P{9V=z.4b}if(!z.1O||z.1O==\'gd\'){if(!k.G||!k.G[z.G]){9W=((-18.5H(p*18.2Q)/2)+0.5)*(z.59-z.4k)+z.4k}P{9W=k.G[z.G](p,n,z.4k,(z.59-z.4k),z.o.1m)}}P{9W=z.4k}z.d3(9V,9W)}};z.d3=u(t,l){1X.j4(l,t)};z.2I=6V(u(){z.2D()},13)};k.fn.cY=u(3V,J){E q.1w(\'1n\',u(){if(!k.4K(q)){k.2H(q,\'1n\');E I}D e=12 k.fx.cY(q,3V,J);e.cG()})};k.fx.cY=u(e,3V,J){D z=q;z.el=k(e);z.el.1Y();z.3V=T(3V)||3;z.J=J;z.5y=1;z.V={};z.V.Y=z.el.B(\'Y\');z.V.Q=T(z.el.B(\'Q\'))||0;z.V.O=T(z.el.B(\'O\'))||0;if(z.V.Y!=\'2s\'&&z.V.Y!=\'1P\'){z.el.B(\'Y\',\'2s\')}z.cG=u(){z.5y++;z.e=12 k.fx(z.el.K(0),{1m:60,21:u(){z.e=12 k.fx(z.el.K(0),{1m:60,21:u(){z.e=12 k.fx(e,{1m:60,21:u(){if(z.5y<=z.3V)z.cG();P{z.el.B(\'Y\',z.V.Y).B(\'Q\',z.V.Q+\'U\').B(\'O\',z.V.O+\'U\');k.2H(z.el.K(0),\'1n\');if(z.J&&z.J.1K==2A){z.J.1D(z.el.K(0))}}}},\'O\');z.e.1L(z.V.O-20,z.V.O)}},\'O\');z.e.1L(z.V.O+20,z.V.O-20)}},\'O\');z.e.1L(z.V.O,z.V.O+20)}};k.fn.23({fo:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4F\',\'in\',G)})},fq:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4F\',\'4l\',G)})},iY:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4F\',\'3R\',G)})},iX:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4r\',\'in\',G)})},jr:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4r\',\'4l\',G)})},jq:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'4r\',\'3R\',G)})},jp:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'O\',\'in\',G)})},jn:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'O\',\'4l\',G)})},jm:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'O\',\'3R\',G)})},iP:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'2L\',\'in\',G)})},ic:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'2L\',\'4l\',G)})},ib:u(H,J,G){E q.1w(\'1n\',u(){12 k.fx.1z(q,H,J,\'2L\',\'3R\',G)})}});k.fx.1z=u(e,H,J,2S,1u,G){if(!k.4K(e)){k.2H(e,\'1n\');E I}D z=q;z.el=k(e);z.G=2g J==\'4V\'?J:G||S;z.J=2g J==\'u\'?J:S;if(1u==\'3R\'){1u=z.el.B(\'19\')==\'1o\'?\'in\':\'4l\'}if(!e.4s)e.4s=z.el.B(\'19\');z.el.1Y();z.H=H;z.fx=k.fx.9P(e);z.1u=1u;z.2S=2S;z.21=u(){if(z.1u==\'4l\')z.el.B(\'3n\',\'2K\');k.fx.a0(z.fx.3p.K(0),z.fx.V);if(z.1u==\'in\'){z.el.B(\'19\',z.el.K(0).4s==\'1o\'?\'2B\':z.el.K(0).4s)}P{z.el.B(\'19\',\'1o\');z.el.B(\'3n\',\'dd\')}if(z.J&&z.J.1K==2A){z.J.1D(z.el.K(0))}k.2H(z.el.K(0),\'1n\')};3m(z.2S){1e\'4F\':z.ef=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'Q\');z.7v=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G),\'W\');if(z.1u==\'in\'){z.ef.1L(-z.fx.V.1q.hb,0);z.7v.1L(0,z.fx.V.1q.hb)}P{z.ef.1L(0,-z.fx.V.1q.hb);z.7v.1L(z.fx.V.1q.hb,0)}1r;1e\'4r\':z.ef=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'Q\');if(z.1u==\'in\'){z.ef.1L(z.fx.V.1q.hb,0)}P{z.ef.1L(0,z.fx.V.1q.hb)}1r;1e\'O\':z.ef=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'O\');z.7v=12 k.fx(z.fx.3p.K(0),k.H(z.H,z.G),\'Z\');if(z.1u==\'in\'){z.ef.1L(-z.fx.V.1q.1C,0);z.7v.1L(0,z.fx.V.1q.1C)}P{z.ef.1L(0,-z.fx.V.1q.1C);z.7v.1L(z.fx.V.1q.1C,0)}1r;1e\'2L\':z.ef=12 k.fx(z.el.K(0),k.H(z.H,z.G,z.21),\'O\');if(z.1u==\'in\'){z.ef.1L(z.fx.V.1q.1C,0)}P{z.ef.1L(0,z.fx.V.1q.1C)}1r}};k.3f=S;k.fn.ig=u(o){E q.1w(\'1n\',u(){12 k.fx.dG(q,o)})};k.fx.dG=u(e,o){if(k.3f==S){k(\'2e\',1h).1S(\'<22 id="3f"></22>\');k.3f=k(\'#3f\')}k.3f.B(\'19\',\'2B\').B(\'Y\',\'1P\');D z=q;z.el=k(e);if(!o||!o.30){E}if(o.30.1K==b0&&1h.9e(o.30)){o.30=1h.9e(o.30)}P if(!o.30.dq){E}if(!o.1m){o.1m=g5}z.1m=o.1m;z.30=o.30;z.8r=o.3l;z.21=o.21;if(z.8r){k.3f.2R(z.8r)}z.a3=0;z.a2=0;if(k.dF){z.a3=(T(k.3f.B(\'5b\'))||0)+(T(k.3f.B(\'5O\'))||0)+(T(k.3f.B(\'4X\'))||0)+(T(k.3f.B(\'5U\'))||0);z.a2=(T(k.3f.B(\'4S\'))||0)+(T(k.3f.B(\'5Q\'))||0)+(T(k.3f.B(\'5M\'))||0)+(T(k.3f.B(\'5n\'))||0)}z.26=k.23(k.1a.3w(z.el.K(0)),k.1a.2o(z.el.K(0)));z.2T=k.23(k.1a.3w(z.30),k.1a.2o(z.30));z.26.1C-=z.a3;z.26.hb-=z.a2;z.2T.1C-=z.a3;z.2T.hb-=z.a2;z.J=o.21;k.3f.B(\'Z\',z.26.1C+\'U\').B(\'W\',z.26.hb+\'U\').B(\'Q\',z.26.y+\'U\').B(\'O\',z.26.x+\'U\').5w({Q:z.2T.y,O:z.2T.x,Z:z.2T.1C,W:z.2T.hb},z.1m,u(){if(z.8r)k.3f.4i(z.8r);k.3f.B(\'19\',\'1o\');if(z.21&&z.21.1K==2A){z.21.1D(z.el.K(0),[z.30])}k.2H(z.el.K(0),\'1n\')})};k.1v={M:{2E:10,ec:\'1Q/iJ.eZ\',e3:\'<1T 2J="1Q/6g.da" />\',eW:0.8,d8:\'iN a6\',dc:\'57\',3W:8J},jQ:I,jW:I,6j:S,8m:I,8k:I,d1:u(2k){if(!k.1v.8k||k.1v.8m)E;D 3K=2k.7L||2k.7K||-1;3m(3K){1e 35:if(k.1v.6j)k.1v.26(S,k(\'a[@4I=\'+k.1v.6j+\']:jJ\').K(0));1r;1e 36:if(k.1v.6j)k.1v.26(S,k(\'a[@4I=\'+k.1v.6j+\']:jL\').K(0));1r;1e 37:1e 8:1e 33:1e 80:1e kb:D 9p=k(\'#87\');if(9p.K(0).53!=S){9p.K(0).53.1D(9p.K(0))}1r;1e 38:1r;1e 39:1e 34:1e 32:1e gl:1e 78:D 9k=k(\'#88\');if(9k.K(0).53!=S){9k.K(0).53.1D(9k.K(0))}1r;1e 40:1r;1e 27:k.1v.au();1r}},7q:u(M){if(M)k.23(k.1v.M,M);if(1X.2k){k(\'2e\',1h).1J(\'6y\',k.1v.d1)}P{k(1h).1J(\'6y\',k.1v.d1)}k(\'a\').1E(u(){el=k(q);en=el.1p(\'4I\')||\'\';e9=el.1p(\'3h\')||\'\';ev=/\\.da|\\.gw|\\.8X|\\.eZ|\\.gn/g;if(e9.6c().d5(ev)!=S&&en.6c().3J(\'eU\')==0){el.1J(\'5h\',k.1v.26)}});if(k.3a.4t){3A=1h.3F(\'3A\');k(3A).1p({id:\'cN\',2J:\'ek:I;\',ej:\'cD\',ep:\'cD\'}).B({19:\'1o\',Y:\'1P\',Q:\'0\',O:\'0\',5E:\'9n:9w.9y.cC(1G=0)\'});k(\'2e\').1S(3A)}8n=1h.3F(\'22\');k(8n).1p(\'id\',\'cP\').B({Y:\'1P\',19:\'1o\',Q:\'0\',O:\'0\',1G:0}).1S(1h.8M(\' \')).1J(\'5h\',k.1v.au);6A=1h.3F(\'22\');k(6A).1p(\'id\',\'eK\').B({4X:k.1v.M.2E+\'U\'}).1S(1h.8M(\' \'));cE=1h.3F(\'22\');k(cE).1p(\'id\',\'dg\').B({4X:k.1v.M.2E+\'U\',5n:k.1v.M.2E+\'U\'}).1S(1h.8M(\' \'));cF=1h.3F(\'a\');k(cF).1p({id:\'gg\',3h:\'#\'}).B({Y:\'1P\',2L:k.1v.M.2E+\'U\',Q:\'0\'}).1S(k.1v.M.e3).1J(\'5h\',k.1v.au);7m=1h.3F(\'22\');k(7m).1p(\'id\',\'cM\').B({Y:\'2s\',cA:\'O\',6w:\'0 9F\',3I:1}).1S(6A).1S(cE).1S(cF);2b=1h.3F(\'1T\');2b.2J=k.1v.M.ec;k(2b).1p(\'id\',\'eM\').B({Y:\'1P\'});4G=1h.3F(\'a\');k(4G).1p({id:\'87\',3h:\'#\'}).B({Y:\'1P\',19:\'1o\',2U:\'2K\',ey:\'1o\'}).1S(1h.8M(\' \'));4M=1h.3F(\'a\');k(4M).1p({id:\'88\',3h:\'#\'}).B({Y:\'1P\',2U:\'2K\',ey:\'1o\'}).1S(1h.8M(\' \'));1Z=1h.3F(\'22\');k(1Z).1p(\'id\',\'eE\').B({19:\'1o\',Y:\'2s\',2U:\'2K\',cA:\'O\',6w:\'0 9F\',Q:\'0\',O:\'0\',3I:2}).1S([2b,4G,4M]);6F=1h.3F(\'22\');k(6F).1p(\'id\',\'ao\').B({19:\'1o\',Y:\'1P\',2U:\'2K\',Q:\'0\',O:\'0\',cA:\'cv\',7i:\'cu\',hC:\'0\'}).1S([1Z,7m]);k(\'2e\').1S(8n).1S(6F)},26:u(e,C){el=C?k(C):k(q);9t=el.1p(\'4I\');D 6B,4u,4G,4M;if(9t!=\'eU\'){k.1v.6j=9t;8Y=k(\'a[@4I=\'+9t+\']\');6B=8Y.1N();4u=8Y.cZ(C?C:q);4G=8Y.K(4u-1);4M=8Y.K(4u+1)}89=el.1p(\'3h\');6A=el.1p(\'4g\');3O=k.1a.6z();8n=k(\'#cP\');if(!k.1v.8k){k.1v.8k=1b;if(k.3a.4t){k(\'#cN\').B(\'W\',18.3r(3O.ih,3O.h)+\'U\').B(\'Z\',18.3r(3O.iw,3O.w)+\'U\').1Y()}8n.B(\'W\',18.3r(3O.ih,3O.h)+\'U\').B(\'Z\',18.3r(3O.iw,3O.w)+\'U\').1Y().fX(cO,k.1v.M.eW,u(){k.1v.cw(89,6A,3O,6B,4u,4G,4M)});k(\'#ao\').B(\'Z\',18.3r(3O.iw,3O.w)+\'U\')}P{k(\'#87\').K(0).53=S;k(\'#88\').K(0).53=S;k.1v.cw(89,6A,3O,6B,4u,4G,4M)}E I},cw:u(89,gP,3O,6B,4u,4G,4M){k(\'#cW\').bk();aX=k(\'#87\');aX.2G();aO=k(\'#88\');aO.2G();2b=k(\'#eM\');1Z=k(\'#eE\');6F=k(\'#ao\');7m=k(\'#cM\').B(\'3n\',\'2K\');k(\'#eK\').3x(6A);k.1v.8m=1b;if(6B)k(\'#dg\').3x(k.1v.M.d8+\' \'+(4u+1)+\' \'+k.1v.M.dc+\' \'+6B);if(4G){aX.K(0).53=u(){q.5B();k.1v.26(S,4G);E I}}if(4M){aO.K(0).53=u(){q.5B();k.1v.26(S,4M);E I}}2b.1Y();82=k.1a.2o(1Z.K(0));56=18.3r(82.1C,2b.K(0).Z+k.1v.M.2E*2);6f=18.3r(82.hb,2b.K(0).W+k.1v.M.2E*2);2b.B({O:(56-2b.K(0).Z)/2+\'U\',Q:(6f-2b.K(0).W)/2+\'U\'});1Z.B({Z:56+\'U\',W:6f+\'U\'}).1Y();dw=k.1a.bm();6F.B(\'Q\',3O.t+(dw.h/15)+\'U\');if(6F.B(\'19\')==\'1o\'){6F.1Y().7f(k.1v.M.3W)}6k=12 9s;k(6k).1p(\'id\',\'cW\').1J(\'hJ\',u(){56=6k.Z+k.1v.M.2E*2;6f=6k.W+k.1v.M.2E*2;2b.2G();1Z.5w({W:6f},82.hb!=6f?k.1v.M.3W:1,u(){1Z.5w({Z:56},82.1C!=56?k.1v.M.3W:1,u(){1Z.bG(6k);k(6k).B({Y:\'1P\',O:k.1v.M.2E+\'U\',Q:k.1v.M.2E+\'U\'}).7f(k.1v.M.3W,u(){db=k.1a.2o(7m.K(0));if(4G){aX.B({O:k.1v.M.2E+\'U\',Q:k.1v.M.2E+\'U\',Z:56/2-k.1v.M.2E*3+\'U\',W:6f-k.1v.M.2E*2+\'U\'}).1Y()}if(4M){aO.B({O:56/2+k.1v.M.2E*2+\'U\',Q:k.1v.M.2E+\'U\',Z:56/2-k.1v.M.2E*3+\'U\',W:6f-k.1v.M.2E*2+\'U\'}).1Y()}7m.B({Z:56+\'U\',Q:-db.hb+\'U\',3n:\'dd\'}).5w({Q:-1},k.1v.M.3W,u(){k.1v.8m=I})})})})});6k.2J=89},au:u(){k(\'#cW\').bk();k(\'#ao\').2G();k(\'#cM\').B(\'3n\',\'2K\');k(\'#cP\').fX(cO,0,u(){k(q).2G();if(k.3a.4t){k(\'#cN\').2G()}});k(\'#87\').K(0).53=S;k(\'#88\').K(0).53=S;k.1v.6j=S;k.1v.8k=I;k.1v.8m=I;E I}};k.R={1A:S,41:S,F:S,1s:S,1q:S,Y:S,9a:u(e){k.R.F=(q.d0)?q.d0:q;k.R.1s=k.1a.4a(e);k.R.1q={Z:T(k(k.R.F).B(\'Z\'))||0,W:T(k(k.R.F).B(\'W\'))||0};k.R.Y={Q:T(k(k.R.F).B(\'Q\'))||0,O:T(k(k.R.F).B(\'O\'))||0};k(1h).1J(\'3D\',k.R.cR).1J(\'5P\',k.R.cK);if(2g k.R.F.1k.g2===\'u\'){k.R.F.1k.g2.1D(k.R.F)}E I},cK:u(e){k(1h).3q(\'3D\',k.R.cR).3q(\'5P\',k.R.cK);if(2g k.R.F.1k.fN===\'u\'){k.R.F.1k.fN.1D(k.R.F)}k.R.F=S},cR:u(e){if(!k.R.F){E}1s=k.1a.4a(e);7p=k.R.Y.Q-k.R.1s.y+1s.y;7r=k.R.Y.O-k.R.1s.x+1s.x;7p=18.3r(18.3L(7p,k.R.F.1k.8g-k.R.1q.W),k.R.F.1k.7h);7r=18.3r(18.3L(7r,k.R.F.1k.8h-k.R.1q.Z),k.R.F.1k.70);if(2g k.R.F.1k.4m===\'u\'){D 8a=k.R.F.1k.4m.1D(k.R.F,[7r,7p]);if(2g 8a==\'hh\'&&8a.1g==2){7r=8a[0];7p=8a[1]}}k.R.F.14.Q=7p+\'U\';k.R.F.14.O=7r+\'U\';E I},26:u(e){k(1h).1J(\'3D\',k.R.8j).1J(\'5P\',k.R.8o);k.R.1A=q.1A;k.R.41=q.41;k.R.1s=k.1a.4a(e);k.R.1q={Z:T(k(q.1A).B(\'Z\'))||0,W:T(k(q.1A).B(\'W\'))||0};k.R.Y={Q:T(k(q.1A).B(\'Q\'))||0,O:T(k(q.1A).B(\'O\'))||0};if(k.R.1A.1k.4o){k.R.1A.1k.4o.1D(k.R.1A,[q])}E I},8o:u(){k(1h).3q(\'3D\',k.R.8j).3q(\'5P\',k.R.8o);if(k.R.1A.1k.3T){k.R.1A.1k.3T.1D(k.R.1A,[k.R.41])}k.R.1A=S;k.R.41=S},6i:u(dx,az){E 18.3L(18.3r(k.R.1q.Z+dx*az,k.R.1A.1k.av),k.R.1A.1k.6x)},6m:u(dy,az){E 18.3L(18.3r(k.R.1q.W+dy*az,k.R.1A.1k.8c),k.R.1A.1k.8b)},fb:u(W){E 18.3L(18.3r(W,k.R.1A.1k.8c),k.R.1A.1k.8b)},8j:u(e){if(k.R.1A==S){E}1s=k.1a.4a(e);dx=1s.x-k.R.1s.x;dy=1s.y-k.R.1s.y;1I={Z:k.R.1q.Z,W:k.R.1q.W};2z={Q:k.R.Y.Q,O:k.R.Y.O};3m(k.R.41){1e\'e\':1I.Z=k.R.6i(dx,1);1r;1e\'fj\':1I.Z=k.R.6i(dx,1);1I.W=k.R.6m(dy,1);1r;1e\'w\':1I.Z=k.R.6i(dx,-1);2z.O=k.R.Y.O-1I.Z+k.R.1q.Z;1r;1e\'5F\':1I.Z=k.R.6i(dx,-1);2z.O=k.R.Y.O-1I.Z+k.R.1q.Z;1I.W=k.R.6m(dy,1);1r;1e\'76\':1I.W=k.R.6m(dy,-1);2z.Q=k.R.Y.Q-1I.W+k.R.1q.W;1I.Z=k.R.6i(dx,-1);2z.O=k.R.Y.O-1I.Z+k.R.1q.Z;1r;1e\'n\':1I.W=k.R.6m(dy,-1);2z.Q=k.R.Y.Q-1I.W+k.R.1q.W;1r;1e\'at\':1I.W=k.R.6m(dy,-1);2z.Q=k.R.Y.Q-1I.W+k.R.1q.W;1I.Z=k.R.6i(dx,1);1r;1e\'s\':1I.W=k.R.6m(dy,1);1r}if(k.R.1A.1k.4v){if(k.R.41==\'n\'||k.R.41==\'s\')4p=1I.W*k.R.1A.1k.4v;P 4p=1I.Z;4W=k.R.fb(4p*k.R.1A.1k.4v);4p=4W/k.R.1A.1k.4v;3m(k.R.41){1e\'n\':1e\'76\':1e\'at\':2z.Q+=1I.W-4W;1r}3m(k.R.41){1e\'76\':1e\'w\':1e\'5F\':2z.O+=1I.Z-4p;1r}1I.W=4W;1I.Z=4p}if(2z.Q<k.R.1A.1k.7h){4W=1I.W+2z.Q-k.R.1A.1k.7h;2z.Q=k.R.1A.1k.7h;if(k.R.1A.1k.4v){4p=4W/k.R.1A.1k.4v;3m(k.R.41){1e\'76\':1e\'w\':1e\'5F\':2z.O+=1I.Z-4p;1r}1I.Z=4p}1I.W=4W}if(2z.O<k.R.1A.1k.70){4p=1I.Z+2z.O-k.R.1A.1k.70;2z.O=k.R.1A.1k.70;if(k.R.1A.1k.4v){4W=4p*k.R.1A.1k.4v;3m(k.R.41){1e\'n\':1e\'76\':1e\'at\':2z.Q+=1I.W-4W;1r}1I.W=4W}1I.Z=4p}if(2z.Q+1I.W>k.R.1A.1k.8g){1I.W=k.R.1A.1k.8g-2z.Q;if(k.R.1A.1k.4v){1I.Z=1I.W/k.R.1A.1k.4v}}if(2z.O+1I.Z>k.R.1A.1k.8h){1I.Z=k.R.1A.1k.8h-2z.O;if(k.R.1A.1k.4v){1I.W=1I.Z*k.R.1A.1k.4v}}D 6p=I;if(k.R.1A.1k.f7){6p=k.R.1A.1k.f7.1D(k.R.1A,[1I,2z]);if(6p){if(6p.1q){k.23(1I,6p.1q)}if(6p.Y){k.23(2z,6p.Y)}}}8d=k.R.1A.14;8d.O=2z.O+\'U\';8d.Q=2z.Q+\'U\';8d.Z=1I.Z+\'U\';8d.W=1I.W+\'U\';E I},2r:u(M){if(!M||!M.3Z||M.3Z.1K!=7M){E}E q.1E(u(){D el=q;el.1k=M;el.1k.av=M.av||10;el.1k.8c=M.8c||10;el.1k.6x=M.6x||6P;el.1k.8b=M.8b||6P;el.1k.7h=M.7h||-aC;el.1k.70=M.70||-aC;el.1k.8h=M.8h||6P;el.1k.8g=M.8g||6P;d6=k(el).B(\'Y\');if(!(d6==\'2s\'||d6==\'1P\')){el.14.Y=\'2s\'}fS=/n|at|e|fj|s|5F|w|76/g;24(i in el.1k.3Z){if(i.6c().d5(fS)!=S){if(el.1k.3Z[i].1K==b0){3v=k(el.1k.3Z[i]);if(3v.1N()>0){el.1k.3Z[i]=3v.K(0)}}if(el.1k.3Z[i].4Y){el.1k.3Z[i].1A=el;el.1k.3Z[i].41=i;k(el.1k.3Z[i]).1J(\'5v\',k.R.26)}}}if(el.1k.5S){if(2g el.1k.5S===\'4V\'){aV=k(el.1k.5S);if(aV.1N()>0){aV.1E(u(){q.d0=el});aV.1J(\'5v\',k.R.9a)}}P if(el.1k.5S==1b){k(q).1J(\'5v\',k.R.9a)}}})},4U:u(){E q.1E(u(){D el=q;24(i in el.1k.3Z){el.1k.3Z[i].1A=S;el.1k.3Z[i].41=S;k(el.1k.3Z[i]).3q(\'5v\',k.R.26)}if(el.1k.5S){if(2g el.1k.5S===\'4V\'){3v=k(el.1k.5S);if(3v.1N()>0){3v.3q(\'5v\',k.R.9a)}}P if(el.1k.5S==1b){k(q).3q(\'5v\',k.R.9a)}}el.1k=S})}};k.fn.23({hz:k.R.2r,hs:k.R.4U});k.2C=S;k.7n=I;k.3k=S;k.7o=[];k.9v=u(e){D 3K=e.7L||e.7K||-1;if(3K==17||3K==16){k.7n=1b}};k.9u=u(e){k.7n=I};k.dL=u(e){q.f.1s=k.1a.4a(e);q.f.1M=k.23(k.1a.3w(q),k.1a.2o(q));q.f.3e=k.1a.6z(q);q.f.1s.x-=q.f.1M.x;q.f.1s.y-=q.f.1M.y;k(q).1S(k.2C.K(0));if(q.f.hc)k.2C.2R(q.f.hc).B(\'19\',\'2B\');k.2C.B({19:\'2B\',Z:\'2P\',W:\'2P\'});if(q.f.o){k.2C.B(\'1G\',q.f.o)}k.3k=q;k.96=I;k.7o=[];q.f.el.1E(u(){q.1M={x:q.8t+(q.4Z&&!k.3a.7I?T(q.4Z.5b)||0:0)+(k.3k.3c||0),y:q.8G+(q.4Z&&!k.3a.7I?T(q.4Z.4S)||0:0)+(k.3k.3d||0),1C:q.4c,hb:q.5W};if(q.s==1b){if(k.7n==I){q.s=I;k(q).4i(k.3k.f.7j)}P{k.96=1b;k.7o[k.7o.1g]=k.1p(q,\'id\')}}});k.am.1D(q,[e]);k(1h).1J(\'3D\',k.am).1J(\'5P\',k.cX);E I};k.am=u(e){if(!k.3k)E;k.fd.1D(k.3k,[e])};k.fd=u(e){if(!k.3k)E;D 1s=k.1a.4a(e);D 3e=k.1a.6z(k.3k);1s.x+=3e.l-q.f.3e.l-q.f.1M.x;1s.y+=3e.t-q.f.3e.t-q.f.1M.y;D 93=18.3L(1s.x,q.f.1s.x);D 5F=18.3L(18.3S(1s.x-q.f.1s.x),18.3S(q.f.3e.w-93));D 99=18.3L(1s.y,q.f.1s.y);D 9g=18.3L(18.3S(1s.y-q.f.1s.y),18.3S(q.f.3e.h-99));if(q.3d>0&&1s.y-20<q.3d){D 3X=18.3L(3e.t,10);99-=3X;9g+=3X;q.3d-=3X}P if(q.3d+q.f.1M.h<q.f.3e.h&&1s.y+20>q.3d+q.f.1M.h){D 3X=18.3L(q.f.3e.h-q.3d,10);q.3d+=3X;if(q.3d!=3e.t)9g+=3X}if(q.3c>0&&1s.x-20<q.3c){D 3X=18.3L(3e.l,10);93-=3X;5F+=3X;q.3c-=3X}P if(q.3c+q.f.1M.w<q.f.3e.w&&1s.x+20>q.3c+q.f.1M.w){D 3X=18.3L(q.f.3e.w-q.3c,10);q.3c+=3X;if(q.3c!=3e.l)5F+=3X}k.2C.B({O:93+\'U\',Q:99+\'U\',Z:5F+\'U\',W:9g+\'U\'});k.2C.l=93+q.f.3e.l;k.2C.t=99+q.f.3e.t;k.2C.r=k.2C.l+5F;k.2C.b=k.2C.t+9g;k.96=I;q.f.el.1E(u(){aw=k.7o.3J(k.1p(q,\'id\'));if(!(q.1M.x>k.2C.r||(q.1M.x+q.1M.1C)<k.2C.l||q.1M.y>k.2C.b||(q.1M.y+q.1M.hb)<k.2C.t)){k.96=1b;if(q.s!=1b){q.s=1b;k(q).2R(k.3k.f.7j)}if(aw!=-1){q.s=I;k(q).4i(k.3k.f.7j)}}P if((q.s==1b)&&(aw==-1)){q.s=I;k(q).4i(k.3k.f.7j)}P if((!q.s)&&(k.7n==1b)&&(aw!=-1)){q.s=1b;k(q).2R(k.3k.f.7j)}});E I};k.cX=u(e){if(!k.3k)E;k.g0.1D(k.3k,[e])};k.g0=u(e){k(1h).3q(\'3D\',k.am).3q(\'5P\',k.cX);if(!k.3k)E;k.2C.B(\'19\',\'1o\');if(q.f.hc)k.2C.4i(q.f.hc);k.3k=I;k(\'2e\').1S(k.2C.K(0));if(k.96==1b){if(q.f.98)q.f.98(k.cJ(k.1p(q,\'id\')))}P{if(q.f.9d)q.f.9d(k.cJ(k.1p(q,\'id\')))}k.7o=[]};k.cJ=u(s){D h=\'\';D o=[];if(a=k(\'#\'+s)){a.K(0).f.el.1E(u(){if(q.s==1b){if(h.1g>0){h+=\'&\'}h+=s+\'[]=\'+k.1p(q,\'id\');o[o.1g]=k.1p(q,\'id\')}})}E{7l:h,o:o}};k.fn.gZ=u(o){if(!k.2C){k(\'2e\',1h).1S(\'<22 id="2C"></22>\').1J(\'7B\',k.9v).1J(\'6y\',k.9u);k.2C=k(\'#2C\');k.2C.B({Y:\'1P\',19:\'1o\'});if(1X.2k){k(\'2e\',1h).1J(\'7B\',k.9v).1J(\'6y\',k.9u)}P{k(1h).1J(\'7B\',k.9v).1J(\'6y\',k.9u)}}if(!o){o={}}E q.1E(u(){if(q.eP)E;q.eP=1b;q.f={a:o.3C,o:o.1G?2m(o.1G):I,7j:o.eS?o.eS:I,hc:o.58?o.58:I,98:o.98?o.98:I,9d:o.9d?o.9d:I};q.f.el=k(\'.\'+o.3C);k(q).1J(\'5v\',k.dL).B(\'Y\',\'2s\')})};k.3b={bM:1,eH:u(3t){D 3t=3t;E q.1E(u(){q.4z.6s.1E(u(ab){k.3b.5c(q,3t[ab])})})},K:u(){D 3t=[];q.1E(u(cL){if(q.bI){3t[cL]=[];D C=q;D 1q=k.1a.2o(q);q.4z.6s.1E(u(ab){D x=q.8t;D y=q.8G;92=T(x*2a/(1q.w-q.4c));91=T(y*2a/(1q.h-q.5W));3t[cL][ab]=[92||0,91||0,x||0,y||0]})}});E 3t},ct:u(C){C.A.fu=C.A.28.w-C.A.1B.1C;C.A.fw=C.A.28.h-C.A.1B.hb;if(C.9r.4z.bC){9Z=C.9r.4z.6s.K(C.bF+1);if(9Z){C.A.28.w=(T(k(9Z).B(\'O\'))||0)+C.A.1B.1C;C.A.28.h=(T(k(9Z).B(\'Q\'))||0)+C.A.1B.hb}9Q=C.9r.4z.6s.K(C.bF-1);if(9Q){D cU=T(k(9Q).B(\'O\'))||0;D cH=T(k(9Q).B(\'O\'))||0;C.A.28.x+=cU;C.A.28.y+=cH;C.A.28.w-=cU;C.A.28.h-=cH}}C.A.g7=C.A.28.w-C.A.1B.1C;C.A.eC=C.A.28.h-C.A.1B.hb;if(C.A.2O){C.A.gx=((C.A.28.w-C.A.1B.1C)/C.A.2O)||1;C.A.gy=((C.A.28.h-C.A.1B.hb)/C.A.2O)||1;C.A.fU=C.A.g7/C.A.2O;C.A.fH=C.A.eC/C.A.2O}C.A.28.dx=C.A.28.x-C.A.2c.x;C.A.28.dy=C.A.28.y-C.A.2c.y;k.11.1c.B(\'9b\',\'ad\')},3H:u(C,x,y){if(C.A.2O){fE=T(x/C.A.fU);92=fE*2a/C.A.2O;ft=T(y/C.A.fH);91=ft*2a/C.A.2O}P{92=T(x*2a/C.A.fu);91=T(y*2a/C.A.fw)}C.A.b3=[92||0,91||0,x||0,y||0];if(C.A.3H)C.A.3H.1D(C,C.A.b3)},eI:u(2k){3K=2k.7L||2k.7K||-1;3m(3K){1e 35:k.3b.5c(q.3U,[ae,ae]);1r;1e 36:k.3b.5c(q.3U,[-ae,-ae]);1r;1e 37:k.3b.5c(q.3U,[-q.3U.A.gx||-1,0]);1r;1e 38:k.3b.5c(q.3U,[0,-q.3U.A.gy||-1]);1r;1e 39:k.3b.5c(q.3U,[q.3U.A.gx||1,0]);1r;1e 40:k.11.5c(q.3U,[0,q.3U.A.gy||1]);1r}},5c:u(C,Y){if(!C.A){E}C.A.1B=k.23(k.1a.3w(C),k.1a.2o(C));C.A.2c={x:T(k.B(C,\'O\'))||0,y:T(k.B(C,\'Q\'))||0};C.A.4n=k.B(C,\'Y\');if(C.A.4n!=\'2s\'&&C.A.4n!=\'1P\'){C.14.Y=\'2s\'}k.11.c5(C);k.3b.ct(C);dx=T(Y[0])||0;dy=T(Y[1])||0;2v=C.A.2c.x+dx;2q=C.A.2c.y+dy;if(C.A.2O){3y=k.11.c7.1D(C,[2v,2q,dx,dy]);if(3y.1K==7M){dx=3y.dx;dy=3y.dy}2v=C.A.2c.x+dx;2q=C.A.2c.y+dy}3y=k.11.ce.1D(C,[2v,2q,dx,dy]);if(3y&&3y.1K==7M){dx=3y.dx;dy=3y.dy}2v=C.A.2c.x+dx;2q=C.A.2c.y+dy;if(C.A.5i&&(C.A.3H||C.A.2Z)){k.3b.3H(C,2v,2q)}2v=!C.A.1O||C.A.1O==\'4j\'?2v:C.A.2c.x||0;2q=!C.A.1O||C.A.1O==\'49\'?2q:C.A.2c.y||0;C.14.O=2v+\'U\';C.14.Q=2q+\'U\'},2r:u(o){E q.1E(u(){if(q.bI==1b||!o.3C||!k.1a||!k.11||!k.1x){E}5x=k(o.3C,q);if(5x.1N()==0){E}D 4N={2p:\'94\',5i:1b,3H:o.3H&&o.3H.1K==2A?o.3H:S,2Z:o.2Z&&o.2Z.1K==2A?o.2Z:S,3v:q,1G:o.1G||I};if(o.2O&&T(o.2O)){4N.2O=T(o.2O)||1;4N.2O=4N.2O>0?4N.2O:1}if(5x.1N()==1)5x.7t(4N);P{k(5x.K(0)).7t(4N);4N.3v=S;5x.7t(4N)}5x.7B(k.3b.eI);5x.1p(\'bM\',k.3b.bM++);q.bI=1b;q.4z={};q.4z.er=4N.er;q.4z.2O=4N.2O;q.4z.6s=5x;q.4z.bC=o.bC?1b:I;bZ=q;bZ.4z.6s.1E(u(2N){q.bF=2N;q.9r=bZ});if(o.3t&&o.3t.1K==7F){24(i=o.3t.1g-1;i>=0;i--){if(o.3t[i].1K==7F&&o.3t[i].1g==2){el=q.4z.6s.K(i);if(el.4Y){k.3b.5c(el,o.3t[i])}}}}})}};k.fn.23({hN:k.3b.2r,hS:k.3b.eH,hG:k.3b.K});k.2u={5I:[],eg:u(){q.5B();X=q.31;id=k.1p(X,\'id\');if(k.2u.5I[id]!=S){1X.5T(k.2u.5I[id])}1z=X.L.3u+1;if(X.L.1Q.1g<1z){1z=1}1Q=k(\'1T\',X.L.5u);X.L.3u=1z;if(1Q.1N()>0){1Q.7a(X.L.3W,k.2u.95)}},dp:u(){q.5B();X=q.31;id=k.1p(X,\'id\');if(k.2u.5I[id]!=S){1X.5T(k.2u.5I[id])}1z=X.L.3u-1;1Q=k(\'1T\',X.L.5u);if(1z<1){1z=X.L.1Q.1g}X.L.3u=1z;if(1Q.1N()>0){1Q.7a(X.L.3W,k.2u.95)}},2I:u(c){X=1h.9e(c);if(X.L.6o){1z=X.L.3u;7d(1z==X.L.3u){1z=1+T(18.6o()*X.L.1Q.1g)}}P{1z=X.L.3u+1;if(X.L.1Q.1g<1z){1z=1}}1Q=k(\'1T\',X.L.5u);X.L.3u=1z;if(1Q.1N()>0){1Q.7a(X.L.3W,k.2u.95)}},go:u(o){D X;if(o&&o.1K==7M){if(o.2b){X=1h.9e(o.2b.X);5N=1X.hn.3h.7C("#");o.2b.6S=S;if(5N.1g==2){1z=T(5N[1]);1Y=5N[1].4E(1z,\'\');if(k.1p(X,\'id\')!=1Y){1z=1}}P{1z=1}}if(o.90){o.90.5B();X=o.90.31.31;id=k.1p(X,\'id\');if(k.2u.5I[id]!=S){1X.5T(k.2u.5I[id])}5N=o.90.3h.7C("#");1z=T(5N[1]);1Y=5N[1].4E(1z,\'\');if(k.1p(X,\'id\')!=1Y){1z=1}}if(X.L.1Q.1g<1z||1z<1){1z=1}X.L.3u=1z;52=k.1a.2o(X);dt=k.1a.aT(X);d9=k.1a.6U(X);if(X.L.3z){X.L.3z.o.B(\'19\',\'1o\')}if(X.L.3s){X.L.3s.o.B(\'19\',\'1o\')}if(X.L.2b){y=T(dt.t)+T(d9.t);if(X.L.1U){if(X.L.1U.5A==\'Q\'){y+=X.L.1U.4C.hb}P{52.h-=X.L.1U.4C.hb}}if(X.L.2x){if(X.L.2x&&X.L.2x.6Q==\'Q\'){y+=X.L.2x.4C.hb}P{52.h-=X.L.2x.4C.hb}}if(!X.L.c1){X.L.df=o.2b?o.2b.W:(T(X.L.2b.B(\'W\'))||0);X.L.c1=o.2b?o.2b.Z:(T(X.L.2b.B(\'Z\'))||0)}X.L.2b.B(\'Q\',y+(52.h-X.L.df)/2+\'U\');X.L.2b.B(\'O\',(52.1C-X.L.c1)/2+\'U\');X.L.2b.B(\'19\',\'2B\')}1Q=k(\'1T\',X.L.5u);if(1Q.1N()>0){1Q.7a(X.L.3W,k.2u.95)}P{aj=k(\'a\',X.L.1U.o).K(1z-1);k(aj).2R(X.L.1U.5R);D 1T=12 9s();1T.X=k.1p(X,\'id\');1T.1z=1z-1;1T.2J=X.L.1Q[X.L.3u-1].2J;if(1T.21){1T.6S=S;k.2u.19.1D(1T)}P{1T.6S=k.2u.19}if(X.L.2x){X.L.2x.o.3x(X.L.1Q[1z-1].6L)}}}},95:u(){X=q.31.31;X.L.5u.B(\'19\',\'1o\');if(X.L.1U.5R){aj=k(\'a\',X.L.1U.o).4i(X.L.1U.5R).K(X.L.3u-1);k(aj).2R(X.L.1U.5R)}D 1T=12 9s();1T.X=k.1p(X,\'id\');1T.1z=X.L.3u-1;1T.2J=X.L.1Q[X.L.3u-1].2J;if(1T.21){1T.6S=S;k.2u.19.1D(1T)}P{1T.6S=k.2u.19}if(X.L.2x){X.L.2x.o.3x(X.L.1Q[X.L.3u-1].6L)}},19:u(){X=1h.9e(q.X);if(X.L.3z){X.L.3z.o.B(\'19\',\'1o\')}if(X.L.3s){X.L.3s.o.B(\'19\',\'1o\')}52=k.1a.2o(X);y=0;if(X.L.1U){if(X.L.1U.5A==\'Q\'){y+=X.L.1U.4C.hb}P{52.h-=X.L.1U.4C.hb}}if(X.L.2x){if(X.L.2x&&X.L.2x.6Q==\'Q\'){y+=X.L.2x.4C.hb}P{52.h-=X.L.2x.4C.hb}}hg=k(\'.ca\',X);y=y+(52.h-q.W)/2;x=(52.1C-q.Z)/2;X.L.5u.B(\'Q\',y+\'U\').B(\'O\',x+\'U\').3x(\'<1T 2J="\'+q.2J+\'" />\');X.L.5u.7f(X.L.3W);3s=X.L.3u+1;if(3s>X.L.1Q.1g){3s=1}3z=X.L.3u-1;if(3z<1){3z=X.L.1Q.1g}X.L.3s.o.B(\'19\',\'2B\').B(\'Q\',y+\'U\').B(\'O\',x+2*q.Z/3+\'U\').B(\'Z\',q.Z/3+\'U\').B(\'W\',q.W+\'U\').1p(\'4g\',X.L.1Q[3s-1].6L);X.L.3s.o.K(0).3h=\'#\'+3s+k.1p(X,\'id\');X.L.3z.o.B(\'19\',\'2B\').B(\'Q\',y+\'U\').B(\'O\',x+\'U\').B(\'Z\',q.Z/3+\'U\').B(\'W\',q.W+\'U\').1p(\'4g\',X.L.1Q[3z-1].6L);X.L.3z.o.K(0).3h=\'#\'+3z+k.1p(X,\'id\')},2r:u(o){if(!o||!o.1Z||k.2u.5I[o.1Z])E;D 1Z=k(\'#\'+o.1Z);D el=1Z.K(0);if(el.14.Y!=\'1P\'&&el.14.Y!=\'2s\'){el.14.Y=\'2s\'}el.14.2U=\'2K\';if(1Z.1N()==0)E;el.L={};el.L.1Q=o.1Q?o.1Q:[];el.L.6o=o.6o&&o.6o==1b||I;97=el.f3(\'hL\');24(i=0;i<97.1g;i++){7Z=el.L.1Q.1g;el.L.1Q[7Z]={2J:97[i].2J,6L:97[i].4g||97[i].hD||\'\'}}if(el.L.1Q.1g==0){E}el.L.4n=k.23(k.1a.3w(el),k.1a.2o(el));el.L.b5=k.1a.aT(el);el.L.bu=k.1a.6U(el);t=T(el.L.b5.t)+T(el.L.bu.t);b=T(el.L.b5.b)+T(el.L.bu.b);k(\'1T\',el).bk();el.L.3W=o.3W?o.3W:g5;if(o.5A||o.9f||o.5R){el.L.1U={};1Z.1S(\'<22 6T="g1"></22>\');el.L.1U.o=k(\'.g1\',el);if(o.9f){el.L.1U.9f=o.9f;el.L.1U.o.2R(o.9f)}if(o.5R){el.L.1U.5R=o.5R}el.L.1U.o.B(\'Y\',\'1P\').B(\'Z\',el.L.4n.w+\'U\');if(o.5A&&o.5A==\'Q\'){el.L.1U.5A=\'Q\';el.L.1U.o.B(\'Q\',t+\'U\')}P{el.L.1U.5A=\'4D\';el.L.1U.o.B(\'4D\',b+\'U\')}el.L.1U.aE=o.aE?o.aE:\' \';24(D i=0;i<el.L.1Q.1g;i++){7Z=T(i)+1;el.L.1U.o.1S(\'<a 3h="#\'+7Z+o.1Z+\'" 6T="gR" 4g="\'+el.L.1Q[i].6L+\'">\'+7Z+\'</a>\'+(7Z!=el.L.1Q.1g?el.L.1U.aE:\'\'))}k(\'a\',el.L.1U.o).1J(\'5h\',u(){k.2u.go({90:q})});el.L.1U.4C=k.1a.2o(el.L.1U.o.K(0))}if(o.6Q||o.9c){el.L.2x={};1Z.1S(\'<22 6T="dn">&7k;</22>\');el.L.2x.o=k(\'.dn\',el);if(o.9c){el.L.2x.9c=o.9c;el.L.2x.o.2R(o.9c)}el.L.2x.o.B(\'Y\',\'1P\').B(\'Z\',el.L.4n.w+\'U\');if(o.6Q&&o.6Q==\'Q\'){el.L.2x.6Q=\'Q\';el.L.2x.o.B(\'Q\',(el.L.1U&&el.L.1U.5A==\'Q\'?el.L.1U.4C.hb+t:t)+\'U\')}P{el.L.2x.6Q=\'4D\';el.L.2x.o.B(\'4D\',(el.L.1U&&el.L.1U.5A==\'4D\'?el.L.1U.4C.hb+b:b)+\'U\')}el.L.2x.4C=k.1a.2o(el.L.2x.o.K(0))}if(o.9D){el.L.3s={9D:o.9D};1Z.1S(\'<a 3h="#2\'+o.1Z+\'" 6T="eY">&7k;</a>\');el.L.3s.o=k(\'.eY\',el);el.L.3s.o.B(\'Y\',\'1P\').B(\'19\',\'1o\').B(\'2U\',\'2K\').B(\'4A\',\'eR\').2R(el.L.3s.9D);el.L.3s.o.1J(\'5h\',k.2u.eg)}if(o.9o){el.L.3z={9o:o.9o};1Z.1S(\'<a 3h="#0\'+o.1Z+\'" 6T="ee">&7k;</a>\');el.L.3z.o=k(\'.ee\',el);el.L.3z.o.B(\'Y\',\'1P\').B(\'19\',\'1o\').B(\'2U\',\'2K\').B(\'4A\',\'eR\').2R(el.L.3z.9o);el.L.3z.o.1J(\'5h\',k.2u.dp)}1Z.bG(\'<22 6T="ca"></22>\');el.L.5u=k(\'.ca\',el);el.L.5u.B(\'Y\',\'1P\').B(\'Q\',\'2P\').B(\'O\',\'2P\').B(\'19\',\'1o\');if(o.2b){1Z.bG(\'<22 6T="dW" 14="19: 1o;"><1T 2J="\'+o.2b+\'" /></22>\');el.L.2b=k(\'.dW\',el);el.L.2b.B(\'Y\',\'1P\');D 1T=12 9s();1T.X=o.1Z;1T.2J=o.2b;if(1T.21){1T.6S=S;k.2u.go({2b:1T})}P{1T.6S=u(){k.2u.go({2b:q})}}}P{k.2u.go({1Z:el})}if(o.cS){fi=T(o.cS)*aC}k.2u.5I[o.1Z]=o.cS?1X.6V(\'k.2u.2I(\\\'\'+o.1Z+\'\\\')\',fi):S}};k.X=k.2u.2r;k.1t={7s:[],5L:{},1c:I,7u:S,26:u(){if(k.11.F==S){E}D 4O,3G,c,cs;k.1t.1c.K(0).3l=k.11.F.A.6R;4O=k.1t.1c.K(0).14;4O.19=\'2B\';k.1t.1c.1B=k.23(k.1a.3w(k.1t.1c.K(0)),k.1a.2o(k.1t.1c.K(0)));4O.Z=k.11.F.A.1B.1C+\'U\';4O.W=k.11.F.A.1B.hb+\'U\';3G=k.1a.cy(k.11.F);4O.5K=3G.t;4O.5z=3G.r;4O.5k=3G.b;4O.5j=3G.l;if(k.11.F.A.46==1b){c=k.11.F.fI(1b);cs=c.14;cs.5K=\'2P\';cs.5z=\'2P\';cs.5k=\'2P\';cs.5j=\'2P\';cs.19=\'2B\';k.1t.1c.5o().1S(c)}k(k.11.F).f5(k.1t.1c.K(0));k.11.F.14.19=\'1o\'},fC:u(e){if(!e.A.44&&k.1x.5r.cQ){if(e.A.3T)e.A.3T.1D(F);k(e).B(\'Y\',e.A.cz||e.A.4n);k(e).aS();k(k.1x.5r).f6(e)}k.1t.1c.4i(e.A.6R).3x(\'&7k;\');k.1t.7u=S;D 4O=k.1t.1c.K(0).14;4O.19=\'1o\';k.1t.1c.f5(e);if(e.A.fx>0){k(e).7f(e.A.fx)}k(\'2e\').1S(k.1t.1c.K(0));D 86=[];D 8q=I;24(D i=0;i<k.1t.7s.1g;i++){D 1j=k.1x.3P[k.1t.7s[i]].K(0);D id=k.1p(1j,\'id\');D 8i=k.1t.8x(id);if(1j.1i.ay!=8i.7l){1j.1i.ay=8i.7l;if(8q==I&&1j.1i.2Z){8q=1j.1i.2Z}8i.id=id;86[86.1g]=8i}}k.1t.7s=[];if(8q!=I&&86.1g>0){8q(86)}},al:u(e,o){if(!k.11.F)E;D 6e=I;D i=0;if(e.1i.el.1N()>0){24(i=e.1i.el.1N();i>0;i--){if(e.1i.el.K(i-1)!=k.11.F){if(!e.5V.b2){if((e.1i.el.K(i-1).1M.y+e.1i.el.K(i-1).1M.hb/2)>k.11.F.A.2q){6e=e.1i.el.K(i-1)}P{1r}}P{if((e.1i.el.K(i-1).1M.x+e.1i.el.K(i-1).1M.1C/2)>k.11.F.A.2v&&(e.1i.el.K(i-1).1M.y+e.1i.el.K(i-1).1M.hb/2)>k.11.F.A.2q){6e=e.1i.el.K(i-1)}}}}}if(6e&&k.1t.7u!=6e){k.1t.7u=6e;k(6e).h5(k.1t.1c.K(0))}P if(!6e&&(k.1t.7u!=S||k.1t.1c.K(0).31!=e)){k.1t.7u=S;k(e).1S(k.1t.1c.K(0))}k.1t.1c.K(0).14.19=\'2B\'},cT:u(e){if(k.11.F==S){E}e.1i.el.1E(u(){q.1M=k.23(k.1a.74(q),k.1a.7G(q))})},8x:u(s){D i;D h=\'\';D o={};if(s){if(k.1t.5L[s]){o[s]=[];k(\'#\'+s+\' .\'+k.1t.5L[s]).1E(u(){if(h.1g>0){h+=\'&\'}h+=s+\'[]=\'+k.1p(q,\'id\');o[s][o[s].1g]=k.1p(q,\'id\')})}P{24(a in s){if(k.1t.5L[s[a]]){o[s[a]]=[];k(\'#\'+s[a]+\' .\'+k.1t.5L[s[a]]).1E(u(){if(h.1g>0){h+=\'&\'}h+=s[a]+\'[]=\'+k.1p(q,\'id\');o[s[a]][o[s[a]].1g]=k.1p(q,\'id\')})}}}}P{24(i in k.1t.5L){o[i]=[];k(\'#\'+i+\' .\'+k.1t.5L[i]).1E(u(){if(h.1g>0){h+=\'&\'}h+=i+\'[]=\'+k.1p(q,\'id\');o[i][o[i].1g]=k.1p(q,\'id\')})}}E{7l:h,o:o}},fF:u(e){if(!e.dq){E}E q.1E(u(){if(!q.5V||!k(e).is(\'.\'+q.5V.3C))k(e).2R(q.5V.3C);k(e).7t(q.5V.A)})},4U:u(){E q.1E(u(){k(\'.\'+q.5V.3C).aS();k(q).dR();q.5V=S;q.fm=S})},2r:u(o){if(o.3C&&k.1a&&k.11&&k.1x){if(!k.1t.1c){k(\'2e\',1h).1S(\'<22 id="e5">&7k;</22>\');k.1t.1c=k(\'#e5\');k.1t.1c.K(0).14.19=\'1o\'}q.do({3C:o.3C,9J:o.9J?o.9J:I,a5:o.a5?o.a5:I,58:o.58?o.58:I,7x:o.7x||o.dC,7y:o.7y||o.fO,cQ:1b,2Z:o.2Z||o.ia,fx:o.fx?o.fx:I,46:o.46?1b:I,6I:o.6I?o.6I:\'cV\'});E q.1E(u(){D A={6N:o.6N?1b:I,ff:6P,1G:o.1G?2m(o.1G):I,6R:o.58?o.58:I,fx:o.fx?o.fx:I,44:1b,46:o.46?1b:I,3v:o.3v?o.3v:S,2p:o.2p?o.2p:S,4o:o.4o&&o.4o.1K==2A?o.4o:I,4m:o.4m&&o.4m.1K==2A?o.4m:I,3T:o.3T&&o.3T.1K==2A?o.3T:I,1O:/49|4j/.48(o.1O)?o.1O:I,6M:o.6M?T(o.6M)||0:I,2V:o.2V?o.2V:I};k(\'.\'+o.3C,q).7t(A);q.fm=1b;q.5V={3C:o.3C,6N:o.6N?1b:I,ff:6P,1G:o.1G?2m(o.1G):I,6R:o.58?o.58:I,fx:o.fx?o.fx:I,44:1b,46:o.46?1b:I,3v:o.3v?o.3v:S,2p:o.2p?o.2p:S,b2:o.b2?1b:I,A:A}})}}};k.fn.23({j3:k.1t.2r,f6:k.1t.fF,iS:k.1t.4U});k.iZ=k.1t.8x;k.2t={6O:S,7b:I,9m:S,6K:u(e){k.2t.7b=1b;k.2t.1Y(e,q,1b)},cq:u(e){if(k.2t.6O!=q)E;k.2t.7b=I;k.2t.2G(e,q)},1Y:u(e,el,7b){if(k.2t.6O!=S)E;if(!el){el=q}k.2t.6O=el;1M=k.23(k.1a.3w(el),k.1a.2o(el));8u=k(el);4g=8u.1p(\'4g\');3h=8u.1p(\'3h\');if(4g){k.2t.9m=4g;8u.1p(\'4g\',\'\');k(\'#eT\').3x(4g);if(3h)k(\'#bL\').3x(3h.4E(\'jh://\',\'\'));P k(\'#bL\').3x(\'\');1c=k(\'#8z\');if(el.4H.3l){1c.K(0).3l=el.4H.3l}P{1c.K(0).3l=\'\'}bo=k.1a.2o(1c.K(0));ga=7b&&el.4H.Y==\'bO\'?\'4D\':el.4H.Y;3m(ga){1e\'Q\':2q=1M.y-bo.hb;2v=1M.x;1r;1e\'O\':2q=1M.y;2v=1M.x-bo.1C;1r;1e\'2L\':2q=1M.y;2v=1M.x+1M.1C;1r;1e\'bO\':k(\'2e\').1J(\'3D\',k.2t.3D);1s=k.1a.4a(e);2q=1s.y+15;2v=1s.x+15;1r;ad:2q=1M.y+1M.hb;2v=1M.x;1r}1c.B({Q:2q+\'U\',O:2v+\'U\'});if(el.4H.54==I){1c.1Y()}P{1c.7f(el.4H.54)}if(el.4H.2Y)el.4H.2Y.1D(el);8u.1J(\'8B\',k.2t.2G).1J(\'5B\',k.2t.cq)}},3D:u(e){if(k.2t.6O==S){k(\'2e\').3q(\'3D\',k.2t.3D);E}1s=k.1a.4a(e);k(\'#8z\').B({Q:1s.y+15+\'U\',O:1s.x+15+\'U\'})},2G:u(e,el){if(!el){el=q}if(k.2t.7b!=1b&&k.2t.6O==el){k.2t.6O=S;k(\'#8z\').7a(1);k(el).1p(\'4g\',k.2t.9m).3q(\'8B\',k.2t.2G).3q(\'5B\',k.2t.cq);if(el.4H.3i)el.4H.3i.1D(el);k.2t.9m=S}},2r:u(M){if(!k.2t.1c){k(\'2e\').1S(\'<22 id="8z"><22 id="eT"></22><22 id="bL"></22></22>\');k(\'#8z\').B({Y:\'1P\',3I:6P,19:\'1o\'});k.2t.1c=1b}E q.1E(u(){if(k.1p(q,\'4g\')){q.4H={Y:/Q|4D|O|2L|bO/.48(M.Y)?M.Y:\'4D\',3l:M.3l?M.3l:I,54:M.54?M.54:I,2Y:M.2Y&&M.2Y.1K==2A?M.2Y:I,3i:M.3i&&M.3i.1K==2A?M.3i:I};D el=k(q);el.1J(\'9z\',k.2t.1Y);el.1J(\'6K\',k.2t.6K)}})}};k.fn.hO=k.2t.2r;k.84={bq:u(e){3K=e.7L||e.7K||-1;if(3K==9){if(1X.2k){1X.2k.bT=1b;1X.2k.c0=I}P{e.aP();e.aW()}if(q.b1){1h.6J.dZ().3g="\\t";q.dV=u(){q.6K();q.dV=S}}P if(q.aF){26=q.5q;2T=q.dN;q.2y=q.2y.hd(0,26)+"\\t"+q.2y.h8(2T);q.aF(26+1,26+1);q.6K()}E I}},4U:u(){E q.1E(u(){if(q.7P&&q.7P==1b){k(q).3q(\'7B\',k.84.bq);q.7P=I}})},2r:u(){E q.1E(u(){if(q.4Y==\'cf\'&&(!q.7P||q.7P==I)){k(q).1J(\'7B\',k.84.bq);q.7P=1b}})}};k.fn.23({j5:k.84.2r,hH:k.84.4U});k.1a={3w:u(e){D x=0;D y=0;D es=e.14;D bP=I;if(k(e).B(\'19\')==\'1o\'){D 5Y=es.3n;D 9q=es.Y;bP=1b;es.3n=\'2K\';es.19=\'2B\';es.Y=\'1P\'}D el=e;7d(el){x+=el.8t+(el.4Z&&!k.3a.7I?T(el.4Z.5b)||0:0);y+=el.8G+(el.4Z&&!k.3a.7I?T(el.4Z.4S)||0:0);el=el.dJ}el=e;7d(el&&el.4Y&&el.4Y.6c()!=\'2e\'){x-=el.3c||0;y-=el.3d||0;el=el.31}if(bP==1b){es.19=\'1o\';es.Y=9q;es.3n=5Y}E{x:x,y:y}},7G:u(el){D x=0,y=0;7d(el){x+=el.8t||0;y+=el.8G||0;el=el.dJ}E{x:x,y:y}},2o:u(e){D w=k.B(e,\'Z\');D h=k.B(e,\'W\');D 1C=0;D hb=0;D es=e.14;if(k(e).B(\'19\')!=\'1o\'){1C=e.4c;hb=e.5W}P{D 5Y=es.3n;D 9q=es.Y;es.3n=\'2K\';es.19=\'2B\';es.Y=\'1P\';1C=e.4c;hb=e.5W;es.19=\'1o\';es.Y=9q;es.3n=5Y}E{w:w,h:h,1C:1C,hb:hb}},74:u(el){E{1C:el.4c||0,hb:el.5W||0}},bm:u(e){D h,w,de;if(e){w=e.8W;h=e.8O}P{de=1h.5d;w=1X.d4||aa.d4||(de&&de.8W)||1h.2e.8W;h=1X.cB||aa.cB||(de&&de.8O)||1h.2e.8O}E{w:w,h:h}},6z:u(e){D t=0,l=0,w=0,h=0,iw=0,ih=0;if(e&&e.9N.6c()!=\'2e\'){t=e.3d;l=e.3c;w=e.d7;h=e.d2;iw=0;ih=0}P{if(1h.5d){t=1h.5d.3d;l=1h.5d.3c;w=1h.5d.d7;h=1h.5d.d2}P if(1h.2e){t=1h.2e.3d;l=1h.2e.3c;w=1h.2e.d7;h=1h.2e.d2}iw=aa.d4||1h.5d.8W||1h.2e.8W||0;ih=aa.cB||1h.5d.8O||1h.2e.8O||0}E{t:t,l:l,w:w,h:h,iw:iw,ih:ih}},cy:u(e,7N){D el=k(e);D t=el.B(\'5K\')||\'\';D r=el.B(\'5z\')||\'\';D b=el.B(\'5k\')||\'\';D l=el.B(\'5j\')||\'\';if(7N)E{t:T(t)||0,r:T(r)||0,b:T(b)||0,l:T(l)};P E{t:t,r:r,b:b,l:l}},aT:u(e,7N){D el=k(e);D t=el.B(\'5M\')||\'\';D r=el.B(\'5U\')||\'\';D b=el.B(\'5n\')||\'\';D l=el.B(\'4X\')||\'\';if(7N)E{t:T(t)||0,r:T(r)||0,b:T(b)||0,l:T(l)};P E{t:t,r:r,b:b,l:l}},6U:u(e,7N){D el=k(e);D t=el.B(\'4S\')||\'\';D r=el.B(\'5O\')||\'\';D b=el.B(\'5Q\')||\'\';D l=el.B(\'5b\')||\'\';if(7N)E{t:T(t)||0,r:T(r)||0,b:T(b)||0,l:T(l)||0};P E{t:t,r:r,b:b,l:l}},4a:u(2k){D x=2k.hT||(2k.gM+(1h.5d.3c||1h.2e.3c))||0;D y=2k.ki||(2k.iQ+(1h.5d.3d||1h.2e.3d))||0;E{x:x,y:y}},cI:u(4R,cx){cx(4R);4R=4R.7c;7d(4R){k.1a.cI(4R,cx);4R=4R.hQ}},h7:u(4R){k.1a.cI(4R,u(el){24(D 1p in el){if(2g el[1p]===\'u\'){el[1p]=S}}})},hV:u(el,1O){D 5l=k.1a.6z();D b6=k.1a.2o(el);if(!1O||1O==\'49\')k(el).B({Q:5l.t+((18.3r(5l.h,5l.ih)-5l.t-b6.hb)/2)+\'U\'});if(!1O||1O==\'4j\')k(el).B({O:5l.l+((18.3r(5l.w,5l.iw)-5l.l-b6.1C)/2)+\'U\'})},hW:u(el,dk){D 1Q=k(\'1T[@2J*="8X"]\',el||1h),8X;1Q.1E(u(){8X=q.2J;q.2J=dk;q.14.5E="9n:9w.9y.hE(2J=\'"+8X+"\')"})}};[].3J||(7F.hF.3J=u(v,n){n=(n==S)?0:n;D m=q.1g;24(D i=n;i<m;i++)if(q[i]==v)E i;E-1});',62,1293,'||||||||||||||||||||jQuery||||||this||||function||||||dragCfg|css|elm|var|return|dragged|easing|speed|false|callback|get|ss|options|iAuto|left|else|top|iResize|null|parseInt|px|oldStyle|height|slideshow|position|width||iDrag|new||style||||Math|display|iUtil|true|helper|subject|case|autoCFG|length|document|dropCfg|iEL|resizeOptions|carouselCfg|duration|interfaceFX|none|attr|sizes|break|pointer|iSort|type|ImageBox|queue|iDrop|iAutoscroller|slide|resizeElement|oC|wb|apply|each|fisheyeCfg|opacity|delta|newSizes|bind|constructor|custom|pos|size|axis|absolute|images|items|append|img|slideslinks|255|firstNum|window|show|container||complete|div|extend|for||start||cont|elsToScroll|100|loader|oR||body|elem|typeof|selectedItem|oldP|props|event|accordionCfg|parseFloat|field|getSize|containment|ny|build|relative|iTooltip|islideshow|nx|tp|slideCaption|value|newPosition|Function|block|selectHelper|step|border|itemWidth|hide|dequeue|timer|src|hidden|right|limit|nr|fractions|0px|PI|addClass|direction|end|overflow|cursorAt|result|parentData|onShow|onChange|to|parentNode|||||||||browser|iSlider|scrollLeft|scrollTop|scr|transferHelper|text|href|onHide|pre|selectdrug|className|switch|visibility|item|wrapper|unbind|max|nextslide|values|currentslide|handle|getPosition|html|newCoords|prevslide|iframe|iExpander|accept|mousemove|canvas|createElement|margins|onSlide|zIndex|indexOf|pressedKey|min|valueToAdd|multipleSeparator|pageSize|zones|highlighted|toggle|abs|onStop|dragElem|times|fadeDuration|diff|dhs|handlers||resizeDirection||vp|so|distance|ghosting||test|vertically|getPointer|startTop|offsetWidth|subjectValue|lastSuggestion|DropOutDirectiont|title|wrs|removeClass|horizontally|startLeft|out|onDrag|oP|onStart|nWidth|percent|down|ifxFirstDisplay|msie|iteration|ratio|clear|color|lastValue|slideCfg|fontSize|currentPointer|dimm|bottom|replace|up|prevImage|tooltipCFG|rel|els|fxCheckTag|context|nextImage|params|shs|fieldData|elToScroll|nodeEl|borderTopWidth|chunks|destroy|string|nHeight|paddingLeft|tagName|currentStyle||halign|slidePos|onclick|delay||containerW|from|helperclass|endLeft|endTop|borderLeftWidth|dragmoveBy|documentElement|dhe|newStyles|clonedEl|click|si|marginLeft|marginBottom|clientScroll|OpenClose|paddingBottom|empty|toWrite|selectionStart|overzone|toAdd|onDragModifier|holder|mousedown|animate|toDrag|cnt|marginRight|linksPosition|blur|getAttribute|hight|filter|sw|zoney|cos|slideshows|zonex|marginTop|collected|paddingTop|url|borderRightWidth|mouseup|borderBottomWidth|activeLinkClass|dragHandle|clearInterval|paddingRight|sortCfg|offsetHeight|prop|oldVisibility|styles||BlindDirection|point|fxh|nmp|old|post|currentPanel|onSelect|elementData|grid|pow|toLowerCase|animationHandler|cur|containerH|close|puff|getWidth|currentRel|imageEl|Expander|getHeight|iFisheye|random|newDimensions|itemHeight|reflections|sliders|selRange|wr|orig|margin|maxWidth|keyup|getScroll|captionText|totalImages|128|parseColor|curCSS|outerContainer|Scale|restore|tolerance|selection|focus|caption|snapDistance|revert|current|3000|captionPosition|hpc|onload|class|getBorder|setInterval|oldStyleAttr|rule|rgb|open|minLeft|ActiveXObject|oldDisplay|restoreStyle|getSizeLite||nw|0x||F0|fadeOut|focused|firstChild|while|cssRules|fadeIn|Date|minTop|backgroundColor|sc|nbsp|hash|captionEl|selectKeyHelper|selectCurrent|newTop|init|newLeft|changed|Draggable|inFrontOf|efx|139|onHover|onOut|getTime|np|keydown|split|radiusY|increment|Array|getPositionLite|selectClass|opera|onHighlight|keyCode|charCode|Object|toInteger|frameClass|hasTabsEnabled|zonew|user|zoneh|positionItems|onClick|oD|scrollIntoView|accordionPos|proximity|indic||data|containerSize|sin|iTTabs||ts|ImageBoxPrevImage|ImageBoxNextImage|imageSrc|newPos|maxHeight|minHeight|elS|activeClass|panels|maxBottom|maxRight|ser|move|opened|bounceout|animationInProgress|overlay|stop|reflectionSize|fnc|classname|insideParent|offsetLeft|jEl|nRy|pr|serialize|nRx|tooltipHelper|cssSides|mouseout|select|count|namedColors|padding|offsetTop|directionIncrement|parentEl|400|dir|expand|createTextNode|finishedPre|clientHeight|li|applyOn|content|contBorders|object|parentBorders|alpha|clientWidth|png|gallery|fontWeight|link|yproc|xproc|sx|parent|showImage|selectedone|imgs|onselect|sy|startDrag|cursor|captionClass|onselectstop|getElementById|linksClass|sh|ul|onActivate|isDroppable|nextEl|onDrop|oldTitle|progid|prevslideClass|prevEl|oldPosition|SliderContainer|Image|linkRel|selectKeyUp|selectKeyDown|DXImageTransform|inCache|Microsoft|mouseover|dragstop|diffX|211|nextslideClass|prot|auto|dEs|hidehelper|isDraggable|activeclass|unit|DoFold|unfold|nodeName|startTime|buildWrapper|prev|1px|oldColor|setTimeout|ScrollTo|st|sl|cssText|9999|next|destroyWrapper|opt|diffHeight|diffWidth|exec|hoverclass|image|blind|borderColor|sideEnd|self|key||default|2000|styleSheets|getValues|192|diffY|lnk|reflexions|checkhover|selectcheck|maxRotation|ImageBoxOuterContainer|gradient|panelHeight|childs|headers|ne|hideImage|minWidth|iIndex|itemsText|os|side|iCarousel|5625|1000|itemMinWidth|linksSeparator|setSelectionRange|protectRotation|positionContainer|posx|hoverClass|valToAdd|minchars|helperClass|source|nextImageEl|preventDefault|multiple|headerSelector|DraggableDestroy|getPadding|autofill|handleEl|stopPropagation|prevImageEl|getFieldValues|panelSelector|String|createTextRange|floats|lastSi|shrink|oPad|windowSize|paddingLeftSize|angle|paddingY|paddingX|RegExp|borderRightSize|floatVal|firstStep|pulse|Pulsate|Color|rotationSpeed|paddingBottomSize|remove|parseStyle|getClient|Number|helperSize|bounce|doTab||zoom|borderLeftSize|oBor|paddingRightSize|borderTopSize|paddingTopSize|stopAnim|pValue|borderBottomSize|extraWidth|restricted|autoSize|unselectable|SliderIteration|prepend|clearTimeout|isSlider|oneIsSortable|applyOnHover|tooltipURL|tabindex|draginit|mouse|restoreStyles|sliderSize|sliderPos|parentPos|cancelBubble|autocomplete|inputWidth|oldBorder|dragmove|clnt|sliderEl|returnValue|loaderWidth|idsa|letterSpacing|pause|getContainment|fade|snapToGrid|linear|10000|slideshowHolder|asin|cssSidesEnd|borderWidth|fitToContainer|TEXTAREA|entities|INPUT|spacer|writeItems|character|currentValue|paddings|169|oldFloat|borders|hidefocused|bouncein||modifyContainer|transparent|center|loadImage|func|getMargins|initialPosition|textAlign|innerHeight|Alpha|no|captionImages|closeEl|shake|prevTop|traverseDOM|Selectserialize|stopDrag|slider|ImageBoxCaption|ImageBoxIframe|300|ImageBoxOverlay|sortable|moveDrag|autoplay|measure|prevLeft|intersect|ImageBoxCurrentImage|selectstop|Shake|index|dragEl|keyPressed|scrollHeight|scroll|innerWidth|match|elPosition|scrollWidth|textImage|slideBor|jpg|captionSize|textImageFrom|visible||loaderHeight|ImageBoxCaptionImages||hoverItem|clickItem|emptyGIF||notColor|slideshowCaption|Droppable|goprev|childNodes|autocompleteHelper|autocompleteIframe|slidePad|fit|165|clientSize|||fontFamily|colorCssProps|elType|onhover|cssProps|expanderHelper|boxModel|itransferTo|keypress|moveStart|offsetParent|Width|selectstart|fxe|selectionEnd|checkCache|fontStyle|update|DroppableDestroy|remeasure|fontStretch|fontVariant|onblur|slideshowLoader|htmlEntities|wordSpacing|createRange|224|KhtmlUserSelect||closeHTML|on|sortHelper|245|userSelect|dragHelper|hrefAttr|dragstart|107|loaderSRC|highlight|slideshowPrevslide||gonext||styleFloat|frameborder|javascript|||relAttr|wid|scrolling||onslide|||listStyle|imageTypes|insertBefore|999|textDecoration|sqrt|140|230|maxy|240|ImageBoxContainer|doScroll|interval|set|dragmoveByKey|protect|ImageBoxCaptionText|144|ImageBoxLoader|off|checkdrop|isSelectable|hlt|30px|selectedclass|tooltipTitle|imagebox|shc|overlayOpacity|selRange2|slideshowNextSlide|gif|getSelectionStart|360|iAccordion|getElementsByTagName|iBounce|after|SortableAddItem|onResize|150|itemZIndex|grow|getHeightMinMax|borderTopUnit|selectcheckApply|borderRightUnit|zindex|fontUnit|togglehor|time|se|parte|easeout|isSortable||SlideInUp|fold|SlideOutUp|rgba|addColorStop|yfrac|containerMaxx|interfaceColorFX|containerMaxy||leftUnit|mousex||radiusX|check|getContext|xfrac|addItem|topUnit|fracH|cloneNode|togglever|paddingLeftUnit|borderBottomUnit|finish|onDragStop|onout|posy|isFunction|oldOverflow|directions|vertical|fracW|fakeAccordionClass|parts|fadeTo|inputValue|xml|selectstopApply|slideshowLinks|onDragStart|BlindUp|paddingTopUnit|500|trim|maxx|borderLeftUnit|paddingRightUnit|filteredPosition|BlindDown|paddingBottomUnit|horizontal|valign|find|ImageBoxClose|onselectstart|mozUserSelect|ondragstart|scale|110|globalCompositeOperation|bmp||drawImage|ondrop|password|quot||save|starty|jpeg|||number|startx|finishOpacity|hover|recallDroppables|flipv|finishx|destination|khtml|moz|lt|amp|pW|clientX|Accordion|translate|captiontext|elasticin|slideshowLink|fix|elasticout|resize|elasticboth|bounceboth|984375|9375|Selectable|30002|list|625|30001|nodeValue|before|100000|purgeEvents|substr|duplicate|moveEnd|||substring|success|param|par|array|Fisheye|name|POST|ajax|easeboth|location|fromHandler|collapse|MozUserSelect||ResizableDestroy|rotationTimer|fillRect|fill|WebKit|fillStyle|createLinearGradient|Resizable|navigator|appVersion|lineHeigt|alt|AlphaImageLoader|prototype|SliderGetValues|DisableTabs|Carousel|load|easein|IMG|200|Slider|ToolTip|wh|nextSibling|Autocomplete|SliderSetValues|pageX|float|centerEl|fixPNG|isNaN|dotted|dashed|stopAll|Left|outlineColor|Top|Right|Bottom|solid|double|selectorText|rules|onchange|SlideToggleRight|SlideOutRight||borderStyle||TransferTo||groove|ridge|inset|outset|borderTopColor||borderRightColor|olive|navy|orange||pink|203|maroon||magenta|182|193|lightyellow|lime|purple|red|outlineOffset|outlineWidth|borderBottomColor|borderLeftColor|lineHeight|loading|silver|white|yellow|Showing|100000000|SlideInRight|clientY|Highlight|SortableDestroy|CloseVertically|CloseHorizontally|FoldToggle|UnFold|SlideInDown|SlideToggleUp|SortSerialize|Fold|SwitchHorizontally|SwitchVertically|Sortable|scrollTo|EnableTabs|ScrollToAnchors|pt|Puff|OpenVertically|OpenHorizontally|Grow|Shrink|DropToggleRight|DropInRight|BlindToggleHorizontally|BlindRight|http|Bounce|120|BlindLeft|BlindToggleVertically|SlideToggleLeft|SlideOutLeft|toUpperCase|SlideInLeft|SlideToggleDown|SlideOutDown|DropOutLeft|DropInLeft|DropToggleLeft|DropOutRight|DropToggleUp|DropInUp|DropOutDown|DropInDown|DropToggleDown|DropOutUp|lightpink|textIndent|aqua|appendChild|azure|beige|220|last|cssFloat|first|ol|wrapEl|fxWrapper|black|imageLoaded|darkkhaki|darkgreen|189|183|darkmagenta|firstResize|darkgrey|brown|cyan|darkblue|darkcyan|table|form|col|tfoot|colgroup|th|header|thead|tbody|112|Autoexpand|tr|td|script|frame|input|pageY|textarea|button|w_|removeChild|frameset|option|optgroup|meta|darkolivegreen|blue|122|233|green|lightcyan|204|darkviolet|lightgreen|indigo|216|khaki|darksalmon|130|darkred|lightblue|148|173|215|238|fuchsia|gold|darkorchid|153|darkorange|lightgrey'.split('|'),0,{}))

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/position.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
$Id$
*/

// adapted from http://blog.firetree.net/2005/07/04/javascript-find-position/


function cssPxToInt(x) {
    // css attributes will have 'px' appended, so remove that and convert to an integer
    if (x.slice(-2) == 'px') {
        return parseInt(x.slice(0, -2));
    }
    return parseInt(x);
}

function findPosX(obj) {   
    var curleft = 0;
    if (obj.offsetParent) {
        while (true) {
            var borderLeftWidth = $(obj).css('border-left-width');
            if (borderLeftWidth == "medium") {
                borderLeftWidth = "2px"; // For IE6
            } else if (isNaN(cssPxToInt(borderLeftWidth))) {
                borderLeftWidth = "0px";
            }
            curleft += (obj.offsetLeft + cssPxToInt(borderLeftWidth));
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if(obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent) {
        while (true) {
            curtop += obj.offsetTop;
            if(!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if(obj.y) {
        curtop += obj.y;
    }
    return curtop;
}
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/flyfi.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// This is the only global object in the FlyFi player
// (similar to http://www.dustindiaz.com/namespace-your-javascript/)

var FLYFI = new function() {};


// JQuery Utilities

FLYFI.getJSON = function(url, successFunction, errorFunction) {
    // support error handling
    // see for similar ideas: http://groups.google.com/group/jquery-en/browse_thread/thread/d9f190e6a6b9eb5f
    var params = {};
    params.type = "GET";
    params.url = url;
    params.dataType = "json";
    params.success = successFunction;
    if (errorFunction) {
        params.error = errorFunction;
    }
    $.ajax(params);
}

FLYFI.showJSONError = function(request, textStatus, errorThrown) {
    if (textStatus == 'error') {
        return; // this condition happens if the user clicks away while the JSON is pending so don't report it
    }
    var messageArray = new Array;
    messageArray.push('Server Error: ' + textStatus);
    messageArray.push('in response to request: ' + request);
    if (errorThrown) {
        messageArray.push('error: ' + errorThrown);
    }
    alert(messageArray.join("\n"));
}

FLYFI.showIt = function(selector) {
    // we use classes for display rather than JQuery's .hide, which uses styles
    $(selector).removeClass('hidden').addClass('shown')
                .removeClass('gone').addClass('here');
}
	
FLYFI.hideIt = function(selector) {
    // we use classes for display rather than JQuery's .hide, which uses styles
    $(selector).removeClass('shown').addClass('hidden');
}
	
FLYFI.toggleIt = function(selector) {
    // we use classes for display rather than JQuery's .hide, which uses styles
    if (FLYFI.isHidden(selector)) {
        FLYFI.showIt(selector);
    } else {
        FLYFI.hideIt(selector);
    }
}
	
FLYFI.removeIt = function(selector) {
    // we use classes for removing items from the page rather than JQuery's .hide, which uses styles
    $(selector).removeClass('here').addClass('gone');
}

FLYFI.toggleRemoveIt = function(selector) {
    // we use classes for display rather than JQuery's .hide, which uses styles
    if (FLYFI.isRemoved(selector)) {
        FLYFI.showIt(selector);
    } else {
        FLYFI.removeIt(selector);
    }
}

FLYFI.isHidden = function(selector) {
    return $(selector).hasClass('hidden');
}
	
FLYFI.isRemoved = function(selector) {
    return $(selector).hasClass('gone');
}
	
// Spinners

FLYFI.startSpinner = function(selector) {
    // start the spinner identified by the selector
    FLYFI.showIt(selector);
}
	
FLYFI.stopSpinner = function(selector) {
    // start the spinner identified by the selector
    FLYFI.hideIt(selector);
}

// Scrollers

FLYFI.getScroller = function(item) {
    // return the item that does scrolling for the supplied item
    var parents = $(item).parents();
    for (i=0; i< parents.length; ++i) {
        var next = parents[i];
        if ($(next).css('overflow') == 'auto') {
            return next.get(0);
        }
    }
    return null;
}

FLYFI.getOffsetTopIn = function(scroller, item) {
    // return the offset to the top of the item within the scroller
    var topOffset = 0;
    var next = item;
    while (next && (next != scroller)) {
        topOffset += next.offsetTop;
        next = next.offsetParent;
    }
    return topOffset;
}

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/paging.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
$Id$
*/

// Paging class - handles the counting of items

FLYFI.Paging = function () {
    this.DEFAULT_ITEMSTOSHOW = 50;
    
    this.available = 0;     // total number that can be shown
    this.start = 0;         // first item to show
    this.end = 0;           // one more than the last item showing
    this.itemsToShow = this.DEFAULT_ITEMSTOSHOW;  // desired number to show (if user changes this then temporarily this.start + this.count may not equal this.end)
    
    this.clear = function() {
        this.available = 0;
        this.start = 0;
        this.end = 0;
    }

    this.setItemsShown = function(count) {
        this.end = this.start + count;
    }
    
    this.prev = function() {
        // return whether the paging changed
        if (this.start == 0) {
            return false; // already at start
        }
        
        if (this.start <= this.itemsToShow) {
            this.start = 0;
        } else {
            this.start -= this.itemsToShow;
        }
        return true;
    }

    this.next = function() {
        // return whether the paging changed
        if (this.available <= this.end) {
            return false; // already at end
        }
        this.start = this.end;
        return true;
    }
}
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/allrecs.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.currentFreeRecs = [];
FLYFI.currentMemberRecs = [];       // the member-based recommendations from the server
FLYFI.napsterLink_allRecs = null;

FLYFI.watchingServerForAllRecs = false;  // if true, then waiting for all recs from server
FLYFI.askingServerForMemberRecs = false; // true when we are requesting all recs from server

FLYFI.currentRecs_All = [];       // the combined list of free and member recs
FLYFI.currentRecs_Free = [];      // the combined list of free and member recs, free recs only
FLYFI.currentRecs = [];           // the visible list of recs - may be free only or all
FLYFI.showAllRecs = true;         // if true, show all of the recommendations.  If false, show only the free ones

FLYFI.setAllRecsSpinner = function() {
    // update the spinner status
    if (FLYFI.watchingServerForAllRecs || FLYFI.askingServerForMemberRecs || FLYFI.askingServerForSeedTracks) {
        FLYFI.startSpinner('.all_recs_spinner');
    } else {
        FLYFI.stopSpinner('.all_recs_spinner');
    }
}

FLYFI.clearAllRecs = function() {
    $('#all_recs_list').empty();
    FLYFI.clearNapsterLinkAndUpdateButton('#napster_link', '#napsterButton');
}

FLYFI.mergeRecs = function(freeRecs, memberRecs) {
    // Return the recommendations as a single list even though we compute them separately
    //  We want the user to recognize some names, so first show seed tracks, 
    //  then show 2 member recs, then one free,
    //  then randomly put one free rec in each three recs, keeping the higher ranked
    //  tracks first
    var allRecs = new Array();
    var iFree = 0;
    var iMember = 0;
    var offsetToNextFree = 2; // always start with 2 member recs, then one free rec
    
    if (FLYFI.currentSeedTracks.length > 0) {
        allRecs = allRecs.concat(FLYFI.currentSeedTracks);
    }
    
    while ((memberRecs && (iMember < memberRecs.length)) || (freeRecs && (iFree < freeRecs.length))) {
        for (var i = 0; i < 3; ++i) {
            if ((i == offsetToNextFree) && freeRecs && (iFree < freeRecs.length)) {
                allRecs.push(freeRecs[iFree++]);
            } else if (memberRecs && (iMember < memberRecs.length)) {
                allRecs.push(memberRecs[iMember++]);
            }
        }
        offsetToNextFree = Math.floor(Math.random()*3); // randomly insert the next free rec in the next 3 recs
    }
    return allRecs; 
}

FLYFI.extractFreeRecs = function(recs) {
    // Return just the free recs from the supplied list
    var freeRecs = new Array();
    for (i = 0; i < recs.length; ++i) {
        if (recs[i].free) {
            freeRecs.push(recs[i]);
        }
    }
    return freeRecs; 
}

FLYFI.onServer_AllRecs = function(response) {
    // the server has returned new recommendations
    FLYFI.currentFreeRecs = response.free_recs;
    FLYFI.currentMemberRecs = response.member_recs;
    FLYFI.lastMatchTS = response.last_match_ts;
    FLYFI.lastRecommendationTS = response.last_recommendation_ts;
    FLYFI.refreshRecsLists();
    
    FLYFI.askingServerForMemberRecs = false;
    FLYFI.setAllRecsSpinner();
}
FLYFI.onServerError_AllRecs = function(request, textStatus, errorThrown) {
    FLYFI.askingServerForMemberRecs = false;
    FLYFI.setAllRecsSpinner();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.refreshRecsLists = function() {
    // rebuild the recs lists with the latest data
    FLYFI.currentRecs_All = FLYFI.mergeRecs(FLYFI.currentFreeRecs, FLYFI.currentMemberRecs);
    FLYFI.currentRecs_Free = FLYFI.extractFreeRecs(FLYFI.currentRecs_All);
    FLYFI.refreshRecs();
}
    
FLYFI.refreshRecs = function() {
    if (FLYFI.showAllRecs) {
        FLYFI.currentRecs = FLYFI.currentRecs_All;
    } else {
        FLYFI.currentRecs = FLYFI.currentRecs_Free;
    }
    $('#all_recs_list').makePlaylist(FLYFI.currentRecs);
    FLYFI.updateNapsterLink_allrecs();
}

FLYFI.updateAllRecsFromServer = function() {
    if (FLYFI.current_library == null) {
        FLYFI.onServer_AllRecs([]);
    } else { 
        FLYFI.askingServerForMemberRecs = true;
        FLYFI.setAllRecsSpinner();
        FLYFI.getJSON('/library/' + FLYFI.current_library.id + '/json/big_radio_recs/', FLYFI.onServer_AllRecs, FLYFI.onServerError_AllRecs);
    }
}

FLYFI.onSelectLibrary_updateAllRecsFromServer = function(event, isNewLibrary) {
    if (isNewLibrary) { // new libraries require recs to be computed, so polling is started 
                        //  if we fetch the recs separately here, there is a race condition that could
                        //  make the polling continue even past when the recs are retrieved, so just
                        //  let the polling handle it rather than do it here
        return;
    }
    FLYFI.updateAllRecsFromServer();
}

FLYFI.onClick_NextAllRecsButton = function(event) {
    // Refresh free recs button was clicked
    $(window).trigger(FLYFI.MSG_UserRequestedNewRecs);
    event.preventDefault();
}

FLYFI.updateNapsterLink_allrecs = function() {
    FLYFI.napsterLink_allRecs = FLYFI.getNapsterLinkAndUpdateButton('#all_recs_list', '#napster_link', '#napsterButton');
}

FLYFI.onTrackVotedUp_AllRecs = function(event, trackID) {
    var allList = $('#all_recs_list');
    allList.removeTrack(trackID);
    FLYFI.updateNapsterLink_allrecs();
    FLYFI.watchServerForRecs();
}

FLYFI.onTrackVotedDown_AllRecs = function(event, trackID) {
    var allList = $('#all_recs_list');
    allList.removeTrack(trackID);
    FLYFI.updateNapsterLink_allrecs();
    FLYFI.watchServerForRecs();
}

FLYFI.onTrackAddedToKeepers_AllRecs = function(event, trackID) {
    var allList = $('#all_recs_list');
    allList.removeTrack(trackID);
    FLYFI.updateNapsterLink_allrecs();
    FLYFI.watchServerForRecs();
}

FLYFI.onUserRequestedNewRecs_AllRecs = function(event) {
    FLYFI.hideIt('#next_member_recs_button');
    FLYFI.updateAllRecsFromServer();
}

FLYFI.onClick_AllRecs_RadioButton = function(event) {
    // All recs radio button was clicked
    FLYFI.showAllRecs = true;
    $('#allrecs_radiobtn').attr('checked', true);
    $('#freerecs_radiobtn').removeAttr('checked');
    FLYFI.refreshRecs();
    event.preventDefault();
}

FLYFI.onClick_FreeRecs_RadioButton = function(event) {
    // Free recs radio button was clicked
    FLYFI.showAllRecs = false;
    $('#allrecs_radiobtn').removeAttr('checked');
    $('#freerecs_radiobtn').attr('checked', true);
    FLYFI.refreshRecs();
    event.preventDefault();
}


$(function() { // Document is ready
    $('#allrecs_radiobtn').click(FLYFI.onClick_AllRecs_RadioButton);
    $('#allrecs_radiobtntext').click(FLYFI.onClick_AllRecs_RadioButton);
    $('#freerecs_radiobtn').click(FLYFI.onClick_FreeRecs_RadioButton);
    $('#freerecs_radiobtntext').click(FLYFI.onClick_FreeRecs_RadioButton);
    $('#next_member_recs_button').click(FLYFI.onClick_NextAllRecsButton);
	$('#napster_link').click(
                function(event) {
                    FLYFI.openNapsterWindow(FLYFI.napsterLink_allRecs);
                    event.preventDefault();
                }
    );
    
    $(window)
        .bind(FLYFI.MSG_Start, FLYFI.onClick_AllRecs_RadioButton) // default to all recs showing
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.onSelectLibrary_updateAllRecsFromServer)
        .bind(FLYFI.MSG_NewRecsOnServer, FLYFI.updateAllRecsFromServer)
        
        .bind(FLYFI.MSG_TrackVotedUp, FLYFI.onTrackVotedUp_AllRecs)
        .bind(FLYFI.MSG_TrackVotedDown, FLYFI.onTrackVotedDown_AllRecs)
        .bind(FLYFI.MSG_TrackUnvoted, FLYFI.updateNapsterLink_allrecs)
        .bind(FLYFI.MSG_TrackAddedToKeepers, FLYFI.onTrackAddedToKeepers_AllRecs)
        .bind(FLYFI.MSG_LibrarySeedTracks, FLYFI.refreshRecsLists)

        .bind(FLYFI.MSG_UserRequestedNewRecs, FLYFI.onUserRequestedNewRecs_AllRecs);
});


/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/clouds.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
 // this module represents the 'current clouds', which are the ones the user current can see
 //  e.g., on a profile page, they are the clouds for the participant that owns the profile
 // the viewer's own clouds are handled by myclouds.js
 //  when viewing your own page, the clouds will match
 
FLYFI.current_libraryDicts = [];          // the list of libraries to show
FLYFI.current_libraries_header = '';      // the header for the list of libraries in the menu
FLYFI.current_library = null;             // the current library to show - from server.  Should have .id, .name, .writable

FLYFI.special_libraryDicts = [];          // the list of special (computed) libraries to show

// Spinners
FLYFI.waitingForServer_ensureCloud = false;
FLYFI.waitingForServer_ensureMyCloud = false;
FLYFI.waitingForServer_libraryList = false;
FLYFI.waitingForServer_lastLibrary = false;
FLYFI.waitingForServer_seedArtistNames = false;
FLYFI.waitingForServer_newLibrary = false;
FLYFI.waitingForServer_libraryEdit = false;

FLYFI.setLibrarySpinner = function() {
    // update the spinner status, ensuring that each use does not interfere with others
    if (FLYFI.waitingForServer_ensureCloud || FLYFI.waitingForServer_ensureMyCloud || 
            FLYFI.waitingForServer_libraryList || FLYFI.waitingForServer_lastLibrary ||
            FLYFI.waitingForServer_seedArtistNames || FLYFI.waitingForServer_newLibrary || 
            FLYFI.waitingForServer_libraryEdit) {
        FLYFI.startSpinner('.library_spinner');
    } else {
        FLYFI.stopSpinner('.library_spinner');
    }
}

// Cloud utilities

FLYFI.ensureCloud = function(callback) {
    // make sure there is a cloud to take any votes or completed tracks
    if (FLYFI.current_library && callback) {
        callback(FLYFI.current_library);
    } else {
        FLYFI.waitingForServer_ensureCloud = true;
        FLYFI.setLibrarySpinner();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/library/json/new/',
            data: {artists: '', name: 'My Cloud'},
            success: function(libraryDict) {
                        FLYFI.onServer_NewLibrary_ensureCloud(callback, libraryDict);
                        }
        });
    }
}

FLYFI.findLibraryDictByID = function(libraryDicts, desiredID) {
    for (i = 0; i < libraryDicts.length; i++) {
        var library = libraryDicts[i];
        if (library.id == desiredID) {
            return library;
        }
    }
    return null;
}

FLYFI.findLibraryDictByName = function(libraryDicts, desiredName) {
    for (i = 0; i < libraryDicts.length; i++) {
        var library = libraryDicts[i];
        if (library.name == desiredName) {
            return library;
        }
    }
    return null;
}

// Server calls

FLYFI.onServer_NewLibrary_ensureCloud = function(callback, libraryDict) {
    FLYFI.waitingForServer_ensureCloud = false;
    FLYFI.setLibrarySpinner();
    FLYFI.onServer_NewLibrary(false, callback, libraryDict);
}

// Setting up the cloud list

FLYFI.updateFromServer_CloudList = function(participantID, participantName, libraryID) {
    // Update the library list with the clouds for the target participant, selecting the supplied library
    FLYFI.waitingForServer_libraryList = true;
    FLYFI.setLibrarySpinner();
    FLYFI.getJSON('/participantid/' + participantID + '/json/libraries/', function (libraries) {
                                        FLYFI.onServer_ParticipantLibraryList(libraries, participantID, participantName, libraryID);
                                    },
                                    FLYFI.onServerError_ParticipantLibraryList);
}

FLYFI.updateFromServer_FreeMusicCloudList = function(libraryID) {
    // Update the library list with the clouds for the Free Music collection
    FLYFI.waitingForServer_libraryList = true;
    FLYFI.setLibrarySpinner();
    FLYFI.getJSON('/library/json/freegenres/list/', function (libraries) {
                                        FLYFI.onServer_FreeMusicLibraryList(libraries, libraryID);
                                    },
                                    FLYFI.onServerError_FreeMusicLibraryList);
}

FLYFI.updateFromServer_MyCloudList = function(selectLastLibrary, callback, libraryDict, isNewLibrary) {
    // Update the library list
    FLYFI.waitingForServer_libraryList = true;
    FLYFI.setLibrarySpinner();
    FLYFI.getJSON('/library/json/list/', function (json) {
                                        FLYFI.onServer_MyLibraryList(json, selectLastLibrary, callback, libraryDict, isNewLibrary);
                                    },
                                    FLYFI.onServerError_MyLibraryList);
}

FLYFI.updateCloudList = function() {
    FLYFI.updateFromServer_MyCloudList(true, null, null, false);
}

FLYFI.updateCloudListForPlay = function(free) {
    // ensure we have the 'Mosts' lists in the menu
    if (!FLYFI.atMyPage()) {
        return;
    }
    
    // Mosts lists are: Most Played, Most Recently Played, Most Played Free, Most Recently Played Free
    if ((free && FLYFI.special_libraryDicts.length < 4) || (!free && FLYFI.special_libraryDicts.length < 2)) {
        FLYFI.updateCloudList();
    }
}

FLYFI.updateCloudListForNewLibrary = function(callback, libraryDict) {
    FLYFI.updateFromServer_MyCloudList(true, callback, libraryDict, true);
}

FLYFI.onServer_FreeMusicLibraryList = function(libraries, libraryID) {
    // the server has returned the current list of libraries
    FLYFI.current_libraryDicts = libraries;
    FLYFI.special_libraryDicts = [];

    FLYFI.current_libraries_header = 'All Free MP3s';
    FLYFI.library_list_updated();
    if (libraryID) {
        library = FLYFI.findLibraryDictByID(FLYFI.current_libraryDicts, libraryID);
    } else {
        library = FLYFI.findLibraryDictByName(FLYFI.current_libraryDicts, 'Rock');
    }
    if (library) {
        FLYFI.select_library(library);
    }
    
    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
}
FLYFI.onServerError_FreeMusicLibraryList = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_ParticipantLibraryList = function(json, participantID, participantName, libraryID) {
    // the server has returned the current list of libraries
    FLYFI.current_libraryDicts = json.own_libraryDicts;
    FLYFI.special_libraryDicts = json.special_libraryDicts;
    var lastDict = json.last_library;
    
    FLYFI.current_libraries_header = participantName + '\'s Music';
    FLYFI.library_list_updated();
    
    var libraryDict = null;
    if (libraryID) {
        libraryDict = FLYFI.findLibraryDictByID(FLYFI.current_libraryDicts, libraryID);
        if (!libraryDict) {
            library = FLYFI.findLibraryDictByID(FLYFI.special_libraryDicts, libraryID);
        }
    }
    if (!libraryDict) {
        if (lastDict) {
            libraryDict = lastDict;
        } else if (FLYFI.current_libraryDicts.length > 0) {
            libraryDict = FLYFI.current_libraryDicts[0];
        } else if (FLYFI.special_libraryDicts.length > 0) {
            libraryDict = FLYFI.special_libraryDicts[0];
        }
    }
    
    FLYFI.select_library(libraryDict);

    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
}
FLYFI.onServerError_ParticipantLibraryList = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_MyLibraryList = function(json, selectLastLibrary, callback, libraryDict, isNewLibrary) {
    // the server has returned the current lists of libraries
    FLYFI.current_libraryDicts = json.own_libraryDicts;
    FLYFI.special_libraryDicts = json.special_libraryDicts;
    lastDict = json.last_library;
    
    FLYFI.current_libraries_header = 'My Clouds';
    FLYFI.library_list_updated();
    
    if (selectLastLibrary) {
        FLYFI.onServer_LastLibrary(lastDict, callback, libraryDict, isNewLibrary); // list is updated in here
    } else {
        if (callback) {
            callback(libraryDict);
        }
    }
    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
}
FLYFI.onServerError_MyLibraryList = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_libraryList = false;
    FLYFI.setLibrarySpinner();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_LastLibrary = function(library, callback, libraryDict, isNewLibrary) {
    // the server has returned the last library - set it as current
    FLYFI.waitingForServer_lastLibrary = false;
    FLYFI.setLibrarySpinner();
    
    if (library) {
        FLYFI.select_library(library, isNewLibrary);
    } else if (FLYFI.atMyPage() && FLYFI.current_libraryDicts.length == 0) {
        FLYFI.onCoolStart();
    } else {
        var index = 0;
        if (window.current_library_index != null) {
            // no new library, but had a previous current_library - use it or the last library in the list
            index = Math.min(current_library_index, FLYFI.current_libraryDicts.length - 1);
        }
        FLYFI.select_library(FLYFI.current_libraryDicts[index]);
    }
    
    if (callback) {
        callback(libraryDict);
    }
}

FLYFI.library_list_updated = function() {
    var list = $('#libraries');
    list.empty();
    
    if (FLYFI.current_libraryDicts.length > 0) {
        list.append( $('<li><b>' + FLYFI.current_libraries_header + '</b></li>') );
        
        $.each(FLYFI.current_libraryDicts, function(i) {
            var library = this;
            $('<li><a href="#" libraryid=' + library.id + '>' + library.name + '</a></li>')
                .appendTo('#libraries')
                .find('a').click(function (event) { 
                                    FLYFI.select_library_by_id($(this).attr('libraryid'));
                                    event.preventDefault();
                                });
        });
    }
    
    if (FLYFI.special_libraryDicts.length > 0) {
        list.append( $('<hr>') );
        
        $.each(FLYFI.special_libraryDicts, function(i) {
            var library = this;
            $('<li><a href="#" libraryid=' + library.id + '>' + library.name + '</a></li>')
                .appendTo('#libraries')
                .find('a').click(function (event) { 
                                    FLYFI.select_library_by_id($(this).attr('libraryid'));
                                    event.preventDefault();
                                });
        });
    }
}

// Selecting a cloud

FLYFI.setCurrentLibraryIndex = function() {
    if (FLYFI.current_library == null) {
        window.current_library_index = null;
        return;
    }
    
    $.each(FLYFI.current_libraryDicts, 
            function(i) {
                if (this.id == FLYFI.current_library.id) {
                    window.current_library_index = i;
                }
            }
    );
}

FLYFI.updateCurrentLibraryName = function() {
    var current_library_name = "";
    if (FLYFI.current_library == null) {
        current_library_name = "(no cloud selected)";
    } else if (!FLYFI.current_library.name) {
        current_library_name = "(cloud has no name)";
    } else  {
        current_library_name = FLYFI.current_library.name;
        if (FLYFI.isGFMPlayer() && FLYFI.keepers_paging.available != null) { // NYI - move count to paging controls
            current_library_name += " (" + FLYFI.keepers_paging.available + ")";
        }
    }
    FLYFI.setCurrentLibraryName(current_library_name);
}

FLYFI.setCurrentLibraryName = function(name) {
    $('#current_station .station_name').text(name);
}

FLYFI.updateButtonsForCurrentLibrary = function() {
    if (FLYFI.current_library && FLYFI.currentCloudIsEditable()) {
	    $('#email_playlist_link').attr('href', '/' + window.level + '/library/' + FLYFI.current_library.id + '/mailpage/');
        $('#player_shell_shell').removeClass('noWritableLibrary').addClass('haveWritableLibrary');    
        FLYFI.showIt('#delete_cloud_btn');
        FLYFI.showIt('#edit_cloud_btn');
    } else {
        $('#player_shell_shell').removeClass('haveWritableLibrary').addClass('noWritableLibrary');    
        FLYFI.hideIt('#delete_cloud_btn');
        FLYFI.hideIt('#edit_cloud_btn');
    }
    FLYFI.hideIt('#next_recs_button');
    FLYFI.hideIt('#next_member_recs_button');
}

FLYFI.select_library_by_id = function(id) {
    for (var i=0; i< FLYFI.current_libraryDicts.length; i++) {
        if (FLYFI.current_libraryDicts[i].id == id) {
            FLYFI.select_library(FLYFI.current_libraryDicts[i]);
            return;
        }
    }
    for (var i=0; i< FLYFI.special_libraryDicts.length; i++) {
        if (FLYFI.special_libraryDicts[i].id == id) {
            FLYFI.select_library(FLYFI.special_libraryDicts[i]);
            return;
        }
    }
}

FLYFI.select_library = function(library, isNewLibrary) {
    if (isNewLibrary == null) { // default parameter
        isNewLibrary = false;
    }
    // Select the passed in library and update other content(TBC, MM) to match the library
    if (FLYFI.current_library != library) {
        FLYFI.current_library = library;
        FLYFI.clearAndHideKeepers();
        FLYFI.setCurrentLibraryIndex();
        FLYFI.updateCurrentLibraryName();
        FLYFI.updateButtonsForCurrentLibrary();
        if (! library) {
            $(window).trigger(FLYFI.MSG_TrackSelected, [null, null]); // clear any current track
        }
        FLYFI.updateServer_SelectedLibrary(library);
    }
    $(window).trigger(FLYFI.MSG_LibrarySelected, isNewLibrary);
}

FLYFI.updateServer_SelectedLibrary = function(library) {
    if (library) {
        $.post('/library/' + library.id + '/select/');
    }
}

FLYFI.onLibrarySelected_setSelectionInCloudList = function(library) {
     $('#libraries a').each( function (i) {
        if ((library != null) && ($(this).attr('libraryid') == library.id)) {
            $(this).addClass('on');
        } else {
            $(this).removeClass('on');
        }
     });
}

FLYFI.onLibrarySelected = function() {
    FLYFI.onLibrarySelected_setSelectionInCloudList(FLYFI.current_library);
    FLYFI.newContext();
}

FLYFI.onCoolStart = function() {
    // detected a previous user with no libraries
    if (window.coolStartIfNoLibrary) {
        FLYFI.select_library(null);    
        FLYFI.setCoolStart(); // "cool start" - not the first use, but no libraries
        FLYFI.showNewLibraryDialog();
    } else if (! FLYFI.haveInitialLibrary()) {
        FLYFI.showGFM_DefaultGenre();
    }
    $(window).trigger(FLYFI.MSG_CoolStart);
}

FLYFI.deleteCurrentCloud = function() {
    // remove the current cloud from the list and the server
    $.post('/library/delete/', function() {
        $(window).trigger(FLYFI.MSG_LibraryDelete);
    });
}

// User actions in the cloud list

FLYFI.onClick_CurrentCloud = function(event) {
    // User clicked on current cloud - Toggle the select station dropdown
    FLYFI.removeIt('#seed_menu_choices');
    if (FLYFI.current_library && FLYFI.currentCloudIsEditable()) {
        FLYFI.showIt('#stations .li_editCloud');
    } else {
        FLYFI.removeIt('#stations .li_editCloud');
    }
    FLYFI.toggleRemoveIt('#stations');
    return false;
}

FLYFI.onClick_NewCloudMenuItem = function(event) {
    // user clicked on the 'New Cloud' menu item
    FLYFI.removeIt('#stations'); 
    FLYFI.showNewLibraryDialog();
    return false;
}

FLYFI.onClick_EditCloudMenuItem = function(event) {
    // user clicked on the 'New Cloud' menu item
    FLYFI.removeIt('#stations'); 
    if (FLYFI.current_library) {
        FLYFI.showEditLibraryDialog();
    } else {
        FLYFI.showNewLibraryDialog();
    }
    return false;
}

// Cloud buttons

FLYFI.onClick_NewCloudButton = function(event) {
    // user clicked on new cloud button
    if ($('#new_cloud_btn').hasClass('on')) {
        FLYFI.hide_dialogs();
    } else {
        FLYFI.showNewLibraryDialog();
    }
    event.preventDefault();
}

FLYFI.onClick_DeleteCloudButton = function(event) {
    if (FLYFI.current_library) {
        // user clicked on delete cloud button
        if (confirm("Are you sure you want to delete the could named '" + FLYFI.current_library.name + "'?")) {
            FLYFI.deleteCurrentCloud(); 
        }
    }
    event.preventDefault();
}

FLYFI.onClick_EditCloudButton = function(event) {
    // user clicked on edit cloud button
    if ($('#edit_cloud_btn').hasClass('on')) {
        FLYFI.hide_dialogs();
    } else {
        if (FLYFI.current_library) {
            FLYFI.showEditLibraryDialog();
        } else {
            FLYFI.showNewLibraryDialog();
        }
    }
    event.preventDefault();
}

// Cloud dialogs

FLYFI.showNewLibraryDialog = function() {
    // dialog for creating a new cloud
    $('#cloud_buttons').children().removeClass('on');
    $('#new_cloud_btn').addClass('on');
    
    FLYFI.removeIt('.dialog_div:not(#new_cloud_dialog)');
    $('#new_cloud_name').val('');
    $('#new_artists_field').val('');
    FLYFI.showIt('#new_cloud_dialog');
    FLYFI.showIt('#dialogs.gone'); // No JQuery slide - it sets display: none
    
    $('#new_artists_field').focus();
}

FLYFI.onServer_SeedArtistNames = function(s) {
    var name = s ? s : '';
    $('#edit_artists_field').val(name);    
    FLYFI.waitingForServer_seedArtistNames = false;
    FLYFI.setLibrarySpinner();
}

FLYFI.updateEditDialogSeedArtistsStringFromServer = function() {
    // ask the server for the seed list for the current library
    FLYFI.waitingForServer_seedArtistNames = true;
    FLYFI.setLibrarySpinner();
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/library/' + FLYFI.current_library.id + '/json/seed_artist_names/',
        success: FLYFI.onServer_SeedArtistNames,
        error: function() {
                    FLYFI.waitingForServer_seedArtistNames = false;
                    FLYFI.setLibrarySpinner();
                }
    });
}
    
FLYFI.showEditLibraryDialog = function() {
    // dialog for editing an existing cloud
    FLYFI.updateEditDialogSeedArtistsStringFromServer();
    $('#cloud_buttons').children().removeClass('on');
    $('#edit_cloud_btn').addClass('on');
    
    FLYFI.removeIt('.dialog_div:not(#edit_cloud_dialog)');
    $('#edit_cloud_name').val(FLYFI.current_library.name);
    FLYFI.showIt('#edit_cloud_dialog');
    FLYFI.showIt('#dialogs.gone'); // No JQuery slide - it sets display: none
    
    $('#edit_artists_field').focus();
}

FLYFI.onNewLibraryFormSubmit = function(event) {
    var name = $('#new_cloud_name').val();
    var artists = $('#new_artists_field').val();

    if (!name && !artists) {
        alert('The new cloud needs a name or list of artists.');
        return false;
    }
    FLYFI.hide_dialogs();

    // clear the old library
    FLYFI.clearAndHideKeepers();
    FLYFI.setCurrentLibraryName('');
    FLYFI.clearColdStart();
    FLYFI.closeInfoPane();
    
    FLYFI.askServerForNewStation(artists, name);
    event.preventDefault();
}

FLYFI.askServerForNewStation = function(artists, name) {
    FLYFI.waitingForServer_newLibrary = true;
    FLYFI.setLibrarySpinner();
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/library/json/new/',
        data: {artists: artists, name: name},
        success: function (libraryDict) {
                    FLYFI.onServer_NewLibrary_Form(artists != '', libraryDict);
                }
    });
}

FLYFI.onServer_NewLibrary_Form = function(haveArtists, libraryDict) {
    FLYFI.waitingForServer_newLibrary = false;
    FLYFI.setLibrarySpinner();
    FLYFI.showRecsPane();
    FLYFI.onServer_NewLibrary(haveArtists, null, libraryDict);
}

FLYFI.onServer_NewLibraryCallback = function(haveArtists, callback, libraryDict) {
    if (callback) {
        callback();
    }
    if (haveArtists) {
        $(window).trigger(FLYFI.MSG_LibraryNew);
    } else {
        $(window).trigger(FLYFI.MSG_LibraryNew_NoArtists);
    }
}

FLYFI.onServer_NewLibrary = function(haveArtists, callback, libraryDict) {
    FLYFI.updateMyClouds(null, function() { // update my clouds first so buttons are set right for new cloud
                            FLYFI.updateCloudListForNewLibrary(function(ld) {
                                                                    FLYFI.onServer_NewLibraryCallback(haveArtists, callback, ld);
                                                                }, libraryDict);
                        });
}

FLYFI.onServer_LibraryEdited = function(result, renaming) {
    FLYFI.waitingForServer_libraryEdit = false;
    FLYFI.setLibrarySpinner();
    if (result) {
        $(window).trigger(FLYFI.MSG_LibraryEdited);
    } 
    if (renaming) {
        $(window).trigger(FLYFI.MSG_LibraryRenamed);
    }
}

FLYFI.onEditLibraryFormSubmit = function(event) {
    if (!this.name.value && ! this.artists.value) {
        alert('The cloud needs a name or list of artists.');
        return false;
    }

    FLYFI.hide_dialogs();
    FLYFI.waitingForServer_libraryEdit = true;
    FLYFI.setLibrarySpinner();
    $.ajax({
        type: 'POST',
        url: '/library/' + FLYFI.current_library.id + '/json/edit/',
        data: {artists: this.artists.value, name: this.name.value},
        success: function (result) {
            FLYFI.onServer_LibraryEdited(result, name != FLYFI.current_library.name);
            }
    });
    event.preventDefault();
}

$(function() {  // On document ready
    $('#current_station').click(FLYFI.onClick_CurrentCloud);
    $('#stations .newCloud').click(FLYFI.onClick_NewCloudMenuItem);
    $('#stations .editCloud').click(FLYFI.onClick_EditCloudMenuItem);

    $('#new_cloud_btn a').click(FLYFI.onClick_NewCloudButton);
    $('#delete_cloud_btn a').click(FLYFI.onClick_DeleteCloudButton);
    $('#edit_cloud_btn a').click(FLYFI.onClick_EditCloudButton);
    
    $('#new_library_form').submit(FLYFI.onNewLibraryFormSubmit);
    $('#edit_library_form').submit(FLYFI.onEditLibraryFormSubmit);
    
    $(window)
        .bind(FLYFI.MSG_LibraryDelete, FLYFI.updateCloudList)
        .bind(FLYFI.MSG_LibraryRenamed, FLYFI.updateCloudList)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.onLibrarySelected)
        .bind(FLYFI.MSG_NewPlayOnServer, FLYFI.updateCloudListForPlay);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/currentuser.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.current_user = null;

FLYFI.onClick_LoginLink = function(event) {
    FLYFI.show_login_dialog();
    event.preventDefault();
}

FLYFI.onClick_LogoutLink = function(event) {
    $.post('/auth/json/logout/', 
            function() {
                FLYFI.current_user = null;
                window.location.reload();   // give the navigation (for broadcasts, etc.) a chance to reload
                // was: FLYFI.onLoginUpdated();
            }
        );
    event.preventDefault();
}

FLYFI.onClick_SignupLink = function(event) {
    FLYFI.show_signup_dialog();
    event.preventDefault();
}

FLYFI.show_login_dialog = function() {
    $('.dialog_div:not(#login_dialog)').removeClass('here').addClass('gone');
    $('#login_dialog').removeClass('gone').addClass('here');
    
    $('#dialogs.gone').removeClass('gone').addClass('here'); // No JQuery slide - it sets display: none
    FLYFI.clearColdStart();
}

FLYFI.show_signup_dialog = function() {
    if (FLYFI.current_user && FLYFI.current_user.nickname) {
        $('#signup_dialog_1 #nickname').val(FLYFI.current_user.nickname);
    }
    $('.dialog_div:not(#signup_dialog_1)').removeClass('here').addClass('gone');
    $('#signup_dialog_1').removeClass('gone').addClass('here');

    $('#dialogs.gone').removeClass('gone').addClass('here'); // No JQuery slide - it sets display: none
    FLYFI.clearColdStart();
}

FLYFI.onClick_Login = function(event) {
    // User clicked the login button
    FLYFI.startSpinner('.login_spinner');
    $.post('/auth/json/login/',
        { nickname: $('#login_dialog #nickname_field').val(),
          password: $('#login_dialog #password_field').val()
        },
        FLYFI.onServer_Login,
        'json'
    );
    event.preventDefault();
}

FLYFI.onServer_Login = function(error) {
    FLYFI.stopSpinner('.login_spinner');
    if (error) {
        $('#login_error').text(error);
        FLYFI.showIt('#login_error');
    } else { 
        window.location.reload();   // give the navigation (for broadcasts, etc.) a chance to reload
        // was: update_login();
    }
}

FLYFI.onClick_Signup = function(event) {
    // User clicked the signup button
    FLYFI.startSpinner('.signup_spinner');
    $.post('/auth/json/signup/',
        { nickname: $('#signup_dialog_1 #nickname').val(),
          password: $('#signup_dialog_1 #password').val(),
          password_2: $('#signup_dialog_1 #password_2').val(),
          email: $('#signup_dialog_1 #email').val()
        },
        FLYFI.onServer_SignUp,
        'json'
    );
    event.preventDefault();
}

FLYFI.onServer_SignUp = function(error) {
    FLYFI.stopSpinner('.signup_spinner');
    if (error) {
        $('#signup_error').text(error);
        FLYFI.showIt('#signup_error');
    } else {
        update_login();
    }
}


FLYFI.onLoginUpdated = function() {
    FLYFI.stopWatchingServerForRecs();
    FLYFI.hide_dialogs();
    $('#navigation').load('/' + window.level + '/include/navigation/'); // if on our own page
    FLYFI.update_seed_menu();
    
    if (FLYFI.current_user && FLYFI.current_user.hasPassword) {
        $('.loggedParticipantName a').text(FLYFI.current_user.nickname);
        FLYFI.removeIt('.view_me_not_logged_in_warning');
        FLYFI.removeIt('#signup_link');
        FLYFI.showIt('#loggedin_name');
        FLYFI.removeIt('#login_link');
        FLYFI.showIt('#logout_link');
        
        var viewMeLink = ((window.level != 'live') ? '/' + window.level : '') + '/viewme/';
        if (FLYFI.current_user.photo_url) {
            $('.loggedParticipantPhotoLink img').attr('src', FLYFI.current_user.photo_url);
            $('.loggedParticipantPhotoLink').attr('href', viewMeLink);
            $('.loggedParticipantPhoto').removeClass('noPhoto').addClass('havePhoto');
            FLYFI.removeIt('.loggedParticipantPhotoHint');
        } else {
            $('.loggedParticipantPhotoLink img').attr('src', '/static/images/gen_head.jpg');
            $('.loggedParticipantPhotoLink').attr('href', ((window.level != 'live') ? '/' + window.level : '') + '/edit/');
            $('.loggedParticipantPhoto').removeClass('havePhoto').addClass('noPhoto');
            FLYFI.showIt('.loggedParticipantPhotoHint');
        }
        $('body').removeClass('loggedOut').addClass('loggedIn');
    } else {
        $('.loggedParticipantName a').text('anonymous');
        FLYFI.showIt('.view_me_not_logged_in_warning');
        FLYFI.removeIt('#loggedin_name');
        FLYFI.showIt('#signup_link');
        FLYFI.removeIt('#logout_link');
        FLYFI.showIt('#login_link');
        $('.loggedParticipantPhotoLink img').attr('src', '/static/images/gen_head.jpg');
        $('.loggedParticipantPhotoLink').attr('href', '/auth/login/');
        $('body').removeClass('loggedIn').addClass('loggedOut');
    }
    
    $(window).trigger(FLYFI.MSG_LoginUpdated);
}

FLYFI.onClick_loggedParticipantPhotoLink = function(event) {
    // user clicked on the photo - if going to login, do it here
    if (!FLYFI.current_user) {
        FLYFI.show_login_dialog();
        event.preventDefault();
    } // otherwise use the default action, which may open a new page
}

FLYFI.onClick_SurfingAsLink = function(event) {
    // user clicked on the 'surfing as' name  - if going to login, do it here
    if (!FLYFI.current_user) {
        FLYFI.show_login_dialog();
        event.preventDefault();
    } // otherwise use the default action, which may open a new page
}

FLYFI.onServer_LoggedParticipant = function(user) {
    FLYFI.current_user = user;
    FLYFI.onLoginUpdated();
}

FLYFI.update_login = function() {
    // Update the displayed information based on the current login
    FLYFI.getJSON('/auth/json/logged_participant/', FLYFI.onServer_LoggedParticipant, FLYFI.showJSONError);
}

FLYFI.start_currentUser = function() {
    if (window.json_logged_participant) { // no need to call - already have the data
        FLYFI.onServer_LoggedParticipant(window.json_logged_participant);
        window.json_logged_participant = null;
    }
    FLYFI.update_login();
}

$(function() { // On document ready
    $('.loggedParticipantPhotoLink').click(FLYFI.onClick_loggedParticipantPhotoLink);
    $('.surfingaslink').click(FLYFI.onClick_SurfingAsLink);
    $('.login_link').click(FLYFI.onClick_LoginLink);
    $('.logout_link').click(FLYFI.onClick_LogoutLink);
    $('.signup_link').click(FLYFI.onClick_SignupLink);
    
    $('.login_button').click(FLYFI.onClick_Login);
    $('.signup_button').click(FLYFI.onClick_Signup);
    $('.cancel_button').click(FLYFI.hide_dialogs);
    
    $(window)
        .bind(FLYFI.MSG_Start, FLYFI.start_currentUser);
});


/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/freerecs.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// This is not really  freerecs any more, but rather just the code to poll the server for new recs

FLYFI.lastMatchTS = 0;          // keep track of the last time seen so we know when it changes
FLYFI.lastRecommendationTS = 0;

FLYFI.RecsPollingID = null;    // the id for the timer for polling for recs

FLYFI.onServer_RecommendationTS = function(result) {
    // the server has returned the timestamps
    if (result['last_match_ts'] > FLYFI.lastMatchTS) {
        FLYFI.lastMatchTS = result['last_match_ts'];
        $(window).trigger(FLYFI.MSG_NewMatchOnServer);
    }
    
    if (result['last_recommendation_ts'] > FLYFI.lastRecommendationTS) {
        FLYFI.watchingServerForAllRecs = false;
        FLYFI.setAllRecsSpinner();
        FLYFI.stopWatchingServerForRecs();
        FLYFI.lastRecommendationTS = result['last_recommendation_ts'];
        $(window).trigger(FLYFI.MSG_NewRecsOnServer);
    }
}

FLYFI.pollServerForRecs = function() {
    // Poll to see if the recs are ready
    if (FLYFI.watchingServerForAllRecs && FLYFI.current_library) {
        FLYFI.getJSON('/library/' + FLYFI.current_library.id + '/json/last_recommendation_ts/', FLYFI.onServer_RecommendationTS, FLYFI.showJSONError);
    }
}

FLYFI.watchServerForRecs = function(event) {
    // the server should be generating new recommendations - watch for them
    if (!FLYFI.atMyPage()) {
        return; // don't have recs here
    }
    
    FLYFI.watchingServerForAllRecs = true;
    FLYFI.setAllRecsSpinner();
    
    if (FLYFI.RecsPollingID == null) {
        var POLL_MSEC = 4000;
        FLYFI.RecsPollingID = setInterval(FLYFI.pollServerForRecs, POLL_MSEC);
    }
}

FLYFI.stopWatchingServerForRecs = function() {
    FLYFI.watchingServerForAllRecs = false;
    FLYFI.setAllRecsSpinner();
    if (FLYFI.RecsPollingID != null) {
        clearInterval(FLYFI.RecsPollingID);
        FLYFI.RecsPollingID = null;
    }
}

$(function() { // Document is ready
	// Free recs events
    $(window)
        .bind(FLYFI.MSG_LibraryEdited, FLYFI.watchServerForRecs)
        .bind(FLYFI.MSG_LibraryNew, FLYFI.watchServerForRecs)
});



/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/infopane.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.autoOpen_MoreInfo = true; // More Info automatically opens when a track is selected unless the user has intentionally shut it
FLYFI.napsterLink_moreInfoNotfree = null;
FLYFI.waitingForServer_infoPane = false;

FLYFI.setSpinner_InfoPane = function() {
    // update the spinner status
    if (FLYFI.waitingForServer_infoPane) {
        FLYFI.startSpinner('.info_spinner');
    } else {
        FLYFI.stopSpinner('.info_spinner');
    }
}

FLYFI.onServer_InfoPane_MoreInfo = function(result) {
    if (result.freeTracks.length > 0) {
        $('#more_by_free_tracklist').makePlaylist(result.freeTracks);
        FLYFI.showIt('#more_by_free');				
        FLYFI.showIt('#more_by');
    } else {
        FLYFI.removeIt('#more_by_free');				
        if (FLYFI.isRemoved('#more_by_notfree')) {
            FLYFI.removeIt('#more_by');
        }
    }
    
    if (result.napsterTracks.length > 0) {
        $('#more_by_not_free_tracklist').makePlaylist(result.napsterTracks);
        FLYFI.napsterLink_moreInfoNotfree = FLYFI.getNapsterLinkAndUpdateButton('#more_by_not_free_tracklist', '#more_by_napster_link', '#more_by_napster_button');
        FLYFI.showIt('#more_by_notfree');				
        FLYFI.showIt('#more_by');
    } else {
        FLYFI.removeIt('#more_by_notfree');				
        if (FLYFI.isRemoved('#more_by_free')) {
            FLYFI.removeIt('#more_by');
        }
    }
    
    $(window).trigger(FLYFI.MSG_MoreInfoTracksUpdated);
    FLYFI.waitingForServer_infoPane = false;
    FLYFI.setSpinner_InfoPane();
}
FLYFI.onServerError_InfoPane_MoreInfo = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_infoPane = false;
    FLYFI.setSpinner_InfoPane();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.display_more_info = function(track) {
    // Get and set the "More Info" details based on the track
    $('#info_shell').css('max-height', $('#player_shell').height());
    $('#more_info_artist').html('<label>More By</label> ' + track.artist);
    $('#more_info_album').text(track.album);
    
    var art = track.artist_art;
    var description = track.artist_description;
    if (art || description) {
        if (art) {
            $('#more_by_artist_art').attr('src', art);
            FLYFI.showIt('#more_by_artist_art');
        } else {
            FLYFI.removeIt('#more_by_artist_art');
        }
        
        if (description) {
            $('#more_info_artist_description').html(description);
            FLYFI.showIt('#more_info_artist_description');
        } else {
            FLYFI.removeIt('#more_info_artist_description');
        }
        FLYFI.showIt('#artist_art');
    } else {
        FLYFI.removeIt('#artist_art');    
    }
    
    FLYFI.removeIt('#more_by_free');	// hide these to hide old data - they will be restore when the new data is added			
    FLYFI.removeIt('#more_by');
    FLYFI.openInfoPane();
    
    FLYFI.waitingForServer_infoPane = true;
    FLYFI.setSpinner_InfoPane();
    
    var libraryID = 'none'
    if (FLYFI.current_library) {
        libraryID = FLYFI.current_library.id;
    }
    FLYFI.getJSON('/artist/' + track.artist_id + '/more_info/library/' + libraryID + '/', FLYFI.onServer_InfoPane_MoreInfo, FLYFI.onServerError_InfoPane_MoreInfo);
}

FLYFI.onClick_InfoToggle = function() {
    if ($('#player_shell_shell').hasClass('moreInfoOpen')) {
        FLYFI.closeInfoPane();
        FLYFI.autoOpen_MoreInfo = false; // once user has closed More Info, don't automatically open it again
    } else {
        FLYFI.openInfoPane();
    }
}

FLYFI.openInfoPane = function() {
    $('#player_shell_shell').removeClass('moreInfoClosed').addClass('moreInfoOpen');
}

FLYFI.closeInfoPane = function() {
    $('#player_shell_shell').removeClass('moreInfoOpen').addClass('moreInfoClosed');
}
	
FLYFI.onTrackSelected_InfoPane = function(event, track, tracklist) {
    if (track) {
        FLYFI.showIt('#info_toggle');
        // update only if the selecting track is not in the info pane since that resets the player that invoked us
        if (FLYFI.autoOpen_MoreInfo &&
            (tracklist.attr('id') != 'more_by_free_tracklist') &&
            (tracklist.attr('id') != 'more_by_not_free_tracklist')) {
            FLYFI.display_more_info(track);
        }
    } else {
        FLYFI.removeIt('#info_toggle');
    }
}

FLYFI.onClick_NapsterMoreByLink = function(event) {
    FLYFI.openNapsterWindow(FLYFI.napsterLink_moreInfoNotfree);
    event.preventDefault();
}

$(function() { // Document is ready
    $('#info_toggle').click(FLYFI.onClick_InfoToggle);
	$('#more_by_napster_link').click(FLYFI.onClick_NapsterMoreByLink);
    
    $(window).bind(FLYFI.MSG_TrackSelected, FLYFI.onTrackSelected_InfoPane);
}
);
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/keepers.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.current_keepers = null;
FLYFI.napsterLink_keepers = null;

FLYFI.keepers_orderBy = null;
FLYFI.keepers_paging = new FLYFI.Paging();

FLYFI.trackIDJustAddedToKeepers = null; // when a track has been added, remember it's id here so we can scroll to it after we get the new list from the server


// Keepers utilities

FLYFI.haveKeepers = function() {
    return (FLYFI.current_keepers && FLYFI.current_keepers.length > 0);
}

FLYFI.clearAndHideKeepers = function() {
    // a new library is being shown, so clear and hide the keepers
    $('#playlist').empty();
    FLYFI.removeIt('#keeperspane');
    FLYFI.clearNapsterLinkAndUpdateButton('#keepers_napster_link', '#keepers_napsterButton');
    FLYFI.onServer_Keepers({'totalAvailable': null, 'tracks': []});
    FLYFI.clearAllRecs(); // no keepers, then no recs to show
}

FLYFI.showKeepers = function() {
    FLYFI.showIt('#keepers');
    FLYFI.showIt('#keeperspane');
}

FLYFI.addToKeepers = function(trackID) {
    FLYFI.ensureCloud(function() {
                    FLYFI.callback_addToKeepers(trackID);
                });
}

// Server calls

FLYFI.onServer_Keepers = function(result) {
    // the server has returned new keepers
    FLYFI.keepers_paging.available = result['totalAvailable'];
    if (FLYFI.keepers_paging.available == null) {
        FLYFI.keepers_paging.clear();
        FLYFI.current_keepers = null;
        FLYFI.napsterLink_keepers = null;
    } else {
        FLYFI.current_keepers = result['tracks'];
        FLYFI.keepers_paging.setItemsShown(FLYFI.current_keepers.length);
    }
    FLYFI.keepers_updated();
    
    FLYFI.stopSpinner('.keepers_spinner');
}
FLYFI.onServerError_Keepers = function(request, textStatus, errorThrown) {
    stopSpinner('.keepers_spinner');
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_PlayedToEnd = function(keepersChanged, trackID) {
    if (keepersChanged) {
        $(window).trigger(FLYFI.MSG_TrackAddedToKeepers, [trackID]);
    }
}
    
FLYFI.callback_addToKeepers = function(trackID) { // define it out here so that current_library is not evaluated until the callback is made
    FLYFI.getJSON("/library/" + FLYFI.current_library.id + "/json/playedtoend/track/" + trackID + "/sourcelibrary/" + FLYFI.current_library.id  + "/",
        function(keepersChanged) {
            FLYFI.onServer_PlayedToEnd(keepersChanged, trackID);
        }, 
        FLYFI.showJSONError);
}
                
FLYFI.keepers_updated = function() {
    if (FLYFI.current_keepers != null || FLYFI.isCustomRadioPlayer()) {
        FLYFI.updateCurrentLibraryName();
        FLYFI.updateKeepersPaging();
        if (FLYFI.current_keepers && FLYFI.current_keepers.length > 0) {
            FLYFI.removeIt('#empty_top_message');
        } else {
            FLYFI.showIt('#empty_top_message');
        }
        var keepers = $('#playlist');
        keepers.makeKeepersPlaylist(FLYFI.current_keepers, FLYFI.keepers_paging.start);
        if (FLYFI.trackIDJustAddedToKeepers) {
            keepers.scrollToRowForTrackID(FLYFI.trackIDJustAddedToKeepers);
            FLYFI.trackIDJustAddedToKeepers = null;
        }
        FLYFI.showKeepers();
        
        if (!FLYFI.isNoRecsPlayer()) {
            FLYFI.showRecsPane(); // recs should be coming!
        }
		FLYFI.reset_sortable();
        FLYFI.napsterLink_keepers = FLYFI.getNapsterLinkAndUpdateButton('#playlist', '#keepers_napster_link', '#keepers_napsterButton');

        if (!FLYFI.initialLibraryShown) {
            $(window).trigger(FLYFI.MSG_InitialLibrary, [FLYFI.current_library.id]);
            FLYFI.initialLibraryShown = true;
        }
    } else {
        FLYFI.removeIt('#keepers');
    }
}

// Paging

FLYFI.updateKeepersPaging = function() {
    // update the display of the start index, end index, prev and next for the Keepers
    if (FLYFI.keepers_paging.available <= FLYFI.keepers_paging.itemsToShow) { // show controls only if not all tracks are showing
        FLYFI.hideIt('#keepers_paging_form');
        FLYFI.hideIt('.keepers_paging_prev');
        FLYFI.hideIt('.keepers_paging_next');
        return;
    } 
    
    var start = FLYFI.keepers_paging.start + 1; // display is 1-based
    var end = FLYFI.keepers_paging.end; // end is the index of the next item, so +1 is already incorporated
    $('.keepers_paging_start').text(start)
    $('.keepers_paging_end').text(end)
    
    if (start > 1) {
        FLYFI.showIt('.keepers_paging_prev');
    } else {
        FLYFI.hideIt('.keepers_paging_prev');
    }
    
    if (end < FLYFI.keepers_paging.available) {
        FLYFI.showIt('.keepers_paging_next');
    } else {
        FLYFI.removeIt('.keepers_paging_next');
    }
    FLYFI.showIt('#keepers_paging_form');
}

FLYFI.getKeepersPagingCountFromForm = function() {
    // returns whether the number changed
    var MINPAGINGCOUNT = 5;
    var MAXPAGINGCOUNT = 200;
    
    var oldCount = FLYFI.keepers_paging.itemsToShow;
    var newCount = parseInt($('#keepers_paging_pageLength').val());
    if (newCount) {
        if (newCount > MAXPAGINGCOUNT) {
            newCount = MAXPAGINGCOUNT;
        } else if (newCount < MINPAGINGCOUNT) {
            newCount = MINPAGINGCOUNT;
        }
        FLYFI.keepers_paging.itemsToShow = newCount;
    }
    $('#keepers_paging_pageLength').val(FLYFI.keepers_paging.itemsToShow);
    return (oldCount != newCount);
}

FLYFI.onSubmit_KeepersPagingPageLength = function(event) {
    var changed = FLYFI.getKeepersPagingCountFromForm();
    if (changed) {
        FLYFI.update_keepers();
    }
    event.preventDefault();
}

FLYFI.onClick_KeepersPagingPrev = function(event) {
    if (FLYFI.keepers_paging.prev()) {
        FLYFI.update_keepers();
    }
    event.preventDefault();
}

FLYFI.onClick_KeepersPagingNext = function(event) {
    if (FLYFI.keepers_paging.next()) {
        FLYFI.update_keepers();
    }
    event.preventDefault();
}

// Sorting

FLYFI.sendKeepersOrderToServer = function() {
    var tracks = $('#playlist .track');
    
    var idArray = new Array;
    for (var i = 0; i < tracks.length; ++i) {
        idArray.push(FLYFI.trackIDFromRow(tracks.eq(i)));
    }
    var ids = idArray.join(",");
    $.ajax({
        type: 'POST',
        url: '/library/' + FLYFI.current_library.id + '/json/update_track_order_from_ids/', 
        data: { ordered_tracks: ids },
        dataType: 'json',
        success: function(error) {
        }
    });
}

FLYFI.onStop_SortableKeepers = function() {
    $(this).css('top', '0px'); // jquery misplaces item, so put it back
    $(this).css('left', '0px');
    
    FLYFI.sendKeepersOrderToServer();
    $('#playlist').updateRanks();
}

FLYFI.reset_sortable = function() {
    if (FLYFI.current_library && FLYFI.isCustomRadioPlayer()) { // only allow sorting in Custom Radio players
		$('#playlist').Sortable(
			{
				accept: 'track',
				//opacity: 100,
				helperclass: 'sortHelper',
				autoScroll: true,
                onStop: FLYFI.onStop_SortableKeepers
			}
		);
	}
}

// Notifications

FLYFI.update_keepers = function(event) {
    if (FLYFI.current_library == null) {
        FLYFI.current_keepers = null;
        FLYFI.keepers_updated();
    } else {
        FLYFI.startSpinner('.keepers_spinner');
        FLYFI.showKeepers();
        var url = '/library/' + FLYFI.current_library.id + '/json/tracks/';
        if (FLYFI.keepers_orderBy) {
            url += "orderby/" + FLYFI.keepers_orderBy + "/";
        }
        if (FLYFI.keepers_paging.start > 0) {
            url += "start/" + FLYFI.keepers_paging.start + "/";
        }
        if (FLYFI.keepers_paging.itemsToShow > 0) {
            url += "count/" + FLYFI.keepers_paging.itemsToShow + "/";
        }
        FLYFI.getJSON(url, FLYFI.onServer_Keepers, FLYFI.onServerError_Keepers);
    }
}

FLYFI.onLibrarySelected_Keepers = function(event) {
    FLYFI.clearAndHideKeepers();
    FLYFI.update_keepers();
}

FLYFI.onTrackAddedToKeepers_Keepers = function(event, trackID) {
    FLYFI.trackIDJustAddedToKeepers = trackID;
    FLYFI.update_keepers();
}

$(function() { // Document is ready
	$('#keepers_napster_link').click(
        function(event) {
            FLYFI.openNapsterWindow(FLYFI.napsterLink_keepers);
            event.preventDefault();
        }
    );
    
    $('#keepers_paging_pageLength').val(FLYFI.keepers_paging.itemsToShow);
    $('#keepers_paging_pageLength').blur(FLYFI.onSubmit_KeepersPagingPageLength);
    $('#keepers_paging_form').submit(FLYFI.onSubmit_KeepersPagingPageLength);
    
    $('.keepers_paging_prev').click(FLYFI.onClick_KeepersPagingPrev);
    $('.keepers_paging_next').click(FLYFI.onClick_KeepersPagingNext);

    $(window)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.onLibrarySelected_Keepers)
        
        .bind(FLYFI.MSG_TrackAddedToKeepers, FLYFI.onTrackAddedToKeepers_Keepers)
        .bind(FLYFI.MSG_TrackVotedDown, FLYFI.update_keepers)
        .bind(FLYFI.MSG_TrackVotedUp, FLYFI.onTrackAddedToKeepers_Keepers)
        .bind(FLYFI.MSG_TrackUnvoted, FLYFI.update_keepers);
});


/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/matchingmembers.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
// Display the number of matching members that is being shown
FLYFI.set_members_count = function(members_count) {
	var html = '';
	
    if (members_count == 1) {
        html = '<b>Top member that relates to this cloud</b>';
    } else if (members_count > 1) {
        html = '<b>Top ' + members_count + ' members that relate to this cloud</b>';
	}

    $('#membercount').empty().append(html);
}

FLYFI.onServer_MatchingMembers = function(members) {
    var memberList = $('#memberlist ul');
    memberList.empty();
        
    var level = (window.level == 'live') ? '' : '/' + window.level;
    
    if (FLYFI.atHome()) { // at home, show only the first three
        members.splice(3, members.length - 3); 
    }
    
    $.each(members, function(i) {
        var name = this.nickname;
        var link = '';
        if (window.level == 'dev') { // NYI - new code - support in DEV level only
            if (name == null || name.length == 0) {
                name = 'anonymous';
                link = '<a href="' + level + '/view/id/' + this.member_id + '/">';
            } else {
                link = '<a href="' + level + '/view/' + name + '/">';
            }
        } else {
            link = '<a href="http://' + window.dev + 'www.goombah.com/view/' + name + '/">';
        }
        
        var itemHTMLArray = new Array;
        itemHTMLArray.push('<li class="member">');
        itemHTMLArray.push(link + '<img class="member_photo" src="' + this.photo_url + '" alt="" border="0" /></a>');
        itemHTMLArray.push(link + name + '</a>');
        if (this.tracks_count) {
            itemHTMLArray.push('tracks: ' + this.tracks_count);
            if (this.tracks_in_common_count) {
                itemHTMLArray.push(' shared: ' + this.tracks_in_common_count);
            }
            if (this.libraryCount) {
                itemHTMLArray.push(' clouds: ' + this.libraryCount);
            }            
        }
        itemHTMLArray.push('</li>');
        
        $(itemHTMLArray.join("\n")).appendTo(memberList);
    });
    
    FLYFI.set_members_count($('#memberlist li').size());
    
    if ($('#memberlist li').size() == 0) {
        $('<li>&nbsp;</li>').appendTo(memberList);
    }
    
    $('#memberlist_shell').removeClass('gone').addClass('here');
}

// Refresh the matching members
FLYFI.refresh_matching_members =function() {
    if (FLYFI.current_library != null) {
        FLYFI.getJSON('/library/' + FLYFI.current_library.id + '/json/matching_members/', FLYFI.onServer_MatchingMembers, FLYFI.showJSONError);
    }
}

$(function() {
    $(window)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.refresh_matching_members)
        .bind(FLYFI.MSG_NewMatchOnServer, FLYFI.refresh_matching_members)
        .bind(FLYFI.MSG_UserRequestedNewRecs, FLYFI.refresh_matching_members);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/myclouds.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
 // this module represents 'my clouds', which are the ones that belong to the viewing user
 //  these may not be the same as the 'current clouds', which are the ones the user can see
 //  and are handled by clouds.js
 //  e.g., on a profile page, the current clouds for the participant that owns the profile,
 //  but tracks that are voted up are added to one of 'my clouds'
 //  when viewing your own page, the clouds will match

FLYFI.my_libraryDicts = [];  // these are the clouds for the viewing user
FLYFI.my_currentLibraryDict = null;  // this is the 'current' clouds for the viewing user, which is the 
                        //  default cloud that tracks are added to when voted
        
FLYFI.currentCloudIsEditable = function() {
    return FLYFI.current_library && FLYFI.findMyLibraryDict(FLYFI.current_library.id) != null;
}

FLYFI.findMyLibraryDict = function(libraryID) {
    for (i = 0; i < FLYFI.my_libraryDicts.length; ++i) {
        if (FLYFI.my_libraryDicts[i].id == libraryID) {
            return FLYFI.my_libraryDicts[i];
        }
    }
    return null;
}

FLYFI.onServer_MyClouds = function(result, callback) {
    FLYFI.my_libraryDicts = result.clouds.concat(result.my_playlists);
    FLYFI.my_currentLibraryDict = result.last_library;
    if (callback) {
        callback();
    }
}

FLYFI.updateMyClouds = function(event, callback) {
    FLYFI.getJSON('/library/json/listmine/', function (result) { FLYFI.onServer_MyClouds(result, callback); }, FLYFI.showJSONError);
}

FLYFI.ensureMyCloud = function(cloudName, callback) {
    // make sure there is a cloud to take any votes or completed tracks
    if (FLYFI.my_currentLibraryDict && FLYFI.my_currentLibraryDict.name == cloudName && callback) {
        callback(FLYFI.my_currentLibraryDict);
    } else {
        FLYFI.waitingForServer_ensureMyCloud = true;
        FLYFI.setLibrarySpinner();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/library/json/new/',
            data: {artists: '', name: cloudName?cloudName:'My Cloud'},
            success: function(libraryDict) {
                        FLYFI.waitingForServer_ensureMyCloud = false;
                        FLYFI.setLibrarySpinner();
                        FLYFI.my_currentLibraryDict = libraryDict;
                        FLYFI.updateMyClouds();
                        if (callback) {
                            callback(FLYFI.my_currentLibraryDict);
                        }
                    }
        });
    }
}

$(function() { // On document ready
    $(window)
        .bind(FLYFI.MSG_LoginUpdated, FLYFI.updateMyClouds)
        .bind(FLYFI.MSG_LibraryNew, FLYFI.updateMyClouds);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/napster.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.napsterURLFromRows = function(trackRows) {
    // trackRows is an Array of the <dt> elements for the tracks.  Returns null is no valid tracks
    var all_napster_ids = new Array;
    for (i=0; i<trackRows.length; i++) {
        row = trackRows.eq(i);
        if (row.attr("napster_url")) {
            var napster_url = row.attr("napster_url")
            var napster_id =napster_url.slice(napster_url.lastIndexOf('=')+1);
            all_napster_ids.push(napster_id);
        }
    }
    if (all_napster_ids.length > 0) {
        return '/napster_player/?napster_ids=' + all_napster_ids.join(",");
    } else {
        return null;
    }
}

FLYFI.openNapsterWindow = function(url) {
    if (url) {
        $('.tracklist .track.on.play').trigger(FLYFI.MSG_Pause);
        window.open(url, 'PlayerWin', 
                    'width=670,height=488,menubar=yes,location=yes,resizable=yes,resizable=yes,scrollbars=yes,status=yes');
    }
}

FLYFI.getNapsterLinkAndUpdateButton = function(listSelector, napsterLinkSelector, napsterButtonSelector) {
    // compute and return the Napster URL for the tracks in the list, setting the buttons accordingly

    var link = null;
    if ($(listSelector + ' > .track.nonfree').length > 0) { // Show link only if we have at least one non-free track (even if some tracks have Napster URLs)
        var trackRows = $(listSelector + ' > .track:not(.voteddown)');
        link = FLYFI.napsterURLFromRows(trackRows);
    }
    
    if (link != null) {
        FLYFI.showIt(napsterLinkSelector);
        FLYFI.showIt(napsterButtonSelector);
    } else {
        FLYFI.clearNapsterLinkAndUpdateButton(napsterLinkSelector, napsterButtonSelector);
    }
    return link;
}

FLYFI.clearNapsterLinkAndUpdateButton = function(napsterLinkSelector, napsterButtonSelector) {
    FLYFI.removeIt(napsterButtonSelector);
    FLYFI.removeIt(napsterLinkSelector);
}
/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/notifications.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// These are the notification string so we "Don't Repeat Yourself"
// So, to use a notification:
//    setup_Notifications(); // do this before using notifiations
//    $(window).trigger(FLYFI.MSG_LibrarySelected);
//    $(window).bind(FLYFI.MSG_LibrarySelected, function(){});

// Process
FLYFI.MSG_Start = "start";                 // the player is ready to be initialized

// Library Notifications
FLYFI.MSG_LibraryNew = "library_new";              // a new library was created
FLYFI.MSG_LibraryNew_NoArtists = "library_new_noArtists";// a new library was created with no artists (so don't wait for recs)
FLYFI.MSG_LibrarySelected = "library_selected";    // passes [isNewLibrary]
FLYFI.MSG_LibraryDelete = "library_delete";        // a library was deleted
FLYFI.MSG_LibraryEdited = "library_edited";        // the current library was edited
FLYFI.MSG_LibraryRenamed = "library_renamed";      // the current library was renamed
FLYFI.MSG_LibrarySeedTracks = "library_seedTracks";// the seed tracks for the current library were updated

// Player Requests
FLYFI.MSG_Select = "select";                   // request to select a track
FLYFI.MSG_Pause = "pause";                     // request to pause a track
FLYFI.MSG_Play = "play";                       // request to play a track
FLYFI.MSG_Stop = "stop";                       // request to stop a track

// Sound Notifications
FLYFI.MSG_SoundFinished = "sound_finished";    // passes [trackID]
FLYFI.MSG_SoundStopped = "sound_stopped";      // passes [trackID]

// Server Notifications
FLYFI.MSG_NewMatchOnServer = "new_match";      // the server has created new matching neighbors and free recommendations
FLYFI.MSG_NewRecsOnServer = "new_recs";        // the server has created new member recommendations
FLYFI.MSG_NewPlayOnServer = "new_play";        // passes [free]; the server has been told about a new play

// Track Notifications
FLYFI.MSG_TrackSelected = "track_selected";    // passes [track, tracklist]
FLYFI.MSG_TrackResumed ="track_resumed";
FLYFI.MSG_TrackPaused = "track_paused";
FLYFI.MSG_TrackStopped = "track_stopped";      // passes []
FLYFI.MSG_TrackLoading = "track_loading";      // passes [row]
FLYFI.MSG_TrackPlaying = "track_playing";      // passes [row]
FLYFI.MSG_TrackBeingViewed = "track_view";     // passes [row]

// Vote Requests
FLYFI.MSG_VoteUp = "vote_up";              // request to vote up a track
FLYFI.MSG_VoteDown = "vote_down";          // request to vote down a track
FLYFI.MSG_Unvote = "unvote";               // request to unvote a track

// Vote Notifications
FLYFI.MSG_TrackVotedDown = "track_voted_down";// a track has been voted down
FLYFI.MSG_TrackVotedUp = "track_voted_up"; // a track has been voted up
FLYFI.MSG_TrackUnvoted = "track_unvoted";  // a track has had its vote removed

// UI Notifications
FLYFI.MSG_MoreInfoTracksUpdated = "more_info_tracks_updated"; // the list of tracks was updated in More Info
FLYFI.MSG_UserRequestedNewRecs = "user_requested_new_recs"; // the user clicked on Refresh Recs
FLYFI.MSG_TrackAddedToKeepers = "track_added_to_keepers"; // passes the trackID

// User Notifications
FLYFI.MSG_ColdStart = "cold_start";        // a new user has come to our page
FLYFI.MSG_CoolStart = "cool_start";        // a previous user has come to our page with no libraries
FLYFI.MSG_InitialLibrary = "initial_library"; // passes [libraryID]
FLYFI.MSG_LoginUpdated = "login_updated";  // passes []

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/playingtrack.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
$Id$
*/

// ensure the soundManager gets initialized

soundManager.safe_createSound = function(oOptions) {
    // Create the given track only when soundManager has finished loading.
    if (this._didInit) {
        this.createSound(oOptions);
    } else {
        this.safe_createSound_args = { oOptions: oOptions };
    }
}
    
soundManager.safe_play = function(sID, oOptions) {
    // Play the given track only when soundManager has finished loading.
    if (this._didInit) {
        this.play(sID, oOptions);
    } else {
        this.safe_play_args = { sID: sID, oOptions: oOptions };
    }
}
    
soundManager.onload = function() {
    if (soundManager.safe_createSound_args) {
        soundManager.createSound(soundManager.safe_createSound_args.oOptions);
    }
    if (soundManager.safe_play_args) {
        soundManager.play(soundManager.safe_play_args.sID, soundManager.safe_play_args.oOptions);
    }
}

FLYFI.PlayingTrack = function() {
    // the class for the one and only track that will play at any time
    
    this.MSEC_DELAYBEFOREPLAY = 500; // delay after calling SoundManager before playing to ensure it 'hears' us

    this.trackID = null;
    this.trackURL = null;
    this.row = null;
    this.scrubThumb = null;
    
    this.everStartedLoading = false;
    this.everStartedPlaying = false;
    
    this.bytesLoaded = 0;
    this.bytesTotal = 0;
    
    this.position = 0;
    this.duration = 0;
    
    this.scrubbing = false;
    
    this.haveTrack = function() {
        return (this.trackID != null);
    }
    
    this.isLoading = function() {
        if (!this.haveTrack()) {
            return false;
        }
        var sound = soundManager.getSoundById(this.trackID);
        return (sound && sound.bytesLoaded);
    }
    
    this.percentLoaded = function() {
        if (this.bytesTotal == 0) {
            return 0;
        }
        return Math.round(this.bytesLoaded / this.bytesTotal * 1000) / 10;
    }

    this.percentPlayed = function() {
        if (this.duration == 0) {
            return 0;
        }
        return Math.round(this.position / this.duration * 1000) / 10;
    }
    
    this.pause = function() {
        if (!this.haveTrack()) {
            return;
        }
        soundManager.pause(this.trackID);
    }

// utilities
    this.isLoadedInSoundManager = function(trackID){
        return ((soundManager.soundIDs.indexOf(trackID) != -1) && soundManager.sounds[trackID].loaded);
    }


    this.play = function(trackID, trackURL, row) {
        this.trackID = trackID;
        this.trackURL = trackURL;
        this.row = row;
        this.scrubThumb = row.find('.scrub_thumb');
        
        if (this.isLoadedInSoundManager(trackID)) {
            this.everStartedLoading = true;
            this.everStartedPlaying = false;
            sound = soundManager.sounds[trackID];
            this.bytesLoaded = sound.bytesLoaded;
            this.bytesTotal = sound.bytesTotal;
            this.onSoundLoading();
            this.position = 0;
            this.duration = 0;
            this.onSoundPlaying();
        } else {
            this.everStartedLoading = false;
            this.everStartedPlaying = false;
            this.bytesLoaded = 0;
            this.bytesTotal = 0;
            this.position = 0;
            this.duration = 0;
            soundManager.safe_createSound({
                id: this.trackID, 
                url: trackURL,
                whileloading: function() {
                    if (!FLYFI.playingTrack.everStartedLoading && !FLYFI.playingTrack.everStartedPlaying) {
                        FLYFI.playingTrack.everStartedLoading = true;
                        $(window).trigger(FLYFI.MSG_TrackLoading, row);
                        return; // don't report first loading progress since it is often 100%, but total is wrong
                    }
                    FLYFI.playingTrack.bytesLoaded = this.bytesLoaded;
                    FLYFI.playingTrack.bytesTotal = this.bytesTotal;
                    FLYFI.playingTrack.onSoundLoading();
                },
                whileplaying: function() {
                    if (!FLYFI.playingTrack.everStartedPlaying) {
                        FLYFI.playingTrack.everStartedPlaying = true;
                        $(window).trigger(FLYFI.MSG_TrackPlaying, row);
                    }
                    FLYFI.playingTrack.position = this.position;
                    FLYFI.playingTrack.duration = this.loaded ? this.duration : this.durationEstimate;
                    FLYFI.playingTrack.onSoundPlaying();
                },
                onfinish: function() { 
                    var trackID = FLYFI.playingTrack.trackID;
                    FLYFI.playingTrack.trackID = null;
                    $(window).trigger(FLYFI.MSG_SoundFinished, [trackID]);
                },
                onstop: function() { 
                    if (!this.loaded) {
                        soundManager.unload(this.sID);
                    }
                    var trackID = FLYFI.playingTrack.trackID;
                    FLYFI.playingTrack.trackID = null;
                    $(window).trigger(FLYFI.MSG_SoundStopped, [FLYFI.playingTrack.trackID]);
                }
            });
        }
        setTimeout(FLYFI.onTimer_Play, this.MSEC_DELAYBEFOREPLAY); // need a delay here or the soundManager doesn't play
    }
    
    this.playAtPercent = function(percent) {
        if (!this.haveTrack()) {
            return;
        }
        var msec = Math.round(this.duration * percent / 100.0);
        this.pause();
        soundManager.setPosition(this.trackID, msec);
        setTimeout(FLYFI.onTimer_Play, this.MSEC_DELAYBEFOREPLAY); // need a delay here or the soundManager doesn't play
    }
    
    this.resume = function() {
        if (!this.haveTrack()) {
            return;
        }
        soundManager.resume(this.trackID);
    }
    
    this.stop = function() {
        soundManager.stopAll();
    }

    this.updateDisplay = function() {
        if (!this.haveTrack()) {
            return;
        }
        $('.track-' + this.trackID).addClass('on').addClass('play');
        this.onSoundLoading();
        this.onSoundPlaying();
    }
    
    this.onSoundLoading = function() {
        var percent = this.percentLoaded();
        FLYFI.tracksByID(FLYFI.playingTrack.trackID).find('.load_progress').css('width', percent + '%');
    }

    this.onSoundPlaying = function(event) {
        var percent = FLYFI.playingTrack.percentPlayed();
        var rows = FLYFI.tracksByID(FLYFI.playingTrack.trackID);
        var self = this;
        
        // rows are different widths, so process them separately
        rows.each(function() {
                        self._adjustPlayingDisplayForRow(this, percent);
                    });
    }

    this._adjustPlayingDisplayForRow = function(row, percent) {
        // the scrub_thumb has to stay within the bar, so it needs to be positioned separately
        // do this work in pixels rather than percent, so we can adjust it
        var wholeWidth = $(row).width();
        var playProgress = $(row).find('.play_progress');
        var scrubThumb = $(row).find('.scrub_thumb');
        
        var newPlayWidth = Math.round(wholeWidth * percent / 100);
        if (newPlayWidth != playProgress.width()) {
            playProgress.css('width', newPlayWidth + 'px');
        }
        
        // adjust the thumb
        if (FLYFI.canScrub(row) && !this.scrubbing && this.scrubThumb.css('display') != 'none') {
            var thumbWidth = scrubThumb.width();    // ensure there is room to show the thumb
            scrubThumb.css('left', Math.round((wholeWidth-thumbWidth) * percent / 100) + 'px');
        }
    }

    this.startScrubbing = function(event, bar) {
        // return whether we could start scrubbing
        var percent = this._computePercent(event, bar);
        if (percent == null) {
            return false;
        }
        this.scrubbing = true;
        this._positionThumb(percent);
        return true;
    }
    
    this.scrub = function(event, bar) {
        this._positionThumb(this._computePercent(event, bar));
    }
    
    this.stopScrubbing = function(event, bar) {
        this.scrubbing = false;
        var percent = this._computePercent(event, bar);
        FLYFI.playingTrack.playAtPercent(percent);
    }
    
    this._positionThumb = function(percent) {
        this.scrubThumb.css('left', percent + '%');
    }
    
    this._computePercent = function(event, bar) {
        // return the percentage represented by the x position of the event in the bar, or null
        var x = event.pageX - findPosX(bar);
        var percent = Math.round((x * 100.0) / $(bar).width());
        if (percent < 0) {
            return 0;
        }
        if (percent > 100 || percent > this.percentLoaded()) {
            return null;
        }
        return percent;
    }
    
}

FLYFI.onTimer_Play = function() {
    soundManager.safe_play(FLYFI.playingTrack.trackID, {});
}
    

// The one and only PlayingTrack
FLYFI.playingTrack = new FLYFI.PlayingTrack();



/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/prefabs.js"></script> */
/* Copyright 2003-2007 Emergent Music LLC  All rights reserved.
 * $Id$
 */

FLYFI.prefab_libraryDicts = new Array; // the Prefab stations, each object having .id and .name
FLYFI.waitingForServer_prefabList = false;

FLYFI.update_prefab_stations = function(selector) {
    if (FLYFI.isGFMPlayer()) { // no prefabs for GFM player
        return; 
    }
    FLYFI.waitingForServer_prefabList = true;
    FLYFI.getJSON("/json/prefabs/", 
                    function(json) { 
                        FLYFI.onServer_Prefabs(json, selector); 
                    }, FLYFI.onServerError_Prefabs );
}

FLYFI.onServer_Prefabs = function(libraryDicts, selector) {
    FLYFI.waitingForServer_prefabList = false;
    FLYFI.prefab_libraryDicts = libraryDicts;
    FLYFI.loadMenuWithPrefabs(selector);
}

FLYFI.onServerError_Prefabs= function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_prefabList = false;
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}


FLYFI.loadMenuWithPrefabs = function(selector) {
    var HTMLArray = new Array;
    HTMLArray.push("<li><b>FlyFi Prefabs</b></li>");
    if (FLYFI.prefab_libraryDicts.length > 0) {
        for (var i=0; i < FLYFI.prefab_libraryDicts.length; i++) {
            var libraryDict = FLYFI.prefab_libraryDicts[i];
            HTMLArray.push("<li><a class=\"Prefab\" href=\"prefabs/?seed_list=library&library_id=" + libraryDict.id + "\">" + libraryDict.name + "</a></li>");
        }
    } else {
        HTMLArray.push("<li>Loading...</li>");
    }

    $(selector).html(HTMLArray.join("\n"))
    if ($('#coldStart_prefabName').text() == '') {
        $('#coldStart_prefabName').text($(selector + ' a:first').text());
    }
}

FLYFI.onClick_PrefabsTrigger = function(event) {
    // user clicked on the prefabs menu
    FLYFI.toggleRemoveIt('#coldstart_prefabs');
    return false;
}

FLYFI.onClickBody_Prefabs = function() {
    // clicking outside a pop-up should cause it to close
    FLYFI.removeIt('#coldstart_prefabs'); 
}

$(function() { // On document ready
    $('#coldStart_prefabNameDiv').click(FLYFI.onClick_PrefabsTrigger);
    $('body').click(FLYFI.onClickBody_Prefabs);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/seedtab.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

FLYFI.initial_library = null; // name of the initial library to be loaded from server (if any) 

FLYFI.seedListJSON = [];    // the JSON used to build the seed menu, in case we need to do it again

FLYFI.currentSeedListName = null;
FLYFI.currentSeedKeepersTracks = null; // the keepers for the current list - always fetched when list selected
FLYFI.currentSeedRecsTracks = null;    // the recs list for the current list - fetched the first time needed (null if not fetched; set to [] if empty)
FLYFI.currentSeedTabTracks = [];           // the list currently shown: either FLYFI.currentSeedKeepersTracks or FLYFI.currentSeedRecsTracks

FLYFI.napsterLink_seed = null;

// seed pane shows a particular library or a GFM genre list or a retrieved list (like My Most Recently Played)
FLYFI.currentSeedLibraryDict = null;        // the library_dict for the library shown in the seed tab 
FLYFI.seedTabGFMGenreId = null;    // the gfm genre to show in the seed tab (null means all)

FLYFI.seedTabOrderBy = "artist"; // track sort order
FLYFI.seedTabPaging = new FLYFI.Paging();

FLYFI.waitingForServer_genreSeedList = false;
FLYFI.waitingForServer_prefabLibraryInfo = false;
FLYFI.waitingForServer_seedKeepers = false;
FLYFI.waitingForServer_seedRecs = false;
FLYFI.waitingForServer_myRecentlyPlayed = false;
FLYFI.waitingForServer_myMostPlayed = false;
FLYFI.waitingForServer_myMostPlayedFree = false;
FLYFI.waitingForServer_seedList = false;
FLYFI.waitingForServer_initialLibraryInfo = false;

FLYFI.setSpinner_SeedTab = function() {
    // update the spinner status
    if (FLYFI.waitingForServer_genreSeedList || FLYFI.waitingForServer_prefabLibraryInfo || FLYFI.waitingForServer_seedKeepers ||
        FLYFI.waitingForServer_seedRecs || FLYFI.waitingForServer_myRecentlyPlayed || FLYFI.waitingForServer_myMostPlayed || 
        FLYFI.waitingForServer_myMostPlayedFree || FLYFI.waitingForServer_seedList || FLYFI.waitingForServer_initialLibraryInfo) {
        FLYFI.startSpinner('.gfm_spinner');
    } else {
        FLYFI.stopSpinner('.gfm_spinner');
    }
}

FLYFI.onClick_SeedMenuTrigger = function(event) {
    // user clicked on the menu within the seed tab
    if (!FLYFI.inColdStart() && !$('#seed_tab').hasClass('on')) {
        // has any library ever been loaded?
        if ((FLYFI.seedTabGFMGenreId == null) && (FLYFI.currentSeedLibraryDict == null)) {
            var name = $('#seed_menu_trigger').text();
            $("#seed_menu_choices a:contains('" + name + "')").click(); // load the default library
        }
        FLYFI.showSeedTab();
    } else {
        FLYFI.toggleRemoveIt('#seed_menu_choices');
    }
    return false;
}

FLYFI.onServer_GFMGenreList = function(result) {
    // the server has returned new GFM list
    FLYFI.waitingForServer_genreSeedList = false;
    FLYFI.setSpinner_SeedTab();
    
    FLYFI.currentSeedLibraryDict = null;
    
    FLYFI.seedTabPaging.available = result['totalAvailable'];
    var tracks = result['tracks'];
    FLYFI.currentSeedKeepersTracks = tracks;
    FLYFI.currentSeedRecsTracks = null;
    FLYFI.currentSeedTabTracks = FLYFI.currentSeedKeepersTracks;
    FLYFI.seedTabPaging.setItemsShown(FLYFI.currentSeedTabTracks.length);
    FLYFI.updateOrderBy_SeedTab();
    FLYFI.seedTracksUpdated();
}
FLYFI.onServerError_GFMGenreList = function(request, textStatus, errorThrown) {
    // the server has returned new GFM list
    FLYFI.waitingForServer_genreSeedList = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.clearAndShowSeedTab = function() {
    FLYFI.clearColdStart();
    FLYFI.currentSeedListName = '';
    FLYFI.currentSeedRecsTracks = null;
    FLYFI.currentSeedKeepersTracks = null;
    FLYFI.currentSeedTabTracks = [];
    FLYFI.seedTabPaging.clear();
    FLYFI.seedTracksUpdated();
}

FLYFI.seedTracksUpdated = function() {
    // display the new seed tracks
    if (FLYFI.currentSeedLibraryDict != null) {
        // NYI - FLYFI.showIt('.seed_keepers_link');
        // NYI - FLYFI.showIt('.seed_recs_link');
    } else {
        // NYI - FLYFI.removeIt('.seed_keepers_link');
        // NYI - FLYFI.removeIt('.seed_recs_link');
    }
    $('#seed_track_list').seedPlaylist(FLYFI.currentSeedTabTracks, FLYFI.seedTabPaging.start);
    if (FLYFI.currentSeedListName.length > 0) {
        $('#seed_menu_trigger').text(FLYFI.currentSeedListName + ' (' + FLYFI.seedTabPaging.available + ')');
    } else {
        $('#seed_menu_trigger').text('');
    }
    FLYFI.updateSeedListPaging();
    FLYFI.napsterLink_seed = FLYFI.getNapsterLinkAndUpdateButton('#seed_track_list', '#seed_napster_link', '#seed_napsterButton');

    FLYFI.showSeedTab();
}

FLYFI.updateSeedListPaging = function() {
    // update the display of the start index, end index, prev and next for the user
    var start = FLYFI.seedTabPaging.start + 1; // display is 1-based
    var end = FLYFI.seedTabPaging.end; // end is the index of the next item, so +1 is already incorporated
    $('.seed_list_start_index').text(start)
    $('.seed_list_end_index').text(end)
    
    if (start > 0) {
        FLYFI.showIt('.seed_list_prev');
    } else {
        FLYFI.hideIt('.seed_list_prev');
    }
    
    if (end < FLYFI.seedTabPaging.available) {
        FLYFI.showIt('.seed_list_next');
    } else {
        FLYFI.removeIt('.seed_list_next');
    }
}

// GFM Menu Item

FLYFI.showGFM_DefaultGenre = function() {
    FLYFI.showIt('#seed_menu');
    FLYFI.loadInitialGFMGenre(1452, 'Rock');
}

FLYFI.onClick_GFMMenuItem = function(event) {
    // user clicked on an item in the seed menu
    FLYFI.selectGFMLibraryItem($(this));
    event.preventDefault();
}

FLYFI.selectGFMLibraryItem = function(item) {
    FLYFI.clearAndShowSeedTab();
    
    var genreID = item.attr("genreID");
    FLYFI.currentSeedListName = item.text(); // will add number after the fetch
    FLYFI.selectGFMGenre(genreID);
}

FLYFI.selectGFMGenre = function(genreID) {
    FLYFI.seedTabGFMGenreId = genreID;
    $('#seed_menu_trigger').text(FLYFI.currentSeedListName);
    
    FLYFI.currentSeedTabTracks = [];
    FLYFI.updateGenreSeedListFromServer(genreID);
}

// Initial Library 

FLYFI.loadInitialGFMGenre = function(genreID, genreName) {
    FLYFI.clearAndShowSeedTab();
    FLYFI.currentSeedListName = genreName;
    FLYFI.selectGFMGenre(genreID);
}

// Prefab Menu Item 

FLYFI.onClick_PrefabMenuItem = function(event) {
    FLYFI.clearAndShowSeedTab();
    
    var libraryID = $(this).attr('libraryID');
    FLYFI.waitingForServer_prefabLibraryInfo = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/library/' + libraryID + '/json/info/', FLYFI.onServer_LibraryInfo, FLYFI.onServerError_LibraryInfo);
    event.preventDefault();
}

FLYFI.onServer_LibraryInfo = function(library) {
    FLYFI.waitingForServer_prefabLibraryInfo = false;
    FLYFI.setSpinner_SeedTab();
    FLYFI.setSeedListToLibrary(library, false);
}
FLYFI.onServerError_LibraryInfo = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_prefabLibraryInfo = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.updateSeedRecsFromServer = function() { // NYI - Add paging
    FLYFI.waitingForServer_seedRecs = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/library/' + FLYFI.currentSeedLibraryDict.id + '/json/recs/', FLYFI.onServer_SeedRecs, FLYFI.onServerError_SeedRecs);
}

FLYFI.updateGenreSeedListFromServer = function(genreID) { // NYI - should be obsolete - we do this by library ID now
    var url = "/gfm/genre/" + genreID + "/json/";
    
    if (FLYFI.seedTabOrderBy) {
        url += "orderby/" + FLYFI.seedTabOrderBy + "/";
    }
    if (FLYFI.seedTabPaging.start > 0) {
        url += "start/" + FLYFI.seedTabPaging.start + "/";
    }
    if (FLYFI.seedTabPaging.itemsToShow > 0) {
        url += "count/" + FLYFI.seedTabPaging.itemsToShow + "/";
    }
    
    FLYFI.waitingForServer_genreSeedList = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON(url, FLYFI.onServer_GFMGenreList, FLYFI.onServerError_GFMGenreList);
}

FLYFI.onServer_SeedKeepers = function(result, firstLoadOfInitialLibrary) {
    // the server has returned new seed keepers
    var totalAvailable = result['totalAvailable'];
    var tracks = result['tracks'];
    FLYFI.waitingForServer_seedKeepers = false;
    FLYFI.setSpinner_SeedTab();
    
    FLYFI.currentSeedKeepersTracks = tracks;
    FLYFI.currentSeedTabTracks = FLYFI.currentSeedKeepersTracks;
    FLYFI.seedTracksUpdated();
    
    if (firstLoadOfInitialLibrary) {
        $(window).trigger(FLYFI.MSG_InitialLibrary, [FLYFI.initial_library.id]);
    }
}
FLYFI.onServerError_SeedKeepers = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_seedKeepers = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_SeedRecs = function(result) {
    // the server has returned new seed recs
    FLYFI.waitingForServer_seedRecs = false;
    FLYFI.setSpinner_SeedTab();
    
    var recs = result['recs']; // list of track summary_dicts
    
    FLYFI.currentSeedRecsTracks = recs;
    FLYFI.currentSeedTabTracks = FLYFI.currentSeedRecsTracks;
    FLYFI.seedTracksUpdated();
}
FLYFI.onServerError_SeedRecs = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_seedRecs = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}


FLYFI.onServer_myRecentlyPlayed = function(tracks) {
    FLYFI.waitingForServer_myRecentlyPlayed = false;
    FLYFI.setSpinner_SeedTab();
    FLYFI.do_onServer_myTracks(tracks);
}
FLYFI.onServerError_myRecentlyPlayed = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_myRecentlyPlayed = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_myMostPlayed = function(tracks) {
    FLYFI.waitingForServer_myMostPlayed = false;
    FLYFI.setSpinner_SeedTab();
    FLYFI.do_onServer_myTracks(tracks);
}
FLYFI.onServerError_myMostPlayed = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_myMostPlayed = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.onServer_myMostPlayedFree = function(tracks) {
    FLYFI.waitingForServer_myMostPlayedFree = false;
    FLYFI.setSpinner_SeedTab();
    FLYFI.do_onServer_myTracks(tracks);
}
FLYFI.onServerError_myMostPlayedFree = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_myMostPlayedFree = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.do_onServer_myTracks = function(tracks) {
    FLYFI.seedTabGFMGenreId = null;
    FLYFI.currentSeedLibraryDict = null;
    
    FLYFI.currentSeedKeepersTracks = tracks;
    FLYFI.currentSeedRecsTracks = null;
    FLYFI.currentSeedTabTracks = FLYFI.currentSeedKeepersTracks;
    FLYFI.seedTracksUpdated();
}

FLYFI.onClick_initialLibraryMenuItem = function(event) {
    FLYFI.clearAndShowSeedTab();
    
    FLYFI.setSeedListToLibrary(FLYFI.initial_library, false);
    if (event) {
        event.preventDefault();
    }
}

FLYFI.setSeedListToLibrary = function(library, firstLoadOfInitialLibrary) {
    FLYFI.seedTabGFMGenreId = null;
    FLYFI.currentSeedLibraryDict = library;
    FLYFI.currentSeedListName = library.name ? library.name : 'unnamed library'; // will add number after the fetch
    $('#seed_menu_trigger').text(FLYFI.currentSeedListName);

    FLYFI.waitingForServer_seedKeepers = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/library/' + FLYFI.currentSeedLibraryDict.id + '/json/tracks/', 
        function(json) {
            FLYFI.onServer_SeedKeepers(json, firstLoadOfInitialLibrary);
        }, FLYFI.onServerError_SeedKeepers);
}

FLYFI.onClick_myRecentlyPlayedMenuItem = function(event) {
    FLYFI.clearAndShowSeedTab();
    FLYFI.currentSeedListName = $(this).text(); // will add number after the fetch
    $('#seed_menu_trigger').text(FLYFI.currentSeedListName);
    
    FLYFI.waitingForServer_myRecentlyPlayed = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/participant/' + FLYFI.current_user.nickname + '/json/recently_played_tracks/', FLYFI.onServer_myRecentlyPlayed, FLYFI.onServerError_myRecentlyPlayed);
    event.preventDefault();
}

FLYFI.onClick_myMostPlayedMenuItem = function(event) {
    FLYFI.clearAndShowSeedTab();
    FLYFI.currentSeedListName = $(this).text(); // will add number after the fetch
    $('#seed_menu_trigger').text(FLYFI.currentSeedListName);
    
    FLYFI.waitingForServer_myMostPlayed = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/participant/' + FLYFI.current_user.nickname + '/json/top_played_tracks/', FLYFI.onServer_myMostPlayed, FLYFI.onServerError_myMostPlayed);
    event.preventDefault();
}

FLYFI.onClick_myMostPlayedFreeMenuItem = function(event) {
    FLYFI.clearAndShowSeedTab();
    FLYFI.currentSeedListName = $(this).text(); // will add number after the fetch
    $('#seed_menu_trigger').text(FLYFI.currentSeedListName);
    
    FLYFI.waitingForServer_myMostPlayedFree = true;
    FLYFI.setSpinner_SeedTab();
    FLYFI.getJSON('/participant/' + FLYFI.current_user.nickname + '/json/top_played_free_tracks/', FLYFI.onServer_myMostPlayedFree, FLYFI.onServerError_myMostPlayedFree);
    event.preventDefault();
}

FLYFI.onClick_SeedKeepersLink = function(event) {
    FLYFI.currentSeedTabTracks = FLYFI.currentSeedKeepersTracks; 
    FLYFI.seedTracksUpdated();
    event.preventDefault();
}

FLYFI.onClick_SeedRecsLink = function(event) {
    if (FLYFI.currentSeedRecsTracks != null) { // if we already have them, just switch
        FLYFI.currentSeedTabTracks = FLYFI.currentSeedRecsTracks; 
        FLYFI.seedTracksUpdated();
    } else {
        FLYFI.updateSeedRecsFromServer();
    }
    event.preventDefault();
}

FLYFI.onServer_SeedList = function(json) {
    // set up the seed menu from the list returned by the server
    FLYFI.seedListJSON = json;
    
    FLYFI.waitingForServer_seedList = false;
    FLYFI.setSpinner_SeedTab();
    
    FLYFI.rebuild_SeedMenu();
}
FLYFI.onServerError_SeedList = function(request, textStatus, errorThrown) {
    // set up the seed menu from the list returned by the server
    FLYFI.waitingForServer_seedList = false;
    FLYFI.setSpinner_SeedTab();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

FLYFI.rebuild_SeedMenu = function() {
    // build the new seed menu
    var HTMLArray = new Array;
    HTMLArray.push("<ul>");

    if (FLYFI.initial_library) {
        HTMLArray.push("<li><b>Initial Library</b></li>");
        HTMLArray.push("<li><a class=\"initiallibrary\" href=\"#\">" + (FLYFI.initial_library.name ? FLYFI.initial_library.name : 'unnamed library') + "</a></li>");
    }
    
    var noParticipant = true;
    for (var i=0; i < FLYFI.seedListJSON.length; i++) {
        var tup = FLYFI.seedListJSON[i];
        if (tup[0] == "Participant") {
            if (noParticipant) {
                var title = window.target_participant_nickname + "'s Clouds";
                HTMLArray.push("<li class=\"Participant_li\"><b>" + title + "</b></li>");
                noParticipant = false;
            }
            HTMLArray.push("<li class=\"Participant_li\"><a class=\"Participant\" href=\"#\" libraryID=\"" + tup[2] + "\">" + tup[1] + "</a></li>");
        }
    }

    var noUploaded = true;
    for (var i=0; i < FLYFI.seedListJSON.length; i++) {
        var tup = FLYFI.seedListJSON[i];
        if (tup[0] == "Uploaded") {
            if (noUploaded) {
                HTMLArray.push("<li class=\"Uploaded_li\"><b>My Uploaded Tracks</b></li>");
                noUploaded = false;
            }
            HTMLArray.push("<li class=\"Uploaded_li\"><a class=\"Uploaded\" href=\"#\" libraryID=\"" + tup[2] + "\">" + tup[1] + "</a></li>");
        }
    }

    if (FLYFI.current_user) {
        HTMLArray.push("<li><b>My Tracks</b></li>");
        HTMLArray.push("<li><a class=\"myrecentlyplayed\" href=\"#\">Recently Played</a></li>");
        HTMLArray.push("<li><a class=\"mymostplayed\" href=\"#\">Most Played</a></li>");
        HTMLArray.push("<li><a class=\"mymostplayedfree\" href=\"#\">Most Played Free</a></li>");
    }

    if (FLYFI.prefab_libraryDicts.length > 0) {
        HTMLArray.push("<li><b>Goombah Clouds</b></li>");
        for (var i=0; i < FLYFI.prefab_libraryDicts.length; i++) {
            var prefab = FLYFI.prefab_libraryDicts[i];
            HTMLArray.push("<li><a class=\"Prefab\" href=\"#\" libraryID=\"" + prefab.id + "\">" + prefab.name + "</a></li>");
        }
    } else if (FLYFI.waitingForServer_prefabList) {
        HTMLArray.push("<li><b>Goombah Clouds</b></li>");
        HTMLArray.push("<li><a class=\"Prefab\">Loading...</a></li>");
    }

    var noGFM = true;
    for (var i=0; i < FLYFI.seedListJSON.length; i++) {
        var tup = FLYFI.seedListJSON[i];
        if (tup[0] == "GFM") {
            if (noGFM) {
                HTMLArray.push("<li class=\"GFM_li\"><b>All Free MP3s</b></li>");
                noGFM = false;
            }
            HTMLArray.push("<li class=\"GFM_li\"><a class=\"GFM\" href=\"#\" genreID=\"" + tup[2] + "\">" + tup[1] + "</a></li>");
        }
    }

    HTMLArray.push("</ul>");
    $('#seed_menu_choices').html(HTMLArray.join("\n"))
    
    $('#seed_menu_choices a.initiallibrary').click(FLYFI.onClick_initialLibraryMenuItem);
    $('#seed_menu_choices a.myrecentlyplayed').click(FLYFI.onClick_myRecentlyPlayedMenuItem);
    $('#seed_menu_choices a.mymostplayed').click(FLYFI.onClick_myMostPlayedMenuItem);
    $('#seed_menu_choices a.mymostplayedfree').click(FLYFI.onClick_myMostPlayedFreeMenuItem);
    
    $('#seed_menu_choices a.Participant').click(FLYFI.onClick_PrefabMenuItem);
    $('#seed_menu_choices a.Uploaded').click(FLYFI.onClick_PrefabMenuItem); // same behavior
    $('#seed_menu_choices a.GFM').click(FLYFI.onClick_GFMMenuItem);
    $('#seed_menu_choices a.Prefab').click(FLYFI.onClick_PrefabMenuItem);
    
    var uploadedItem = $('#seed_menu_choices a.Uploaded:visible:first');
    if (uploadedItem.length > 0) {
        uploadedItem.click();
    } else {
        if ($('#seed_menu_trigger').text() == '') {
            $('#seed_menu_trigger').text($('#seed_menu_choices a:first').text());
        }
    }
}

FLYFI.update_seed_menu = function() {
    FLYFI.waitingForServer_seedList = true;
    FLYFI.setSpinner_SeedTab();
    var url = "/seedlists/";
    if (window.target_participant_id) {
        url += "participant/" + window.target_participant_id;
    }
    FLYFI.getJSON(url, FLYFI.onServer_SeedList, FLYFI.onServerError_SeedList);
}

// ---- Seed pane

FLYFI.getSeedListCountFromForm = function() {
    // returns whether the number changed
    var MINPAGINGCOUNT = 5;
    var MAXPAGINGCOUNT = 200;

    var oldCount = FLYFI.seedTabPaging.itemsToShow;
    var newCount = parseInt($('#gfm_page_size_field').val());
    if (newCount) {
        if (newCount > MAXPAGINGCOUNT) {
            newCount = MAXPAGINGCOUNT;
        } else if (newCount < MINPAGINGCOUNT) {
            newCount = MINPAGINGCOUNT;
        }
        FLYFI.seedTabPaging.itemsToShow = newCount;
    }
    $('#gfm_page_size_field').val(FLYFI.seedTabPaging.itemsToShow);
    return (oldCount != newCount);
}

FLYFI.resetPaging_SeedTab = function() {
    // redisplay the page for a new sort order or page length
    if (FLYFI.seedTabGFMGenreId != null) {
        FLYFI.updateGenreSeedListFromServer(FLYFI.seedTabGFMGenreId);
    }
    if (FLYFI.currentSeedLibraryDict != null) {
        // NYI
    }
}

FLYFI.onSubmit_Paging_SeedTab = function(event) {
    var changed = FLYFI.getSeedListCountFromForm();
    if (changed) {
        FLYFI.resetPaging_SeedTab();
    }
    event.preventDefault();
}

FLYFI.onClick_seedListPrev = function(event) {
    if (FLYFI.seedTabPaging.prev()) {
        FLYFI.resetPaging_SeedTab();
    }
    event.preventDefault();
}

FLYFI.onClick_seedListNext = function(event) {
    if (FLYFI.seedTabPaging.next()) {
        FLYFI.resetPaging_SeedTab();
    }
    event.preventDefault();
}

FLYFI.updateOrderBy_SeedTab = function() {
    if ((FLYFI.seedTabOrderBy == "artist") && $('.sort_by_artist').hasClass('on')) {
        return; // already set
    }
    if ((FLYFI.seedTabOrderBy == "track") && $('.sort_by_track').hasClass('on')) {
        return; // already set
    }
    if ((FLYFI.seedTabOrderBy == "genre") && $('.sort_by_genre').hasClass('on')) {
        return; // already set
    }
    $('.sort_by').removeClass('on');
    if (FLYFI.seedTabOrderBy == "artist") {
        $('.sort_by_artist').addClass('on');
        return; 
    }
    if (FLYFI.seedTabOrderBy == "track") {
        $('.sort_by_track').addClass('on');
        return; 
    }
    if (FLYFI.seedTabOrderBy == "genre") {
        $('.sort_by_genre').addClass('on');
        return; 
    }
}

FLYFI.onClick_SortByArtist = function(event) {
    if (FLYFI.seedTabOrderBy == "artist") {
        return;
    }
    FLYFI.seedTabOrderBy = "artist";
    FLYFI.seedTabPaging.start = 0;
    FLYFI.resetPaging_SeedTab();
    event.preventDefault();
}

FLYFI.onClick_SortByTrack = function(event) {
    if (FLYFI.seedTabOrderBy == "track") {
        return;
    }
    FLYFI.seedTabOrderBy = "track";
    FLYFI.seedTabPaging.start = 0;
    FLYFI.resetPaging_SeedTab();
    event.preventDefault();
}

FLYFI.onClick_SortByGenre = function(event) {
    if (FLYFI.seedTabOrderBy == "genre") {
        return;
    }
    FLYFI.seedTabOrderBy = "genre";
    FLYFI.seedTabPaging.start = 0;
    FLYFI.resetPaging_SeedTab();
    event.preventDefault();
}

FLYFI.onClick_SortByReleaseDate = function(event) {
    if (FLYFI.seedTabOrderBy == "release_date") {
        return;
    }
    FLYFI.seedTabOrderBy = "release_date";
    FLYFI.seedTabPaging.start = 0;
    FLYFI.resetPaging_SeedTab();
    event.preventDefault();
}

$(function() { // On document ready
    $('#seed_menu_trigger').click(FLYFI.onClick_SeedMenuTrigger);
    $('#seed_menu_arrow').click(FLYFI.onClick_SeedMenuTrigger);
    $('#seed_keepers_link').click(FLYFI.onClick_SeedKeepersLink);
    $('#seed_recs_link').click(FLYFI.onClick_SeedRecsLink);
    
    $('#gfm_page_size_field').val(FLYFI.seedTabPaging.itemsToShow);
    $('#gfm_page_size_field').blur(FLYFI.onSubmit_Paging_SeedTab);
    $('#gfm_paging_form').submit(FLYFI.onSubmit_Paging_SeedTab);
    
    $('.sort_by_artist').click(FLYFI.onClick_SortByArtist);
    $('.sort_by_track').click(FLYFI.onClick_SortByTrack);
    $('.sort_by_genre').click(FLYFI.onClick_SortByGenre);
    $('.sort_by_date').click(FLYFI.onClick_SortByReleaseDate);
    $('.seed_list_prev').click(FLYFI.onClick_seedListPrev);
    $('.seed_list_next').click(FLYFI.onClick_seedListNext);
    
	$('#seed_napster_link').click(
                function(event) {
                    FLYFI.openNapsterWindow(FLYFI.napsterLink_seed);
                    event.preventDefault();
                }
    );

});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/seedtracks.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

/*  Seed tracks are added when a library is created or edited.  They are used as recommendations, but 
    are by the identified artists for the library rather than selected by the recommender. 
    
    Uses Free Recs Spinner when talking to the server.
*/
    
FLYFI.currentSeedTracks = [];
FLYFI.askingServerForSeedTracks = false;  // true when we are requesting seed tracks from server

FLYFI.updateSeedTracks = function() {
    if (FLYFI.current_library) {
        FLYFI.askingServerForSeedTracks = true;
        FLYFI.setAllRecsSpinner();
        
        FLYFI.getJSON('/library/' + FLYFI.current_library.id + '/json/seed_tracks/', FLYFI.onServer_UpdateSeedTracks, FLYFI.onServerError_UpdateSeedTracks);
    }
}

FLYFI.onServer_UpdateSeedTracks = function(tracks) {
    // the server has returned the seed tracks for the library
    if (FLYFI.currentSeedTracks != tracks) {
        FLYFI.currentSeedTracks = tracks;
        $(window).trigger(FLYFI.MSG_LibrarySeedTracks);
    }
    FLYFI.askingServerForSeedTracks = false;
    FLYFI.setAllRecsSpinner();
}
FLYFI.onServerError_UpdateSeedTracks = function(request, textStatus, errorThrown) {
    FLYFI.askingServerForSeedTracks = false;
    FLYFI.setAllRecsSpinner();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}


FLYFI.getSeedTracks = function() {
    // the library has changed, so clear the seed tracks and get new ones
    FLYFI.currentSeedTracks = [];
    if (FLYFI.current_library) {
        FLYFI.askingServerForSeedTracks = true;
        FLYFI.setAllRecsSpinner();
        
        FLYFI.getJSON('/library/' + FLYFI.current_library.id + '/json/seed_tracks/', FLYFI.onServer_GetSeedTracks, FLYFI.onServerError_GetSeedTracks);
    }
}

FLYFI.onServer_GetSeedTracks = function(tracks) {
    // the server has returned the seed tracks for the library
    FLYFI.currentSeedTracks = tracks;
    $(window).trigger(FLYFI.MSG_LibrarySeedTracks);
    
    FLYFI.askingServerForSeedTracks = false;
    FLYFI.setAllRecsSpinner();
}
FLYFI.onServerError_GetSeedTracks = function(request, textStatus, errorThrown) {
    // the server has returned the seed tracks for the library
    FLYFI.askingServerForSeedTracks = false;
    FLYFI.setAllRecsSpinner();

    FLYFI.showJSONError(request, textStatus, errorThrown);
}

$(function() { // Document is ready
	// Seed tracks events
    $(window)
        .bind(FLYFI.MSG_LibraryNew, FLYFI.getSeedTracks)
        .bind(FLYFI.MSG_LibraryEdited, FLYFI.updateSeedTracks)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.updateSeedTracks);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/playlist.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
$Id$
*/

var removeDeferred = new Array; // if a track is removed while playing, save the row here and remove it later

var mouseDown_Row = null;       // row for a mouse down in a row but only until the mouse up
var addDialog_track = null;     // the track being added in the Add dialog
var addDialog_targetCloudID = null; // the cloud the track is being added to in the Add dialog

var lastReported_TrackID;  // the TrackID of the last track reported to the server (so we don't report the same one twice)

// server

FLYFI.server_voteUp = function(track, libraryid) {
    $.post("/library/" + libraryid + "/vote_up/sourcelibrary/" + FLYFI.current_library.id + '/',
        {'track_id': track.id}, 
        function() {
            if (FLYFI.atMyPage() || FLYFI.isCustomRadioPlayer()) {
                $(window).trigger(FLYFI.MSG_TrackVotedUp, [track.id]);
            }
        }
    );
}

FLYFI.server_voteDown = function(track) {
    var url = "/blacklist/" + track.id + "/";
    if (FLYFI.atMyPage() || FLYFI.isCustomRadioPlayer()) {
        url = "/library/" + FLYFI.current_library.id + "/vote_down/";
    }
    FLYFI.ensureCloud(function() {
                    $.post(url,
                        {'track_id': track.id},
                        function() {
                            if (FLYFI.atMyPage() || FLYFI.isCustomRadioPlayer()) {
                                $(window).trigger(FLYFI.MSG_TrackVotedDown, [track.id]);
                            }
                        }
                    );
                }
    );
}

FLYFI.server_unvote = function(track) {
    FLYFI.ensureCloud(function() {
                    $.post("/library/unvote/" + track.id + "/", 
                        function() {
                            if (FLYFI.atMyPage() || FLYFI.isCustomRadioPlayer()) {
                                $(window).trigger(FLYFI.MSG_TrackUnvoted, [track.id]);
                            }
                        }
                    );
                }
    );
}

FLYFI.server_ReportPlay = function(trackID, free) {
    if (trackID == lastReported_TrackID) {
        return; // don't report the same track twice in a row
    }
    $.post("/json/play/" + trackID + "/", function() {
                                                $(window).trigger(FLYFI.MSG_NewPlayOnServer);
                                            }
    );
    lastReported_TrackID = trackID;
}

FLYFI.trackIDFromRow = function(row) {
    var classes = new String(row.attr('className')).split(' ');
    for (i=0; i< classes.length; i++) {
        var c = classes[i];
        if (c.substr(0, 'track-'.length) == 'track-') {
            return c.slice('track-'.length);
        }
    }
    return null;
}

FLYFI.tracksByID = function(trackID) {
    return $('.track-' + trackID);
}

function setClickedRow(row) {
    // class 'on' is used for tracks with the selected ID
    // class 'clicked' is used for the one row that the user clicked on
    if (row.hasClass('clicked')) { // already set?
        return;    
    }
    
    if (! row.hasClass('on')) {
        $('.track').removeClass('on').removeClass('play'); // turn all others off
        FLYFI.tracksByID(FLYFI.trackIDFromRow(row)).addClass('on');
    }
    
    $('.track').removeClass('clicked'); // turn all others off
    row.addClass('clicked');
}

// Scrubbing

FLYFI.canScrub = function(row) {
    // all playlists scrub unless they have the class 'noScrub'
    var tracklist = $(row).parents('.tracklist');
    return !tracklist.hasClass('noScrub');
}

function onMouseDown_Row(event) {
    // user has clicked on a row - may need to play or scrub. 
    var row = $(this);
    if (!FLYFI.canScrub(row)) {
        row.trigger(FLYFI.MSG_Play);
        return; // allow inherited events
    }

    // If the track is not loaded: start playing at the beginning
    if (FLYFI.playingTrack.trackID != FLYFI.trackIDFromRow(row) || !FLYFI.playingTrack.everStartedLoading) {
        row.trigger(FLYFI.MSG_Play);
        return false;
    }
    
    mouseDown_Row = row;
    var progressBars = row.find('.progress_bars');
    if(!FLYFI.playingTrack.startScrubbing(event, progressBars[0])) {
        row.trigger(FLYFI.MSG_Play);   // could not scrub, so start playing at the beginning.
    }
    return false;
}

function onMouseMove_Row(event) {
    var row = $(this);
    if (!FLYFI.canScrub(row)) {
        return; // allow inherited events
    }
    
    if (!mouseDown_Row) {
        return false;
    }
    
    var progressBars = row.find('.progress_bars');
    FLYFI.playingTrack.scrub(event, progressBars[0]);
    return false;
}

function onMouseUp_Row(event) {
    var row = $(this);
    if (!FLYFI.canScrub(row)) {
        return; // allow inherited events
    }
    
    mouseDown_Row = null;
    
    var progressBars = row.find('.progress_bars');
    FLYFI.playingTrack.stopScrubbing(event, progressBars[0]);
    return false;
}

function onPlay(row, track) {
    if (row.hasClass('on') && !row.hasClass('play')) {  // If the playback is paused, simply resume.
        setClickedRow(row);
        FLYFI.playingTrack.resume();
        FLYFI.tracksByID(track.id).addClass('play');
        $(window).trigger(FLYFI.MSG_TrackResumed, [track, row]);
        return;
    }

    setClickedRow(row);
    
    $('.track').removeClass('play'); // turn all others off
    FLYFI.playingTrack.stop();
    removeDeferredRows();
    
    var tracklist = $(row).parents('.tracklist');
    $(window).trigger(FLYFI.MSG_TrackSelected, [track, tracklist]);
    
    FLYFI.playingTrack.play(track.id, track.play_url, row);
    FLYFI.playingTrack.updateDisplay();
}

function onPlayNotFree(row, track) {
    // a not-free track has been requested to play
    setClickedRow(row);
    
    FLYFI.playingTrack.stop();
    removeDeferredRows();
    
    var tracklist = $(row).parents('.tracklist');
    $(window).trigger(FLYFI.MSG_TrackSelected, [track, tracklist]);

    $(window).trigger(FLYFI.MSG_TrackBeingViewed, row);
}

function ignoreEvent(event) {
    // call this so an even it not handled - added for scrolling
    event.stopPropagation();   
}

function _doVoteUp(track) {
    FLYFI.server_voteUp(track, FLYFI.current_library.id); 
}

function onVoteUp_Row(row, track) {
    if ((FLYFI.atMyPage() || FLYFI.isCustomRadioPlayer()) && FLYFI.currentCloudIsEditable()) {
        track.vote = 1;
        FLYFI.tracksByID(track.id).addClass('votedup').removeClass('voteddown');
        FLYFI.ensureCloud(function() { _doVoteUp(track) } );
        
    } else {
        askUser_AddKeeper(track);
    }
}

function updateAddKeeperCloudList(track) {
    var list = $('#addKeeper_dialog_clouds');
    list.empty();
    
    if (FLYFI.my_libraryDicts.length > 0) {
        list.append( $('<li><b>My Clouds</b></li>') );
        
        $.each(FLYFI.my_libraryDicts, function(i) {
            var libraryDict = this;
            var onClass = ((FLYFI.my_currentLibraryDict && (libraryDict.id == FLYFI.my_currentLibraryDict.id)) ? ' class="on"' : '');
            $('<li><a href="#"' + onClass + ' libraryid=' + libraryDict.id + '>' + libraryDict.name + '</a></li>')
                .appendTo('#addKeeper_dialog_clouds')
                .find('a').click(function (event) { 
                                    $('#addKeeper_dialog_targetCloud').text($(this).text());
                                    addDialog_targetCloudID = $(this).attr('libraryid');
                                    $('#addKeeper_dialog_clouds a').removeClass('on');
                                    $(this).addClass('on');
                                    event.preventDefault();
                                });
        });
    }
    var l = $('#addKeeper_dialog_clouds li');
    var x = l.length;
}

function askUser_AddKeeper(track) {
    addDialog_track = track;
    updateAddKeeperCloudList(track);
    $('#addKeeper_dialog_trackname').text(track.title);
    $('#addKeeper_dialog_artistname').text(track.artist);
    if ($('#addKeeper_dialog_clouds li').length > 0) {
        var cloudName = '(click to select target cloud)';
        if (FLYFI.my_currentLibraryDict) {
            cloudName = FLYFI.my_currentLibraryDict.name;
            addDialog_targetCloudID = FLYFI.my_currentLibraryDict.id;
        } else {
            addDialog_targetCloudID = null;
        }
        $('#addKeeper_dialog_targetCloud').text(cloudName);
        FLYFI.showIt('#addKeeper_dialog_targetCloudDiv');
    } else {
        FLYFI.removeIt('#addKeeper_dialog_targetCloudDiv');
    }
    $('#addKeeper_dialog_NewCloudName').val('My Cloud'); // NYI should be unique name
    $('#addKeeper_dialog').modal();
}

FLYFI.onClickCancel_AddKeeper = function() {
    $.modal.close();
}

FLYFI.onSubmit_AddKeeper_NewCloudName = function(event) {
    FLYFI.onClickCreate_AddKeeper(event);
    return false;
}

FLYFI.onClick_AddKeeper = function() {
    // clicking outside a pop-up should cause it to close
    FLYFI.removeIt('#addKeeper_dialog_clouds'); 
}


FLYFI.onClickTargetCloud_AddKeeper = function(event) {
    // User clicked on target cloud - Toggle the dropdown
    if ($('#addKeeper_dialog_clouds li').length == 0) {
        FLYFI.removeIt('#addKeeper_dialog_clouds');
    } else {
        FLYFI.toggleRemoveIt('#addKeeper_dialog_clouds');
    }
    return false;
}

function onCallback_AddKeeper_EnsureMyCloud(libraryDict) {
    _doAddKeeper(libraryDict.id);
    $.modal.close();
}

FLYFI.onClickCreate_AddKeeper = function() {
    var cloudNameField = $('#addKeeper_dialog_NewCloudName');
    var cloudName = cloudNameField.val();
    FLYFI.ensureMyCloud(cloudName, onCallback_AddKeeper_EnsureMyCloud);
}

FLYFI.onClickOK_AddKeeper = function() {
    if (addDialog_targetCloudID == null) {
        alert('Please choose cloud or click the Create button');
        return;
    }
    _doAddKeeper(addDialog_targetCloudID);
    $.modal.close();
}

function _doAddKeeper(libraryID) {
    FLYFI.server_voteUp(addDialog_track, libraryID);
    FLYFI.my_currentLibraryDict = FLYFI.findMyLibraryDict(libraryID);
    addDialog_track.vote = 1;
    FLYFI.tracksByID(addDialog_track.id).addClass('votedup').removeClass('voteddown');
}

(function($) {

    // Playlists  
    $.make_player = function(track, rank, settings) {
        settings = $.extend({
            keep_button: true,
            voteup_button: true,
            votedown_button: true,
            artist_url_button: false,
            album_url_button: false
        }, settings);
        
        var voted = (track.vote != null) ? (track.vote == 0 ? " voteddown" : " votedup") : "";
        var free = track.free ? " free" : " nonfree";
        var owned = track.owned ? " owned" : "";
        var blacklisted = track.blacklisted ? " blacklisted" : "";
        var trackIDclass = " track-" + track.id

        var trackHTMLArray = new Array;
        trackHTMLArray.push("<dt class=\"track" + trackIDclass + voted + free + owned + blacklisted + "\">");
        trackHTMLArray.push("   <div class=\"progress_bars\">");
        trackHTMLArray.push("       <div class=\"load_progress\"></div>");
        trackHTMLArray.push("       <div class=\"play_progress\"></div>");
        trackHTMLArray.push("       <span class=\"rank\">" + rank + ". </span>");
        trackHTMLArray.push("       <span class=\"artist\">" + track.artist + "</span>");
        trackHTMLArray.push("       <span class=\"title\">" + track.title + "</span>");
        trackHTMLArray.push("   <div class=\"scrub_thumb\" /></div>");
        trackHTMLArray.push("   <span class=\"track_btns\">");
        if (settings.keep_button && track.free) {
            trackHTMLArray.push("       <a class=\"keep_btn\" href=\"http://" + window.dev + "files.goombah.com/tracks/download/" + track.id +"/\">Keep</a>");
        }
        if (settings.votedown_button) {
            trackHTMLArray.push("       <a class=\"votedown_btn\" href=\"#\">Vote down</a>");
        }
        if (settings.voteup_button) {
            trackHTMLArray.push("       <a class=\"voteup_btn\" href=\"#\">Vote up</a>");
        }
        trackHTMLArray.push("       <a class=\"play_btn\" href=\"#\">Play</a>");
        trackHTMLArray.push("   </span>");
        trackHTMLArray.push("</dt>");

        if (settings.artist_url_button) {
            // NYI track_btns.append('<li class="artistlink_btn"><a href="' + track.artistURL + '" /></li>');
        }
        if (settings.album_url_button) {
            // NYI  track_btns.append('<li class="albumlink_btn"><a href="' + track.albumURL + '" /></li>');
        }

        var widget = $(trackHTMLArray.join("\n"));
        return widget;
    }

    // Append a track to the playlist.
    $.fn.playlist_append_track = function(list, track, rank) {
        settings = {
            keep_button: true,
            voteup_button: true,
            votedown_button: true,
            artist_url_button: false,
            album_url_button: false
        };
        list.append($.make_player(track, rank, settings));
        var row = list.children().slice(-1);
        row.attr("napster_url", track.napster_url);
        row.attr("buy_url", track.buy_url);
        
        row.mouseover(function() { $(this).addClass('over'); })
            .mouseout(function(event) { $(this).removeClass('over'); })
            .mousedown(onMouseDown_Row)
            .mousemove(onMouseMove_Row)
            .mouseup(onMouseUp_Row)
        
            .bind(FLYFI.MSG_Select, function() {
                $(window).trigger(FLYFI.MSG_TrackSelected, [track, list]);
            })
            .bind(FLYFI.MSG_Play, function() { 
                $(this).scrollToShowRow($(this));
                if (track.free) {
                    onPlay($(this), track); 
                    FLYFI.server_ReportPlay(track.id, true);
                } else {
                    onPlayNotFree($(this), track);
                }
            })
            .bind(FLYFI.MSG_Pause, function() {
                FLYFI.playingTrack.pause();
                FLYFI.tracksByID(FLYFI.playingTrack.trackID).removeClass('play');
                setClickedRow(row);
                $(window).trigger(FLYFI.MSG_TrackPaused, [track, list]);
            })
            .bind(FLYFI.MSG_VoteUp, function() { onVoteUp_Row(row, track); } )
            .bind(FLYFI.MSG_VoteDown, function() {
                var trackID = FLYFI.playingTrack.trackID;
                if (trackID == track.id) {
                    FLYFI.playingTrack.stop();
                    $(this).parents('.tracklist').playlist_next(true);
                }
                track.vote = 0;
                FLYFI.tracksByID(track.id).addClass('voteddown').removeClass('votedup');
                FLYFI.server_voteDown(track);
            })
            .bind(FLYFI.MSG_Unvote, function() {
                track.vote = null;
                FLYFI.tracksByID(track.id).removeClass('voteddown').removeClass('votedup');
                FLYFI.server_unvote(track);
            })
            .bind(FLYFI.MSG_Stop, function() {
                FLYFI.playingTrack.stop();
                removeDeferredRows();
            });

        row.find('.voteup_btn').
            click(function(event) {
                    if (track.vote == 1) {
                        $(this).parents('.track').trigger(FLYFI.MSG_Unvote);
                    } else {
                        $(this).parents('.track').trigger(FLYFI.MSG_VoteUp);
                    }
                    return false;
                })
            .mousedown(ignoreEvent) // don't scrub on click in button
            .mouseup(ignoreEvent);
        
        row.find('.votedown_btn').
            click(function(event) {
                    if (track.vote == 0 || track.blacklisted) {
                        $(this).parents('.track').trigger(FLYFI.MSG_Unvote);
                    }  else {
                        $(this).parents('.track').trigger(FLYFI.MSG_VoteDown);
                    }
                    return false;
                })
            .mousedown(ignoreEvent) // don't scrub on click in button
            .mouseup(ignoreEvent);
        
        row.find('.keep_btn')
            .click(function(event) {
                    FLYFI.tracksByID(track.id).parents('.track').addClass('downloaded');
                    event.stopPropagation(); // allow the default event, which is the download
                })
            .mousedown(ignoreEvent) // don't scrub on click in button
            .mouseup(ignoreEvent);
        
        row.find('.play_btn')
            .click(function(event) {
                    var row = $(this).parents('.track');
                    if (track.free) {
                        if (row.hasClass('play')) {
                            row.trigger(FLYFI.MSG_Pause);
                        } else {
                            row.trigger(FLYFI.MSG_Play);
                        }
                    } else { 
                        FLYFI.openNapsterWindow(track.napster_url);
                        FLYFI.server_ReportPlay(track.id, false);
                    }
                    return false;
                })
            .mousedown(ignoreEvent) // don't scrub on click in button
            .mouseup(ignoreEvent);

                
        row.find('.artistlink_btn').click(function(event) {
            return false;
        });
        row.find('.albumlink_btn').click(function(event) {
            return false;
        });
    }

    $.fn.doMakePlaylist = function(tracks, startOffset) {
        // Create the a playlist in the current element with track players associated with the given tracks.
        if (FLYFI.isCurrentList(this.id)) {
            this.find('.track.on').trigger(FLYFI.MSG_Stop);
        }
        this.empty();
        if (tracks) {
            var self = this;
            $.each(tracks, function(i) { $(self).playlist_append_track(self, this, startOffset+1+i); });
        }
        FLYFI.playingTrack.updateDisplay();
        return this;
    }

    $.fn.makePlaylist = function(tracks) {
        return this.doMakePlaylist(tracks, 0, true);
    }
    
    $.fn.makeKeepersPlaylist = function(tracks, startOffset) {
        return this.doMakePlaylist(tracks, startOffset, !FLYFI.isCustomRadioPlayer()); // custom radio allows sorting of keepers, so don't scrub
    }
    
    $.fn.seedPlaylist = function(tracks, startOffset) {
        return this.doMakePlaylist(tracks, startOffset, true);
    }

    $.fn.hasPlayableTracks = function() {
        return this.find('.track:not(.voteddown):not(.nonfree)').length > 0;
    }
    
    $.fn.playlist_first = function(playIt) {
        // Play the first track.
        var next = this.find('.track:not(.voteddown):not(.nonfree)').eq(0);
        if (next.length > 0) {
            if (playIt) {
                next.trigger(FLYFI.MSG_Play);
            } else {
                next.trigger(FLYFI.MSG_Select);
            }
        } else {
            this.playlist_firstInNextList(playIt);
        }
    }
    
    $.fn.playlist_firstInNextList = function(playIt) {
        var last = this;
        while (true) {
            var next = nextTrackList(last);
            if ((next == this) && (!this.hasPlayableTracks())) {
                return;  // came around to same list with no playable tracks, so do nothing
            }
            
            if (next.hasPlayableTracks()) {
                if ((next == this) && (next.find('.track:not(.voteddown):not(.nonfree)').length == 1)) {
                    return;  // came around to same list with only this track, so do nothing
                }
                next.playlist_first(playIt);
                return;
            } else {
                if (next == this) {
                    return;  // came around to same list with nothing to do, so do nothing
                }
                last = next;
            }
        }
    }

    $.fn.playlist_last = function(playIt) {
        // Play the last track.
        var tracks = this.find('.track:not(.voteddown):not(.nonfree)');
        var next = tracks.eq(tracks.length-1);
        if (next.length > 0) {
            if (playIt) {
                next.trigger(FLYFI.MSG_Play);
            } else {
                next.trigger(FLYFI.MSG_Select);
            }
        } else {
            this.playlist_lastInPrevList(playIt);
        }
    }
        
    $.fn.playlist_lastInPrevList = function (playIt) {
        var last = this;
        while (true) {
            var next = prevTrackList(last);
            if ((next == this) && (!this.hasPlayableTracks())) {
                return;  // came around to same list with no playable tracks, so do nothing
            }
            
            if (next.hasPlayableTracks()) {
                if ((next == this) && (next.find('.track:not(.voteddown):not(.nonfree)').length == 1)) {
                    return;  // came around to same list with only this track, so do nothing
                }
                next.playlist_last(playIt);
                return;
            } else {
                if (next == this) {
                    return;  // came around to same list with nothing to do, so do nothing
                }
                last = next;
            }
        }
    }

    $.fn.playlist_next = function(playIt) {
        // play the next playable track (if none, go to next non-playable)
        var current = this.find('.track.on');
        if (current.length == 0) {
            this.playlist_first(playIt);
            return;
        }
        
        var next = current.nextAll('.track:not(.voteddown):not(.nonfree)').eq(0);
        if (next.length > 0) {
            if (playIt) {
                next.trigger(FLYFI.MSG_Play);
            } else {
                next.trigger(FLYFI.MSG_Select);
            }
        } else {
            this.playlist_firstInNextList(playIt);
        }
    }
    
    $.fn.playlist_prev = function(playIt) {
        // Skip to the previous track.
        var current = $(this).find('.track.on');
        if (current.length == 0) {
            this.playlist_last(playIt);
            return;
        }
        
        var prev = current.prevAll('.track:not(.voteddown):not(.nonfree)').eq(0);
        if (prev.length > 0) {
            prev.trigger(FLYFI.MSG_Play);
        } else {
            this.playlist_lastInPrevList(playIt);
        }
    }
  
    // Scroll the given player into view in the playlist.
    $.fn.scrollToShowRow = function(row) {
        if (row.length == 0) {
            return; // track may not be in this list
        }
        var rowItem = row[0];
        var scroller = FLYFI.getScroller(this);
        if (!scroller) return;
        
        var extraToShow = 35;
        var rowTopInScroller = FLYFI.getOffsetTopIn(scroller, rowItem);
        if (scroller.scrollTop > rowTopInScroller) { // track is above the top of the visible area
            scroller.scrollTop = Math.max(0, rowTopInScroller - extraToShow);
        } else if (scroller.scrollTop + scroller.clientHeight < rowTopInScroller + rowItem.offsetHeight) {  // track is below the bottom of the visible area
            scroller.scrollTop = Math.min(scroller.scrollHeight, rowTopInScroller + rowItem.offsetHeight + extraToShow) 
                                    - scroller.clientHeight;
        }
    }
    
    $.fn.findRowForTrackID = function(trackID) {
        return this.find('.track-' + trackID);
    }
    
    $.fn.scrollToRowForTrackID = function(trackID) {
        this.scrollToShowRow(this.findRowForTrackID(trackID));
    }
    
    $.fn.removeTrack = function(trackID) {
        var row = $(this).find('.track-' + trackID);
        if (row.hasClass('play')) { // delay removal until the track stops playing
            removeDeferred.push(row);
        } else {
            row.remove();
            this.updateRanks();
        }
    }

    $.fn.updateRanks = function() {
        var tracks = $(this).find('.track');
        for (var i = 0; i < tracks.length; ++i) {
            tracks.eq(i).find('.rank').text(i+1);
        }
    }

})(jQuery);

function removeDeferredRows() {
    for (var i=0; i < removeDeferred.length; ++i) {
        var row = removeDeferred[i];
        var tracklist = $(row).parents('.tracklist');
        if (tracklist.length > 0) {
            row.remove();
            tracklist.updateRanks();
        }
    }
    removeDeferred.splice(0, removeDeferred.length);
}

// Sound

FLYFI.onSoundFinished = function(event, trackID) {
    $('.track').find('.play_progress').css('width', 0).removeClass('play');
    if (FLYFI.atMyPage()) {
        FLYFI.addToKeepers(trackID);
    }
    if (FLYFI.current_tracklist != null) {
        FLYFI.current_tracklist.playlist_next(true);
    }
}

FLYFI.onSoundStopped = function(event, trackID) {
    $('.track').find('.play_progress').css('width', 0).removeClass('play').removeClass('on');
    $(window).trigger(FLYFI.MSG_TrackStopped);
}

FLYFI.onMoreInfoTracksUpdate_Playlist = function() {
    FLYFI.playingTrack.updateDisplay();
}

$(function() { // Document is ready
    // Lists that may be shown late (after the playlist has already started playing the track)
    // need to be updated again
    $(window)
        .bind(FLYFI.MSG_MoreInfoTracksUpdated, FLYFI.onMoreInfoTracksUpdate_Playlist)
        
        .bind(FLYFI.MSG_SoundFinished, FLYFI.onSoundFinished)
        .bind(FLYFI.MSG_SoundStopped, FLYFI.onSoundStopped);
        
    $('#addKeeper_dialog_targetCloudDiv').click(FLYFI.onClickTargetCloud_AddKeeper);
    $('#addKeeper_dialog_OK').click(FLYFI.onClickOK_AddKeeper);
    $('#addKeeper_dialog_Create').click(FLYFI.onClickCreate_AddKeeper);
    $('#addKeeper_dialog_Cancel').click(FLYFI.onClickCancel_AddKeeper);
    $('#addKeeper_dialog_NewCloudNameForm').submit(FLYFI.onSubmit_AddKeeper_NewCloudName);
    $('#addKeeper_dialog').click(FLYFI.onClick_AddKeeper);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/taste_based_content_list.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */
 
FLYFI.waitingForServer_TBC = false;

FLYFI.setTBCLoading = function() {
    if (FLYFI.waitingForServer_TBC) {
        FLYFI.showIt('.broadcasts .loading');
    } else {
        FLYFI.hideIt('.broadcasts .loading');
    }
}

FLYFI.onServer_TasteBasedContent = function(data) {
    FLYFI.waitingForServer_TBC = false;
    FLYFI.setTBCLoading();
    
    var startInData = 0;
    var articleTiles = $('.broadcasts .taste_based_content.article');
    var articleCount = 0;
    for (var i = 0; i < articleTiles.length; i++) {
        var tile = articleTiles.eq(i);
        var content = data[startInData + i]
        tile.html(content);
        if (content != '') {
            articleCount += 1;
            tile.find('.mp3').jmp3();
        }
    }
    if (articleCount > 0) {
        FLYFI.showIt('.broadcasts .tbc_articles');
    } else {
        FLYFI.removeIt('.broadcasts .tbc_articles');
    }

    startInData += articleTiles.length;
    var bannerTiles = $('.broadcasts .taste_based_content.banner');
    var bannerCount = 0;
    for (var i = 0; i < bannerTiles.length; i++) {
        var tile = bannerTiles.eq(i);
        var content = data[startInData + i]
        tile.html(content);
        if (content != '') {
            bannerCount += 1;
            tile.find('.mp3').jmp3();
        }
    }
    if (bannerCount > 1) {
        FLYFI.showIt('.broadcasts .taste_based_content.banner');
    } else if (bannerCount == 1) {
        FLYFI.showIt('.broadcasts .taste_based_content.banner.one');
        FLYFI.removeIt('.broadcasts .taste_based_content.banner.two');
    } else {
        FLYFI.removeIt('.broadcasts .taste_based_content.banner');
    }

    startInData += bannerTiles.length;    
    var eventTiles = $('.broadcasts .taste_based_content.event');
    var eventCount = 0;
    for (var i = 0; i < eventTiles.length; i++) {
        var tile = eventTiles.eq(i);
        var content = data[startInData + i]
        tile.html(content);
        if (content != '') {
            eventCount += 1;
            tile.find('.mp3').jmp3();
        }
    }

    startInData += eventTiles.length;  
    var newReleaseTiles = $('.broadcasts .taste_based_content.new_release');
    var newReleaseCount = 0;
    for (var i = 0; i < newReleaseTiles.length; i++) {
        var tile = newReleaseTiles.eq(i);
        var content = data[startInData + i]
        tile.html(content);
        if (content != '') {
            newReleaseCount += 1;
            tile.find('.mp3').jmp3();
        }
    }
    if (newReleaseCount > 1) {
        FLYFI.showIt('.broadcasts .taste_based_content.new_release');
    } else if (bannerCount == 1) {
        FLYFI.showIt('.broadcasts .taste_based_content.new_release.one');
        FLYFI.removeIt('.broadcasts .taste_based_content.new_release.two');
    } else {
        FLYFI.removeIt('.broadcasts .taste_based_content.new_release');
    }
    
    addReflections();
}
FLYFI.onServerError_TasteBasedContent = function(request, textStatus, errorThrown) {
    FLYFI.waitingForServer_TBC = true;
    FLYFI.setTBCLoading();
    
    FLYFI.showJSONError(request, textStatus, errorThrown);
}

// Fill all of the TBC tiles
FLYFI.getTBCIfCurrentLibrary = function() {
    if (!FLYFI.current_library) {
        return;
    }
    FLYFI.getTBC();
}

FLYFI.getTBC = function() {
    var libraryID = 'none';
    if (FLYFI.current_library) {
	    libraryID = FLYFI.current_library.id;
	}
    FLYFI.getTBCForLibrary(libraryID);
}

FLYFI.getTBCForLibrary = function(libraryID) {
    var articleCount = $('.broadcasts .taste_based_content.article').length;
    var bannerCount = $('.broadcasts .taste_based_content.banner').length;
    var eventCount = $('.broadcasts .taste_based_content.event').length;
    var newReleaseCount = $('.broadcasts .taste_based_content.new_release').length;
    var types = new Array;
    for (var i = 0; i < articleCount; ++i) {
        types.push('A');
    }
    for (var i = 0; i < bannerCount; ++i) {
        types.push('B');
    }
    for (var i = 0; i < eventCount; ++i) {
        types.push('E');
    }
    for (var i = 0; i < newReleaseCount; ++i) {
        types.push('N');
    }
    if (types.length == 0) {
        return; // nothing to do
    }
    var typeString = types.join('');
    
	var url = '/' + window.level + '/library/' + libraryID + '/json/taste_based_content/bytype/' + typeString + '/';
    
    FLYFI.waitingForServer_TBC = true;
    FLYFI.setTBCLoading();
	FLYFI.getJSON(url, FLYFI.onServer_TasteBasedContent, FLYFI.onServerError_TasteBasedContent);
}

$(document).ready(function() {
    $(window)
        .bind(FLYFI.MSG_ColdStart, FLYFI.getTBC)
        .bind(FLYFI.MSG_CoolStart, FLYFI.getTBC)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.getTBCIfCurrentLibrary)
        .bind(FLYFI.MSG_TrackAddedToKeepers, FLYFI.getTBC)
        .bind(FLYFI.MSG_UserRequestedNewRecs, FLYFI.getTBCIfCurrentLibrary);
});

/* SOURCE LINK: <script type="text/javascript" language="javascript" src="/static/{{ level }}/js/player/player.js"></script> */
/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// page can pass parameters to indicate how we start:
// window.autoplayTrackId - the id of the track to start playing (should be in the initial list)
// window.coolStartIfNoLibrary - show the coolstart dialog if there is nothing else to show
// window.allfree - true if we are showing the All Free Mp3s page
// window.dev - 'dev' or '' indicating whether we are running in development
// window.editCloudName - true if the cloud name needs editing (maybe for a new library?)
// window.initial_gfm_genre_id - the id of the initial GFM genre to show in the seeds 
// window.initial_gfm_genre_name - the name of the initial GFM genre to show in the seeds 
// window.initial_library_id - the initial library to show in the seeds (overrides window.initial_gfm_genre_id if both specified)
// window.level - the dev/demo/live level to use in URLs
// window.json_logged_participant - the initial data for /auth/json/logged_participant/ (so we don't need to make the extra call)
// window.subnav - the page being shown
// window.target_participant_id - the id of the participant whose libraries are to be browsed
// window.target_participant_nickname - the nickname of the participant whose libraries are to be browsed

FLYFI.initialCloudShown = false; // false until we have a chance to load the cloud library
FLYFI.playerStartingUp = true;    // true until the initial display is shown - NYI: combine with initialLibraryShown?
FLYFI.initialLibraryShown = false; // false until we have a chance to load the initial library

FLYFI.current_tracklist = null; // used to track where the play-next and play-prev buttons go

// What Player?

FLYFI.isGFMPlayer = function() {
    return $('body').hasClass('gfm');
}

FLYFI.isNoRecsPlayer = function() {
    return $('body').hasClass('norecs');
}    

FLYFI.isCustomRadioPlayer = function() {
    return $('body').attr('id') == 'custom_radio';
}

FLYFI.atHome = function() {
    return $('body').hasClass('home');
}

FLYFI.atMyPage = function() {
    // is the user viewing his or her own clouds?
    return ((FLYFI.current_user || window.coolStartIfNoLibrary) &&
            (!window.target_participant_id || window.target_participant_id == FLYFI.current_user.id) && 
            !FLYFI.isNoRecsPlayer() && 
            !FLYFI.isCustomRadioPlayer());
}

// Panes

FLYFI.onClick_TogglePlayerOpen = function() {
    // click on the Toggle Player button
    if ($('#player_shell_shell').hasClass('playerOpen')) {
        $('#player_shell_shell').removeClass('playerOpen').addClass('playerClosed');    
        FLYFI.closeInfoPane(); // close the More Info pane, too, so when we show a dialog or whatever it is hidden
    } else {
        $('#player_shell_shell').removeClass('playerClosed').addClass('playerOpen');    
    }
}

FLYFI.onClick_Body = function() {
    // clicking outside a pop-up should cause it to close
    FLYFI.removeIt('#seed_menu_choices');
    FLYFI.removeIt('#stations'); 
}

FLYFI.showRecsPane = function() {
    // user clicked on the free recs tab
    FLYFI.newContext();
    
    $('.panetab').removeClass('on');
    $('#recs_tab').addClass('on');

    FLYFI.removeIt('#seed_pane');
    FLYFI.showIt('#tabs .tracklist_header');
    FLYFI.showIt('#seed_menu');
    FLYFI.removeIt('#free_recs_pane'); // NYI - remove once we are happy with one recs list
    FLYFI.removeIt('#recs_pane .tracklist_header'); // NYI - remove once we are happy with one recs list - only needed for the spinner
    FLYFI.showIt('#recs_pane');
    FLYFI.showIt('#panes');
}

FLYFI.showSeedTab = function() {
    FLYFI.newContext();
    
    $('.panetab').removeClass('on');
    $('#seed_tab').addClass('on');

    FLYFI.removeIt('#recs_pane');
    FLYFI.removeIt('#tabs .tracklist_header');
    FLYFI.removeIt('#recs_pane .tracklist_header');
    FLYFI.showIt('#seed_menu');
    FLYFI.showIt('#seed_pane');
    FLYFI.showIt('#panes');
}

FLYFI.newContext = function() {
    if (FLYFI.current_library || FLYFI.haveInitialLibrary()) {
        FLYFI.clearColdStart();
        FLYFI.hide_dialogs();
        return;
    }
}

FLYFI.hide_dialogs = function() {
    // Hide all of the dialogs
    if (window.editCloudName) {
        return; // this dialog is forced to be shown, so don't hide it
    }
    
    FLYFI.removeIt('#dialogs'); // No JQuery slide - it sets display: none
    $('#cloud_buttons').children().removeClass('on');
}


// Library State

FLYFI.onLoginUpdated_Player = function() {
    if (FLYFI.playerStartingUp) {
    
        if (window.target_participant_id) {
            FLYFI.updateFromServer_CloudList(window.target_participant_id, window.target_participant_nickname, window.initial_library_id);
        
        } else if (window.allfree) {
            var libraryID = 0;
            if (window.initial_library_id) {
                libraryID = window.initial_library_id;
            }
            FLYFI.updateFromServer_FreeMusicCloudList(libraryID);
            
        } else if (FLYFI.haveInitialLibrary() && !FLYFI.initialLibraryShown) {
            FLYFI.updateFromServer_MyCloudList(false, FLYFI.showInitialLibrary, null, false);
            
        } else if (!FLYFI.haveInitialLibrary() && !FLYFI.isNoRecsPlayer() && FLYFI.needColdStart()) {
            FLYFI.show_cold_start();
            
        } else { // 'Normal' start-up
            FLYFI.updateFromServer_MyCloudList(true, null, null, false);
            
            // NYI - this should be going away
            if (!FLYFI.isCustomRadioPlayer()) {
                if (FLYFI.isGFMPlayer()) {
                    FLYFI.showGFM_DefaultGenre();
                } 
                FLYFI.showRecsPane();
            }
        } 
    } else if (FLYFI.atMyPage()) {
        FLYFI.updateFromServer_MyCloudList(true);
    }

    FLYFI.playerStartingUp = false;
}

FLYFI.haveInitialLibrary = function() {
    return (window.initial_library_id || (window.initial_gfm_genre_id != null));
}

FLYFI.showInitialLibrary = function() {
    FLYFI.select_library_by_id(window.initial_library_id);
    FLYFI.initialLibraryShown = true;
}

FLYFI.onInitialLibrary_Player = function(event, libraryID) {
    if (window.autoplayTrackId && FLYFI.current_library && (FLYFI.current_library.id == libraryID)) {
        $('#playlist').findRowForTrackID(window.autoplayTrackId).mousedown().mouseup();
        window.autoplayTrackId = null;
    }
}

FLYFI.onLibrarySelected_Player = function(event) {
    if (!FLYFI.initialCloudShown && window.editCloudName) {
        FLYFI.keepers_updated();
        FLYFI.onClick_EditCloudMenuItem();
    }
    FLYFI.initialCloudShown = true;
}

// Cold start

FLYFI.needColdStart = function() {
    // Cold Start is when the user has NEVER been here before - save that data in a cookie
    var COOKIE_playerRan = 'playerRan';

    if (!window.coolStartIfNoLibrary || readCookie(COOKIE_playerRan)) {
        return false;
    } 
    
    createCookie(COOKIE_playerRan, 1, 10*365); // good for ten years
    return true;
}

FLYFI.setColdStart = function() {
    $('body').removeClass('coldStartOff').removeClass('coldStartOff_nolib').addClass('coldStartOn');
}

FLYFI.setCoolStart = function() {
    $('body').removeClass('coldStartOff').removeClass('coldStartOn').addClass('coldStartOff_nolib');
}

FLYFI.clearColdStart = function() {
    $('body').removeClass('coldStartOn').removeClass('coldStartOff_nolib').addClass('coldStartOff');
}

FLYFI.inColdStart = function() {
    return $('body').hasClass('coldStartOn');
}

FLYFI.show_cold_start = function() {
    $('#new_cloud_name').val('');
    FLYFI.setColdStart();
    FLYFI.update_prefab_stations('#coldstart_prefabs');
    $('#new_artists_field').val('').focus();
    $(window).trigger(FLYFI.MSG_ColdStart);
}

// Track list

FLYFI.currentTrackList = function() {
    // return the tracklist that is currently visible in the player
    if (FLYFI.current_tracklist) {
        return FLYFI.current_tracklist;
    } else if (FLYFI.haveKeepers()) {
        return $('#playlist'); // no current list - go first to keepers if there are any
    } else { // next try the visible pane lists
        var visible_tracklists = $("#panes.here .tracklist");
        for (var i = 0; i < visible_tracklists.length; i++) {
            var tracklist = visible_tracklists.eq(i);
            if (tracklist.find('.track').length > 0) {
                return tracklist;
            }
        }
    }
    return null; // not set up yet
}

FLYFI.isCurrentList = function(trackListID) {
    var currentList = FLYFI.currentTrackList();
    if (! currentList) {
        return false;
    } 
    return (currentList[0].id == trackListID);
}

FLYFI.nextTrackList = function(currentList) {
    // return the tracklist that should play next
    var currentID = currentList[0].id;
    if (currentID == 'playlist') {
        if ($('#recs_tab').hasClass('on')) {
            return $('#free_recs_list');
        } else {
            return $('#seed_track_list');
        }
    } else if (currentID == 'free_recs_list') {
        return $('#all_recs_list');
    } else if ((currentID == 'all_recs_list') || (currentID == 'seed_track_list')) {
        return $('#playlist');
    } else if (currentID == 'more_by_free_tracklist') {
        return $('#more_by_not_free_tracklist');
    } else if (currentID == 'more_by_not_free_tracklist') {
        return $('#playlist'); // after more-info lists, go back to keepers
    } else {
        return currentList; // don't leave the track list
    }
}

FLYFI.prevTrackList = function(currentList) {
    // return the tracklist that should play next
    var currentID = currentList[0].id;
    if (currentID == 'playlist') {
        if ($('#recs_tab').hasClass('on')) {
            return $('#all_recs_list');
        } else {
            return $('#seed_track_list');
        }
    } else if ((currentID == 'free_recs_list') || (currentID == 'seed_track_list')) {
        return $('#playlist');
    } else if (currentID == 'all_recs_list') {
        return $('#free_recs_list');
    } else if (currentID == 'more_by_free_tracklist') {
        return $('#playlist'); // after more-info lists, go back to keepers
    } else if (currentID == 'more_by_not_free_tracklist') {
        return $('#more_by_free_tracklist'); // after more-info lists, go back to keepers
    } else {
        return currentList; // don't leave the track list
    }
}

// Track state

FLYFI.onTrackSelected_Player = function(event, track, tracklist) { 
    FLYFI.current_tracklist = tracklist;
    if (track) {
        $('#player_controls').addClass('on');
        $('.buy_btn a').attr('href', track.buy_url);
    } else {
        $('#player_controls').removeClass('on');
    }
}

FLYFI.onTrackLoading_Player = function(event, row) { 
    $('#now_playing label').text('Loading:');
    FLYFI.now_playing_update(row);
}

FLYFI.onTrackPlaying_Player = function(event, row) { 
    $('#now_playing label').text('Playing:');
    FLYFI.now_playing_update(row);
    $('#player_controls').addClass('on');
}

FLYFI.onTrackBeingViewed_Player = function(event, row) { 
    $('#now_playing label').text('Viewing:');
    FLYFI.now_playing_update(row);
}

FLYFI.onTrackResumed_Player = function(event, track, tracklist) { 
    $('#player_controls').addClass('on');
}

FLYFI.onTrackPaused_Player = function(event, track, tracklist) { 
    $('#player_controls').removeClass('on');
}

// Player controls

FLYFI.onClick_PlayerControls_PlayButton = function() {
    // Search for the track that's currently playing.
    if (FLYFI.current_tracklist && FLYFI.playingTrack.trackID) {
        row = FLYFI.current_tracklist.findRowForTrackID(FLYFI.playingTrack.trackID);
        if (row.length > 0) {
            row.find('.play_btn').click();
        } else { // may have changed libraries
            var tracklists = $(".tracklist");
            rows = tracklists.findRowForTrackID(FLYFI.playingTrack.trackID);
            if (rows.length > 0) { // play it somewhere else
                rows.eq(0).find('.play_btn').click();
            } else { // not on any visible lists
                FLYFI.playingTrack.pause(); // turn off the sound
                FLYFI.now_playing_clear();
            }
        }
        return;
    }
    
    // Didn't find a playing track. Play the first track we can find.
    var tracklist = FLYFI.currentTrackList();
    if (tracklist) {
        tracklist.playlist_first(true);
    }
}

FLYFI.onMouseOver_PlayerControls_PlayButton = function() {
    $('#player_shell_shell').addClass('napsterHover');    
}

FLYFI.onMouseOut_PlayerControls_PlayButton = function() {
    $('#player_shell_shell').removeClass('napsterHover');    
}

FLYFI.onClick_PlayerControls_BackButton = function() {
    // Back button clicked.
    var tracklist = FLYFI.currentTrackList();
    if (tracklist) {
        tracklist.playlist_prev(true);
    }
}

FLYFI.onClick_PlayerControls_NextButton = function() {
    // Next button clicked.
    var tracklist = FLYFI.currentTrackList();
    if (tracklist) {
        tracklist.playlist_next(true);
    }
}

FLYFI.onClick_PlayerControls_BuyButton = function(event) {
    // Buy button clicked.
    var url = $('.buy_btn a').eq(0).attr('href');
    if (url) {
        window.open(url, 'PlayerWin', 
                'width=670,height=488,menubar=yes,location=yes,resizable=yes,resizable=yes,scrollbars=yes,status=yes');
    }
    event.preventDefault();
}

// Now Playing

FLYFI.now_playing_update = function(row) {
    $('#now_playing .artist').text($(row).find('.artist').text());
    $('#now_playing .title').text($(row).find('.title').text());
}

FLYFI.now_playing_clear = function() {
    $('#now_playing').find('label,.artist,.title').empty();
    $('#player_controls').removeClass('on');
}

$(function() { // On document ready

    // Prevent default behaviour of links with a href="#" attribute.
    $('a[href="#"]').click(
                        function(event) { 
                            event.preventDefault(); 
                        });

    $('body').click(FLYFI.onClick_Body);
    
    $('#shrink_player_toggle').click(FLYFI.onClick_TogglePlayerOpen);
    $('#player_controls .play_btn').mouseover(FLYFI.onMouseOver_PlayerControls_PlayButton);
    $('#player_controls .play_btn').mouseout(FLYFI.onMouseOut_PlayerControls_PlayButton);
    $('#player_controls .play_btn').click(FLYFI.onClick_PlayerControls_PlayButton);
    $('#player_controls .back_btn').click(FLYFI.onClick_PlayerControls_BackButton);
    $('#player_controls .next_btn').click(FLYFI.onClick_PlayerControls_NextButton);
    $('#player_controls .buy_btn').click(FLYFI.onClick_PlayerControls_BuyButton);
    
    $('#recs_tab').click(FLYFI.showRecsPane);
    $('#seed_tab').click(FLYFI.onClick_SeedMenuTrigger); // clicking on tab is same as clicking on trigger
    
    $(window)
        .bind(FLYFI.MSG_LoginUpdated, FLYFI.onLoginUpdated_Player)
        .bind(FLYFI.MSG_InitialLibrary, FLYFI.onInitialLibrary_Player)
        .bind(FLYFI.MSG_LibrarySelected, FLYFI.onLibrarySelected_Player)
        
        .bind(FLYFI.MSG_TrackSelected, FLYFI.onTrackSelected_Player)
        .bind(FLYFI.MSG_TrackLoading, FLYFI.onTrackLoading_Player)
        .bind(FLYFI.MSG_TrackPlaying, FLYFI.onTrackPlaying_Player)
        .bind(FLYFI.MSG_TrackBeingViewed, FLYFI.onTrackBeingViewed_Player)
        .bind(FLYFI.MSG_TrackResumed, FLYFI.onTrackResumed_Player)
        .bind(FLYFI.MSG_TrackPaused, FLYFI.onTrackPaused_Player)
        .bind(FLYFI.MSG_TrackStopped, FLYFI.now_playing_clear);
        
            
    if (FLYFI.isCustomRadioPlayer()) {
        $('#playlist').addClass('noScrub');
        FLYFI.showIt('#seed_tab');
    }
    $(window).trigger(FLYFI.MSG_Start); // ready to roll
});



