/**************************************************************************************\
*   Name:           PlayerInterface                                                    *
*   Author:         Philip Rasmussen (DK)                                              *
*   Version:        0.1.3 (beta)                                                       *
*   Description:	Controls the interface of the Pickupsongs Player and provides an   *
*                   API to set data and execute actions presented in the interface.    *
\**************************************************************************************/

function PlayerInterface(playerId){

	var $this = this;
	var loc = top.location;
	var splitted = loc.toString().split('#');

	this._eventListeners = {}; // Next, Previous, Shuffle, Repeat
	
	this.Queue = new Queue();
	this.Player = new Player(playerId);
	this._ready = false;
	this._repeat = false;
	this._shuffle = false;
	this._catNo = '';
	this._cover = '';
	this._productId = null;
	this._waveform = '';
	this._artist = '';
	this._vocalist = '';
	this._source = '';
	this._sourceLink = '';
	this._sourceName = '';
	this._sourceNameLink = '';
	this._songName = '';
	this._songLink = '';
	this._fast_clear = false;
	this._finalize_status = '';
	this._handleHeight = 8;
    this._pageX = 0;
	this._defaultWaveformPrefix = splitted[0] + '/en/media/catalog/product/default';
	
	this.play = function(){
//		$(this).jPlayer("pauseOthers"); 
		if(this._ready) this.Player.play();
		return this;
	}
	
	this.pause = function(){
	
		if(this._ready) this.Player.pause();
		
		return this;
	}
	
	this.playPauseStatus = function(enable){
	
		var suffix = (this.Player.isPlaying() ? 'pause' : 'play')
	
		if(enable != null){
		
			if(enable) jQuery('#player_'+suffix).removeAttr('disabled');
			else jQuery('#player_'+suffix).attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_'+suffix).attr('disabled');
	}
	
	this.previous = function(){
	
		var data;
	
		if(this.shuffle()){ this.Queue.pointer(Math.floor(Math.random()*this.Queue.count())); data = this.Queue.current();}
		else data = this.Queue.previous();
		
		if(this.Player.song() != (SAMPLE_DIR_PATH + data[0])) this.setSong(data);
		
		this.triggerEvent('previous');
		
		return this;
	}
	
	this.previousStatus = function(enable){

		if(enable != null){
			var p_prev = jQuery('#player_previous');
			if(enable) { p_prev.removeAttr('disabled'); p_prev.addClass('enabled'); }
			else { p_prev.removeClass('enabled'); p_prev.attr('disabled', true); }

			return this;
		}
		
		return !jQuery('#player_previous').attr('disabled');
	}
	
	this.next = function(){
	
		var data;
	
		if(this.shuffle()){ this.Queue.pointer(Math.floor(Math.random()*this.Queue.count())); data = this.Queue.current();}
		else data = this.Queue.next();
		
		if(this.Player.song() != (SAMPLE_DIR_PATH + data[0])) this.setSong(data);
		
		this.triggerEvent('next');
		
		return this;
	}
	
	this.nextStatus = function(enable){
	
		if(enable != null){
			var p_next = jQuery('#player_next');
			if(enable) { p_next.removeAttr('disabled'); p_next.addClass('enabled'); }
			else { p_next.removeClass('enabled'); p_next.attr('disabled', true); }
		
			return this;
		}
		
		return !jQuery('#player_next').attr('disabled');
	}
	
	this.shuffle = function(shuffle){
	
		if(shuffle != null){
		
			this._shuffle = shuffle;
			this._updateButtons();
		
			this.triggerEvent('shuffle');
			
			return this;
		}
		
		return this._shuffle;
	}
	
	this.shuffleStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_shuffle').removeAttr('disabled');
			else jQuery('#player_shuffle').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_shuffle').attr('disabled');
	}
	
	this.repeat = function(repeat){
	
		if(repeat != null){
		
			this._repeat = repeat;
			this._updateButtons();
		
			this.triggerEvent('repeat');
			
			return this;
		}
		
		return this._repeat;
	}
	
	this.repeatStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_repeat').removeAttr('disabled');
			else jQuery('#player_repeat').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_repeat').attr('disabled');
	}
	
	this.license = function(){
	
		var url = ((this.songName()).link).toString().replace('/#/', '/en/');
		if(url != null) {
		
			fr2.location = url + '?license=1';
			return this;
		}
		
		return false;
	}
	
	this.licenseStatus = function(enable){
		if(enable != null){

			if(enable) jQuery('#player_license').removeAttr('disabled');
			else jQuery('#player_license').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_license').attr('disabled');
	}

	this.addToCart = function(){
	
		var id = this.productId();
	
		if(id != null) {
		
			fr2.location = splitted[0] + 'en/checkout/cart/add?product='+ id +'&qty=1';
			return this;
		}
		
		return false;
	}
	
	this.addToCartStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_shoppingcart').removeAttr('disabled');
			else jQuery('#player_shoppingcart').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_shoppingcart').attr('disabled');
	}
	
	this.addToPlaylist = function(){
		
		var id = this.productId();
		if(id != null){
		
			registryUrl = splitted[0] + 'en/playlist/event/quickAddItem/product/'+ id +'/';		
			fr2.PUS.MusicSearch.Results.Track.addToPlaylist(registryUrl);
			
			return this;
		}
		
		return false;
	}
	
	this.addToPlaylistStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_playlist_favourite').removeAttr('disabled');
			else jQuery('#player_playlist_favourite').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_playlist_favourite').attr('disabled');
	}

	this.share = function(){
	
		var url = ((this.songName()).link).replace('/en/', '/#/');
		var title = (this.songName()).name;

		if(!url || !title) return false;

		//fr2.PUS.MusicSearch.Results.Track.shareThis(url, title);
		/*fr2.PUS.DivPopUp.clear().setName("share").setTitle('<div class="share-popup-title">Share</div>');

		var content = '<div class="share-body"><div><a href="mailto:?Subject=Awesome%20Track&body=<a href=\''+url+'\'>'+title+'</a>"><img src="skin/frontend/pus_new/pus_theme/images/share_email.png" alt="Email" /></a></div> <div><a target="_blank" href="http://www.facebook.com/share.php?u='+ escape(url) +'"><img src="skin/frontend/pus_new/pus_theme/images/share_fb.png" alt="Facebook" /></a></div> <div><a target="_blank" href="http://twitter.com/home?status=Add+This:+'+ escape(url) +'"><img src="skin/frontend/pus_new/pus_theme/images/share_twitter.png" alt="Twitter" /></a></div>   </div>';
		fr2.PUS.DivPopUp.setContent(content).show();*/
		top.sharePopup(title, url);
		

		/*var object = SHARETHIS.addEntry({
			title: title,
			url: url			
		}, {offsetLeft: -349, offsetTop: 10});

		object.attachButton(document.getElementById('player_share_span'));
		object.popup();*/

		return this;
	}
	
	this.shareStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_share').removeAttr('disabled');
			else jQuery('#player_share').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_share').attr('disabled');
	}
	
	this.follow = function(){
		var id = this.productId();
		if(id != null){
		
			fr2.location = splitted[0] + 'en/favorites/index/add/product/'+ id +'/';			
			
			return this;
		}
		
		return false;	
		
	}
	
	this.followStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_follow').removeAttr('disabled');
			else jQuery('#player_follow').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_follow').attr('disabled');
	}
	
	this.review = function(){
	
		var id = this.productId();

		if(id != null) {
		
			fr2.location = splitted[0] + 'en/review/product/list/id/'+ id +'/#review-form';
			return this;
		}
		
		return false;
	}
	
	this.reviewStatus = function(enable){
	
		if(enable != null){
		
			if(enable) jQuery('#player_review').removeAttr('disabled');
			else jQuery('#player_review').attr('disabled', true);
		
			return this;
		}
		
		return !jQuery('#player_review').attr('disabled');
	}
	
	this.cover = function(cover){
	
		if(cover != null){
		
			jQuery('#player_cover').attr('src', cover);
			this._cover = cover;

			jQuery('#player_cover').closest('a').attr('href', this._songLink);
			return this;
		}
		
		return this._cover;
	}
	
	this.catNo = function(catNo){
	
		if(catNo != null){
		
			jQuery('#player_cat_no').text(catNo);
			this._catNo = catNo;
		
			return this;
		}
		
		return this._catNo;
	}
	
	this.vocalist = function(vocalist){
	
		if(vocalist != null){
		
			jQuery('#player_vocalist').text(vocalist);
			jQuery('#player_band_feat').toggle(vocalist != '' && this.artist() != '');
			this._vocalist = vocalist;
		
			return this;
		}
		
		return this._vocalist;
	}
	
	this.artist = function(artist){
	
		if(artist != null){
		
			jQuery('#player_artist').text(artist);
			this._artist = artist;
		
			return this;
		}
		
		return this._artist;	
	}
	
	this.source = function(name, link){
	
		if(name != null){
		
			jQuery('#player_source').html('<a target="fr2" href="'+link+'">'+name+'</a>');
			this._source = name;
			this._sourceLink = link;
		
			return this;
		}
		
		return this._source;
	}
	
	this.sourceName = function(name, link){
	
		if(name != null){
		
			jQuery('#player_name').html('<a target="fr2" href="'+link+'">'+name+'</a>');
			this._sourceName = name;
			this._sourceNameLink = link;
			
			return this;
		}
		
		return {name: this._songName, link: this._songLink};
	}

	this.songName = function(name, link){
	
		if(name != null || link != null){
		
			jQuery('#player_track').html('<a target="fr2" href="'+link+'">'+name+'</a>');
			this._songName = name;
			this._songLink = link;
		
			return this;
		}
		
		return {name: this._songName, link: this._songLink};
	}
	
	this.waveform = function(url){
        if(url == '') {
            jQuery('#player_progress_bar').css('background-image', 'none');
            jQuery('#player_load_bar').css('background-image', 'none');
            jQuery('#player_play_bar').css('background-image', 'none');
            
            return this._waveform;
        }
	
		if(url != null){
            jQuery('#player_play_bar').css('width', '0%');
            jQuery('#player_load_bar').css('width', '0%');

            jQuery('#player_play_bar').css('background-image', 'url('+url+'-s3.png)');            
            jQuery('#player_load_bar').css('background-image', 'url('+url+'-s2.png)');            
			jQuery('#player_progress_bar').css('background-image', 'url('+url+'-s1.png)');

			this._waveform = url;
			
			return this;
		}		
	}

	this.finalizeStatus = function(finalize_status){
	
		if(finalize_status != ''){

			this._finalize_status = finalize_status;
			
			return this;
		}
		
		return this._finalize_status;
	}

	this.filterOptionFastClear = function(fast_clear){
	
		if(typeof fast_clear == 'boolean'){

			this._fast_clear = fast_clear;
			return this;
		}
		
		return this._fast_clear;
	}

	this.productId = function(id){
	
		if(id !== undefined){
			
			this._productId = id;
			return this;
		}
		
		return this._productId;
	}
	
	this.productUrl = function(url){
	
		if(url !== undefined){
			
			this._songLink = url;
			return this;
		}
		
		return this._songLink;
	}

	this.setSong = function(data){ // file url, track name, artist/band, vocalist, cover url, waveform url prefix, product id, cat no, source type, source name
	
		if(data == null) return;
this.removeSong();
		jQuery('#player-bar').removeClass('inactive');

		this.Player.song((SAMPLE_DIR_PATH + data[0]));
		this.songName(data[2], data[1]);
		this.artist(data[3]);
		this.vocalist(data[4]);
		this.cover(data[5]);
		this.waveform(data[6] ? WAVEFORM_DIR_PATH + data[6] : this._defaultWaveformPrefix);
		this.productId(data[7]);
		this.catNo(data[8]);
		this.source(data[9], data[10]);
		this.sourceName(data[11], data[12]);
		this.finalizeStatus(data[13]);
		this.filterOptionFastClear(data[14]);

		
		this._updateButtons();
		this.play();

		if(fr2.jQuery('#track-details').text() == 'Yes' && fr2.Mage.Cookies.get('link-to-player')==1 && fr2.location != data[1] && fr2.Mage.Cookies.get('is-unloading')==0) {
			fr2.location = data[1];
		}

		var now = new Date();
		expiredate = new Date(now.valueOf()+(3600*24*2*1000));
		fr2.Mage.Cookies.set('recently-played', data[7] + ',' + fr2.Mage.Cookies.get('recently-played'),expiredate);

		////////////////////
		jQuery('img#player_cover').css({'display':'','visibility':'visible'});
		////////////////////

		return this;
	}

	this.removeSong = function(){
	
		this.Player.removeSong();
		this.songName('', '#');
		this.artist('');
		this.vocalist('');
		this.cover('');
		this.waveform('');
		this.productId(null);
		this.catNo('');
		this.source('', '#');
		this.sourceName('', '#');
		this.finalizeStatus('');
		this.filterOptionFastClear(false);
		
		jQuery('#player_total_time span').text('00:00');
		
		jQuery('#player-bar').addClass('inactive');
		
		this._updateButtons();
		
		return this;
	}
	
	this.addEventListener = function(type, handler){
	
		if(!this._eventListeners[type]) this._eventListeners[type] = [];
		if(typeof handler == 'function') this._eventListeners[type].push(handler);
	}
	
	this.removeEventListener = function(type, handler){
	
		var handlers = this._eventListeners[type];
	
		if(handlers){
		
			var length = handlers.length;
		
			for(var i = 0; i<length; ++i) if(handlers[i] == handler){this._eventListeners[type].splice(i, 1); break;};
		}
		
		return this;
	}
	
	this.triggerEvent = function(type){
	
		var handlers = this._eventListeners[type];
	
		if(handlers){
		
			var length = handlers.length;
		
			for(var i = 0; i<length; ++i) handlers[i].apply(this, []);
		}
		
		return this;
	}


