<?php
	include_once("lib/php/include/db.php");
	$dbarb = ConnectToRead();
	if(isset($_GET['vid']) && $_GET['vid'] != '')
		$sql = 'select * from rep_videos where id = '.$_GET['vid'].' limit 1';
	else
		$sql = 'select * from rep_videos where duration <= 60 order by rand() limit 1';
	$result = mysql_query($sql, $dbarb);
	$videoarb = mysql_fetch_assoc($result);
	
	echo "<!-- ConnectionParams";
	var_dump($dbarb, $sql, $result, mysql_error());
	echo "-->";
	
	if($videoarb['id'] < 10) {
		$videoarb['id'] = '00'.$videoarb['id'];
	} else if($videoarb['id'] >= 10 && $videoarb['id'] < 100) {
		$videoarb['id'] = '0'.$videoarb['id'];
	}
	
	if($videoarb['id'] == '00' || $videoarb['id'] == '') {
		$videoarb['id'] = rand(101, 2400);
	}

	$video_title = $videoarb['title'];
	$video_description = $videoarb['description'];
	$video_category = $videoarb['keywords'];
	
	function ConnectToMyCustomAdminVideoArb(){
		$db = ConnectToRead();
		return $db;
	}
?>
<div id="video_box" style="width:<?php echo $width; ?>px; height:<?php echo $height; ?>px; background-color:#000;" itemprop="video" itemscope itemtype="http://schema.org/VideoObject">
	<div id="video" style="width:<?php echo $width; ?>px; height:<?php echo $height; ?>px;">
		<?php if(!$_GET['d']) { ?>
		<div style="padding-top:80px;width:360px; height:240px; margin:0 auto;"><img src="http://b36df47b3d.site.internapcdn.net/video-play-button.png" width="360" height="240" onclick="loadLiverail('video')" id="playbutton"></div>
		<?php } ?>
	</div>
	<?php
		class aff_mCachedbArb extends Memcache {
			static private $instance = null;
			static private $port = 11211;
			static function mGet() {
				if (self::$instance == null) {
					self::$instance = new Memcache;
					self::$instance->addServer("192.168.30.51", self::$port);
				}
				return self::$instance;
			}
		}

		function get_domain_id_arb($url)
		{
			$pieces = parse_url('http://'.$url);
			$domain = isset($pieces['host']) ? $pieces['host'] : '';
			if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
				return $regs['domain'];
			}
			return false;
		}
		$idurl = get_domain_id_arb($_SERVER['HTTP_HOST']);

		parse_str(parse_url('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], PHP_URL_QUERY), $qs);
		$cid = ((isset($qs['cid'])) ? $qs['cid'] : '');

		$badreferrer = true;
		include_once 'lib/php/api/adsafe/api.php';
		$ad_safe = new _AdSafe();
		$url = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
		if($ad_safe->isSafe($url)){
			$badreferrer = false;
		}

		echo "<!-- *******-1***** Bad ref: $badreferrer; sref: {$_SERVER['HTTP_REFERER']}; url: $url -->";

		if((isset($_GET['usf']) && $_GET['usf'] == 1)) {
			$badreferrer = true;
		}

		echo "<!-- *******0***** Bad ref: $badreferrer; sref: {$_SERVER['HTTP_REFERER']}; url: $url -->";

		if($_SERVER['HTTP_REFERER'] == null || $_SERVER['HTTP_REFERER'] == ''){
			//for blank refs, block only if set in Affiliate table
			$sql = "SELECT blank_refs from AffiliateIDs ai, Affiliate a where ai.affiliate = a.name and ai.id=".addslashes($cid);
			$mkey = md5($sql);
			if(!$block = aff_mCachedbArb::mGet()->get($mkey)){
				$db = ConnectToMyCustomAdminVideoArb();
				$res = mysql_query($sql,$db);
				while($row = mysql_fetch_array($res)){
					$blank_ref = $row['blank_refs'];	//if 1, block ads for blank refs
				}
				$block = array("block_blank_refs"=>$blank_ref);
				aff_mCachedbArb::mGet()->set($mkey, $block, 0, 60*60);
				mysql_close($db);
			}
			if($block["block_blank_refs"] == "1") {
				$badreferrer = true;
			} else {
				$badreferrer = false;
			}
		}

		echo "<!-- *******1***** Bad ref: $badreferrer; sref: {$_SERVER['HTTP_REFERER']}; url: $url -->";

		$master_cache_key = md5('affid_'.$idurl);
		$site_aff_id = aff_mCachedbArb::mGet()->get($master_cache_key);
		if(!$site_aff_id) {
			$l_aff = ConnectToMyCustomAdminVideoArb();
			$q_aff = "select id from AffiliateIDs where Affiliate in (select name from Affiliate where sitename = '".$idurl."') limit 1";
			$r_aff = mysql_query($q_aff, $l_aff);
			$row_aff = mysql_fetch_row($r_aff);
			$site_aff_id = $row_aff[0];
			if($site_aff_id) {
				aff_mCachedbArb::mGet()->set($master_cache_key, $site_aff_id, 0, 60*60*24*30);
			} else {
				aff_mCachedbArb::mGet()->set($master_cache_key, $idurl, 0, 60*60*3);
			}
			mysql_close($db);
		}
		if(isset($_GET['d']) && $_GET['d'] == 1){ 
			if(isset($_GET['cid']) && $_GET['cid']!=""){
				$ga_cid = $_GET['cid'];
			}
			if($ga_cid){
				$sitename_ga = $_SERVER['HTTP_HOST'];
				$sitename_ga = str_replace("http://","",$sitename_ga);
				$sitename_ga = str_replace("www.","",$sitename_ga);
				$sitename_ga = str_replace(".com","",$sitename_ga);
				$sitename_ga = str_replace(".net","",$sitename_ga);
				$sitename_ga .= "_".$ga_cid;

		?>
		<script>
		  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

		  ga('create', 'UA-40214058-12', '<?=$sitename_ga?>');
		  ga('send', 'pageview');

		</script>
		<?
			}
		}
		?>
	<script type="text/javascript" src="http://player.admedia.com/?site=<?php echo $amid; ?>"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/spin.js/1.3.2/spin.min.js"></script>
	<script type="text/javascript" src="http://s.colo.com/jwplayer.js"></script>
	<script>
		<?php if(isset($_GET['d']) && $_GET['d'] == 1){ ?>
			var sptg = document.getElementById('video_box');
			var spinner = new Spinner({color: '#fff'}).spin(sptg);
			window.onbeforeunload = confirmExit;
			function confirmExit() {
				return 'Are you sure you want to exit this page?';
			}
		<?php } ?>
		var injected = false;
		var fired = false;
		var pix1 = false;
		var pix2 = false;
		var ply = false;
	
		var loadLiverail = function(el){
			load_adm_player(el);
			return;
			<?php 
			//we are using admedia's player to play the preroll.
			?>
			var LiveRailVPAID,
			vpaidFrame,
			vpaidLoader,
			adElement = document.getElementById(el);
			
			function onVPAIDLoad() {
			   LiveRailVPAID.subscribe(function() { 
					<?php if(isset($_GET['d']) && $_GET['d'] == 1){ ?>spinner.stop();<?php } ?>
					LiveRailVPAID.startAd();
					if(el == 'video') {
						if(!injected) {
							injected = true;
						}
					}
			   }, 'AdLoaded');
			   LiveRailVPAID.subscribe(function() {
					<?php if(isset($_GET['d']) && $_GET['d'] == 1){ ?>spinner.stop();<?php } ?>
					if(el == 'video') {
						if(!injected) {
							injected = true;
						}
					}
			   }, 'AdStarted');
			   LiveRailVPAID.subscribe(function() {
				<?php if($cid == 43973) { ?>
					if(fired == false) {
						var img = document.createElement('img'); img.height = '1'; img.width = '1';
						img.src = 'http://www.advconversion.com/ads-conversiontrack/conversion/track.do?type=img&advertiserId=65313';
						document.getElementsByTagName('body')[0].appendChild(img);
						fired = true;
					}
				<?php } ?>
				<?php if($cid) { ?>
					if(pix1 == false) {
						var img = document.createElement('img'); img.height = '1'; img.width = '1';
						img.src = 'http://pixel.admedia.com/varb.php?aid=<?php echo $cid; ?>&site=<?php echo $_SERVER['HTTP_HOST']; ?>&start=1';
						document.getElementsByTagName('body')[0].appendChild(img);
						pix1 = true;
					}
					ply = true;
				<?php } ?>
			   }, 'AdImpression');
			   LiveRailVPAID.subscribe(function(msg) { 
			   }, 'AdLog');
			   LiveRailVPAID.subscribe(function() {
				<?php if($cid) { ?>
					if(ply == true && pix2 == false) {
						var img = document.createElement('img'); img.height = '1'; img.width = '1';
						img.src = 'http://pixel.admedia.com/varb.php?aid=<?php echo $cid; ?>&site=<?php echo $_SERVER['HTTP_HOST']; ?>&end=1';
						document.getElementsByTagName('body')[0].appendChild(img);
						pix2 = true;
					}
				<?php } ?>
			   }, 'AdVideoComplete');
			   LiveRailVPAID.subscribe(function() {
				<?php if($cid) { ?>
					if(ply == true && pix2 == false) {
						var img = document.createElement('img'); img.height = '1'; img.width = '1';
						img.src = 'http://pixel.admedia.com/varb.php?aid=<?php echo $cid; ?>&site=<?php echo $_SERVER['HTTP_HOST']; ?>&end=1';
						document.getElementsByTagName('body')[0].appendChild(img);
						pix2 = true;
					}
				<?php } ?>
					<?php if(isset($_GET['d']) && $_GET['d'] == 1){ ?>spinner.stop();<?php } ?>
					if(el == 'video') {
						playVideo();
						if(!injected) {
							injected = true;
						}
					} else if (el == 'video_wrapper') {
						header = document.getElementById('video_box');
						header.style.display = 'none';
					}
			   }, 'AdStopped');
			   LiveRailVPAID.subscribe(function(message) {
					<?php if(isset($_GET['d']) && $_GET['d'] == 1){ ?>spinner.stop();<?php } ?>
					if(el == 'video') {
						playVideo();
						if(!injected) {
							injected = true;
						}
					} else if (el == 'video_wrapper') {
						header = document.getElementById('video_box');
						header.style.display = 'none';
					}
			   }, 'AdError');
			   
			   LiveRailVPAID.initAd(adElement.offsetWidth, adElement.offsetHeight, 'normal', 600, creativeData, environmentVars);
			}
			 
			vpaidFrame = document.createElement('iframe');
			vpaidFrame.style.display = 'none';
			vpaidFrame.onload = function() {
				vpaidLoader = vpaidFrame.contentWindow.document.createElement('script');
				vpaidLoader.src = 'http://cdn-static.liverail.com/js/LiveRail.AdManager-1.0.js';
				vpaidLoader.onload = function() {
					LiveRailVPAID = vpaidFrame.contentWindow.getVPAIDAd();
					LiveRailVPAID.handshakeVersion('2.0');
					onVPAIDLoad();
				};
				vpaidFrame.contentWindow.document.body.appendChild(vpaidLoader);
			};
			document.body.appendChild(vpaidFrame);

			<?php 
			if($_GET['campaign'] == "apnx")
				$lr_vertical = ",cpc_arb";
			else
				$lr_vertical = "";
			if(isset($_GET['cid']) && $_GET['cid']!=""){
				$amid .= "_".$_GET['cid'];
				$affCpcArb_vertical = ',aff_cpc_arb';
			}
			
			$ctp = '';
			if(!$_GET['d']) {
				$ctp = ',clicktoplay';
			}
			
			
			function getLRID($aid){
				$aSql = "select lr_id from AffiliateIDs where id = {$aid} limit 1";
				$mkey = 'aff_lrid_'.md5($aid);
				$expire = 60*20;
				if(!$aff_lrid = aff_mCachedbArb::mGet()->get($mkey)){
					$db = ConnectToRead();
					$aRes = mysql_query($aSql, $db);
					if($aRes){
						$aRow = mysql_fetch_assoc($aRes);
						if($aRow && $aRow['lr_id'] != ''){
							$aff_lrid = $aRow['lr_id'];
							if($aff_lrid > 0)
								aff_mCachedbArb::mGet()->set($mkey, $aff_lrid, 0, $expire);
							else
								aff_mCachedbArb::mGet()->set($mkey, "NONE000", 0, $expire);
						}
					}
					mysql_close($db);
				}
				if(!is_numeric($aff_lrid)){
					$aff_lrid = 0;
				}
				return intval($aff_lrid);
			}
			
			$lr_publisher_id = getLRID($amid);
			if(!$lr_publisher_id){
				$lr_publisher_id = 109659;
			}
			?>
			var creativeData = {},
			environmentVars = {
				slot: adElement,
				LR_ENVIRONMENT: 'flash',
				//LR_PUBLISHER_ID: 1331,
				LR_PUBLISHER_ID: <? echo intval($lr_publisher_id);?>,
				LR_VIDEO_AMID: 'vast_<?php echo $amid; ?>',
				LR_TAGS: '<?php echo (($_GET['usf'] == 1) ? $amid.'_backfill'.$ctp : ''.substr($ctp, 1)) ?>',
				LR_AUTOPLAY: 1,
				LR_CONTENT:1,
				LR_VERTICALS:'site',
				LR_LAYOUT_SKIN_ID:2,
				LR_COMPANIONS:'300:250:adm_vsldr_cmp',
				LR_CUSTOM1: document.location.href	//for spotx content_page_url
			};			
		}

		
		function load_adm_player(el){
			adm_player.init({player_id:el,video_url:'http://s.colo.com/<?php echo $videoarb['id']; ?>.mp4', width:"<?php echo $width; ?>",height:"<?php echo $height; ?>", title:"<?php echo $video_title; ?>", description:"<?php echo $video_description; ?>", category:"<?php echo $video_category; ?>"});
		}
		<?php if($_GET['d'] && $_GET['d'] == 1) { ?>
		
			<?php if(isset($badreferrer) && $badreferrer == false) { ?>
			loadLiverail('video');
			<?php } else { ?>
			playVideo();
			<?php } ?>
		
		<?php } ?>
	</script>
	<script type="text/javascript">
		var playVideo = function() {
			var adElement = document.getElementById('video');
			var vidUrl = 'http://s.colo.com/<?php echo $videoarb['id']; ?>.mp4';
			jwplayer('video').setup({
				file: vidUrl,
				width: <?php echo $width; ?>,
				height: <?php echo $height; ?>,
				flashplayer: 'http://s.colo.com/player.swf',
				stretching: 'fill',
				autostart: true
			}).onComplete(function() {
				document.getElementById('video_wrapper').innerHTML = '';
				<?php if(isset($badreferrer) && $badreferrer == false && !stristr($_SERVER['HTTP_HOST'], 'sandglass.tv')) { ?>
				loadLiverail('video_wrapper');
				<?php } else { ?>
				header = document.getElementById('video_box');
				header.style.display = 'none';
				<?php } ?>
			});
		}
	</script>
	<meta itemprop="name" content="<?php echo $videoarb['title']; ?>" />
	<meta itemprop="description" content="<?php echo $videoarb['description']; ?>" />
	<meta itemprop="duration" content="<?php echo ltrim(gmdate("\P\Ti\Ms\S", $videoarb['duration']), '0'); ?>" />
	<meta itemprop="thumbnailUrl" content="http://s.colo.com/<?php echo $videoarb['id']; ?>.jpeg" />
	<meta itemprop="contentURL" content="http://s.colo.com/<?php echo $videoarb['id']; ?>.mp4" />
	<meta itemprop="height" content="<?php echo $width; ?>" />
	<meta itemprop="width" content="<?php echo $height; ?>" />
</div>