/* 
	Viberoll playlists javascript UI interaction class
	
	@author: Angel Kostadinov(angel.kostadinov@toxicmedia.bg)
	@version: 1.0
*/
function playlist()
{
	this.id = null;
	this.previd = null;
	this.player = null;
	this.items 	= 4;
	this.featured = 0;
	this.clips 	= 0;
	this.controls = 
	{ 
		id: 			null,
		progress: 		null,
		timer: 			null,
		statuslength: 	0,
		duration: 		0,
		bytes:			0,
		bytesloaded: 	0,
		repeat:			false,
		shuffle: 		false,
		volume:			30,
		lastvolume: 	30,
		icons: 
		{
			play: null,
			forward: null,
			backward: null,
			shuffle: null,
			repeat:null
		}
	};
	this.state = 
	{
		play: 0,
		last: 0
	}
	
	this.sequence = null;
	
	this.domain = null;
}

playlist.prototype.getDomain = function()
{
	domain = 'http://' + document.location.toString().match(/:\/\/(.[^\/]+\/(viberoll.com){0,1})/)[1];
	
	return !domain.match(/\/$/) ? domain + '/' : domain;
}

playlist.prototype.init = function()
{
	this.domain = this.getDomain();
	
	/* Construct accordion navigation */
	this.accordion();
	
	/* Enable navigation items scroll  */
	this.scrollable();
	
	/* Enable appending of custom playlists  */
	this.appendable();
	
	setTimeout(function()
	{
		$('.accordion').css({ visibility: 'visible'});
	},200);
}

playlist.prototype.appendable = function()
{
	var p = this;
	
	$('input.addlist').bind('click',function()
	{
		p.addPlaylist();
	});
}

playlist.prototype.activateControls = function()
{
	$(this).addClass('hovered');
	$('a',this).addClass('activated');
}
playlist.prototype.deactivateControls = function()
{
	$(this).removeClass('hovered');
	$('a',this).removeClass('activated');
}

playlist.prototype.appendPlaylist = function(api,name, playlist)
{
	var self = this;
	var $np = $('<p id="PL' + playlist +'">' + name + '</p>');
	
	
	$np.append('<span><a class="edit-playlist"></a><a class="remove-playlist"></a></span>');
	$np.bind('mouseover',self.activateControls);
	$np.bind('mouseout',self.deactivateControls);
		
  	api.getItemWrap().append($np);    
  	
  	 	
    api.reload().end().click(api.getSize()-1);
    
    /* Activate list */
    this.id = playlist;
}

playlist.prototype.emptyCurrentPlaylist = function()
{
	$('ul.cliplist').empty();
}

playlist.prototype.deselectCurrentPlaylist = function()
{
	$('p.active').removeClass('active');
}

playlist.prototype.removePlaylist = function( playlist )
{
	if (confirm('Confirm deleting playlist?'))
	{
		this.state.last = -1;
		
		var api = this.getAPI();
		
		api.getItems().filter('p[id=' + playlist + ']').remove();
		
		// rebuild scrollable and go one step backward
		api.rebuild();
	
		$.ajax({
			type: "POST",
			url: vibelist.domain + "plugins/vibe/server/removeplaylist.php",
			data: 'playlist_id=' + playlist.substr(2),
			dataType: "text",
			cache:false
		});
	}
}

playlist.prototype.sharePlaylistClip = function(event,clip_id, viberoll_id)
{
	/* Cronstruct crossbrowser event */
	if (!event) var event = window.event;
	
	/* Cancel bubbling */
	event.cancelBubble = true;
	
	/* Cancel propogation */
	if (event.stopPropagation) event.stopPropagation();
	
	var $sharer = $('<div></div>');

	$sharer.addClass('sharer');
	
	$sharer.append('<div class="accountinfo"><strong>copy this videoclip link</strong> to share it with your friends</div>');
	$sharer.append('<input type="text" value="http://www.viberoll.com/clip/' + viberoll_id + '" class="direct-link" />');
	$sharer.append('<input type="button" name="cancel" value="Cancel" class="register-button dynamic cancelcopy" />');
	
	$('#template').append($sharer);
	
	$('.cancelcopy').bind('click',function()
	{
		$sharer.remove();
	});
}

