<?php
	class CustomFieldsEventHandler extends InpDBEventHandler  {
	
		/**
		 * Apply any custom changes to list's sql query
		 *
		 * @param kEvent $event
		 * @access protected
		 * @see OnListBuild
		 */
		function SetCustomQuery(&$event)
		{
			$object =& $event->getObject();
			
			$item_type=$this->Application->GetVar('cf_type');
			$object->SetWhereClause('%1$s.Type='.$item_type);
			$object->AddOrderField('DisplayOrder', 'ASC');
		}
		
		/**
		 * Prevents from duplicate item creation
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemCreate(&$event)
		{
			$object =& $event->getObject();
			$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
			
			$new_field_name=$items_info[0]['FieldName'];

			$table = $this->Application->getUnitOption($event->Prefix,'TableName');
			$found = $this->Conn->GetOne("SELECT count(*) FROM ".$table." WHERE FieldName='".$new_field_name."'");
		
			if($found){
				$event->status=erFAIL;
				$object->FieldErrors['FieldName']['pseudo'] = $this->Application->Phrase('la_error_CustomExists');
			}
			else {
				$item_type=$this->Application->GetVar('cf_type');

				$object->SetDBField('Type', $this->Application->GetVar('cf_type'));
			}
		}
		
		function OnAfterItemCreate(&$event)
		{
			$this->Application->SetVar('cf_id', '');
		}		

		function OnAfterItemUpdate(&$event)
		{
			$this->Application->SetVar('cf_id', '');
		}
		
		function OnCancelEdit(&$event){
			$this->Application->SetVar('cf_id', '');
		}
		/**
		 * Occurse after deleting item, id of deleted item
		 * is stored as 'id' param of event
		 *
		 * @param kEvent $event
		 * @access public
		 */
		function OnAfterItemDelete(&$event)
		{
			$object =& $event->getObject();
			$custom_field_id=$event->getEventParam('id');
			$this->Application->SetVar('cf_id', '');
			
			$sql='DELETE FROM '.TABLE_PREFIX.'CustomMetaData WHERE CustomFieldId='.$custom_field_id;
			$this->Conn->Query($sql);
			
			
		}
		
		function OnMassDelete(&$event)
		{
			parent::OnMassDelete($event);
			$event->redirect_params = Array('opener' => 's');
		}
	}
?>