// MISC FUNCTIONS

	this._updateButtons = function(){
	
		var count = $this.Queue.count();

		if(count <= 1){
			
			$this.previousStatus(false);
			$this.nextStatus(false);
			$this.shuffleStatus(false);
		}
		else {
		
			$this.previousStatus(!$this.Queue.startReached() || ($this.repeat() || $this.shuffle()));
			$this.nextStatus(!$this.Queue.endReached() || ($this.repeat() || $this.shuffle()));
			$this.shuffleStatus(true);
		}
		
			$this.playPauseStatus(count);

		if(count > 0)
			$this.repeatStatus(count);
		else
			$this.repeatStatus(false);

			$this.licenseStatus($this._fast_clear);

			$this.addToCartStatus(count);
			$this.shareStatus(count);
			$this.followStatus(count);
			$this.reviewStatus(count);
			$this.addToPlaylistStatus(count);
			
		return this;
	}

// SETUP EVENT HANDLERS

	this.Player.addEventListener('ready', function(){

		$this._ready = true;
		$this.Player.triggerEvent('volumeChange');
		$this.setSong($this.Queue.current());
	});
	
	// EVENT NOT USED: Player - loadingStarted
	this.Player.addEventListener('loadingStarted', function(){

	});
	
	this.Player.addEventListener('progressChange', function(){

		var playerInfo = $this.Player.loadedStatus(true);
		jQuery('#player_load_bar').width(playerInfo.percentLoaded+'%');
		jQuery('#player_total_time span').text(playerInfo.durationLoaded);
		jQuery('#player_play_bar').width((100 * playerInfo.percentPlayed / playerInfo.percentLoaded  ) +'%');
	});
	
	this.Player.addEventListener('timeChange', function(){
	
		var playerInfo = $this.Player.loadedStatus(true);

		jQuery('#player_play_bar').width((100 * playerInfo.percentPlayed / playerInfo.percentLoaded  ) +'%');
		jQuery('#player_play_time span').text(playerInfo.time);        
	});
	
	// EVENT NOT USED: Player - timeJump
	this.Player.addEventListener('timeJump', function(){
        //var playerInfo = $this.Player.loadedStatus(true);
        //jQuery('#player_play_bar').width(playerInfo.percentPlayed+'%');
        //if($this._pageX > 0)
        //    jQuery('#player_play_bar').width((($this._pageX - jQuery('#player_progress_bar').offset().left) * 100) / jQuery('#player_load_bar').width() + '%');
    });
    
	this.Player.addEventListener('songFinished', function(){
	
		if(!$this.Queue.endReached() || ($this.repeat() || $this.shuffle())) $this.next().play();
		else $this.Player.triggerEvent('pause');
	});
	
	this.Player.addEventListener('play', function(){
	
		jQuery('#player_play').hide();
		jQuery('#player_pause').show();
	});
	
	this.Player.addEventListener('pause', function(){
	
		jQuery('#player_pause').hide();
		jQuery('#player_play').show();
	});
	
	this.Player.addEventListener('songChanged', function(){
	
		$this.play();
	});
	
	// EVENT NOT USED: Player - songRemoved
	
	this.Player.addEventListener('volumeChange', function(){
	
		var height = (jQuery('#player_volume_bar').height()-$this._handleHeight)/100*$this.Player.volume()+$this._handleHeight;
		jQuery('#player_volume_bar_value').height(height);
	});

	this.Queue.addEventListener('itemInserted', function(){
		if($this._ready && $this.Player.song() == '')  $this.setSong($this.Queue.current()); 
		if($this.Queue.current() == undefined && $this.Queue.count() > 0) {
			$this.removeSong();
			$this.setSong($this.Queue._items[0]);
			$this.Queue.pointer(0);
			$this.repeatStatus(false);
			$this._updateButtons();
		}
	});

	this.Queue.addEventListener('itemMoved', function(){
	
		$this._updateButtons();
	});

	this.Queue.addEventListener('itemRemoved', function(){
	
		if($this.Queue.count() == 0) $this.removeSong();
		else $this._updateButtons();
	});

	this.Queue.addEventListener('itemChanged', function(){
	
		var current = $this.Queue.current();
	
		if($this.catNo() != current[7]) $this.setSong(current);
	});
	
	// EVENT NOT USED: Queue - pointerChanged
	
	jQuery(function(){ // Init controls
	
		// PLAYER CONTROLS - LEFT
	
		jQuery('#player_play').click(function(){ // Play button
		
			$this.play();
		});
		
		jQuery('#player_pause').click(function(){ // Pause button
		
			$this.pause();
		});
		
		jQuery('#player_previous').click(function(){ // Previous button
		
			$this.previous();
		});
		
		jQuery('#player_next').click(function(){ // Next button
		
			$this.next();
		});
		
		jQuery('#player_repeat').click(function(){ // Repeat button
		
			jQuery(this).toggleClass('enabled');
			$this.repeat(jQuery(this).hasClass('enabled'));
		});
		
		jQuery('#player_shuffle').click(function(){ // Shuffle button
		
			jQuery(this).toggleClass('enabled');
			$this.shuffle(jQuery(this).hasClass('enabled'));
		});
	
		// PLAYER CONTROLS - RIGHT
		
		jQuery('#player_playlist_favourite').click(function(){ // ADD TO PLAYLIST button
			
			$this.addToPlaylist();
		});
		
		jQuery('#player_follow').click(function(){ // ADD TO PLAYLIST button
			
			$this.follow();
		});

		jQuery('#player_review').click(function(){ // REVIEW button
			
			$this.review();
		});

		jQuery('#player_shoppingcart').click(function(){ // ADD TO CART button
			
			$this.addToCart();
		});
		jQuery('#player_share').click(function(){ // ADD TO CART button
			
			$this.share();
		});
		jQuery('#player_license').click(function(){ // License button
			
			$this.license();
		});

		// Disable extra buttons for now
		jQuery('#player_blank').attr('disabled', true);
		//$this.shareStatus(false);
		//$this.followStatus(false);
		//$this.reviewStatus(false);
		//$this.addToPlaylistStatus(false);
		//$this.addToCartStatus(false);
		
		(function(){ // Volume bar
		
			var handleHeight = $this._handleHeight,
				offset = jQuery('#player_volume_bar').offset().top,
				height = jQuery('#player_volume_bar').height()-handleHeight,
				heightAndOffset = height + offset;
				
			jQuery('#player_volume_bar').add('#player_volume_bar_value').attr('ondrag','return false;').attr('onselect','return false;');

			jQuery('#player_volume_bar').mousedown(function(e){
			
				var event = jQuery.Event('mousemove');
				event.pageY = e.pageY;
			
				jQuery(this).mouseup(function(e){
				
					jQuery(this).unbind('mouseup mouseleave mousemove');
				
				}).mouseleave(function(e){
				
					jQuery(this).mouseup();
				
				}).mousemove(function(e){
				
					var volume = 0;
				
					if(e.pageY >= heightAndOffset) volume = 0;
					else if(e.pageY <= offset) volume = 100;
					else volume = 100-((e.pageY-offset)/height)*100;

					$this.Player.volume(volume);
					
				}).trigger(event);
			});
				
		})();
		
		(function(){ // Progress bar
		
			var offset = jQuery('#player_progress_bar').offset().left,
				width = jQuery('#player_progress_bar').width(),
				widthAndOffset = width + offset;			
			
			jQuery('#player_progress_bar').attr('onselect','return false;');

			jQuery('#player_load_bar').click(function(e){

				var time = 0;

				if(e.pageX >= widthAndOffset) time = 100;
				else if(e.pageX <= offset) time = 0;
				else time = ((e.pageX-offset)/width)*($this.Player.loadedStatus().duration);

                $this._pageX = e.pageX;
				$this.Player.time(time);
				

				

			});
				
		})();
	});
}

var Pickupsongs = {player: new PlayerInterface('jPlayer')}
