<?php

/*
	[Discuz!] (C)2001-2007 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms

	$RCSfile: advertisements.inc.php,v $
	$Revision: 1.16.2.1 $
	$Date: 2007/03/21 15:52:38 $
*/

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

$advarray = array();
if(!empty($_DCACHE['advs'])) {
	$advs = $_DCACHE['advs'];
	if(defined('CURSCRIPT') && in_array(CURSCRIPT, array('forumdisplay', 'viewthread')) && !empty($fid)) {
		foreach($advs AS $type => $advitems) {
			foreach($advitems AS $target => $advcode) {
				if($target == 'forum_'.$fid || $target == 'forum_all') {
			        	if(substr($type, 0, 6) == 'thread') {
			                	$advarray[substr($type, 0, 7)][substr($type, 8, strlen($type))] = $advcode;
			        	} else {
				        	$advarray[$type] = $advcode;
			        	}
				}
			}
		}
		$advs = $advarray;
	}
	if($globaladvs) {
		foreach($globaladvs AS $key => $value) {
			if(isset($advs[$key])) {
				$advs[$key] = array_merge($advs[$key], $value);
			} else {
				$advs[$key] = $value;
			}
		}
	}
	$advarray = $advs;
} else {
	$advarray = $globaladvs;
}

$advlist['redirect'] = array_merge($globaladvs, $redirectadvs);

foreach($advarray as $advtype => $advcodes) {
        if(substr($advtype, 0, 6) == 'thread') {
                for($i = 1; $i <= $ppp; $i++) {
                        $adv_codes = @array_unique(array_merge((isset($advcodes[$i]) ? $advcodes[$i] : array()), (isset($advcodes[0]) ? $advcodes[0] : array())));
                        $advcount = count($adv_codes);
                        $advlist[$advtype][$i - 1] = $advcount > 1 ? $adv_codes[mt_rand(0, $advcount -1)] : $adv_codes[0];
                }
        } elseif($advtype == 'intercat') {
                $advlist['intercat'] = $advcodes;
        } else {
        	$advcount = count($advcodes);
        	if($advtype == 'text') {
        		if($advcount > 5) {
        			$minfillpercent = 0;
        			for($cols = 5; $cols >= 3; $cols--) {
        				if(($remainder = $advcount % $cols) == 0) {
        					$advcols = $cols;
        					break;
        				} elseif($remainder / $cols > $minfillpercent)  {
        					$minfillpercent = $remainder / $cols;
        					$advcols = $cols;
        				}
        			}
        		} else {
        			$advcols = $advcount;
        		}

        		$advlist[$advtype] = '';
        		for($i = 0; $i < $advcols * ceil($advcount / $advcols); $i++) {
        			$advlist[$advtype] .= (($i + 1) % $advcols == 1 || $advcols == 1 ? '<tr align="center" class="altbg2">' : '').
        				'<td width="'.intval(100 / $advcols).'%">'.(isset($advcodes[$i]) ? $advcodes[$i] : '&nbsp;').'</td>'.
        				(($i + 1) % $advcols == 0 ? "</tr>\n" : '');
        		}
        	} else {
        		$advlist[$advtype] = $advcount > 1 ? $advcodes[mt_rand(0, $advcount - 1)] : $advcodes[0];
        	}
        }
}

?>