playlist.prototype.copyPlaylistClip = function(event,clip_id, viberoll_id)
{
	/* Cronstruct crossbrowser event */
	if (!event) var event = window.event;
	
	/* Cancel bubbling */
	event.cancelBubble = true;
	
	/* Cancel propogation */
	if (event.stopPropagation) event.stopPropagation();
	
	if ($('.allmyplaylists p').length == 0)
	{
		alert('You must create playlist first before copying this clip!');
		return;
	}
	
	var $copier = $('<div></div>');
	var $tmplist = $('<div></div>');

	/* Add CSS class */
	$copier.addClass('copier');
	$tmplist.addClass('tmplist');
	
	
	/* Add inside content */
	$copier.append('<div class="accountinfo"><strong>add clip</strong> to playlist(s)</div>');
	
	$copier.append($tmplist);
	
	$('.allmyplaylists p').each(function()
	{
		$tmplist.append('<input type="checkbox" name="copyto_' + $(this).attr('id').substr(2) + '" class="checkbox copyto" /> ' + $(this).text() + '<br />');
	});
	
	$copier.append('<input type="button" name="copy" value="Copy clip" class="register-button dynamic copyclip" />');
	$copier.append('<input type="button" name="cancel" value="Cancel" class="register-button dynamic cancelcopy" />');
	
	
	
	$('#template').append($copier);
	
	$('.copyclip').bind('click',function()
	{
		var copyto = $('.copyto').map(function()
		{
			if ($(this).attr('checked') == true)
			{
				var playlist_id = $(this).attr('name').substr(7);
				
				return playlist_id;
			}
		}).get().join('&playlist[]=');
		
		if (copyto.length > 0) /* Check if we have checked at least one playlist */
		{
			$copier.empty().addClass('copying');
			
			copyto = 'playlist[]=' + copyto;
			
			$.ajax({
				type: "POST",
				url: vibelist.domain + "plugins/vibe/server/copyclip.php",
				data: 'clip_id=' + clip_id + '&' + copyto,
				dataType: "text",
				cache:false,
				success: function(response)
				{
					$copier.remove();
				}
			});	
		}
		else 
		{
			alert('You must select at least one playlist to copy the clip');
		}
	});
	
	$('.cancelcopy').bind('click',function()
	{
		$copier.remove();
	});
}

playlist.prototype.removePlaylistClip = function(event)
{
	/* Cronstruct crossbrowser event */
	if (!event) var event = window.event;
	
	/* Cancel bubbling */
	event.cancelBubble = true;
	
	/* Cancel propogation */
	if (event.stopPropagation) event.stopPropagation();
	
	if (confirm('Are you sure?'))
	{
		var api = $('div.clipscroll').scrollable();
		var playlistid = $(this).attr('rel');
		var clipid = $(this).attr('id');
		
		$.ajax({
			type: "POST",
			url: vibelist.domain + "plugins/vibe/server/removeclip.php",
			data: 'clip_id=' + clipid + '&playlist_id=' + vibelist.id,
			dataType: "text",
			cache:false,
			success: function(response)
			{
				$(event.target).parents().filter('li').fadeOut(300,function()
				{
					$(this).remove();
					api.reload().next(); 
					
					if ($('ul.cliplist li').length == 0)
					{
						$('ul.cliplist').addClass('emptyplaylist');
					}
				});
			}
		});
	}	
}

playlist.prototype.showClipOptions = function()
{
	var $context 	= $('<div></div>');
	var clip_id 	= $(this).parents().filter('li').attr('id');
	var viberoll_id = $(this).parents().filter('li').attr('vibe');

	$context.addClass('context-menu');
	$context.append('<div class="accountinfo centered"><strong>viberoll</strong> clip options</div>');
	$context.append('<a class="option-copy" href="javascript:void(0)">Add to playlist</a>');
	$context.append('<a class="option-share" href="javascript:void(0)">Share</a>');
	
	$context.append('<input type="button" name="cancel" value="Cancel" class="register-button canceloptions" />');
	
	$('.clipscroll').append($context);
	
	
	$('.canceloptions').bind('click',function()
	{
		$context.remove();
	});
	
	$('.option-copy').bind('click',function(event)
	{
		$context.remove();
		vibelist.copyPlaylistClip(event,clip_id,viberoll_id);
	});
	
	$('.option-share').bind('click',function(event)
	{
		$context.remove();
		vibelist.sharePlaylistClip(event,clip_id,viberoll_id);
	});
	
}

