<?php
defined('_VALID') or die('Restricted Access!');

require $config['BASE_DIR']. '/classes/filter.class.php';
require $config['BASE_DIR']. '/include/adodb/adodb.inc.php';
require $config['BASE_DIR']. '/classes/pagination.class.php';
require $config['BASE_DIR']. '/include/compat/json.php';
require $config['BASE_DIR']. '/include/dbconn.php';

disableRegisterGlobals();

function clean( $string )
{
    $string = ereg_replace('[^ 0-9a-zA-Z]', ' ', $string);
    $string = preg_replace('/\s\s+/', ' ', $string);
    $string = trim($string);
    $string = str_replace(' ', '-', $string);
    
    return strtolower($string);
}

function truncate( $string, $length=80)
{
    if ( $length == 0 ) {
        return '';
    }
    
    if (strlen($string) > $length) {
        $etc     = ' ...';
        $length -= min($length, strlen($etc));
        return substr($string, 0, $length) . $etc;
    } else {
        return $string;
    }
}

function duration( $duration)
{
    $duration_formated  = NULL;
    $duration           = round($duration);
    if ( $duration > 3600 ) {
        $hours              = floor($duration/3600);
        $duration_formated .= sprintf('%02d',$hours). ':';
        $duration           = round($duration-($hours*3600));
    }
    if ( $duration > 60 ) {
        $minutes            = floor($duration/60);
        $duration_formated .= sprintf('%02d', $minutes). ':';
        $duration           = round($duration-($minutes*60));
    } else {
        $duration_formated .= '00:';
    }
                                    
    return $duration_formated . sprintf('%02d', $duration);
}

function time_range( $time )
{
    $range          = NULL;
    $current_time   = time();
    $interval       = $current_time-$time;
    if ( $interval > 0 ) {
        $day    = $interval/(60*60*24);
        if ( $day >= 1 ) {
            $range      = floor($day). ' days';
            $interval   = $interval-(60*60*24*floor($day));
        }
        if( $interval > 0 && $range == '' ) {
            $hour       = $interval/(60*60);
            if ( $hour >=1 ) {
                $range      = floor($hour). ' hours';
                $interval   = $interval-(60*60*floor($hour));
            }
        }
        if ( $interval > 0 && $range == '' ) {
            $min        = $interval/(60);
            if ( $min >= 1 ) {
                $range=floor($min). ' minutes';
                $interval=$interval-(60*floor($min));
            }
        }
        if ( $interval > 0 && $range == '' ) {
            $scn        = $interval;
            if ( $scn >= 1 ) {
                $range  = $scn. ' seconds';
            }
        }
        return ( $range != '' ) ? $range. ' ago' : 'just now';                                                                                                                                                                                                                                                                                           
    }
}

function video_rating_small( $rate )
{
    $class_1    = '';
    $class_2    = '';
    $class_3    = '';
    $class_4    = '';
    $class_5    = '';
    if ( $rate > 0.5 ) {
        $class_1 = ' class="half"';
        if ( $rate >= 1 ) {
            $class_1 = ' class="full"';
        }
        if ( $rate >= 2 ) {
            $class_2 = ' class="full"';
        } elseif ( $rate >= 1.5 ) {
            $class_2 = ' class="half"';
        }
        if ( $rate >= 3 ) {
            $class_3 = ' class="full"';
        } elseif ( $rate >= 2.5 ) {
            $class_3 = ' class="half"';
        }
        if ( $rate >= 4 ) {
            $class_4 = ' class="full"';
        } elseif ( $rate >= 3.5 ) {
            $class_4 = ' class="half"';
        }
        if ( $rate >= 5 ) {
            $class_5 = ' class="full"';
        } elseif ( $rate >= 4.5 ) {
            $class_5 = ' class="half"';
        }                                                                                                                                                                                                                                        
    } 
    
    $output     = array();
    $output[]   = '<ul class="rating_small">';
    $output[]   = '<li><span' .$class_5. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_4. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_3. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_2. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_1. '>&nbsp;</span></li>';
    $output[]   = '</ul>';
    
    return implode("\n", $output);                                                           
}                                                                            

