YAHOO.namespace("youporn.tabs"); 

YAHOO.youporn.tabs = function () {
	var THUMBS_PER_ROW = 4;
	var thumbnailIsSet = false;
	
	function createVideoInfoTabview (producer_id) {
		var videoInfoTabview = new YAHOO.widget.TabView('videoInfoTabview');
		
		videoInfoTabview.on('contentReady', function() {
			// add thumbnails tab
			var num_thumbnails = videoInfoTabview.get('element').getAttribute("thumbnails");
			videoInfoTabview.addTab(new YAHOO.widget.Tab({
				label: 'Thumbnails (' + num_thumbnails + ')',
				content: ''
			}), 1);    					
		});		

		videoInfoTabview.on('activeTabChange', function(e) {
			var selectedTab = this.getTab(this.getTabIndex(e.newValue));
			
			if (selectedTab.get('label').indexOf('Thumbnails') == 0 && !thumbnailIsSet) {
				var video_id       = videoInfoTabview.get('element').getAttribute("video");
				var num_thumbnails = videoInfoTabview.get('element').getAttribute("thumbnails");
				var dir_split      = videoInfoTabview.get('element').getAttribute("dirsplit");
				var multiple_thumbnail_url = videoInfoTabview.get('element').getAttribute("multiple_thumbnail_url");
				
				selectedTab.set('content', writeThumbnails(video_id, num_thumbnails, dir_split, producer_id, multiple_thumbnail_url));
				
				thumbnailIsSet = true; 
			}
		});   				
	}
	
	function writeThumbnails (video_id, n, dir_split, producer_id, multiple_thumbnail_url) {
		var html = '<div id="thumbnails">';
		
		if (n > 0) {
			if (n == 1) {
				html += '<h2>' + n + ' thumbnail </h2>';
			} 
			else {
				html += '<h2>' + n + ' thumbnails </h2>';
			}

			for (i=1; i<=n; i++) {
				if (i==1) { 
					html += '<ul class="clearfix">'; 
				}

				var url;
				if (producer_id == 18) {
					url = multiple_thumbnail_url + '/' + i + '.jpg?cb=1';
				}
				else {
					url = 'http://ss-' + ((video_id % 3) + 1) + '.youporn.com/screenshot/' + dir_split + 'screenshot_multiple/' + video_id + '/' + video_id + '_multiple_' + i + '_large.jpg';				
				}
				
				if ((i % THUMBS_PER_ROW) == 0) {
					html += '<li class="last">';
				}
				else {
					html += '<li>';
				}
				html += '<img src="' + url + '" width="120" height="90" />';
				html += '</li>';

				if (i==n) {
					html += '</ul>';
				} 
				else if ((i % THUMBS_PER_ROW) == 0) {
					html += '</ul>';
					html += '<ul class="last clearfix">';
				}
			}
		} 
		else {
			html += '<h2>There are no thumbnails for this video.</h2>';
		}
		html += '</div>';
		return html;
	};
	
	return {
		init: function (producer_id) {
			createVideoInfoTabview(producer_id);
			new YAHOO.widget.TabView('moreVideosTabview');
		}
	};
}();

