(function($) 
{
	$.fn.search = function(src)
	{
		var defaults = 
		{
			items: 9,
			filter: 'relevance',
			type: 'All'			
		};
		
		var results = [];
		
		var options  = $.extend({}, defaults, options);
		
		var applySortFilter = function()
		{
			
			var filter = $(this).attr('class').split(/\s/).pop();
			
			options.filter = filter;
			
			$('a.sort').removeClass('active-filter');
			$(this).addClass('active-filter');
			
			search(0);
		};
		
		var applyTypeFilter = function()
		{
			
			var type = $(this).attr('class').split(/\s/).pop();
			
			options.type = type;
			
			$('a.type').removeClass('active-filter');
			$(this).addClass('active-filter');

			search(0);
		};
		
		var addPlaylist = function()
		{
			if (!vibelist.id)
			{
				alert('Please select playlist');
				return;
			}
			
			if (1 == vibelist.featured)
			{
				alert('You cannot add clips to featured playlist. Please create your own playlist');
				return;
			}
			
			$('ul.cliplist').removeClass('emptyplaylist');
			
			var api = $('div.clipscroll').scrollable();
			var clipid = $(this).attr('id');
			var $cell =  $(this).parents().filter('.cell');
			var title = $cell.find('.clip-title').text();
			var thumbnail = $cell.find('img').attr('src');
			var duration = $cell.find('.clip-duration').attr('title');
			
			
			var $t = $('<li title="' + title + '">'+  (title.length > 30 ? title.substr(0,30) + '...' : title) + ' </li>');
			
			/* Check if the clip already exists in the current playlist */
			if ($('ul.cliplist li[id=' + clipid + ']').length > 0)
			{
				alert('This clip already exists in the current playlist!');
				return;
			}

  			$t.attr('id',clipid);
  			
  			$t.append('<span><a class="clip-options"></a><a class="remove-clip"></a></span>');
  			$t.append('<a class="play-clip"></a>');

  			
  			$('a.remove-clip',$t).bind('click',vibelist.removePlaylistClip);
  			$('a.clip-options',$t).bind('click',vibelist.showClipOptions);
  			
  			$('.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 */
				vibelist.state.last = -1;
				
  				vibelist.playClip($pa.attr('id'));
  			});
  			
  			$t.bind('mouseover',function()
  			{
  				if (false == $(this).hasClass('active'))
  				{
  					$(this).addClass('hovered-clip');
  				}
  				
  			}).bind('mouseout',function()
  			{
  				$(this).removeClass('hovered-clip');
  			});
  			
  			/* Add clip to database */
			$.ajax(
			{
				type: "POST",
				url: vibelist.domain + "plugins/vibe/server/addclip.php",
				data: 'playlist=' + vibelist.id + '&youtubeid=' + clipid + '&title=' + encodeURIComponent(title) + '&thumbnail=' + thumbnail + '&duration=' + duration,
				cache:false,
				success: function(response)
				{
					/* Set li value with the viberoll clip id */
					$t.attr('vibe',parseInt(response));
					$t.find('a.remove-clip').attr('id',parseInt(response));
					
					/* Hide add loaders */
					api.reload().getItemWrap().append($t);  
					api.reload().end();
				}
			});
		};
		
		var next = function()
		{
			$('.currentpage').removeClass('currentpage');
			$(this).addClass('currentpage');
			
			var page = parseInt($(this).attr('rel'));
			
			search(page);
		}
		
		var reset = function()
		{
			$('#searchpaging').empty();
			$('.topsearch').addClass('noback');
			$('.filters').removeClass('inv');
			$('.gap').removeClass('inv');
			
			results.length = null;
		}

		var search = function(index)
		{
			
			
			/* Open search tab */
			$('.search-tabs').tabs('select',2);
			
			if (!index) index = 1;
			
			reset();
			
			var string = $('input[name=search]').val();

			$("#searchgrid div.cell").empty().addClass('load');
			
			$('.search-status strong').eq(0).html(string);
			
			pageTracker._trackEvent('Search','Initiated','Video search');
			
			
			$.ajax({
				  type: "GET",
				  url: vibelist.domain + "plugins/vibe/server/search.php?keyword=" + encodeURIComponent(string) + '&index=' + index + '&filter=' + options.filter + '&type=' + options.type,
				  dataType: "xml",
				  cache: false,
				  success: function(response)
				  {
				  		var paging = 
				  		{
				  			next: parseInt($('pagination',response).attr('next')),
				  			prev: parseInt($('pagination',response).attr('prev'))
				  		}

				  		display($('clip',response), $('page',response), paging);
				  		
				  		$('.search-status strong').eq(1).html($('clips',response).attr('total'));
				  },
				  error: function (XMLHttpRequest, textStatus, errorThrown) 
				  {
				  		alert(textStatus);
						this;
				  }
				});
		}
		
		var display = function(clips, pages, paging)
		{
			$('.invisible').removeClass('invisible');
			$('.search-status-popular').addClass('invisible');
			
			$("#searchgrid div.cell").empty().removeClass('inv').addClass('load');
			
			
			/* Direct attach */
			
			for (i=0; i < clips.length; i++)
	  		{
	  			id = $(clips[i]).attr('id');
	  			
	  			title = $('title',clips[i]).text();
	  			content = $('content',clips[i]).text();
	  			thumbnail = $('thumbnail',clips[i]).text();
	  			duration = $(clips[i]).attr('duration');
	  			seconds = $(clips[i]).attr('seconds');
	  			

	  			var img = new Image();
	  			
	  			var $cell = $('#searchgrid div.cell').eq(i).removeClass('load');
	  			
	  			$(img).addClass('result-thumbnail');
	  			
	  			$cell.append(img);
	  			$cell.append('<a class="addable" id="' + id +'">Add to playlist in use</a>');
				$cell.append('<div class="clip-title">' + title +'</div>');
				$cell.append('<div class="clip-content" title="' + content + '">' + (content.length > 80 ? content.substr(0,80) + '...' : content) + '</div>');
				$cell.append('<div class="clip-duration" title=' + seconds + '>' + duration + '</div>');
				
	  			
				$('.addable',$cell).bind('click',addPlaylist);

	  			img.src = thumbnail;
	  		}
	  		
	  		if (i < 6) /* Complete the missing clips */
	  		{
	  			$('.load').removeClass('load');
	  		}
		  	
		  	if (paging.prev != -1)
		  	{
		  		$('#searchpaging').append('<a class="searchpage prevresults" rel="' + paging.prev + '"></a>');
		  	}

		  	
		  	/* Build paging */
		  	$(pages).each(function()
		  	{
		  		var sel = parseInt($(this).attr('selected'));
		  		
		  		$('#searchpaging').append('<a class="searchpage' + (0 == sel ? '' : ' selected') + '" rel="' + $(this).text() + '">' + $(this).text() + '</a>');
		  	});
		  	
		  	if (paging.next != -1)
		  	{
		  		$('#searchpaging').append('<a class="searchpage nextresults" rel="' + paging.next + '"></a>');
		  	}
		  	
		  	$('a.searchpage').bind('click',next);
		}

		return this.each(function()
		{	
			$(this).find('input[name=search]').keyup(function(event)
			{
				if (event.keyCode == 13) 
				{
			        search(0);
			    }
			});
			
			$(this).find('a').click(function()
			{
				search(0);
			});
			
			/* Append search filters */
			$('a.sort').each(function()
			{
				$(this).bind('click',applySortFilter);
			});
			
			$('a.type').each(function()
			{
				$(this).bind('click',applyTypeFilter);
			});
			
			$('a.add-searched-list').bind('click',addPlaylist);
		});
	};
})(jQuery);

$(function()
{
	/* Initialize search */
	$('.search-heading-body').search();
	
	/* Initialize tabs */
	$('.search-tabs').tabs(
	{
		select: function(event, ui) 
		{
			$('a.active-tab').removeClass('active-tab');
			$(ui.tab).addClass('active-tab');
		}
	});
});