/*	
	functions.js
	===============================================================
	Panoramica
	_______________________________________________________________
*/

/*	
	@ to_hex
	@ rgb_to_hex
	@ get_theme_color
  ---------------------------------------------------------------
	Gets an element's colour from the stylesheet.
	_______________________________________________________________
*/			

	function to_hex(N) 
	{
		// http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtoHex.htm		
	 if (N === null) 
	 {
		 return "00";
	 }
	 N = parseInt(N, 10); 
	 if (N === 0 || isNaN(N)) 
	 {
		 return "00";
	 }
	 N = Math.max(0,N); 
	 N = Math.min(N,255); 
	 N = Math.round(N);
	 return ("0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16));
	}		
	
	function rgb_to_hex(color)
	{	
		//console.debug( "rgb_to_hex('", color, "')");
	
		// FF formats the color as RGB, so we need to convert it to hex for sIFR
		if (color.indexOf('rgb') != -1)		
		{
			// rgb(193, 19, 30)
			var colors = color.replace('rgb(', '');
					colors = colors.replace(')', '');
					colors = colors.replace(' ', '');		
			
			// 193,19,30
			var colors_array = colors.split(',');
			var r = colors_array[0];
			var g = colors_array[1];						
			var b = colors_array[2];
	
			// http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtoHex.htm
			var hex_string = ('#' + to_hex(r) + to_hex(g) + to_hex(b));
			
			return (hex_string.toLowerCase());
		}
		else
		{			
			// IE already formats the color as hex
			return (color.toLowerCase());
		}
	}	

	function get_theme_colour(what)
	{				
		var theme_colour;
		
		if (what == 'bg')
		{			
			theme_colour = rgb_to_hex( glow.dom.get('#shell').css('background-color') ).substring(1); // substring strips leading '#'		
		}
		else if (what == 'fg')
		{
			theme_colour = rgb_to_hex( glow.dom.get('#soundcloud-player').css('border-top-color') ).substring(1); // substring strips leading '#'		
		}

		return theme_colour;			
	}
	
/*	
	@ embed_soundcloud_player
  ---------------------------------------------------------------
	color - uses theme link color:
	play button background (gradient), 
	unbuffered waveform foreground,
	buffered waveform background (gradient),
	hovered set track title background,
	info text link color
	
	Always #fff / grey??:
	text color,
	button foreground / icon color
	
	comments_color:
	not sure as no comments yet, could be the text colour, doesn't look the background color is affected
	
	theme_color:
	background color - uses page bg color	
	
	soundcloud_player is a global here so that we can control it via the SC API outisde of this function
	
	http://www.schillmania.com/projects/soundmanager2/doc/				

	Methods tested and working in FF3.5:
	soundcloud_player.movie.play()
	soundcloud_player.movie.stop()	
	soundcloud_player.movie.pause()	
	soundcloud_player.movie.prev()				
	soundcloud_player.movie.next() - can call multiple times to skip to a certain track to fake 'randomisation'
	soundcloud_player.movie.setVolume(50) - does not update slider tho
	
	soundcloud_player.movie.load(trackNum - 1)		
	_______________________________________________________________
*/		

	//var soundcloud_player;
	//soundcloud.debug = true;
	
	var soundcloud_player_sc = false; // global reference for sc control
	var progress_timer = false;
	var sc_current = 0;
	var sc_current_duration = 0;

	function embed_soundcloud_player()
	{
		soundcloud_player_glow = new glow.embed.Flash('http://player.soundcloud.com/player.swf', 
		'#soundcloud-player', 
		'9.0.124',
		{
			height: soundcloud_height,
			width: '99%', /* else last couple of px sometimes not rendered, hiding RHS of player */
			message: '', /* noflash - 'false' sans quotes also seems to work ok here */
			id: 'panplayer',
			name: 'panplayer',			
			params: {
				allowscriptaccess: 'always',
				bgcolor: get_theme_colour('bg'), /* bgcolor while loading */
				flashVars: {  
					enable_api: true, 
					object_id: 'panplayer',
					url: soundcloud_url,
					auto_play: 'true', // false makes api play fail in safari
					color: get_theme_colour('fg'),						
					download: 'false',			
					sharing: 'true',						
					show_artwork: 'false',						
					show_comments: 'true',
					show_playcount: 'false',
					theme_color: get_theme_colour('bg')				
				}
			}				
		});
		soundcloud_player_glow.embed();
		
		// if flash embedded ok, remove the warning and output a heading
		if (soundcloud_player_glow.movie) // or, soundcloud_player.isSupported
		{
			glow.dom.create('<h3>')
			.addClass('player-heading')
			.text('Listen:')
			.insertBefore('#soundcloud-player');
			
//			glow.dom.create('<h4 class="track-info">')
//			.append( glow.dom.create('<span>').text('Now playing: ') )
//			.append( glow.dom.create('<span>').addClass('track-number') )
//			.append( glow.dom.create('<span>').addClass('track-name') )
//			.append( glow.dom.create('<span>').addClass('track-duration') )							
//			.insertAfter('.player-heading');	
			
			glow.dom.get('#warning')
			.remove();
		}
		else
		{
			glow.dom.get('#warning p.summary')
			.empty()
			.append(
				glow.dom.create('<span>')		
				.text('You appear to have an ')
			)
			.append(
				glow.dom.create('<strong>')
				.text('old version of Flash')
			)
			.append(
				glow.dom.create('<span>')		
				.text('. ')
			);
			
			glow.dom.get('#warning .action span')
			.text('Upgrade Flash Player');
			
			glow.dom.get('#warning .action a')			
			.attr({
				href : 'http://get.adobe.com/flashplayer/'					
			});
		}
		
		// Tell the SoundCloud player to start playing
		// note that SC event listeners require jQuery rather than Glow	(jQuery now disabled and still working)
		soundcloud.addEventListener('onPlayerReady', 
			function(player, data) 
			{
				sc_init();						
			}
		);		
		
//		soundcloud.addEventListener('onMediaBuffering', 
//			function(player, data) 
//			{
//				glow.dom.get('.tracklisting dd.current .waveform-buffered').css({ width : ( data.percent + '%' ) });
//			}
//		);		
		
		soundcloud.addEventListener('onMediaEnd', 
			function(player, data) 
			{
//				clearTimeout( progress_timer );
				sc_play_next();						
			}
		);			
	}
	
	function sc_init()
	{
		soundcloud_player_sc = soundcloud.getPlayer('panplayer'); // optional but probably a good habit to get into		
//		sc_tracklisting_buttons();	
//		sc_play_random();
			sc_play(1);
	}
	
	function sc_tracklisting_buttons()
	{		
		var dd_tracks = glow.dom.get('.tracklisting dd.track');		
		
		dd_tracks.each(
			function(i) 
			{
				var _this = dd_tracks.slice( i-1, i );
				
				// INJECT A BUTTON, TO ALLOW THIS TRACK TO BE PLAYED
				_this.get('dd.waveform')
				.append( glow.dom.create('<button>').attr({ type : 'button', id : ( 'button_' + i ), title : ( 'Play track ' + i ) })
					.append( glow.dom.create('<span>').text('Play') )			
				);
				
				// ADD CLICK LISTENER TO BUTTON, TO PLAY THIS TRACK		
				glow.events.addListener( ( '#button_' + i ), 'click', 			
					function () 
					{
						var id = glow.dom.get(this).attr('id');
						//console.log( 'clicked: ' + id );
						var id_n = id.replace('button_', '');

						sc_play(id_n);
					}
				)			
			}
		); 	
	}
	
	function sc_tracklisting_highlight( n )
	{
		var dt_tracks = '.tracklisting dt.track';
		var dd_tracks = '.tracklisting dd.track';
		
		glow.dom.get(dd_tracks).each(
			function(i) 
			{
				// add click listener, to play this track
				if ( i == n )
				{					
					//glow.dom.get(dd_tracks).slice( i-1, i ).addClass('current');
					glow.dom.get(this).addClass('current');		
					glow.dom.get(dt_tracks).slice( i, (i+1) ).addClass('current');						
				}
				else
				{		
					glow.dom.get(this).removeClass('current');			
					glow.dom.get(dt_tracks).slice( i, (i+1) ).removeClass('current');					
				}
			}
		); 
	}
	
	function sc_play( n )
	{
		var t = (n - 1);
		//soundcloud_player_sc.api_skip( t ); // 0 based array
		soundcloud_player_sc.api_play();	
//		sc_tracklisting_highlight( t );	
//		var current_track_name = glow.dom.get('.tracklisting dt.title').slice( t, (t+1) ).text();
//		var current_track_duration = glow.dom.get('.tracklisting dd.duration').slice( t, (t+1) ).text();		
		
//		glow.dom.get('.track-number').text( '#' + n + ': ' );
//		glow.dom.get('.track-name').text( "'" + current_track_name + "'" );
//		glow.dom.get('.track-duration').text( ' | ' + current_track_duration );	
		
		sc_current = n;
//		sc_current_duration = soundcloud_player_sc.api_getTrackDuration();		
//		sc_progress();
	}
	
	function sc_play_next()
	{
		sc_play( sc_current + 1 );
	}
	
	function sc_play_random()
	{
		var num_tracks = soundcloud_player_sc.api_getTracks().length;
		var random_track = Math.floor( Math.random() * ( num_tracks + 1 ) );
		sc_play( random_track );
	}	

	function sc_progress()
	{		
		var play_percent = ( ( ( soundcloud_player_sc.api_getTrackPosition() / sc_current_duration ) * 100 ) + '%' );
		glow.dom.get('.tracklisting dd.current .waveform-playing').css({ width : play_percent });
		setTimeout ( "sc_progress()", 500 );			
	}
	
/*	
	move_footer()
	---------------------------------------------------------------
	Ensure that the footer bg image sits at the bottom of the viewport
	
	if (shell_liner_height != viewport_height) // < or >

	// <
	// main height is less than the browser height
	// so stretch the height of main to push the footer down.
	// increasing the height by the amount that the shell is shorter than the browser window		
	
	// >
	// main height is stretched to push footer down
	// this makes it too high when the window is resized down
	// so reduce the height by the amount that is now taller than the browser window		
	_______________________________________________________________
*/	
	
	function move_footer() 
	{
		if ( glow.dom.get('#shell').length > 0 )
		{
			glow.dom.get('body').addClass('stretched'); // remove noscript btm borders/extra padding below p.top, before calculating height
			
			// Push the footer down to the foot of the page, by setting a minimum height on the preceding div#main			
			var shell_liner_height = glow.dom.get('#shell > div > div').height();			

			// Push the footer down to the foot of the page, by setting a minimum height on the preceding div#main
			var viewport_height = glow.dom.get(window).height();

			var div_body = glow.dom.get('#body');
			
			if (shell_liner_height != viewport_height)
			{	
				new_height = ( div_body.height() + (viewport_height - shell_liner_height) );
				new_height_px = (new_height + 'px');
			
				if (glow.env.ie < 7)
				{						
					div_body.css('height', new_height_px);
				}
				else 
				{
					div_body.css('min-height', new_height_px);			
				}					
			}
		}
	}
	
/*	
	activate_faux_links()
	---------------------------------------------------------------
	Make elements with 'a blur' classname act like links
	_______________________________________________________________
*/		
	
	function activate_faux_links()
	{	
		var faux_links = glow.dom.get('.a');
		
		glow.events.addListener( faux_links, 'mouseover', 
			function () 
			{
				glow.dom.get(this).removeClass('blur');
				glow.dom.get(this).addClass('hover');				
			}
		);	
		
		glow.events.addListener( faux_links, 'mouseout', 
			function () 
			{
				glow.dom.get(this).removeClass('hover');
				glow.dom.get(this).addClass('blur');				
			}
		);					
	}
	
/*	
	request_theme_image_details()
	---------------------------------------------------------------
	Get theme details from Flickr and display
	Originally from Dan Smith - Life 
	_______________________________________________________________
*/		

	function request_theme_image_details(serverside_script)
	{
		create_theme_image_details_holder();		
		
		glow.net.get(serverside_script, {
			onLoad: 
				function(response) 
				{			
					// is selector syntax causing an error in IE8??
					glow.dom.get('#themeinfo > .section > .liner').html( response.text() ); // replace loading msg contents	
					
				},
			onError: 
				function(response) {
					// response.statusText());
					// is this causing an error in IE8??
					glow.dom.get('#status').text('Sorry, theme information not available - please check your internet connection or try again later. ');		
				}
		});			
	}
	
/*	
	create_theme_image_details_holder() - Glow
	---------------------------------------------------------------
	Get theme details from Flickr and display
	Originally from Dan Smith - Life
	_______________________________________________________________
*/			
	
	function create_theme_image_details_holder()
	{	
		glow.dom.create('<div>').addClass('panel').attr('id', 'themeinfo' )
		.append(
			glow.dom.create('<h3>')
			.append(
				glow.dom.create('<span>').text('Featured picture:' )
			)
		)
//			.append(
//				glow.dom.create('<p>' ).addClass('note').text('Background info about this theme. ')
//			)
			.append(
				glow.dom.create('<div>').addClass('section')
				.append(
					glow.dom.create('<div>').addClass('liner')
					.append(
						glow.dom.create('<p>').attr('id', 'status')
						.append(								
							glow.dom.create('<img>').attr({ 
								src : '/_resources/v2/ui/images/inline/animations/loader/gray_busy.gif', 
								width : '29', 
								height : '5', 
								alt : 'Loading...' 
							})
						)
						.append(
							glow.dom.create('<span>').text('Loading theme details..')			
						)
						.append(							
							glow.dom.create('<div>').addClass('clear')		
						)											
					)
				)			
			)			
			.appendTo( 
				glow.dom.get('#related') 
			);		
	}
	
/*	
	make_frames_clickable()
	---------------------------------------------------------------
	Make index .frames clickable, so that even empty frames
	(ie with no image) can be clicked	
	_______________________________________________________________
*/

	function make_frames_clickable() 
	{	
		glow.dom.get('#main > div > div').each(
			function()
			{
				var this_div = glow.dom.get(this);
				
				if ( this_div.hasClass('post') && this_div.hasClass('a') && this_div.hasClass('blur') )
				{					
					glow.events.addListener( this_div, 'click', 
						function () 
						{
							window.location = glow.dom.get(this_div).get('a').attr('href');
						}
					);
					
					glow.events.addListener( this_div, 'mouseover', 
						function () 
						{							
							window.status = glow.dom.get(this_div).get('a').attr('href');
						}
					);																	
					
					glow.events.addListener( this_div, 'mouseout', 
						function () 
						{
							window.status = '';
						}
					);						
				}
			}
		);
	}	
	
/*	
	remove_spam_trap()
	---------------------------------------------------------------
	Prevent keyboard users from focussing spam trap.
	Removal is the best option as forcing the focus on to the
	next element would prevent users from tabbing through a form 
	backwards.
	
	Note that the parent div is left in as it contains a hidden input
	which is required by the form.
	_______________________________________________________________
*/	
	
	function remove_spam_trap()
	{
		glow.dom.get('#honeypot-error').remove();
		glow.dom.get('#honeypot').remove();		
	}
	
/*	
	enhance_accessibility_panel()
	---------------------------------------------------------------
	_______________________________________________________________
*/		
	
	function enhance_accessibility_panel()
	{
		var accessibility, wrapper;
		
		wrapper = glow.dom.get( '#accessibility .wrapper' );
		
			wrapper.addClass( 'access' );
		
			glow.dom.create('<button></button>')
			.text( '+' )
			.attr('title', 'Show page options') 
			.attr('id', 'accessibility-toggle')
			.attr('type', 'button')
			.insertBefore(wrapper);
		
			glow.events.addListener( '#accessibility-toggle', 'mouseover', 			
				function () 
				{
					_this = glow.dom.get( '#accessibility-toggle' );
					_this.addClass('focus');
				}
			)		
		
			glow.events.addListener( '#accessibility-toggle', 'focus', 			
				function () 
				{
					_this = glow.dom.get( '#accessibility-toggle' );
					_this.addClass('focus');
				}
			)
			
			glow.events.addListener( '#accessibility-toggle', 'mouseout', 			
				function () 
				{
					wrapper = glow.dom.get( '#accessibility .wrapper' );
					if ( wrapper.hasClass('access') )
					{					
						_this = glow.dom.get( '#accessibility-toggle' );
						_this.removeClass('focus');
					}
				}
			)						
			
			glow.events.addListener( '#accessibility-toggle', 'blur', 			
				function () 
				{
					_this = glow.dom.get( '#accessibility-toggle' );
					_this.removeClass('focus');
				}
			)			
			
			glow.events.addListener( '#accessibility-toggle', 'click', 
				function () 
				{
					_this = glow.dom.get( '#accessibility-toggle' );
					
					wrapper = glow.dom.get( '#accessibility .wrapper' );
					if ( wrapper.hasClass('access') )
					{
						wrapper.removeClass('access');
						_this			
						.text( '-' )
			 			.attr('title', 'Hide page options');					
					}
					else
					{
						wrapper.addClass('access');
						_this					
						.text( '+' )
			 			.attr('title', 'Show page options');				
					}
				}
			);			 
	}
