var page_id;
var nowPlaying;
var player;
var highlightColor = '#000000';
var startPulsator;
var playerReady = 0;
var waitingCycles = 0;
// override default easing
jQuery.easing.def = "easeInOutQuad";

/* 
* slowly fades the loading screen, starts 1st track, start pulsator
*/
function revealBooklet() {
	if (player && player.playerJQ) jQuery('.play', player.playerJQ).click();

	jQuery('#rightpanel .excerpt-container:eq(3)').each(bubbleHover);
	jQuery('#leftpanel .excerpt-container:eq(4)').each(bubbleHover);
	hideUnselectedTips();
	
	//jQuery('*').queue('fx', []);
	jQuery('*:animated').stop(true, true);
	jQuery('.song-excerpt').css('opacity', null);

	jQuery('#loader').hide('slide', {direction:'down'}, 2000);
}
/* 
* does the init stuff, like creating widgets, registering event-handlers and so on.
*/
function init(withPlayer) {
	// return if there is nothing to do...
	if (jQuery('#wrapper').length == 0) return;
	// get page ID
	page_id = jQuery('.mainpage').attr('id');
	page_id = parseInt(page_id.substring(4, page_id.length));
	loaderStatus("Page identified.");
	borderize();
	if (withPlayer) loadPlaylist();
	loaderStatus("Borders wrapped.");

	// show main, made so early for avoiding interference with ui-widgets, still hidden by loader!
	createNavi();
	loaderStatus("Sidebars ready.");
	subContentControls();
	loaderStatus("Content controls activated.");
	otherControls();
	loaderStatus("Additional controls activated.");
	otherEffects();
	loaderStatus("Effects activated.");
	
	// make some error stuff
	if (!withPlayer) {
		jQuery('.bottompanel').html('<a href="http://get.adobe.com/de/flashplayer/" target="_blank">Du ben&ouml;tigst Flash um Musik abspielen zu k&ouml;nnen!</a>');
		chameleon('#027602');
		loaderStatus('Player nicht gestartet!');
		revealBooklet();
	} else {
		waitingRevealer();
	}
}

function waitingRevealer() {
	switch (playerReady) {
		case 0:
			loaderStatus("Warten auf Playlist...");
			setTimeout("waitingRevealer()", 250);
			waitingCycles++;
			if (waitingCycles > 20) playerReady = -1;
			break;
		case 1:
			loaderStatus("Fertig!");
			revealBooklet();
			break;
		case -1:
			jQuery('.bottompanel').html('<a href="mailto:support@7ieben.de" target="_blank">Leider ist ein Fehler aufgetreten. Sag uns bitte Bescheid!</a>');
			chameleon('#027602');
			loaderStatus('Player nicht gestartet!');
			revealBooklet();
			break;
	}
}

function borderize() {
	borderString = '<div class="top-border"><div class="bottom-border"><div class="left-border"><div class="right-border"><div class="tl-corner"><div class="tr-corner"><div class="br-corner"><div class="bl-corner"></div></div></div></div></div></div></div></div>';
	jQuery('#content .mainpage').wrap(borderString);
	//jQuery('#leftpanel .borderwrapper').wrap(borderString);
	//jQuery('#rightpanel .borderwrapper').wrap(borderString);
}

function loadPlaylist() {
	jQuery.post(ajax_request_url, { ajax : 'playlist', id: page_id }, function (data, textStatus) {
		// create our player - playlist is contained in the answer data.
		data  = jQuery(data);
		player = createPlayer(data, '#bottompanel');
		// effects for player must wait for player creation...
		highlighter(jQuery('#bottompanel .player .control'));
		loaderStatus('Playlist geladen');
		playerReady = 1;
	});
}
function createNavi() {
	createBubbleNavi({
		container:'#rightpanel .widgets', 
		bubbles:'.excerpt-container', 
		tip: '.misc-excerpt', 
		alignment: 'left',
		heights: new Array(85, 65, 40, 33, 30),
		opacities: new Array(1, .9, .5, .4, .3)
	});
	createBubbleNavi({
		container:'#leftpanel .songlist', 
		bubbles:'.excerpt-container', 
		tip: '.song-excerpt', 
		alignment: 'right',
		heights: new Array(85, 65, 40, 33, 30),
		opacities: new Array(1, .9, .5, .4, .3)
	});	
}