playlist.prototype.updatePlaylistTitle = function( playlist, title)
{
	$.ajax({
		type: "POST",
		url: vibelist.domain + "plugins/vibe/server/updateplaylist.php",
		data: 'title=' + title + '&playlist_id=' + playlist,
		dataType: "text",
		cache:false,
		success: function(response)
		{
			var $p = $('p[id=PL' + playlist + ']');
			var $c = $p.children().filter('span').clone(true);
			
			$p.empty().html(title);
			$c.appendTo($p);
		}
	});	
};

playlist.prototype.loadClips = function(playlist)
{
	var self = this;

	self.deselectCurrentPlaylist();

	this.id = playlist;
	

	$('div.clipscroll').scrollable(
	{
		items:'ul.cliplist', 
        vertical:true, 
        nextPage:'a.nextclips', 
        prevPage:'a.prevclips',
        clickable:false,
        size:15,
        activeClass: 'active-clip' 
	});


	var api = $('div.clipscroll').scrollable();
	var seek = true;
	
	api.reload().reset();
	
	self.emptyCurrentPlaylist();
	
	$("#clipsloader").show();
	
	$.ajax({
	  type: "GET",
	  url: vibelist.domain + "plugins/vibe/server/clips.php?playlist_id=" + playlist,
	  dataType: "xml",
	  cache: false,
	  error: function (XMLHttpRequest, textStatus, errorThrown) 
	  {
	  		/* Handle error  */
	  },
	  success: function(response)
	  {
	  		var clips = $('clip',response);

	  		if (clips.length == 0)
	  		{
	  			$('ul.cliplist').addClass('emptyplaylist');
	  		}
	  		else 
	  		{
	  			$('ul.cliplist').removeClass('emptyplaylist');
	  		}
	  		
	  		for (i=0; i < clips.length; i++)
	  		{
	  			var viberollid = $(clips[i]).attr('ID');
	  			var youtubeid  = $(clips[i]).attr('YouTubeID');
	  			
	  			var tip = parseInt($(clips[i]).attr('tooltip'));
	  			
	  			var $t = $('<li' + (1 == tip ? ' title="' + $(clips[i]).attr('title') + '"' : '') + '>' + $(clips[i]).text() + '</li>');

	  			$t.attr('id',youtubeid);
	  			$t.attr('vibe',viberollid);
	  			
	  			$t.append('<span><a class="clip-options"></a></span>');
	  			
	  			if (0 == self.featured)
	  			{
	  				$t.find('span').append('<a class="remove-clip" id="' + $(clips[i]).attr('ID')  +'"></a>');
	  			}
	  			
	  			$t.append('<a class="play-clip"></a>');

	  			$('.play-clip',$t).bind('click',function(event)
	  			{
	  				/* Cronstruct crossbrowser event */
					if (!event) var event = window.event;
					
					/* Cancel bubbling */
					event.cancelBubble = true;
					
					/* Cancel propogation */
					if (event.stopPropagation) event.stopPropagation();
					
	  				var $pa = $(this).parents().eq(0);
	  				var cl = $('ul.cliplist').sortable('toArray');
	  				
	  				for (x = 0; x < cl.length; x++)
	  				{
	  					if (cl[x] == $pa.attr('id'))
	  					{
		  					api.reload().click(x);
		  					break;
	  					}
	  				}

					/* Reset player state, programatically */
					self.state.last = -1;
					
	  				self.playClip($pa.attr('id'));
	  			});
	  			
	  			
	  			$t.bind('mouseover',function()
	  			{
	  				if (false == $(this).hasClass('active'))
	  				{
	  					$(this).addClass('hovered-clip');
	  				}
	  				
	  			});
	  			
	  			$t.bind('mouseout',function()
	  			{
	  				$(this).removeClass('hovered-clip');
	  			});
	  			
	  			$('a.remove-clip',$t).bind('click',self.removePlaylistClip);
	  			$('a.clip-options',$t).bind('click',self.showClipOptions);
	  			
	  			api.reload().getItemWrap().append($t);   
	  			
	  			if (youtubeid == vibelist.controls.id)
	  			{
	  				api.reload().click(i);
	  				
	  				setTimeout(function()
	  				{
	  					api.seekTo(i);
	  				},300);
	  			}
	  		}
	  		
	  		vibelist.clips = i;
	  		
	  		/* Create shuffle seuqence */
	  		vibelist.createShuffleSequence(i);
	  		
	  		$("#clipsloader").hide();
	  }
	});
	
	$('ul.cliplist').sortable(
	{
		containment: 'parent',
		axis: 'y',
		placeholder: 'clip-placeholder',
		opacity:0.4,
		update: function(event,ui)
		{
			var order = $(this).sortable('toArray').join('&clip[]=');

			$('#block-ui').css({ opacity:0.5}).show();
			
			$.ajax(
			{
				  type: "POST",
				  url: vibelist.domain + "plugins/vibe/server/sort.php",
				  data: 'playlist=' + vibelist.id + '&' + order,
				  success: function(response)
				  {
				  		$('#block-ui').hide();
				  }
			});		  
		},
		stop: function(event,ui)
		{
			ui.item.css({top:0,left:0});
		}
	});
	
	if (1 == this.featured)
	{
		$('ul.cliplist').sortable('disable');
	}
	else 
	{
		$('ul.cliplist').sortable('enable');
	}
}

