(function($) {

  $.fn.threadsPlayer = function(options) {
  	
  	var tp = $.fn.threadsPlayer;
  	
// -------------------------------------------
// member vars
// -------------------------------------------
  
		tp.isPlaying = false;
		tp.hasBeenPlayed = false;
		tp.currentResponse = null;

// -------------------------------------------
// immutable member functions
// -------------------------------------------

  	tp.load = function(command) {
			$.ajax({
   			type: 'GET',
   			url: tp.settings.playlistUrl,
   			preload: 'auto',
   			dataType: 'jsonp',
   			jsonpCallback: 'jsonpCallback',
   			data: 'command='+command+'&collectionType='+tp.settings.collectionType+'&collectionId='+tp.settings.collectionId+'&trackId='+tp.settings.currentTrackId+'&uniqueId='+tp.settings.playerId+'&imageSize='+tp.settings.imageSize+'&playerType='+tp.settings.playerType,
   			success: function(response){
   				tp.currentResponse = response;
     			$('#threadsplayer').jPlayer('setMedia', { mp3 : response.url});
     			$('#threadsplayer_thumb').attr('src', response.image);
     			tp.play();
     			tp.updateTrackDetails(response);
   			}
			});
		};

		tp.showLoading = function() {
			//$('#threadsplayer_thumb').attr('src', tp.settings.loadingIconUrl);
		};
	
		tp.disableBuyButton = function() {
			console.log('hiding buy button');
			$('.threadsplayer_buy').hide();
		};
	
		tp.enableBuyButton = function() {
			$('.threadsplayer_buy').show();
		};
	
		tp.updateTrackDetails = function(response) {
			tp.settings.updateTrackDetailsPre(response);
			
			if(response.image != $('#threadsplayer_thumb').attr('src')) tp.showLoading();
			tp.settings.currentTrackId = response.id;
			tp.settings.facebookLikeUrl = response.facebookLikeUrl;
			
			if(response.embedUrl != undefined && response.embedUrl != '') {
  			tp.settings.embedUrl = response.embedUrl;
			}
			else tp.settings.embedUrl = null;
			
			tp.initializeEmbedButton();
			
   		tp.settings.collectionType = response.collectionType;
   		tp.settings.collectionId = response.collectionId;
    	$('#threadsplayer_artist').html(response.artist);
  		$('#threadsplayer_song').html(response.songTitle);
  		if(!tp.hasBeenPlayed) $('#threadsplayer_thumb').attr('src', response.image);
  		if(response.buyDetails != undefined && response.buyDetails != '') {
  			tp.enableBuyButton();
				$('#threadsplayer_buy_details').html(response.buyDetails);
			}
			else tp.disableBuyButton();
			
			if(response.other != undefined && response.other != '') $('#threadsplayer_other').html(response.other);
			else $('#threadsplayer_other').html('');
			
			tp.settings.updateTrackDetailsPost(response);
			
		}
		
		tp.resetSinglePlayers = function(target) {
  		$('.threadsplayer_single').each(function() {
  			if(target != this) $(this).children(':first').removeClass('ui-icon-pause').addClass('ui-icon-play');
  		});
  	}
  	
  	tp.play = function() {
  		tp.settings.playPre();
  		$('#threadsplayer').jPlayer('play');
  		$('a#threadsplayer_play').button('option', {
     		icons: { primary: 'ui-icon-pause' }
    	});
    	tp.isPlaying = true;
    	if(!tp.hasBeenPlayed) tp.hasBeenPlayed = true;
    	tp.settings.playPost();
  	}
  	
  	tp.pause = function() {
  		tp.settings.pausePre();
  		$('#threadsplayer').jPlayer('pause');
  		$('a#threadsplayer_play').button('option', {
     		icons: { primary: 'ui-icon-play' }
    	});
  		tp.isPlaying = false;
  		tp.settings.pausePost();
  	}
  	
  	// initialise the controls
  	tp.initializeControls = function() {
  	
  		// pre hook for extending
  		tp.settings.initializeControlsPre();
  	
  		// set the bindings to allow album playback
			$('#threadsplayer').bind($.jPlayer.event.ended, function(e) {
				tp.load('next');
			});
			
			$('#threadsplayer').bind($.jPlayer.event.loadstart, function(e) {
				if(tp.hasBeenPlayed) tp.showLoading();
			});
			
			$('#threadsplayer').bind($.jPlayer.event.progress, function(e) {
				if(e.jPlayer.status.duration > 0 && $('#threadsplayer_thumb').attr('src') == tp.settings.loadingIconUrl) {
					$('#threadsplayer_thumb').attr('src', tp.currentResponse.image);
					if($('#threadsplayer_progress')) $('#threadsplayer_progress').slider('enable');
				}
			});
		
		
  		$('#threadsplayer_play').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  			if(tp.isPlaying) {
  				tp.pause();
  			}
  			else {
  				tp.play();
  			}
  			tp.resetSinglePlayers(this);
  			return true;
  		});
		
			// initiate the link for previous track 
  		$('.jp-previous').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  			tp.load('previous');
  			tp.resetSinglePlayers(this);
  		});
  	
  		// initiate the link for next track 
  		$('.jp-next').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  			tp.load('next');
  			tp.resetSinglePlayers(this);
  		});
  		
  		// initiate the link for showing the social network buttons 
  		$('#threadsplayer_share').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  			var t = $('#threadsplayer_sn');
  			if(t.is(':hidden')) {
  				t.show().offset({ top: 0, left: 0 }).hide();
  				var pos = $('#threadsplayer_sn_wrapper').offset();
  				t.offset({ top: (pos.top + tp.settings.snOffsetTop), left: (pos.left + tp.settings.snOffsetLeft) });
  				t.slideDown(400);
  			}
  			else {
  				t.offset({ top: 0, left: 0 });
  				t.hide();
  			}
  		});
  
  	
  		// initiate the links for the single track players 
  		$('.threadsplayer_single').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  			tp.resetSinglePlayers(this);
  			
  			if($(this).children(':first').hasClass('ui-icon-play')) {
  				$(this).children(':first').removeClass('ui-icon-play').addClass('ui-icon-pause');
  				
  				$('a#threadsplayer_play').button('option', {
     				icons: { primary: 'ui-icon-pause' }
    			});
  				
  				if(tp.settings.currentTrackId == this.id) $('#threadsplayer').jPlayer('play');
  				else {
  					tp.settings.currentTrackId = this.id;
  					tp.load('current');
  				}
  			}
  			else {
  				$(this).children(':first').removeClass('ui-icon-pause').addClass('ui-icon-play');
  				$('a#threadsplayer_play').button('option', {
     				icons: { primary: 'ui-icon-play' }
    			});
  				$('#threadsplayer').jPlayer('pause');
  			}
  		});
  		
  		// post hook for extending
  		tp.settings.initializeControlsPost();
  	}
  	
  	// hide the buy container
  	tp.hideBuyContainer = function() {
  		if($('#threadsplayer_buy_details').is(':visible')) {
  	   	$('#threadsplayer_buy_details').dialog('close');
    		tp.menuIsOpen = false;
			}
		};
  	
  	// initialize the buy container
  	tp.initializeBuyContainer = function() {
  		
  		var ch = tp.settings.buyContainerHeight;
  		var cw = tp.settings.buyContainerWidth;
  	
	  	$('#threadsplayer_buy_details').dialog({ 
  			autoOpen: false 
  			, height: tp.settings.buyContainerHeight
  			, width:	tp.settings.buyContainerWidth
  			, show:		'fade'
  			, hide:		'fade'
  		});
  		
  		// initiate the link for the buy now button 
  		$('.threadsplayer_buy').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
     		if($('#threadsplayer_buy_details').dialog('isOpen')) {
     			tp.hideBuyContainer();
     		}
     		else {
     			$('#threadsplayer_buy_details').dialog('open');
     		}
     	});
     
     // handle clicks on the body to close the buy container
     	$(document).click(function(e) {
     		var t = e.target;
     		if($(t).parents($('#threadsplayer_buy_details')).length === 0) tp.hideBuyContainer();
				return true;
     	});
     
     	// handle clicks on links to close the buy container
     $('a').click(function(e) {
     		if(!$(this).hasClass('threadsplayer_buy')) tp.hideBuyContainer();
     		return true;
     	});  		
  		
  	};
  	
  	tp.initializeFBButton = function() {
  		if(tp.settings.facebookLikeUrl && $('#fb-root')) {
	  		$.getScript(document.location.protocol+'//connect.facebook.net/en_US/all.js', function() {
  				if($('#fb-root')) {
	  				$('html').attr('xmlns', 'http://www.w3.org/1999/xhtml');
						$('html').attr('xmlns:fb', 'http://www.facebook.com/2008/fbml');
						$('fb\\:like').attr('href', tp.settings.facebookLikeUrl);
  					FB.init({
  						'appId' : 	'137185016367699',
  						'status' : 	true,
  						'cookie' :	true,
  						'xfbml'	:		false
  					});
  					FB.XFBML.parse($('#fb-root')[0]);
  				}
  			});
  		}
  	};
  	
  	tp.initializeTwitterButton = function() {
  		$.getScript(document.location.protocol+'//platform.twitter.com/widgets.js', function() {});
  	
  		$('.twitter-share-button').click(function(e) {
  			e.stopPropagation();
  			e.preventDefault();
  		}); 
  	
  	};
  	
  	tp.initializeEmbedButton = function() {
  		if(tp.settings.embedUrl) {
	  		$('#threadsplayer_embed').show();
	  		$('#threadsplayer_embed').attr('href', tp.settings.embedUrl); 
  			$('#threadsplayer_embed').attr('target', '_blank'); 
  		}	
  		else $('#threadsplayer_embed').hide();
  	};
  		
  		
  	// style the controls using jquery ui 
  	tp.styleControls = function() {
  	
  		// pre hook for extending
    	tp.settings.styleControlsPre();
  	
  		$('a#threadsplayer_play').button({
     		icons: { primary: 'ui-icon-play' },
     		text: false
    	});
    
  		$('a.jp-next').button({
     		icons: { primary: 'ui-icon-seek-end' },
     		text: false
   		});
    
    	$('a.jp-previous').button({
  	 		icons: { primary: 'ui-icon-seek-first' },
     		text: false
   		});
    
    	$('a.threadsplayer_single').button({
   	 		icons: { primary: 'ui-icon-play' },
     		text: false
    	});
    
  		$('.threadsplayer_buy').button({
     		icons: { primary: 'ui-icon-cart' },
    		text: false
    	});
    	
    	$('#threadsplayer_share').button({
     		icons: { primary: 'ui-icon-comment' },
    		text: false
    	});
    	
    	$('#threadsplayer_embed').button({
     	
    	});
    	
    	// post hook for extending
    	tp.settings.styleControlsPost();
    	
  	};
  	
  	
  	tp.initializeStylesheets = function() {
  		var a = new Array();
  		$('head link').each(function(index) {
  			a.push($(this).attr('href'));
  		});
  		
  		$.each(tp.settings.css, function(index, value) {
  			if(jQuery.inArray(value, a) == -1) {
  				$('<link rel="StyleSheet" href="'+value+'" type="text/css" />').appendTo('head');
  			}
  		});
  		
  	};
 
 