function bubbleHover() {
	// re-get the main object
	bubbleNav = jQuery(this).data('options').bubbleNav;
	
	// show & hide tip
	jQuery(bubbleNav.data('options').tip, this).show();
	jQuery(bubbleNav.data('options').tip, bubbleNav.not(this)).hide();
	
	// class updates
	jQuery(this).removeClass('un-hovered').addClass('hovered');
	bubbleNav.not(this).removeClass('hovered').addClass('un-hovered');

	// set hovered index
	index = bubbleNav.index(this);
	bubbleNav.data('hovIndex',index);
	// init summed size
	bubbleNav.data('sumSize',0);
	
	// go for each nav item
	bubbleNav.each(function (i) {
		// calculate height & opacity
		distance = bubbleNav.data('hovIndex')-i;
		heightIndex = Math.min(bubbleNav.data('options').heights.length-1, Math.abs(distance));
		opacityIndex = Math.min(bubbleNav.data('options').opacities.length-1, Math.abs(distance));
		jQuery(this).data('distance', distance);
		newHeight = bubbleNav.data('options').heights[heightIndex];
		newOpacity = bubbleNav.data('options').opacities[opacityIndex];
		jQuery(this).data('newHeight', newHeight);
		
		if (jQuery(this).is('.hovered')) {
			jQuery('.marker',this).fadeIn(700);
		} else {
			jQuery('.marker',this).stop(true, true).hide();
		}
		// excerpt adjustements
		tip = jQuery(this).data('options').tip;
		alignment = jQuery(this).data('options').alignment;
		// add height
		bubbleNav.data('sumSize',bubbleNav.data('sumSize') + newHeight);
		// height/opacity-anim
		jQuery(this).stop(true).animate({
				height:	newHeight + 'px',
				queue:	false,
				opacity: newOpacity
			},
			'normal'
		);
		// tip position adjustement
		switch (alignment) {
			case 'left':
				jQuery(jQuery(this).data('options').tip, this).stop(true).css({	left: newHeight+'px' });			
				break;
			case 'right':
				jQuery(jQuery(this).data('options').tip, this).stop(true).css({	right: newHeight+'px' });			
				break;
			case 'top':
				jQuery(jQuery(this).data('options').tip, this).stop(true).css({	top: newHeight+'px' });									
				break;
			case 'bottom':
				jQuery(jQuery(this).data('options').tip, this).stop(true).css({	bottom: newHeight+'px' });									
				break;
		}
	});
	// global margin-correction
	allHeight = bubbleNav.data('options').parentHeight;
	sumHeight = bubbleNav.data('sumSize');
	correction = Math.round((allHeight-sumHeight)/2);		
	jQuery(bubbleNav.data('options').container).stop().animate({marginTop: correction, queue:false});
	return false;
}
function hideUnselectedTips() {
	jQuery('#rightpanel .excerpt-container:not(.active-subcontent) .misc-excerpt').stop(true, true).hide();
	jQuery('#leftpanel .excerpt-container:not(.active-subcontent) .song-excerpt').stop(true, true).hide();
	jQuery('.excerpt-container:not(.active-subcontent) .marker').stop(true, true).hide();
}

function createBubbleNavi(options) {
	// check options
	if (!options.container || !options.bubbles || !options.alignment) return
	// get jq-objects
	navParent = jQuery(options.container);
	bubbleNav = jQuery(options.bubbles, navParent);
	// add options
	options.size = bubbleNav.size();
	options.bubbleNav = bubbleNav;
	options.parentHeight = navParent.height();
	options.balancedHeight = options.parentHeight/options.size; // in pixels!
	// cache it
	navParent.data('options', options);
	bubbleNav.data('options', options);
	
	// height initialization
	bubbleNav.css({ height: bubbleNav.data('options').balancedHeight+'px'});
	
	// hover functions
	bubbleNav.hover(
		bubbleHover,
		function () {
		}
	);
	navParent.hover(
		function () {},
		function () {
			// execute hover function in context of activated element
			jQuery(jQuery(this).data('options').bubbles+'.active-subcontent', this).each(bubbleHover);
			hideUnselectedTips();
		}
	);
}