$data   = array('status' => 0, 'videos' => '', 'page' => 0, 'pages' => 0, 'debug' => '');
if ( isset($_POST['video_id']) && isset($_POST['move']) && isset($_POST['page']) ) {
    $filter         = new VFilter();
    $vid            = $filter->get('video_id', 'INTEGER');
    $page           = $filter->get('page', 'INTEGER');
    $move           = ( $_POST['move'] == 'next' ) ? 'next' : 'prev';
    if ( $move == 'prev' ) {
        $page   = ( $page < 1 ) ? 1: $page-1;
    } else {
        $page   = $page+1;
    }
    
    $sql            = "SELECT title, channel, keyword, type FROM video WHERE VID = " .$vid. " LIMIT 1";
    $rs             = $conn->execute($sql);
    $video          = $rs->getrows();
    $video          = $video['0'];
    
    $sql_add        = NULL;
    if ( $video['keyword'] ) {
        $keywords   = explode(' ', $video['keyword']);
        $sql_add   .= " OR (";
        $sql_or     = NULL;
        foreach ( $keywords as $keyword ) {
            $sql_add .= $sql_or. " keyword LIKE '%" .mysql_real_escape_string($keyword). "%'";
            $sql_or   = " OR ";
        }
        $sql_add   .= ")";
    }
    
	$type			= ($config['show_private_videos'] == '1') ? '' : " AND type = 'public'";
    $sql            = "SELECT COUNT(VID) AS total_videos FROM video WHERE channel = '" .$video['channel']. "' AND VID != " .$vid. "
					   AND active = '1'" .$type. "
                       AND ( title LIKE '%" .mysql_real_escape_string($video['title']). "%' " .$sql_add. ")";
    $rs             = $conn->execute($sql);
    $total          = $rs->fields['total_videos'];
    if ( $total > 100 ) {
	$total = 100;
    }
    $total          = ( $total > 100 ) ? 100 : $total;
    $pagination     = new Pagination(10, $page);
    $limit          = $pagination->getLimit($total);
    $sql            = "SELECT VID, title, duration, addtime, rate, viewnumber, type, thumb
	                   FROM video 
                       WHERE channel = '" .intval($video['channel']). "' AND VID != " .$vid. "
					   AND active = '1'" .$type. "
                       AND ( title LIKE '%" .mysql_real_escape_string($video['title']). "%' " .$sql_add. ")
                       ORDER BY addtime DESC LIMIT " .$limit;
    $rs             = $conn->execute($sql);
    $videos         = $rs->getrows();
    $code           = array();
    $total_pages    = $pagination->getTotalPages();
    $page           = ( $page >= $total_pages ) ? $total_pages : $page;
	$private_img    = '<img alt="" style="position: absolute; left: 0px; top: +0px; width: 160px; height: 120px;" src="'.$config['BASE_URL'].'/templates/frontend/' .$config['template']. '/images/private-video.png" />';
    foreach ( $videos as $video ) {
        $code[]     = '<div class="video_box_related">';
        $code[]     = '<a href="' .$config['BASE_URL']. '/video/' .$video['VID']. '/' .clean($video['title']). '">';
        $code[]     = '<span class="font-13 font-bold">' .htmlspecialchars(truncate($video['title'], 21), ENT_QUOTES, 'UTF-8'). '</span><br />';
        $code[]     = '<img src="' .$config['BASE_URL']. '/media/videos/tmb/' .$video['VID']. '/'.$video['thumb'].'.jpg" title="' .htmlspecialchars($video['title'], ENT_QUOTES, 'UTF-8'). '" alt="' .htmlspecialchars($video['title'], ENT_QUOTES, 'UTF-8'). '" width="160" height="120" id="rotate_' .$video['VID']. '" /><br />';
		if ($video['type'] == 'private') {
			$code[] = $private_img;
		}
        $code[]     = '</a>';
        $code[]     = '<div class="vbox_rel_left">';
        $code[]     = duration($video['duration']). '<br />';
        $code[]     = time_range($video['addtime']);
        $code[]     = '</div>';
        $code[]     = '<div class="vbox_rel_right">';
        $code[]     = video_rating_small($video['rate']);
        $code[]     = '<div class="clear_right"></div>';
        $code[]     = $video['viewnumber']. ' views';
        $code[]     = '</div>';
        $code[]     = '<div class="clear"></div>';
        $code[]     = '</div>';
    }
    
    $data['page']   = $page;
    $data['status'] = ( $total_pages > 1 ) ? 1 : 0;
    $data['videos'] = implode("\n", $code);
    $data['pages']  = $total_pages;
}

echo json_encode($data);
die();
?>
