$(document).ready(function() {
	$(document).bind('soundcloud:onMediaEnd', function() { changeTitle(null); });
	$(document).bind('scPlayer:onMediaPause', function() { changeTitle(null); });
});

function playCount( player ) {
	var trackId = player.find('.sc-trackId').html();

	if ( ! trackId ) {
		return;
	}

	var key = 'playcount-' + trackId;

	if ( $.cookie( key ) == null ) {
		$.get( __BASEURL__ + '/track-logview', { sc_id: trackId } );
		$.cookie( key, true, { expires: 365, path: '/'  } );
	}
}

function get_ents( str ) {
	var temp = document.createElement("pre");
	temp.innerHTML = str;
	return temp.firstChild.nodeValue;
}

var theTitle = '';
function changeTitle( player ) {
	if ( player == null ) {
		if ( theTitle ) {
			$(document).attr('title', theTitle);
			theTitle = '';
		}
	}
	else {
		if ( theTitle == '' ) {
			theTitle = $(document).attr('title');
		}
		
		$(document).attr('title', get_ents( '\u25B6 ' + player.find('.sc-titleText').html()));
	}
}

function stopSCPlayer() {
	if ( scPlayerType == 'html' ) {
		try {
			eng = soundcloud.getPlayer('scPlayerEngine');
			if ( eng != undefined ) {
				eng.api_stop();
				changeTitle( null );
			}
		}
		catch( err ) {}
	}
}

var lastOnMediaEndFunction = null;

function createSCPlayer( settings ) {
	var $container = $(settings.container);
	var elementId = $container.attr('id') + '-player';
	$container.html('<div id="' + elementId + '"></div>');

	var width = "600px";
	var height = "80px";
	
	if ( settings.width ) {
		width = settings.width;
	}

	if ( settings.height ) {
		height = settings.height;
	}

	if ( scPlayerType == 'flash' ) {
		var flashvars = {
			enable_api: true,
			object_id: elementId,
			url: settings.media_url,
			color: '#ffb924',
			theme_color: '#080808',
			waveform_color: '#ffb924'

		};

		var params = {
			allowscriptaccess: "always",
			wmode: "transparent"
		};

		var attributes = {
			
		};

		swfobject.embedSWF("http://player.soundcloud.com/player.swf", elementId, width, height, "9.0.0","expressInstall.swf", flashvars, params, attributes);

		if ( settings.autoPlay ) {
			$(document).unbind('soundcloud:onPlayerReady');
			$(document).bind('soundcloud:onPlayerReady', function( event ) {
				event.target.api_play();
			});
		}
	}
	else {
		$('#' + elementId).scPlayer({
			links: [{url: settings.media_url, title: settings.media_url}],
			autoPlay: settings.autoPlay,
			titleText: settings.titleText,
			trackId: settings.trackId
		});
	}

	if ( typeof settings.onMediaEnd == 'function' ) {
		if ( lastOnMediaEndFunction != null ) {
			$(document).unbind('soundcloud:onMediaEnd', lastOnMediaEndFunction);
		}

		lastOnMediaEndFunction = settings.onMediaEnd;
		$(document).bind('soundcloud:onMediaEnd', settings.onMediaEnd);
	}
}

$(document).ready(function () {
	
	//$('#nav ul').append('<li class="bg"></li>');
	
	/*$("#djtool-trigger").click(function () {
		alert("This will open the DJ Tool, but it's not available yet");
	});*/
	
});

