<?php

//global $Debug;  $Debug = true;
 
class TemplateManagerView extends Slot {

	var $SectionID = 38;
	var $ModuleID = 15;
	var $colors = array('red' => '#DC143C', 'yellow' => '#FF8C00', 'green' => '#006400', 'black' => '#000000', 'blue' => '#4169E1',);
	var $action;
	var $subaction;
	var $templates = array();
	var $template = array();
	var $item_opers = array();
	var $param_types = array();
	var $current_item;
	var $terminated = false;
	var $undo = 0;
	var $check = array();

	function __construct($pquery) {
		parent::__construct($pquery);
	}

	function init() { 
		GLOBAL $TOOLS_PATH;
		$this->action = isset($this->LocalTarget[0]) ? $this->LocalTarget[0] : '';
		$this->templates = $this->Action->Server->getGuide('template');
		if(!empty($this->action) && !is_numeric($this->action) && (($this->action != 'Add' && !array_key_exists(@$this->LocalTarget[1], $this->templates)) || ($this->server_type != 'dev' && $this->action != 'View')) && ($this->action != 'Spellcheck' && $this->action != 'Spellword' && $this->action != 'Spelladd')) return $this->terminateAction();
		$this->item_opers = $this->Action->Server->getGuide('templateitemoper');
		$this->param_types = $this->Action->Server->getGuide('templateitemcondparamtype');
		switch($this->action){
			case 'Add': {
				if(empty($this->Request)){
					$this->Request['submit']['add'] = 'item';
					$this->Request['form'] = $this->Action->Handler->_parseContent($this->Action->Handler->createTemplate());
				}
				$this->Scheme = 'action';
				break;
			}
			case 'Duplicate': {
				if(empty($this->Request)){
					$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1]), $this);
					$this->template = $this->PreparedTemplates;
					$this->prepareTemplate(false);
					$this->template['id'] = '';
					$this->template['uid'] = '';
					$this->template['date_created'] = '';
					$this->template['date_changed'] = '';
					$this->template['comments'] = array();
					$count = count($this->template['items']);
					for ($i = 0; $i < $count; $i++) $this->template['items'][$i]['uid'] = '';
				}
				$this->Scheme = 'action';
				break;
			}
			case 'Update': case 'View': case 'Delete': {
				if($this->action != 'View'){
					$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
					if(empty($this->PreparedTemplates)) $this->Action->processEvent($this->SectionID, 'lock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
					else if($this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) return $this->terminateAction();
				}
				if($this->action == 'Update' && @$this->LocalTarget[2] == 'Undo' && @$this->LocalTarget[3] && is_numeric($this->LocalTarget[3])) $this->undo = $this->LocalTarget[3];
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1], 'undo' => $this->undo), $this);
				if(empty($this->Request)){
					if($this->undo && !empty($this->PreparedTemplates['_error'])) return $this->terminateAction();
					$this->template = $this->PreparedTemplates;
					$this->prepareTemplate(false);
				}
				$this->Scheme = 'action';
				break;
			}
			case 'Unlock': {
				$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
				if(@$this->PreparedTemplates['access_flag'] == $this->Action->Security->currentuser->id) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
				return $this->terminateAction();
				break;
			}
			case 'FullHistory': {
				$request = array ('id' => $this->LocalTarget[1]);
				$request['pageRecordsQty'] = 20;
				$request['curPageNumber'] = isset($this->LocalTarget[2]) ? $this->LocalTarget[2] + 1 : 1;
				$this->Action->processEvent($this->SectionID, 'select_templatecomments', $request, $this);
				$this->getPageControl($this->Home.'/Registar/TemplateManager/FullHistory/'.$this->LocalTarget[1]);
				$this->Scheme = 'fullhistory';
				break;
			}
			case 'Spellcheck': $this->Scheme = $this->server_type=='dev'? 'spellcheck' : 'default'; break;
			case 'Spellword': $this->Scheme = $this->server_type=='dev'? 'spellword' : 'default'; break;
			case 'Spelladd': $this->Scheme = $this->server_type=='dev'? 'spelladd' : 'default'; break;
			default: {
				$this->Scheme = 'default';
				$request = array();
				$this->Action->processEvent($this->SectionID, 'select', $request, $this);
				break;
			}
		}
		if(empty($this->Request) || validate($this->getRequestField('check'))){
			$this->setSchemeTemplate($this->Scheme);
			return;
		}
		if(!isset($this->Request['submit'])) $this->Request['submit'] = array();
		$from_item = current($this->Request['form']['items']);
		$this->template = $this->Request['form'];
		$this->prepareTemplate();
		$this->template['uid'] = isset($this->PreparedTemplates['uid']) ? $this->PreparedTemplates['uid'] : '';
		$this->template['date_created'] = isset($this->PreparedTemplates['date_created']) ? $this->PreparedTemplates['date_created'] : '';
		$this->template['date_changed'] = isset($this->PreparedTemplates['date_changed']) ? $this->PreparedTemplates['date_changed'] : '';
		$this->template['comments'] = isset($this->PreparedTemplates['comments']) ? $this->PreparedTemplates['comments'] : array();
		$this->subaction = key($this->Request['submit']);
		switch($this->subaction){
			case 'change': {
				$this->current_item = $this->Request['submit'][$this->subaction];
				$this->changeItemsPriorities($from_item);
				break;
			}
			case 'add': {
				$count = count($this->template['items']);
				$max_id = 1;
				for ($i = 0; $i < $count; $i++)
					if($this->template['items'][$i]['id'] > $max_id) $max_id = $this->template['items'][$i]['id'];
				$this->current_item = ++$max_id;
				$this->template['items'][$count] = $this->Action->Handler->_parseContent(new TemplateItem());
				$this->template['items'][$count]['id'] = $max_id;
				$this->template['items'][$count]['conds'][0] = $this->Action->Handler->_parseContent(new TemplateItemCond());
				$this->template['items'][$count]['conds'][0]['params'][0] = $this->Action->Handler->_parseContent(new TemplateItemCondParam());
				break;
			}
			case 'delete': {
				$count = count($this->template['items']);
				if($count == 1){
					$this->current_item = $this->template['items'][0]['id'];
					$this->template['items'][0]['number'] = 1;
					$this->template['items'][0]['default_item'] = 1;
					break;
				}
				$this->changeItemsPriorities($from_item);
				$index = false;
				for ($i = 0; $i < $count; $i++){
					if($this->template['items'][$i]['id'] == $this->Request['submit'][$this->subaction]){
						$index = $i;
						break;
					}
				}
				if($index !== false){
					unset($this->template['items'][$index]);
					$this->current_item = isset($this->template['items'][$index + 1]) ? $this->template['items'][$index + 1]['id'] : $this->template['items'][$index - 1]['id'];
					$this->template['items'] = array_values($this->template['items']);
					$count--;
					for ($i = 0; $i < $count; $i++)
						if($this->template['items'][$i]['number'] > $from_item['number']) $this->template['items'][$i]['number']--;
					if($from_item['default_item']) $this->template['items'][0]['default_item'] = 1;
				}
				break;
			}
			default: {
				$this->changeItemsPriorities($from_item);
				$this->current_item = $from_item['id'];
				switch($this->action){
					case 'Update': case 'Add': case 'Duplicate': {
						if($this->validateTemplate()){
							$this->template['action'] = $this->action;
							$this->template['id_user'] = $this->Action->Security->currentuser->id;
							if ($this->Action->processEvent($this->SectionID, 'save', $this->template, $this)) {
								if(!empty($this->template['id'])) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->template['id'], 'member' => $this->Action->Security->currentuser->id), $this);
								header('Location: '.$this->Home.'/Registar/TemplateManager'.$this->SID);
							}
							else $this->errors['validate'] = $this->PreparedTemplates['_error'];
						}
						break;
					}
					case 'Delete': {
						include($TOOLS_PATH.'\checker.php');
						$this->check = check_to_delete($this->template['id'], 'Template');
						if (empty($this->check)){
							$this->Action->processEvent($this->SectionID, 'delete', $this->template, $this)
							and $this->clearUndo($this->template['id'])
							and header('Location: '.$this->Home.'/Registar/TemplateManager'.$this->SID);
						}
						else {
							$this->Scheme = 'nodelete';
							$this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->template['id'], 'member' => $this->Action->Security->currentuser->id), $this);
						}
						break;
					}
				}
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'nodelete': $this->fillNoDelete(); break;
			case 'action': $this->fillAction(); break;
			case 'fullhistory': $this->fillFullHistory(); break;
			case 'spellcheck': $this->fillSpellcheck(); break;
			case 'spellword': $this->fillSpellword(); break;
			case 'spelladd': $this->fillSpelladd(); break;
			default: $this->fillDefault(); break;
		}
	}
	

	function fillDefault() {
		if($this->terminated) return false;
		$this->TempFillEls['addBut'] = $btnEdit_vis = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$count = count($this->PreparedTemplates);
		for ($i = 0; $i < $count; $i++){
			$locked = empty($this->PreparedTemplates[$i]['access_flag']) || $this->PreparedTemplates[$i]['access_flag'] == $this->Action->Security->currentuser->id ? false : true;
			$presets_count = explode('/', $this->PreparedTemplates[$i]['published_count']);
			$c = count($this->PreparedTemplates[$i]['publish']);
			$this->TempFillEls['template'][$i] = array(
				'id' => $this->PreparedTemplates[$i]['id'],
				'name' => $this->PreparedTemplates[$i]['name'],
				'name_color' => $this->colors[($this->PreparedTemplates[$i]['unmodified'] > 30 ? 'black' : ($this->PreparedTemplates[$i]['unmodified'] > 14 && $this->PreparedTemplates[$i]['unmodified'] <= 30 ? 'green' : ($this->PreparedTemplates[$i]['unmodified'] > 7 && $this->PreparedTemplates[$i]['unmodified'] <= 14 ? 'yellow' : 'red')))],
				'published_count' => $this->PreparedTemplates[$i]['published_count'],
				'published_count_cursor' => $c ? 'pointer' : 'auto',
				'published_count_color' => $this->colors[($presets_count[0] >= $presets_count[1] ? 'green' : (empty($presets_count[0]) ? 'red' : 'blue'))],
				'chbAdds_disabled' => $locked ? 'disabled' : '',
				'date_changed' => $this->PreparedTemplates[$i]['date_changed'],
				'btnUnlock_vis' => $this->PreparedTemplates[$i]['access_flag'] == $this->Action->Security->currentuser->id ? 'visible' : 'hidden',
				'btnEdit_vis' => $btnEdit_vis,
				'btnDuplicate_vis' => $btnEdit_vis,
				'chbAdds_vis' => $this->TempFillEls['pubBut'],
				'btnUnlock_disp' => $locked ? 'none' : '',
				'btnEdit_disp' => $locked ? 'none' : '',
				'btnDuplicate_disp' => $locked ? 'none' : '',
				'locked_message_disp' => $locked ? '' : 'none',
				'user_name' => $this->PreparedTemplates[$i]['username'],
				'date_locked' => $this->PreparedTemplates[$i]['date_locked'],
			);
			$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']=[];';
			$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]=[];';
			for($j = 0; $j < $c; $j++){
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']=[];';
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_id"]='.$this->PreparedTemplates[$i]['publish'][$j]['package_id'].';';
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_name"]="'.$this->PreparedTemplates[$i]['publish'][$j]['package_name'].'";';
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["username"]="'.$this->PreparedTemplates[$i]['publish'][$j]['username'].'";';
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["hostpath"]="'.$this->PreparedTemplates[$i]['publish'][$j]['hostpath'].'";';
				$this->TempFillEls['template'][$i]['publish'][]['variable'] = 'templates['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["date_published"]="'.$this->PreparedTemplates[$i]['publish'][$j]['date_published'].'";';
			}
		}
		$this->clearAllTemplates();
	}

	function fillAction() {
		if($this->terminated) return false;
		if(empty($this->current_item)) $this->current_item = $this->template['items'][0]['id'];
		if($this->undo) $this->TempFillEls['undo'] = 'Undo up to '.$this->undo.' version';
		$this->TempFillEls['action'] = $this->action;
		$this->TempFillEls['form_id'] = inputHidden('form[id]', $this->template['id']);
		$this->TempFillEls['form_undo'] = inputHidden('form[undo]', $this->undo);
		if(!empty($this->template['id'])){
			$this->TempFillEls['id'] = '['.$this->template['id'].']';
			$this->TempFillEls['template'] = $this->template['id'];
			$this->TempFillEls['name'] = '"'.$this->template['name'].'"';
		}
		$this->TempFillEls['form_name'] = inputText('form[name]', $this->template['name'], 80, '', 128);//hint="Template name" onChange="validateText(this)"
		$this->TempFillEls['uid'] = $this->template['uid'];
		$this->TempFillEls['date_created'] = $this->template['date_created'];
		$this->TempFillEls['date_changed'] = $this->template['date_changed'];
		$count = count($this->template['items']);
		$this->TempFillEls['btnDeleteItem_vis'] = $count == 1 ? 'hidden' : 'visible';
		$item_priority = array();
		for ($i = 0; $i < $count; $i++) $item_priority[$i + 1] = $i + 1;
		for ($i = 0; $i < $count; $i++){
			$this->TempFillEls['items_buttons'][$i]['id'] = $this->template['items'][$i]['id'];
			$this->TempFillEls['items_buttons'][$i]['name'] = $this->template['items'][$i]['name'];
			$this->TempFillEls['items_buttons'][$i]['sbt_class_adds'] = $this->current_item == $this->template['items'][$i]['id'] ? '' : ($this->template['items'][$i]['default_item'] ? 'lightblue' : 'gray');
			if($this->current_item == $this->template['items'][$i]['id']) {
				$this->TempFillEls['form_item_id'] = inputHidden('form[items]['.$i.'][id]', $this->template['items'][$i]['id']);
				$this->TempFillEls['item_id'] = $this->template['items'][$i]['id'];
				$this->TempFillEls['form_item_name'] = inputText('form[items]['.$i.'][name]', $this->template['items'][$i]['name'], 80, 'item_id="'.$this->template['items'][$i]['id'].'" onChange="changeBtnItem(this)"', 128);
				$this->TempFillEls['form_item_uid'] = inputHidden('form[items]['.$i.'][uid]', $this->template['items'][$i]['uid']);
				$this->TempFillEls['item_uid'] = $this->template['items'][$i]['uid'];
//			$this->TempFillEls['form_item_value'] = inputTextArea('form[items]['.$i.'][value]', $this->template['items'][$i]['value'], '', 25, 'style="width: 880px;" id=contents'.$i);
				$content = preg_replace('/&(\w+;)/', '&amp;$1', $this->template['items'][$i]['value']);
			$this->TempFillEls['form_item_value'] = inputTextArea('form[items]['.$i.'][value]', $content, '', 25, 'style="width: 880px;" id=contents'.$i);
				$this->TempFillEls['form_item_value_element'] = 'contents'.$i;
				$this->TempFillEls['form_default_item'] = inputHidden('form[items]['.$i.'][default_item]', '0').inputCheckbox('form[items]['.$i.'][default_item]', $this->template['items'][$i]['default_item']);
				$this->TempFillEls['form_item_number'] = implode('', radioButtons($item_priority, 'form[items]['.$i.'][number]', (empty($this->template['items'][$i]['number']) ? key(array_reverse($item_priority, true)) : $this->template['items'][$i]['number'])));
				$this->TempFillEls['form_item_cond_oper'] = implode('', radioButtons($this->item_opers, 'form[items]['.$i.'][cond_oper]', (empty($this->template['items'][$i]['cond_oper']) ? key($this->item_opers) : $this->template['items'][$i]['cond_oper'])));
				$this->TempFillEls['form_item_param_oper'] = implode('', radioButtons($this->item_opers, 'form[items]['.$i.'][param_oper]', (empty($this->template['items'][$i]['param_oper']) ? key($this->item_opers) : $this->template['items'][$i]['param_oper'])));
				$cond_count = count($this->template['items'][$i]['conds']);
				for ($j = 0; $j < $cond_count; $j++){
					$this->TempFillEls['item_conds'][$j]['cond_ident'] = $j;
					$param_count = count($this->template['items'][$i]['conds'][$j]['params']);
					for ($k = 0; $k < $param_count; $k++){
						$this->TempFillEls['item_conds'][$j]['item_conds_params'][$k]['param_ident'] = $j.'_'.$k;
						$this->TempFillEls['item_conds'][$j]['item_conds_params'][$k]['name'] = inputText('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][name]', $this->template['items'][$i]['conds'][$j]['params'][$k]['name'], 40);
						$this->TempFillEls['item_conds'][$j]['item_conds_params'][$k]['value'] = inputText('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][value]', $this->template['items'][$i]['conds'][$j]['params'][$k]['value'], 40);
						$this->TempFillEls['item_conds'][$j]['item_conds_params'][$k]['type'] = inputSelect('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][type]', $this->param_types, $this->template['items'][$i]['conds'][$j]['params'][$k]['type'], 'style="width: 215px;"');
					}
				}
			}
			else {
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][id]', $this->template['items'][$i]['id']);
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][name]', $this->template['items'][$i]['name']);
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][uid]', $this->template['items'][$i]['uid']);
//				$this->TempFillEls['hidden_items'][]['property'] = inputTextArea('form[items]['.$i.'][value]', $this->template['items'][$i]['value']);
			$this->TempFillEls['hidden_items'][]['property'] = inputTextArea('form[items]['.$i.'][value]', preg_replace('/&(\w+;)/', '&amp;$1', $this->template['items'][$i]['value']) );
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][default_item]', $this->template['items'][$i]['default_item']);
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][number]', $this->template['items'][$i]['number']);
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][cond_oper]', $this->template['items'][$i]['cond_oper']);
				$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][param_oper]', $this->template['items'][$i]['param_oper']);
				$cond_count = count($this->template['items'][$i]['conds']);
				for ($j = 0; $j < $cond_count; $j++){
					$param_count = count($this->template['items'][$i]['conds'][$j]['params']);
					for ($k = 0; $k < $param_count; $k++){
						$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][name]', $this->template['items'][$i]['conds'][$j]['params'][$k]['name']);
						$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][value]', $this->template['items'][$i]['conds'][$j]['params'][$k]['value']);
						$this->TempFillEls['hidden_items'][]['property'] = inputHidden('form[items]['.$i.'][conds]['.$j.'][params]['.$k.'][type]', $this->template['items'][$i]['conds'][$j]['params'][$k]['type']);
					}
				}
			}
		}
		$this->TempFillEls['form_comment'] = inputTextarea('form[comment]', '', '', 5, 'id="form[comment]" style="width: 500px;"');
		if(!empty($this->template['comments'])) $this->fillFullHistory(false);
		$this->TempFillEls['spell'] = $this->LocalTarget[0]=='Delete'? array() : array(array());
		$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
		if(!empty($this->template['_error'])) $this->errors['model'] = $this->template['_error'];
		if(count($this->errors) > 0) $this->errors['header'] = 'There were some errors.<br>Please see below for details';
		foreach ($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $this->printError($v).($k == 'header' ? '<p>' : '');
		$this->clearAllTemplates();
	}

	function fillFullHistory($main = true) {
		if($this->terminated) return false;
		if($main) $history = &$this->PreparedTemplates['curPage'];
		else $history = &$this->template['comments'];
		$count = count($history);
		for ($i = 0; $i < $count; $i++){
			$date = explode('.', $history[$i]['date']);
			$this->TempFillEls['comments'][$i] = array(
				'number' => $main ? ($this->PreparedTemplates['pageRecordsQty'] * ($this->PreparedTemplates['curPageNumber'] - 1) + $i + 1) : ($i + 1),
				'date' => $date[0],
				'member' => $history[$i]['member'],
				'version' => $history[$i]['version'],
				'value' => wordwrap($history[$i]['value'], 30, '<br>', 1),
				'id' => $this->LocalTarget[1],
				'undo_vis' => $history[$i]['file'] ? 'visible' : 'hidden',
			);
		}
		if($main) {
			$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
			$this->TempFillEls['name'] = $this->PreparedTemplates['name'];
			$this->clearAllTemplates();
		}
	}
	
	function fillNoDelete() {
		if($this->terminated) return false;
		$this->TempFillEls['id'] = $this->template['id'];
		$this->TempFillEls['name'] = $this->template['name'];
		$count = count($this->check);
		for ($i = 0; $i < $count; $i++)
			$this->TempFillEls['Pages'][0]['pitems'][$i] = array(
				'item' => makeLink($this->Home.$this->check[$i]['path'], $this->check[$i]['name']),
				'id' => $this->check[$i]['id'],
			);
		$this->clearAllTemplates();
	}
	
	function fillSpellcheck() {
		//printArray($this->Request);
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		require_once($CORE_PATH.'\Tools\spell_checker.php');
		$cp = new PSpell();
		if(!empty($this->Request) && !empty($this->Request['form'])) {
			foreach($this->Request['form']['items'] as $k => $v) {
				$cp->spellCheck($v['value'],'Item '.($k+1),$k);
			}
			if(!empty($cp->count)) {
				$this->TempFillEls['error'] = array(array());
				$i = 1;
				$check = 0;
				if(!empty($this->Request['check']) && $this->Request['check']=='submit') $check = 1;
				//printArray($cp->errorMsg);
				foreach($cp->errorMsg as $key => $value) {
					if(!empty($value['count'])) {
						$div = eregi_replace(' ','',$key);
						$this->TempFillEls['objects'][$key] = array(
							'object' => $key,
							'count'  => $value['count'],
							'objecttype' => $div,
							'div' => $i,
						);
						foreach($value['errors'] as $error) {
							$this->TempFillEls['objects'][$key]['errors'][] = array(
								'url_word' => urlencode($error['word']).'?&check='.$check.'&div='.$div.'&editor_id='.($value['id']+1).'&id='.$i,
								'word' => $error['word'],
								'string' => $error['string'],
								'div' => $i,
							);
							$i++;
						}
					}
				}
			}
			else {
				$this->TempFillEls['ok'] = array(array());
				if(!empty($this->Request['check']) && $this->Request['check']=='submit') $this->TempFillEls['submit'] = array(array());
			}
		}
	}
	
	function fillSpellword() {
		global $REGISTRY, $CORE_PATH;
		//printArray($this->Request);
		//printArray($REGISTRY['Request']['Query']);
		$word = @$this->LocalTarget[1];
		$this->TempFillEls['word'] = $word;
		$this->TempFillEls['check'] = $check = $REGISTRY['Request']['Query']['check'];
		$this->TempFillEls['id'] = $REGISTRY['Request']['Query']['id'];
		$this->TempFillEls['editor_id'] = $editor_id = ($REGISTRY['Request']['Query']['editor_id'] - 1);
		$this->TempFillEls['div'] = $REGISTRY['Request']['Query']['div'];
		require_once($CORE_PATH.'\Tools\spell_checker.php');
		$cp = new PSpell();
		if(empty($this->LocalTarget[2])) {
			$words = $cp->getSuggestions($word);
			foreach($words as $value) $this->TempFillEls['suggestion'][0]['words'][]['value'] = makeLink('javascript:;',$value,array(),'','style="text-decoration:none;font-weight:normal" onclick="replaceWord(\''.addslashes($word).'\',\''.addslashes($value).'\','.$editor_id.',\''.$check.'\','.$this->TempFillEls['id'].',\''.$this->TempFillEls['div'].'\')"');
		}
		else $this->TempFillEls['open_edit'][0]['link'] = makeLink($REGISTRY['Request']['Query']['url'],'Go to edit this mistake',array(),'','target="_blank" style="text-decoration:none;color:red"');
	}

	function fillSpelladd() {
		$word = @$this->LocalTarget[1];
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		require_once($CORE_PATH.'\Tools\spell_checker.php');
		$cp = new PSpell();
		$cp->addWord($word);
	}
	
	function validateTemplate() {
		if(($id = array_search($this->template['name'], $this->templates)) !== false && $id != $this->template['id']) $this->errors['name'] = 'Template with such name already exists';
		if(!is_AlphaNumUnderDefis($this->template['name'], 1, 128)) $this->errors['name'] = 'Template name is not valid';
		$count = count($this->template['items']);
		if(!$count) $this->errors['validate'] = 'Template has to contain at least one item';
		for ($i = 0; $i < $count; $i++) {
			$this->template['items'][$i]['value'] = str_replace('&amp;','&', $this->template['items'][$i]['value']);
			if(empty($this->template['items'][$i]['name']) || strlen($this->template['items'][$i]['name']) < 3 || strlen($this->template['items'][$i]['name']) > 128) $this->errors['item_name'][] = 'Template Item name "'.$this->template['items'][$i]['name'].'" is not valid';
			//if(empty($this->template['items'][$i]['value'])) $this->errors['item_value'][] = 'Template Item "'.$this->template['items'][$i]['name'].'" value is not valid';
			for ($j = 0; $j < $count; $j++)
				if($this->template['items'][$i]['name'] == $this->template['items'][$j]['name'] && $this->template['items'][$i]['id'] != $this->template['items'][$j]['id']){
					$this->errors['item_name'][$this->template['items'][$i]['name']] = 'Template Item with such name "'.$this->template['items'][$i]['name'].'" already exists';
					break;
				}
		}
		if(!empty($this->errors['item_name'])) $this->errors['item_name'] = implode('.<br>', $this->errors['item_name']);
		//if(!empty($this->errors['item_value'])) $this->errors['item_value'] = implode('.<br>', $this->errors['item_value']);
		return empty($this->errors) ? true : false;
	}
	
	function prepareTemplate($incrementization = true){
		if($incrementization){
			ksort($this->template['items']);
			$this->template['items'] = array_values($this->template['items']);
		}
		$count = count($this->template['items']);
		for ($i = 0; $i < $count; $i++){
			if(!isset($this->template['items'][$i]['conds']) || !is_array($this->template['items'][$i]['conds'])) $this->template['items'][$i]['conds'] = array();
			if($incrementization) $this->template['items'][$i]['conds'] = array_values($this->template['items'][$i]['conds']);
			if(empty($this->template['items'][$i]['conds'])) $this->template['items'][$i]['conds'][0]['params'][0] = $this->Action->Handler->_parseContent(new TemplateItemCondParam());
			$cond_count = count($this->template['items'][$i]['conds']);
			if($incrementization)
				for($j = 0; $j < $cond_count; $j++) $this->template['items'][$i]['conds'][$j]['params'] = array_values($this->template['items'][$i]['conds'][$j]['params']);
		}
	}
	
	function changeItemsPriorities($from_item){
		$count = count($this->template['items']);
		$prev_number = array_fill(1, $count, true);
		$prev_item_index = false;
		for ($i = 0; $i < $count; $i++){
			if($from_item['default_item'] && $this->template['items'][$i]['id'] != $from_item['id']) $this->template['items'][$i]['default_item'] = '0';
			if(($from_item['number'] == $this->template['items'][$i]['number']) && $this->template['items'][$i]['id'] != $from_item['id']) $prev_item_index = $i;
			unset($prev_number[$this->template['items'][$i]['number']]);
		}
		if(!empty($prev_number) && $prev_item_index !== false) $this->template['items'][$prev_item_index]['number'] = key($prev_number);
	}

	function clearUndo($id) {
		GLOBAL $ROOT_PATH, $TOOLS_PATH;
		include_once($TOOLS_PATH.'\func.php');
		$path = $ROOT_PATH.'\undo\template\\'.$id;
		if(file_exists($path)) mysystem('rm -rf '.$path);
		return true;
	}
	
	function terminateAction(){
		$this->terminated = true;
		$this->clearAllTemplates();
		header('Location: '.$this->Home.'/Registar/TemplateManager'.$this->SID);
		return true;
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'get_lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'unlock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'open');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'delete');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_templatecomments');
	}

	function setSpellCookie($value) {
		setcookie("spell_check",$value,time()+86400*365,"/");
	}

	function getSpellCookie() {
		return isset($_COOKIE['spell_check']) && $_COOKIE['spell_check']==1? TRUE : FALSE;
	}

}
?>