/**
 * Todo:
 *  - Bug when switching between calendar and works (with subsections open)
 * 
 * 
 */


var Klangatang = function() {
	
	this.iLastResize = true;
	this.oResizeCheckInterval = false;
	this.bWorksClicked = false;
	this.bCalendarClicked = false;
	this.bAboutFoldClicked = false;
	this.sActiveWorkSection = false;
	this.bNoLoadPrograms = false;
	this.bNoLoadComposers = false;
	this.bNoLoadPieces = false;
	this.bNoAutoLoadCalendar = false;
	this.aColors = new Array('purple','mint','blue','yellow');
	this.iActiveColor = -1;
	this.bAllowHashParse = true;
	this.sActiveComposerLet = false;
	this.sActivePieceLet = false;
	this.sActiveProgramLet = false;
	this.oScrollUp = false;
	this.oScrollDown = false;
	this.oJukebox = false;
	this.aTracks = false;
	this.bInitJukebox = false;
	this.bAllowHashSet = true;
	this.bAutoPlayJukebox = true;
	this.sColor = false; 
	this.sShortProgramSort = 'title';
	
	/**
	 * Klangatang constructor ;)
	 */
	this.construct = function() {
		
		
		
		var that=this;
		this.initColor();
		this.setMaxHeights();
		this.initScrollPane();
		
		this.sendScreenInfo();
		this.setupAjax();
		this.bindToFolds();
		this.bindToWorkSubfolds();
		this.bindToComposerLets();
		this.bindToPieceLets();
		this.bindToProgramLets();
		this.bindToCalendarLinks();
		this.bindToHashChange();
		// this.initFancyScroll();
		
		this.parseHash(true);
		this.initBackground(true);
		
		$(window).resize(function() {

			
			// Resizer
			that.iLastResize = that.microtime();
			
			if(!that.oResizeCheckInterval) {
				
				that.oResizeCheckInterval = window.setInterval( function() {
					iDiv = (that.microtime() - that.iLastResize);
					
					if( iDiv > 250) {
						
						that.fixSocial();
						that.sendScreenInfo();
						that.setMaxHeights();
						window.clearInterval(that.oResizeCheckInterval);
						that.oResizeCheckInterval = false;
						that.initBackground(false);
					}
				},50)
			}
			
		});

		
	},
	
	this.fixSocial = function() {
		var iWidth = parseInt( $('#col1').innerWidth())-40;
		var iPer = iWidth/6;
		$('#social img').css({width: iPer});
	},
	
	this.initBackground = function(bInit) {
		var sBackground = LINKROOT+'/images/frontend/'+this.sColor+'/bg.gif';

		var iImageWidth = 1920;
		var iImageHeight = 1200;

		var iWindowWidth = $(window).width();
		var iWindowHeight = $(window).height();

		var iOver = iImageWidth / iImageHeight;
		var iUnder = iImageHeight / iImageWidth;

		if( (iWindowWidth / iWindowHeight) >= iOver) {
			var iNewImgWidth = iWindowWidth;
			var iNewImgHeight = iUnder*iWindowWidth;
		} else {
			var iNewImgWidth = iOver*iWindowHeight;
			var iNewImgHeight = iWindowHeight;
		}

		// Diff
		iDiffWidth = (iNewImgWidth - iWindowWidth)/2;
		iDiffHeight = (iNewImgHeight - iWindowHeight)/2;

		iMarginLeft = iDiffWidth * -1;
		iMarginTop = iDiffHeight * -1;

		if(iMarginLeft > 0) {
			iMarginLeft = 0;	
		}

		if(iMarginTop > 0) {
			iMarginTop = 0;	
		}	
		

		if(bInit) {
			$('#bg').html('<img src="'+sBackground+'" id="backgroundimage" style="display:none" />');
			$('#backgroundimage').css({width: iNewImgWidth, height: iNewImgHeight, marginTop: iMarginTop, marginLeft: iMarginLeft}).fadeIn(4000);
		} else {
			$('#backgroundimage').css({width: iNewImgWidth, height: iNewImgHeight, marginTop: iMarginTop, marginLeft: iMarginLeft});
		}
		

	}





	function preLoad() {
		var sHtml = '';
		$.each(aBackgroundFiles, function(sKey,sValue) {
			
			sHtml += '<img src="'+LINKROOT+'/'+sValue+'" />';
		})
		
		
		
		$('#preload').html(sHtml);		
	}

	this.initFancyScroll = function() {
		var that=this;
		$('div.inner').each( function() {
			$('<a href="javascript:;" class="scroll scroll-up"><span>UP</span></a>').prependTo(this);
			$('<a href="javascript:;" class="scroll scroll-down"><span>DOWN</span></a>').appendTo(this);
		});
		
		$('a.scroll-down').mouseover( function() {
			var oBtn = this;
			
			var iCur = parseInt( $('div.target',$(this).parent()).css('marginTop'));
			var iAvail = $(this).parent().height();
			iPer = 20;
			var iNew = iCur-iPer;
			var iMax = ($('div.target',$(this).parent()).height() - iAvail + 50)* -1;
			
			if(iNew < iMax) {
				iNew = iMax;
			}
			
			$('div.target',$(this).parent()).css({marginTop: iNew});
			
			that.oScrollDown = setTimeout( function() {
				$(oBtn).mouseover();
			},75);
			
		});
		
		$('a.scroll-down').mouseout(function() {
			clearTimeout(that.oScrollDown);
		});
		
		$('a.scroll-up').mouseover( function() {
			var oBtn = this;
			
			var iCur = parseInt( $('div.target',$(this).parent()).css('marginTop'));
			var iAvail = $(this).parent().height();
			iPer = 20;
			var iNew = iCur+iPer;
			var iMax = 0;
			if(iNew > iMax) {
				iNew = iMax;
			}
			
			$('div.target',$(this).parent()).css({marginTop: iNew});
			
			that.oScrollUp = setTimeout( function() {
				$(oBtn).mouseover();
			},75);
			
		});
		
		$('a.scroll-up').mouseout(function() {
			clearTimeout(that.oScrollUp);
		});		
	}
	
	this.setHash = function(sHash) {
		if(!this.bAllowHashSet) {
			return;
		}
		var that=this;
		this.bAllowHashParse = false;
		
		document.location.href = sHash;
		
		setTimeout( function() {that.bAllowHashParse = true;},200);
		
	},
	
	this.parseHash = function(bOnLoad) {
		var that=this;
		
		if(this.bAllowHashParse) {
			sHash = window.location.hash.replace('#!','');
			aParts = sHash.split(':');
			
			switch(aParts[0]) {
			
				case 'subcontent':
					// @todo
				break;
				
				case 'jukebox':
					// @todo
				break;
				
				case 'news':
					// @todo
					break;
			
				case 'tweets':
					// @todo
					break;
					
				case 'nlsubok':
					this.getNewsletterContent('newsletter_subscribe_success');
					break;
				
				case 'nlsubfail':
					this.getNewsletterContent('newsletter_subscribe_fail');
					break;
					
				case 'nlunsubok':
					this.getNewsletterContent('newsletter_unsubscribe_success');
					break;
					
				case 'nlunsubfail':
					this.getNewsletterContent('newsletter_unsubscribe_fail');
					break;
					
					
				case 'newsletter':
					// @todo
					break;
					
				case 'spotlight':
					// @todo
					break;
					
			
				case 'content':
					if(!$('a[rel="getcontent:'+aParts[1]+'"]').hasClass('foldactive')) {
						$('a[rel="getcontent:'+aParts[1]+'"]').click();
					}					
					break;
					
				case 'calendar':
					if(aParts[1] == 0) {
					} else {
						that.bCalendarClicked = true;
						that.allowHashParse = false;
						if(!$('#calendarfold').hasClass('foldactive')) {
							that.showCalendar($("#calendarfold"));
						}
						that.loadCalendar(aParts[1]);
						that.allowHashParse = true;
					}
					break;
					
				case 'composer':
					that.bWorksClicked = true;
					if(!$('a#worksfold').hasClass('foldactive')) {
						$('a#worksfold').click();
					}
					$('#subfold_works a[rel="composers"]').click();
					$('a.composer-let[rel="'+aParts[1]+'"]').click();
					$('a.composer-name').removeClass('active');
					
					that.getComposer( aParts[2] );
					break;
					
				case 'piece':
					that.bWorksClicked = true;
					if(!$('a#worksfold').hasClass('foldactive')) {
						$('a#worksfold').click();
					}
					$('#subfold_works a[rel="pieces"]').click();
					$('a.piece-let[rel="'+aParts[1]+'"]').click();
					$('a.piece-name').removeClass('active');
					
					that.getPiece( aParts[2] );
					break;
					
				case 'program':
					that.bWorksClicked = true;
					if(!$('a#worksfold').hasClass('foldactive')) {
						$('a#worksfold').click();
					}
					$('#subfold_works a[rel="programs"]').click();
					$('a.program-let[rel="'+aParts[1]+'"]').click();
					$('a.program-name').removeClass('active');
					
					that.getProgram( aParts[2] );
					break;	
					
				
				case 'works':
					if(aParts[1] == 'frontpage') {
						that.bWorksClicked = false;
						if(!$('a#worksfold').hasClass('foldactive')) {
							$('a#worksfold').click();	
						} else {
							$('#composers').hide();
							$('#pieces').hide();
							$('#programs').hide();
							$('#composer').hide();
							$('#piece').hide();
							$('#program').hide();

							that.showWorksFront();
						}
						
						break;
					}
					break;
					
				default:
					if(bOnLoad) {
						this.onFirstLoad();
					}
					break;
					
			}
		}
		
	},
	
	/**
	 * Open certain columns on autoload
	 */
	
	this.onFirstLoad = function () {
		// $('table.main').hide();
		
		
		
		var that=this;
		this.bAllowHashSet = false;
		this.bAutoPlayJukebox = false; 
		
		// setTimeout( function() { $('table.main').fadeIn(2000); },2000);
		setTimeout( function() { $('#jukeboxfold').click(); },1000);
		setTimeout( function() { $('#tweetsfold').click(); },1500);
		setTimeout( function() { $('#newsfold').click(); },2000);		
		setTimeout( function() { $('#upcomingeventfold').click(); },2500);
		setTimeout( function() { $('#spotlightfold').click(); },3000);
		setTimeout( function() { that.bAllowHashSet = true; that.bAutoPlayJukebox = true; },3500);
		
		
	},
	

	
	this.bindToHashChange = function() {
		var that=this;
		$(window).hashchange( function(){
			that.parseHash(false);
		});
	},
	
	this.initColor = function() {
		iColor = Math.floor ( Math.random() * this.aColors.length ); 
		
		$('body').addClass(this.aColors[iColor]);
		this.sColor = this.aColors[iColor];
		
	},
	
	this.setupAjax = function() {
		
		$.ajaxSetup({
			  async: false,
			  global: true,
			  cache: true
		});
		
	},
	
	
	this.sendScreenInfo = function() {
		var oScreenInfo = new Object();
		oScreenInfo.width = $(window).width();
		oScreenInfo.height = $(window).height();
		oScreenInfo.col3width = $('#worksfold').width();
		
		$.post(LINKROOT+'/do/frontend/setscreeninfo',oScreenInfo);
	},
	
	this.initScrollPane = function() {
		
	},
	
	this.setMaxHeights = function () {
		
		var iAvail = $(window).height()-70;

		if($('html').hasClass('lt-1280')) {
			iAvail = iAvail+90;
		}
		
		
		$('table#main td').each( function() {
			var sCol = this.id;
			var iUsed = 0;
			var iMax = 0;
			var iUsed = 0;
			$('a.fold',this).each( function() {
				iUsed += 41;
			});
			
			
			
			switch(sCol) {
			
				case 'col2':
					iUsed += $('#jukebox').height();
					iUsed += 30;
					break;
			
				case 'col3':
					
					$('a.foldactive',this).each( function() {
						// Height of col3 depends on which block is active
						switch(this.id) {
							case 'worksfold':
							
								iUsed += (21+41);
								$('#block_works div.nested-flex').each( function() {									
									iThisHeight = $(this).height();
									sDisplay = $(this).css('display');
									
									if(sDisplay == 'block') {
										iUsed += iThisHeight;
										iUsed += 24;
									}
								});
								break;
								
							case 'calendarfold':
								iUsed +=  20 + ( $('#subfold_calendar ul ul').length * 16);
								break;
								
							case 'aboutfold':
								iUsed += 20;
								break;
						}
					});
					
										
					break;
					
				case 'col4':
					$('a.foldactive',this).each( function() {
		
						// Height of col4 depends on which block is active
						switch(this.id) {

								
							case 'shortprogramsfold':
								iUsed +=  20;
								break;
						}
					});					
					break;
			}
			
			
			var iMax = iAvail - iUsed - 35;
			$('div.inner',this).css({maxHeight: iMax});
			
			
			
		});
		
		
		this.checkFancyScroll();
	}
	
	
	this.checkFancyScroll = function () {
		return;
		
		// Now check overflows
		$('div.inner').each( function() {
			var iHeight = parseInt( $(this).css('maxHeight').replace('px','') )-50;
			var iContent = $('div.target',$(this)).height();
			
			
		
			
			if(iContent > iHeight) {
				$(this).addClass('has-overflow');
			} else {
				$(this).removeClass('has-overflow');
			}
		});
	}
	
	/**
	 * Bind to composer alphabet letters
	 */
	this.bindToComposerLets = function() {
		var that=this;
		$('a.composer-let').click( function() {
			$('#subfold_works_composers a').removeClass('active');
			$(this).addClass('active');
			that.getComposers( $(this).attr('rel') );
		});
	},

	/**
	 * Bind to piece alphabet letters
	 */
	this.bindToPieceLets = function() {
		var that=this;
		$('a.piece-let').click( function() {
			$('#subfold_works_pieces a').removeClass('active');
			$(this).addClass('active');

			if(!that.bNoLoadPieces) {
				that.getPieces( $(this).attr('rel') );	
			} else {
				that.bNoLoadPieces = false;
			}
			
		});
	},

	/**
	 * Bind to program alphabet letters
	 */
	this.bindToProgramLets = function() {
		var that=this;
		$('a.program-let').click( function() {
			$('#subfold_works_programs a').removeClass('active');
			$(this).addClass('active');
			
			if(!that.bNoLoadPrograms) {
				that.getPrograms( $(this).attr('rel') );	
			} else {
				that.bNoLoadPrograms = false;
			}
			
			
		});
	},	
	
	/**
	 * Bind to names of composers
	 */
	this.bindToComposerNames = function() {
		var that=this;
		$('a.composer-name').click( function() {
			iComposer = $(this).attr('rel');
			
			$('a.composer-name').removeClass('active');
			$('a.composer-name[rel="'+iComposer+'"]').addClass('active');
			
			
			that.getComposer( iComposer );
		});
	},
	
	this.bindToCalendarLinksInline = function(sBlock) {
		var that=this;
		$('#'+sBlock+' a.calendar-jump').click( function() {
			aParts = $(this).attr('rel').split(':');
			iEvent = aParts[1];
			iMonth = aParts[0];
			
			$('#events').hide();
			
			that.foldInAll($(this).parent().parent().parent().parent().parent().parent(), function() {
				that.bCalendarClicked = true;
				that.showCalendar($("#calendarfold"));
				$('a.cal-'+iMonth).click();
			}); 
		});
		
	}
	
	this.bindToComposerNamesInline = function(sBlock) {
		var that=this;
		$('#'+sBlock+' a.composer-name').click( function() {
			aParts = $(this).attr('rel').split(':');
			iComposer = aParts[1];
			sLet = aParts[0];
			$('#subfold_works a[rel="composers"]').click();
			$('a.composer-let[rel="'+sLet+'"]').click();
			$('a.composer-name').removeClass('active');
			
			that.getComposer( iComposer );
		});
	},

	/**
	 * Bind to piece names
	 */
	this.bindToPieceNames = function() {
		var that=this;
		$('a.piece-name').click( function() {
			iPiece = $(this).attr('rel');
			
			$('a.piece-name').removeClass('active');
			$('a.piece-name[rel="'+iPiece+'"]').addClass('active');
			
			
			that.getPiece( iPiece );
		});
	},

	this.bindToPieceNamesInline = function(sBlock) {
		var that=this;
		$('#'+sBlock+' a.piece-name').click( function() {
			aParts = $(this).attr('rel').split(':');
			iPiece = aParts[1];
			sLet = aParts[0];
			$('#subfold_works a[rel="pieces"]').click();
			$('a.piece-let[rel="'+sLet+'"]').click();
			$('a.piece-name').removeClass('active');
			
			that.getPiece( iPiece );
		});
	},
	
	/**
	 * Bind to program names
	 */
	this.bindToProgramNames = function() {
		var that=this;
		$('a.program-name').click( function() {
			iProgram = $(this).attr('rel');
			
			$('a.program-name').removeClass('active');
			$('a.program-name[rel="'+iProgram+'"]').addClass('active');
			
			
			that.getProgram( iProgram );
		});
	},

	this.bindToProgramNamesInline = function(sBlock) {
		var that=this;
		$('#'+sBlock+' a.program-name').click( function() {
			aParts = $(this).attr('rel').split(':');
			iProgram = aParts[1];
			sLet = aParts[0];
			$('#subfold_works a[rel="programs"]').click();
			$('a.program-let[rel="'+sLet+'"]').click();
			$('a.program-name').removeClass('active');
			
			that.getProgram( iProgram );
		});
	},
	
	/**
	 * Bind to sub items under 'works'
	 */
	this.bindToWorkSubfolds = function() {
		var that=this;
		$('#subfold_works a').click( function() {
			$('#worksfront').slideUp('medium','easeInOutCirc');
			switch($(this).attr('rel')) {
				case 'composers':
					$('#subfold_works a').removeClass('subactive');
					$(this).addClass('subactive');
					that.showComposerAlpha(false);
					$('#subfold_works_composers a:first').click();
					break;
					
				case 'pieces':
					$('#subfold_works a').removeClass('subactive');
					$(this).addClass('subactive');
					that.showPiecesAlpha(false);
					$('#subfold_works_pieces a:first').click();
					break;
					
				case 'programs':
					$('#subfold_works a').removeClass('subactive');
					$(this).addClass('subactive');
					that.showProgramsAlpha(false);
					$('#subfold_works_programs a:first').click();
					break;
					
					
			}
		});
	},
	
	this.bindToWorksFrontBrowseLinks = function() {
		$('#browse_composers').click( function() {
			$('#worksfront').slideUp('medium','easeInOutCirc');
			$('#subfold_works a[rel="composers"]').click();
			$('#subfold_works_composers a:first').click();
		});
		
		$('#browse_pieces').click( function() {
			$('#worksfront').slideUp('medium','easeInOutCirc');
			$('#subfold_works a[rel="pieces"]').click();
			$('#subfold_works_pieces a:first').click();
		});

		$('#browse_programs').click( function() {
			$('#worksfront').slideUp('medium','easeInOutCirc');
			$('#subfold_works a[rel="programs"]').click();
			$('#subfold_works_programs a:first').click();
		});
		
	}
	
	/**
	 * Bind to fold out links
	 */
	this.bindToFolds = function() {
		var that=this;
		$('a.fold').click(function() {
			var aParts = $(this).attr('rel').split(':');
			
			switch(aParts[0]) {
			
				case 'getupcomingevents':
					that.getShortEvents(this,$(this).parent(),'upcoming');
					break;

				case 'getpreviousevents':
					that.getShortEvents(this,$(this).parent(),'previous');
					break;
					
				case 'getfutureprograms':
					that.getFuturePrograms(this,$(this).parent());
					break;
					
				case 'gettweets':
					that.getTweets(this,$(this).parent());
					break;
					
				case 'getnews':
					that.getNews(this,$(this).parent());
					break;
					
				case 'getshortprograms':
					that.getShortPrograms(this,$(this).parent());
					break;
					
					
				case 'getspotlight':
					that.getSpotlight(this,$(this).parent());
					break;
					
				case 'getnewsletter':
					that.getNewsletter(this,$(this).parent());
					break;
					
				case 'getjukebox':
					that.getJukebox(this,$(this).parent());
					break;
					
			
				case 'getcontent':
					that.getContent( this,aParts[1],$(this).parent() );
					break;
					
				case 'getcalendar':
					that.showCalendar( this );
					break;
					
				case 'getworks':
					if(!that.bWorksClicked) {
						that.showWorksFront();
						that.bWorksClicked = true;
					}
					
					that.showWorks( this,aParts[1]);
					/*
					 * if(!that.bWorksClicked) { $('#subfold_works
					 * a[rel="composers"]').addClass('subactive');
					 * that.showComposerAlpha(true);
					 * 
					 * $('#subfold_works_composers
					 * a[rel="A"]').addClass('active'); that.getComposers( 'A' );
					 * that.bWorksClicked = true; }
					 */
					break;
			}
		});
		
		// Subcontent folds
		$('a.subcontent').click( function() {
			var aParts = $(this).attr('rel').split(':');
			
			switch(aParts[0]) {
				case 'getsubcontent': 
					that.getSubContent( this,aParts[1] );
					break;
					
			}
			
		});
		
		// Sub folds
		$('a.subspecial').click( function() {
			var aParts = $(this).attr('rel').split(':');
			
			switch(aParts[0]) {
				case 'shortprogramsort': 
					that.resortShortPrograms( this,aParts[1] );
					break;
					
			}
			
		});		
		
	},
	
	
	this.bindToShortProgramLinks = function (sFold) {
		var that=this;
		$('a.shortprogramlink', $('#'+sFold).parent()).click( function() {
			aParts = $(this).attr('rel').split(':');
			iProgram = aParts[1];
			sLet = aParts[0];

			
			that.foldInAll( $('#col3') , function() {
			
				// This fixes a bug noticed by pete, when interacting 3rd & 4th column
				$('#block_works div.subfold').hide();
				$('#block_works div.nested-fold').hide();
				$('#subfold_works').show();
				
				this.bWorksClicked = true;
				$('#subfold_works a[rel="programs"]').click();
				$('a.program-let[rel="'+sLet+'"]').click();
				
				$('#worksfold').addClass('foldactive');
				$('#worksfront').hide();
				$('#composer').hide();
				$('#piece').hide();
				$('#program').hide();
	
				
				that.getProgram(iProgram);
				$('a.program-name').removeClass('active');
				$('#block_works div.content').slideDown('medium','easeInOutCirc');
			});
			
		});

	}
	
	/**
	 * Re-sort short program list
	 */
	
	this.resortShortPrograms = function(oTrigger, sSorter) {
		this.sShortProgramSort = sSorter;
		var that=this;
		
		$('#subfold_shortprograms a.sub').removeClass('subactive');
		$(oTrigger).addClass('subactive');
		
		
		$('#subfold_shortprograms').parent().slideUp('medium','easeInOutCirc', function() {
			// Load programs

			that.setMaxHeights();
			
			$.get(LINKROOT+'/view/program/shortlist?sort='+that.sShortProgramSort, function(sData){
				$('div.target',$(oTrigger).parent().parent().parent()).html(sData);
				that.bindToShortProgramLinks('shortprogramsfold');
				$('div.content',$(oTrigger).parent().parent().parent()).slideDown('medium','easeInOutCirc', function() {
					oTrigger.focus();
					that.checkFancyScroll();
				});
				
				
			});
			
		});
		

	}
	
	/**
	 * Show works frontpage
	 */
	
	this.showWorksFront = function() {
		var that=this;
		this.setHash('#!works:frontpage');
		that.setMaxHeights();
		$.get(LINKROOT+'/view/frontend/works', function(sData){
			$('#worksfront div.target').html(sData);
			$('#worksfront').slideDown('medium','easeInOutCirc', function() {that.checkFancyScroll();});
			that.bindToWorksFrontBrowseLinks();
			
			that.bindToComposerNamesInline('worksfront');
			that.bindToPieceNamesInline('worksfront');
			that.bindToProgramNamesInline('worksfront');
		});
		
	},
	
	
	/**
	 * Bind to calendar (month) links
	 */
	this.bindToCalendarLinks = function () {
		var that=this;
		$('ul.calendar a').click( function() {
			aParts = $(this).attr('rel').split(':');
			that.loadCalendar(aParts[1]);
		});
	},
	
	this.loadCalendar = function(iMonth) {
		this.setHash('#!calendar:'+iMonth);
		var that=this;
		$('#events').slideUp('medium','easeInOutCirc', function() {
			$('ul.calendar span.active').removeClass('active');
			$('ul.calendar a').removeClass('active');
			$('ul.calendar a[rel="'+iMonth+'"]').addClass('active');
			$('ul.calendar a.active').each( function() {
				$('span.date',$(this).parent().parent()).addClass('active');
			});
			
			$.get(LINKROOT+'/view/event/list/'+iMonth, function(sData) {
				$('#events div.target').html(sData);
				$('#events').slideDown('medium','easeInOutCirc', function() {that.checkFancyScroll();});
				that.bindToCalendarProgramLinks();
			});
			
		});
		
	},
	
	/**
	 * Program links inside calendar
	 */
	this.bindToCalendarProgramLinks = function() {
		var that=this;
		$('#events a.program').click( function() {
			var aParts = $(this).attr('rel').split(':');
			that.foldInAll( $(this).parent().parent().parent().parent().parent().parent().parent().parent(), function() {
				that.bNoLoadPrograms = true;
				that.getProgramFromCalendar(aParts[0],aParts[1]);
			});
		});
	},
	
	this.getProgramFromCalendar = function(sLet,iProgram) {
		this.bWorksClicked = true;
		$('#subfold_works a[rel="programs"]').click();
		$('a.program-let[rel="'+sLet+'"]').click();
		
		$('#worksfold').addClass('foldactive');
		$('#worksfront').hide();
		$('#composer').hide();
		$('#piece').hide();
		$('#program').hide();

		
		this.getProgram(iProgram);
		$('a.program-name').removeClass('active');
		$('#block_works div.content').slideDown('medium','easeInOutCirc');

		
		
				
	}
	
	/**
	 * Shows calendar block
	 */
	this.showCalendar = function(oTrigger) {
		
		$('#block_works div.nested-fold').hide();
		var that=this;
		if(!$(oTrigger).hasClass('foldactive')) {
			// Fold in others
			this.foldInAll( $(oTrigger).parent().parent(), function() {
				// Show
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$('#block_calendar div.content').slideDown('medium','easeInOutCirc');
				
				if(!that.bCalendarClicked) {
					$('ul.calendar a:first').click();
					that.bCalendarClicked = true;
				}
				
			} );
			
			
		} else {
			// Hide
			$(oTrigger).removeClass('foldactive');
			$('#block_calendar div.content').slideUp('medium','easeInOutCirc');
		}

	},
	
	/**
	 * Hide visible works details
	 */
	
	this.hideWorksDetails = function(sCallBack) {
		if(!this.sActiveWorkSection) {
			if(typeof(sCallBack) != 'undefined') {
				sCallBack();
			}
		} else {
			$('#'+this.sActiveWorkSection).slideUp('medium','easeInOutCirc', function() {
				if(typeof(sCallBack) != 'undefined') {
					sCallBack();
				}
			});	
		}
		
		
	},

	/**
	 * Get a single composer
	 */
	
	this.getComposer = function(iComposer) {
		
		this.setHash('#!composer:'+this.sActiveComposerLet+':'+iComposer);
		var that=this;
		
		$('#worksfront').slideUp('medium','easeInOutCirc', function() {
		
			that.hideWorksDetails(function() {	
				$.get(LINKROOT+'/view/composer/detail/'+iComposer, function(sData) {
					$('#composer div.target').html(sData);
					$('#composer').slideDown('medium','easeInOutCirc', function() {that.checkFancyScroll();});
					that.bindToPieceNamesInline('composer');
					setTimeout( function() {$('a.composer-name[rel="'+iComposer+'"]').addClass('active');},200);
					$('a.composer-name[rel="'+iComposer+'"]').addClass('active');
					that.sActiveWorkSection = 'composer';
				});				
			});
		});
	},
	
	/**
	 * Hide composer
	 */
	this.hideComposer = function() {
		$('#composer').slideUp('medium','easeInOutCirc');
	},


	/**
	 * Get a single piece
	 */
	
	this.getPiece = function(iPiece) {
		var that=this;
		this.setHash('#!piece:'+this.sActivePieceLet+':'+iPiece);
		$('#worksfront').slideUp('medium','easeInOutCirc', function() {
		
			that.hideWorksDetails(function() {
	
				$.get(LINKROOT+'/view/piece/detail/'+iPiece, function(sData) {
					$('#piece div.target').html(sData);
					$('#piece').slideDown('medium','easeInOutCirc', function() {that.checkFancyScroll();});
					
					setTimeout( function() { $('a.piece-name[rel="'+iPiece+'"]').addClass('active'); },200);
					$('a.piece-name[rel="'+iPiece+'"]').addClass('active');
					that.sActiveWorkSection = 'piece';
					
					that.bindToComposerNamesInline('piece');
					that.bindToProgramNamesInline('piece');
					that.bindToCalendarLinksInline('piece');
				});
				
			});	
		
		});
	},
	
	/**
	 * Hide piece
	 */
	this.hidePiece = function() {
		$('#piece').slideUp('medium','easeInOutCirc');
	},

	/**
	 * Get a single program
	 */
	
	this.getProgram = function(iProgram) {
		var that=this;
		this.setHash('#!program:'+this.sActiveProgramLet+':'+iProgram);
		$('#worksfront').slideUp('medium','easeInOutCirc', function() {
		
			that.hideWorksDetails(function() {
	
				$.get(LINKROOT+'/view/program/detail/'+iProgram, function(sData) {
					$('#program div.target').html(sData);
					$('#program').slideDown('medium','easeInOutCirc', function() {that.checkFancyScroll();});
					// that.bindToComposerPieces();
					setTimeout( function() {$('a.program-name[rel="'+iProgram+'"]').addClass('active');},200);
					$('a.program-name[rel="'+iProgram+'"]').addClass('active');
					that.sActiveWorkSection = 'program';
					
					that.bindToComposerNamesInline('program');
					that.bindToPieceNamesInline('program');
					that.bindToCalendarLinksInline('program');
					
				});
				
			});	
		
		});
	},
	
	/**
	 * Hide program
	 */
	this.hideProgram = function() {
		$('#program').slideUp('medium','easeInOutCirc');
	},
	
	
	/**
	 * Get composers for selected letter
	 */
	this.getComposers = function(sLet) {
		var that=this;
		this.sActiveComposerLet = sLet;
		// this.setHash('#!composers:'+sLet);
		$.get(LINKROOT+'/view/composer/list/'+sLet, function(sData){
			$('#composers').html(sData);
			$('#composers').slideDown('medium','easeInOutCirc', function() { that.setMaxHeights();});
			that.bindToComposerNames();
			
		});
	},

	/**
	 * Get pieces for selected letter
	 */
	this.getPieces = function(sLet) {
		var that=this;
		// this.setHash('#!pieces:'+sLet);
		this.sActivePieceLet = sLet;
		$.get(LINKROOT+'/view/piece/list/'+sLet, function(sData){
			$('#pieces').html(sData);
			$('#pieces').slideDown('medium','easeInOutCirc', function() { that.setMaxHeights();});
			that.bindToPieceNames();
		});
	},

	/**
	 * Get programs for selected letter
	 */
	this.getPrograms = function(sLet) {
		var that=this;
		this.sActiveProgramLet = sLet;
		// this.setHash('#!programs:'+sLet);
		$.get(LINKROOT+'/view/program/list/'+sLet, function(sData){
			$('#programs').html(sData);
			$('#programs').slideDown('medium','easeInOutCirc', function() { that.setMaxHeights();});
			that.bindToProgramNames();
		});
	},	
	
	/**
	 * Hide composers
	 */
	
	this.hideComposers = function() {
		$('#composers').slideUp('medium','easeInOutCirc');
	},
	
	/**
	 * Show/hide composer alphabet links
	 */
	
	this.showComposerAlpha = function() {
		this.hideAllWorksAlpha();
		$('#subfold_works_composers').slideDown('medium','easeInOutCirc');
	},
	
	this.hideComposerAlpha = function() {
		$('#subfold_works_composers').slideUp('medium','easeInOutCirc');
	},
	

	/**
	 * Show/hide pieces alphabet links
	 */
	
	this.showPiecesAlpha = function() {
		this.hideAllWorksAlpha();
		$('#subfold_works_pieces').slideDown('medium','easeInOutCirc');
	},
	
	this.hidePiecesAlpha = function() {
		$('#subfold_works_pieces').slideUp('medium','easeInOutCirc');
	},

	/**
	 * Show/hide programs alphabet links
	 */
	
	this.showProgramsAlpha = function() {
		this.hideAllWorksAlpha();
		$('#subfold_works_programs').slideDown('medium','easeInOutCirc');
	},
	
	this.hideProgramsAlpha = function() {
		$('#subfold_works_programs').slideUp('medium','easeInOutCirc');
	},
	
	/**
	 * Hide all works alphas
	 */
	
	this.hideAllWorksAlpha = function() {
		this.hidePiecesAlpha();
		this.hideComposerAlpha();
		this.hideProgramsAlpha();
		
		$('#composers').slideUp('medium','easeInOutCirc');
		$('#pieces').slideUp('medium','easeInOutCirc');
		$('#programs').slideUp('medium','easeInOutCirc');
	}
	this.showWorks = function (oTrigger,sSubItem) {
		var that=this;
		
		
		if(!$(oTrigger).hasClass('foldactive')) {
			// Fold in others
			this.foldInAll( $(oTrigger).parent().parent(), function() {
				// Show
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				$('#block_works div.content').slideDown('medium','easeInOutCirc');
				that.setMaxHeights();
			} );
			
			
		} else {
			// Hide
			$(oTrigger).removeClass('foldactive');
			$('#block_works div.content').slideUp('medium','easeInOutCirc');
		}
		
		
	},
	
	this.getWorks = function(sSubItem) {
		$('a.sub').removeClass('subactive');
		$('#sub-'.sSubItem).addClass('subactive');
		
		switch(sSubItem) {
		case 'composers':
			sUrl = LINKROOT+'/view/composer/list';
			break;
			
	}
	
	$.get(sUrl, function(sData){
		$('#block_works div.inner').html(sData);
		$('#block_works div.content').slideDown('medium','easeInOutCirc');
	});
		
	},
		
	
	/**
	 * Fold in all active blocks
	 */
	this.foldInAll = function(oCol,sCallback) {
		
		if($('a.foldactive',oCol).length == 0) {
			sCallback();	
		} else {
			$('a.foldactive',oCol).each( function() {
				$(this).removeClass('foldactive');
				$('div.content',$(this).parent()).slideUp('medium','easeInOutCirc', function(){
					sCallback();
				});
			});
		}
		
		
	}
	
	
	/**
	 * Loads sub-menu content into block
	 */
	this.getSubContent = function(oTrigger, sCode) {
		this.setHash('#!subcontent:'+sCode);
		var that=this;
		
		$('a.subcontent').removeClass('subactive');		
		$('a.subcontent[rel="getsubcontent:'+sCode+'"]').addClass('subactive');
		
		$('div.inner',$(oTrigger).parent().parent()).slideUp('medium','easeInOutCirc', function() {
			$.get(LINKROOT+'/view/content/ajax/'+sCode, function(sData){
				$('div.inner div.target',$(oTrigger).parent().parent()).html(sData);
				$('div.inner',$(oTrigger).parent().parent()).slideDown('medium','easeInOutCirc', function() {
					oTrigger.focus();
					that.checkFancyScroll();
				});
				
				
			});
		});
	},
	
	/**
	 * Loads news into block
	 */
	this.getNews = function(oTrigger,oBlock) {
		this.setHash('#!news');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load news
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/news/list', function(sData){
					$('div.content div.inner div.target',oBlock).html(sData);
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},

	/**
	 * Loads future programs into block
	 */
	this.getFuturePrograms = function(oTrigger,oBlock) {
		this.setHash('#!futureprograms');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load programs
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/program/future', function(sData){
					$('div.content div.inner div.target',oBlock).html(sData);
					that.bindToShortProgramLinks('futureprogramfold');
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},
	
	/**
	 * Loads short programs into block
	 */
	this.getShortPrograms = function(oTrigger,oBlock) {
		this.setHash('#!shortprograms');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load programs
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/program/shortlist?sort='+that.sShortProgramSort, function(sData){
					
					$('div.content div.inner div.target',oBlock).html(sData);
					that.bindToShortProgramLinks('shortprogramsfold');
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},
	
	
	/**
	 * Loads spotlight into block
	 */
	this.getSpotlight = function(oTrigger,oBlock) {
		this.setHash('#!spotlight');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load news
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/news/spotlight', function(sData){
					$('div.content div.inner div.target',oBlock).html(sData);
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},

	/**
	 * Bind to newsletter buttons
	 */
	this.bindToNewsletter = function() {
		var that=this;

		$('#newsletter_btn_subscribe').click( function() {
			that.newsletterSubscribe();			
		});
		
		$('#newsletter_btn_unsubscribe').click( function() {
			that.newsletterUnsubscribe();			
		});		
	},
	
	this.hideNewsletterError = function() {
		$('#newsletter_error').html('&nbsp;');
	},
	
	this.newsletterError = function(sMsg) {
		$('#newsletter_error').html(sMsg).fadeIn('slow');
	},
	
	/**
	 * Subscribe to newsletter
	 */
	this.newsletterSubscribe = function () {
		var that=this;
		that.hideNewsletterError();
		var aFields = $('#newsletterform').serialize();
		$.post(LINKROOT+'/do/newsletter/subscribe', aFields, function(sResponse){
			if(sResponse == 'OK') {
				// OK!
				that.getNewsletterContent('newsletter_confirm');
				
			} else {
				// Error
				that.newsletterError(sResponse);
			}
		});
		
		
	},

	/**
	 * Unsubscribe to newsletter
	 */
	this.newsletterUnsubscribe = function () {
		var that=this;
		that.hideNewsletterError();
		var aFields = $('#newsletterform').serialize();
		$.post(LINKROOT+'/do/newsletter/unsubscribebyemail', aFields, function(sResponse){
			if(sResponse == 'OK') {
				// OK!
				that.getNewsletterContent('newsletter_unsubscribe_success');
				
			} else {
				// Error
				that.newsletterError(sResponse);
			}
		});
		
		
	},	
	
	this.getNewsletterContent = function(sContent) {
		var that=this;
		// Load message
		$('#newsletterfold').addClass('foldactive');
		that.setMaxHeights();
		
		$.get(LINKROOT+'/view/content/ajax/'+sContent, function(sData){					
			$('div.content div.inner div.target',$('#newsletterfold').parent()).html(sData);
			$('div.content',$('#newsletterfold').parent()).slideDown('medium','easeInOutCirc', function() {
				$('#newsletterfold').focus();
				that.checkFancyScroll();
			});
			
			
		});		
	}

	/**
	 * Loads newsletter into block
	 */
	this.getNewsletter = function(oTrigger,oBlock) {
		this.setHash('#!newsletter');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load news
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/newsletter/subscribe', function(sData){					
					$('div.content div.inner div.target',oBlock).html(sData);
					that.bindToNewsletter();
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},
	
	/**
	 * Loads tweets into block
	 */
	this.getTweets = function(oTrigger,oBlock) {
		this.setHash('#!tweets');
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load tweets
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/twitterfeed/list', function(sData){
					$('div.content div.inner div.target',oBlock).html(sData);
					that.fixSocial();
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
						
					});
					
					
				});
			});
		}
	},

	/**
	 * Loads short events into block
	 */
	this.getShortEvents = function(oTrigger,oBlock,sType) {
		this.setHash('#!'+sType);
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				// Load events
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				$.get(LINKROOT+'/view/event/'+sType, function(sData){
					$('div.content div.inner div.target',oBlock).html(sData);
					
					switch(sType) {
						case 'upcoming':
							that.bindToShortProgramLinks('upcomingeventfold');
							break;
							
						case 'previous':
							that.bindToShortProgramLinks('previouseventfold');
							break;
					}
					
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});
					
					
				});
			});
		}
	},
	
	
	/**
	 * Starts the jukebox
	 */
	this.initJukebox = function(oJukebox) {
		
		var that=this;
		var aPlaylist = new Array();
		$.each(this.aTracks, function(iIndex,aTrack) {
			oTrack = new Object();
			oTrack.name = aTrack.tbl_jukebox_name;
			oTrack.mp3 = LINKROOT+'/'+aTrack.tbl_jukebox_file;
			aPlaylist.push( oTrack );
		});
		
		
		this.oJukebox = new Playlist("2", aPlaylist, {
			
			
			ready: function() {
				that.bInitJukebox = true; 
				that.oJukebox.displayPlaylist();
				that.oJukebox.playlistInit(that.bAutoPlayJukebox); // Parameter
																	// is a
																	// boolean
													// for autoplay.
				$('#jp_playlist_2').slideDown('medium','easeInOutCirc');
			},
			ended: function() {
				that.oJukebox.playlistNext();
			},
			play: function() {
				$(this).jPlayer("pauseOthers");
			},
			supplied: "mp3"
		});


		
	},
	
	/**
	 * Loads jukebox into block
	 */
	this.getJukebox = function(oTrigger,oBlock) {
		var that=this;
		this.setHash('#!jukebox');
		
		if(this.bInitJukebox) {
			if($(oTrigger).hasClass('foldactive')) {
				// Pause
				$('#jquery_jplayer_2').jPlayer('pause');
				
				// Just close this one
				$(oTrigger).removeClass('foldactive')
				$('div.content',oBlock).slideUp('medium','easeInOutCirc');
				
				
			}else {
				// Close others
				this.foldInAll($(oTrigger).parent().parent(), function() {
					
					$(oTrigger).addClass('foldactive');
					that.setMaxHeights();
					
					// play
					$('#jquery_jplayer_2').jPlayer('play');
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						
					});
				});
			}			
			
		} else {
			
			var that=this;
			if($(oTrigger).hasClass('foldactive')) {
			
				// Just close this one
				$(oTrigger).removeClass('foldactive')
				$('div.content',oBlock).slideUp('medium','easeInOutCirc');
			} else {
				// Close others
				this.foldInAll($(oTrigger).parent().parent(), function() {
					
					// Load jukebox
					$(oTrigger).addClass('foldactive');
					that.setMaxHeights();
					
					$.getJSON(LINKROOT+'/view/jukebox/player', function(aTracks){
						
						that.aTracks = aTracks;
						that.initJukebox();
						
						$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
							oTrigger.focus();
							that.checkFancyScroll();
						});
						
						
					});
				});
			}
		}
	},
	
	
	/**
	 * Loads content into block
	 */
	this.getContent = function(oTrigger, sCode,oBlock) {
		this.setHash('#!content:'+sCode);
		var that=this;
		if($(oTrigger).hasClass('foldactive')) {
			// Just close this one
			$(oTrigger).removeClass('foldactive')
			$('div.content',oBlock).slideUp('medium','easeInOutCirc');
		} else {
			// Close others
			this.foldInAll($(oTrigger).parent().parent(), function() {
				
				bSkipLoadContent = false;
				
				// Special action?
				switch($(oTrigger).attr('id')) {
					case 'aboutfold':
						if(!that.bAboutFoldClicked) {
							$('a.subcontent[rel="getsubcontent:aboutus"]').addClass('subactive');
							$('a.subcontent[rel="getsubcontent:members"]').removeClass('subactive');
							$('a.subcontent[rel="getsubcontent:faq"]').removeClass('subactive');
							that.bAboutFoldClicked = true;							
						} else {
							bSkipLoadContent = true;
						}
						break;
				}
				
				
				// Load content
				$(oTrigger).addClass('foldactive');
				that.setMaxHeights();
				
				if(bSkipLoadContent) {
					$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
						oTrigger.focus();
						that.checkFancyScroll();
					});					
				} else {
				
					$.get(LINKROOT+'/view/content/ajax/'+sCode, function(sData){
						$('div.content div.inner div.target',oBlock).html(sData);
						$('div.content',oBlock).slideDown('medium','easeInOutCirc', function() {
							oTrigger.focus();
							that.checkFancyScroll();
						});
						
						
					});
				}
			});
		}
	},

	
	this.microtime = function() {
		var now = new Date().getTime() 
		return parseInt(now);

	}
	
}


