<?php

//error_reporting(E_ALL);
//global $Debug;$Debug = true;

class ContentManagerView extends Slot {

	var $SectionID = 4;
	var $ModuleID = 4;
	var $pages = array();
	var $reqfield = '<img src="/i/must.gif">&nbsp;';
	var $contenttype = array(
		0 => 'Subcategory',
		1 => 'Page',
	);
	var $colors = array(
		'red' => '#DC143C',
		'yellow' => '#FF8C00',
		'green' => '#006400',
		'black' => '#000000',
		'blue' => '#4169E1',
	);
	var $check = array();
	var $menu_id = 0;
	var $default_page_array = array();
	var $copy = false;
	var $terminated = false;

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

	function init() {
		GLOBAL $TOOLS_PATH, $REGISTRY;
		if(isset($this->LocalTarget[0]) && $this->LocalTarget[0]!='Json') {
			$this->Action->processEvent($this->SectionID,'select_pages',array(),$this);
			$this->pages = $this->PreparedTemplates;
//			printArray($this->pages); 
			$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'select_pages');
		}
		$undo = 0;
		switch(@$this->LocalTarget[0]) {
			case 'CRList': {
				$this->customerreviews = $this->Db->SelectGuide(array('customerreview g'),array('g.id','g.name'),array('1' => '1'));
				foreach($this->customerreviews as $key => $value) {
					$this->TempFillEls['items'][] = array(
						'number' => $key,
						'name' => $value,
						'name2' => htmlspecialchars(strip_tags($value), ENT_QUOTES),
						'id' => @$this->LocalTarget[1],
						'form_name' => 'page',
					);
				}
				$this->Scheme = 'crlist';
			break;
			}
			case 'Preview': $this->Scheme = $this->server_type=='dev'? 'preview' : 'default'; 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;
			case 'Json':
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = 'json';
			break;
			case 'Sort':
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = $this->server_type=='dev'? 'sort' : 'default';
			break;
			case 'Sort_':
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = $this->server_type=='dev'? 'sort_' : 'default';
			break;
			case 'ViewAll':
				if($this->server_type=='dev') {
					$request = $this->LocalTarget;
					$request['pageRecordsQty'] = 20;
					$request['curPageNumber'] = isset($this->LocalTarget[2])? $this->LocalTarget[2]+1 : 1;
					$this->Action->processEvent($this->SectionID,'select_modulecomments',$request,$this);
					if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
					else {
						$this->getPageControl($this->Home.'/Registar/ContentManager/ViewAll/'.$this->LocalTarget[1]);
						if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
					}
					$this->Scheme = 'viewall';
				}
				else $this->Scheme = 'default';
			break;
			case 'Update': case 'Duplicate': case 'Delete':
				if($this->server_type=='dev') {
					if(!empty($this->LocalTarget[1]) && validate(intval($this->LocalTarget[1]))) {
						$this->Action->processEvent($this->SectionID,'getlock',array('module' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
						if(!empty($this->PreparedTemplates['access_flag']) && $this->PreparedTemplates['access_flag']!=$this->Action->Security->currentuser->id) {
							header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							$this->terminated = true;
							return;
						}
						else {
							$undo = (!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2] == 'Undo') ? 1 : 0;
							$this->copy = (!$undo && $this->LocalTarget[0] == 'Update' && !empty($this->LocalTarget[2]) && validate(intval($this->LocalTarget[2]))) ? $this->LocalTarget[2] : false;
							if($this->copy) {
								$preparedTemplates = $this->PreparedTemplates;
								$this->Action->processEvent($this->SectionID, 'getlock', array('module' => $this->LocalTarget[2], 'member' => $this->Action->Security->currentuser->id), $this);
								if(!empty($this->PreparedTemplates['access_flag']) && $this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) {
									header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
									$this->terminated = true;
									return;
								}
								$this->PreparedTemplates = $preparedTemplates;
							}
							$selected = $this->Db->SelectSingle('module', 'type', array('id' => $this->LocalTarget[1]));
							if($this->LocalTarget[0]=='Delete') {
								if(empty($selected) || $selected!=1 || $selected==9 ||$this->LocalTarget[1]==1) header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							}
							if($this->LocalTarget[0]=='Duplicate') {
								if($selected==9 || $selected==8) header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							}
							$selected2 = $this->copy === false ? 0 : $this->Db->SelectSingle('module', 'type', array('id' => $this->copy));
							if($selected == 8 || $selected2 == 8){
								header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
								break;
							}
							if(empty($this->PreparedTemplates['access_flag']) && $this->LocalTarget[1]!=10 && $this->LocalTarget[1]!=60 && $this->LocalTarget[1]!=30) $this->Action->processEvent($this->SectionID,'lock',array('module' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
							$array = array('id' => $this->LocalTarget[1]);
							if($undo == 1) $array['undo'] = $this->LocalTarget[3];
							if($this->copy) $array['copy'] = $this->LocalTarget[2];
							$this->customerreviews = $this->Db->SelectGuide(array('customerreview g'),array('g.id','g.name'),array('1' => '1'));
							$this->Action->processEvent($this->SectionID,'open_page',$array,$this);
							if(!empty($this->PreparedTemplates['_error'])) header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							if(empty($this->PreparedTemplates['type']['id']) || ($this->PreparedTemplates['type']['id']!=1 && $this->PreparedTemplates['type']['id']!=3 && $this->PreparedTemplates['type']['id']!=6 && $this->PreparedTemplates['type']['id']!=9)) header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							if($REGISTRY['HomeTarget'] == $this->PreparedTemplates['id'] && $this->LocalTarget[0] == 'Delete') header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
							else {
								$this->Action->processEvent($this->SectionID,'select_layouts',array(),$this);
								$this->full_layouts = $this->PreparedTemplates;
								$array = array('module' => 1,'item' =>  $this->LocalTarget[1]);
								if($undo == 1) $array['undo'] = $this->LocalTarget[3];
								if($this->copy) $array['copy'] = $this->LocalTarget[2];
								$this->Action->processEvent($this->SectionID,'open_meta',$array,$this);
								$array = array('id' => $this->LocalTarget[1]);
								if($undo == 1) $array['undo'] = $this->LocalTarget[3];
								if($this->copy) $array['copy'] = $this->LocalTarget[2];
								$this->Action->processEvent($this->SectionID,'get_mli',$array,$this);
								$this->Scheme = 'action';
							}
						}
					}
					else header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
				}
				else header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
			break;
			case 'Add':
				if($this->server_type=='dev') {
					$this->Action->processEvent($this->SectionID,'select_layouts',array(),$this);
					$this->full_layouts = $this->PreparedTemplates;
					$this->Scheme = 'action';
				}
				else $this->Scheme = 'default';
			break;
			default:
				if(!empty($this->LocalTarget[0])){
					header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
					$this->terminated = true;
					return;
				}
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = 'default';
			break;
		}
		if(!empty($this->Request)) {
			if($this->server_type=='dev' || $this->getRequestField('step')=='filter') {
				switch($this->getRequestField('step')) {
					case 'homepage': {
						if(!empty($this->Request['form']['homepage'])){
							$pages = $this->Action->Server->getGuide('page');
							if(isset($pages[$this->Request['form']['homepage']])){
								GLOBAL $Server, $REGISTRY;
								$REGISTRY['HomeTarget'] = $this->Request['form']['homepage'];
								$Server->saveRegistry();
								$this->Action->processEvent($this->SectionID, 'log', array('type' => 3, 'entity' => 6, 'event' => 12, 'value' => 'Change Home Target to Page "'.$pages[$this->Request['form']['homepage']].'" ['.$REGISTRY['HomeTarget'].']'), $this);
							}
						}
						header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
						break;
					}
					case 'edit': case 'add':
						$this->Request['form']['id_user']=$this->Action->Security->currentuser->id;
						if($undo ==1) $this->Request['form']['_undo_'] = $this->LocalTarget[3];
						if($this->copy) $this->Request['form']['copy'] = $this->LocalTarget[2];
						$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
						if(isset($this->PreparedTemplates['parent']['id']) && $this->PreparedTemplates['parent']['id'] != $this->Request['form']['parent']['id'] && empty($this->Request['form']['duplicate_id']))
							$this->Request['form']['autochange'] = 'true';
						if($this->Request['form']['is_describe'])
							$this->Request['form']['default_page'] = 0;
						if(isset($this->Request['default_spell']) && $this->Request['default_spell']==1) {
							if(isset($this->Request['check_spell']) && $this->Request['check_spell']==1)
								$this->setSpellCookie("1");
							else $this->setSpellCookie("0");
						}
						$this->validateForm()
						and $this->Action->processEvent($this->SectionID,'save',$this->getRequestField('form'),$this)
						and setcookie("curId",$this->PreparedTemplates['parent']['id'],0,'/Registar/')
						and header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
					break;
					case 'sort':
						$this->sortingPages_();
						$this->Action->processEvent($this->SectionID,'sort',$this->getRequestField('form'),$this)
						and header('Location: '.$this->Home.'/Registar/ContentManager/Sort'.$this->SID);
					break;
					case 'delete':
						include ($TOOLS_PATH.'\checker.php');
						$this->check = check_to_delete($this->getRequestFormField('id'),'Page');
						if(empty($this->check) || isset($this->check['pages']) && empty($this->check['pages']) &&
							isset($this->check['menues']) && empty($this->check['menues']) &&
							isset($this->check['layouts']) && empty($this->check['layouts']) &&
							isset($this->check['templates']) && empty($this->check['templates']) &&
							isset($this->check['defaults']) && empty($this->check['defaults'])) {
							$this->Action->processEvent($this->SectionID,'delete',$this->getRequestField('form'),$this)
							and $this->clearUndo($this->getRequestFormField('id'))
							and header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
						}
						else $this->Scheme = 'nodelete';
					break;
					case 'unlock':
						$this->Request['form']['member'] = $this->Action->Security->currentuser->id;
						$this->Action->processEvent($this->SectionID,'unlock',$this->getRequestField('form'),$this);
						if(!isset($_POST['do_not_redirect']))
							header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
						exit;
					break;
					case 'filter':
						if(isset($this->Request['form']['pagetype'])) {
							$cookie = implode(',',array_keys($this->Request['form']['pagetype']));
							setcookie("pagetypes",$cookie,time()+86400*365,"/");
						}
						else setcookie("pagetypes",'',time()+86400*365,"/");
						header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
					break;
				}
			}
			else header('Location: '.$this->Home.'/Registar/ContentManager'.$this->SID);
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function clearUndo($id) {
		global $ROOT_PATH;
		if(file_exists($ROOT_PATH.'/undo/module/'.$id)) {
			chdir($ROOT_PATH.'/undo/module/'.$id);
			$dir = dir('.');
			$dir->rewind();
			while($file = $dir->read()) if(is_file($file)) unlink($ROOT_PATH.'/undo/module/'.$id.'/'.$file);
			rmdir($ROOT_PATH.'/undo/module/'.$id);
			$dir->close();
		}
		return true;
	}

	function validateForm() {
		global $subdomains;
		if(empty($subdomains)) $subdomains = $this->Db->SelectList('domain','subdomain',array('domain'));
		if(!is_AdvCleanText2($this->getRequestFormField('sys_name'),2,128)) $this->errors['sys_name'] = 'Page\'s Name is empty or is not valid';
		if(!is_AdvCleanText2($this->getRequestFormField('name'),2,128)) $this->errors['name'] = 'Page\'s Header is empty or is not valid';
		if($this->getRequestFormField('id')!=1 && !is_URLText($this->getRequestFormField('path'),1,128)&& $this->getRequestFormField('is_describe')!=2) $this->errors['path'] = 'Page\'s URL is empty or is not valid';
		if(!validate($this->getRequestFormField('path')) && $this->getRequestFormField('id')!=1 && $this->getRequestFormField('is_describe')!=2) $this->errors['path'] = 'Page\'s URL is empty';
		else if(validate($this->getRequestFormField('path')) && !is_URLText($this->getRequestFormField('path'),1,128)) $this->errors['path'] = 'Page\'s URL is not valid';
		else if(validate($this->getRequestFormField('path')) && in_array($this->getRequestFormField('path'),array('.','..'))) $this->errors['path'] = 'Page\'s URL is not valid';
		else $this->Request['form']['path'] = stripslashes($this->getRequestFormField('path'));
		if($this->getRequestFormField('is_describe')==2) {
			if(!is_URLText($this->getRequestFormField('param_name'),1,64)) $this->errors['param_name'] = 'Parameter\'s Name is empty or is not valid';
			if(!is_URLText($this->getRequestFormField('param_value'),1,64)) $this->errors['param_value'] = 'Parameter\'s Value is empty or is not valid';
		}
		if($this->LocalTarget[0]!='Add'&&$this->LocalTarget[0]!='Duplicate')
			if(!is_FullText($this->getRequestFormField('comment'),5,4096)) $this->errors['comment'] = 'Comment is empty or is not valid';
		if(($this->getRequestFormField('id')==1 && $this->LocalTarget[0]=='Delete') || ($this->LocalTarget[0]=='Delete' && $this->getRequestFormField('type',1)!=1))
			$this->errors['model'] = 'The given page cannot be deleted';
		if($this->getRequestFormField('is_describe')==1) {
			//if($this->Request['form']['type']['id']!=9) {
			
			$this->Request['form']['meta']['title'] = 		preg_replace("/—/","-",$this->Request['form']['meta']['title']);
			$this->Request['form']['meta']['title'] = 		preg_replace("/®/","",$this->Request['form']['meta']['title']);
			$this->Request['form']['meta']['title'] = 		preg_replace("/\"/","",$this->Request['form']['meta']['title']);
			$this->Request['form']['meta']['description'] =	preg_replace("/™/"," ",$this->Request['form']['meta']['description']);
			$this->Request['form']['meta']['description'] =	preg_replace("/\+/"," plus",$this->Request['form']['meta']['description']);
			$this->Request['form']['meta']['keywords'] = 	preg_replace("/—/","-",$this->Request['form']['meta']['keywords']);
			$this->Request['form']['meta']['description'] = preg_replace("/—/","-",$this->Request['form']['meta']['description']);
		
			if(!is_AdvCleanText($this->Request['form']['meta']['title'],3,286)) $this->errors['title'] = 'Page\'s Title is empty or is not valid';
			if(!is_AdvCleanText($this->Request['form']['meta']['keywords'],3,486)) $this->errors['keywords'] = 'Page\'s Keywords is empty or is not valid';
			if(!is_AdvCleanText($this->Request['form']['meta']['description'],3,486)) $this->errors['description'] = 'Page\'s Description is empty or is not valid';
			//}
			if(!validate($this->getRequestFormField('layout',1))) $this->errors['layout'] = 'Page\'s Layout is a not selected';
			if(!validate($this->getRequestFormField('controlid'))) $this->errors['controlid'] = 'Page\'s Type is a not selected';
		}
		if(validate($this->getRequestFormField('id'))) {
			if($this->getRequestFormField('parent',1)==$this->getRequestFormField('id')) $this->errors['parent'] = 'The page(subcategory) cannot be own parent';
			else if(!empty($this->pages[$this->getRequestFormField('id')]) && $this->validateMenuArray($this->pages[$this->getRequestFormField('id')],$this->getRequestFormField('parent',1)))
				$this->errors['parent'] = 'The page(subcategory) cannot have the parent the page(subcategory) enclosed in it';
			if($this->getRequestFormField('bc_parent',1)==$this->getRequestFormField('id')) $this->errors['bc_parent'] = 'The page(subcategory) cannot be own breadcrumbs parent';
			else if(!empty($this->pages[$this->getRequestFormField('id')]) && $this->validateMenuArray($this->pages[$this->getRequestFormField('id')],$this->getRequestFormField('bc_parent',1)))
				$this->errors['bc_parent'] = 'The page(subcategory) cannot have the breadcrumbs parent the page(subcategory) enclosed in it';
		}
		$this->customerreviews = $this->Db->SelectGuide(array('customerreview g'),array('g.id','g.name'),array('1' => '1'));
		empty($this->Request['form']['customerreviewitems']) and $this->Request['form']['customerreviewitems'] = array();
		$cr_ids = array();
		$i = 1;
		foreach($this->Request['form']['customerreviewitems'] as $key => $value) {
			if(!in_array($value['object'],array_keys($this->customerreviews)) || in_array($value['object'],$cr_ids)) unset($this->Request['form']['customerreviewitems'][$key]);
			else {
				$this->Request['form']['customerreviewitems'][$key]['sort_order'] = $i*10;
				$cr_ids[] = $value['object'];
				$i++;
			}
		}
		if(count($this->errors) > 0) return FALSE;
		else {
			$this->Request['form']['keywords'] = ' ';
			$links = ' ';
			foreach($this->full_layouts as $key => $value) {
				foreach($value['contenttypes'] as $k => $v) $types[$value['id']][$v['type']['id']] = 1;
			}
			foreach($this->Request['form']['contents'] as $key => $value) {
				if(empty($types[$this->Request['form']['layout']['id']][$value['type']])) unset($this->Request['form']['contents'][$key]);
			}
			foreach($this->Request['form']['contents'] as $key => $value) {
//				$this->Request['form']['contents'][$key]['value'] = eregi_replace($this->Home.'/','/',$this->Request['form']['contents'][$key]['value']);
				$this->Request['form']['contents'][$key]['value'] = str_replace($this->Home.'/','/',$this->Request['form']['contents'][$key]['value']);
				$this->Request['form']['contents'][$key]['value'] = str_replace('&amp;','&',$this->Request['form']['contents'][$key]['value']);
				$links.= implode(' ',$this->link_array($this->Request['form']['contents'][$key]['value'])).' ';
				$this->Request['form']['keywords'].= $this->clear_it($this->Request['form']['contents'][$key]['value']).' ';
			}
//print $this->Request['form']['keywords'];exit;
			$this->Request['form']['keywords'] = trim($this->Request['form']['keywords'].' __-__ '.$links);
			if($this->getRequestFormField('is_describe')!=0) {
				global $TOOLS_PATH;
				include($TOOLS_PATH.'\page_validator.inc');
				$self = $this->path_sticker($this->getRequestFormField('parent',1)).'/'.$this->getRequestFormField('path');
				$subdomain = '';
				if(preg_match("/^(\/subdomains)/i", $self)) {
					$paths = explode('/',strtolower(preg_replace('/^\//i','',$self)));
					$entry = array_shift($paths);
					if(in_array($paths[0],$subdomains)) $subdomain = $paths[0];
				}
				$error_array = page_validate($this->Request['form']['contents'],$self,$subdomain);
				$this->errors['validate'] = '';
				foreach($error_array as $value) {
		//if(!empty($value)) $this->errors['validate'].= $value;
				}
				if(!empty($this->errors['validate'])) return FALSE;
				else {
					unset($this->errors['validate']);
					return TRUE;
				}
			}
			else return TRUE;
		}
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'nodelete': $this->fillNoDelete(); break;
			case 'action': $this->fillAction(); break;
			case 'preview': $this->fillPreview(); break;
			case 'spellcheck': $this->fillSpellcheck(); break;
			case 'spellword': $this->fillSpellword(); break;
			case 'spelladd': $this->fillSpelladd(); break;
			case 'viewall': $this->fillViewAll(); break;
			case 'sort_': $this->fillSort_(); break;
			case 'sort': $this->fillSort_(); break;
			case 'json': $this->fillJson(); break;
			case 'help': $this->fillSort(); break;
			default: $this->fillSelect(); break;
			case 'crlist': break;
		}
	}

	function fillSort() {
		$this->setSortArray($this->pages[0],1);
	}

	function fillViewAll() {
		global $REGISTRY, $ROOT_PATH;
		foreach($this->PreparedTemplates['curPage'] as $ind => $val) {
			$tok = explode(".",$val['date']);
			$this->TempFillEls['comments'][] = array(
				'number' => ($this->PreparedTemplates['pageRecordsQty']*($this->PreparedTemplates['curPageNumber']-1))+($ind+1),
				'date' => $tok[0],
				'author' => $val['member'],
				'changed' => $val['value'],
				'version' => $val['version'],
				'button' =>  file_exists($ROOT_PATH.'/undo/module/'.$this->PreparedTemplates[1].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates[1],'version' => $val['version'])) : array(),
			);
		}
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'select_modulecomments');
	}

	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 fillSpellword() {
		global $REGISTRY, $CORE_PATH;
		$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['div'] = $REGISTRY['Request']['Query']['div'];
		require_once($CORE_PATH.'\Tools\spell_checker.php');
		$cp = new PSpell();
		if(empty($this->LocalTarget[2])) {
			$this->TempFillEls['editor_id'] = $editor_id = $REGISTRY['Request']['Query']['editor_id'];
			$words = $cp->getSuggestions($word);
			foreach($words as $value)
				if(isset($REGISTRY['Request']['Query']['meta'])) $this->TempFillEls['suggestion'][0]['words'][]['value'] = makeLink('javascript:void(0);',$value,array(),'','style="text-decoration:none;font-weight:normal" onclick="replaceWord2(\''.addslashes($word).'\',\''.addslashes($value).'\',\''.$check.'\','.$this->TempFillEls['id'].',\''.$this->TempFillEls['div'].'\')"');
				else $this->TempFillEls['suggestion'][0]['words'][]['value'] = makeLink('javascript:void(0);',$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 fillSpellcheck() {
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		require_once($CORE_PATH.'\Tools\spell_checker.php');
		$cp = new PSpell();
		if(!empty($this->Request) && !empty($this->Request['id'])) {
			$layout = $this->Db->SelectArray('layout','value',array('id' => $this->Request['id']));
			if(!empty($layout[0])) {
				$body = $layout[0]['value'];
				// Check Spelling in Layout
				$cp->spellCheck($body,'Layout',$this->Request['id']);
				foreach($this->Request['contents'] as $key => $value) {
					switch($value['type']) {
						case '1': $main = @$value['value']; break;
						case '2': $top = @$value['value']; break;
						case '3': $left = @$value['value']; break;
						case '4': $bottom = @$value['value']; break;
						case '5': $image = @$value['value']; break;
						case '6': $right = @$value['value']; break;
					}
				}
				empty($image) and $image = '';
				// Check Spelling in Image Area
				$cp->spellCheck($image,'Image Area');
				if(!empty($this->Request['contents'][3]['value']))
					$full_left = $this->Request['contents'][3]['value'];
				else $full_left = '';
				// Check Spelling in Left Area
				$cp->spellCheck($full_left,'Left Area');
				if(!empty($this->Request['leftmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['leftmenu']),$this);
					$this->leftmenu = $this->PreparedTemplates;
					$left_template = file_get_contents($CORE_PATH.'\Templates\LeftMenuView\LeftMenuView.default.html');
					$parser = new XTemplate($left_template);
					$els = &$parser->getElements();
					$this->setLeftMenuArray($this->leftmenu,0);
					$menus = $this->Action->Handler->selectMenus(array('type' => 4));
					$this->TempFillEls['menu'][0]['name']=$menus[$this->menu_id];
					$full_left = $parser->parseTemplate($this->TempFillEls);
					// Check Spelling in Left Menu
					$cp->spellCheck($full_left,'Left Menu',$this->Request['leftmenu']);
				}
				if(!empty($this->Request['contents'][4]['value']))
					$full_right = $this->Request['contents'][4]['value'];
				else $full_right = '';
				// Check Spelling in Right Area
				$cp->spellCheck($full_right,'Right Area');
				if(!empty($this->Request['rightmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['rightmenu']),$this);
					$this->rightmenu = $this->PreparedTemplates;
					$right_template = file_get_contents($CORE_PATH.'\Templates\RightView\RightView.default.html');
					$parser = new XTemplate($right_template);
					$els = &$parser->getElements();
					$this->setLeftMenuArray($this->rightmenu,0);
					if(!empty($this->TempFillEls['menu'][0])) {
						$menus = $this->Action->Handler->selectMenus(array('type' => 6));
						$this->TempFillEls['menu'][0]['name'] = $menus[$this->menu_id];
					}
					$full_right = $parser->parseTemplate($this->TempFillEls);
					// Check Spelling in Right Menu
					$cp->spellCheck($full_right,'Right Menu',$this->Request['rightmenu']);
				}
				if(!empty($this->Request['contents'][5]['value']))
					$full_bottom = $this->Request['contents'][5]['value'];
				else $full_bottom = '';
				// Check Spelling in Bottom Area
				$cp->spellCheck($full_bottom,'Bottom Area');
				if(!empty($this->Request['bottommenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['bottommenu']),$this);
					$this->bottommenu = $this->PreparedTemplates;
					$bottom_template = file_get_contents($CORE_PATH.'\Templates\FooterView\FooterView.default.html');
					$parser = new XTemplate($bottom_template);
					$els = &$parser->getElements();
					foreach($this->bottommenu as $key => $value)
						$menu[] = makeLink($value['path'],$value['label'],array(),$value['anchor'],($value['target']? 'target="_blank" class=copyright' : 'target="_top" class=copyright'));
					$this->TempFillEls['items'] = implode(' | ',$menu);
					$full_bottom = $parser->parseTemplate($this->TempFillEls);
					// Check Spelling in Bottom Menu
					$cp->spellCheck($full_bottom,'Bottom Menu',$this->Request['bottommenu']);
				}
				$navtab = '';
				if(!empty($this->Request['tabsmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['tabsmenu']),$this);
					$this->tabsmenu = $this->PreparedTemplates;
					$tabs_template = file_get_contents($CORE_PATH.'\Templates\NavTabView\NavTabView.default.html');
					$parser = new XTemplate($tabs_template);
					$els = &$parser->getElements();
					$this->setTabsMenuArray($this->tabsmenu,0.1);
					foreach($this->TempFillEls['items'] as $key=>$val){;
						$this->TempFillEls['items'][$key]['left']='1';
						$this->TempFillEls['items'][$key]['right']='1';
					}
					$navtab = $parser->parseTemplate($this->TempFillEls);
					// Check Spelling in NavTab Menu
					$cp->spellCheck($navtab,'Tabs Menu',$this->Request['tabsmenu']);
				}
				// Check Spelling in Meta
				$meta = $this->Request['title']." ".$this->Request['keywords']." ".$this->Request['description'];
				$cp->spellCheck($meta,'Meta Information');
				// Check Spelling in Main Area
				$cp->spellCheck($main,'Main Area');
				// Check Spelling in Top Area
				$cp->spellCheck($top,'Top Area');
				if(!empty($this->Request['idpage'])) {
					$jszones=$this->Db->SelectAny('select value from modulejszone where ownerid=\''.$this->Request['idpage'].'\' order by type');
					// Check Spelling in JS Zones
					isset($jszones[0]['value']) and $cp->spellCheck($jszones[0]['value'],'JS Head Zone');
					isset($jszones[1]['value']) and $cp->spellCheck($jszones[1]['value'],'JS Body Before Zone');
					isset($jszones[2]['value']) and $cp->spellCheck($jszones[2]['value'],'JS Body After Zone');
				}
				if(!empty($cp->count)) {
					$this->TempFillEls['error'] = array(array());
					$i = 1;
					$check = 0;
					if(!empty($this->Request['check']) && $this->Request['check']=='submit') $check = 1;
					foreach($cp->errorMsg as $key => $value) {
						if(!empty($value['count'])) {
							$div = eregi_replace(' ','',$key);
							switch($key) {
								default: case 'Top Area': $editor_id = 0; break;
								case 'Image Area': $editor_id = 1; break;
								case 'Main Area': $editor_id = 2; break;
								case 'Left Area': $editor_id = 3; break;
								case 'Right Area': $editor_id = 4; break;
								case 'Bottom Area': $editor_id = 5; break;
							}
							$this->TempFillEls['objects'][$key] = array(
								'object' => $key,
								'count'  => $value['count'],
								'objecttype' => $div,
								'div' => $i,
							);
							foreach($value['errors'] as $error) {
								switch($key) {
									case 'Left Menu': case 'Right Menu': case 'Tabs Menu': case 'Bottom Menu': {
										$this->TempFillEls['objects'][$key]['errors'][] = array(
											'url_word' => urlencode($error['word']).'/1?check='.$check.'&div='.$div.'&id='.$i.'&url=/Registar/MenuManager/'.eregi_replace(' ','',$key).'/Update/'.$value['id'],
											'word' => $error['word'],
											'string' => $error['string'],
											'div' => $i,
										);
									}
									break;
									case 'Layout': {
										$this->TempFillEls['objects'][$key]['errors'][] = array(
											'url_word' => urlencode($error['word']).'/1?check='.$check.'&div='.$div.'&id='.$i.'&url=/Registar/LayoutManager/Update/'.$value['id'],
											'word' => $error['word'],
											'string' => $error['string'],
											'div' => $i,
										);
									}
									break;
									case 'Meta Information': {
										$this->TempFillEls['objects'][$key]['errors'][] = array(
											'url_word' => urlencode($error['word']).'?meta=1&editor_id='.$editor_id.'&check='.$check.'&div='.$div.'&id='.$i,
											'word' => $error['word'],
											'string' => $error['string'],
											'div' => $i,
										);
									}
									break;
									default: {
										$this->TempFillEls['objects'][$key]['errors'][] = array(
											'url_word' => urlencode($error['word']).'?editor_id='.$editor_id.'&check='.$check.'&div='.$div.'&id='.$i,
											'word' => $error['word'],
											'string' => $error['string'],
											'div' => $i,
										);
									}
									break;
									case 'JS Head Zone': case 'JS Body Before': case 'JS Body After':{
										$this->TempFillEls['objects'][$key]['errors'][] = array(
											'url_word' => urlencode($error['word']).'/1?check='.$check.'&div='.$div.'&id='.$i.'&url=/Registar/MetaManager/Info/'.$value['id'],
											'word' => $error['word'],
											'string' => $error['string'],
											'div' => $i,
										);
									}
									break;
								}
								$i++;
							}
						}
					}
				}
				else {
					$this->TempFillEls['ok'] = array(array());
					if(!empty($this->Request['check']) && $this->Request['check']=='submit') $this->TempFillEls['submit'] = array(array());
				}
				$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_menu');
			}
		}
	}

	function fillPreview() {
		global $REGISTRY, $CORE_PATH;
		if(!empty($this->Request) && !empty($this->Request['id'])) {
			$layout = $this->Db->SelectArray('layout','value',array('id' => $this->Request['id']));
			if(!empty($layout[0])) {
				$body = $layout[0]['value'];
				$body = preg_replace('~{rootPath:static}~',$REGISTRY['Globals']['static']['rootPath'],$body);
				$body = preg_replace('~{picPath:static}~',$REGISTRY['Globals']['static']['picPath'],$body);
				$body = preg_replace('~{homePath:static}~',$REGISTRY['Globals']['static']['homePath'],$body);
				$body = preg_replace('~{currentYear:static}~',$REGISTRY['Globals']['static']['currentYear'],$body);
				foreach($this->Request['contents'] as $key => $value) {
					switch($value['type']) {
						case '1': $main = @$value['value']; break;
						case '2': $top = @$value['value']; break;
						case '3': $left = @$value['value']; break;
						case '4': $bottom = @$value['value']; break;
						case '5': $image = @$value['value']; break;
						case '6': $right = @$value['value']; break;
					}
				}
				empty($image) and $image = '';
				if(!empty($this->Request['contents'][3]['value']))
					$full_left = $this->Request['contents'][3]['value'];
				else $full_left = '';
				if(!empty($this->Request['leftmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['leftmenu']),$this);
					$this->leftmenu = $this->PreparedTemplates;
					$left_template = file_get_contents($CORE_PATH.'\Templates\LeftMenuView\LeftMenuView.default.html');
					$parser = new XTemplate($left_template);
					$els = &$parser->getElements();
					$this->setLeftMenuArray($this->leftmenu,0);
					$this->TempFillEls['describe'][] = array('value' => $left);
					$menus = $this->Action->Handler->selectMenus(array('type' => 4));
					$this->TempFillEls['menu'][0]['name']=$menus[$this->menu_id];
					$full_left = $parser->parseTemplate($this->TempFillEls);
				}
				if(!empty($this->Request['contents'][4]['value']))
					$full_right = $this->Request['contents'][4]['value'];
				else $full_right = '';
				if(!empty($this->Request['rightmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['rightmenu']),$this);
					$this->rightmenu = $this->PreparedTemplates;
					$right_template = file_get_contents($CORE_PATH.'\Templates\RightView\RightView.default.html');
					$parser = new XTemplate($right_template);
					$els = &$parser->getElements();
					$this->setLeftMenuArray($this->rightmenu,0.1);
					$this->TempFillEls['describe'][] = array('value' => $right);
					if(!empty($this->TempFillEls['menu'][0])) {
						$menus = $this->Action->Handler->selectMenus(array('type' => 6));
						$this->TempFillEls['menu'][0]['name'] = $menus[$this->menu_id];
					}
					$full_right = $parser->parseTemplate($this->TempFillEls);
				}
				if(!empty($this->Request['contents'][5]['value']))
					$full_bottom = $this->Request['contents'][5]['value'];
				else $full_bottom = '';
				if(!empty($this->Request['bottommenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['bottommenu']),$this);
					$this->bottommenu = $this->PreparedTemplates;
					$bottom_template = file_get_contents($CORE_PATH.'\Templates\FooterView\FooterView.default.html');
					$parser = new XTemplate($bottom_template);
					$els = &$parser->getElements();
					foreach($this->bottommenu as $key => $value)
						$menu[] = makeLink($value['path'],$value['label'],array(),$value['anchor'],($value['target']? 'target="_blank" class=copyright' : 'target="_top" class=copyright'));
					$this->TempFillEls['items'] = implode(' | ',$menu);
					$this->TempFillEls['describe'][] = array('value' => $bottom);
					$full_bottom = $parser->parseTemplate($this->TempFillEls);
				}
				$navtab = '';
				if(!empty($this->Request['tabsmenu'])) {
					$this->TempFillEls = array();
					$this->Action->processEvent($this->SectionID,'open_menu',array('id' => $this->Request['tabsmenu']),$this);
					$this->tabsmenu = $this->PreparedTemplates;
					$tabs_template = file_get_contents($CORE_PATH.'\Templates\NavTabView\NavTabView.default.html');
					$parser = new XTemplate($tabs_template);
					$els = &$parser->getElements();
					$this->setTabsMenuArray($this->tabsmenu,0.1);
					foreach($this->TempFillEls['items'] as $key=>$val){;
						$this->TempFillEls['items'][$key]['left']='1';
						$this->TempFillEls['items'][$key]['right']='1';
					}
					$navtab = $parser->parseTemplate($this->TempFillEls);
				}
				$navpanel = '';
				$this->TempFillEls = array();
				$this->entry[] = array('name' => $this->Request['name'],'path' => $this->Request['path'],'bc_parent' => $this->Request['bc_parent']);
				$this->getRealUrl($this->Request['bc_parent']);
				krsort($this->entry);
				reset($this->entry);
				foreach($this->entry as $id => $nav)
					$entry[] = empty($id)? $nav['name'] : makeLink($this->Home.'/'.$nav['path'],$nav['name']);
				if(count($entry)) $this->TempFillEls['nav'][$id]['entryLink'] = implode('&nbsp;->&nbsp;',$entry);
				$navpanel_template = file_get_contents($CORE_PATH.'\Templates\NavPanelView\NavPanelView.default.html');
				$parser = new XTemplate($navpanel_template);
				$els = &$parser->getElements();
				$navpanel = $parser->parseTemplate($this->TempFillEls);
				$meta = '<TITLE>'.$this->Request['title']."</TITLE>\r\n<meta name=\"keywords\" content=\"".$this->Request['keywords']."\">\r\n<meta name=\"description\" content=\"".$this->Request['description']."\">\r\n";
				if(!empty($this->Request['idpage']))
					$jszones=$this->Db->SelectAny('select value from modulejszone where ownerid=\''.$this->Request['idpage'].'\' order by type');
				$body = preg_replace('~{meta:virtual}~',"\r\n<!-- START META -->\r\n".preg_replace('~\$~','\\\$',$meta)."<!-- END META -->\r\n",$body);
				$body = preg_replace('~{top:virtual}~',"\r\n<!-- START TOP -->\r\n".preg_replace('~\$~','\\\$',$top)."<!-- END TOP -->\r\n",$body);
				$body = preg_replace('~{main:virtual}~',"\r\n<!-- START MAIN -->\r\n".preg_replace('~\$~','\\\$',$main)."<!-- END MAIN -->\r\n",$body);
				$body = preg_replace('~{image:virtual}~',"\r\n<!-- START IMAGE -->\r\n".$image."<!-- END IMAGE -->\r\n",$body);
				$body = preg_replace('~{left:virtual}~',"\r\n<!-- START LEFT -->\r\n".preg_replace('~\$~','\\\$',$full_left)."<!-- END LEFT -->\r\n",$body);
				$body = preg_replace('~{right:virtual}~',"\r\n<!-- START RIGHT -->\r\n".preg_replace('~\$~','\\\$',$full_right)."<!-- END RIGHT -->\r\n",$body);
				$body = preg_replace('~{navtab:virtual}~',"\r\n<!-- START NAVTAB -->\r\n".preg_replace('~\$~','\\\$',$navtab)."<!-- END NAVTAB -->\r\n",$body);
				$body = preg_replace('~{bottom:virtual}~',"\r\n<!-- START BOTTOM -->\r\n".preg_replace('~\$~','\\\$',$full_bottom)."<!-- END BOTTOM -->\r\n",$body);
				$body = preg_replace('~{adminpanel:virtual}~',"\r\n<!-- START ADMINPANEL -->\r\n <!-- END ADMINPANEL -->\r\n",$body);
				$body = preg_replace('~{jshead:virtual}~',"\r\n<!-- START JSHEAD -->\r\n".(isset($jszones[0]['value'])? $jszones[0]['value']:'')."<!-- END JSHEAD -->\r\n",$body);
				$body = preg_replace('~{jsbody_before:virtual}~',"\r\n<!-- START JSBODY_BEFORE -->\r\n".(isset($jszones[1]['value'])? $jszones[1]['value']:'')."<!-- END JSBODY_BEFORE -->\r\n",$body);
				$body = preg_replace('~{jsbody_after:virtual}~',"\r\n<!-- START JSBODY_AFTER -->\r\n".(isset($jszones[2]['value'])? $jszones[2]['value']:'')."<!-- END JSBODY_AFTER -->\r\n",$body);
				$body = preg_replace('~{navpanel:virtual}~',"\r\n<!-- START NAVPANEL -->\r\n".preg_replace('~\$~','\\\$',$navpanel)."<!-- END NAVPANEL -->\r\n",$body);
				$body = preg_replace('~{leftS:static}~','{',$body);
				$this->TempFillEls['body'] = $body;
				//printArray($this->TempFillEls['body']);
				$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_menu');
			}
		}
	}

	function fillNoDelete() {
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
		$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
		$this->TempFillEls['sec_name'] = '" '.$this->PreparedTemplates['sys_name'].' "';
		empty($this->check['pages']) and $this->check['pages'] = array();
		empty($this->check['defaults']) and $this->check['defaults'] = array();
		empty($this->check['menues']) and $this->check['menues'] = array();
		empty($this->check['templates']) and $this->check['templates'] = array();
		empty($this->check['layouts']) and $this->check['layouts'] = array();
		foreach($this->check['pages'] as $key => $value) {
			$this->TempFillEls['Pages'][0]['pitems'][] = array(
				'item' => makeLink($this->Home.'/Registar/'.(empty($value['update_path']) ? (empty($value['js']) ? 'ContentManager' : 'MetaManager/Page').'/Update/'.$value['id'] : $value['update_path']), $value['name']),
				'id' => $value['id'],
				'path' => empty($value['path']) ? '&nbsp;' : makeLink($this->Home.$value['path'], 'View', array(), '', 'class=adminlink'),
			);
		}
		foreach($this->check['defaults'] as $key => $value) {
			$this->TempFillEls['Defaults'][0]['ditems'][] = array(
				'item' => makeLink($this->Home.$value['path'],$value['name']),
				'id' => $value['id'],
			);
		}
		foreach($this->check['menues'] as $key => $value) {
			$this->TempFillEls['Menues'][0]['mitems'][] = array(
				'item' => makeLink($this->Home.'/Registar/MenuManager/'.$value['type'].'Menu/Update/'.$value['id'], $value['name']),
			);
		}
		foreach($this->check['templates'] as $key => $value) {
			$this->TempFillEls['Templates'][0]['titems'][] = array(
				'item' => makeLink($this->Home.'/Registar/TemplateManager/Update/'.$value['id'],$value['name']),
			);
		}
		foreach($this->check['layouts'] as $key => $value) {
			$this->TempFillEls['Layouts'][0]['litems'][] = array(
				'item' => makeLink($this->Home.'/Registar/LayoutManager/Update/'.$value['id'],$value['name']),
			);
		}
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_page');
	}

	function fillAction() {
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		if($this->copy) $this->TempFillEls['copy'] = '(copy content from ['.$this->copy.'])';
		$start = $style = $select = '';
		$this->pagetypes = $this->Action->Server->getGuide('pagetype');
		$this->layouts = $this->Action->Server->getGuide('layout');
		$this->leftmenu = $this->Action->Server->getGuide('leftmenu');
		$this->rightmenu = $this->Action->Server->getGuide('rightmenu');
		$this->tabsmenu = $this->Action->Server->getGuide('tabsmenu');
		$this->bottommenu = $this->Action->Server->getGuide('bottommenu');
		$this->areatype = $this->Action->Server->getGuide('contenttype');
		$i = 1;
		foreach($this->full_layouts as $key => $value) {
			$types = array(1 => 0,2 => 0,3 => 0,4 => 0,5 => 0,6 => 0);
			foreach($value['contenttypes'] as $k => $v) {
				$types[$v['type']['sort_order']] = 1;
			}
			$this->TempFillEls['layouts'][$key] = array(
				'id' => $i,
				'types' => implode(',',$types),
			);
			$i++;
		}
		switch($this->LocalTarget[0]) {
			case 'Delete': {
				$this->TempFillEls['city'] = 1;
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_meta');
				foreach($this->PreparedTemplates as $value) {
					switch($value['metatype']['id']) {
						case 1: $this->TempFillEls['title'] = @$value['value']; break;
						case 2: $this->TempFillEls['description'] = @$value['value']; break;
						case 3: $this->TempFillEls['keywords'] = @$value['value']; break;
					}
				}
				empty($this->TempFillEls['title']) and $this->TempFillEls['title'] = ' --- ';
				empty($this->TempFillEls['description']) and $this->TempFillEls['description'] = ' --- ';
				empty($this->TempFillEls['keywords']) and $this->TempFillEls['keywords'] = ' --- ';
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
				$this->TempFillEls['is_insearch'] = $this->PreparedTemplates['is_insearch']==1? 'Yes' : 'No';
				$this->TempFillEls['is_exsearch'] = $this->PreparedTemplates['is_exsearch']==1? 'Yes' : 'No';
				$this->TempFillEls['is_describe'] = $this->contenttype[$this->PreparedTemplates['is_describe']];
				$this->TempFillEls['step'] = 'delete';
				$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['unlock_id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['type'] = $this->PreparedTemplates['type'];
				$this->TempFillEls['page_type'] = $this->PreparedTemplates['is_describe'];
				$this->TempFillEls['action'] = $this->LocalTarget[0];
				$this->TempFillEls['sec_name'] = '" '.$this->PreparedTemplates['sys_name'].' "';
				$this->TempFillEls['sys_name'] = @$this->PreparedTemplates['sys_name'];
				$this->TempFillEls['path'] = @$this->PreparedTemplates['path'];
				$this->TempFillEls['name'] = @$this->PreparedTemplates['name'];
				$this->default_page_array[0] = 'No Default Page';
				$this->setDefaultPageArray($this->pages[0], 0);
				unset($this->default_page_array[1]);
				unset($this->default_page_array[empty($this->Request)? $this->PreparedTemplates['id'] : $this->Request['form']['id']]);
				foreach($this->default_page_array as $key => $value)
					$this->TempFillEls['default_page'][]['option'] = '<option value="'.$key.'" style="color: '.(is_numeric($key) ? 'black' : 'gray').';" '.(empty($this->Request) ? ($key == $this->PreparedTemplates['default_page'] ? 'selected' : '') : ($key == $this->Request['form']['default_page'] ? 'selected' : '')).'>'.$value.'</option>';
				$this->TempFillEls['default_page_ability'] = 'disabled';
				$i = 0;
				foreach($this->areatype as $key => $value) {
					$this->TempFillEls['contents'][$i] = array(
						'name' => ucfirst($value).' Area',
						'aname' => ucfirst($value).'Area',
						'value' => '<div style="border:1px solid black;padding: 1px;">'.@$this->getContent($this->PreparedTemplates['contents'],$key).'</div>',
						'div' => $i,
						'buttons' => array(),
					);
					$i++;
				}
				$this->TempFillEls['layout'] = @$this->layouts[$this->PreparedTemplates['layout']['id']];
				$this->TempFillEls['controlid'] = @$this->pagetypes[$this->PreparedTemplates['controlid']];
				$layout_init = array();
				$i = 1;
				foreach($this->layouts as $key => $value) {
					$layout_init[$key] = $i;
					$i++;
				}
				$number_cr = !empty($this->PreparedTemplates['customerreviewitems']) && count($this->PreparedTemplates['customerreviewitems']) > 0? count($this->PreparedTemplates['customerreviewitems']) : 0;
				for($i = 1; $i <= $number_cr; $i++) {
					$this->TempFillEls['cr_items'][$i] = array(
						'num' => $i,
						'sort_order' => isset($this->PreparedTemplates['customerreviewitems'][$i-1])? $this->PreparedTemplates['customerreviewitems'][$i-1]['sort_order'] : $i*10,
						'name' => strip_tags($this->customerreviews[$this->PreparedTemplates['customerreviewitems'][$i-1]['object']]),
					);
				}
				$selected = $this->Db->SelectAny("select mc.*,m.username as member from modulecomment mc, member m where m.id=mc.member and mc.ownerid = ".$this->PreparedTemplates['id']." order by mc.version DESC LIMIT 10 OFFSET 0");
				if(!empty($selected)) {
					$this->TempFillEls['ViewAllButton']='<input type="button" name="View_All" class=adminsubmit value="View All" onclick="open(\'/Registar/ContentManager/ViewAll/'.$this->PreparedTemplates['id'].'\',\'displayWindow\',\'width=950,height=600,scrollbars=yes\');">';
					foreach($selected as $ind => $val){
						$tok = explode(".",$val['date']);
						$this->TempFillEls['comment'][] = array(
							'number' => ($ind+1),
							'date' => $tok[0],
							'author' => $val['member'],
							'changed' => $val['value'],
							'version' => $val['version'],
							'button' => $ind!=0 && file_exists($ROOT_PATH.'/undo/module/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
						);
					}
				}
				$this->TempFillEls['layout_init'] = !empty($this->PreparedTemplates['layout']['id']) && $this->PreparedTemplates['is_describe']!=0 && isset($layout_init[$this->PreparedTemplates['layout']['id']])? $layout_init[$this->PreparedTemplates['layout']['id']] : 0;
				$this->setMenuArray($this->pages[0],0);
				$this->TempFillEls['parent'] = !empty($this->modules[$this->PreparedTemplates['parent']['id']])? $this->modules[$this->PreparedTemplates['parent']['id']] : $REGISTRY['Core']['SiteName'];
				$this->TempFillEls['bc_parent'] = !empty($this->modules[$this->PreparedTemplates['bc_parent']['id']])? $this->modules[$this->PreparedTemplates['bc_parent']['id']] : $REGISTRY['Core']['SiteName'];
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'get_mli');
				$this->TempFillEls['bottommenu'] = !empty($this->bottommenu[$this->PreparedTemplates['bottom']])? $this->bottommenu[$this->PreparedTemplates['bottom']] : 'No menu';
				$this->TempFillEls['leftmenu'] = !empty($this->leftmenu[$this->PreparedTemplates['left']])? $this->leftmenu[$this->PreparedTemplates['left']] : 'No menu';
				$this->TempFillEls['rightmenu'] = !empty($this->rightmenu[$this->PreparedTemplates['right']])? $this->rightmenu[$this->PreparedTemplates['right']] : 'No menu';
				$this->TempFillEls['tabsmenu'] = !empty($this->tabsmenu[$this->PreparedTemplates['tabs']])? $this->tabsmenu[$this->PreparedTemplates['tabs']] : 'No menu';
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'delete');
				!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->PreparedTemplates['_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>' : '');
			break;
			}
			case 'Update': {
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
				if($this->PreparedTemplates['type']['id']!=9) {
					$this->TempFillEls['city'] = 1;
				}
				else $this->TempFillEls['city'] = 0;
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_meta');
				foreach($this->PreparedTemplates as $value) {
					switch($value['metatype']['id']) {
						case 1: $this->TempFillEls['title'] = inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : @$value['value']),80,1,'style="width:848px;"'); break;
						case 2: $this->TempFillEls['description'] = inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : @$value['value']),80,3,'style="width:420px;"'); break;
						case 3: $this->TempFillEls['keywords'] = inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : @$value['value']),80,3,'style="width:420px;"'); break;
					}
				}
				empty($this->TempFillEls['title']) and $this->TempFillEls['title'] = inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : ''),80,1,'style="width:848px;"');
				empty($this->TempFillEls['description']) and $this->TempFillEls['description'] = inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : ''),80,3,'style="width:420px;"');
				empty($this->TempFillEls['keywords']) and $this->TempFillEls['keywords'] = inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : ''),80,3,'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
				//printArray($this->PreparedTemplates);
				$this->TempFillEls['is_insearch'] = inputHidden('form[is_insearch]',0).inputCheckbox('form[is_insearch]',(!empty($this->Request)? $this->Request['form']['is_insearch'] : $this->PreparedTemplates['is_insearch']));
				$this->TempFillEls['is_exsearch'] = inputHidden('form[is_exsearch]',0).inputCheckbox('form[is_exsearch]',(!empty($this->Request)? $this->Request['form']['is_exsearch'] : $this->PreparedTemplates['is_exsearch']));
				$this->TempFillEls['is_describe'] = $this->PreparedTemplates['id']==1 || $this->PreparedTemplates['type']['id']==9? 'Page'.inputHidden('form[is_describe]',1) : inputSelect('form[is_describe]',$this->contenttype,(!empty($this->Request)? $this->Request['form']['is_describe'] : $this->PreparedTemplates['is_describe']),'onchange="javascript:changeType(document.forms[\'page\'].elements[\'form[is_describe]\'].selectedIndex);return true;"');
				$this->TempFillEls['step'] = 'edit';
				$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['unlock_id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['type'] = $this->PreparedTemplates['type']['id'];
				$this->TempFillEls['page_type'] = !empty($this->Request)? $this->Request['form']['is_describe'] : $this->PreparedTemplates['is_describe'];
				$this->TempFillEls['action'] = $this->LocalTarget[0];
				if(!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2]=='Undo')
					$this->TempFillEls['undo'] = '(Undo v.'.$this->LocalTarget[3].')';
				$this->TempFillEls['sec_name'] = $this->LocalTarget[0]=='Add'? '' : '" '.$this->PreparedTemplates['sys_name'].' "';
				$this->TempFillEls['sys_name'] = inputText('form[sys_name]',(!empty($this->Request)? $this->Request['form']['sys_name'] : @$this->PreparedTemplates['sys_name']),80,'style="width:420px;"');
				$this->TempFillEls['path'] = $this->PreparedTemplates['id']==1? inputHidden('form[path]','') : inputText('form[path]',(!empty($this->Request)? $this->Request['form']['path'] : @$this->PreparedTemplates['path']),80,'style="width:420px;"');
				$this->TempFillEls['name'] = inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : @$this->PreparedTemplates['name']),80,'style="width:420px;"');
				$this->TempFillEls['old_url'] = empty($this->PreparedTemplates['old_url']) ? @$this->PreparedTemplates['path'] : $this->PreparedTemplates['old_url'];
				$this->TempFillEls['cr_buttons'] = array(array());
				$this->default_page_array[0] = 'No Default Page';
				$this->setDefaultPageArray($this->pages[0], 0);
				unset($this->default_page_array[1]);
				unset($this->default_page_array[empty($this->Request)? $this->PreparedTemplates['id'] : $this->Request['form']['id']]);
				foreach($this->default_page_array as $key => $value)
					$this->TempFillEls['default_page'][]['option'] = '<option value="'.$key.'" style="color: '.(is_numeric($key) ? 'black' : 'gray').';" '.(empty($this->Request) ? ($key == $this->PreparedTemplates['default_page'] ? 'selected' : '') : ($key == $this->Request['form']['default_page'] ? 'selected' : '')).'>'.$value.'</option>';
				$i = 0;
				foreach($this->areatype as $key => $value) {
//					$content = preg_replace('/&(\w+;)/', '&amp;$1', @$this->getContent($this->PreparedTemplates['contents'],$key)) ;
			$content = preg_replace('/&([#a-zA-Z0-9]{1,8}+);/', '&amp;$1;', @$this->getContent($this->PreparedTemplates['contents'],$key)) ;
					$this->TempFillEls['contents'][$i] = array(
						'name' => ucfirst($value).' Area',
						'aname' => ucfirst($value).'Area',
//						'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? preg_replace('~</textarea>~is', '<*textarea>',@$this->Request['form']['contents'][$i]['value']) : preg_replace('~</textarea>~is', '<*textarea>',@$this->getContent($this->PreparedTemplates['contents'],$key))),140,25,'id=contents'.$i.' style="width:890px;"'),
//'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? preg_replace('~</textarea>~is', '<*textarea>',@$this->Request['form']['contents'][$i]['value'] ) : preg_replace('~</textarea>~is', '<*textarea>',     $content          )),140,25,'id=contents'.$i.' style="width:890px;"'),
'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? preg_replace('~</textarea>~is', '<*textarea>',   preg_replace('/&(\w+;)/', '&amp;$1;', @$this->Request['form']['contents'][$i]['value']   )    ) : preg_replace('~</textarea>~is', '<*textarea>',     $content          )),140,25,'id=contents'.$i.' style="width:890px;"'),
						'type' => inputHidden('form[contents]['.$i.'][type]',$key),
						'sort_order' => inputHidden('form[contents]['.$i.'][sort_order]',$i+1),
						'div' => $i,
						'buttons' => $this->PreparedTemplates['type']['id']==9? array() : array(array('div' => $i,'templates' => $select)),
					);
					$i++;
				}
//exit;
				$number_cr = !empty($this->Request['form']['customerreviewitems']) && count($this->Request['form']['customerreviewitems']) > 0? count($this->Request['form']['customerreviewitems']) : (!empty($this->PreparedTemplates['customerreviewitems']) && count($this->PreparedTemplates['customerreviewitems']) > 0? count($this->PreparedTemplates['customerreviewitems']) : 0);
				for($i = 1; $i <= $number_cr; $i++) {
					$this->TempFillEls['cr_items'][$i] = array(
						'num' => $i,
						'sort_order' => inputText('form[customerreviewitems]['.$i.'][sort_order]',(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['sort_order'] : (isset($this->PreparedTemplates['customerreviewitems'][$i-1])? $this->PreparedTemplates['customerreviewitems'][$i-1]['sort_order'] : $i*10)),2,'style="width:30px;"'),
						'delete_cr' => array(array('num' => $i)),
						'object' => inputHidden('form[customerreviewitems]['.$i.'][object]', (!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : $this->PreparedTemplates['customerreviewitems'][$i-1]['object'])),
						'name' => inputText('form[customerreviewitems]['.$i.'][name]', htmlspecialchars(strip_tags($this->customerreviews[(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : $this->PreparedTemplates['customerreviewitems'][$i-1]['object'])]), ENT_QUOTES),2,'disabled="true" style="width:480px;"'),
						'type' => inputHidden('form[customerreviewitems]['.$i.'][moduletype]', 1),
						'change_cr' => array(array('num' => $i)),
					);
					if(!empty($this->errors['cr'][$i]))
						foreach($this->errors['cr'][$i] as $key => $value) $this->TempFillEls['cr_items'][$i][$key.'_error'] = $this->printError($value);
				}
				$this->TempFillEls['textareaValidJS']='if(parseInt(document.getElementById("comment").value.length+"-")<5 && document.getElementById("check_spell").checked==false){
					//document.getElementById("comment").focus();
					alert("Comment is empty or is not valid");
					return false;
					}';
				$this->TempFillEls['ViewAllButton']='<input type="button" name="View_All" class=adminsubmit value="View All" onclick="open(\'/Registar/ContentManager/ViewAll/'.$this->PreparedTemplates['id'].'\',\'displayWindow\',\'width=950,height=600,scrollbars=yes\');">';
				$this->TempFillEls['textareaComment']='<textarea name=form[comment] id=comment cols=80 rows=5>'.(!empty($this->Request['form']['comment'])? $this->Request['form']['comment'] : '').'</textarea>';
				$selected = $this->Db->SelectAny("select mc.*,m.username as member from modulecomment mc, member m where m.id=mc.member and mc.ownerid = ".$this->PreparedTemplates['id']." order by mc.version DESC LIMIT 10 OFFSET 0");
				if(!empty($selected)) {
					foreach($selected as $ind => $val) {
						$tok = explode(".",$val['date']);
						$this->TempFillEls['comment'][] = array(
							'number' => ($ind+1),
							'date' => $tok[0],
							'author' => $val['member'],
							'changed' => $val['value'],
							'version' => $val['version'],
							'button' => $ind!=0 && file_exists($ROOT_PATH.'/undo/module/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
						);
					}
				}
				$this->TempFillEls['start']=$start;
				$this->TempFillEls['controlid'] = inputSelect('form[controlid]',mergeArrays(array('0' => ' ------- Select Type ------- '),$this->pagetypes),(!empty($this->Request)? $this->Request['form']['controlid'] : $this->PreparedTemplates['controlid']));
				$this->TempFillEls['layout'] = inputSelect('form[layout][id]',mergeArrays(array('0' => ' ------- Select Layout ------- '),$this->layouts),(!empty($this->Request)? $this->Request['form']['layout']['id'] : $this->PreparedTemplates['layout']['id']),"onchange=\"javascript:over('layout',document.forms['page'].elements['form[layout][id]'].selectedIndex)\"");
				$layout_init = array();
				$i = 1;
				foreach($this->layouts as $key => $value) {
					$layout_init[$key] = $i;
					$i++;
				}
				$this->TempFillEls['layout_init'] = !empty($this->Request)? ($this->Request['form']['is_describe']!=0? (isset($layout_init[$this->Request['form']['layout']['id']])? $layout_init[$this->Request['form']['layout']['id']] : 0) : 0) : ($this->PreparedTemplates['is_describe']!=0 && isset($layout_init[$this->PreparedTemplates['layout']['id']])? $layout_init[$this->PreparedTemplates['layout']['id']] : 0);
				$this->setMenuArray($this->pages[0],0);
				$this->TempFillEls['parent'] = $this->PreparedTemplates['id']==1? inputHidden('form[parent][id]',0) : inputSelect('form[parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('parent',1) : $this->PreparedTemplates['parent']['id']),'style="width:420px;"');
				$this->TempFillEls['bc_parent'] = inputSelect('form[bc_parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('bc_parent',1) : $this->PreparedTemplates['bc_parent']['id']),'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'get_mli');
				$this->TempFillEls['bottommenu'] = inputSelect('form[menu][bottom]',mergeArrays(array('0' => ' ------- Select Bottom Menu ------- '),$this->bottommenu),(!empty($this->Request)? $this->Request['form']['menu']['bottom'] : $this->PreparedTemplates['bottom']),'style="width:420px;"');
				$this->TempFillEls['leftmenu'] = inputSelect('form[menu][left]',mergeArrays(array('0' => ' ------- Select Left Menu ------- '),$this->leftmenu),(!empty($this->Request)? $this->Request['form']['menu']['left'] : $this->PreparedTemplates['left']),'style="width:420px;"');
				$this->TempFillEls['rightmenu'] = inputSelect('form[menu][right]',mergeArrays(array('0' => ' ------- Select Right Menu ------- '),$this->rightmenu),(!empty($this->Request)? $this->Request['form']['menu']['right'] : $this->PreparedTemplates['right']),'style="width:420px;"');
				$this->TempFillEls['tabsmenu'] = inputSelect('form[menu][tabs]',mergeArrays(array('0' => ' ------- Select Tabs Menu ------- '),$this->tabsmenu),(!empty($this->Request)? $this->Request['form']['menu']['tabs'] : $this->PreparedTemplates['tabs']),'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'save');
				!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->PreparedTemplates['_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->TempFillEls['prew'] = array(array());
				$this->TempFillEls['spell'] = array(array());
				$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
			break;
			}
			case 'Duplicate': {
				$this->TempFillEls['city'] = 1;
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_meta');
				foreach($this->PreparedTemplates as $value) {
					switch($value['metatype']['id']) {
						case 1: $this->TempFillEls['title'] = inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : @$value['value']),80,1,'style="width:848px;"'); break;
						case 2: $this->TempFillEls['description'] = inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : @$value['value']),80,3,'style="width:420px;"'); break;
						case 3: $this->TempFillEls['keywords'] = inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : @$value['value']),80,3,'style="width:420px;"'); break;
					}
				}
				empty($this->TempFillEls['title']) and $this->TempFillEls['title'] = inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : ''),80,1,'style="width:848px;"');
				empty($this->TempFillEls['description']) and $this->TempFillEls['description'] = inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : ''),80,3,'style="width:420px;"');
				empty($this->TempFillEls['keywords']) and $this->TempFillEls['keywords'] = inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : ''),80,3,'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
				$this->TempFillEls['is_insearch'] = inputHidden('form[is_insearch]',0).inputCheckbox('form[is_insearch]',(!empty($this->Request)? $this->Request['form']['is_insearch'] : $this->PreparedTemplates['is_insearch']));
				$this->TempFillEls['is_exsearch'] = inputHidden('form[is_exsearch]',0).inputCheckbox('form[is_exsearch]',(!empty($this->Request)? $this->Request['form']['is_exsearch'] : $this->PreparedTemplates['is_exsearch']));
				$this->TempFillEls['is_describe'] = inputSelect('form[is_describe]',$this->contenttype,(!empty($this->Request)? $this->Request['form']['is_describe'] : $this->PreparedTemplates['is_describe']),'onchange="javascript:changeType(document.forms[\'page\'].elements[\'form[is_describe]\'].selectedIndex);return true;"');
				$this->TempFillEls['step'] = 'add';
				$this->TempFillEls['id'] = '';
				$this->TempFillEls['duplicate_id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['unlock_id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['type'] = 1;
				$this->TempFillEls['page_type'] = !empty($this->Request)? $this->Request['form']['is_describe'] : $this->PreparedTemplates['is_describe'];
				$this->TempFillEls['action'] = $this->LocalTarget[0];
				$this->TempFillEls['sec_name'] = '" '.$this->PreparedTemplates['sys_name'].' "';
				$this->TempFillEls['sys_name'] = inputText('form[sys_name]',(!empty($this->Request)? $this->Request['form']['sys_name'] : @$this->PreparedTemplates['sys_name']),80,'style="width:420px;"');
				$this->TempFillEls['path'] = inputText('form[path]',(!empty($this->Request)? $this->Request['form']['path'] : @$this->PreparedTemplates['path']),80,'style="width:420px;"');
				$this->TempFillEls['name'] = inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : @$this->PreparedTemplates['name']),80,'style="width:420px;"');
				$this->TempFillEls['old_url'] = @$this->PreparedTemplates['path'];
				$this->TempFillEls['cr_buttons'] = array(array());
				$this->default_page_array[0] = 'No Default Page';
				$this->setDefaultPageArray($this->pages[0], 0);
				unset($this->default_page_array[1]);
				unset($this->default_page_array[empty($this->Request)? $this->PreparedTemplates['id'] : $this->Request['form']['id']]);
				foreach($this->default_page_array as $key => $value)
					$this->TempFillEls['default_page'][]['option'] = '<option value="'.$key.'" style="color: '.(is_numeric($key) ? 'black' : 'gray').';" '.(empty($this->Request) ? ($key == $this->PreparedTemplates['default_page'] ? 'selected' : '') : ($key == $this->Request['form']['default_page'] ? 'selected' : '')).'>'.$value.'</option>';
				$i = 0;
				foreach($this->areatype as $key => $value) {
					$this->TempFillEls['contents'][$i] = array(
						'name' => ucfirst($value).' Area',
						'aname' => ucfirst($value).'Area',
						'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? preg_replace('~</textarea>~is', '<*textarea>',@$this->Request['form']['contents'][$i]['value']) : preg_replace('~</textarea>~is', '<*textarea>',@$this->getContent($this->PreparedTemplates['contents'],$key))),140,25,'id=contents'.$i.' style="width:890px;"'),
						'type' => inputHidden('form[contents]['.$i.'][type]',$key),
						'sort_order' => inputHidden('form[contents]['.$i.'][sort_order]',$i+1),
						'div' => $i,
						'buttons' => array(array('div' => $i,'templates' => $select)),
					);
					$i++;
				}
				$this->TempFillEls['start']=$start;
				$this->TempFillEls['layout'] = inputSelect('form[layout][id]',mergeArrays(array('0' => ' ------- Select Layout ------- '),$this->layouts),(!empty($this->Request)? $this->Request['form']['layout']['id'] : $this->PreparedTemplates['layout']['id']),"onchange=\"javascript:over('layout',document.forms['page'].elements['form[layout][id]'].selectedIndex)\"");
				$this->TempFillEls['controlid'] = inputSelect('form[controlid]',mergeArrays(array('0' => ' ------- Select Type ------- '),$this->pagetypes),(!empty($this->Request)? $this->Request['form']['controlid'] : $this->PreparedTemplates['controlid']));
				$layout_init = array();
				$i = 1;
				foreach($this->layouts as $key => $value) {
					$layout_init[$key] = $i;
					$i++;
				}
				$number_cr = !empty($this->Request['form']['customerreviewitems']) && count($this->Request['form']['customerreviewitems']) > 0? count($this->Request['form']['customerreviewitems']) : (!empty($this->PreparedTemplates['customerreviewitems']) && count($this->PreparedTemplates['customerreviewitems']) > 0? count($this->PreparedTemplates['customerreviewitems']) : 0);
				for($i = 1; $i <= $number_cr; $i++) {
					$this->TempFillEls['cr_items'][$i] = array(
						'num' => $i,
						'sort_order' => inputText('form[customerreviewitems]['.$i.'][sort_order]',(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['sort_order'] : (isset($this->PreparedTemplates['customerreviewitems'][$i-1])? $this->PreparedTemplates['customerreviewitems'][$i-1]['sort_order'] : $i*10)),2,'style="width:30px;"'),
						'delete_cr' => array(array('num' => $i)),
						'object' => inputHidden('form[customerreviewitems]['.$i.'][object]', (!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : $this->PreparedTemplates['customerreviewitems'][$i-1]['object'])),
						'name' => inputText('form[customerreviewitems]['.$i.'][name]', htmlspecialchars(strip_tags($this->customerreviews[(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : $this->PreparedTemplates['customerreviewitems'][$i-1]['object'])]), ENT_QUOTES),2,'disabled="true" style="width:480px;"'),
						'type' => inputHidden('form[customerreviewitems]['.$i.'][moduletype]', 1),
						'change_cr' => array(array('num' => $i)),
					);
					if(!empty($this->errors['cr'][$i]))
						foreach($this->errors['cr'][$i] as $key => $value) $this->TempFillEls['cr_items'][$i][$key.'_error'] = $this->printError($value);
				}
				$this->TempFillEls['layout_init'] = !empty($this->Request)? ($this->Request['form']['is_describe']==1? (isset($layout_init[$this->Request['form']['layout']['id']])? $layout_init[$this->Request['form']['layout']['id']] : 0) : 0) : ($this->PreparedTemplates['is_describe']!=0 && isset($layout_init[$this->PreparedTemplates['layout']['id']])? $layout_init[$this->PreparedTemplates['layout']['id']] : 0);
				$this->setMenuArray($this->pages[0],0);
				$this->TempFillEls['parent'] = inputSelect('form[parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('parent',1) : $this->PreparedTemplates['parent']['id']),'style="width:420px;"');
				$this->TempFillEls['bc_parent'] = inputSelect('form[bc_parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('bc_parent',1) : $this->PreparedTemplates['bc_parent']['id']),'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'get_mli');
				$this->TempFillEls['bottommenu'] = inputSelect('form[menu][bottom]',mergeArrays(array('0' => ' ------- Select Bottom Menu ------- '),$this->bottommenu),(!empty($this->Request)? $this->Request['form']['menu']['bottom'] : $this->PreparedTemplates['bottom']),'style="width:420px;"');
				$this->TempFillEls['leftmenu'] = inputSelect('form[menu][left]',mergeArrays(array('0' => ' ------- Select Left Menu ------- '),$this->leftmenu),(!empty($this->Request)? $this->Request['form']['menu']['left'] : $this->PreparedTemplates['left']),'style="width:420px;"');
				$this->TempFillEls['rightmenu'] = inputSelect('form[menu][right]',mergeArrays(array('0' => ' ------- Select Right Menu ------- '),$this->rightmenu),(!empty($this->Request)? $this->Request['form']['menu']['right'] : $this->PreparedTemplates['right']),'style="width:420px;"');
				$this->TempFillEls['tabsmenu'] = inputSelect('form[menu][tabs]',mergeArrays(array('0' => ' ------- Select Tabs Menu ------- '),$this->tabsmenu),(!empty($this->Request)? $this->Request['form']['menu']['tabs'] : $this->PreparedTemplates['tabs']),'style="width:420px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'save');
				!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->PreparedTemplates['_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->TempFillEls['prew'] = array(array());
				$this->TempFillEls['spell'] = array(array());
				$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
			break;
			}
			case 'Add': {
				$this->TempFillEls['city'] = 1;
				$this->TempFillEls['title'] = inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : ''),80,1,'style="width:848px;"');
				$this->TempFillEls['description'] = inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : ''),80,3,'style="width:420px;"');
				$this->TempFillEls['keywords'] = inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : ''),80,3,'style="width:420px;"');
				$this->TempFillEls['is_insearch'] = inputHidden('form[is_insearch]',0).inputCheckbox('form[is_insearch]',(!empty($this->Request)? $this->Request['form']['is_insearch'] : 1));
				$this->TempFillEls['is_exsearch'] = inputHidden('form[is_exsearch]',0).inputCheckbox('form[is_exsearch]',(!empty($this->Request)? $this->Request['form']['is_exsearch'] : 1));
				$this->TempFillEls['is_describe'] = inputSelect('form[is_describe]',$this->contenttype,(!empty($this->Request)? $this->Request['form']['is_describe'] : 1),'onchange="javascript:changeType(document.forms[\'page\'].elements[\'form[is_describe]\'].selectedIndex);return true;"');
				$this->TempFillEls['step'] = 'add';
				$this->TempFillEls['id'] = '';
				$this->TempFillEls['unlock_id'] = '';
				$this->TempFillEls['type'] = 1;
				$this->TempFillEls['page_type'] = !empty($this->Request)? $this->Request['form']['is_describe'] : 1;
				$this->TempFillEls['action'] = $this->LocalTarget[0];
				$this->TempFillEls['sec_name'] = $this->LocalTarget[0]=='Add'? '' : '" '.$this->PreparedTemplates['sys_name'].' "';
				$this->TempFillEls['sys_name'] = inputText('form[sys_name]',(!empty($this->Request)? $this->Request['form']['sys_name'] : ''),80,'style="width:420px;"');
				$this->TempFillEls['path'] = inputText('form[path]',(!empty($this->Request)? $this->Request['form']['path'] : ''),80,'style="width:420px;"');
				$this->TempFillEls['name'] = inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : ''),80,'style="width:420px;"');
				$this->TempFillEls['cr_buttons'] = array(array());
				$this->default_page_array[0] = 'No Default Page';
				$this->setDefaultPageArray($this->pages[0], 0);
				unset($this->default_page_array[1]);
				if(!empty($this->Request['form']['id']))
					unset($this->default_page_array[$this->Request['form']['id']]);
				foreach($this->default_page_array as $key => $value)
					$this->TempFillEls['default_page'][]['option'] = '<option value="'.$key.'" style="color: '.(is_numeric($key) ? 'black' : 'gray').';" '.(empty($this->Request) ? ($key === 0 ? 'selected' : '') : ($key == $this->Request['form']['default_page'] ? 'selected' : '')).'>'.$value.'</option>';
				$i = 0;
				foreach($this->areatype as $key => $value) {
					$this->TempFillEls['contents'][$i] = array(
						'name' => ucfirst($value).' Area',
						'aname' => ucfirst($value).'Area',
						'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? preg_replace('~</textarea>~is', '<*textarea>',@$this->Request['form']['contents'][$i]['value']) : ''),140,25,'id=contents'.$i.' style="width:890px;"'),
						'type' => inputHidden('form[contents]['.$i.'][type]',$key),
						'sort_order' => inputHidden('form[contents]['.$i.'][sort_order]',$i+1),
						'div' => $i,
						'buttons' => array(array('div' => $i,'templates' => $select)),
					);
					$i++;
				}
				$this->TempFillEls['start']=$start;
				$this->TempFillEls['layout'] = inputSelect('form[layout][id]',mergeArrays(array('0' => ' ------- Select Layout ------- '),$this->layouts),(!empty($this->Request)? $this->Request['form']['layout']['id'] : 0),"onchange=\"javascript:over('layout',document.forms['page'].elements['form[layout][id]'].selectedIndex)\"");
				$this->TempFillEls['controlid'] = inputSelect('form[controlid]',mergeArrays(array('0' => ' ------- Select Type ------- '),$this->pagetypes),(!empty($this->Request)? $this->Request['form']['controlid'] : 3));
				$layout_init = array();
				$i = 1;
				foreach($this->layouts as $key => $value) {
					$layout_init[$key] = $i;
					$i++;
				}
				$number_cr = !empty($this->Request['form']['customerreviewitems']) && count($this->Request['form']['customerreviewitems']) > 0? count($this->Request['form']['customerreviewitems']) : 0;
				for($i = 1; $i <= $number_cr; $i++) {
					$this->TempFillEls['cr_items'][$i] = array(
						'num' => $i,
						'sort_order' => inputText('form[customerreviewitems]['.$i.'][sort_order]',(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['sort_order'] : $i*10),2,'style="width:30px;"'),
						'delete_cr' => array(array('num' => $i)),
						'object' => inputHidden('form[customerreviewitems]['.$i.'][object]', (!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : 0)),
						'name' => inputText('form[customerreviewitems]['.$i.'][name]', htmlspecialchars(strip_tags($this->customerreviews[(!empty($this->Request)? @$this->Request['form']['customerreviewitems'][$i]['object'] : '')]), ENT_QUOTES),2,'disabled="true" style="width:480px;"'),
						'type' => inputHidden('form[customerreviewitems]['.$i.'][moduletype]', 1),
						'change_cr' => array(array('num' => $i)),
					);
					if(!empty($this->errors['cr'][$i]))
						foreach($this->errors['cr'][$i] as $key => $value) $this->TempFillEls['cr_items'][$i][$key.'_error'] = $this->printError($value);
				}
				$this->TempFillEls['layout_init'] = !empty($this->Request)? ($this->Request['form']['is_describe']==1? (isset($layout_init[$this->Request['form']['layout']['id']])? $layout_init[$this->Request['form']['layout']['id']] : 0) : 0) : 0;
				$this->setMenuArray($this->pages[0],0);
				$this->TempFillEls['parent'] = inputSelect('form[parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('parent',1) : 0),'style="width:420px;"');
				$this->TempFillEls['bc_parent'] = inputSelect('form[bc_parent][id]',mergeArrays(array('0' => ' ------- '.$REGISTRY['Core']['SiteName'].' ------- '),$this->modules),(!empty($this->Request)? $this->getRequestFormField('bc_parent',1) : 0),'style="width:420px;"');
				$this->TempFillEls['bottommenu'] = inputSelect('form[menu][bottom]',mergeArrays(array('0' => ' ------- Select Bottom Menu ------- '),$this->bottommenu),(!empty($this->Request)? $this->Request['form']['menu']['bottom'] : 0),'style="width:420px;"');
				$this->TempFillEls['leftmenu'] = inputSelect('form[menu][left]',mergeArrays(array('0' => ' ------- Select Left Menu ------- '),$this->leftmenu),(!empty($this->Request)? $this->Request['form']['menu']['left'] : 0),'style="width:420px;"');
				$this->TempFillEls['rightmenu'] = inputSelect('form[menu][right]',mergeArrays(array('0' => ' ------- Select Right Menu ------- '),$this->rightmenu),(!empty($this->Request)? $this->Request['form']['menu']['right'] : 0),'style="width:420px;"');
				$this->TempFillEls['tabsmenu'] = inputSelect('form[menu][tabs]',mergeArrays(array('0' => ' ------- Select Tabs Menu ------- '),$this->tabsmenu),(!empty($this->Request)? $this->Request['form']['menu']['tabs'] : 0),'style="width:420px;"');
				!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->PreparedTemplates['_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->TempFillEls['prew'] = array(array());
				$this->TempFillEls['spell'] = array(array());
				$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
			break;
			}
		}
		$this->TempFillEls['new_param_id_cr'] = $number_cr;
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_meta');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_page');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'get_mli');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'delete');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'select_layouts');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'getlock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'log');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'save');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'sort');
	}

	function getParents($id,$arr){
		$count=count($this->allPage);
		for($i=0;$i<$count;$i++) {
			if($this->allPage[$i]['parent']==$id) $arr[]=$this->allPage[$i];
			if($this->allPage[$i]['id']==$id) $arr = $this->getParents($this->allPage[$i]['parent'],$arr);
		}
		return $arr;
	}

	function fillJson(){
		global $REGISTRY,$subdomains,$signature;
		$this->setPath();
		switch($this->LocalTarget[1]){
			case 'getSavePosition':
				if(isset($this->LocalTarget[2])&&is_numeric($this->LocalTarget[2])){
//					$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path,('now' - date_changed) as interval, sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6 or type=8)  order by parent , sort_order ASC ");
					$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, TIMESTAMPDIFF(day,date_changed,NOW()) as 'interval', sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6 or type=8)  order by parent , sort_order ASC ");
					$pagetypes = array();
					if(isset($_COOKIE['pagetypes'])) {
						$pagetypes = explode(',',$_COOKIE['pagetypes']);
					}
					else $pagetypes = array_keys($this->pagetypes);
					foreach($this->allPage as $key => $value) {
						if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($this->allPage[$key]);
					}
					$this->allPage = array_values($this->allPage);
					$aParents = $this->getParents($this->LocalTarget[2],array());
					$countParents=count($aParents);
				}
			case 'getChild':
				if(isset($this->LocalTarget[2])&&(is_numeric($this->LocalTarget[2])||$this->LocalTarget[2]=='All')){
					if(!isset($this->allPage))
				//		$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path,('now' - date_changed) as interval, sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6 or type=8)  order by parent , sort_order ASC");
						$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, TIMESTAMPDIFF(day,date_changed,NOW()) as 'interval', sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6 or type=8)  order by parent , sort_order ASC");
					$pagetypes = array();
					if(isset($_COOKIE['pagetypes'])) {
						$pagetypes = explode(',',$_COOKIE['pagetypes']);
					}
					else $pagetypes = array_keys($this->pagetypes);
					foreach($this->allPage as $key => $value) {
						if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($this->allPage[$key]);
					}
					$this->allPage = array_values($this->allPage);//printArray($this->allPage);
					$users = $this->Db->SelectGuide('member g', array('g.id','g.username as name'),array(1 => 1));
					$select_servers=$this->Db->SelectAny("select path from preset");
					$countServers=count($select_servers);
					$hasCurServer='false';
					foreach($select_servers as $value)
						if($value['path']=='http://'.$_SERVER['HTTP_HOST'].'/') $hasCurServer='true';
					$cnt=0;
					$arrId = Array();
					$arrPath = Array();
					$count=count($this->allPage);
					$countParents=(isset($aParents))? count($aParents): 0;
					for($i=0;$i<$count;$i++){
						for($k=0;$k<$countParents;$k++)
							if($aParents[$k]['id']==$this->allPage[$i]['id'])
								$this->LocalTarget[2]=$aParents[$k]['parent'];
						if(($this->allPage[$i]['parent']==$this->LocalTarget[2]||$this->LocalTarget[2]=='All')&&$this->allPage[$i]['parent']!=0){
							$cnt++;
							$arrId[]=$this->allPage[$i]['id'];
						}
					}
					$arrIsChild=$this->is_child_arr($arrId);
					$this->TempFillEls['items'] = Array();
					$cntNow=0;
					if(empty($subdomains)) $subdomains = $this->Db->SelectList('domain','subdomain',array('domain'));
					for($i=0;$i<$count;$i++){
						for($k=0;$k<$countParents;$k++)
							if($aParents[$k]['id']==$this->allPage[$i]['id'])
								$this->LocalTarget[2]=$aParents[$k]['parent'];
						$arrPath[$this->allPage[$i]['id']]=(!isset($arrPath[$this->allPage[$i]['parent']]))? $this->getPath($this->allPage[$i]['id'],$this->allPage): $arrPath[$this->allPage[$i]['parent']].'/'.$this->allPage[$i]['path'];
						if(($this->allPage[$i]['parent']==$this->LocalTarget[2]||$this->LocalTarget[2]=='All')&&$this->allPage[$i]['parent']!=0){
							$cntNow++;
							$status=number_format(((count($this->TempFillEls['items'])+1)/$cnt)*100,0);
							$lock=!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']!=$this->Action->Security->currentuser->id? true: false;
							$button='*';
							$lockLine= Array();
							if(!$lock){
								$button=(isset($arrIsChild[$this->allPage[$i]['id']])||$this->allPage[$i]['id']=='1'||$this->allPage[$i]['type']==3||$this->allPage[$i]['type']==6)? 'R': '';
								$button.=($this->allPage[$i]['is_describe']==0)? 'V':'';
								$button.=(!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']==$this->Action->Security->currentuser->id)? '':'U';
							}
							else {
								$lockLine['time']=$this->getTime($this->allPage[$i]['date_locked']);
								$lockLine['username']=$users[$this->allPage[$i]['access_flag']];
							}
							$publishServers = $this->Db->SelectAny('SELECT count(preset.id) AS count FROM preset WHERE preset.id IN (SELECT DISTINCT packagepublish.host FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.host = preset.id AND packagepublish.date_published > \''.$this->allPage[$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type IN (3, 9) AND packageitem.object = \''.$this->allPage[$i]['id'].'\'))');
							$publishServers = $publishServers[0]['count'];
							$level=(count(explode('/',$arrPath[$this->allPage[$i]['id']]))-2)*20;
							if($this->server_type!='dev') {
								$button='*';
								$lockLine = array();
							}
							if(preg_match("/^(\/subdomains)/i", $arrPath[$this->allPage[$i]['id']])) {
								$paths = explode('/',strtolower(preg_replace('/^\//i','',$arrPath[$this->allPage[$i]['id']])));
								array_shift($paths);
								if(in_array($paths[0],$subdomains)) {
									$this->allPage[$i]['sub'] = 1;
									$this->allPage[$i]['viewpath'] = 'http://'.(isset($REGISTRY['typedomain']) ? $REGISTRY['typedomain'].'.' : '').$paths[0].'.'.$signature['domain'][0].preg_replace('/^(\/subdomains\/'.$paths[0].')/i', '', $arrPath[$this->allPage[$i]['id']]);
								}
								else {
									$this->allPage[$i]['sub'] = 0;
									$this->allPage[$i]['viewpath'] = 'http://'.(isset($REGISTRY['typedomain']) ? $REGISTRY['typedomain'].'.' : '').$signature['domain'][0].$arrPath[$this->allPage[$i]['id']];
								}
							}
							else {
								$this->allPage[$i]['viewpath'] = 'http://'.(isset($REGISTRY['typedomain']) ? $REGISTRY['typedomain'].'.' : '').$signature['domain'][0].$arrPath[$this->allPage[$i]['id']];
								$this->allPage[$i]['sub'] = 0;
							}
							unset($paths);
							$this->TempFillEls['items'][$this->allPage[$i]['id']]=array(
								'pubBut' => 'hidden',//$this->server_type=='pro'? 'hidden' : 'visible',
								'funcName' => 'pageControler.addItem',
								'id' => $this->allPage[$i]['id'],
								'sort' => $this->allPage[$i]['sort_order'],
								'name' => $this->allPage[$i]['name'],
								'parent' => $this->allPage[$i]['parent'],
								'bullet' => (isset($arrIsChild[$this->allPage[$i]['id']]))? '_plus'.($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? ($this->allPage[$i]['sub']? '_black' : '') : '_home_page') : ($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? ($this->allPage[$i]['is_describe']==0? ($this->allPage[$i]['sub']? '_black' : '_green') : ($this->allPage[$i]['sub']? '_1a' : '')) : '_home_page'),
								'radioChecked' => $REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? '': 'checked',
								'radioDisabled' => ($this->allPage[$i]['is_describe']==0)?  'disabled':(!empty($lockLine)? 'disabled' : ''),
								'path' => $this->allPage[$i]['viewpath'],
								'level' => $level,
								'status' => $status,
								'all' => $cnt,
								'now' => $cntNow,
								'button' => $button,
								'hasServerInfo' => $publishServers ? 'true' : 'false',
								'lockLine' => (!empty($lockLine))? $lockLine['username'].'|'.$lockLine['time'] :'*',
								'is_child'=> isset($arrIsChild[$this->allPage[$i]['id']])? 'true':'false',
								'checkDisabled' => !empty($lockLine)? 'disabled' : '',
								'servers' => '['.$publishServers.'/'.$countServers.']',
								'colorServers' => $publishServers == 0 ? $this->colors['red'] : ($publishServers < $countServers ? $this->colors['blue'] : $this->colors['green']),
								'color' => $this->colors[$this->allPage[$i]['interval'] > 30? 'black' : ($this->allPage[$i]['interval'] > 14 && $this->allPage[$i]['interval'] <= 30? 'green' : ($this->allPage[$i]['interval'] > 7 && $this->allPage[$i]['interval'] <= 14? 'yellow' : 'red'))],
								'copyAbility' => $this->server_type == 'dev' && (empty($this->allPage[$i]['access_flag']) || $this->allPage[$i]['access_flag'] == $this->Action->Security->currentuser->id) ? '1' : '0',
							);
							$this->TempFillEls['itemsfunc'][0]='';
						}
					}
				}
			break;
			case 'getServerInfo':
				if(isset($this->LocalTarget[2]) && is_numeric($this->LocalTarget[2])){
					$date_changed = $this->Db->SelectAny('SELECT date_changed FROM module WHERE id = '.$this->LocalTarget[2]);
					$packagepublish = $this->Db->SelectAny('SELECT packagepublish.id, packagepublish.ownerid as package_id, packagepublish.host, packagepublish.userid, packagepublish.date_published FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.date_published > \''.$date_changed[0]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type IN (3, 9) AND packageitem.object = \''.$this->LocalTarget[2].'\') ORDER BY packagepublish.date_published DESC');
					$presets_unique = array();
					$c = count($packagepublish);
					if($c)
						$this->TempFillEls['serverInfo'][] = array(
							'funcName' => 'pageControler.addServerInfo',
							'idPage' => $this->LocalTarget[2],
							'package' => '<b>Package</b>',
							'serverName' => '<b>Host</b>',
							'userName' => '<b>User Name</b>',
							'time' => '<b>Date Published</b>',
							'hideServerInfoImg' => 'x',
						);
					for ($j = 0; $j < $c; $j++){
						if(isset($presets_unique[$packagepublish[$j]['host']])) continue;
						$presets_unique[$packagepublish[$j]['host']] = true;
						$package = $this->Db->SelectAny('SELECT name FROM package WHERE id = '.$packagepublish[$j]['package_id'].' LIMIT 1');
						$hostpath = $this->Db->SelectAny('SELECT name FROM preset WHERE id = '.$packagepublish[$j]['host'].' LIMIT 1');
						$username = $this->Db->SelectAny('SELECT username FROM member WHERE id = '.$packagepublish[$j]['userid'].' LIMIT 1');
						$this->TempFillEls['serverInfo'][] = array(
							'funcName' => 'pageControler.addServerInfo',
							'idPage' => $this->LocalTarget[2],
							'package' => '<a href="'.$this->Home.'/Registar/PackageManager/Look/'.$packagepublish[$j]['package_id'].'">['.$packagepublish[$j]['package_id'].']&nbsp;&nbsp;'.$package[0]['name'].'</a>',
							'serverName' => empty($hostpath) ? '<unknown>' : $hostpath[0]['name'],
							'userName' => empty($username) ? '<unknown>' : $username[0]['username'],
							'time' => $this->getTime($packagepublish[$j]['date_published']),
							'hideServerInfoImg' => '1',
						);
					}
					$this->TempFillEls['serverinfofunc'][0]['idPage'] = $this->LocalTarget[2];
				}
			break;
			default:break;
		}
	}

	function fillSort_(){
		$this->setArrayPage();
	}

	function fillSelect() {
		if($this->terminated) return;
		$this->TempFillEls['addBut'] = $this->server_type=='dev'? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = 'hidden' ;//$this->server_type=='pro'? 'hidden' : 'visible';
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) {
			$pagetypes = explode(',',$_COOKIE['pagetypes']);
		}
		else $pagetypes = array_keys($this->pagetypes);
		$this->TempFillEls['filter_count'] = count($pagetypes);
		$this->TempFillEls['filter_all'] = count($this->pagetypes);
		$this->TempFillEls['disabled'] = count($pagetypes)>0? '' : 'disabled';
		foreach($this->pagetypes as $key => $value) {
			$this->TempFillEls['pagetypes'][] = array(
				'check' => inputCheckbox('form[pagetype]['.$key.']',(in_array($key,$pagetypes)? TRUE : FALSE),'onclick="setPT(this)"'),
				'name' => $value,
			);
		}
		$this->setArrayPage();
	}

	function setArrayPage(){
		global $REGISTRY, $signature;
		$this->setPath();
//		$this->allPage = $this->Db->SelectAny('SELECT id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, (\'now\' - date_changed) AS interval, sort_order, controlid FROM module WHERE name != \'\' AND type in (1,6,8,9) ORDER BY parent, sort_order ASC');
		$this->allPage = $this->Db->SelectAny('SELECT id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, TIMESTAMPDIFF(day,date_changed,NOW()) AS \'interval\', sort_order, controlid FROM module WHERE name != \'\' AND type in (1,6,8,9) and id not in (1,20) ORDER BY parent, sort_order ASC');
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) $pagetypes = explode(',',$_COOKIE['pagetypes']);
		else $pagetypes = array_keys($this->pagetypes);
		$count = count($this->allPage);
		for($i = 0; $i < $count; $i++)
			if($this->allPage[$i]['is_describe'] && !in_array($this->allPage[$i]['controlid'], $pagetypes))
				unset($this->allPage[$i]);
		$this->allPage = array_values($this->allPage);
		$select_servers = $this->Db->SelectAny('SELECT path FROM preset');
		$hasCurServer = 'false';
		$countServers = count($select_servers);
		for($i = 0; $i < $countServers; $i++)
			if($select_servers[$i]['path'] == 'http://'.$_SERVER['HTTP_HOST'].'/')
				$hasCurServer = 'true';
		$users = $this->Db->SelectGuide('member g', array('g.id', 'g.username as name'), array(1 => 1));
		$pubBut = 'hidden' ;//$this->server_type == 'pro' ? 'hidden' : 'visible';
		$isDev = $this->server_type == 'dev' ? true : false;
		$count = count($this->allPage);
		$flagHP = false;
		for($i = 0; $i < $count; $i++) {
			$isHP = false;
			if($REGISTRY['HomeTarget'] == $this->allPage[$i]['id']){
				$flagHP = true;
				$isHP = true;
			}
			if(!empty($this->allPage[$i]['parent'])) continue;
			$publishServers = $this->Db->SelectAny('SELECT count(preset.id) AS count FROM preset WHERE preset.id IN (SELECT DISTINCT packagepublish.host FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.host = preset.id AND packagepublish.date_published > \''.$this->allPage[$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type IN (3, 9) AND packageitem.object = \''.$this->allPage[$i]['id'].'\'))');
			$publishServers = $publishServers[0]['count'];
			$is_child = $this->is_child($this->allPage[$i]['id']);
			$lock = empty($this->allPage[$i]['access_flag']) || $this->allPage[$i]['access_flag'] == $this->Action->Security->currentuser->id ? false : true;
			$this->TempFillEls['idFirstLevel'][] = Array('id' => $this->allPage[$i]['id']);
			if(preg_match("/^(subdomains)/i", $this->allPage[$i]['path']) && $this->allPage[$i]['type']==8) $this->allPage[$i]['sub'] = 1;
			else $this->allPage[$i]['sub'] = 0;
			$this->TempFillEls['pages'][$this->allPage[$i]['id']] = array(
				'funcName' => 'pageControler.addItem',
				'id' => $this->allPage[$i]['id'],
				'name' => $this->allPage[$i]['name'],
				'sort' => $this->allPage[$i]['sort_order'],
				'bullet' => $is_child? '_plus'.($isHP? '_home_page' : ($this->allPage[$i]['sub']? '_black' : '')) : ($isHP? '_home_page' : ($this->allPage[$i]['is_describe']==0? ($this->allPage[$i]['sub']? '_black' : '_green') : ($this->allPage[$i]['sub']? '_1a' : ''))),
				'radioChecked' => $isHP ? 'checked': '',
				'radioDisabled' => $this->allPage[$i]['is_describe'] == 0?  'disabled' : ($lock ? 'disabled' : ''),
				'path' => 'http://'.(isset($REGISTRY['typedomain'])? $REGISTRY['typedomain'].'.' : '').$signature['domain'][0].'/'.$this->allPage[$i]['path'],
				'bR'=> ($is_child || $this->allPage[$i]['id'] == 1 || $this->allPage[$i]['type'] == 3 || $this->allPage[$i]['type'] == 6 || $this->allPage[$i]['type'] == 8 || $this->allPage[$i]['type'] == 9 || $isHP) ? 'hidden': 'visible',
				'bV' => $this->allPage[$i]['is_describe'] == 0 || $this->allPage[$i]['type'] == 9? 'hidden' : 'visible',
				'bD' => $this->allPage[$i]['type']==8? 'hidden' : 'visible',
				'bD2' => $this->allPage[$i]['type']==9 || $this->allPage[$i]['type']==8? 'hidden' : 'visible',
				'bU' => (!empty($this->allPage[$i]['access_flag']) && $this->allPage[$i]['access_flag'] == $this->Action->Security->currentuser->id) ? 'visible':'hidden',
				'pubBut' => 'hidden' ,//$this->allPage[$i]['type'] == 8? 'hidden' : $pubBut,
				'countServers' => $countServers,
				'colorServers' => $publishServers == 0 ? $this->colors['red'] : ($publishServers < $countServers ? $this->colors['blue'] : $this->colors['green']),
				'publishServers' => $publishServers,
				'hasServerInfo' => $publishServers ? 'true' : 'false',
				'action' => $is_child ? 'getChild': '',
				'color' => $this->colors[$this->allPage[$i]['interval'] > 30? 'black' : ($this->allPage[$i]['interval'] > 14 && $this->allPage[$i]['interval'] <= 30? 'green' : ($this->allPage[$i]['interval'] > 7 && $this->allPage[$i]['interval'] <= 14? 'yellow' : 'red'))],
				'copy_ability' => $isDev && (empty($this->allPage[$i]['access_flag']) || $this->allPage[$i]['access_flag'] == $this->Action->Security->currentuser->id) && $this->allPage[$i]['type'] != 8 && $this->allPage[$i]['type'] != 9 ? '1' : '0',
			);
			if($is_child){
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['is_child'] = 'true';
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['cursor'] = 'pointer';
			}
			else $this->TempFillEls['pages'][$this->allPage[$i]['id']]['is_child'] = 'false';
			if($isDev){
				if($lock){
					$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayBut'] = 'none';
					$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayLockLine'] = 'block';
					$this->TempFillEls['pages'][$this->allPage[$i]['id']]['checkDisabled'] = 'disabled';
				}
				else{
					$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayBut'] = 'block';
					$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayLockLine'] = 'none';
				}
			}
			else{
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayBut'] = 'none';
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['displayLockLine'] = 'none';
			}
			if($lock){
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['time'] = $this->getTime($this->allPage[$i]['date_locked']);
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]['username'] = $users[$this->allPage[$i]['access_flag']];
			}
		}
		if($flagHP) $this->TempFillEls['idHomePage'][0] = Array('idHP' => $REGISTRY['HomeTarget']);
	}

	function getPath($id,$arr,$path=Array()){
		foreach($arr as $value){
			if($value['id']==$id){
				$path[]=$value['path'];
				return $this->getPath($value['parent'],$arr,$path);
			}
		}
		return '/'.implode('/',array_reverse($path));
	}

	function getTime($str){
		$time=explode('.',$str);
		return $time[0];
	}

	function is_child($parent){
		$count = count($this->allPage);
		for($i=0;$i < $count;$i++)
			if($this->allPage[$i]['parent']==$parent) return true;
		return false;
	}

	function is_child_arr($arr){
		$count = count($this->allPage);
		$count_id = count($arr);
		$res = Array();
		for($i=0;$i < $count;$i++)
			for($k=0;$k<$count_id;$k++)
				if($this->allPage[$i]['parent']==$arr[$k]) $res[$arr[$k]]=true;
		return $res;
	}

	function setTargetArray($array = array(),$level = 1,$levels = array(),$path = '') {
		$i = 0;
		if($level==1) {
			$this->servers_num = $this->Db->SelectAny("select count(*) from preset");
			if(!empty($this->servers_num)) $this->servers_num = $this->servers_num[0]['count'];
			else $this->servers_num = 0;
		}
		foreach($array as $value) {
			$levels[$level] = $i==sizeof($array)-1? 1 : 0;
			$color = $value['interval'] > 30? 'black' : ($value['interval'] > 14 && $value['interval'] <= 30? 'green' : ($value['interval'] > 7 && $value['interval'] <= 14? 'yellow' : 'red'));
			if($value['serverspub']['num'] > 0){
				$serv_alt = '<table cellpadding="0" cellspacing="1" style="display:inline;"><tr><td colspan=2><b>Published to Servers:</b></td></tr>';
				foreach ($value['serverspub'] as $k => $v)
					if(is_numeric($k)) $serv_alt .= '<tr><td width=140>'.$v['name'].'  </td><td width=160>'.$v['date'].' </td></tr>';
				$serv_alt .= '</table>';
			}
			else $serv_alt = '';
			$this->TempFillEls['pages'][$value['id']] = array(
				'id' => $value['id'],
				'dyn' => $value['is_describe']==2? '2' : '',
				'path' => $path.'/'.$value['path'].($value['is_describe']==2? '?'.$value['param_name'].'='.$value['param_value'] : ''),
				'name' => '<span style="color:'.$this->colors[$color].'">'.$value['name'].'</span>',
				'serv_alt' => $serv_alt,
				'servers_num' => '<span style="color:'.$value['serverspub']['color'].'; font-size:10px">['.$value['serverspub']['num'].' / '.$this->servers_num.']</span>',
				'width' => intval($level*20),
				'width2' => 376 - intval($level*20),
				'pub_disabled' => (!empty($value['access_flag']) && $value['access_flag'] != $this->Action->Security->currentuser->id) ? 'disabled' : '',
				'publish_name' => $value['name'],
				'start_div' => '<div id=page'.$value['id'].(!empty($this->pages[$value['id']])? ' style="display: none;"' : '').'>',
				'minus' => !empty($this->pages[$value['id']])? '_minus' : '',
				'View' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (!empty($value['is_describe'])? array(array('id' => $value['id'],'path' => $path.'/'.($value['is_describe']==2? '?'.$value['param_name'].'='.$value['param_value'] : $value['path']))) : array()),
				'Delete' => $value['type']==1 && $value['id']!=1? (!empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (empty($this->pages[$value['id']])? array(array('id' => $value['id'])) : array())) : array(),
				'noView' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (!empty($value['is_describe'])? array() : array(array())),
				'noDelete' => $value['type']==1 && $value['id']!=1? (!empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (empty($this->pages[$value['id']])? array() : array(array()))) : array(array()),
				'Locked' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array(array('username' => $value['username'],'date' => $value['date_locked'])) : array(),
				'is_lock' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : array(array('id' => $value['id'])),
				'UnLock' => !empty($value['access_flag']) && $value['access_flag']==$this->Action->Security->currentuser->id? array(array('id' => $value['id'])) : array(),
				'no_UnLock' => empty($value['access_flag']) || (!empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id)? array(array()) : array(),
			);
			if(!empty($this->pages[$value['id']])) {
				$this->TempFillEls['pages'][$value['id']]['header'] = array(array(
					'id' => $value['id'],
					'dyn' => $value['is_describe']==2? '2' : '',
					'path' => $path.'/'.$value['path'].($value['is_describe']==2? '?'.$value['param_name'].'='.$value['param_value'] : ''),
					'name' => '<span style="color:'.$this->colors[$color].'">'.$value['name'].'</span>',
					'serv_alt' => $serv_alt,
					'servers_num' => '<span style="color:'.$value['serverspub']['color'].'; font-size:10px">['.$value['serverspub']['num'].' / '.$this->servers_num.']</span>',
					'width' => intval($level*20),
					'width2' => 376 - intval($level*20),
					'publish_name' => $value['name'],
					'View' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (!empty($value['is_describe'])? array(array('id' => $value['id'],'path' => $path.'/'.($value['is_describe']==2? '?'.$value['param_name'].'='.$value['param_value'] : $value['path']))) : array()),
					'noView' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (!empty($value['is_describe'])? array() : array(array())),
					'Locked' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array(array('username' => $value['username'],'date' => $value['date_locked'])) : array(),
					'is_head_lock' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : array(array('id' => $value['id'])),
					'UnLock' => !empty($value['access_flag']) && $value['access_flag']==$this->Action->Security->currentuser->id? array(array('id' => $value['id'])) : array(),
					'no_UnLock' => empty($value['access_flag']) || (!empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id)? array(array()) : array(),
				));
				$this->TempFillEls['pages'][$value['id']]['onclick'] = array(array('id' => $value['id']));
				$this->setTargetArray($this->pages[$value['id']],$level+1,$levels,$path.'/'.$value['path']);
			}
			else {
				if($level==1) $this->TempFillEls['pages'][$value['id']]['end_div'] = '</div>';
				else $this->TempFillEls['pages'][$value['id']]['end_div'] = !empty($levels[$level])? (!empty($levels[$level-1])? (!empty($levels[$level-2])? str_repeat('</div>',4) : str_repeat('</div>',3)) : str_repeat('</div>',2)) : '</div>';
			}
			$i++;
		}
	}

	function sortingPages() {
		foreach($this->pages as $k => $v) {
			foreach($v as $key => $value) {
				$this->pages[$k][$key]['sort_order'] = intval($this->Request['form'][$value['id']]['sort_order1']);
			}
			uasort($this->pages[$k],'by_order');
			$i = 1;
			foreach($this->pages[$k] as $key => $value) {
				$this->Request['form'][$value['id']]['sort_order1']= $i*10;
				$this->Request['form'][$value['id']]['sort_order2']= $i*10;
				$i++;
			}
		}
	}

	function sortingPages_() {
		foreach($this->pages as $k => $v) {
			foreach($v as $key => $value) {
				if(isset($this->Request['form'][$value['id']]['sort_order1'])){
					$this->pages[$k][$key]['sort_order'] = intval($this->Request['form'][$value['id']]['sort_order1']);
				}
			}
			uasort($this->pages[$k],'by_order');
			$i = 1;
			foreach($this->pages[$k] as $key => $value) {
				$this->Request['form'][$value['id']]['sort_order1']= $i*10;
				$i++;
			}
		}
	}

	function setSortArray($array = array(),$level = 1,$levels = array(),$path = '') {
		$i = 0;
		foreach($array as $value) {
			$levels[$level] = $i == sizeof($array)-1? 1 : 0;
			$this->TempFillEls['pages'][$value['id']] = array(
				'id' => $value['id'],
				'path' => $path.'/'.$value['path'],
				'name' => $value['name'],
				'sort_order' => inputText('form['.$value['id'].'][sort_order1]',$value['sort_order'],5,'style="width:30px;" id=page'.$value['id'].' onchange="document.forms[0].elements[\'form['.$value['id'].'][sort_order2]\'].value = this.value"'),
				'width' => intval($level*20),
				'width2' => 462 - intval($level*20),
				'width3' => 520 - intval($level*20),
				'start_div' => '<div id=page'.$value['id'].(!empty($this->pages[$value['id']])? ' style="display: none;"' : '').'>',
				'minus' => !empty($this->pages[$value['id']])? '_minus' : '',
			);
			if(!empty($this->pages[$value['id']])) {
				$this->TempFillEls['pages'][$value['id']]['header'] = array(array(
					'id' => $value['id'],
					'path' => $path.'/'.$value['path'],
					'name' => $value['name'],
					'sort_order' => inputText('form['.$value['id'].'][sort_order2]',$value['sort_order'],5,'style="width:30px;" id=header'.$value['id'].' onchange="document.forms[0].elements[\'form['.$value['id'].'][sort_order1]\'].value = this.value"'),
					'width' => intval($level*20),
					'width2' => 462 - intval($level*20),
					'width3' => 520 - intval($level*20),
				));
				$this->TempFillEls['pages'][$value['id']]['onclick'] = array(array('id' => $value['id'],));
				$this->setSortArray($this->pages[$value['id']],$level+1,$levels,$path.'/'.$value['path']);
			}
			else {
				if($level==1) $this->TempFillEls['pages'][$value['id']]['end_div'] = '</div>';
				else $this->TempFillEls['pages'][$value['id']]['end_div'] = !empty($levels[$level])? (!empty($levels[$level-1])? (!empty($levels[$level-2])? str_repeat('</div>',4) : str_repeat('</div>',3)) : str_repeat('</div>',2)) : '</div>';
			}
			$i++;
		}
	}

	function setMenuArray($array = array(),$level = 0) {
		foreach($array as $value) {
			if($value['id']!=1) {
				$this->modules[$value['id']] = str_repeat(" - ",$level).$value['name'];
				if(!empty($this->pages[$value['id']])) $this->setMenuArray($this->pages[$value['id']],$level+2);
			}
		}
	}

	function setDefaultPageArray($array = array(),$level = 0) {
		foreach($array as $value) {
			if($value['type'] == 1 || $value['type'] == 8) {
				if($value['is_describe'] == 1)
					$this->default_page_array[$value['id']] = str_repeat(" - ", $level).$value['name'];
				else
					$this->default_page_array['dir'.$value['id']] = str_repeat(" - ", $level).$value['name'];
				if(!empty($this->pages[$value['id']]))
					$this->setDefaultPageArray($this->pages[$value['id']], $level + 2);
			}
		}
	}

	function setDynArray($array = array(),$level = 0) {
		foreach($array as $value) {
			if($value['is_describe']!=2) {
				$this->modules[$value['id']] = str_repeat(" - ",$level).$value['name'];
				if(!empty($this->pages[$value['id']])) $this->setDynArray($this->pages[$value['id']],$level+2);
			}
		}
	}

	function validateMenuArray($array = array(),$parent) {
		foreach($array as $value) {
			if($value['id']==$parent) return 1;
			if(!empty($this->pages[$value['id']])) $this->validateMenuArray($this->pages[$value['id']],$parent);
		}
		return 0;
	}

	function getContent($array,$type) {
		foreach($array as $key => $value)
			if($value['type']==$type) return $value['value'];
		return '';
	}

	function setLeftMenuArray($array = array(),$level = 1,$subitems = array()) {
		$i = 0;
		foreach($array as $key => $value) {
			$this->menu_id = $value['ownerid'];
			$this->TempFillEls['menu'][0]['items'][$key] = array(
				'id' => $key,
				'url' => $value['path']=='/'.implode('/',$this->LocalTarget)? trim($value['label']) : makeLink($value['path'],trim($value['label']),array(),$value['anchor'],($value['target']? 'target="_blank"' : 'target="_top"')),
				'width' => intval($level*12),
				'width2' => 150 - intval($level*12)-($level >= 1? 10 : 0),
				'arrow' => $level >= 1? array(array('number' => ($value['path']=='/'.implode('/',$this->LocalTarget)? '2' : '1'))) : array(),
				'not' => $value['path']=='/'.implode('/',$this->LocalTarget)? '' : 'not',
				'bgcolor' => $value['path']=='/'.implode('/',$this->LocalTarget)? '#CDE8F4' : '#BDD9E6',
				'select' => $value['path']=='/'.implode('/',$this->LocalTarget)? ($level >= 1? '_2' : '2') : ($level >= 1? '_' : ''),
				'css' => $level >= 1? 'style="padding-left:24px"' : '',
				'line' => $level < 1? array(array()) : ($i+1==count($array)? array(array()) : array()),
			);
			if(!empty($value['subcat'])) $this->setLeftMenuArray($value['subcat'],$level+1);
			$i++;
		}
	}

	function setTabsMenuArray($array = array(),$level = 1,$subitems = array()) {
		$i = 0;
		foreach($array as $key => $value) {
			$this->TempFillEls['items'][$key] = array(
				'id' => $key,
				'url' =>  isset($_POST['path'])&&$value['path']=='./'.$_POST['path']? trim($value['label']) : makeLink($value['path'],trim($value['label']),array(),$value['anchor'],($value['target']? 'target="_blank"' : 'target="_top"')),
				'not' => $value['path']=='/'.implode('/',$this->LocalTarget)? '' : 'class="active"',
				'select'=> isset($_POST['path'])&&$value['path']=='./'.$_POST['path']? '2' : '',
				'roll' => isset($_POST['path'])&& $value['path']=='./'.$_POST['path']? array() : array(array('id' => $key)),
				'roll_left' => isset($_POST['path'])&& $value['path']=='./'.$_POST['path']? array() : array(array('id' => $key)),
				'roll_right' => isset($_POST['path'])&& $value['path']=='./'.$_POST['path']? array() : array(array('id' => $key)),
			);
			$i++;
		}
	}

	function getRealUrl($id) {
		$selected = $this->Db->SelectArray('module',array('name','path','bc_parent'),array('id' => $id));
		foreach($selected as $value) {
			$this->entry[] = $value;
			if(!empty($value['bc_parent']) && $value['bc_parent']!=1) $this->getRealUrl($value['bc_parent']);
			else $this->entry[] = array('name' => 'Home','path' => '','bc_parent' => 0);
		}
	}

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

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

	function link_array($text) {
		global $REGISTRY;
		$text = preg_replace("~'~","\"",$text);
		$text = preg_replace("~&#39;~","\"",$text);
		$text = preg_replace("~&quot;~","\"",$text);
		$text = preg_replace("/%20/"," ",$text);
		$text = preg_replace("/<!--.*?-->/s"," ",$text);
		$text = preg_replace("/<style.*?\/style>/is",'',$text);
		$text_arr = explode('>',$text);
		$links_array = array();
		$rep_pattern = array(
			"/.*src[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*window\.open[\s]*\([\s]*\"([^\"]*)\".*/i",
			"/.*window\.location[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*document\.location[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*location\.href[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*location\.pathname[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*url[\s]*\([\s]*\"?[\s]*([^\"]*)\"?\).*/i",
			"/.*url[\s]*=[\s]*\"?[\s]*([^\"]*)\"?.*/i",
			"/.*href[\s]*=[\s]*\"([^\"]*)\".*/i",
		);
		$match_pattern = "/[href|window\.|location|url].*/i";
		foreach($text_arr as $text_row) {
			if(preg_match_all($match_pattern,$text_row,$l_arr)){
				foreach($l_arr as $l) {
					foreach($l as $l_row) {
						foreach($rep_pattern as $pattern) {
							$link = preg_replace($pattern,"$1",$l_row);
							if(strcmp($link,$l_row) != 0) {
								//print '<li>'.$link;
								//if(preg_match('/^(http|mailto|\.|\?)/i',$link)) continue;
								//print '<li>'.$link;
								$link = preg_replace('/#.*/','',$link);
								$link = trim(preg_replace("/\?.*/",'',$link));
								if(preg_match('/{.*}.*/',$link))
									foreach ($REGISTRY['Globals']['static'] as $key => $reg)
										if(is_string($reg)) $link = preg_replace('/{'.$key.':static}/i',$reg,$link);
								if($link!='' && !preg_match('/^[\?\/{]/',$link) && !preg_match('/^(http|mailto|\.|\?)/i',$link)) $link = '/'.$link;
								if($link != '' && $link != '#') $links_array[] = $link;
							}
						}
					}
				}
			}
		}
		return array_unique($links_array);
	}

	function clear_it($text){
		$text = preg_replace("/&#39;/","'",$text);
		$text = preg_replace("/%20/"," ",$text);
		$text = preg_replace("/<script.*?\/script>/is",'',$text);
		$text = preg_replace("/<style.*?\/style>/is",'',$text);
		$text = preg_replace('!</td>!i'," ",$text); # strip_tags bug
		$text = preg_replace('!<(div|br)[^>]*>!is'," ",$text); # div bug
		$text = strip_tags($text);
		$text = preg_replace("/&\w*;/", " ", $text);
		$text = preg_replace("/[\r|\n]/", ' ', $text);
		$text = preg_replace("/[[:space:]]+/", ' ', $text);
		$text = preg_replace("/{[^}]*}/",' ',$text);
		
		$text = preg_replace("/—/","-",$text);
		$text = preg_replace("/®/","&reg;",$text);
		return $text;
	}

	function setPath() {
		global $REGISTRY,$signature,$RequestBroker;
		$host = getenv('HTTP_HOST');
//		foreach($signature['domain'] as $value) $host = eregi_replace($value,'',$host);
		foreach($signature['domain'] as $value) $host = preg_replace('/('.$value.')/i','', $host);
		if(!empty($host)) {
			$domains = explode('.',$host);
			foreach($domains as $key => $value) if(empty($value)) unset($domains[$key]);
			if(in_array($domains[0],$RequestBroker->deny_urls)) $REGISTRY['typedomain'] = $domains[0];
		}
	}

	function path_sticker($id) {
		global $DatabaseBroker, $Paths;
		if(empty($Paths)) {
			$query = 'SELECT id, path, parent FROM module';
			$selected = $DatabaseBroker->SelectAny($query);
			foreach($selected as $value)
				$Paths[$value['id']] = array(
					'path' => $value['path'],
					'parent' => $value['parent'],
				);
		}
		$p = '';
		while(1){
			if(empty($Paths[$id])) return null;
			if(empty($Paths[$id]['parent'])) return '/'.$Paths[$id]['path'].$p;
			$p = '/'.$Paths[$id]['path'].$p;
			$id = $Paths[$id]['parent'];
		}
	}
}
?>