function otherControls() {
	// make tracklinks play tracks
	jQuery('.panel .tracklink').click(function() {
		if (!player) return;
		player.play(this.href.substring(this.href.indexOf('#')+5, this.href.length));
		return false; // don't follow the link!
	});
	
	// make panels hide the content.
	jQuery('#wrapper .activator').click(function() {
		jQuery('#wrapper .activator').css('visibility','hidden');
		activateSubContent(null, '#leftpanel .excerpt-container, #rightpanel .excerpt-container');
	});
	
	// make register/lostpasswort links use the iframe
	jQuery('.iframed').click(function() {
			jQuery('#adminhelper').remove();
			activateSubContent('#iframe-container');
			jQuery('<iframe id="adminhelper" name="adminhelper" src="'+this.href+'"></iframe>')
				.load(function () {
				if(this.contentDocument)  
				   // Firefox, Opera  
				   context = this.contentDocument;  
				else if(this.contentWindow)  
				   // Internet Explorer  
				   context = this.contentWindow.document;  
				else if(this.document)  
				   // Others?  
				   context = this.document;  
					jQuery('head', context).prepend('<style type="text/css">#login h1 {display:none;} body.login { border:none; background-color:#000;} body.login form {background-color: #000; margin-right:8px; border:none;} #backtoblog {display:none;} div#login {margin:0px; width:100%; height:100%; background-color:#000; position:absolute;} #nav {display:none;} #user_pass, #user_login, #user_email, #pass1, #pass2, #regcode, #captcha, #firstname, #lastname, #website, #aim, #yahoo, #jabber, #about {font-size:12px !important; background-color:#AAA !important; border-color:#CCC !important; color:#000 !important; margin-bottom: 0px !important;} .updated, .login #login_error, .login .message {background-color:#CCC !important; border-color: #FFF !important; margin:1px !important; padding:7px !important;} .submit {margin-top:10px;} .submit input { background: #333 !important; -moz-border-radius:0px !important; border:none !important;} form {padding: 16px 16px 0px !important;<style>');
					jQuery('input:submit', context).click(function () {
						jQuery('#adminhelper').fadeOut();
					});
					jQuery(this).fadeIn();
				}).appendTo('#iframe-container');
			return false;
	});
}

function otherEffects() {
	// other nice effects
	highlighter(jQuery('#wrapper .activator'));
	jQuery('#wrapper .mainpage').click(function() {
		jQuery('#wrapper .activator')
			.stop()
			.css('background-color', highlightColor)
			.animate({backgroundColor: '#000000'}, 1500);
	});
		// make links switch to gray on hover
	jQuery('a').not('.static-color').hover(
		function () {
			jQuery(this).css({color:'#EEE'});
		},
		function () {
			jQuery(this).css({color:highlightColor});
		}		
	);
}
/* 
* simple helper to make an elements background fadin/out on hover
*/
function highlighter(jqElem) {
	jqElem.hover(
		function () {
			highlighted = jQuery(this);
			if (highlighted.is('.chameleon')) return;
			highlighted.stop().animate({backgroundColor: highlightColor}).addClass('highlighted');
		},
		function () {
			highlighted = jQuery(this);
			if (highlighted.is('.chameleon')) return;
			highlighted.stop().removeClass('highlighted').animate({backgroundColor: "#000000"});
		}
	);
}

function subContentControls() {
	// activate loginlinks
	jQuery('a[href=#login]').addClass('contentlink');
	
	// make contentlinks show subcontent
	jQuery('.lyriclink, .contentlink').click(function() {
		if (jQuery(this).is('.active-link')) return false;
		jQuery('.active-link').removeClass('active-link');
		jQuery('.active-subcontent')
			.removeClass('active-subcontent');
		jQuery(this).parents('.excerpt-container')
			.addClass('active-subcontent');
		jQuery(this)
			.addClass('active-link');
		activateSubContent(this.href.substring(this.href.indexOf('#'), this.href.length));
		return false;
	});
}