var Playlist = function(instance, playlist, options) {
	var self = this;

	this.instance = instance; // String: To associate specific HTML with this
								// playlist
	this.playlist = playlist; // Array of Objects: The playlist
	this.options = options; // Object: The jPlayer constructor options for this
							// playlist

	this.current = 0;

	this.cssId = {
		jPlayer: "jquery_jplayer_",
		interface: "jp_interface_",
		playlist: "jp_playlist_"
	};
	this.cssSelector = {};

	$.each(this.cssId, function(entity, id) {
		self.cssSelector[entity] = "#" + id + self.instance;
	});

	if(!this.options.cssSelectorAncestor) {
		this.options.cssSelectorAncestor = this.cssSelector.interface;
	}

	
	$(this.cssSelector.jPlayer).jPlayer(this.options);

	$(this.cssSelector.interface + " .jp-previous").click(function() {
		self.playlistPrev();
		$(this).blur();
		return false;
	});

	$(this.cssSelector.interface + " .jp-next").click(function() {
		self.playlistNext();
		$(this).blur();
		return false;
	});
};



Playlist.prototype = {
		displayPlaylist: function() {
			var self = this;
			$(this.cssSelector.playlist + " ul").empty();
			for (i=0; i < this.playlist.length; i++) {
				var listItem = (i === this.playlist.length-1) ? "<li class='jp-playlist-last'>" : "<li>";
				listItem += "<a href='javascript:;' id='" + this.cssId.playlist + this.instance + "_item_" + i +"' tabindex='1'>"+ this.playlist[i].name +"</a>";

				// Create links to free media
				if(this.playlist[i].free) {
					var first = true;
					listItem += "<div class='jp-free-media'>(";
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check
																	// property
																	// is a
																	// media
																	// format.
							if(first) {
								first = false;
							} else {
								listItem += " | ";
							}
							listItem += "<a id='" + self.cssId.playlist + self.instance + "_item_" + i + "_" + property + "' href='" + value + "' tabindex='1'>" + property + "</a>";
						}
					});
					listItem += ")</span>";
				}

				listItem += "</li>";

				// Associate playlist items with their media
				$(this.cssSelector.playlist + " ul").append(listItem);
				$(this.cssSelector.playlist + "_item_" + i).data("index", i).click(function() {
					var index = $(this).data("index");
					if(self.current !== index) {
						self.playlistChange(index);
					} else {
						$(self.cssSelector.jPlayer).jPlayer("play");
					}
					$(this).blur();
					return false;
				});

				// Disable free media links to force access via right click
				if(this.playlist[i].free) {
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check
																	// property
																	// is a
																	// media
																	// format.
							$(self.cssSelector.playlist + "_item_" + i + "_" + property).data("index", i).click(function() {
								var index = $(this).data("index");
								$(self.cssSelector.playlist + "_item_" + index).click();
								$(this).blur();
								return false;
							});
						}
					});
				}
			}
		},
		playlistInit: function(autoplay) {
			if(autoplay) {
				this.playlistChange(this.current);
			} else {
				this.playlistConfig(this.current);
			}
		},
		playlistConfig: function(index) {
			$(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
			$(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
			this.current = index;
			$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
		},
		playlistChange: function(index) {
			this.playlistConfig(index);
			$(this.cssSelector.jPlayer).jPlayer("play");
		},
		playlistNext: function() {
			var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
			this.playlistChange(index);
		},
		playlistPrev: function() {
			var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
			this.playlistChange(index);
		}
	};

