<?php

class Ads extends Controller{

	/**
	 * @param $f3 \Base
	 */
	public function getIndex($f3){

		// Template settings
		$f3->set('active','ads');
		$f3->set('inc_bottom', 'ads-bottom.html');
		$f3->set('title',$f3->get('lang_ads'));

		// Load available ads for listing
		$res_ads = new \Models\Ad();
		if ($f3->get('USER')->role < 8){
			$ads = $res_ads->find(array('advertiser=?',$f3->get('USER')->_id));
			$f3->set('inc','ads-advertiser.html');
		} else {
			$ads = $res_ads->find();
			$f3->set('inc','ads.html');
		}


		// Get ad stats
		$statsData = new Statsdata();
		$adStats = $statsData->DashboardTopAds(7, false);

		$res_ads = array();
		if ($ads){
			$count = 1;
			foreach ($ads as $ad) {
				$res_ad = array();
				$res_ad['id'] = $ad->_id;
				$res_ad['title'] = '<a href="index.php?ads&edit&'.$ad->_id.'">'.$ad->title.'</a>';
				$res_ad['approved'] = $ad->approved;
				if ((!empty($ad->start_date)) && (strtotime($ad->start_date) > time())){
					$res_ad['status_type'] = 'info';
					$res_ad['status_text'] = $f3->get('lang_scheduled');
				} elseif ((!empty($ad->end_date)) && (strtotime($ad->end_date) < time()) && ($ad->status == 0)) {
					$res_ad['status_type'] = 'danger';
					$res_ad['status_text'] = $f3->get('lang_ended');
				} elseif ((!empty($ad->end_date)) && (strtotime($ad->end_date) < strtotime("7 days"))) {
					$res_ad['status_type'] = 'warning';
					$res_ad['status_text'] = $f3->get('lang_ending');
				} elseif ($ad->status == 1) {
					$res_ad['status_type'] = 'success';
					$res_ad['status_text'] = $f3->get('lang_on');
				} else {
					$res_ad['status_type'] = 'danger';
					$res_ad['status_text'] = $f3->get('lang_off');
				}
				$res_ad['last_updated'] = date('Y/m/d H:i:s', $ad->last_updated);
				$res_ad['groups'] = $ad->groups;
				$res_ad['advertiser'] = $ad->advertiser  ? '<a href="index.php?users&edit&'.$ad->advertiser->_id.'">'.$ad->advertiser->username.'</a>' : '-';
				$res_ad['impressions'] = array_key_exists($ad->_id, $adStats)  ? $adStats[$ad->_id]['impressions'] : 0;
				$res_ad['clicks'] = array_key_exists($ad->_id, $adStats) ? $adStats[$ad->_id]['clicks'] : 0;
				$res_ad['limit_end_date'] = (($ad->limit_start_date) && ($ad->limit_time)) ? date('Y-m-d',strtotime('+'.$ad->limit_time.' days', $ad->limit_start_date)) : '-';
				$res_ad['limit_reached_date'] = $ad->limit_reached_date ? $ad->limit_reached_date : '-';
				$res_ad['img']  = '';
				switch ($ad->type){
					case 'banner':
						$res_ad['type'] = 'fa-picture-o';
						$res_ad['img'] = $ad->type_banner->src_lg ? '<img src="'.$ad->type_banner->src_lg.'" height="12" width="24" alt="" />' : '';
						break;
					case 'textlink':
						$res_ad['type'] = 'fa-external-link';
						break;
					case 'video':
						$res_ad['type'] = 'fa-video-camera';
						break;
					case 'freeform':
						$res_ad['type'] = 'fa-square-o';
						break;
				}
				$res_ad['count'] = $count;
				$res_ads[] = $res_ad;
				$count++;
			}
		}
		$f3->set('res_ads',$res_ads);

		echo Template::instance()->render('layout.html');

	}

	/**
	 * @param $f3 \Base
	 */
	public function getCreateSelect($f3){

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		// Template settings
		$f3->set('active','ads');
		$f3->set('inc','ads-select.html');
		$f3->set('inc_bottom', null);
		$f3->set('title',$f3->get('lang_ads'));
		echo Template::instance()->render('layout.html');
	}