/* 
* function for activating/deactivating  content shown in the main content area.
* - active-subcontent marks menu-item
* - visible-subContent marks content container
*/
function activateSubContent(idSelector) {
	if (idSelector) {
		jQuery('#content .visible-subContent')
			.removeClass('visible-subContent')
			.fadeOut('slow');
		jQuery(idSelector)
			.addClass('visible-subContent')
			.fadeIn();
		jQuery('.activator').css('visibility','visible');
	} else {
		jQuery('.active-subcontent')
			.removeClass('active-subcontent')
			.removeClass('chameleon');
		jQuery('.active-link').removeClass('active-link');
		jQuery('#content .visible-subContent')
			.removeClass('visible-subContent')
			.fadeOut();
	}
	hideUnselectedTips();
}
/* 
* change the highlightcolor and fade all static colored elements
*/
function chameleon(color) {
	if (color) highlightColor = color;
	jQuery('.chameleon, .highlighted').animate({backgroundColor:highlightColor}, 1500);
	jQuery('a').not('.static-color').animate({color:highlightColor}, 1500);
}

function loaderStatus(message) {
	jQuery('#loader div').html(message);
}

// init code: on sucess load with player, onerror without player.
soundManager.onload = function() {
	jQuery(document).ready(function() {
		// call the init function.
		init(true);
	});
};
soundManager.onerror = function() {
	jQuery(document).ready(function() {
		// call the init function.
		init(false);
	});
};