// -------------------------------------------
// default settings & mutable methods
// -------------------------------------------
  
  	tp.settings = {
  		'playerId'									: null,
  		'playlistUrl' 							:	null,
  		'playerType'								: 'small',
  		'collectionId'							: null,
  		'collectionType'						: null,
  		'currentTrackId'						: null,
  		'loadingIconUrl'						: '/threads_assets/threadsplayer/img/threadsplayer_loading.gif',
  		'buyContainerWidth'					: 'auto',
  		'buyContainerHeight'				: 'auto',
  		'snOffsetTop'					 			:	4,
  		'snOffsetLeft'					 		:	0,
  		'css'												: [],
  		'facebookLikeUrl'						: null,
  		'embedUrl'									: null,
  		'templateUrl'								: null,
  		'showMainPlayer'						: true,
  		'imageSize'									: 70,
  		
  		'playPre'										: function() { },
  		'playPost'									: function() { },
  		'pausePre'									: function() { },
  		'pausePost'									: function() { },
  		'styleControlsPre'					: function() { },
  		'styleControlsPost'					: function() { },
  		'initializeControlsPre'			: function() { },
  		'initializeControlsPost'		: function() { },
  		'updateTrackDetailsPre'			: function(response) { },
  		'updateTrackDetailsPost'		: function(response) { }
  	};
  	
  	// merge the options & settings
  	if(options) $.extend(tp.settings, options);
  	
  	// override settings if an html version is available
  	if($('#threadsplayer_playerId')) tp.settings.playerId = $('#threadsplayer_playerId').text();
  	if($('#threadsplayer_collectionId')) tp.settings.collectionId = $('#threadsplayer_collectionId').text();
  	if($('#threadsplayer_collectionType')) tp.settings.collectionType = $('#threadsplayer_collectionType').text();
		if($('#threadsplayer_currentTrackId')) tp.settings.currentTrackId = $('#threadsplayer_currentTrackId').text();
		if($('#threadsplayer_facebookLikeUrl')) tp.settings.facebookLikeUrl = $('#threadsplayer_facebookLikeUrl').text();

