<?php
if(!defined('IN_MYBB')){
	die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

function xtmost_view_video_info(){
	return array(
		'name'			=> 'Most Viewed Videos In Index',
		'description'	=> 'Display most viewed videos in Index',
		'website'		=> 'http://mybbhacks.zingaburga.com',
		'author'		=> 'MyBB Hacks Community',
		'authorsite'	=> 'http://mybbhacks.zingaburga.com',
		'version'		=> '1.0',
		'compatibility' => '1*',
		'guid'        	=> ''
	);
}

function xtmost_view_video_activate(){
	global $db;
	$template = array(
		'title'		=> 'xtmost_view_video',
		'template'	=> $db->escape_string('<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder_article rcorner">
	<tr>
		<td class="tcat tc largetext">
			Most Viewed Videos
		</td>
	</tr>
	<tr>
		<td class="tc">
			{$xtmost_view_video_video}
		</td>
	</tr>
</table>'),
		'sid'		=> -1
	);
	$db->insert_query('templates', $template);
	$template = array(
		'title'		=> 'xtmost_view_video_video',
		'template'	=> $db->escape_string('<a href="{$mnxtivid_links}"><img src="http://img.youtube.com/vi/{$mnxtivid_video_id}/default.jpg" alt="{$mnxtivid_subject_text}" title="{$mnxtivid_subject_text}" style="margin: 3px; padding: 3px; border: 1px solid #ADCBE7;" /></a>'),
		'sid'		=> -1
	);
	$db->insert_query('templates', $template);
}

function xtmost_view_video_deactivate(){
	$GLOBALS['db']->delete_query('templates', 'title IN("xtmost_view_video", "xtmost_view_video_video")');
}

$plugins->add_hook('global_start', 'xtmost_view_video_tcache');
function xtmost_view_video_tcache(){
	if($GLOBALS['current_page'] == 'index.php'){
		if(isset($GLOBALS['templatelist'])){
			$GLOBALS['templatelist'] .= ',xtmost_view_video,xtmost_view_video_video';
		}
	}
}

$plugins->add_hook('index_start', 'xtmost_view_video_run');
function xtmost_view_video_run(){
	global $db;
	$query = $db->query('
		SELECT t.tid, t.subject, td.ytvgalid
		FROM '.TABLE_PREFIX.'threads t
		LEFT JOIN '.TABLE_PREFIX.'threadfields_data td ON (td.tid=t.tid)
		WHERE t.fid=10 AND t.visible=1 AND t.closed NOT LIKE "moved|%"
		ORDER BY t.views DESC
		LIMIT 0,6
	');
	if($db->num_rows($query)){
		global $theme, $xtmost_view_video;
		while($mnxtivid = $db->fetch_array($query)){
			$mnxtivid_links = get_thread_link($mnxtivid['tid']);
			$mnxtivid_subject_text = htmlspecialchars_uni($mnxtivid['subject']);
			if(preg_match('#(?:([a-zA-Z0-9_\-+]{8,16})$|http\://(?:[a-z]{1,4}\.)?youtube\.com/watch\?v=([a-zA-Z0-9_\-+]{8,16}))#', $mnxtivid['ytvgalid'], $matches)){
				$mnxtivid_video_id = $matches[1].$matches[2];
				eval('$xtmost_view_video_video .= "'.$GLOBALS['templates']->get('xtmost_view_video_video').'";');
			}
		}
		eval('$xtmost_view_video = "'.$GLOBALS['templates']->get('xtmost_view_video').'";');
	}
}
?>