var promoRotator = function() {
	var _current = 0;
	var _containerID;
	var _promoList;
	var _autoRotateDuration;
	var _intervalID;

	var _private = {};

	var _public = {
		nextStep: function() {
			_public.displayStep( _current + 1 );
		},

		displayStep: function( step ) {
			window.clearInterval( _intervalID );

			if ( step < 1 || step > _promoList.length ) {
				step = 1;
			}

			var firstRun = false;
			if ( _current == 0 ) {
				firstRun = true;
			}

			if ( ! firstRun ) {
				var promo_before = _promoList[ _current - 1 ];
				$('#' + _containerID + ' .promoContent-back').css('background-image', 'url(' + promo_before.picture + ')');
				$('#' + _containerID + ' .promoContent-back .title').html( promo_before.title );
				if (promo_before.text_color) {
					$('#' + _containerID + ' .promoContent-back .title').css({color: '#' + promo_before.text_color});
				}
				else {
					$('#' + _containerID + ' .promoContent-back .title').css({color: '#FFDD00'});
				}
				
				$('#' + _containerID + ' .promoContent-back').show();
			}

			_current = step;

			var promo = _promoList[ _current - 1 ];
			
			//console.log(promo);
			
			$('#' + _containerID).unbind('click');
			$('#' + _containerID + ' .promoContent').click(function() {
				if ( promo.url.length > 0 ) {
					if ( promo.openInNewWindow ) {
						window.open( promo.url, '_blank', '' );
					}
					else {
						window.location.href = promo.url;
					}
				}
			});

			$('#' + _containerID + ' .promoNavigation .steps .step').removeClass('active');
			$('#' + _containerID + ' .promoNavigation .steps .step:eq(' + (_current - 1) + ')').addClass('active');
			$('#' + _containerID + ' .promoContent .title').html( promo.title );
			if (promo.text_color) {
				$('#' + _containerID + ' .promoContent .title').css({color: '#' + promo.text_color});
			}
			else {
				$('#' + _containerID + ' .promoContent .title').css({color: '#FFDD00'});
			}				
			$('#' + _containerID + ' .promoNavigation .counter .current').html( _current );
			$('#' + _containerID + ' .promoContent').css('background-image', 'url(' + promo.picture + ')');

			if ( ! firstRun ) {
				$('#' + _containerID + ' .promoContent-back').fadeOut('slow');
			}

			if ( _autoRotateDuration > 0 ) {
				_intervalID = window.setInterval( _public.nextStep, _autoRotateDuration );
			}
		},

		init: function( containerID, promoList, autoRotateDuration ) {
			_containerID = containerID;
			_promoList = promoList;
			_autoRotateDuration = autoRotateDuration;

			$('#' + _containerID).append('<div class="promoContent"></div>');
			$('#' + _containerID + ' .promoContent').append('<div class="title"></div>');
			
			$('#' + _containerID).append('<div class="promoContent-back"></div>');
			$('#' + _containerID + ' .promoContent-back').append('<div class="title"></div>');
			
			$('#' + _containerID).append('<div class="promoNavigation"></div>');
			$('#' + _containerID + ' .promoNavigation').append('<ul class="steps clr"></ul>');
			$('#' + _containerID + ' .promoNavigation').append('<div class="counter"></div>');

			if ( _promoList.length > 0 ) {
				for( var i = 1; i <= _promoList.length; ++i ) {
					$('#' + _containerID + ' .promoNavigation .steps').append('<li id="' + _containerID + '-step' + i + '" class="step">' + i + '</li>')
					$('#' + _containerID + ' .promoNavigation .steps #' + _containerID + '-step' + i).click(function( event ) {
							event.stopImmediatePropagation();
							_public.displayStep( $(this).attr('id').substr( _containerID.length + 5 ) );
							return false;
					});
				}

				$('#' + _containerID + ' .promoNavigation .counter').html('<span class="current">' + _current + '</span>/' + _promoList.length);

				_public.nextStep();
			}
		}
	}

	return _public;
}();

// Disable sc-player auto-load
if ( $.scPlayer != undefined ) {
	$.scPlayer.defaults.onDomReady = null;
}

/**
 * Youtube button function for the tinymce
 */
function setupYouTubeButton(ed) {
	ed.addButton('youtube', {
	title : 'YouTube',
	image : __BASEURL__ + '/images/youtube.gif',
	onclick : function() {
					   if (videoUrl = prompt('Insert here the Youtube video URL:')) {
					
		           var str;

							 var width = 560;
							 var height = 340;
		
		           if (videoUrl.match(/youtube.com/i)) {
                 var regexp = /www.youtube.com\/watch\?v=(.{11}).*/i;
                 var match = regexp.exec(videoUrl);
                 if (match != null) {
                   videoId = match[1];
                   str = '<object width=\"' + width + '" height=\"' + height + '\" style=\"display: block; margin: 0 auto;\">';
                   str += '<param name=\"movie\" value=\"http://www.youtube.com/v/'+videoId+'?fs=1&amp;hl=en_US\"></param>';
                   str += '<param name=\"allowFullScreen\" value=\"true\"></param>';
                   str += '<param name=\"allowscriptaccess\" value=\"always\"></param>';
                   str += '<embed src=\"http://www.youtube.com/v/'+videoId+'?fs=1&amp;hl=en_US\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"' + width + '\" height=\"' + height + '\"></embed>';
                   str += '</object>';
                 }
		           }
		
		           if (str == '') {
                 alert('Wrong URL!');
                 return;
		           } else {
								 ed.focus();

								img = ed.dom.create('img', {
									//id : data.id,
									//style : data.style,
									//align : data.align,
									src : ed.theme.url + '/img/trans.gif',
									'class' : 'mceItemMedia mceItemFlash',
									'data-mce-json' : tinymce.util.JSON.serialize({'object_html': str}, "'")
								});

								img.width = width;
								img.height = height;

								ed.selection.setNode( img );

								 //ed.selection.setContent(str);
								 ed.execCommand('mceRepaint');
		           }
					   }
					}
	});
}