playlist.prototype.createShuffleSequence = function(size)
{
	this.sequence = new Array();
	
	for (sq = 0; sq < size; sq++)
	{	
		this.sequence.push(sq);
	}
	
	this.sequence.sort(function() {return 0.5 - Math.random()});
}

playlist.prototype.addPlaylist = function()
{
	var name = $('input[name=newplaylist]').val();
	
	/* Reset input value */
	$('input[name=newplaylist]').val('');
	
	$.ajax({
		type: "POST",
		url: vibelist.domain + "plugins/vibe/server/addlist.php",
		data: 'title=' + name,
		dataType: "text",
		cache:false,
		success: function(response)
		{
			var playlist = parseInt(response);
			
			if (0 !== playlist)
			{
				$('.accordion').accordion('activate',1);
		
				vibelist.appendPlaylist(vibelist.getAPI(),name, playlist);
			}
			else 
			{
				alert('Error while creating new playlist');
			}
		}
	});	
}


playlist.prototype.scrollable = function()
{
	var self = this;
	
	$('.playlists').scrollable
	({ 
        items:'.playlist', 
        vertical:true, 
        next:'a.nextplaylist', 
        prev:'a.prevplaylist',
        size:this.items,
        clickable:true,
        onClicked: function(index)
        {
        	var item = this.getItems().eq(index);

        	self.featured = true == item.hasClass('featured') ? 1 : 0;
        	
        	self.loadClips(item.attr('id').substr(2));
        }
    });
}

playlist.prototype.playClip = function( id )
{
	/* Equalize current playlist with the current playlist */
	this.previd = this.id;
	
	document.title = $('li[id=' + id + ']').attr('title').length > 0 ?  $('li[id=' + id + ']').attr('title') : $('li[id=' + id + ']').text();
	
	/* Remove pause classes */
	$('a.stopped-clip').removeClass('stopped-clip');
	
	/* Load clip */
	this.loadClip(id,0);
	
	/* Adjust sound settings */
	if (true == this.player.isMuted())
	{
		this.player.unMute();
	}
	
	/* Adjust volume */
	this.player.setVolume(this.controls.volume);
	
	/* Play the clip */
	this.player.playVideo();
	
	$.ajax({
		type: "POST",
		url: vibelist.domain + "plugins/vibe/server/updateviews.php",
		data: 'clip_id=' + id + '&playlist_id=' + vibelist.id,
		dataType: "text",
		cache:false
	});	
}

playlist.prototype.seekClip = function( position )
{
	var seconds = parseInt((this.controls.duration * position)/100);
	
	this.player.seekTo(seconds,true);
}

playlist.prototype.loadClip = function( id )
{		
	/* Intialize player UI */
	this.initalizeUI(id);
	
	/* Load video clip */
	this.player.loadVideoById(id, 0);
	 
	/* Intialize status trace */
	setTimeout(function()
	{
		vibelist.updateUI();
	},250);
}

