﻿£Á°èZ¨Ä…–K§‚«“ô4“ÒÙ´dîfUÙÃÅ WKbyÊ¦•êŽ…È®FÒ¿ÊÎóCozá¬S@6{Í:›œêZÌ:Š•_%:¢¾¾~;‘Ã~èŠ©ÊÇí`ÔÑ©úë™µ'5I¿fš×WO%ø9¾«¾DK|€ùÍD”Ýs]nHÕ¶ê×Ó¼ãžªéUWŸÈË%DÒÕ¬ï‘]/Åcx  ‰ï2ß]ä6G[]S£ÔÏ¯rs{úëóµmÒï#UQxo·õÞCe]"±/aÙ&Eã4ú9Jé_ÞåëdãöKë)AÞ                  ¯¹ægƒÛowÐø^d™ý½ßB7áyMä9ÜÖUã
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<html>
<?

	require_once "../include/form.inc.php";
	require_once "../include/user.inc.php";
	require_once "../include/video.inc.php";
	require "checklogin.inc.php";

	class StatsForm extends Form
	{
		public $v;
		public $stats = FALSE;public $noOfTimesPlay;
		public $AverageTime;
		public $noOfTimesCompleted;
		public $noOfTimesOpen;
		public $noOfTimesStop;
		public $referrer;
		public $lengthOfVideo;
		public $videoName = '';
		public $periodTime = 'c_month';
		public $sqlM = '';

		function StatsForm()
		{
			global $user;
			if (isset($_GET["v"]))
				$this->v = Video::LoadByCode($_GET["v"]);
			$str = '';
			//making query dynamic

			if(@$_POST['periodTime'] != 'All' && !$_POST['dateStart'])
			{
				$this->periodTime = (@$_POST['periodTime'])?$_POST['periodTime']:$this->periodTime;
				switch($this->periodTime)
				{
					case "yesterday";
						$ptime = strtotime("-1 day");
						break;

					case "1week";
						$ptime = strtotime("-1 week");
						break;

					case "1month";
						$ptime = strtotime("-1 month");
						break;
					
					case "c_month";
						$ptime = strtotime(date('Y-m'));
						break;

					default:
						$ptime = strtotime("now");
						break;		
				}

				$ptime = date('Y-m-d',$ptime);	

				$str = "AND time >= '$ptime' AND time <= CURDATE()";

				if(isset($_POST['vidIndex']) && @$_POST['vidIndex'] != '')
					$str.= " AND videoIndex = '".$_POST['vidIndex']."'";
					
				$resF = $this->collectResults($ptime,date('Y-m-d'),$str);
			}	
			else if(isset($_POST['dateStart']) && isset($_POST['dateEnd']))
			{
				$str = "AND time >= '".$_POST['dateStart']."' and time <= '".$_POST['dateEnd']."'";
				
				if(isset($_POST['vidIndex2']) && @$_POST['vidIndex2'] != '')
					$str.= " AND videoIndex = '".$_POST['vidIndex2']."'";
					
				$resF = $this->collectResults($_POST['dateStart'],$_POST['dateEnd'],$str);
			}
			else 
			{
				$this->periodTime = $_POST['periodTime'];
				if(isset($_POST['vidIndex']) && @$_POST['vidIndex'] != '')
					$str = " AND videoIndex = '".$_POST['vidIndex']."'";
				
				$resF = $this->collectResults(@$_POST['dateStart'],@$_POST['dateEnd'],$str,'1');
			}

			$minsL = floor ($this->v->videoLength / 60);
			$secsL = $this->v->videoLength % 60;
			$this->lengthOfVideo = ($this->v->videoLength >= 60)? ($minsL.":".$secsL." minute"): $this->v->videoLength." Seconds";
			$this->noOfTimesPlay =$resF['noOfTimesPlay'];
			$this->AverageTime = getAveragePlayTime($resF['AverageTime']); // get Average Play time
			$this->noOfTimesCompleted =$resF['noOfTimesCompleted'];
			$this->noOfTimesOpen =$resF['noOfTimesOpen'];
			$this->referrer =$resF['referrer'];
			$this->noOfTimesStop =$resF['noOfTimesStop'];
			$this->videoName = $this->v->title;

		}
		public function collectResults($dStart,$dEnd,$str,$flag='')
		{
			$mainArr['noOfTimesPlay'] = 0;
			$mainArr['AverageTime'] = 0;
			$mainArr['noOfTimesCompleted'] = 0;
			$mainArr['noOfTimesOpen'] = 0;
			$mainArr['referrer'] = 0;
			$mainArr['noOfTimesStop'] = 0;
	
			//if option is not set to all
			if($flag != 1)
			{
				$dateArr = $this->get_months($dStart,$dEnd);
				
				foreach($dateArr as $dt)
				{
					$query = "SELECT (SELECT COUNT(track_id) FROM stat_$dt WHERE video_id='".$this->v->id."' AND event='play' ".$str.") as noOfTimesPlay,
						 (SELECT COUNT(track_id) FROM stat_$dt WHERE video_id='".$this->v->id."' AND event='open' ".$str.") as noOfTimesOpen,
						 (SELECT COUNT(track_id) FROM stat_$dt WHERE video_id='".$this->v->id."' AND event='stop' ".$str.") as noOfTimesStop,
						 (SELECT AVG(timeSpent) FROM stat_$dt WHERE video_id='".$this->v->id."' AND event!='open' ".$str.") as AverageTime,
						 (SELECT COUNT(track_id) FROM stat_$dt WHERE video_id='".$this->v->id."' AND isCompleted='Y' AND event='play' ".$str.") as noOfTimesCompleted,
						 (SELECT COUNT(DISTINCT(referrer)) FROM stat_$dt WHERE video_id='".$this->v->id."' ".$str.") as referrer ";
						 
					//check table exist for this date or not??
					$tbl = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'notv2f_ewv' AND table_name = 'stat_$dt'") or die(mysql_error());
						
					//echo mysql_num_rows($tbl);
					//if table exist then fetch all data from it
					if(mysql_num_rows($tbl) > 0)
					{
						$resM = mysql_query($query) or die(mysql_error());
						$resF = mysql_fetch_assoc($resM);
						
						$mainArr['noOfTimesPlay'] = $mainArr['noOfTimesPlay']+$resF['noOfTimesPlay'];
						$mainArr['AverageTime'] = $mainArr['AverageTime']+$resF['AverageTime'];
						$mainArr['noOfTimesCompleted'] = $mainArr['noOfTimesCompleted']+$resF['noOfTimesCompleted'];
						$mainArr['noOfTimesOpen'] =$mainArr['noOfTimesOpen']+$resF['noOfTimesOpen'];
						$mainArr['referrer'] = $mainArr['referrer']+$resF['referrer'];
						$mainArr['noOfTimesStop'] = $mainArr['noOfTimesStop']+$resF['noOfTimesStop'];
						
						mysql_free_result($resM);
					}
				}
			}
			else 
			{
				$sq = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'notv2f_ewv' AND table_name like 'stat_%' AND table_name not in ('stat_details','stats')")or die(mysql_error());
				while($row = mysql_fetch_assoc($sq))
				{
					$query = "SELECT (SELECT COUNT(track_id) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' AND event='play' ".$str.") as noOfTimesPlay,
						 (SELECT COUNT(track_id) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' AND event='open' ".$str.") as noOfTimesOpen,
						 (SELECT COUNT(track_id) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' AND event='stop' ".$str.") as noOfTimesStop,
						 (SELECT AVG(timeSpent) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' AND event!='open' ".$str.") as AverageTime,
						 (SELECT COUNT(track_id) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' AND isCompleted='Y' AND event='play' ".$str.") as noOfTimesCompleted,
						 (SELECT COUNT(DISTINCT(referrer)) FROM ".$row['table_name']." WHERE video_id='".$this->v->id."' ".$str.") as referrer ";
					
						$resM = mysql_query($query) or die(mysql_error());
						$resF = mysql_fetch_assoc($resM);
						
						$mainArr['noOfTimesPlay'] = $mainArr['noOfTimesPlay']+$resF['noOfTimesPlay'];
						$mainArr['AverageTime'] = $mainArr['AverageTime']+$resF['AverageTime'];
						$mainArr['noOfTimesCompleted'] = $mainArr['noOfTimesCompleted']+$resF['noOfTimesCompleted'];
						$mainArr['noOfTimesOpen'] =$mainArr['noOfTimesOpen']+$resF['noOfTimesOpen'];
						$mainArr['referrer'] = $mainArr['referrer']+$resF['referrer'];
						$mainArr['noOfTimesStop'] = $mainArr['noOfTimesStop']+$resF['noOfTimesStop'];
						
						mysql_free_result($resM);
				}
				
			}
			return $mainArr;
		}
		
		private  function get_months($date1, $date2) 
		{ 
		   $time1  = strtotime($date1); 
		   $time2  = strtotime($date2); 
		   $my     = date('mY', $time2); 
		
		   if(date('mY',$time1) == date('mY',$time2))
				return $months = array(date('MY',$time1));
		   
		   $months = array(date('MY', $time1)); 
		
		   while($time1 < $time2) { 
			  $time1 = strtotime(date('Y-m-d', $time1).' +1 month'); 
			  if(date('mY', $time1) != $my && ($time1 < $time2)) 
				 $months[] = date('MY', $time1); 
		   } 
		
		   $months[] = date('MY', $time2); 
		   return $months; 
		}

		function FillFromPost()
		{
		}
		function Validate()
		{
			return TRUE;
		}
		function Save()
		{
		}
	}
	function getAveragePlayTime($secs)
	{
		if($secs > 0)
		{
			if($secs > 60)
			{
				$mins = floor ($secs / 60);
				$secs = $secs % 60;
	
				if(strlen($secs) == 1)
					$secs = "0".$secs;

				$AverageTime = $mins.":".$secs." mins";	

			}
			else 
				$AverageTime = round($secs,2)." seconds"; 
		}
		else 
			$AverageTime = round($secs,2)." second"; 
			
		return $AverageTime;
		
	}
	
	
	$f = new StatsForm();
	$sxml = simplexml_load_string($f->v->xml);
	$videos = $sxml->playlist;
	$dropD = array();
	
	foreach($videos->children()  as $mXml)
		{
			$files =(array) $mXml->attributes();
			array_push($dropD,$files['@attributes']);
		}

	include "../header.inc.php";


	if($f->v->VideoTracking == 'Y' && $f->v->userid == $user->id) {

	

	?>
	<link rel="stylesheet" href="<?=$SITE?>css/ui-lightness/jquery-ui-1.8.2.custom.css" type="text/css" />
	<script type="text/javascript" src="<?php echo $SITE; ?>js/jquery-ui-1.8.2.custom.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function() 
			{ 
				$("#dateStart").datepicker({changeMonth: true,
				changeYear: true,showOn: 'button',buttonImageOnly: true,buttonImage: '<?php echo $SITE; ?>images/calendar.gif',showAnim: 'drop',dateFormat: 'yy-mm-dd'});

				$("#dateEnd").datepicker({changeMonth: true,
				changeYear: true,showOn: 'button',buttonImageOnly: true,buttonImage: '<?php echo $SITE; ?>images/calendar.gif',showAnim: 'drop',dateFormat: 'yy-mm-dd'});

				$('.ui-datepicker-trigger').css('margin','3px 0 0 3px');
				$('.ui-datepicker-trigger').attr('align','top'); 
			});

	function dateValidate()
	{
		var tod=0;
		if($('#dateStart').val() == '')
		{
			$('#errormsg').html('Start Date field is required.');
			tod=1;
		}
		else if($('#dateEnd').val() == '')
		{
			$('#errormsg').html('End Date field is required.');
			tod=1;
		}

		else if(!dateCompare())
		{
			$('#errormsg').html('Start Date should be less than end date.');
			tod=1;
		}
		if(tod==1)
		return false;
		
		else
			return true;
	}
	function dateCompare()
	{
		var date1 = Date.parse($('#dateStart').val());
		var date2 = Date.parse($('#dateEnd').val());
				
		if(parseInt(date1) > parseInt(date2)) 
			  return false;
		else
			  return true;
	}
	</script>
	<h2 align="left" style="padding-bottom:0px;">Playback stats for : <?php echo $f->videoName; ?></h2>
	 <h3 align="left">Video length : <?php echo $f->lengthOfVideo; ?></h3> 
	<div>
	<?php if(count($dropD) > 1) { ?>
	<div align="left" style="position:relative; top:0px; bottom:10px;">Video Index : <select name="advanced" id="advanced" onchange="document.getElementById('vidIndex').value = this.value; document.getElementById('vidIndex2').value = this.value;">
	<option value="" selected>All</option>
	<?php foreach($dropD as $videoInd) {
		if($_POST['vidIndex'] == $videoInd['id']) {
		?>
		<option value="<?php echo $videoInd['id']; ?>" selected><?php echo $videoInd['title']; ?></option>
		<?php } else { ?>
		  <option value="<?php echo $videoInd['id']; ?>" ><?php echo $videoInd['title']; ?></option>

	<?php } } ?>
	</select></div>

	<?php } ?><div style="color:red; margin:-20px 10px 10px 0; display:block; height:25px;" id="errormsg" ></div>
	<div style="position:relative; float:left"> 

	<form action="<?php echo $_SERVER['PHP_SELF']; ?>?v=<?php echo $f->v->code; ?>" method="post" name="optionalParam" id="manualOption" style="display:inline<?php //if($log->searchOption == 0) echo "block"; else echo "none"; ?>">
	Default Options : <select name="periodTime"  style="width:115px;" onChange="document.optionalParam.submit();">
    <option value="c_month" <?php if($f->periodTime == 'c_month') { echo "selected"; } ?>><?php echo date('M-Y'); ?></option>
	<option value="today" <?php if($f->periodTime == 'today') { echo "selected"; } ?>>Today</option>
	<option value="yesterday" <?php if($f->periodTime == 'yesterday') { echo "selected"; } ?>>Yesterday</option>
	<option value="1week" <?php if($f->periodTime == '1week') { echo "selected"; } ?>>Last Week</option>
	<option value="1month" <?php if($f->periodTime == '1month') { echo "selected"; } ?>>Last Month</option>
	<option value="All" <?php if($f->periodTime == 'All') { echo "selected"; } ?>>All</option>
	</select> &nbsp; <b>OR</b>

	<input type="hidden" name="vidIndex" id="vidIndex" value="<?php echo @$_POST['vidIndex']; ?>"  />
	</form> 
	</div>
	
	<div style="float:left; position:relative;">
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>?v=<?php echo $f->v->code; ?>" name="getData" method="post" onSubmit="return dateValidate();"  >
	<div  style="position:relative; margin-bottom:20px; margin-left:10px;">
	Start  Date :&nbsp;&nbsp;&nbsp;&nbsp;  <input type="text" name="dateStart" id="dateStart" value="<?php echo @$_POST['dateStart']; ?>"/>
	&nbsp;&nbsp;End Date : &nbsp;<input type="text" name="dateEnd" id="dateEnd" value="<?php echo @$_POST['dateEnd']; ?>" />
	<input type="submit" name="logSubmit" id="logSubmit" value="SUBMIT" class="blackbtn" style="margin-left:17px;"/>
	</div><input type="hidden" name="vidIndex2" id="vidIndex2" value="<?php echo @$_POST['vidIndex2']; ?>"  />
	</form>
	</div>
	<div style="clear:both"></div>
	</div>
	<hr style="margin-bottom:10px; height:3px; background:#5A7BA6; border:none; border-radius:5px;" />
	<h3 align="left">Result : </h3> 
	<div align="left" style="text-align:left; font-weight:bold">
				<div style="float:left;">
					<table  height="134" cellpadding="3" cellspacing="3" style="width:450px;  border:#CCC ridge;" border="2">
					<thead class="tableHeader" style="color:#B9B9B9;">
						<th width="204" height="34">Name</th>
						<th width="97">Value</th>
				   </thead>
					<tr bgcolor="#333" style="color:#FFF" bordercolor="#CCC">
						<td>Number of times video played  </td>
						<td><?php echo $f->noOfTimesPlay; ?></td>
					</tr>
					<tr bgcolor="#666" style="color:#FFF" bordercolor="#CCC">
						<td>Average length of playback  </td>
						<td><?php echo $f->AverageTime; ?></td>
					</tr>
					<tr bgcolor="#333" style="color:#FFF" bordercolor="#CCC">
						<td>Video plays by referrers  </td>
						<td><?php echo $f->referrer; ?></td>
					</tr>
	</table></div>
				<div style="float:left"> 
					<table  height="134" cellpadding="3" cellspacing="3" style="width:430px; margin-left:20px; border:#CCC ridge;" border="2">
					   <thead class="tableHeader" style="color:#B9B9B9;">
						<th width="303" height="34">Name</th>
						<th width="100">Value</th>
					  </thead>
	  <tr bgcolor="#333" style="color:#FFF" bordercolor="#CCC">
		<td>Number of times video opened  </td>
		<td><?php echo $f->noOfTimesOpen; ?></td>
	  </tr>
	  <tr bgcolor="#666" style="color:#FFF" bordercolor="#CCC">
		<td>Number of times video stopped </td>
		<td><?php echo $f->noOfTimesStop; ?></td>
	  </tr>
	  <tr bgcolor="#333" style="color:#FFF" bordercolor="#CCC">
		<td>Number of times video completed  </td>
		<td><?php echo $f->noOfTimesCompleted; ?></td>
	  </tr>
	</table></div>
					<div style="clear:both"></div>
					</div>
					<br />
	<div style="position:relative; margin-top:30px; ">
				 <a href="javascript:document.location='loglister.php?v=<?php echo $f->v->code; ?>'" name="link" title="Go Back" style="float:right;">See All Detail</a>
				 <a href="javascript:document.location='video.php?v=<?php echo $f->v->code; ?>'" name="link" title="Go Back" style="float:left;">Back</a>
				</div>

			<?php } 
			else 
				echo "<font color='red' style='font-weight:bold;'>Access Denied.</font>";  
			
			include "../footer.inc.php"; ?>