<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

	$rates=array();
	$result=Db::i()->select("SELECT p.place_id, value, rate, id FROM ?_ad_rotator_places p LEFT JOIN ?_ad_rotator_values v ON p.place_id=v.place_id WHERE p.active=1 AND v.active=1");
	$places=array();
	if ($result) foreach($result as $var)
	{
		if (!array_key_exists($var['place_id'], $rates)) $rates[$var['place_id']]=0;
		$places[$var['place_id']][$var['id']]=array('value'=>$var['value'],
													'rate'=>$rates[$var['place_id']]+$var['rate']);
		$rates[$var['place_id']]+=$var['rate'];
	}
	
	if(count($rates)) foreach ($rates as $place_id=>$max_rate)
	{
		$rand=rand(0, $max_rate);
		foreach($places[$place_id] as $val)
		{
			if($rand<=$val['rate'])
			{
				Tpl::i()->assign('_module_ad_rotator_'.$place_id, $val['value']);
				break;
			}
		}
	}
