<?php

	class AjaxFormHelper extends kHelper {

		/**
		 * Sets error info as parameters in response object
		 * Expects that event status is not erSUCCESS
		 *
		 * @param kEvent $event
		 * @param Array $response
		 */
		public function prepareJSONErrors($event, &$response)
		{
			$object = $event->getObject();
			/* @var $object kDBItem */

			$response['status'] = 'FAILED';
			$response['field_errors'] = $this->getErrorMessages($object);
		}

		/**
		 * Returns object errors
		 *
		 * @param kDBItem $object
		 * @return Array
		 */
		public function getErrorMessages(&$object)
		{
			$error_msgs = Array ();
			$field_errors = array_keys( $object->GetFieldErrors() );

			foreach ($field_errors as $field) {
				if ( !$object->GetErrorPseudo($field) ) {
					continue;
				}

				if ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage') {
					$field = 'l' . $this->Application->GetVar('m_lang') . '_' . $field;
				}

				$error_field = $object->GetFieldOption($field, 'error_field', false, $field);
				$error_msgs[$field] = $object->GetErrorMsg($error_field);
			}

			return $error_msgs;
		}

		/**
		 * Sends JSON-encoded response as event result to the browser
		 *
		 * @param kEvent $event
		 * @param Array $response
		 */
		public function sendResponse($event, $response = Array ())
		{
			if ( !isset($response['status']) ) {
				$response['status'] = 'OK';
			}

			$json_helper = $this->Application->recallObject('JSONHelper');
			/* @var $json_helper JSONHelper */

			echo $json_helper->encode($response);

			$event->status = kEvent::erSTOP;
		}

		/**
		 * Calls given event and returns nice JSON output
		 *
		 * @param kEvent $event
		 * @param string $call_event
		 * @param Array $params
		 */
		public function transitEvent($event, $call_event, $params = Array ())
		{
			$params['status'] = 'OK';
			$event->CallSubEvent($call_event);

			if ( $event->status != kEvent::erSUCCESS ) {
				$this->prepareJSONErrors($event, $params);
			}
			else {
				if ( !isset($params['redirect_to']) && ($event->redirect === true || strlen($event->redirect) > 0) ) {
					$params['redirect_to'] = $this->Application->HREF($event->redirect, '', $event->getRedirectParams(), $event->redirectScript);
				}

				$params = array_merge($params, $event->getRedirectParams());
			}

			$this->sendResponse($event, $params);
		}
	}