<?php

class DefaultPageView extends Slot {

	var $SectionID = 4;
	var $ModuleID = 4;
	var $pages = array();
	var $reqfield = '<img src="/i/must.gif">&nbsp;';
	var $check = array();

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

	function init() {
		global $TOOLS_PATH;
		$undo = 0;
		$this->Action->processEvent($this->SectionID,'select_pages',array(),$this);
		$this->pages = $this->PreparedTemplates;
		switch(@$this->LocalTarget[0]) {
			case 'Preview': $this->Scheme = 'preview'; 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 'ViewAll':
				if($this->server_type=='dev') {
					$request[1] = 10;
					$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/DefaultPage/ViewAll/'.$this->LocalTarget[1]);
						if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
					}
					$this->Scheme = 'viewall';
				}
				else $this->Scheme = 'default';
			break;
			case 'Update':
				if(!empty($this->LocalTarget[2]) && validate(intval($this->LocalTarget[2])) && $this->LocalTarget[1]=='Undo')
					$undo = 1;
				else $undo = 0;
				$array = array('id' => 10);
				if($undo == 1) $array['undo'] = $this->LocalTarget[2];
				$this->Action->processEvent($this->SectionID,'open_page',$array,$this);
				if(!empty($this->PreparedTemplates['_error'])) header('Location: '.$this->Home.'/Registar/DefaultPage'.$this->SID);
				else {
					$this->Action->processEvent($this->SectionID,'select_layouts',array(),$this);
					$this->full_layouts = $this->PreparedTemplates;
					$array = array('module' => 1,'item' => 10);
					if($undo == 1) $array['undo'] = $this->LocalTarget[2];
					$this->Action->processEvent($this->SectionID,'open_meta',$array,$this);
					$array = array('id' => 10);
					if($undo == 1) $array['undo'] = $this->LocalTarget[2];
					$this->Action->processEvent($this->SectionID,'get_mli',$array,$this);
					$this->Scheme = 'action';
				}
				$this->Scheme = 'default';
			break;
			default:header('Location: '.$this->Home.'/Registar/DefaultPage/Update'.$this->SID); break;
		}
		if(!empty($this->Request)) {
			if($this->server_type=='dev') {
				switch($this->getRequestField('step')) {
					case 'edit':
						$this->Request['form']['id_user']=$this->Action->Security->currentuser->id;
						if($undo ==1) $this->Request['form']['_undo_'] = $this->LocalTarget[1];
						$this->validateForm()
						and $this->Action->processEvent($this->SectionID,'save',$this->getRequestField('form'),$this)
						and header('Location: '.$this->Home.'/Registar/DefaultPage'.$this->SID);
					break;
					case 'unlock':
						$this->Request['form']['member'] = $this->Action->Security->currentuser->id;
						$this->Action->processEvent($this->SectionID,'unlock',$this->getRequestField('form'),$this)
						and header('Location: '.$this->Home.'/Registar/DefaultPage'.$this->SID);
					break;
				}
			}
			else header('Location: '.$this->Home.'/Registar/DefaultPage/Update'.$this->SID);
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function validateForm() {
		if(!is_AdvCleanText($this->getRequestFormField('sys_name'),2,512)) $this->errors['sys_name'] = 'Page\'s Name is empty or is not valid';
		if(!is_AdvCleanText($this->getRequestFormField('name'),2,512)) $this->errors['name'] = 'Page\'s Header is empty or is not valid';
		if(!is_AdvCleanText($this->getRequestFormField('comment'),5,4096)) $this->errors['comment'] = 'Comment is empty or is not valid';
		if(!is_AdvCleanText($this->Request['form']['meta']['title'],3,512)) $this->errors['title'] = 'Page\'s Title is empty or is not valid';
		if(!is_AdvCleanText($this->Request['form']['meta']['keywords'],3,512)) $this->errors['keywords'] = 'Page\'s Keywords is empty or is not valid';
		if(!is_AdvCleanText($this->Request['form']['meta']['description'],3,512)) $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(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']);
				$links.= implode(' ',$this->link_array($this->Request['form']['contents'][$key]['value'])).' ';
				$this->Request['form']['keywords'].= $this->clear_it($this->Request['form']['contents'][$key]['value']).' ';
			}
			$this->Request['form']['keywords'] = trim($this->Request['form']['keywords'].' __-__ '.$links);
			global $TOOLS_PATH;
			include($TOOLS_PATH.'\page_validator.inc');
			$error_array = page_validate($this->Request['form']['contents']);
			$this->errors['validate'] = '';
			foreach($error_array as $value) {
				if(!empty($value)) $this->errors['validate'].= $value;
			}
			if(!empty($this->errors['validate'])) return FALSE;
			else return TRUE;
		}
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'preview': $this->fillPreview(); break;
			case 'viewall': $this->fillViewAll(); break;
			case 'spellcheck': $this->fillSpellcheck(); break;
			case 'spellword': $this->fillSpellword(); break;
			case 'spelladd': $this->fillSpelladd(); break;
			default: case 'action': $this->fillAction(); break;
		}
	}

	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(),
			);
		}
	}

	function fillPreview() {
		global $REGISTRY, $CORE_PATH;
		if(!empty($this->Request) && !empty($this->Request['id'])) {
			$this->layouts = $this->Action->Server->getGuide('layout');
			$layout = $this->Db->SelectArray('layout','value',array('id' => $this->Request['id']));
			if(!empty($layout[0])) {
				$body = $layout[0]['value'];
				$body = eregi_replace('{rootPath:static}',$REGISTRY['Globals']['static']['rootPath'],$body);
				$body = eregi_replace('{picPath:static}',$REGISTRY['Globals']['static']['picPath'],$body);
				$body = eregi_replace('{homePath:static}',$REGISTRY['Globals']['static']['homePath'],$body);
				$body = eregi_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 = implode(' ',file($CORE_PATH.'\Templates\LeftMenuView\LeftMenuView.default.html'));
					$parser = new XTemplate($left_template);
					$els = &$parser->getElements();
					$this->setLeftMenuArray($this->leftmenu,0.1);
					$this->TempFillEls['describe'][] = array('value' => $left);
					$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 = implode(' ',file($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);
					$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 = implode(' ',file($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 = implode(' ',file($CORE_PATH.'\Templates\NavTabView\NavTabView.default.html'));
					$parser = new XTemplate($tabs_template);
					$els = &$parser->getElements();
					$this->setTabsMenuArray($this->tabsmenu,0.1);
					$navtab = $parser->parseTemplate($this->TempFillEls);
				}
				$navpanel = '';
				$meta = '<TITLE>'.$this->Request['title']."</TITLE>\n<meta name=\"keywords\" content=\"".$this->Request['keywords']."\">\n<meta name=\"description\" content=\"".$this->Request['description']."\">\n";
				$body = preg_replace('~{meta:virtual}~','<!-- START META -->'.$meta.'<!-- END META -->',$body);
				$body = preg_replace('~{top:virtual}~','<!-- START TOP -->'.$top.'<!-- END TOP -->',$body);
				$body = preg_replace('~{main:virtual}~','<!-- START MAIN -->'.$main.'<!-- END MAIN -->',$body);
				$body = preg_replace('~{image:virtual}~','<!-- START IMAGE -->'.$image.'<!-- END IMAGE -->',$body);
				$body = preg_replace('~{left:virtual}~','<!-- START LEFT -->'.$full_left.'<!-- END LEFT -->',$body);
				$body = preg_replace('~{right:virtual}~','<!-- START RIGHT -->'.$full_right.'<!-- END RIGHT -->',$body);
				$body = preg_replace('~{navtab:virtual}~','<!-- START NAVTAB -->'.$navtab.'<!-- END NAVTAB -->',$body);
				$body = preg_replace('~{bottom:virtual}~','<!-- START BOTTOM -->'.$full_bottom.'<!-- END BOTTOM -->',$body);
				$body = preg_replace('~{adminpanel:virtual}~','<!-- START ADMINPANEL --> <!-- END ADMINPANEL -->',$body);
				$body = preg_replace('~{jshead:virtual}~','<!-- START JSHEAD --> <!-- END JSHEAD -->',$body);
				$body = preg_replace('~{jsbody_before:virtual}~','<!-- START JSBODY_BEFORE --> <!-- END JSBODY_BEFORE -->',$body);
				$body = preg_replace('~{jsbody_after:virtual}~','<!-- START JSBODY_AFTER --> <!-- END JSBODY_AFTER -->',$body);
				$body = preg_replace('~{navpanel:virtual}~','<!-- START NAVPANEL -->'.$navpanel.'<!-- END NAVPANEL -->',$body);
				$body = preg_replace('~{leftS:static}~','{',$body);
				$this->TempFillEls['body'] = $body;
			}
		}
	}

	function fillAction() {
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		$start = '';
		$style = '';
		$select = '';
		$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++;
		}
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_meta');
		foreach($this->PreparedTemplates as $value) {
			switch($value['metatype']['id']) {
				case 1: $this->TempFillEls['title'] = $this->server_type=='dev'? inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : @$value['value']),80,1,'style="width:870px;"') : (!empty($this->Request)? $this->Request['form']['meta']['title'] : @$value['value']); break;
				case 2: $this->TempFillEls['description'] = $this->server_type=='dev'? inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : @$value['value']),80,3,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['meta']['description'] : @$value['value']); break;
				case 3: $this->TempFillEls['keywords'] = $this->server_type=='dev'? inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : @$value['value']),80,3,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['meta']['keywords'] : @$value['value']); break;
			}
		}
		$this->TempFillEls['addBut'] = $this->server_type=='dev'? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = $this->server_type=='pro'? 'hidden' : 'visible';
		if(!empty($this->LocalTarget[2]) && validate(intval($this->LocalTarget[2])) && $this->LocalTarget[1]=='Undo')
			$this->TempFillEls['undo'] = '(Undo v.'.$this->LocalTarget[2].')';
		empty($this->TempFillEls['title']) and $this->TempFillEls['title'] = $this->server_type=='dev'? inputTextArea('form[meta][title]',(!empty($this->Request)? $this->Request['form']['meta']['title'] : ''),80,1,'style="width:870px;"') : (!empty($this->Request)? $this->Request['form']['meta']['title'] : '');
		empty($this->TempFillEls['description']) and $this->TempFillEls['description'] = $this->server_type=='dev'? inputTextArea('form[meta][description]',(!empty($this->Request)? $this->Request['form']['meta']['description'] : ''),80,3,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['meta']['description'] : '');
		empty($this->TempFillEls['keywords']) and $this->TempFillEls['keywords'] = $this->server_type=='dev'? inputTextArea('form[meta][keywords]',(!empty($this->Request)? $this->Request['form']['meta']['keywords'] : ''),80,3,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['meta']['keywords'] : '');
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_page');
		$this->TempFillEls['is_describe'] = 1;
		$this->TempFillEls['step'] = 'edit';
		$this->TempFillEls['id'] = 10;
		$this->TempFillEls['type'] = $this->PreparedTemplates['type']['id'];
		$this->TempFillEls['page_type'] = 1;
		$this->TempFillEls['action'] = 'Save';
		$this->TempFillEls['sec_name'] = '" '.$this->PreparedTemplates['sys_name'].' "';
		$this->TempFillEls['sys_name'] = $this->server_type=='dev'? inputText('form[sys_name]',(!empty($this->Request)? $this->Request['form']['sys_name'] : @$this->PreparedTemplates['sys_name']),80,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['sys_name'] : @$this->PreparedTemplates['sys_name']);
		$this->TempFillEls['name'] = $this->server_type=='dev'? inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : @$this->PreparedTemplates['name']),80,'style="width:430px;"') : (!empty($this->Request)? $this->Request['form']['name'] : @$this->PreparedTemplates['name']);
		$i = 0;
		foreach($this->areatype as $key => $value) {
			$this->TempFillEls['contents'][$i] = array(
				'name' => ucfirst($value).' Area',
				'value' => inputTextArea('form[contents]['.$i.'][value]',(!empty($this->Request)? @$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;"'.($this->server_type!='dev'? ' readonly' : '')),
				'type' => inputHidden('form[contents]['.$i.'][type]',$key),
				'sort_order' => inputHidden('form[contents]['.$i.'][sort_order]',$i+1),
				'div' => $i,
				'buttons' => $this->server_type=='dev'? array(array('div' => $i,'templates' => $select)) : array(),
			);
			$i++;
		}
		$this->TempFillEls['textareaValidJS']='if(parseInt(document.getElementById("comment").value.length+"-")<5){
			//document.getElementById("comment").focus();
			alert("Comment is empty or is not valid");
			return false;
			}';
		$this->TempFillEls['ViewAllButton'] = $this->server_type=='dev'? '<input type="button" name="View_All" class=adminsubmit value="View All" onclick="open(\'/Registar/DefaultPage/ViewAll/'.$this->PreparedTemplates['id'].'\',\'displayWindow\',\'width=950,height=600,scrollbars=yes\');">' : '';
		$this->TempFillEls['textareaComment'] = $this->server_type=='dev'? '<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");
		//printArray($selected);
		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' => $this->server_type=='dev'? ($ind!=0 && file_exists($ROOT_PATH.'/undo/module/10/'.$val['version'].'.inc')? array(array('id' => 10,'version' => $val['version'])) : array()) : array(),
				);
			}
		}
		$this->TempFillEls['start']=$start;
		$this->TempFillEls['layout'] = $this->server_type=='dev'? 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)\"") : (!empty($this->Request)? $this->layouts[$this->Request['form']['layout']['id']] : $this->layouts[$this->PreparedTemplates['layout']['id']]);
		$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']==1? (isset($layout_init[$this->Request['form']['layout']['id']])? $layout_init[$this->Request['form']['layout']['id']] : 0) : 0) : ($this->PreparedTemplates['is_describe']==1? $layout_init[$this->PreparedTemplates['layout']['id']] : 0);
		$this->setMenuArray($this->pages[0],0);
		$this->TempFillEls['parent'] = inputHidden('form[parent][id]',0);
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'get_mli');
		//printArray($this->PreparedTemplates);
		$this->TempFillEls['bottommenu'] = $this->server_type=='dev'? inputSelect('form[menu][bottom]',mergeArrays(array('0' => ' ------- Select Bottom Menu ------- '),$this->bottommenu),(!empty($this->Request)? $this->Request['form']['menu']['bottom'] : $this->PreparedTemplates['bottom'])) : (!empty($this->Request)? $this->bottommenu[$this->Request['form']['menu']['bottom']] : @$this->bottommenu[$this->PreparedTemplates['bottom']]);
		$this->TempFillEls['leftmenu'] = $this->server_type=='dev'? inputSelect('form[menu][left]',mergeArrays(array('0' => ' ------- Select Left Menu ------- '),$this->leftmenu),(!empty($this->Request)? $this->Request['form']['menu']['left'] : $this->PreparedTemplates['left'])) : (!empty($this->Request)? $this->leftmenu[$this->Request['form']['menu']['left']] : @$this->leftmenu[$this->PreparedTemplates['left']]);
		$this->TempFillEls['rightmenu'] = $this->server_type=='dev'? inputSelect('form[menu][right]',mergeArrays(array('0' => ' ------- Select Right Menu ------- '),$this->rightmenu),(!empty($this->Request)? $this->Request['form']['menu']['right'] : $this->PreparedTemplates['right'])) : (!empty($this->Request)? $this->rightmenu[$this->Request['form']['menu']['right']] : @$this->rightmenu[$this->PreparedTemplates['right']]);
		$this->TempFillEls['tabsmenu'] = $this->server_type=='dev'? inputSelect('form[menu][tabs]',mergeArrays(array('0' => ' ------- Select Tabs Menu ------- '),$this->tabsmenu),(!empty($this->Request)? $this->Request['form']['menu']['tabs'] : $this->PreparedTemplates['tabs'])) : (!empty($this->Request)? $this->tabsmenu[$this->Request['form']['menu']['tabs']] : @$this->tabsmenu[$this->PreparedTemplates['tabs']]);
		$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->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,'save');
		$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->TempFillEls['prew'] = array(array());
		$this->TempFillEls['spell'] = array(array());
		$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
	}

	function fillSpelladd() {
		$word = @$this->LocalTarget[1];
		global $REGISTRY, $CORE_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:;',$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:;',$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 = implode(' ',file($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 = implode(' ',file($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 = implode(' ',file($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 = implode(' ',file($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 setTargetArray($array = array(),$level = 1,$levels = array(),$path = '') {
		$i = 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'));
			$this->TempFillEls['pages'][$value['id']] = array(
				'id' => $value['id'],
				'path' => $path.'/'.$value['path'],
				'name' => '<span style="color:'.$this->colors[$color].'">'.$value['name'].'</span>',
				'width' => intval($level*20),
				'width2' => 376 - 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' : '',
				'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['path'])) : array()),
				'Delete' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (empty($this->pages[$value['id']])? array(array('id' => $value['id'])) : array()),
				'noView' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (!empty($value['is_describe'])? array() : array(array())),
				'noDelete' => !empty($value['access_flag']) && $value['access_flag']!=$this->Action->Security->currentuser->id? array() : (empty($this->pages[$value['id']])? 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'],
					'path' => $path.'/'.$value['path'],
					'name' => '<span style="color:'.$this->colors[$color].'">'.$value['name'].'</span>',
					'width' => intval($level*20),
					'width2' => 376 - intval($level*20),
					'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['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 setMenuArray($array = array(),$level = 0) {
		foreach($array as $value) {
			$this->modules[$value['id']] = str_repeat(" - ",$level).$value['name'];
			if(!empty($this->pages[$value['id']])) $this->setMenuArray($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->TempFillEls['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',
			);
			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' => $value['path']=='/'.implode('/',$this->LocalTarget)? 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"',
			);
			$i++;
		}
	}
	
	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);
		return $text;
	}

}
?>