	/**
	 * @param $f3 \Base
	 */
	public function getCreate($f3){

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		$type = $f3->get('PARAMS.type');
		if (!$type) $f3->reroute('/index.php?ads&create');

		$type = strtolower($type);
		if (($type != 'banner') && ($type != 'freeform')
				&& ($type != 'textlink') && ($type != 'video'))
			$f3->reroute('/index.php?ads&create');

		$f3->set('include_type', 'ads-edit-type-'.$type.'.html');

		// Template settings
		$f3->set('active','ads');
		$f3->set('inc','ads-edit.html');
		$f3->set('inc_bottom', 'ads-edit-bottom.html');
		$f3->set('title',$f3->get('lang_ads'));

		// Create a blank ad model
		$ad = new \Models\Ad();
		$ad->type = $type;
		$f3->set('ad',$ad);

		// Load available groups for listing
		$res_groups = new \Models\Group();
		$groups = $res_groups->find(null, array('order'=>'title'));
		$f3->set('res_groups',$groups);
		$f3->set('group_ids',array());


		$res_users = new \Models\User();
		$users = $res_users->find(array('role = ?', 1), array('order'=>'username'));
		$f3->set('res_users',$users);

		// Load countries
		$f3->set('arrCountries',Geo::getCountries());

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postCreate($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?ads&list');

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		$type = $f3->get('POST.type');
		if (!$type) $f3->reroute('/index.php?ads&create');

		$type = strtolower($type);
		if (($type != 'banner') && ($type != 'freeform')
				&& ($type != 'textlink') && ($type != 'video'))
			$f3->reroute('/index.php?ads&create');

		if ($f3->get('POST.advertiser') == '') $f3->set('POST.advertiser', null);

		// Set the start date as now if using a limiter, assuming ad is enabled
		if (($f3->get('POST.limit_time') != '') && ($f3->get('POST.status') == '1')){
			$f3->set('POST.limit_start_date', time());
		}

		$result = false;
		try {
			$ad = new \Models\Ad();
			$result = $ad->post($f3, $params, false);

			if ($f3->get('POST.test') != '1'){

				$result ? $f3->reroute('/index.php?ads&list') : $f3->reroute('/index.php?ads&create&'.$type);
			}
		} catch (Exception $e){
			Utils::Logger('postCreate:Error posting ad - '.$e);
		}

	}


	/**
	 * @param $f3 \Base
	 */
	public function getEdit($f3){

		$userSql = '';
		// Less than admins/super admins can only see their ads
		if ($f3->get('USER')->role < 8){
			$userSql = ' AND advertiser='.$f3->get('USER')->_id;
		}

		$id = $f3->get('PARAMS.id');
		$ad = new \Models\Ad();
		$ad->load(array('_id = ?'.$userSql, $id));
		if ($ad->dry()) $f3->reroute('/index.php?ads&list');
		$f3->set('ad', $ad);

		$f3->set('include_type', 'ads-edit-type-'.$ad->type.'.html');

		// Template settings
		$f3->set('active','ads');
		$f3->set('inc','ads-edit.html');
		$f3->set('inc_bottom', 'ads-edit-bottom.html');
		$f3->set('title',$f3->get('lang_ads'));

		$f3->set('time_last_updated', date('Y/m/d H:i:s', $ad->last_updated));

		if ($f3->get('USER')->role < 8){
			echo Template::instance()->render('layout.html');
			return;
		}

		// Load available groups for listing
		$res_groups = new \Models\Group();
		$groups = $res_groups->find(null, array('order'=>'title'));
		$f3->set('res_groups',$groups);

		// Get selected group ids
		$group_ids = array();
		if ($ad->groups){
			foreach ($ad->groups as $group){
				$group_ids[] = $group->_id;
			}
		}
		$f3->set('group_ids',$group_ids);

		$res_users = new \Models\User();
		$users = $res_users->find(array('role = ?', 1),array('order'=>'username'));
		$f3->set('res_users',$users);

		// Load countries
		$f3->set('arrCountries',Geo::getCountries());

		// Load regions if already set
		if ($ad->geo_regions != null){
			$f3->set('arrRegions',Geo::getRegions($ad->geo_countries[0]));
		}

		// Load cities if already set
		if ($ad->geo_cities != null){
			$rc = explode('|', $ad->geo_regions[0]);
			$f3->set('arrCities',Geo::getCities($ad->geo_countries[0], $rc[1]));
		}

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postEdit($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?ads&list');

		$userSql = '';
		// Less than admins/super admins can only see their ads
		if ($f3->get('USER')->role < 8){
			$userSql = ' AND advertiser='.$f3->get('USER')->_id;
			$f3->set('POST.status', '0');
			$f3->set('POST.approved', '0');
		}

		$ad = new \Models\Ad();
		$ad->load(array('_id = ?'.$userSql, $f3->get('PARAMS.id')));
		if ($ad->dry()) $f3->reroute('/index.php?ads&list');

		if ($f3->get('USER')->role >= 8){
			if ($f3->get('POST.advertiser') == '') $f3->set('POST.advertiser', null);

			// If approving the ad, also set it's status to On
			if ($f3->exists('POST.approved')){
				$f3->get('POST.approved') == '1' ? $f3->set('POST.status', '1') :  $f3->set('POST.status', '0');
			}

			// If limiting the ad, set start date as now if just enabled
			if (($f3->get('POST.limit_time') != '') && ($f3->get('POST.status') == '1') && ($ad->status == 0)){
				$f3->set('POST.limit_start_date', time());
			} elseif ($f3->get('POST.status') == '0'){
				$f3->set('POST.limit_start_date', '0');
			} else {
				$f3->set('POST.limit_start_date', $ad->limit_start_date);
			}
		}

		try {
			$ad = new \Models\Ad();
			if ($f3->get('USER')->role < 8){
				$result = $ad->post($f3, $params, false);
			} else {
				$result = $ad->post($f3, $params, true, array('sale','sale_record','approved'));
			}

			$result ? $f3->reroute('/index.php?ads&list') : $f3->reroute('/index.php?ads&edit&'.$f3->get('PARAMS.id'));
		} catch (Exception $e){
			Utils::Logger('postEdit:Error posting ad - '.$e);
		}

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postDelete($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?ads&list');

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		try {
			$adId = $params['id'];
			$ad = new \Models\Ad();
			$ad->load(array('_id = ?', $adId));
			if ($ad->dry()) return;

			$groups = $ad->groups;

			if (!empty($groups)){
				foreach ($groups as $group) {

					// remove ad from any groups
					$g = new \Models\Group();
					$g->load(array('_id = ?', $group->_id));

					$group_ads = $group->ads;

					$groupAdsArray = array();
					foreach ($group_ads as $group_ad) {
						if ($group_ad->_id == $ad->_id) continue;
						$groupAdsArray[] = $group_ad->_id;
					}

					$g->ads = $groupAdsArray;
					$g->save();

					// clear any ad id from any ordered group list
					if (empty($group->ad_order)) continue;
					$adOrderArray = explode(',',$group->ad_order);

					if (!in_array($ad->_id,$adOrderArray)) continue;
					$newAdOrderArray = array();
					foreach ($adOrderArray as $ado) {
						if ($ado == $ad->_id) continue;
						$newAdOrderArray[] = $ado;
					}
					$adOrder = implode(',', $newAdOrderArray);

					$g->ad_order = $adOrder;
					$g->save();
				}
			}

			$ad = new \Models\Ad();
			$result = $ad->delete($f3, $params);
			echo $result;
		} catch (Exception $e){
			Utils::Logger('postDelete:Error deleting ad - '.$e);
		}
		$msg = \FlashMessage::instance();
		$arr = $msg->getMessages();

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getCodes($f3, $params){

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		$id = $f3->get('PARAMS.id');
		$ad = new \Models\Ad();
		$ad->load(array('_id = ?', $id));
		if ($ad->dry()) $f3->reroute('/index.php?ads&list');
		$f3->set('ad', $ad);

		// Template settings
		$f3->set('active','ads');
		$f3->set('inc','ads-code.html');
		$f3->set('inc_bottom', 'ads-code-bottom.html');
		$f3->set('title',$f3->get('lang_ad_code'));

		$f3->set('php_only', false);
		if ($ad->type == 'freeform'){
			if ((stristr($ad->type_freeform->text, '<script>') !== false) ||
					(stristr($ad->type_freeform->text, '<?php') !== false)){
				$f3->set('php_only', true);
			}
		}

		$f3->set('vast', false);
		if ($ad->type == 'video'){
			$videoSrc = $ad->type_video->src;
			$extension = strtolower(pathinfo($videoSrc, PATHINFO_EXTENSION));
			if ($extension != 'swf') $f3->set('vast', true);
		}

		echo Template::instance()->render('layout.html');
	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getCode($f3, $params){

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}
		$code = '';

		$id = $f3->get('PARAMS.id');
		$type = $f3->get('PARAMS.type');
		if ((empty($id)) || (empty($type))) return;

		$url = str_replace('admin', 'api',$f3->get('HOST').$f3->get('BASE'));
		$htmlUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&t&a&'.$id;

		$ad = new \Models\Ad();
		$ad->load(array('_id=?', $id));
		if ($ad->dry()) return;

		$keywords = $f3->get('GET.k') ? html_entity_decode(str_replace(', ',',',$f3->get('GET.k'))) : '';
		if (!empty($keywords)){
			$keywordsOrIdData = 'data-k="'.urlencode($keywords).'"';
			$jsUrl = $url.'/index.php?js&ka&';
			$phpUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&ka&k='.urlencode($keywords).'&';
			$class = 'makv1_';
			$varCheck = 'mysa_'.$class;
		} else {
			$keywordsOrIdData = 'data-id="'.$id.'"';
			$jsUrl = $url.'/index.php?js&a&';
			$phpUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&a&i='.$id.'&';
			$class = 'mav1_';
			$varCheck = 'mysa_'.$class;
		}

		$html_ad_title = htmlentities('<!--'.$ad->title.'-->');

		switch ($type){
			case 1: // JS Standard HTML
				$code = $html_ad_title.htmlentities('<span '.$keywordsOrIdData.' class="'.$class.'1"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if ('.$varCheck.'1) return; var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'1&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'1=true;</script></span>');
				break;
			case 2: // JS Floating top
				$code = $html_ad_title.htmlentities('<span '.$keywordsOrIdData.' data-l="top" class="'.$class.'3"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if ('.$varCheck.'3) return;var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'3&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'3=true;</script></span>');
				break;
			case 3: // JS Floating bottom
				$code = $html_ad_title.htmlentities('<span '.$keywordsOrIdData.' data-l="bottom" class="'.$class.'3"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if ('.$varCheck.'3) return;var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'3&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'3=true;</script></span>');
				break;
			case 5: // PHP Standard HTML
				$code = '&lt;?php'.htmlentities(' /* '.$ad->title.' */ '.'@readfile(\''.$phpUrl.'c=1&at=p&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
			case 6: // PHP Floating top
				$code = '&lt;?php'.htmlentities(' /* '.$ad->title.' */ '.'@readfile(\''.$phpUrl.'c=3&at=p&loc=top&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
			case 7: // PHP Floating bottom
				$code = '&lt;?php'.htmlentities(' /* '.$ad->title.' */ '.'@readfile(\''.$phpUrl.'c=3&at=p&loc=bottom&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
			case 9: // HTML Only
				$content = '';
				if ($ad->type == 'banner'){
					$content = '<img src="'.$ad->type_banner->src_lg.'" alt="'.$ad->type_banner->alt.'" class="'.$ad->type_banner->css_class.'" />';
				} elseif ($ad->type == 'textlink'){
					$content = $ad->type_textlink->anchor;
				} elseif ($ad->type == 'freeform'){
					$content = $ad->type_freeform->text;
				}
				$outUrl = $f3->get('SCHEME').'://'.$url.'/index.php?out&a&'.$id;

				$code = htmlentities('<img src="'.$htmlUrl.'" alt="" /><a href="'.$outUrl.'">'.$content.'</a>');
				break;
			case 10: // VAST
				$outUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&v&a&'.$id;
				$code = htmlentities($outUrl);
		}

		echo json_encode($code);
	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getImages($f3, $params){

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}

		$uploadDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . str_replace('/',DIRECTORY_SEPARATOR, $f3->get('UPLOADS'));
		$uploadUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').'/'.$f3->get('UPLOADS');

		$extensionArray = array();
		if ($f3->get('PARAMS.type') == 'banner'){
			$extensionArray = array('jpg','jpeg','gif','png');
		} elseif ($f3->get('PARAMS.type') == 'video'){
			$extensionArray = array('swf','mp4','webm','flv');
		}

		$html = '<h4>'.$f3->get('lang_click_the_image_to_select').'</h4>';
		$files = scandir($uploadDir);
		foreach($files as $file){
			$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

			if (in_array($extension, $extensionArray)){

				if ($f3->get('PARAMS.type') == 'banner'){
					$html .= '<img src="'.$uploadUrl.$file.'" class="gallery_modal_select" style="cursor: pointer;" width="120" height="120" data-file="'.$uploadUrl.$file.'"> '.$file.'<br />';
				} elseif ($f3->get('PARAMS.type') == 'video'){
					$html .= '<i class="fa fa-video-camera fa-5x gallery_modal_select" style="cursor: pointer;" data-file="'.$uploadUrl.$file.'"></i> '.$file.'<br />';
				}

			}
		}

		echo (json_encode($html));
	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function previewAd($f3, $params){
		$adCode = '';
		try{
			$baseUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').str_replace('admin','api',$f3->get('BASE'));
			$adCode = file_get_contents($baseUrl.'/index.php?in&a&i=' . $f3->get('PARAMS.id') . '&c=1&at=p');
		} catch (Exception $e){
			Utils::Logger('[previewAd]Error calling ad preview - '.$e);
		}

		echo $adCode;
	}


	/**
	 * @param $f3 \Base
	 */
	public function getRegions($f3){
		echo '{"Items":'.json_encode(Geo::getRegions(strtoupper($f3->get('PARAMS.cc')))).'}';
	}

	/**
	 * @param $f3 \Base
	 */
	public function getCities($f3){
		$p = explode('|',strtoupper($f3->get('PARAMS.rc')));
		$cc = $p[0];
		echo '{"Items":'.json_encode(Geo::getCities($p[0],$p[1])).'}';
	}


	/**
	 * @param $f3 \Base
	 */
	public function postUpload($f3){
		$web = \Web::instance();

		$type = $f3->get('PARAMS.type');
		if (!$type) return;
		$type = strtolower($type);


		$overwrite = true; // set to true, to overwrite an existing file; Default: false
		//$slug = true; // rename file to filesystem-friendly version
		$uploadUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').'/';

		
		
		if ($type == 'banner'){
			$file = $web->receive(function($file){
						if ($file['error'] != 0) return false;

						if (($file["type"] == 'image/png') ||
								($file["type"] == 'image/jpg') ||
								($file["type"] == 'image/jpeg') ||
								($file["type"] == 'image/gif')){

							if($file['size'] > (2 * 1024 * 1024)) // if bigger than 2 MB
								return false; // this file is not valid, return false will skip moving it
							return true; // allows the file to be moved from php tmp dir to your defined upload dir
						}
						return false;

					},
					$overwrite,
					function($file){
						return Utils::GenerateSlugFilename($file);
					}
			);
			if ($file){
				$id = $f3->get('PARAMS.id');
				if (!empty($id)){
					$userSql = '';
					// Less than admins/super admins can only see their ads
					if ($f3->get('USER')->role < 8){
						$userSql = ' AND advertiser='.$f3->get('USER')->_id;
					}
					$ad = new \Models\Ad();
					
					$ad->load(array('_id = ?'.$userSql, $id));
					if ($ad->dry()) {
						echo '{"result":'.json_encode(array('error'=>'Error uploading file - No associated ad.')).'}';
						return;
					}
					if ($ad->sale){
						$max_height = $ad->sale->banners_height;
						$max_width = $ad->sale->banners_width;
						if ((empty($max_height)) || (empty($max_width))) return true;
						list($width, $height, $type, $attr) = getimagesize($uploadUrl.key($file));
						//echo '{"result":'.json_encode(array('error'=>'max_height='.$max_height.'|max_width='.$max_width.'|width='.$width.'|height='.$height)).'}';
						//return;
						if ((empty($height)) || (empty($width))) return true;
						if (($height != $max_height) && ($width != $max_width)) {
							echo '{"result":'.json_encode(array('error'=>'Error uploading file - Please make sure the dimensions are '.$max_height.'x'.$max_width)).'}';
							return false;
						}
					}
				}
			}
		} else if ($type == 'video'){
			$file = $web->receive(function($file){
						if ($file['error'] != 0) return false;

						if (($file["type"] == 'video/mp4') ||
								($file["type"] == 'video/webm') ||
								($file["type"] == 'video/x-flv') ||
								($file["type"] == 'application/x-shockwave-flash')){

							if($file['size'] > (20 * 1024 * 1024)) // if bigger than 10 MB
								return false; // this file is not valid, return false will skip moving it

							return true; // allows the file to be moved from php tmp dir to your defined upload dir
						}

						return false;

					},
					$overwrite,
					function($file){
						return Utils::GenerateSlugFilename($file);
					}
			);
		}
		if ($file){
			echo '{"result":'.json_encode(array('url'=>$uploadUrl.key($file))).'}';
		} else {
			echo '{"result":'.json_encode(array('error'=>'Error uploading file.')).'}';
		}
	}
}