function createPlayer( playlistJQ, appendToSelector ) {
	var playerInstance = { // will be populated later
		play : function (index) {
			if (!index) {
				// this branch actually starts the sound
				this.setVolume();
				if (this.playlist[this.nowPlaying]) {
					chameleon(this.playlist[this.nowPlaying].chameleonColor);
					this.playlist[this.nowPlaying].play();
					this.updateTitle();
				}
				// check control status
				jQuery('.play', this.playerJQ).removeClass('play').addClass('pause');
				// activate playing marker
				jQuery('.show-on-play:not(.playing-'+this.nowPlaying+')').css('visibility','hidden');
				jQuery('.show-on-play.playing-'+this.nowPlaying).css('visibility', 'visible');
			} else {
				// this branch just sets the correct index, if provided and calls play() again
				try {
					index = parseInt(index);
					if (index < 0) index = 0;
					if (index >= this.playlist.length) index = this.playlist.length-1;
					if (index == this.nowPlaying) {
						jQuery('.play, .pause', this.playerJQ).click();
					} else {
						if (this.playlist[this.nowPlaying]) this.playlist[this.nowPlaying].stop();
						this.nowPlaying = index;
						this.play();
					}
				} catch (e) {}
			}
		},
		pause : function () {
			if (this.playlist[this.nowPlaying]) this.playlist[this.nowPlaying].pause();
		},
		togglePlay : function() {
			this.setVolume();
			if (this.playlist[this.nowPlaying]) {
				chameleon(this.playlist[this.nowPlaying].chameleonColor);
				this.playlist[this.nowPlaying].togglePause();
				// activate playing marker
				jQuery('.show-on-play:not(.playing-'+this.nowPlaying+')').css('visibility','hidden');
				jQuery('.show-on-play.playing-'+this.nowPlaying).css('visibility', 'visible');				
			}
		},
		stop : function() {
			if (this.playlist[this.nowPlaying]) {
				this.playlist[this.nowPlaying].stop();
				// hide markers
				jQuery('.show-on-play').css('visibility','hidden');
				this.setProgress(1);
				this.updateProgress();
			}
		},
		next : function() {
			if (this.playlist[this.nowPlaying] && this.playlist[this.nowPlaying].playState == 1) {
				this.stop();
				this.nowPlaying++;
				if (this.nowPlaying == this.playlist.length) this.nowPlaying = 0;
				this.stop();
				this.play();
			} else {
				this.nowPlaying++;
				if (this.nowPlaying == this.playlist.length) this.nowPlaying = 0;
			}
			this.updateTitle();
		},
		previous : function() {
			if (this.playlist[this.nowPlaying] && this.playlist[this.nowPlaying].playState == 1) {
				this.stop();
				this.nowPlaying--;
				if (this.nowPlaying < 0) this.nowPlaying = this.playlist.length-1;
				this.stop();
				this.play();
			} else {
				this.nowPlaying--;
				if (this.nowPlaying < 0) this.nowPlaying = this.playlist.length-1;
			}
			this.updateTitle();
		},
		setVolume : function(volume) {
			if (volume) this.volume = volume;
			if (this.playlist[this.nowPlaying]) this.playlist[this.nowPlaying].setVolume(this.volume);			
		},
		// this updates all id3 monitors and resets the buffer
		updateTitle: function () {
			songname = '';
			trackNumber = '';
			if (!this.playlist[this.nowPlaying]) return;
			if (this.playlist[this.nowPlaying].id3['songname']) {
				id3 = this.playlist[this.nowPlaying].id3;
				songname = id3['songname'];
				trackNumber = id3['track'] ? (id3['track']) : '';
			} else {
				 songname = this.playlist[this.nowPlaying].sID;
			}
			this.titleJQ.html(songname);
			this.trackNoJQ.html(trackNumber);
			this.updateProgress();
			this.updateBuffer();
		},
		isPlaying : function () {
			if (!this.playlist[this.nowPlaying]) return 0;
			return this.playlist[this.nowPlaying].playState;
		},
		// placeholder
		onLeftPeak : function (f) {
		},
		onRightPeak : function (f) {
		},
		// this updates the progress according to the currently active song
		updateProgress: function () {
			if (!this.playlist[this.nowPlaying]) return;
			if (this.progressSlider.data('noUpdate') === true) return;
			if (this.playlist[this.nowPlaying].readyState == 3) {
				duration = this.playlist[this.nowPlaying].duration
			} else {			
				duration = this.playlist[this.nowPlaying].durationEstimate;
			}
			progress = this.playlist[this.nowPlaying].position;

			if (!progress || !duration || 0 == duration) return;
			// calculate percent
			if ( 0 == duration ) return;
			position = Math.round(progress/duration * 1000);
			this.progressSlider
				.data('playerProgress', position)
				.slider('value', position);
			seconds = Math.round(progress / 1000);
			minutes = Math.floor(seconds / 60);
			seconds -= minutes*60;
			if (seconds < 10) seconds = '0'+seconds;
			if (minutes < 10) minutes = '0'+minutes;
			this.elapsedJQ.html(minutes + ' : ' + seconds);
			
		},
		// and this one percent to set a song-position
		setProgress: function (position) {
			if (position == this.progressSlider.data('playerProgress')) return;
			if (!this.playlist[this.nowPlaying]) return;
			duration = 0;
			if (this.playlist[this.nowPlaying].readyState == 3) {
				duration = this.playlist[this.nowPlaying].duration;
			} else {			
				duration = this.playlist[this.nowPlaying].durationEstimate;
			}
			// don't jump further than loaded
			progress = Math.min(Math.round(position/1000 * duration), this.playlist[this.nowPlaying].duration);
			this.playlist[this.nowPlaying].setPosition(progress);
		},
		updateBuffer : function(loaded, total) {
			if (!loaded || !total) {
				this.bufferedJQ.css({width: '0px'});			
			} else {
				ratio = loaded / total;
				this.bufferedJQ.css( {width: Math.round(184 * ratio) +'px'} );
			}
		},
		toggleMute : function () {},
		init: function() {
			// create player container
			this.playerJQ = jQuery('<div class="player"></div>');
			// create volume control
			this.playerJQ.append('<div class="volume"></div>');
			this.playerJQ.append('<div class="controls"><div class="control previous"></div><div class="control play"></div><div class="control stop"></div><div class="control next"></div></div>');
			this.playerJQ.append('<div class="progress-bar"></div>');
			this.volumeSlider = jQuery('.volume', this.playerJQ).slider({
				axis: 'horizontal',
				animate: true,
				range: "min",
				min: 0,
				max: 100,
				value: 75,
				slide: function (e, ui) {
					jQuery(this).data('supervisor').setVolume(ui.value);
				}
			}).data('supervisor', this);
			this.progressSlider = jQuery('.progress-bar', this.playerJQ).slider({
				axis: 'horizontal',
				animate: false,
				range: "min",
				min: 0,
				max: 1000,
				value: 0,
				start: function(e, ui) {
					// dismiss progress update while sliding!
					jQuery(this).data('noUpdate', true);
				},
				stop: function (e, ui) {
					jQuery(this).data('supervisor').setProgress(ui.value);
					// re-enable progress updates
					jQuery(this).data('noUpdate', false);
				}
			}).data('supervisor', this).data('playerProgress', 0);
			// create previous control
			jQuery('.previous', this.playerJQ).data('supervisor', this).click(function () {
				jQuery(this).data('supervisor').previous();
			});
			// create play/pause control
			jQuery('.play', this.playerJQ)
				.data('supervisor', this)
				.click(function () {
					jQuery(this).toggleClass('play').toggleClass('pause').data('supervisor').togglePlay();
				});
			jQuery('.pause', this.playerJQ)
				.data('supervisor', this)
				.click(function () {
					jQuery(this).toggleClass('play').toggleClass('pause').data('supervisor').togglePlay();
				});
			// create stop control
			jQuery('.stop', this.playerJQ)
				.data('supervisor', this)
				.click(function () {
					jQuery('.pause', jQuery(this).data('supervisor').playerJQ)
						.addClass('play')
						.removeClass('pause');
					jQuery(this)
						.data('supervisor')
						.stop();
				});
			// create next control
			jQuery('.next', this.playerJQ).data('supervisor', this).click(function () {
				jQuery(this).data('supervisor').next();
			});
			// create monitors
			this.monitorJQ = jQuery('<div class="monitors"></div>').appendTo(this.playerJQ);
			this.trackNoJQ = jQuery('<div class="tracknumber"></div>').appendTo(this.monitorJQ);
			this.titleJQ = jQuery('<div class="trackinfo">Loading...</div>').appendTo(this.monitorJQ);
			this.elapsedJQ = jQuery('<div class="elapsed"></div>').appendTo(this.monitorJQ);
			this.bufferedJQ = jQuery('<div class="buffered chameleon"></div>').appendTo(this.playerJQ);
			
			// create playlist
			var elements = jQuery("a", playlistJQ).get();
			if (elements.length == 0) return;
			for (i = 0; i<elements.length; i++) {
				title = elements[i].innerHTML;
				this.playlist[i] = soundManager.createSound({ 
					id:title, 
					url:elements[i].href,
//					autoLoad: (i = 0 ? true : false), // preload the 1st song only
					onfinish: function () { this.player.next(); this.player.play(); },
					onid3: function () {
						this.player.updateTitle()
					},
					whileloading: function() {
						this.player.updateBuffer(this.bytesLoaded,this.bytesTotal);
					},
					onload: function() {
						this.player.updateBuffer();
					},
					whileplaying: function() {
						this.player.updateProgress();
						this.player.onLeftPeak(this.peakData.left*100 / this.volume);
						this.player.onRightPeak(this.peakData.right* 100 / this.volume);
					}
				});
				this.playlist[i].player = this;
				this.playlist[i].chameleonColor = elements[i].title;
			}
			// initialize with first track
			this.next();
			// add player to DOM
			this.playerJQ.appendTo(appendToSelector);
			// initialize volume on 75%
			this.volumeSlider.slider('moveTo', 75);
			// fade to 1st song
			chameleon(this.playlist[0].chameleonColor);
		},
		nowPlaying : -1,
		playlist : new Array(),
		volume : 100,
		slider : null
	};  
	playerInstance.init();
	return playerInstance;
}
