var VideoSourceCollapser = 
{
	m_szCollapsedImage	: 'icon-toggle-plus.png',
	m_szExpandedImage 	: 'icon-toggle-minus.png',
	
	init: function()
	{
		var aTables = $A(document.getElementsByClassName('collapsable'));
		
		if (!aTables)
		{
			return;
		}
		
		aTables.each(function (pTable)
		{
			var aRows = $A(pTable.rows);
			var pPreviousRow = '';
			var iFoundHeaders = 0;
			
			aRows.each(function (pRow, iIndex)
			{
				if (iIndex < 10)
				{
					return;
				}
				
				if ($(pRow).hasClassName('collapsable_header'))
				{
					iFoundHeaders++;

					pRow.down('td').removeClassName('header_expanded');
					pRow.down('td').addClassName('header_collapsed');
					
					if (iFoundHeaders > 1)
					{
						VideoSourceCollapser.toggleImage(pRow.down('td').down('img'), VideoSourceCollapser.m_szCollapsedImage);
						pRow.onclick = function() { VideoSourceCollapser.expand(this); }
					}
					else
					{
						pRow.onclick = function() { VideoSourceCollapser.collapse(this); }
					}
					
					return;
				}
				
				if (iFoundHeaders > 1)
				{
					pRow.hide();
				}
			});
		});
	},
	
	expand: function(pRow)
	{
		VideoSourceCollapser.toggleImage(pRow.down('td').down('img'), VideoSourceCollapser.m_szExpandedImage);

		pRow.down('td').removeClassName('header_collapsed');
		pRow.down('td').addClassName('header_expanded');
		pRow.onclick = function()
		{
			VideoSourceCollapser.collapse(this);
		}
		
		while (pRow)
		{
			pRow = pRow.next('tr');
			
			if (!pRow || pRow.hasClassName('collapsable_header'))
			{
				return;
			}
			
			pRow.show();
		}
	},
	
	collapse: function(pRow)
	{
		VideoSourceCollapser.toggleImage(pRow.down('td').down('img'), VideoSourceCollapser.m_szCollapsedImage);
		
		pRow.down('td').removeClassName('header_collapsed');
		pRow.down('td').addClassName('header_expanded');
		pRow.onclick = function()
		{
			VideoSourceCollapser.expand(this);
		}
		
		while (pRow)
		{
			pRow = pRow.next('tr');
			
			if (!pRow || pRow.hasClassName('collapsable_header'))
			{
				return;
			}
			
			pRow.hide();
		}
	},
	
	// Helper method to toggle the collapse/expande image
	toggleImage: function(pImage, szNewRelativeImagePath)
	{
		// Regex for obtaining image src base
		var pRegex 		= new RegExp("(.+/).+$");	
		
		// Perform regex and save results to matches array
		var aMatches 	= pRegex.exec(pImage.src);
		
		// Ensure we have a match
		if (aMatches[1] == undefined)
		{
			// Error occured.
			return;
		}
				
		// Set the new image path
		pImage.src = aMatches[1] + szNewRelativeImagePath;
	}
}

Event.observe(window, 'load', VideoSourceCollapser.init);
Event.observe(window, 'load', function() { Semto_Rating.init('rate-episode', VidsTv.getBaseUrl()) });