playlist.prototype.loadPrevClip = function()
{	
	if (0 == this.sequence.length)
	{
		this.createShuffleSequence($('.cliplist li').length);
	}
	
	var rand = this.sequence.shift();
	
	var clips = $('.cliplist li').map(function()
	{
		return $(this).attr('id')
	});
	
	index = 0;
	
	if (true === this.controls.shuffle)
	{
		index = rand;
	}
	else 
	{
		for ( i=0; i < clips.length; i++ )
		{
			if (clips[i].toString().indexOf(this.controls.id) != -1)
			{
				if (i - 1 >= 0)
				{
					index = i - 1;
					break;
				}
				else 
				{
					index = rand;
					break;
				}
			}
		}
	}
	
	$('.clipscroll').scrollable().click(index);
	
	this.playClip(clips[index],0);
}

playlist.prototype.stopVideo = function()
{
	$('li.active-clip').find('a.play-clip').addClass('stopped-clip');
	
	this.player.stopVideo();
	this.player.clearVideo();
}

playlist.prototype.loadNextClip = function()
{	
	/* Abort next clip if playlist has been changed meanwhile */
	if (this.id != this.previd)
	{
		this.stopVideo();
		return;
	}
	
	if (0 == this.sequence.length)
	{
		this.createShuffleSequence($('.cliplist li').length);
	}
	
	var rand = this.sequence.shift();
	
	var clips = $('.cliplist li').map(function()
	{
		return $(this).attr('id')
	});
	
	var index = 0;

	if (true === this.controls.shuffle)
	{
		index = rand;
	}
	else
	{
		for ( i=0; i < clips.length; i++ )
		{
			if (clips[i].toString().indexOf(this.controls.id) != -1)
			{
				if (i + 1 < clips.length)
				{
					index = i + 1;
					break;
				}
				else 
				{
					if (true === this.controls.repeat)
					{
						index = 0;
						break;
					}
					else index = null;
				}
			}
		}
	}

	if (null != index)
	{
		$('.clipscroll').scrollable().click(index);
		
		this.playClip(clips[index],0);
	}
	else 
	{
		this.state.play = -1;
		this.state.last = -1;
		this.stopVideo();
	}
}

playlist.prototype.initalizeUI = function( id )
{
	this.controls.id 				= id;
	this.controls.duration 			= 0;
	this.controls.progress 			= $('.player-progress').get();
	this.controls.timer 			= $('.player-time').get();
	this.controls.progresslength 	= $(this.controls.progress).parent().width();
	this.controls.buffer			=  $('.player-buffer').get();
	this.controls.icons.play	 	= $('a.ico-play');
	this.state.play					= 0;
	
	$('#ui-media-kit').hide();
}

playlist.prototype.updateUI = function()
{
	if (vibelist.state.play == -1) return;
	
	if (0 == Math.round(this.controls.duration) || 10 > Math.round(this.controls.bytes))
	{
		this.controls.duration = this.player.getDuration();
		this.controls.bytes = this.player.getVideoBytesTotal();
	}
	else 
	{
		/* Update actual info */
		var time = this.player.getCurrentTime();
		var bytes = this.player.getVideoBytesLoaded();
		var normalized = this.controls.progresslength / this.controls.duration;
		
		/* Prepare current time*/
		var min = parseInt(time/60);
		var sec = parseInt(time - (min*60));
			
		sec = sec < 10 ? '0' + sec.toString() : sec;
		
		/* Prepare whole duration */
		var durmin = parseInt(this.controls.duration/60);
		var dursec = parseInt(this.controls.duration - (durmin*60));
			
		dursec = dursec < 10 ? '0' + dursec.toString() : dursec;
			
		var progress = time.toFixed(1) * normalized.toFixed(4);
		var buffpercent = Math.round((bytes / this.controls.bytes) * 100);
		var buffer = Math.round((this.controls.progresslength * buffpercent) / 100) - 5;
		
		
		if (time)
		{
			$('#player-time').html(min.toString() + ':' + sec.toString() + '/' + durmin.toString() + ':' + dursec.toString());
			

			if (progress > 0)
			{
				$(this.controls.progress).css(
				{
					width: Math.round(progress)
				});
			}

			if (buffer > 0)
			{
				$(this.controls.buffer).css(
				{
					width: buffer
				});
			}
		}
	}
	
	
	setTimeout(function()
	{
		vibelist.updateUI();
	},250);
}


playlist.prototype.getAPI = function()
{
	return $('.enabled').find(".playlists").scrollable();
}

playlist.prototype.accordion = function()
{
	$('.accordion').accordion().controllable();
}