<?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
*/

class adv_rotator_editor_value extends DefaultObject
{
	protected $allowed_keys=array('name', 'value', 'active', 'rate');
	
	public $validation=HTML_QuickForm2_Rule::ONBLUR_CLIENT_SERVER;
	
	public function __construct($id=null)
	{
		$this->data['id']=&$this->data['value_id'];
		if ($id) $this->loadDataById($id);
	}
	
	public function loadDataById($id)
	{
		if ($data=Db::i()->selectRow("SELECT * FROM ?_ad_rotator_values WHERE value_id=?", $id)) {
			$this->set($data);
		}
	}
	
	public function add($place, $data)
	{
		$this->_filterKeys($data);
		$data['place_id']=$place->id;
		$data['id']=Db::i()->query("INSERT INTO ?_ad_rotator_values (?#) VALUES(?a)", array_keys($data), array_values($data));
		$place=Factory::create('adv_rotator_editor.value');
		$place->set($data);
		return $place;
	}

	public function toggle()
	{
		$this->update(array('active'=>$this->active?0:1));
	}

	public function delete()
	{
		Db::i()->query("DELETE FROM ?_ad_rotator_values WHERE value_id=?", $this->id);
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query("UPDATE ?_ad_rotator_values SET ?a WHERE value_id=?", $data, $this->id);
	}

	protected function _resetItemCache()
	{
	}
	
	public function buildEditForm()
	{
		$form = Factory::create('HTML_QuickForm2', null, 'post', array('action'=>'#'));
		$token=$form->addElement('hidden', 'token', array('value' => User::i()->token));
		
		$name=$form->addElement('text', 'name', null, array('label' => _m('Название:')));
		$value=$form->addElement('textarea', 'value', null, array('label' => _m('Значение:')));
		
		$name->addRule('required', _m('Название не может быть пустым'), null, $this->validation);
		
		$form->addElement('submit', null, array('value'=>_m('Сохранить')));
		
		if ($this->id) $form->addDataSource(Factory::create('HTML_QuickForm2_DataSource_Array', $this->data));
		
		return $form;
	}
}