// -------------------------------------------
// all method declarations must happen before here
// loop through all the selected DOM elements and do our thing
// -------------------------------------------

  	return this.each(function() {
  	
  		$this = $(this);
  		
  		// load stylesheets. we do it now so that the player is styled
 		 	// immediately after loading
	  	tp.initializeStylesheets();
  		
  		$.getScript('/threads_assets/threadsplayer/jquery.jplayer.min.js', function() {  	
	  		
	  		$.ajax({
  	 			type: 'GET',
   				url: tp.settings.templateUrl,
   				preload: 'auto',
   				dataType: 'jsonp',
   				jsonpCallback: 'jsonpCallback',
   				success: function(response) {
   				
   					if(tp.settings.showMainPlayer) {
	   					$this.wrap('<div id="threadsplayer_wrapper"></div>');
  	 					$('#threadsplayer_wrapper').append(response.html);	
	 	 					// add the loading icon
							$('<img src="'+tp.settings.loadingIconUrl+'" alt="loading" id="threadsplayer_thumb" />').appendTo('#threadsplayer_thumb_wrapper');
 						}
 						tp.styleControls();
 
  					// initialise jPlayer and load the first track 
						$.ajax({
  	 					type: 'GET',
   						url: tp.settings.playlistUrl,
   						dataType: 'jsonp',
   						jsonpCallback: 'jsonpCallback',
   						data: 'command=current&collectionType='+tp.settings.collectionType+'&collectionId='+tp.settings.collectionId+'&trackId='+tp.settings.currentTrackId+'&uniqueId='+tp.settings.playerId+'&imageSize='+tp.settings.imageSize+'&playerType='+tp.settings.playerType,
   						success: function(response) {
   							tp.currentResponse = response;
   							$('#threadsplayer').jPlayer({
   				 				ready: function () {
   	 		 	 					$this.jPlayer('setMedia', { mp3: response.url });
    							},
    							swfPath: '/threads_assets/threadsplayer',
    							cssSelectorAncestor: '#threadsplayer_controls',
    							supplied: 'mp3'
  							});
  							$('#threadsplayer_thumb').attr('src', response.image);
  							tp.updateTrackDetails(response);
   						}
						});
			
						// initialize the controls
  					tp.initializeControls();
  					tp.initializeBuyContainer();
  					tp.initializeFBButton();
  					tp.initializeTwitterButton();
					}
				});
  		});
  	});
  	
 	// end $.fn.threadsPlayer
	};
  
// end ready  
})(jQuery);

function jsonpCallback(data){ }
