<?php
class Admin extends Controller
{
	var $collectionlangs = array('eng','hun','ita','ger');
	
	function Admin()
	{
		parent::Controller();
		
		if($this->uri->segment(2)=='login')
		{
			
		}
		else
		{
			if(isset($this->muser->user['admin']) && $this->muser->user['admin']===true)
			{
				$this->lang->load('admin', $this->muser->user['admin_lang']);
			}
			else
			{
				redirect(PREURL.'admin/login');
			}
		}
	}
	
	function login()
	{
		
		$lang = $this->uri->segment(3);
		
		if($lang == 'jap')
		{
			$this->muser->user['lang']='jap';
			
			unset($this->muser->user['admin']);
			unset($this->muser->user['admin_lang']);
			$this->phpsession->save('user',$this->muser->user);
			redirect('/admin/login');
		}
		elseif($lang == 'gr')
		{
			$this->muser->user['lang']='gr';
			
			unset($this->muser->user['admin']);
			unset($this->muser->user['admin_lang']);
			$this->phpsession->save('user',$this->muser->user);
			redirect('/admin/login');
		}
		elseif($lang == 'cr')
		{
			$this->muser->user['lang']='cr';
			
			unset($this->muser->user['admin']);
			unset($this->muser->user['admin_lang']);
			$this->phpsession->save('user',$this->muser->user);
			redirect('/admin/login');
		}
		elseif($lang == 'ita')
		{
			$this->muser->user['lang']='ita';
			
			unset($this->muser->user['admin']);
			unset($this->muser->user['admin_lang']);
			$this->phpsession->save('user',$this->muser->user);
			redirect('/admin/login');
		}
		
		
		$passwd = $this->input->post('passwd');
		if(!$passwd)
		{
			$data['admin']=true;
			$data['tartalom']='admin/login';
			$data['csik']=array('home','admin','adminlogin');
			$this->load->view('site',$data);
		}
		else
		{
			$accounts = $this->config->item('accounts');
			
			if(in_array($passwd,$accounts) && $accounts[$this->muser->user['lang']]==$passwd)
			{
				$this->muser->user['admin']=true;
				//$this->muser->user['admin_lang']=array_search($passwd,$this->config->item('accounts'));
				$this->muser->user['admin_lang'] = $this->muser->user['lang'];
				
				$this->phpsession->save('user',$this->muser->user);
				
				redirect(PREURL.'admin');
			}
			else
			{
				$data['error']='Hibás jelszó';
				$data['admin']=true;
				$data['tartalom']='admin/login';
				$data['csik']=array('home','admin','adminlogin');
				$this->load->view('site',$data);
			}
		}
	}
	
	function error_log()
	{
        $yesterday = date("Y-m-d", strtotime("-1 days"));
		if(file_exists('/home/cadline/public_html/website/system/logs/log-'.$yesterday.'.php'))
		{
            exec('mail -s "Log file for date: '.$yesterday.'" abartha84@gmail.com < /home/cadline/public_html/website/system/logs/log-'.$yesterday.'.php');
		}
		else
		{
            exec('echo "No log file!" | mail -s "Log file for date: '.$yesterday.'" abartha84@gmail.com');
		}
		
		redirect('admin');
	}
	
	function index()
	{
		$data['admin']=true;
		$data['title'] = 'ARCHLine.XP Admin';
		$data['tartalom']='admin/index';
		$data['csik']=array('home','admin');
		
		
		$num_dl_trial = $this->db->select("count(*) as c")->where('stat_version','trial')->get('download_stats')->row()->c;
		$num_dl_student = $this->db->select("count(*) as c")->where('stat_version','student')->get('download_stats')->row()->c;
		$sum = $num_dl_student + $num_dl_trial;
		$num_dl_interior = $this->db->select("count(*) as c")->where('stat_version','interior')->get('download_stats')->row()->c;
		$num_dl_free = $this->db->select("count(*) as c")->where('stat_version','free')->get('download_stats')->row()->c;
		
		$sum = $num_dl_student + $num_dl_trial + $num_dl_interior + $num_dl_free;
		$data['dl_trial_percent'] = floor(($num_dl_trial/$sum)*100);
		$data['dl_student_percent'] = floor(($num_dl_student/$sum)*100);
		$data['dl_interior_percent'] = floor(($num_dl_interior/$sum)*100);
		$data['dl_free_percent'] = floor(($num_dl_free/$sum)*100);
		
		
		$num_act_trial = $this->db->select("count(*) as c")->where('act_version','trial')->get('activations')->row()->c;
		$num_act_student = $this->db->select("count(*) as c")->where('act_version','student')->get('activations')->row()->c;
	//	$num_act_interior = $this->db->select("count(*) as c")->where('act_version','interior')->get('activations')->row()->c;
		$num_act_full = $this->db->select("count(*) as c")->where('act_version','full')->get('activations')->row()->c;
		
		$sum = $num_act_student + $num_act_trial + $num_act_full;
		$data['act_trial_percent'] = floor(($num_act_trial/$sum)*100);
		$data['act_student_percent'] = floor(($num_act_student/$sum)*100);
	//	$data['act_interior_percent'] = floor(($num_act_interior/$sum)*100);
		$data['act_full_percent'] = floor(($num_act_full/$sum)*100);
		
		// LT letöltés próba
		$this->load->helper('file');
		$data['lt_counter'] = read_file('lt_counter.txt');
		// vége
		
		
		$this->load->view('site',$data);
	}
	
	function act_stat()
	{
		$data['admin']=true;
		$data['tartalom']='admin/act_stat';
		$data['csik']=array('home','admin');

		$from = $this->uri->segment(3);
		if(!$from || !is_numeric($from))
		{
			$from = 0;
		}
		$this->load->library('pagination');
		
		$config['base_url'] = '/admin/act_stat2/';
		$config['total_rows'] = $this->db->select('count(*) as c')->get('activations')->row()->c;
		$config['per_page'] = '100'; 
		$config['full_tag_open'] = '<center>';
		$config['full_tag_close'] = '</center>';
		
		$config['last_link'] = 'Utolsó';
		$config['first_link'] = 'Első';
		
		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';
		
		$this->pagination->initialize($config); 
		
		$data['stats'] = $this->db->orderby('act_date','desc')->limit($config['per_page'],$from)->get('activations')->result();
		$this->load->view('site',$data);
	}
	
	function act_stat2()
	{
		$data['admin']=true;
		$data['tartalom']='admin/act_stat2';
		$data['csik']=array('home','admin');
		
		
		$from = $this->uri->segment(3);
		if(!$from || !is_numeric($from))
		{
			$from = 0;
		}
		$this->load->library('pagination');
		
		$config['base_url'] = '/admin/act_stat2/';
		$config['total_rows'] = $this->db->select('count(*) as c')->get('activations2')->row()->c;
		$config['per_page'] = '100'; 
		$config['full_tag_open'] = '<center>';
		$config['full_tag_close'] = '</center>';
		
		$config['last_link'] = 'Utolsó';
		$config['first_link'] = 'Első';
		
		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';
		
		$this->pagination->initialize($config); 
		
		$data['stats'] = $this->db->orderby('act_date','desc')->limit($config['per_page'],$from)->get('activations2')->result();
		
		$this->load->view('site',$data);
	}
	
	function promo_mail_stat()
	{
		$data['admin'] = true;
		$data['tartalom'] = 'admin/promo_mail_stat';
		$data['csik'] = array('home','admin');


		$from = $this->uri->segment(3);
		if(!$from || !is_numeric($from))
		{
			$from = 0;
		}
		$this->load->library('pagination');

		$config['base_url'] = '/admin/promo_mail_stat/';
		$config['total_rows'] = $this->db->select('count(*) as c')->get('promo_mail')->row()->c;
		$config['per_page'] = '100';
		$config['full_tag_open'] = '<center>';
		$config['full_tag_close'] = '</center>';

		$config['last_link'] = 'Utolsó';
		$config['first_link'] = 'Első';

		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';

		$this->pagination->initialize($config);

		//get the stats
		$data['stats'] = $this->db->orderby('date','desc')->limit($config['per_page'],$from)->get('promo_mail')->result();
		
		//get the mail types
		$data['types'] = $this->db->select('type')->distinct()->orderby('type', 'ASC')->get('promo_mail')->result();
		
		//get the count for each type
		foreach($data['types'] as $t)
		{
			$data['counts'][$t->type] = $this->db->select('COUNT(`id`) as count')->where('type', $t->type)->get('promo_mail')->result();
			$data['counts_dist'][$t->type] = $this->db->select('COUNT(DISTINCT(`email`)) as count_dist')->where('type', $t->type)->get('promo_mail')->result();
		}

		$this->load->view('site',$data);
	}
	
	function promo_iroda()
	{
		$strEmails = '';
		$strType = $this->uri->segment(3);
		
        $emailek = $this->db->select('DISTINCT(`email`)')->where('type', $strType)->get('promo_mail')->result();
        
        foreach($emailek as $e)
        {
			$strEmails .= $e->email . "\n";
        }
        
        $data = array('emailek' => $strEmails);
        
        echo $this->do_post_request('http://iroda/clusers_test/clusers/search_by_email_post', $data);
	}
	
	function do_post_request($url, $data, $optional_headers = null)
	{
		$params = array('http' => array(
								'method' => 'post',
								'content' => $data
								)
						);
						
		if($optional_headers!== null)
		{
			$params['http']['header'] = $optional_headers;
		}
		
		$ctx = stream_context_create($params);
		$fp = @fopen($url, 'rb', false, $ctx);

		if(!$fp)
		{
			throw new Exception("Problem with $url, $php_errormsg");
		}

		$response = @stream_get_contents($fp);

		if($response === false)
		{
			throw new Exception("Problem reading data from $url, $php_errormsg");
		}
		
		return $response;
	}
	
	function dl_stat()
	{
		$data['admin']=true;
		$data['tartalom']='admin/dl_stat';
		$data['csik']=array('home','admin');


		$from = $this->uri->segment(3);
		if(!$from || !is_numeric($from))
		{
			$from = 0;
		}
		$this->load->library('pagination');
		
		$config['base_url'] = '/admin/dl_stat/';
		$config['total_rows'] = $this->db->select('count(*) as c')->get('download_stats')->row()->c;
		$config['per_page'] = '100'; 
		$config['full_tag_open'] = '<center>';
		$config['full_tag_close'] = '</center>';
		
		$config['last_link'] = 'Utolsó';
		$config['first_link'] = 'Első';
		
		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';
		
		$this->pagination->initialize($config); 

		$data['ctrs'] = array('hun' => 'magyar', 'ita' => 'olasz', 'aus' => 'osztrák', 'che' => 'cseh', 'cro' => 'horvát', 'ger' => 'német', 'gre' => 'görög', 'jap' => 'japán', 'spa' => 'spanyol', 'kor' => 'koreai', 'pol' => 'lengyel', 'mex' => 'mexikói', 'ser' => 'szerb', 'ben' => 'benelux', 'uk' => 'angol');

		$data['stats'] = $this->db->orderby('stat_date','desc')->limit($config['per_page'],$from)->get('download_stats')->result();
		
		$this->load->view('site',$data);
	}
	
	function dl_stat_xls()
	{
		if($this->uri->segment(3))
		{
			$ctr = $this->uri->segment(3);
			
			switch($ctr)
			{
				case 'hun':
				    $ctr_where = "stat_country = 'Magyarország' OR stat_country = 'Hungary'";
				    break;
                case 'ita':
				    $ctr_where = "stat_country = 'Olaszország' OR stat_country = 'Italy'";
				    break;
                case 'aus':
				    $ctr_where = "stat_country = 'Ausztria' OR stat_country = 'Austria'";
				    break;
				case 'che':
				    $ctr_where = "stat_country = 'Csehország' OR stat_country = 'Czech Republic'";
				    break;
				case 'cro':
				    $ctr_where = "stat_country = 'Horvátország' OR stat_country = 'Croatia'";
				    break;
				case 'ger':
				    $ctr_where = "stat_country = 'Németország' OR stat_country = 'Germany'";
				    break;
				case 'gre':
				    $ctr_where = "stat_country = 'Görögország' OR stat_country = 'Greece'";
				    break;
				case 'jap':
				    $ctr_where = "stat_country = 'Japán' OR stat_country = 'Japan' OR stat_country = 'jap'";
				    break;
				case 'spa':
				    $ctr_where = "stat_country = 'Spanyolország' OR stat_country = 'Spain'";
				    break;
				case 'kor':
				    $ctr_where = "stat_country = 'Dél-Korea' OR stat_country = 'Korea, South'";
				    break;
				case 'pol':
				    $ctr_where = "stat_country = 'Lengyelország' OR stat_country = 'Poland'";
				    break;
				case 'mex':
				    $ctr_where = "stat_country = 'Mexikó' OR stat_country = 'Mexico'";
				    break;
				case 'ser':
				    $ctr_where = "stat_country = 'Szerbia' OR stat_country = 'Serbia'";
				    break;
				case 'ben':
				    $ctr_where = "stat_country = 'Hollandia' OR stat_country = 'Belgium' OR stat_country = 'Luxemburg' OR stat_country = 'Netherlands'";
				    break;
                case 'uk':
				    $ctr_where = "stat_country = 'United Kingdom' OR stat_country = 'Egyesült Királyság'";
				    break;
				default:
				    $ctr_where = "stat_country = ''";
				    break;
			}

            $stats = $this->db->orderby('stat_date','desc')->where('stat_email!=','0')->where($ctr_where)->get('download_stats')->result();

		}
		else
			$stats = $this->db->orderby('stat_date','desc')->where('stat_email!=','0')->where('stat_date>1325385015')->get('download_stats')->result();

		$this->load->library('Excel');
		
		$workbook = new Excel();
		
		//sending header and creating a worksheet
		$workbook->send('download_stat.xls');
		$workbook->setVersion(8);
		$worksheet =& $workbook->addWorksheet('Download Stats');

		//setting encoding
		$worksheet->setInputEncoding('UTF-8');

		//bold formating
		$fm_ttl =& $workbook->addFormat();
		$fm_ttl->setBold();
		$fm_ttl->setAlign('equal_space');
		
		//set the titles
		$worksheet->write(0, 0, 'Dátum', $fm_ttl);
		$worksheet->write(0, 1, 'Név', $fm_ttl);
		$worksheet->write(0, 2, 'Email', $fm_ttl);
		$worksheet->write(0, 3, 'Tel', $fm_ttl);
		$worksheet->write(0, 4, 'Ország', $fm_ttl);
		$worksheet->write(0, 5, 'Típus', $fm_ttl);
		
		//populate the worksheet
		$i = 1;
		foreach($stats as $s)
		{
			$worksheet->write($i, 0, date('Y-m-d',$s->stat_date));
			$worksheet->write($i, 1, $s->stat_first);
			$worksheet->write($i, 2, $s->stat_email);
			$worksheet->write($i, 3, $s->stat_tel);
			$worksheet->write($i, 4, $s->stat_country);
			$worksheet->write($i, 5, $s->stat_version);
            $i++;
		}

		$workbook->close();
	}
	
	
	function forum_xls()
	{
		$stats = $this->db->orderby('datum','desc')->where('nUserID IS NOT NULL')->where('datum IS NOT NULL')->where('szabaly!=','0')->get('`cadline2`.`forum_user`')->result();

		$this->load->library('Excel');
		
		$workbook = new Excel();
		
		//sending header and creating a worksheet
		$workbook->send('forum_belepok.xls');
		$workbook->setVersion(8);
		$worksheet =& $workbook->addWorksheet('Download Stats');

		//setting encoding
		$worksheet->setInputEncoding('UTF-8');

		//bold formating
		$fm_ttl =& $workbook->addFormat();
		$fm_ttl->setBold();
		$fm_ttl->setAlign('equal_space');
		
		//set the titles
		$worksheet->write(0, 0, 'Dátum', $fm_ttl);
		$worksheet->write(0, 1, 'Név', $fm_ttl);
		$worksheet->write(0, 2, 'Email', $fm_ttl);
		$worksheet->write(0, 3, 'nUserID', $fm_ttl);
		
		//populate the worksheet
		$i = 1;
		foreach($stats as $s)
		{
			$worksheet->write($i, 0, $s->datum);
			$worksheet->write($i, 1, $s->nev);
			$worksheet->write($i, 2, $s->email);
			$worksheet->write($i, 3, $s->nUserID);
            $i++;
		}

		$workbook->close();
	}
	
	
	function db_backup()
	{
		$this->load->helper('file');
		$this->load->library('zip');
		
		$name = 'db-backup-'.date("Y-m-d-H-i-s");
		
		file_exists("backup.sql") ? @unlink("backup.sql") : "";
		file_exists("backup.tgz") ? @unlink("backup.tgz") : "";
		
		exec("mysqldump -ucadline cadline2 > backup.sql");
		
		$this->zip->add_data($name.'.sql', read_file("backup.sql"));
		$this->zip->download($name.'.sql.zip');
		
		file_exists("backup.sql") ? @unlink("backup.sql") : "";
	}
	
	function services(){
		$data['flashinfok'] = $this->db->query("SELECT * FROM service_flash WHERE position > 0 ORDER BY service, position")->result();
		
		$data['admin']=true;
		$data['aktiv']=14;
		$data['tartalom']='admin/services';
		$data['csik']=array('home','admin');
		$data['javascript']=array('admin_settings');
		$this->load->view('site',$data);
	}
	
	function set_services(){
		$idk = $this->input->post('idk');
		$pozok = $this->input->post('poz');
		$fajlok = $this->input->post('fajl');
		$feltoltott_fajlok = $this->input->post('fajlfel');
		$mpk = $this->input->post('mp');
		$temak = $this->input->post('service');
		$delek = $this->input->post('del');
		
		foreach($idk as $id){
			$del = $delek[$id];
			if( $del == "on" ){
				$this->db->query("UPDATE service_flash SET position = 0 WHERE id = {$id}");
			}else{
				// új kép feltöltése ha van
				$this->kep2(&$fajlok[$id],'public/img/services/reel',$_FILES["fajlfel"],$id);
				
				$uj->position = $pozok[$id];
				$uj->filename = $fajlok[$id];
				$uj->runtime = $mpk[$id];
				$uj->service = $temak[$id];
				
				$this->db->update('service_flash',$uj,"id={$id}");
				//$this->mflashreel->edit($uj,$id);
			}
		}
		
		// ha van új, akkor beszúrjuk
		$uj_del = $this->input->post('uj_del');
		if( $uj_del != "on" ){
			$kep = $this->input->post('uj_fajl');
			
			// új kép feltöltése ha van
			$this->kep3(&$kep,'public/img/services/reel','uj_fajlfel');
			
			$uj->position = $this->input->post('uj_poz');
			$uj->filename = $kep;
			$uj->runtime = $this->input->post('uj_mp');
			$uj->service = $this->input->post('uj_service');
			
			$this->db->insert('service_flash',$uj);
			//$this->mflashreel->newrow($uj);
		}
		
		redirect('admin/services');
	}
	
	
	function settings()
	{
		$settings = $this->db->where('lang',$this->muser->user['lang'])->get('settings');
		if($settings->num_rows()==0)
		{
			$data['settings'] = false;
		}
		else
		{
			$data['settings'] = $settings->result();
		}
		
		$settings->free_result();
		
		$nyelv = $this->muser->user['admin_lang'];
		
		$foolaliinfok = $this->db->query("SELECT * FROM welcome_box WHERE (sorszam_2014>0 or sorszam_2014=-1) AND nyelv='{$nyelv}' ORDER BY sorszam_2014")->result();
		
		foreach($foolaliinfok as $doboz){
			$doboz->infok = $this->db->query("SELECT * FROM welcome_info WHERE doboz=".$doboz->id." AND (sorszam>0 or sorszam=-1) AND nyelv='{$nyelv}' ORDER BY sorszam")->result();
		}
		
		$data['fooldalinfok'] = $foolaliinfok;
		$data['info_json']    = json_encode($foolaliinfok);
		$data['info_fo_json'] = json_encode($this->db->query("SELECT * FROM welcome_info WHERE sorszam=200 AND nyelv='{$nyelv}' ORDER BY sorszam")->result());
		
		$kepek = $this->muser->get_welcome_img();
		$data['kepek'] = $kepek;
		
		$bannerek = $this->db->query("SELECT * FROM welcome_banner2 WHERE position>0 AND lang='{$nyelv}' ORDER BY position ASC")->result();
		$data['bannerek'] = $bannerek;
		
		$data['admin']=true;
		$data['aktiv']=9;
		$data['tartalom']  = 'admin/settings';
		$data['csik']      = array('home','admin');
		$data['javascript']= array('admin_settings', 'jquery_ui', 'ui.datepicker-hu');
		$data['style']     = array('jquery.ui');
		$this->load->view('site',$data);
	}
	
	function boxedit(){
		$id    = $this->input->post('id');
		$tomb['cim_2014']   = $this->input->post('cim_2014');
		$tomb['sorszam_2014'] = $this->input->post('sorszam_2014');
		
		// tartalom kép csere
		if( $_FILES["kep"]["error"]==0 ){
			include('application/helpers/sajatfeltolto.php');
			$hova  = "public/img/welcome/2014/";
			$ujkep = feltolt("kep",$hova,'icon_'.$_FILES["kep"]["name"],true);
			
			// átméretezés
			include('application/helpers/myimg_helper.php');
			kemeretezesvagassh($ujkep,$ujkep,41,41);
			chmod($ujkep,0777);
		}
			
		if( $ujkep ){
			$tomb['kep'] = basename($ujkep);
		}
		
		if($id == "uj"){
			$tomb['nyelv'] = $this->muser->user['admin_lang'];
			$this->db->insert('welcome_box',$tomb);
		}else{
			$this->db->update('welcome_box',$tomb,"id={$id}");
		}
		//$this->cache->delete('welcome-dobozok-'.$nyelv);
		//$this->cache->delete('foinfo-dobozok-'.$nyelv);
		
		redirect('admin/settings');
	}
	
	function delwelbox(){
		$id    = $this->uri->segment(3);
		$this->db->update('welcome_box',array('sorszam'=>0),"id={$id}");
		
		//$this->cache->delete('foinfo-dobozok-hun');
		//$this->cache->delete('foinfo-dobozok-eng');
		redirect('admin/settings');
	}
	
	function infoedit(){
		$i_id    = $this->input->post('info_id');
		$doboz   = $this->input->post('doboz');
		$sorszam = $this->input->post('sorszam');
		$cim     = $this->input->post('cim_2014');
		$info    = $this->input->post('info');
		$link    = $this->input->post('link');
		$link_cim= $this->input->post('link_cim');
		$ujkep   = "";
		
		$nyelv   = $this->muser->user['admin_lang'];
		
		$tomb = array(
				'doboz'  => $doboz,
				'sorszam'=> $sorszam,
				'cim_2014' => $cim,
				'info'   => $info,
				'link'   => $link,
				'link_cim'=> $link_cim
			);
		
		// tartalom kép csere
		if( $_FILES["kep"]["error"]==0 ){
			include('application/helpers/sajatfeltolto.php');
			$hova  = "public/img/welcome/{$nyelv}/";
			$ujkep = feltolt("kep",$hova,$_FILES["kep"]["name"],true);
			
			// átméretezés
			include('application/helpers/myimg_helper.php');
			kemeretezesvagassh($ujkep,$ujkep,110,60);
			chmod($ujkep,0777);
		}
			
		if( $ujkep ){
			$tomb['kep'] = $ujkep;
		}
		
		// tartalom szerkesztése
		if($i_id == "uj"){
			$tomb['nyelv'] = $nyelv;
			$this->db->insert('welcome_info',$tomb);
			$c_id = mysql_insert_id();
		}else{
			$this->db->update('welcome_info',$tomb,"info_id={$i_id}");
		}
		
		//$this->cache->delete('welcome-dobozok-'.$nyelv);
		//$this->cache->delete('foinfo-dobozok-'.$nyelv);
		
		redirect('admin/settings');
	}
	
	function foinfoedit(){
		$i_id    = $this->input->post('info_id');
		$cim     = $this->input->post('cim_2014');
		$info    = $this->input->post('info');
		$link    = $this->input->post('link');
		
		$tomb = array(
				'cim_2014' => $cim,
				'info'  => $info,
				'link'  => $link
			);
		$this->db->update('welcome_info',$tomb,"info_id={$i_id}");
		
		//$this->cache->delete('foinfo-dobozok-hun');
		//$this->cache->delete('foinfo-dobozok-eng');
		
		redirect('admin/settings');
	}
	
	function delwelinfo(){
		$i_id    = $this->uri->segment(3);
		$this->db->update('welcome_info',array('sorszam'=>0),"info_id={$i_id}");
		
		$this->cache->delete('foinfo-dobozok-hun');
		$this->cache->delete('foinfo-dobozok-eng');
		redirect('admin/settings');
	}
	
	function set_settings()
	{
		$mezonevek = $this->db->query('select name from settings where lang=\''.$this->muser->user['admin_lang'].'\'');
		foreach($mezonevek->result() as $mezo)
		{
			$value = mysql_real_escape_string($this->input->post($mezo->name));
			
			$this->db->update('settings',array('value'=>$value),"name='".$mezo->name."' and lang='".$this->muser->user['admin_lang']."'");
			
		}
		
		redirect('admin/settings');
		
	}
	
	function set_settings_img(){
		
		//flash adatok módosítása
		$this->load->model('mflashreel');
		$idk = $this->input->post('idk');
		$cimek = $this->input->post('title');
		$pozok = $this->input->post('poz');
		$fajlok = $this->input->post('fajl');
		$feltoltott_fajlok = $this->input->post('fajlfel');
		$linkek = $this->input->post('link');
		$startok = $this->input->post('start');
		$stopok = $this->input->post('stop');
		$delek = $this->input->post('del');
		
		foreach($idk as $id){
			unset($uj);
			$del = $delek[$id];
			if( $del == "on" ){
				$uj->position = 0;
				$this->db->update('welcome_banner2',$uj,'id='.$id);
			}else{
				// új kép feltöltése ha van
				$this->kep2(&$fajlok[$id],'public/img/banner405',$_FILES["fajlfel"],$id);
				
				$uj->title = $cimek[$id];
				$uj->position = $pozok[$id];
				$uj->filename = $fajlok[$id];
				$uj->link = $linkek[$id];
				$uj->start_date = strtotime($startok[$id]);
				$uj->stop_date = strtotime($stopok[$id]);
				
				$this->db->update('welcome_banner2',$uj,'id='.$id);
			}
		}
		
		// ha van új, akkor beszúrjuk
		$uj_del = $this->input->post('uj_del');
		if( $uj_del != "on" ){
			$kep = $this->input->post('uj_fajl');
			
			// új kép feltöltése ha van
			$this->kep3(&$kep,'public/img/banner405','uj_fajlfel');
			
			$uj->lang     = hun() ? "hun" : "eng";
			$uj->title    = $this->input->post('uj_title');
			$uj->position = $this->input->post('uj_poz');
			$uj->filename = $kep;
			$uj->title    = $this->input->post('uj_title');
			$uj->link     = $this->input->post('uj_link');
			$uj->start_date = strtotime($this->input->post('uj_start'));
			$uj->stop_date  = strtotime($this->input->post('uj_stop'));
			
			$this->db->insert('welcome_banner2',$uj);
		}
		
		redirect('admin/settings');
	}
	
	
	function set_settings_video(){
		// videók módosítása
		$videokdb = $this->input->post('videokdb');
		for($i=0;$i<$videokdb;$i++){
			$welvid_id = $this->input->post('vidwelvid_id'.$i);
			$sorszam = $this->input->post('vidsorszam'.$i);
			$youtubeid = $this->input->post('vidyoutube'.$i);
			$kep = $this->input->post('vidkep'.$i);
			$cim = $this->input->post('vidcim'.$i);
			$leiras = $this->input->post('vidleiras'.$i);
			$torles = $this->input->post('viddel'.$i);
			
			
			$kepuj = 'vidkep'.$i;
			
			if( $torles == "on" )
				$sorszam = 0;
			
			if(hun())
				$lang = "hun";
			else
				$lang = "eng";
			
			$utvonal = 'public/img/welcome/'.$lang;
			
			$this->kep3(&$kepuj,$utvonal,'vidkep'.$i);
			
			if( $kepuj != ('vidkep'.$i) ){
				$kep = $utvonal."/".$kepuj;
			}else{
				$kep = false;
			}
			
			if($welvid_id)
				$this->muser->set_settings_video($welvid_id, $sorszam, $youtubeid, $kep, $cim, $leiras);
			
		}
		
		
		// új videó
		$uj = $this->input->post('ujviddel');
		if( $uj != "on" ){
			$record->sorszam = $this->input->post('ujvidsorszam');
			$record->youtubeid = $this->input->post('ujvidyoutube');
		//	$record->kep = $this->input->post('ujvidkep');
			$record->cim = $this->input->post('ujvidcim');
			$record->leiras = $this->input->post('ujvidleiras');
			
			$kepuj = 'ujvidkep';
			
			if(hun())
				$lang = "hun";
			else
				$lang = "eng";
			
			$record->nyelv = $lang;
			
			$utvonal = 'public/img/welcome/'.$lang;
			
			$this->kep3(&$kepuj,$utvonal,'ujvidkep');
			
			if( $kepuj != '' ){
				$record->kep = $utvonal."/".$kepuj;
			}else{
		//		$record->kep = false;
			}
			
			
			//$this->muser->new_video($sorszam, $youtubeid, $kep, $cim, $leiras);
			$this->db->insert('`welcome_videos`',$record);
		}
		
		redirect("admin/settings");
	}
	
	
	function faq()
	{
		$this->load->model('mfaq');
	
		$data['latest_100']=$this->mfaq->get_latest(100,$this->muser->user['admin_lang'],true);
		$data['admin']=true;
		$data['aktiv']=4;
		$data['tartalom']='admin/faq';
		$data['csik']=array('home','admin');
		$this->load->view('site',$data);
	}
	
	function events()
	{
		$this->load->model('mevents');
	
		$data['events']=$this->mevents->get_latest(100,$this->muser->user['admin_lang'],true,false);
		$data['admin']=true;
		$data['aktiv']=7;
		$data['tartalom']='admin/events';
		$data['csik']=array('home','admin');
		$this->load->view('site',$data);
	}
    
    function events_new(){
        $this->load->model('mevents');
        
        $data['error'] = false;
        
        $do = $this->input->post('do');
        
        //esemény módosítása
        if($do && $do == 'modositas'){
            $post['datum'] = $this->input->post('datum');
            $post['ora_kezdet'] = $this->input->post('ora_kezdet');
            $post['ora_veg'] = $this->input->post('ora_veg');
            $post['perc_kezdet'] = $this->input->post('perc_kezdet');
            $post['perc_veg'] = $this->input->post('perc_veg');
            $post['event_limit'] = $this->input->post('event_limit');
            $post['active'] = $this->input->post('active');
            $post['nev'] = $this->input->post('nev');
            $post['event_id'] = $this->input->post('event_id');
            $post['event_main_id'] = $this->input->post('event_main_id');
            
            if($error = $this->mevents->modifyEvent($post)){
                $data['error'] = $error;
            }
        }
        
        //új esemény rögzítése
        if($do && $do == 'rogzites'){
            $post['datum'] = $this->input->post('datum');
            $post['ora_kezdet'] = $this->input->post('ora_kezdet');
            $post['ora_veg'] = $this->input->post('ora_veg');
            $post['perc_kezdet'] = $this->input->post('perc_kezdet');
            $post['perc_veg'] = $this->input->post('perc_veg');
            $post['event_limit'] = $this->input->post('event_limit');
            $post['active'] = $this->input->post('active');
            $post['nev'] = $this->input->post('nev');
            $post['event_main_id'] = $this->input->post('event_main_id');
            
            if($error = $this->mevents->createEvent($post)){
                $data['error'] = $error;
            }
        }
        
        //főesemény módosítása
        if($do && $do == 'modositas_main'){
            $config['upload_path'] = '/home/cadline/public_html/website/public/upload/eng/image/events/banner/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '1000';
            $config['overwrite'] = true;
            
            $this->load->library('upload', $config);
            
            if(isset($_FILES, $_FILES['kep']['name']) && $_FILES['kep']['name'] != ''){
                if(!$this->upload->do_upload('kep')){
            	   $data['error'] = $this->upload->display_errors('<p>', '</p>');
                } else {
                    $kep = $this->upload->file_name;
                }
            } else {
                $kep = $this->input->post('kep_eredeti');
            }
            
            $config['upload_path'] = '/home/cadline/public_html/website/public/upload/eng/image/events/banner/thumbs/';
            $config['allowed_types'] = 'gif|jpg|png|swf';
            $config['max_size'] = '1000';
            $config['overwrite'] = true;
            
            $this->upload->initialize($config);
            
            if(isset($_FILES, $_FILES['thumb']['name']) && $_FILES['thumb']['name'] != ''){
                if(!$this->upload->do_upload('thumb')){
            	   $data['error'] = $this->upload->display_errors('<p>', '</p>');
                } else {
                    $thumb = $this->upload->file_name;
                }
            } else {
                $thumb = $this->input->post('thumb_eredeti');
            }
			
			for($i=1;$i<5;$i++){
				if( isset($_FILES['kiskep'.$i]) &&  $_FILES['kiskep'.$i]["error"]==0 ){
					if(!$this->upload->do_upload('kiskep'.$i)){
						$data['error'] = $this->upload->display_errors('<p>', '</p>');
					} else {
						$kisk = 'elokep'.$i;
						$$kisk =$this->upload->file_name;
						
						// lekicsinyitett valtozat letrehozasa
						$helye = substr($config['upload_path'],0,-1);
						$mibol = $config['upload_path'].$kisk;
						include('application/helpers/myimg_helper.php');
						kepmeretezesvagas($mibol,$helye,"elo_".$kisk,130,65);
					}
				} else {
					$kisk = 'elokep'.$i;
					$$kisk = $this->input->post('kiskep_eredeti'.$i);
				}
			}
			
			if( isset($_FILES['kozepkep']) && $_FILES['kozepkep']["error"]==0 ){
				if(!$this->upload->do_upload('kozepkep')){
					$data['error'] = $this->upload->display_errors('<p>', '</p>');
				} else {
					$kozepkep ='public/upload/eng/image/events/banner/thumbs/'.$this->upload->file_name;
				}
			} else {
				$kozepkep = $this->input->post('kozepkep_eredeti');
			}
			
			
			if(!$data['error']){
				$post = array(
					'event_main_id'     => $this->input->post('event_main_id'),
					'nev'               => $this->input->post('nev'),
					'leiras'            => substr($this->input->post('leiras'), 0, 500),
					'kep'               => $kep,
					'thumb'             => $thumb,
					'weboldal'          => $this->input->post('weboldal'),
					'archline_oldal'    => $this->input->post('archline_oldal'),
					'sikeres_reg_oldal' => $this->input->post('sikeres_reg_oldal'),
					'sikeres_reg_mail'  => $this->input->post('sikeres_reg_mail'),
					'reg_torles_oldal'  => $this->input->post('reg_torles_oldal'),
					'datum_kezdet'      => $this->input->post('datum_kezdet'),
					'ora_kezdet'        => $this->input->post('ora_kezdet'),
					'perc_kezdet'       => $this->input->post('perc_kezdet'),
					'datum_veg'         => $this->input->post('datum_veg'),
					'ora_veg'           => $this->input->post('ora_veg'),
					'perc_veg'          => $this->input->post('perc_veg'),
					'limit'             => $this->input->post('event_main_limit'),
					'active'            => $this->input->post('active'),
					'event_view_id'     => $this->input->post('event_view_id'),
					
					'rss'               => $this->input->post('rss'),
					
					'elokep1'           => $elokep1,
					'elokep2'           => $elokep2,
					'elokep3'           => $elokep3,
					'elokep4'           => $elokep4,
					'kozepkep'          => $kozepkep,
					'shorttext'         => $this->input->post('rovid_oldal')
				);
				
				if($error = $this->mevents->modifyMainEvent($post)){
					$data['error'] = $error;
				}
			}
		}
		
		//új főesemény létrehozása
		if($do && $do == 'rogzites_main'){
			$config['upload_path'] = '/home/cadline/public_html/website/public/upload/eng/image/events/banner/';
			$config['allowed_types'] = 'gif|jpg|png|swf';
			$config['max_size'] = '1000';
			$config['overwrite'] = true;
			
			$this->load->library('upload', $config);
			
			if(isset($_FILES, $_FILES['kep']['name']) && $_FILES['kep']['name'] != ''){
				if(!$this->upload->do_upload('kep')){
            	   $data['error'] = $this->upload->display_errors('<p>', '</p>');
                } else {
                    $kep = $this->upload->file_name;
                }
            } else {
                $kep = '';
            }
            
            $config['upload_path'] = '/home/cadline/public_html/website/public/upload/eng/image/events/banner/thumbs/';
            $config['allowed_types'] = 'gif|jpg|png|swf';
            $config['max_size'] = '1000';
            $config['overwrite'] = true;
            
            $this->upload->initialize($config);
            
            if(isset($_FILES, $_FILES['thumb']['name']) && $_FILES['thumb']['name'] != ''){
                if(!$this->upload->do_upload('thumb')){
            	   $data['error'] = $this->upload->display_errors('<p>', '</p>');
                } else {
                    $thumb = $this->upload->file_name;
                }
            } else {
                $thumb = '';
            }
            
            if(!$data['error']){
                $post = array(
                    'nev'               => $this->input->post('nev'),
                    'leiras'            => substr($this->input->post('leiras'), 0, 500),
                    'kep'               => $kep,
                    'thumb'             => $thumb,
                    'weboldal'          => $this->input->post('weboldal'),
                    'archline_oldal'    => $this->input->post('archline_oldal'),
                    'sikeres_reg_oldal' => $this->input->post('sikeres_reg_oldal'),
                    'sikeres_reg_mail'  => $this->input->post('sikeres_reg_mail'),
                    'reg_torles_oldal'  => $this->input->post('reg_torles_oldal'),
                    'datum_kezdet'      => $this->input->post('datum_kezdet'),
                    'ora_kezdet'        => $this->input->post('ora_kezdet'),
                    'perc_kezdet'       => $this->input->post('perc_kezdet'),
                    'datum_veg'         => $this->input->post('datum_veg'),
                    'ora_veg'           => $this->input->post('ora_veg'),
                    'perc_veg'          => $this->input->post('perc_veg'),
                    'limit'             => $this->input->post('event_main_limit'),
                    'active'            => $this->input->post('active'),
                    'lang'              => $this->muser->user['admin_lang'],
                    'event_view_id'     => $this->input->post('event_view_id'),
                    
                    'rss_date'          => time(),
                    'rss'               => $this->input->post('rss')
                );
                
                if($error = $this->mevents->createMainEvent($post)){
                    $data['error'] = $error;
                }
            }
        }
        
        //collecting pages
        $this->load->model('mpages');
        
        if(hun()){
            $category = 'események';
        } else {
            $category = 'events';
        }
        
        $data['event_pages'] = $this->mpages->get_category_pages($category, $this->muser->user['admin_lang'], true, 'page_title', 'asc');
        
        //collecting events
        $main_events = $this->mevents->getMainEvents($this->muser->user['admin_lang']);
        
        //creating json for the javascript
        
        
        foreach($main_events as $main_event){
            $main_event->events_list = $this->mevents->getEvents($main_event->event_main_id);
            
            $main_event->urlname = $this->db->query("SELECT urlname FROM events_new_main WHERE event_main_id = ".$main_event->event_main_id)->row()->urlname;
            
            $elokepek = $this->mevents->getEventImages($main_event->event_main_id);
            
            for($i=1;$i<5;$i++){
            	$qaf = "elokep".$i;
            	$main_event->$qaf = $elokepek->$qaf;
            }
            $main_event->kozepkep = $elokepek->kozepkep;
            $main_event->shorttext = $elokepek->shorttext;
            
            if($main_event->events_list){
                foreach($main_event->events_list as $event){
                    $event->reg_list = $this->mevents->getRegistrations($event->event_id);
                }
            }
        }
        
        $data['main_events_json'] = json_encode($main_events);
        
		$data['main_events'] = $main_events;
        
        //collecting event view types
        $event_views = $this->mevents->getEventViews();
        
        $data['event_views'] = $event_views;
        
		$data['admin'] = true;
		$data['aktiv'] = 10;
		$data['tartalom'] = 'admin/events_new/index';
		$data['csik'] = array('home', 'admin');
        $data['javascript'] = array('jquery_ui', 'ui.datepicker-hu', 'jquery.numeric.pack');
        $data['style'] = array('jquery.ui');
        
		$this->load->view('site',$data);
    }
    
    function events_new_event_delete(){
        $this->load->model('mevents');
        
        $event_id = $this->uri->segment(3);
        
        if($event_id){
            $this->mevents->deleteEventByID($event_id);
			$this->cache->delete('archline-klub-idopontok');
        }
        
        redirect('admin/workshop');
    }
    
    function events_new_main_event_delete(){
        $this->load->model('mevents');
        
        $event_main_id = $this->uri->segment(3);
        
        if($event_main_id){
            $this->mevents->deleteMainEventByID($event_main_id);
        }
        
        redirect('admin/workshop');
    }
    
    function events_new_reg_delete(){
        $this->load->model('mevents');
        
        $reg_id = $this->uri->segment(3);
        
        if($reg_id && $reg_details = $this->mevents->getRegistrationDetails($reg_id)){
            
            //set the email's content and...
            $event_main_details = $this->mevents->getMainEventDetails($reg_details->event_main_id);
            
            $page = $this->mpages->get_row($event_main_details->reg_delete_page);
            
            //send the email
            $this->load->library('email');
            $this->email->initialize();
            $this->email->setFrom('info@archlinexp.com', 'CadLine');
			$this->email->subject($page->page_title);
			$this->email->message($page->page_body);
			
			$this->email->send($reg_details->reg_email, 'smtp');
            
            //delete registration
            $this->mevents->deleteRegistrationByID($reg_id);
			
			if($reg_details->event_main_id==56)
				$this->cache->delete('archline-klub-idopontok');
        }
        
        redirect('admin/workshop');
    }
    
    function faqedit()
	{
		$this->load->model('mfaq');
		
		$faq_id = $this->uri->segment(3);
		
		if(!is_numeric($faq_id) && $faq_id != 'new')
		{
			show_error('Hibás azonosító: '.$faq_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($faq_id =='new')
			{
				$record = $this->mdb->set_empty_object('faq');
				$record->faq_id = $faq_id;
			}
			else
			{
				$record = $this->mfaq->get_row($faq_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$faq_id);
				}
			}
			
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=4;
			$data['tartalom']='admin/faqedit';
			$data['csik']=array('home','admin');
			
			
			
			$types = $this->config->item('faq_types');
			foreach($types as $type)
			{
				$data['types'][$type]=$this->lang->line('faq_cat_'.$type);
			}
			
			
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			$record = $this->mdb->set_post_object('faq');
			
			$record->faq_lang = $this->muser->user['admin_lang'];
			$record->faq_date = time();
			
			if ($record->faq_id == 'new')
			{
				unset($record->faq_id);
				$this->db->insert('faq',$record);
			}
			else
			{
				unset($record->faq_count);
				$this->db->update('faq',$record,'faq_id='.$record->faq_id);
				
			}
		
			redirect('admin/faq');
		
		}
	}
	
	function eventsedit()
	{
		$this->load->model('mevents');
		
		$event_id = $this->uri->segment(3);
		
		if(!is_numeric($event_id) && $event_id != 'new')
		{
			show_error('Hibás azonosító: '.$event_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($event_id =='new')
			{
				$record = $this->mdb->set_empty_object('events');
				$record->event_id = $event_id;
				
				$record->event_ev = $this->mevents->ev;
				$record->event_ho = $this->mevents->ho;
				$record->event_nap = $this->mevents->nap;
				
			}
			else
			{
				$record = $this->mevents->get_row($event_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$event_id);
				}
			}
			
			
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=7;
			$data['tartalom']='admin/eventsedit';
			$data['csik']=array('home','admin');
			
			
			
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			$record = $this->mdb->set_post_object('events');
			
			$record->event_title = str_replace('_','&nbsp;',$record->event_title);
			
			$record->event_title = trim($record->event_title);
			
			$record->event_lang = $this->muser->user['admin_lang'];
			
			$record->event_stamp = mktime(0,0,0,$record->event_ho,$record->event_nap+1,$record->event_ev);
			
			if ($record->event_id == 'new')
			{
				unset($record->event_id);
				$this->db->insert('events',$record);
			}
			else
			{
				$this->db->update('events',$record,'event_id='.$record->event_id);
			}
			
			
			
			// többi frissítése
			
			$this->db->update('events',array('event_text'=>$record->event_text),"event_title='".$record->event_title."'");
			
		
			redirect('admin/events');
		
		}
	}
	
	
	function events2sedit()
	{
		$this->load->model('mevents');
		
		$event_id = $this->uri->segment(3);
		
		if(!is_numeric($event_id) && $event_id != 'new')
		{
			show_error('Hibás azonosító: '.$event_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($event_id =='new')
			{
				$record = $this->mdb->set_empty_object('events2');
				$record->event_id = $event_id;
			}
			else
			{
				$record = $this->mevents->get_row2($event_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$event_id);
				}
			}
			
			
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=4;
			$data['tartalom']='admin/eventsedit';
			$data['csik']=array('home','admin');
			
			
			
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			$record = $this->mdb->set_post_object('events');
			
			$record->event_lang = $this->muser->user['admin_lang'];
			
			$record->event_stamp = mktime(0,0,0,$record->event_ho,$record->event_nap+1,$record->event_ev);
			
			if ($record->event_id == 'new')
			{
				unset($record->event_id);
				$this->db->f('events',$record);
			}
			else
			{
				$this->db->update('events',$record,'event_id='.$record->event_id);
			}
		
			redirect('admin/events');
		
		}
	}
	
	
	function faqdelete()
	{
		$faq_id = $this->uri->segment(3);
		
		if(!$faq_id ||!is_numeric($faq_id))
		{
			show_404();
		}
		
		$this->db->delete('faq','faq_id='.$faq_id,1);
		
		redirect('admin/faq');
	}
	
	function eventsdelete()
	{
		$event_id = $this->uri->segment(3);
		
		if(!$event_id ||!is_numeric($event_id))
		{
			show_404();
		}
		
		$this->db->delete('events','event_id='.$event_id,1);
		
		redirect('admin/events');
	}
	
	
	
	function japanCSV()
	{
		if(jap())
		{
			$q = $this->db->where('stat_version','3months')->orwhere('stat_version','japtrial')->orderby('stat_date','desc')->get('download_stats');
			if($q->num_rows()==0)
			{
				die('No data avaiable for CSV Creation (no downloads)');
			}
			else
			{
				$data = 'Date;E-Mail;Name;Pronounciation;Company;Address;Telephone;FAX;Version;AutoCAD;VectorWorks;ArchiCAD;JWCAD;ARCHITREND;GoogleSketchup;DRACAD;SuperSoft;Other;Opinion';
				
				foreach($q->result() as $sor)
				{
					$date = date("Y-m-d",$sor->stat_date);
					
					$data.="\n".$date.';'.$sor->stat_email.';'.$sor->stat_first.';'.$sor->stat_pron.';'.$sor->stat_company.';'.$sor->stat_cim.';'.$sor->stat_tel.';'.$sor->stat_fax.';'.$sor->stat_version.';'.$sor->stat_ucAUC.';'.$sor->stat_ucARC.';'.$sor->stat_ucVEW.';'.$sor->stat_ucJWC.';'.$sor->stat_ucART.';'.$sor->stat_ucGSK.';'.$sor->stat_ucDRC.';'.$sor->stat_ucSSO.';'.$sor->stat_ucELS.';'.$sor->stat_opinion;
				}
				
				header("Content-type: application/octet-stream");
				header("Content-Disposition: attachment; filename=\"download-stats.csv\"");

				echo $data;
			}
		}
	}
	
	function news()
	{
		$this->load->model('mnews');
		$lang = $this->muser->user['admin_lang'];
		
	//	$data['latest_100']=$this->mnews->get_latest(100,$this->muser->user['admin_lang']);
		
		// hírek
		$data['latest_100']=$this->db->query("SELECT *, DATE(CONCAT(news_y,'/',news_m,'/',news_d)) as ujdatum  FROM `news` WHERE news_lang='{$lang}' order by ujdatum DESC")->result();
		
		
		// hírlevelek
		$parancs = " (SELECT *, substr(video,26,11) vidazon, 0 keptipus FROM newsletter WHERE `deleted` = 0 AND lang = '{$lang}' AND video LIKE '%youtube.com%') ";
		$parancs .= " UNION ";
		$parancs .= " (SELECT *, video vidazon, 1 keptipus FROM newsletter WHERE `deleted` = 0 AND lang = '{$lang}' AND (video NOT LIKE '%youtube.com%' OR video IS NULL) ) ";
		$parancs .= " ORDER BY title";
		//print $parancs;
		$data['hirlevelek'] = $this->db->query($parancs)->result();
		
		foreach($data['hirlevelek'] as $level){
			$szoveg = $level->text;
			/*$tmpv = */preg_match("/(<p class=\"nl-cim-belso\"><strong>).+(<\/strong><\/p>)/",$level->text,$tmpv);
			$level->alcim = substr($tmpv[0],32);
			$level->alcim = substr($level->alcim,0,-13);
			$rizsa = explode($tmpv[0],$level->text);
			$level->szoveg = $rizsa[1];
		}
		
		$data['hirlevelek_json'] = json_encode($data['hirlevelek']);



// 2014.06.05. F.Zs.
      $data['napitippek']=$this->db->query("SELECT t.*, IF(LOCATE('youtube.com',t.`video`)>0,substr(t.`video`,26,11),`video`) AS vidazon, IF(LOCATE('youtube.com',t.`video`)>0,0,1) keptipus FROM tipoftheday t WHERE t.`deleted` = 0 AND t.`lang`='{$lang}';")->result();
		foreach($data['napitippek'] as $level){
			$szoveg = $level->text;
			preg_match("/(<p class=\"nl-cim-belso\"><strong>).+(<\/strong><\/p>)/",$level->text,$tmpv);
			$level->alcim = substr($tmpv[0],32);
			$level->alcim = substr($level->alcim,0,-13);
			$rizsa = explode($tmpv[0],$level->text);
			$level->szoveg = $rizsa[1];
		}
		$data['napitippek_json'] = json_encode($data['napitippek']);
// 2014.06.05. F.Zs.


		
		// követési linkek
		$old_db = hun() ? 'clusers' : 'clusers_eng';
		$field  = hun() ? 'strTopic' : 'strTopic_Eng';
		$data['linkek']      = $this->db->query("SELECT * FROM followed_links WHERE lang='{$lang}' AND `show`=1 ORDER BY name ASC")->result();
		$data['json_linkek'] = json_encode($data['linkek']);
		$data['crmtopics']   = $this->db->query("SELECT nTopicID, {$field} as topicnev FROM `cl_hlusers`.`u_topic` WHERE old_db='{$old_db}' ORDER BY topicnev ASC")->result();
		
		
		$data['javascript'] = array('jquery_ui','plugin/jquery.maskedinput-1.2.2','plugin/jquery.maskedinput-1.2.2.min');
		$data['style'] = array('jquery.ui');
		
		$data['admin']=true;
		$data['aktiv']=2;
		$data['tartalom']='admin/news';
		$data['csik']=array('home','admin');
		$this->load->view('site',$data);
	}
	
	function set_nl(){
		$nl_id = $this->input->post('nl_id');
		$hirlevel['title'] = $this->input->post('title');
		if( $this->input->post('baltipus') == "mappa")
			$hirlevel['video'] = $this->input->post('video');
		else
			$hirlevel['video'] = "http://www.youtube.com/v/".$this->input->post('video')."?version=3&amp;hl=hu_HU&amp;rel=0";
		//$hirlevel['text'] = $this->input->post('leiras');
		$hirlevel['text'] = "<p class=\"nl-cim-belso\"><strong>".$this->input->post('subtitle')."</strong></p>".$this->input->post('leiras');
		$hirlevel['link'] = $this->input->post('link');
		
		if( $this->input->post('baltipus') == "kep" && isset($_FILES, $_FILES['kep']['name']) && $_FILES['kep']['name'] != '' ){
			include('application/helpers/sajatfeltolto.php');
			
			//$kepurl = "public/img/newsletter/";
			move_uploaded_file($_FILES["kep"]["tmp_name"], "public/img/newsletter/" . $_FILES["kep"]["name"]);
		//	$kepurl = feltolt('kep',"public/img/newsletter/",$_FILES[$asd]['name'],true);
			$kepurl = "public/img/newsletter/".$_FILES["kep"]["name"];
			
			$hirlevel['video'] = $kepurl;
		}elseif( $this->input->post('baltipus') == "kep" ){
			unset($hirlevel['video']);
		}
		
		
		if(!$nl_id){
			$subject = str_replace(' ','-',strtolower($this->input->post('url')));
			$pattern = '/[-_a-z0-9]*/';
			preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
			$url = "";
			foreach($matches[0] as $m)
				if($m[0])
					$url .= $m[0];
			
			
			$hirlevel['lang'] = $this->muser->user['admin_lang'];
			$hirlevel['deleted'] = '0';
			$hirlevel['url'] = $url;
			$this->db->insert('newsletter',$hirlevel);
			
			$azonhossz = strlen($url);
			
			// Twitter bejegyzés
			require_once('application/plugins/Twitter-PHP/twitter.class.php');
			require_once('application/plugins/Twitter-PHP/OAuth.php');
			if(hun()){
				$msg = "Hírlevél: ".substr($hirlevel['title'],0,(140-53-$azonhossz))." (http://www.archline.hu/newsletter/show/".$url.")";
				
				require_once('application/plugins/codebird-php-2.4.1/src/codebird.php');
				$cb = \Codebird\Codebird::getInstance();
				$reply = $cb->statuses_update('status='.$msg);
				redirect("admin/news");
				exit;
				
				/*$consumerKey       = 'y550xIIROlUYS0TubCqAJA';
				$consumerSecret    = 'sWHuS8TevjHopNeSCf73AeX6JUT1B3e1ma1zF810I';
				$accessToken       = '136217633-6MIHowRunalfGoUHUoMd53MtgGqtXCO36vtxEWAL';
				$accessTokenSecret = 'KNGkVbV8cTqY9DlSj61neMNJYgdexL90WXSpEgqwmw';
				*/
				
			}else{
				$consumerKey       = 'DWj2LuQIRRTgu9Qxk23VLQ';
				$consumerSecret    = 'GbFeFwO5u3y9rt059ecHvBRwsrquz8v3qu4x0W9Uxwg';
				$accessToken       = '121794123-a5fJS7pIA4q70vEP4deT41lm0NsTfsXqR3EaTrno';
				$accessTokenSecret = 'RKQnfiQrrklBxN0imwGTn6BPuwq1IJqHuQN2iQ0ms';
				
				$msg = "Newsletter: ".substr($hirlevel['title'],0,(140-58-$azonhossz))." (http://www.archlinexp.com/newsletter/show/".$url.")";
				
				$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
				$status = $twitter->send($msg);
				// End Twitter bejegyzés
			}
			redirect("admin/news");
			
		}else{
			$this->db->update('newsletter',$hirlevel,"nl_id = '".$nl_id."'");
		}
		
		redirect("admin/news");
	}
	
	function del_nl(){
		$nl_id = $this->uri->segment(3);
		
		$this->db->update('newsletter',array('deleted'=>'1'),"nl_id = '".$nl_id."'");
		redirect('admin/news');
	}



// 2014.06.06. F.Zs.
	function set_nt(){
		$nl_id = $this->input->post('nl_id');
		$hirlevel['title'] = $this->input->post('title');
		$hirlevel['video'] = ($this->input->post('baltipus') == "kep" ? $this->input->post('kep2') : "http://www.youtube.com/v/".$this->input->post('video')."?version=3&amp;hl=hu_HU&amp;rel=0");                                
		$hirlevel['text']  = "<p class=\"nl-cim-belso\"><strong>".$this->input->post('subtitle')."</strong></p>".$this->input->post('leiras');
		$hirlevel['link']  = $this->input->post('link');
		
		if( $this->input->post('baltipus')=="kep" && isset($_FILES, $_FILES['kep']['name']) && $_FILES['kep']['name']!='')
      {
/*
			include('application/helpers/sajatfeltolto.php');
			$hirlevel['video'] = "/public/img/tipoftheday/".$_FILES["kep"]["name"];
			move_uploaded_file($_FILES["kep"]["tmp_name"], $hirlevel['video']);
*/
         include('application/helpers/sajatfeltolto.php');
			move_uploaded_file($_FILES["kep"]["tmp_name"], "public/img/tipoftheday/".$_FILES["kep"]["name"]);
			$hirlevel['video'] = "/public/img/tipoftheday/".$_FILES["kep"]["name"];
		}
		
		if(!$nl_id){
			$subject = str_replace(' ','-',strtolower($this->input->post('url')));
			$pattern = '/[-_a-z0-9]*/';
			preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);

			$url = "";
			foreach($matches[0] as $m) if($m[0]) $url .= $m[0];
			
			$hirlevel['lang'] = $this->muser->user['admin_lang'];
			$hirlevel['deleted'] = '0';
			$hirlevel['url'] = $url;
			
			$this->db->insert('tipoftheday',$hirlevel);
			
			$azonhossz = strlen($url);

/*
			// Twitter bejegyzés
			require_once('application/plugins/Twitter-PHP/twitter.class.php');
			require_once('application/plugins/Twitter-PHP/OAuth.php');
			if(hun()){
				$msg = "Hírlevél: ".substr($hirlevel['title'],0,(140-53-$azonhossz))." (http://www.archline.hu/newsletter/show/".$url.")";
				
				require_once('application/plugins/codebird-php-2.4.1/src/codebird.php');
				$cb = \Codebird\Codebird::getInstance();
				$reply = $cb->statuses_update('status='.$msg);
				redirect("admin/news");
				exit;
				
//				$consumerKey       = 'y550xIIROlUYS0TubCqAJA';
//				$consumerSecret    = 'sWHuS8TevjHopNeSCf73AeX6JUT1B3e1ma1zF810I';
//				$accessToken       = '136217633-6MIHowRunalfGoUHUoMd53MtgGqtXCO36vtxEWAL';
//				$accessTokenSecret = 'KNGkVbV8cTqY9DlSj61neMNJYgdexL90WXSpEgqwmw';
				
			}else{
				$consumerKey       = 'DWj2LuQIRRTgu9Qxk23VLQ';
				$consumerSecret    = 'GbFeFwO5u3y9rt059ecHvBRwsrquz8v3qu4x0W9Uxwg';
				$accessToken       = '121794123-a5fJS7pIA4q70vEP4deT41lm0NsTfsXqR3EaTrno';
				$accessTokenSecret = 'RKQnfiQrrklBxN0imwGTn6BPuwq1IJqHuQN2iQ0ms';
				
				$msg = "Newsletter: ".substr($hirlevel['title'],0,(140-58-$azonhossz))." (http://www.archlinexp.com/newsletter/show/".$url.")";
				
				$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
				$status = $twitter->send($msg);
				// End Twitter bejegyzés
			}
*/			
			redirect("admin/news");
			
		}
      else
      {
			$this->db->update('tipoftheday',$hirlevel,"nl_id = '".$nl_id."'");
		}
		redirect("admin/news");
	}
	
	function del_nt(){
		$this->db->update('tipoftheday',array('deleted'=>'1'),"nl_id = '".$this->uri->segment(3)."'");
		redirect('admin/news');
	}
// 2014.06.06. F.Zs.
	
	
	
	function set_followlink(){
		$id = $this->input->post('id');
		if(!is_numeric($id) && $id!="new")
			return;
		
		$tomb = array();
		$tomb['name']      = $this->input->post('name');
		$tomb['esem_id']   = $this->input->post('esem_id');
		$tomb['esem_cont'] = $this->input->post('esem_cont');
		$tomb['redirect']  = $this->input->post('redirect');
		
		if($id=="new"){
			$tomb['lang']  = $this->muser->user['admin_lang'];
			
			$subject = str_replace(' ','-',strtolower($this->input->post('alias')));
			$pattern = '/[-_a-z0-9]*/';
			preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
			$alias = "";
			foreach($matches[0] as $m)
				if($m[0])
					$alias .= $m[0];
			
			if(!$alias){
				print "Hibas url azonosito: ".$this->input->post('alias');
				return;
			}
			
			$tomb['alias'] = $alias;
			$this->db->insert('followed_links',$tomb);
		}
		else{
			$this->db->update('followed_links',$tomb,"id = {$id}");
		}
		
		redirect('admin/news');
	}
	
	function del_followlink(){
		$id = $this->uri->segment(3);
		if(!is_numeric($id))
			return;
		
		$this->db->update('followed_links',array('show'=>0),"id = {$id}");
		
		redirect('admin/news');
	}
	
	function editor(){
		$this->load->model('mpages');
	
		$data['list']=$this->mpages->get_latest(1000,$this->muser->user['admin_lang']);
		
        $sort = $this->uri->segment(3);
        
        if(!$sort){
            $sort = 'page_date';
        }
        
		$data['by_category']=$this->mpages->get_all_by_category($sort,"0");
		$data['admin']=true;
		$data['aktiv']=6;
		$data['tartalom']='admin/editor';
		$data['csik']=array('home','admin');
		$this->load->view('site',$data);
	}
	
	function pageedit()
	{
		$this->load->model('mpages');
		
		$page_id = $this->uri->segment(3);
		
		if(!is_numeric($page_id) && $page_id != 'new')
		{
			show_error('Hibás azonosító: '.$page_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($page_id =='new')
			{
				$record = $this->mdb->set_empty_object('pages');
				$record->page_id = $page_id;
			}
			else
			{
				$record = $this->mpages->get_row($page_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$page_id);
				}
			}
			
			$data['cat']=$this->mpages->get_category_dropdown();
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=6;
			$data['tartalom']='admin/pageedit';
			$data['javascript']='../ckeditor/ckeditor';
			$data['csik']=array('home','admin');
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			$record = $this->mdb->set_post_object('pages');
			
			$record->page_lang = $this->muser->user['admin_lang'];
			
			$record->page_date = time();
			
			unset($record->page_url);
			
			if ($record->page_id == 'new')
			{
				unset($record->page_id);
				$this->db->insert('pages',$record);
			}
			else
			{
				$this->db->update('pages',$record,'page_id='.$record->page_id);
			}
		
			redirect('admin/editor');
		
		}
	}
	
    function pageedit_help()
	{
        if(!hun())
            redirect('admin/editor');
        
        $this->load->model('mpages');
		
		$page_id = $this->uri->segment(3);
		
		if(!is_numeric($page_id) && $page_id != 'new')
		{
			show_error('Hibás azonosító: '.$page_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($page_id =='new')
			{
				$record = $this->mdb->set_empty_object('pages');
				$record->page_id = $page_id;
			}
			else
			{
				$record = $this->mpages->get_row($page_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$page_id);
				}
			}
			
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=6;
			$data['tartalom']='admin/pageedit_help';
			$data['csik']=array('home','admin');
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
            die(print_r($this->input->post('page_body')));
			$record = $this->mdb->set_post_object('pages');
			
			$record->page_lang = $this->muser->user['admin_lang'];
			
			$record->page_date = time();
			
			if ($record->page_id == 'new')
			{
				unset($record->page_id);
				$this->db->insert('pages',$record);
			}
			else
			{
				$this->db->update('pages',$record,'page_id='.$record->page_id);
			}
		
			redirect('admin/editor');
		
		}
	}
    
	function logout()
	{
		$this->muser->user['admin']=false;
		$this->phpsession->save('user',$this->muser->user);
		
		redirect();
		
	}
	
	function banner()
	{
		$do = $this->input->post('do');
		
		if($do)
		{
			if($_FILES['banner']['name'])
			{
				$config['upload_path'] = 'public/upload/'.$this->muser->user['admin_lang'];
				$config['allowed_types'] = 'gif|jpg|png|swf';
				$config['max_size']	= '1000';
				$config['max_width']  = '2048';
				$config['max_height']  = '2048';
				
				$this->load->library('upload', $config);
			
				if ( ! $this->upload->do_upload('banner'))
				{
					show_error($this->upload->display_errors());
				}	
				else
				{
					$file = $this->upload->data();
					
					$path = 'public/upload/'.$this->muser->user['admin_lang'].'/'.$file['file_name'];
					$this->muser->set_setting('banner','/'.$path,$this->muser->user['admin_lang']);
					
					
					if(substr_count($file['file_name'],'.swf')!=0)
					{
						$config['image_library'] = 'gd2';
						$config['source_image'] = $path;
						$config['maintain_ratio'] = TRUE;
						$config['width'] = 648;
						$config['height'] = 648;
						
						$this->load->library('image_lib', $config);
						
						$this->image_lib->resize();
						
						$is_flash = false;
					}
					else
					{
						$is_flash = true;
					}
					
					
				}
				
				
				
			}
			
			$page = $this->input->post('page');
			if($page == 'none')
			{
				$this->muser->set_setting('banner_link',$this->input->post('banner_link'),$this->muser->user['admin_lang']);
			}
			else
			{
				$this->muser->set_setting('banner_link',$page,$this->muser->user['admin_lang']);
			}
			
			
				redirect('admin/banner');
			
		}
		else
		{
			$data['admin']=true;
			$data['tartalom']='admin/banner';
			$data['csik']=array('home','admin');
			$data['aktiv']=5;
			
			$data['banner']=$this->muser->get_setting('banner',$this->muser->user['admin_lang']);
			$data['banner_link']=$this->muser->get_setting('banner_link',$this->muser->user['admin_lang']);
			
			if($data['banner_link']=='')
			{
				$data['banner_link']='http://';
			}
			
			if($data['banner'])
			{
				$file = substr($data['banner'],1);
				if(is_file($file))
				{
					$data['file'] = $file;
				}
				else
				{
					$data['file'] = false;
				}
			}
			else
			{
				$data['file'] = false;
			}
			
			$this->load->view('site',$data);
		}
	}
	
	function newsedit()
	{
		$this->load->model('mnews');
		
		$news_id = $this->uri->segment(3);
		
		if(!is_numeric($news_id) && $news_id != 'new')
		{
			show_error('Hibás azonosító: '.$news_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($news_id =='new')
			{
				$record = $this->mdb->set_empty_object('news');
				$record->news_id = $news_id;
			
				$record->news_y = date('Y');
				$record->news_m = date('m');
				$record->news_d = date('d');
				
				// alap keret angolhoz
				if( !hun() ){
					$recordtemp = $this->mnews->get_row(135);
					$record->news_text = $recordtemp->news_text;
				}
				
			}
			else
			{
				$record = $this->mnews->get_row($news_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$news_id);
				}
			}

			$data['cat']=$this->mnews->get_category_dropdown();
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=2;
			$data['tartalom']='admin/newsedit';
			$data['csik']=array('home','admin');
			$this->load->view('site',$data);
			
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			
			$record = $this->mdb->set_post_object('news');
			
			$record->news_lang = $this->muser->user['admin_lang'];
			
			if ($record->news_id == 'new')
			{
				if($this->input->post('news_url')=="")
					print "Hiba: Nem volt kitöltve az url!";
				unset($record->news_id);
				$subject = str_replace(' ','-',strtolower($this->input->post('news_url')));
				$pattern = '/[-_a-z0-9]*/';
				preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
				$url = "";
				foreach($matches[0] as $m)
					if($m[0])
						$url .= $m[0];
				$record->url = $url;
				unset($record->news_url);
				$this->db->insert('news',$record);
				
				$ujid = mysql_insert_id();
				
				// Ha nem volt sikeres a beszúrás kilépés.
				if( !$ujid ){
					print "Az új hír felvétele sikertelen!";
					exit;
				}
				
				if( $url )
					$new_id = $url;
				else
					$new_id = $ujid;
				
				// Twitter bejegyzés
				require_once('application/plugins/Twitter-PHP/twitter.class.php');
				require_once('application/plugins/Twitter-PHP/OAuth.php');
				if(hun()){
					$msg = "Új hír: ".substr($record->news_title,0,85)." (http://www.archline.hu/news/show/".$new_id.")";
					require_once('application/plugins/codebird-php-2.4.1/src/codebird.php');
					$cb = \Codebird\Codebird::getInstance();
					$reply = $cb->statuses_update('status='.$msg);
					/*$consumerKey       = 'y550xIIROlUYS0TubCqAJA';
					$consumerSecret    = 'sWHuS8TevjHopNeSCf73AeX6JUT1B3e1ma1zF810I';
					$accessToken       = '136217633-6MIHowRunalfGoUHUoMd53MtgGqtXCO36vtxEWAL';
					$accessTokenSecret = 'KNGkVbV8cTqY9DlSj61neMNJYgdexL90WXSpEgqwmw';
					*/
					
				}else{
					$consumerKey       = 'DWj2LuQIRRTgu9Qxk23VLQ';
					$consumerSecret    = 'GbFeFwO5u3y9rt059ecHvBRwsrquz8v3qu4x0W9Uxwg';
					$accessToken       = '121794123-a5fJS7pIA4q70vEP4deT41lm0NsTfsXqR3EaTrno';
					$accessTokenSecret = 'RKQnfiQrrklBxN0imwGTn6BPuwq1IJqHuQN2iQ0ms';
					
					$msg = "New: ".substr($record->news_title,0,85)." (http://www.archlinexp.com/news/show/".$new_id.")";
					print "twitter kozben 1";
					/*$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
					$status = $twitter->send($msg);*/
					require_once('application/plugins/codebird-php-2.4.1/src/codebird.php');
					$cb = \Codebird\Codebird::getInstance();
					$reply = $cb->statuses_update('status='.$msg);
					// End Twitter bejegyzés
					print "twitter utan";
				}
				
			}
			else
			{
				unset($record->news_url);
				unset($record->url);
				$this->db->update('news',$record,'news_id='.$record->news_id);
			}
		
			redirect('admin/news');
		
		}
	}
	
	function newsdelete()
	{
		$news_id = $this->uri->segment(3);
		
		if(!$news_id ||!is_numeric($news_id))
		{
			show_404();
		}
		
		$this->db->delete('news','news_id='.$news_id);
		
		redirect('admin/news');
	}
	
	function pagedelete()
	{
		$page_id = $this->uri->segment(3);
		
		if(!$page_id ||!is_numeric($page_id))
		{
			show_404();
		}
		
		//die("Ezt törölném ha be lenne kapcsolva a törlés: ".$page_id);
		
		$this->db->delete('pages',"page_id=$page_id and page_lang='".$this->muser->user['admin_lang']."'",1);
		
		redirect('admin/editor');
	}
	
	function downloads()
	{
		$this->load->model('mdownloads');
		$this->load->model('mversion');
	
		$data['trials']=$this->mdownloads->generate_subfolder_dropdown('trials');
		
		$data['trial']=$this->muser->get_setting('trial_'.$this->muser->user['admin_lang']);
		$data['student']=$this->muser->get_setting('student_'.$this->muser->user['admin_lang']);
		
		if($data['trial']==''){
			$data['trial']='http://';
		}
		
		if($data['student']==''){
			$data['student']='http://';
		}
		
	
		$data['downloads'] = $this->mdownloads->get_latest(999,$this->muser->user['admin_lang']);
		$data['frissitesek'] = $this->mversion->get_all("","ev DESC, projectid ASC, pkgid DESC");
		
		$data['frissitesek_json'] = json_encode($data['frissitesek']);
		
		$fajlok = $this->get_directory_file("public/downloads","exe");
	//	$dokumentumok = $this->get_directory_file("public/downloads");
		
		// hogy a kis es nagybetuk ne szamitsanak a rendezesnel
		$array_lowercase = array_map('strtolower', $fajlok);
		array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $fajlok);
		
		
	//	sort($fajlok);
	//	sort($dokumentumok);
		
		$data['fajlok'] = $fajlok;
	//	$data['dokumentumok'] = $dokumentumok;
		
		$data['utolso'] = $data['frissitesek'][count($data['frissitesek'])-1]->azonosito;
		
		$data['admin']=true;
		$data['aktiv']=3;
		$data['javascript'] = array('jquery_ui','jquery.numeric.pack', 'tablesorter/jquery.tablesorter.min');
		$data['style'] = array('jquery.ui', '../js/tablesorter/themes/blue/style');
		$data['tartalom']='admin/downloads';
		$data['csik']=array('home','admin');
	
		$this->load->view('site',$data);
	}
	
	
	function set_update(){
		$ver_id = $this->input->post('ver_id');
		$nyelvek = $this->input->post('lang');
		$verzio['azonosito'] = $this->input->post('azonosito');
		$verzio['projectid'] = $this->input->post('projectid');
		$verzio['pkgid']     = $this->input->post('pkgid');
		$verzio['ev']        = $this->input->post('ev');
	//	$verzio['lang']      = ";";
	//	$verzio['usertype']  = $this->input->post('usertype');
		$verzio['tipus']     = $this->input->post('tipus');
		$verzio['fajl']      = $this->input->post('fajl');
		$verzio['datum']     = $this->input->post('datum');
		$verzio['doksi']     = $this->input->post('doksi');
		$verzio['doksi_hun'] = $this->input->post('doksi_hun');
		$verzio['leiras']    = $this->input->post('leiras');
		$verzio['leiras_hun'] = $this->input->post('leiras_hun');
		$verzio['hash']      = $this->input->post('hash');
		if( $_POST['csendes'] == "on" )
			$verzio['csendes'] = '1';
		else
			$verzio['csendes'] = '0';
		if( $_POST['aktiv'] == "on" )
			$verzio['aktiv'] = '1';
		else
			$verzio['aktiv'] = '0';
		if( $_POST['public'] == "on" )
			$verzio['public'] = '1';
		else
			$verzio['public'] = '0';
		
		
		if( $this->input->post('userek') == "xy" ){
			$usereknek = trim($this->input->post('usertype'));
			if( substr($usereknek,0,1) != ";" )
				$usereknek = ";".$usereknek;
			if( substr($usereknek,-1) != ";" )
				$usereknek .= ";";
			
			$verzio['usertype'] = $usereknek;
		}
		else
			$verzio['usertype'] = "all";
		
		
		/*foreach($nyelvek as $nyelv)
			$verzio['lang'] .= $nyelv.";";
		
		if(strstr($verzio['lang'],'99'))
			$verzio['lang'] = '99';*/
		
		$this->db->update('version',$verzio,"ver_id = '".$ver_id."'");
		redirect("admin/downloads");
	}
	
	function newupdate(){
		$nyelvek = $this->input->post('lang');
		
		$verzio['azonosito'] = $this->input->post('azonosito');
		$verzio['projectid'] = $this->input->post('projectid');
		$verzio['pkgid']     = $this->input->post('pkgid');
		$verzio['ev']        = $this->input->post('ev');
	//	$verzio['lang']      = ";";
		$verzio['tipus']     = $this->input->post('tipus');
	//	$verzio['usertype']  = $this->input->post('usertype');
		$verzio['fajl']      = $this->input->post('fajl');
		$verzio['datum']     = $this->input->post('datum');
		$verzio['doksi']     = $this->input->post('doksi');
		$verzio['doksi_hun'] = $this->input->post('doksi_hun');
		$verzio['leiras']    = $this->input->post('leirasuj');
		$verzio['leiras_hun'] = $this->input->post('leirasuj_hun');
		$verzio['hash']      = $this->input->post('hash');
		if( $_POST['csendes'] == "on" )
			$verzio['csendes'] = '1';
		else
			$verzio['csendes'] = '0';
			
		if( $_POST['aktiv'] == "on" )
			$verzio['aktiv'] = '1';
		else
			$verzio['aktiv'] = '0';
			
		if( $_POST['public'] == "on" )
			$verzio['public'] = '1';
		else
			$verzio['public'] = '0';
		
		if( $this->input->post('userek') == "xy" ){
			$usereknek = trim($this->input->post('usertype'));
			if( substr($usereknek,0,1) != ";" )
				$usereknek = ";".$usereknek;
			if( substr($usereknek,-1) != ";" )
				$usereknek .= ";";
			
			$verzio['usertype'] = $usereknek;
		}
		else
			$verzio['usertype'] = "all";
		
		/*foreach($nyelvek as $nyelv)
			$verzio['lang'] .= $nyelv.";";
		
		if(strstr($verzio['lang'],'99'))
			$verzio['lang'] = '99';*/
		
		$this->db->insert('version',$verzio);
		redirect("admin/downloads");
	}
	
	function updatedelete(){
		$ver_id = $this->uri->segment(3);
		
		$this->db->update('version',array('deleted'=>"1"),"ver_id='".$ver_id."'");
		redirect("admin/downloads");
	}
	
	function collection()
	{
		$this->load->model('mcollection');
		
		$tipusok=$this->mcollection->get_type();
		foreach($tipusok as $tipus){
			$tipus->kategoria = $this->mcollection->get_kategoriak($tipus->tipus);
			foreach($tipus->kategoria as $kategoria){
				$kategoria->fajl = $this->mcollection->get_bykategoria($kategoria->dl_id);
				$kategoria->darab = $this->mcollection->get_darabegykategoria($kategoria->dl_id);
			}
			$tipus->darab = $this->mcollection->get_darabegytipus($tipus->tipus);
		}
		
		$data['main_events_json'] = json_encode($tipusok);
		
		$data['tipusok'] = $tipusok;
		
		$data['admin']=true;
		$data['aktiv']=11;
		if( true || strstr($_SERVER['HTTP_USER_AGENT'],'Ubuntu/8.04') )
			$data['tartalom']='admin/collection_new';
		else
			$data['tartalom']='admin/collection';
		$data['csik']=array('home','admin');
		
		$data['javascript'] = array('jquery_ui', 'ui.datepicker-hu', 'jquery.numeric.pack');
		$data['style'] = array('jquery.ui');
	
		$this->load->view('site',$data);
	}
	
	
	function kategedit(){
		if($this->input->post('do')!=false){
			$dl_id = $this->input->post('dlid');
			$tipus = $this->input->post('tipus');
			$nev_hun = $this->input->post('nev_hun');
			$nev_eng = $this->input->post('nev_eng');
			
			if($dl_id == "uj"){
				$this->muser->new_kategoria($tipus,$nev_hun,$nev_eng);
			}else{
				$this->muser->set_kategoria($dl_id, $tipus, $nev_hun, $nev_eng);
			}
			
			redirect('admin/collection');
		}
		else{
			if(hun())
				$data['title'] = 'ARCHLine.XP Kategória szerkesztés';
			else
				$data['title'] = 'ARCHLine.XP Edit Category';
			$data['admin']=true;
			$data['aktiv']=11;
			$data['tartalom']='admin/kategedit';
			$data['csik']=array('home','admin');
			
			if( $this->uri->segment(3) == "new" ){
				$data['uj'] = true;
				$kateg->tipus = $this->uri->segment(4);
				$data['kateg'] = $kateg;
				
			}
			else{
				$dlid = $this->uri->segment(3);
				$data['kateg'] = $this->muser->get_kategoria($dlid);
			}
				
			$this->load->view('site',$data);
		}
	}
	
	function delkateg(){
		$mit = $this->uri->segment(3);
		
		if( $mit != "" && is_numeric($mit) )
			$this->muser->del_kategoria($mit);
		
		redirect('admin/collection');
	}
	
	function projectsedit(){
		$this->load->model('mprojects');
		$this->load->model('mcollection');
	
		if($this->input->post('do')!=false){
			$pr_id = $this->input->post('prid');
			$lang = $this->muser->user['lang'];
			
			$error = "";
			$kep = "";
			
			$this->kep(&$kep);
			
			$prSize = 6500;
			$mi = "/home/cadline/public_html/website/".$_POST["originalFilenameField"];
			$prSize = filesize($mi); //??
			
			
			if(!$error){
				$ujpr->email = $_POST["projectEmailField"];
				$ujpr->title = $_POST["projhectNameField"];
				$ujpr->meret = $prSize;
				$ujpr->datum = date('Y-m-d H:i:s',time());
				$ujpr->nyelv = $lang;
				$ujpr->kep = $kep;
				$ujpr->kategoria = $_POST["kategoria"];
				$ujpr->text = $_POST["projectDescriptionField"];
				$ujpr->project = $_POST["originalFilenameField"];
				$ujpr->object = $_POST["originalFilenameField"];
				$ujpr->szerzo = $_POST["SzerzoField"];
				$ujpr->kat_id = $_POST["kategoria"];
				
				$this->mprojects->editproject($ujpr,$pr_id);
				//$this->mcollection->editobject($ujpr,$pr_id);
			}
			
			redirect('admin/collection');
		}
		else{
			$data['admin']=true;
			$data['aktiv']=11;
			
			$data['title'] = 'ARCHLine.XP Project szerkesztés';
			$data['tartalom']='admin/projectedit';
			$data['csik']=array('home','admin');
			
			$prid = $this->uri->segment(3);
			$data['project'] = $this->mprojects->get_row($prid);
			
			$data['kategoriak'] = $this->muser->get_kategoriak('project');
				
			$this->load->view('site',$data);
		}
	
	}
	
	function delproject(){
		$this->load->model('mprojects');
		$this->load->model('mcollection');
		
		$prid = $this->uri->segment(3);
		$this->mprojects->del($prid);	// A project fájlt és a hozzá tartozó képet is törli a szerverről.
		//$this->mcollection->del($prid);
		
		redirect('admin/collection');
	}
	
	function objectsedit(){
		$this->load->model('mobjects');
		$this->load->model('mcollection');
		
		if($this->input->post('do')!=false){
			$pr_id = $this->input->post('prid');
			$lang = $this->muser->user['lang'];
			
			$error = "";
			$kep = "";
			
			$this->kep(&$kep,'objects');
			
			$prSize = 6500;
			$mi = "/home/cadline/public_html/website/".$_POST["originalFilenameField"];
			$prSize = filesize($mi); //??
			
			
			if(!$error){
				$ujpr->email = $_POST["projectEmailField"];
				$ujpr->title = $_POST["projhectNameField"];
				$ujpr->meret = $prSize;
				$ujpr->datum = date('Y-m-d H:i:s',time());
				$ujpr->nyelv = $lang;
				$ujpr->kep = $kep;
				$ujpr->kategoria = $_POST["kategoria"];
				$ujpr->text = $_POST["projectDescriptionField"];
				$ujpr->object = $_POST["originalFilenameField"];
				$ujpr->szerzo = $_POST["SzerzoField"];
				$ujpr->kat_id = $_POST["kategoria"];
				
			//	$this->mobjects->editobject($ujpr,$pr_id);
				$this->mcollection->editobject($ujpr,$pr_id);
			}
			
			redirect('admin/collection');
		}
		else{
			if(hun())
				$data['title'] = 'ARCHLine.XP Objektum szerkesztés';
			else
				$data['title'] = 'ARCHLine.XP Edit Object';
			$data['admin']=true;
			$data['aktiv']=11;
			$data['tartalom']='admin/objectedit';
			$data['csik']=array('home','admin');
			
			$prid = $this->uri->segment(3);
			$data['object'] = $this->mcollection->get_row($prid);
			
			$data['kategoriak'] = $this->muser->get_kategoriak('object');
				
			$this->load->view('site',$data);
		}
	}
	
	function delobject(){
		$this->load->model('mobjects');
		$this->load->model('mcollection');
		
		$objid = $this->uri->segment(3);
		$this->mobjects->del($objid);	// Az objektum fajlt es a hozza tartozo kepet is torli a szerverrol.
		//$this->mcollection->del($objid);
		
		redirect('admin/collection');
	}
	
	function groupsedit(){
		$this->load->model('mgroups');
		$this->load->model('mcollection');
		$this->load->model('mforum');
		
		if($this->input->post('do')!=false){
			$pr_id = $this->input->post('prid');
			$lang = $this->muser->user['lang'];
			
			$error = "";
			$kep = $this->input->post('kep_eredeti');
			
			$tipusa = $this->mcollection->get_tipus($_POST["kategoria"]);
			$this->kep(&$kep,$tipusa);
			
			$prSize = 6500;
			$mi = "/home/cadline/public_html/website/".$_POST["originalFilenameField"];
			$prSize = filesize($mi); //??
			
			
			if(!$error){
				$ujpr->email	 = $_POST["projectEmailField"];
				$ujpr->title	 = $_POST["projhectNameField"];
				$ujpr->meret	 = $prSize;
				$ujpr->datum	 = date('Y-m-d H:i:s',time());
				$ujpr->nyelv	 = $lang;
				$ujpr->kep		 = $kep;
				$ujpr->kategoria = $_POST["kategoria"];
				$ujpr->text		 = $_POST["projectDescriptionField"];
				$ujpr->group	 = $_POST["originalFilenameField"];
				$ujpr->object	 = $_POST["originalFilenameField"];
				$ujpr->szerzo	 = $_POST["SzerzoField"];
				$ujpr->kat_id	 = $_POST["kategoria"];
				$ujpr->fajl		 = $_POST["originalFilenameField"];
				if( $_POST["bizalom"] != "" )
					$ujpr->bizalom	 = $_POST["bizalom"];
				if( $_POST["sorszam"] != "" && is_numeric($_POST["sorszam"]) )
					$ujpr->archline_sorszam	 = $_POST["sorszam"];
				
				//$this->mgroups->editgroup($ujpr,$pr_id);
				$this->mcollection->editobject($ujpr,$pr_id);
			}
			
			redirect('admin/collection');
		}
		else{
			if(hun())
				$data['title'] = 'ARCHLine.XP Csoport szerkesztés';
			else
				$data['title'] = 'ARCHLine.XP Edit Group';
			$data['admin']=true;
			$data['aktiv']=11;
			$data['tartalom']='admin/groupedit';
			$data['csik']=array('home','admin');
			
			$prid = $this->uri->segment(3);
			$group = $this->mcollection->get_row($prid);
			$data['group'] = $group;
			
			$data['tulaj'] = $this->mforum->get_userUid($group->u_id);
			
			$tipus = $this->mcollection->get_tipus($data['group']->kat_id);
			
			$data['kategoriak'] = $this->muser->get_kategoriak($tipus);
				
			$this->load->view('site',$data);
		}
	}
	
	function delgroup(){
		$this->load->model('mgroups');
		$this->load->model('mcollection');
		
		$grid = $this->uri->segment(3);
		//$this->mgroups->del($grid);	// A csoport fajlt es a hozza tartozo kepet is torli a szerverrol.
		$this->mcollection->del($grid);
		
		redirect('admin/collection');
	}
	
	function kep(&$kep,$mappa="group",$ujkep="kep"){
		if ($_FILES[$ujkep]["error"]==0){
			$lang = $this->muser->user['lang'];
			$kepnev = time()."_". $_FILES[$ujkep]["name"];
			$ide= "public/img/collection/".$mappa."/".$kepnev;
			if (copy($_FILES[$ujkep]["tmp_name"],$ide)){
				$kep = $ide;
				//print " Sikerült a képmásolás! ";
			}else{
				$prFile = "NULL";
				//print " Nem sikerült a képet felmásolni! <pre>"; print_r($_FILES[$ujkep]);
			}
		}
	}
	
	function kep2(&$kep,$hova,$filestomb,$id){
		if ($filestomb["error"][$id]==0){
			$lang = $this->muser->user['lang'];
			$kepnev = $filestomb["name"][$id];
			$ide= $hova."/".$kepnev;
			if (copy($filestomb["tmp_name"][$id],$ide)){
				$kep = $kepnev;//$ide;
			}
		}
	}
	
	function kep3(&$kep,$hova,$ujkep){
		if ($_FILES[$ujkep]["error"]==0){
			$kepnev = $_FILES[$ujkep]["name"];
			$ide= $hova."/".$kepnev;
			if (copy($_FILES[$ujkep]["tmp_name"],$ide)){
				$kep = $kepnev;//$ide;
			}
		}
	}
	
	function kep4(&$kep,$hova,$ujkep){
		if ($_FILES[$ujkep]["error"]==0){
			$kepnev = $_FILES[$ujkep]["name"];
			$ide= $hova."/".$kepnev;
			if (copy($_FILES[$ujkep]["tmp_name"],$ide)){
				$kep = $ide;
			}
		}
	}
	
	function download_set()
	{
		$this->muser->set_setting('trial_'.$this->muser->user['admin_lang'],$this->input->post('trial'));
		$this->muser->set_setting('student_'.$this->muser->user['admin_lang'],$this->input->post('student'));		
		
		
		redirect('admin/downloads');
	}
	
	function downloadsedit()
	{
		$this->load->model('mdownloads');
		
		$this->load->helper('directory');
		
		$data['dropdown']=$this->mdownloads->generate_file_dropdown();
		
		
		
		$download_id = $this->uri->segment(3);
		
		if(!is_numeric($download_id) && $download_id != 'new')
		{
			show_error('Hibás azonosító: '.$download_id);
		}
		
		$do = $this->input->post('do');
		if(!$do)
		// AKKOR FORM
		{
			if($download_id =='new')
			{
				$record = $this->mdb->set_empty_object('downloads');
				$record->download_id = $download_id;
			
				$data['remote']='http://';
			}
			else
			{
				$record = $this->mdownloads->get_row($download_id);
				if(!$record)
				{
					show_error('Nincs ilyen azonosítójú hír: '.$download_id);
				}
				
				if(array_key_exists($record->download_file,$data['dropdown']))
				{
					$data['remote']='';
				}
				else
				{
					$data['remote']=$record->download_file;
				}
			}
			
			
			
			
			
			
			
			$data['record']=$record;
			$data['admin']=true;
			$data['aktiv']=3;
			$data['tartalom']='admin/downloadsedit';
			$data['csik']=array('home','admin');
			$this->load->view('site',$data);
				
		}
		else
		//AKKOR PEDIG ADATBÁZISBEVITEL
		{
			$record = $this->mdb->set_post_object('downloads');
			
		//	if( $this->input->post('download_category') == "workshop" ){
		//		$record->download_date = $this->input->post('download_date');
		//	}else{
				$record->download_date = time();
		//	}
			
			//$record->download_date = time();
			
			$this->load->helper('file');
			
			$record->download_lang = $this->muser->user['admin_lang'];
			
			
			$download_file_remote = $this->input->post('download_file_remote');
			
			if($download_file_remote == 'http://')
			{
				$download_file_remote = '';
			}
			
			if($download_file_remote != '')
			{
				$record->download_file = mysql_real_escape_string($download_file_remote);
				$record->download_size = 0;
				
			}
			else
			{
				$fileinfo = get_file_info('.'.$record->download_file);
				$record->download_size = $fileinfo['size'];	
			}
			
			
			
			
			if ($record->download_id == 'new')
			{
				unset($record->download_id);
				$this->db->insert('downloads',$record);
			}
			else
			{
				$this->db->update('downloads',$record,'download_id='.$record->download_id);
			}
		
			redirect('admin/downloads');
		
		}
	}
	
	function downloadsdelete()
	{
		$news_id = $this->uri->segment(3);
		
		if(!$news_id ||!is_numeric($news_id))
		{
			show_404();
		}
		
		$this->db->delete('downloads','download_id='.$news_id,1);
		
		redirect('admin/downloads');
	}
	
	
	function render(){
		$this->load->model('mrender');
		$this->load->model('mforum');
		
		$data['title'] = 'ARCHLine.XP Renderek';
		$data['admin']=true;
		$data['aktiv']=12;
		$data['tartalom']='admin/render';
		$data['csik']=array('home','admin');
		
		$data['style'] = array('fancybox2');
		$data['javascript'] = array('fancybox/jquery-1.3.2.min','fancybox/jquery.easing.1.3','fancybox/jquery.fancybox-1.2.1.pack','fancybox/fancy');
		
		$rend = ""; $ir = "";
		
		if( $this->uri->segment(3) != "" )
			$rend = $this->uri->segment(3);
		if( $this->uri->segment(4) != "" )
			$ir = $this->uri->segment(4);
		
		$uresek = $this->mrender->get_all($rend,$ir);
		foreach($uresek as $render){
			$render->tulaj = $this->mforum->get_nev($render->user_id);
		}
		
		if($rend == 'user_id' && $ir == "asc")
			usort( $uresek, "hasonlito" );
		elseif($rend == 'user_id' && $ir == "desc")
			usort( $uresek, "hasonlitovissza" );
		
	/*	$hibasak = $this->mrender->get_byallapot("32");
		foreach($hibasak as $render){
			$render->tulaj = $this->mforum->get_nev($render->user_id);
		}
		
		$varakozok = $this->mrender->get_byallapot("4");
		foreach($varakozok as $render){
			$render->tulaj = $this->mforum->get_nev($render->user_id);
		}
		*/
		$data['uresek'] = $uresek;
		$data['irany'] = $ir;
	//	$data['hibasak'] = $hibasak;
	//	$data['varakozok'] = $varakozok;
			
		$this->load->view('site',$data);
	}
	
	function editrender(){
		$render_id = $this->uri->segment(3);
		$a = $_POST['allapot'];
		
		$this->db->update('render_img',array('allapot'=>$a,'datum'=>time()),"render_id = '".$render_id."'");
		redirect('admin/render');
	}
	
	function delrender(){
		$render_id = $this->uri->segment(3);
		
		$this->db->update('render_img',array('deleted'=>'1'),"render_id = '".$render_id."'");
		redirect('admin/render');
	}
	
	function rendertorol(){
		$this->load->model('mrender');
		
		$miket = $this->input->post('torol');
		
		foreach($miket as $mi){
		//	print "<br />id: ".$mi;
			$this->mrender->del($mi);
			
			$record->osztaly = "admin";
			$record->fv = "rendertorol";
			$record->hiba = "törlés: ".$mi;
			$record->datum = date('Y-m-d H:i:s',time());
		//	$this->db->insert('a_hibak',$record);
		}
		
		redirect('admin/render');
	}
	
	function phpinfo(){
		phpinfo();
	}
	
	
	function get_directory_file($path,$kit="pdf"){
		$path_id = opendir($path);
		while($file_name = readdir($path_id)){
			if($file_name != "." && $file_name != ".."){
				$file["type"] = filetype($path . "/" . $file_name);
				if($file["type"] == "dir"){
					$file_array = array();
					$file_array = $this->get_directory_file($path."/".$file_name,$kit);
					if(isset($found))
						$found = array_merge($found, $file_array);
					else
						$found = $file_array;
				}
				else{
				/*	$file["accessed"] = fileatime($path . "/" . $file_name);
					$file["changed"] = filectime($path . "/" . $file_name);
					$file["group"] = filegroup($path . "/" . $file_name);
					$file["inode"] = fileinode($path . "/" . $file_name);
					$file["modified"] = filemtime($path . "/" . $file_name);
					$file["owner"] = fileowner($path . "/" . $file_name);
					$file["permissions"] = fileperms($path . "/" . $file_name);
					$file["size"] = filesize($path . "/" . $file_name);*/
					if(substr($file_name,-4) == ".".$kit)
						$found[substr($path,17)."/".$file_name] = substr($path,17)."/".$file_name;
					//	$found[$path][] = substr($path,17)."/".$file_name;
				}
			}
		}
		closedir($path_id);
		if(!isset($found))
		{
			$found = array();
		}
		return($found);
	}
	
	
	function galeria(){
		$this->load->model('mgallery');
		
		$fajlok = array('img/honapkepe'=>'img/honapkepe');
		
		$intfajlok = scandir('/var/www/hosting/cadline.hu/www/public/gallery/');
		$archfajlok = scandir('/var/www/hosting/cadline.hu/www/public/galeria/');
		
		foreach($intfajlok as $m){
			if($m != "." && $m != ".."){
				$fajlok['gallery/'.$m] = 'gallery/'.$m;
			}
		}
		
		foreach($archfajlok as $m){
			if($m != "." && $m != ".."){
				$fajlok['galeria/'.$m] = 'galeria/'.$m;
			}
		}
		
		
		$nyelv = $this->muser->user['admin_lang'];
		
		$honapkepekepek = $this->mgallery->get_all('hun','honapkepe');
		foreach($honapkepekepek as $hk){
			$hk->kiemelt4 = $hk->kiemelt3 = $hk->kiemelt2 = $hk->kiemelt1 = null;
			if( file_exists('public/img/honapkepe/galeria/'.$hk->sorszam.'/sorrend.php') ){
				include('public/img/honapkepe/galeria/'.$hk->sorszam.'/sorrend.php');
				$kiemeltek = $images;
				
				$hk->kiemelt1 = $kiemeltek[0];
				$hk->kiemelt2 = $kiemeltek[1];
				$hk->kiemelt3 = $kiemeltek[2];
				$hk->kiemelt4 = $kiemeltek[3];
			}else{
				$images = scandir('public/img/honapkepe/galeria/'.$hk->sorszam);
				$i=1;
				foreach($images as $img){
					if( $img != ".."  &&  $img != "."  &&  !is_dir('public/img/honapkepe/galeria/'.$hk->sorszam."/".$img)  &&  $img != "sorrend.php" ){
						$hk->{'kiemelt'.$i} = $img;
						$i++;
					}
				}
			}
		}
		//print_r($honapkepekepek);
		
		$data['honapkepek_json'] = json_encode($honapkepekepek);
		$data['honapkepek'] = $honapkepekepek;
		$data['ktkepek'] = $this->mgallery->get_all($nyelv,'kezzel');
		$data['interiorkepek'] = $this->mgallery->get_all($nyelv,'interior');
		$data['architectkepek'] = $this->mgallery->get_all($nyelv,'architect');
		$data['photokepek'] = $this->mgallery->get_all($nyelv,'photo');
		
		$data['galeriak_json'] = json_encode($this->mgallery->get_all($nyelv));
		
		$data['fajlok'] = $fajlok;
		
		$data['title'] = 'ARCHLine.XP Galériák';
		$data['admin'] = true;
		$data['aktiv'] = 13;
		$data['tartalom']='admin/galeria';
		$data['csik']  = array('home','admin');
		
		$data['style'] = array('jquery.ui');
		$data['javascript'] = array('jquery_ui');
		
		$this->load->view('site',$data);
	}
	
	/*function editgaleria(){
		$gal_id = $this->input->post('gal_id');
		$galeria['cim'] = $this->input->post('cim');
		$galeria['terulet'] = $this->input->post('terulet');
		$galeria['leiras'] = $this->input->post('leiras');
		$galeria['mappa'] = $this->input->post('mappa');
		$galeria['link'] = $this->input->post('link');
		$galeria['kezdo'] = $this->input->post('kezdo');
		$galeria['sorszam'] = $this->input->post('sorszam');
		if( $_POST['uj'] == "on" )
			$galeria['uj'] = '1';
		else
			$galeria['uj'] = '0';
		
		if( $galeria['terulet'] == "honapkepe" )
			$galeria['leiras'] .= "###".$this->input->post('leiras2');
		
		
		if( isset($_FILES) && $_FILES['fajlok']['name'] != ''){
			include('application/helpers/sajatfeltolto.php');
			
		//	$hovakep = "public/upload/eng/";
			switch($galeria['terulet']){
				case 'interior':
						$hovakep = 'public/gallery/';
						
						if( $galeria['mappa'] == "" && $this->input->post('ujgal') == 'igen' && substr(basename( $_FILES['fajlok']['name'] ),-4) == ".zip" )
							$hovakep .= substr(basename( $_FILES['fajlok']['name'] ), 0, -4) . '/';
						break;
				case 'architect':
						$hovakep = 'public/gallery/';
						if( $galeria['mappa'] == "" && $this->input->post('ujgal') == 'igen' && substr(basename( $_FILES['fajlok']['name'] ),-4) == ".zip" )
							$hovakep .= substr(basename( $_FILES['fajlok']['name'] ), 0, -4) . '/';
						break;
				case 'photo':
						$hovakep = 'public/gallery/';
						if( $galeria['mappa'] == "" && $this->input->post('ujgal') == 'igen' && substr(basename( $_FILES['fajlok']['name'] ),-4) == ".zip" )
							$hovakep .= substr(basename( $_FILES['fajlok']['name'] ), 0, -4) . '/';
						break;
				case 'kezzel':
						$hovakep = 'public/img/kezzeltervez/'.$galeria['mappa'].'/';
						break;
				case 'honapkepe':
						$hovakep = 'public/img/honapkepe/galeria/'.$galeria['sorszam'];
						break;
			}
			
			if( !is_dir($hovakep) && $hovakep != "" ){
				mkdir($hovakep,0777);
				exec('chmod 777 /var/www/hosting/cadline.hu/www/'.$hovakep);
			}
			
			
			$ered = feltolt('fajlok',$hovakep,$_FILES['fajlok']['name'],true);
			if($ered){
				
				$mit = '/var/www/hosting/cadline.hu/www/'.$ered;
				exec('chmod 777 '.$mit);
				
				if( substr($ered,-4) == ".zip" ){
					$hova2 = '/var/www/hosting/cadline.hu/www/'.$hovakep;
					
					
					require_once('application/helpers/pclzip.lib.php');
					$archive = new PclZip($mit);
					if($archive->extract(PCLZIP_OPT_PATH, $hova2) == 0){
						die("Error : ".$archive->errorInfo(true));
					}
					
					$galeria['mappa'] = substr(basename($ered),0,-4);
					
					unlink($ered);
				}elseif( is_dir($hovakep.$galeria['mappa']) ){
					copy($ered,$hovakep.$galeria['mappa']);
				}
			}
			else{
				$record->osztaly = "admin";
				$record->fv = "editgaleria";
				$record->hiba = "Fajl feltoltesi hiba:\n".$_FILES['fajlok']['name']."\nide: ".$hovakep;
				$record->datum = date('Y-m-d H:i:s',time());
				$this->db->insert('a_hibak',$record);
			}
		}
		
		
		if( $this->input->post('ujgal') == 'nem' )
			$this->db->update('gallerys',$galeria,"gal_id = '".$gal_id."'");
		elseif( $this->input->post('ujgal') == 'igen' ){
			$galeria['nyelv'] = $this->muser->user['admin_lang'];
			$galeria['deleted'] = '0';
			$this->db->insert('gallerys',$galeria);
		}
		
		redirect('admin/galeria');
	}*/
	
	function edithkgaleria(){
		$gal_id = $this->input->post('gal_id');
		$galeria['cim']     = $this->input->post('cim');
		$galeria['terulet'] = 'honapkepe';
		$galeria['leiras']  = $this->input->post('leiras');
		$galeria['kezdo']   = $this->input->post('kezdo');
		$galeria['sorszam'] = $this->input->post('sorszam');
		
		// kiemelt képek
		$kiemeltek = "array(\n";//array();
		$kiemeltekmappa = 'public/img/honapkepe/galeria/'.$galeria['sorszam'];
		$kiemeltekfajl = $kiemeltekmappa.'/sorrend.php';
		
		exec('rm -R public/img/honapkepe/galeria/'.$galeria['sorszam']);
		mkdir($kiemeltekmappa,0644);
		chmod($kiemeltekmappa,0777);
		
		mkdir($kiemeltekmappa.'/thumbs',0644);
		chmod($kiemeltekmappa.'/thumbs',0777);
		
		$kivev = (2011 + (int)($galeria['sorszam']/12.00009));
		$kivhonap = (($galeria['sorszam']-1)%12+1);
		$evho  = ( $kivhonap < 10 ) ? $kivev."0".$kivhonap : $kivev.$kivhonap;
		
		for($i=1; $i<=4; $i++){
			if( $this->input->post('kiemelt'.$i) ){
				$fajli = $this->input->post('kiemelt'.$i);
				exec('cp public/img/honapkepe/'.$evho.'/'.$fajli.' '.$kiemeltekmappa.'/'.$fajli);
				exec('cp public/img/honapkepe/'.$evho.'/thumbs/'.$fajli.' '.$kiemeltekmappa.'/thumbs/'.$fajli);
				$kiemeltek .= '\t\"'.$this->input->post('kiemelt'.$i).'\"';
				if( $this->input->post('kiemelt'.($i+1)) )
					$kiemeltek .= ",\n";
				else
					$kiemeltek .= "\n";
			}
		}
		$kiemeltek .= ");\n";
	//	$sorrendphp = print_r($kiemeltek,true);
		$sorrendphp = $kiemeltek;
	//	print "<textarea rows='25' cols='80'>\n";
	//	exec('rm '.$kiemeltekfajl)."\n";
		exec('echo \'<?\' > '.$kiemeltekfajl)."\n";
		exec('echo "\$images = '.$sorrendphp.'" >> '.$kiemeltekfajl)."\n";
		exec('echo "?>" >> '.$kiemeltekfajl);
	//	print_r($_POST);
	//	print "</textarea>";
	//	...
	
		// adatbázis
		if( $this->input->post('ujgal') == 'nem' )
			$this->db->update('gallerys',$galeria,"gal_id = '".$gal_id."'");
		elseif( $this->input->post('ujgal') == 'igen' ){
			$galeria['nyelv'] = $this->muser->user['admin_lang'];
			$galeria['deleted'] = '0';
			$this->db->insert('gallerys',$galeria);
		}
		
		redirect('admin/galeria');
		
	}
	
	function ajaxhkkepek(){
		$sorszam = $this->uri->segment(3);
		$ev    = 2011+(int)(($sorszam-1)/12);
		$honap = (($sorszam-1)%12)+1;
		$honap = ($honap>=10) ? $honap : '0'.$honap;
		$mappa = $ev.$honap;
		
		$utvonal = '/var/www/hosting/cadline.hu/www/public/img/honapkepe/'.$mappa.'/';
		$kepek = scandir($utvonal);
		$nyerteskep = $this->db->query("SELECT kezdo FROM gallerys WHERE sorszam={$sorszam} AND terulet='honapkepe' AND deleted=0")->row();
		
		print "<select name=\"kezdo\" id=\"kezdo\" style=\"width: 255px;\">\n\t\t";
		print	"<option value=\"\">-- ".lang('collec_valasszon')." --</option>\n\t\t";
				foreach($kepek as $kep){
					if( $kep!="." && $kep!=".." && !is_dir($utvonal.$kep) && substr($kep,0,4)!="692_" ){
						if( $kep == $nyerteskep->kezdo )
							print "<option value=\"".$kep."\" selected=\"selected\">";
						else
							print "<option value=\"".$kep."\">";
						
						print 	$kep;
						print "</option>\n\t\t";
					}
				}
		print "</select>";
	}
	
	
	function galeriadelete(){
		$gal_id = $this->uri->segment(3);
		
		$this->db->update('gallerys',array('deleted'=>'1'),"gal_id = '".$gal_id."'");
		redirect('admin/galeria');
	}
	
	function ujgalkep(){
		if( $_FILES["gallery2012"]["error"]==0 ){
			include('application/helpers/sajatfeltolto.php');
			include('application/helpers/myimg_helper.php');
			
			$hova    = "public/img/gallery2012/";
			$fajlnev = $_FILES["gallery2012"]["name"];
			feltolt("gallery2012",$hova,$fajlnev,true);
			kemeretezesvagassh($hova.$fajlnev,$hova.$fajlnev,800,600);
			kemeretezesvagassh($hova.$fajlnev,$hova.'thumbs/'.$fajlnev,68,68);
			kemeretezesvagassh($hova.$fajlnev,$hova.'300/'.$fajlnev,300,225);
			chmod($hova.$fajlnev,0777);
		}
		
		redirect('admin/galeria');
	}
	
	function ujarchgalkep(){
		if( $_FILES["gallery2012"]["error"]==0 ){
			include('application/helpers/sajatfeltolto.php');
			include('application/helpers/myimg_helper.php');
			
			$hova    = "public/img/gallery2012architect/";
			$fajlnev = $_FILES["gallery2012"]["name"];
			feltolt("gallery2012",$hova,$fajlnev,true);
			kemeretezesvagassh($hova.$fajlnev,$hova.$fajlnev,800,600);
			kemeretezesvagassh($hova.$fajlnev,$hova.'thumbs/'.$fajlnev,68,68);
			kemeretezesvagassh($hova.$fajlnev,$hova.'300/'.$fajlnev,300,225);
			chmod($hova.$fajlnev,0777);
		}
		
		redirect('admin/galeria');
	}
	
	function createthumbs(){
		$utvonal = $this->input->post('utvonal');
		
		
		if( !$utvonal ){
			?>
			<form action="" method="post">
			Utvonal: <input type="text" name="utvonal" /> <input type="submit" value="OK" /><br />
			pelda: public/img/gallery2012/
			</form>
			<?
		}
		else{
			if( substr($utvonal,-1) != "/" )
				$utvonal .= "/";
			
			if( !is_dir($utvonal) ){
				print "A megadott mappa nem letezik: ".$utvonal;
				exit();
			}
			
			$utvonalthumbs = $utvonal."thumbs/";
			
			if( !is_dir($utvonalthumbs) ){
				mkdir($utvonalthumbs,0644);
				chmod($utvonalthumbs,0777);
			}
			
			$nagykepek = scandir($utvonal);
			$letrehozva= "";
			
			include('application/helpers/myimg_helper.php');
			foreach( $nagykepek as $nagy ){
				$nagykep = $utvonal.$nagy;
				// ha letezik a thumb kep akkor ne irja felul
				if( $nagy!="."  &&  $nagy!=".."  &&  !is_dir($nagykep)  &&  !file_exists($utvonalthumbs.$nagy) ){
					$ujkiskep = $utvonalthumbs.$nagy;
					kemeretezesvagassh($nagykep,$ujkiskep,68,68);
					chmod($ujkiskep,0777);
					$letrehozva .= $ujkiskep."<br />";
					print "<br>ok: ".$ujkiskep;
				}
			}
			print "Letrehozva: ".$letrehozva;
			exit();
		}
	}
	
	function creategallerylink(){
		$utvonal = $this->input->post('utvonal');
		
		
		if( !$utvonal ){
			?>
			<form action="" method="post">
			Mappa: <input type="text" name="utvonal" /> <input type="submit" value="OK" /><br />
			pelda: public/img/gallery2012/
			</form>
			<?
		}
		else{
			if( substr($utvonal,-1) != "/" )
				$utvonal .= "/";
			
			if( !is_dir($utvonal) ){
				print "A megadott mappa nem letezik: ".$utvonal;
				exit();
			}
			
			print $utvonal." : ".base64_encode($utvonal);
			exit();
		}
	}
	
	function workshop(){
		$this->load->model('mevents');
		
		$data['error'] = false;
		$nyelv = hun() ? "hun" : "eng";
		
		$do = $this->input->post('do');
		
		//esemény módosítása
		if($do && $do == 'modositas'){
			$post['datum']       = $this->input->post('datum');
			$post['ora_kezdet']  = $this->input->post('ora_kezdet');
			$post['ora_veg']     = $this->input->post('ora_veg');
			$post['perc_kezdet'] = $this->input->post('perc_kezdet');
			$post['perc_veg']    = $this->input->post('perc_veg');
			$post['event_limit'] = $this->input->post('event_limit');
			$post['active']      = $this->input->post('active');
			$post['nev']         = $this->input->post('nev');
			$post['event_id']    = $this->input->post('event_id');
			$post['event_main_id'] = $this->input->post('event_main_id');
			$post['location']    = ($this->input->post('event_location2') != "") ? $this->input->post('event_location2') : $this->input->post('event_location');
			$post['csoport']     = $this->input->post('csoport');
			
			if( $this->input->post('online') == "on" )
				$post['online'] = '1';
			else
				$post['online'] = 'NULL';
			
			if($error = $this->mevents->modifyEvent($post)){
				$data['error'] = $error;
			}
			
			if($post['event_main_id']==56 || $post['event_main_id']==63 )
				$this->cache->delete('archline-klub-idopontok-'.$nyelv);
		}
		
		//új esemény rögzítése
		if($do && $do == 'rogzites'){
			$post['datum']       = $this->input->post('datum');
			$post['ora_kezdet']  = $this->input->post('ora_kezdet');
			$post['ora_veg']     = $this->input->post('ora_veg');
			$post['perc_kezdet'] = $this->input->post('perc_kezdet');
			$post['perc_veg']    = $this->input->post('perc_veg');
			$post['event_limit'] = $this->input->post('event_limit');
			$post['active']      = $this->input->post('active');
			$post['nev']         = $this->input->post('nev');
			$post['event_main_id'] = $this->input->post('event_main_id');
			$post['location']    = ($this->input->post('event_location2') != "") ? $this->input->post('event_location2') : $this->input->post('event_location');
			$post['csoport']     = $this->input->post('csoport');
			
			if( $this->input->post('online') == "on" )
				$post['online'] = '1';
			else
				$post['online'] = 'NULL';
            
            if($error = $this->mevents->createEvent($post)){
                $data['error'] = $error;
            }
			
			if($post['event_main_id']==56 || $post['event_main_id']==63 )
				$this->cache->delete('archline-klub-idopontok-'.$nyelv);
        }
        
        //főesemény módosítása
        if($do && $do == 'modositas_main'){
        
            $config['upload_path'] = 'public/img/workshop/ENG/subjects/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '1000';
            $config['overwrite'] = true;
            
            $this->load->library('upload', $config);
            
            $this->upload->initialize($config);
			
			if( isset($_FILES['fokep']) && $_FILES['fokep']["error"]==0 ){
				
				include('application/helpers/sajatfeltolto.php');
				
				$fokep = feltolt('fokep',$config['upload_path'],"big_".$_FILES['fokep']["name"],true);
				
				if(!$fokep){
					$data['error'] = "Kép feltöltési hiba";
				}else{
					exec('convert -resize 458 '.$fokep.' public/img/workshop/ENG/subjects/'.substr(basename($fokep),4));
					$fokep = substr(basename($fokep),4);
				}
				
			} else {
				$fokep = $this->input->post('fokep_eredeti');
			}
			
			
			if(!$data['error']){
				$post = array(
					'event_main_id'     => $this->input->post('event_main_id'),
					'nev'               => $this->input->post('nev'),
					'sikeres_reg_oldal' => $this->input->post('sikeres_reg_oldal'),
					'sikeres_reg_mail'  => $this->input->post('sikeres_reg_mail'),
					'reg_torles_oldal'  => $this->input->post('reg_torles_oldal'),
					'datum_kezdet'      => $this->input->post('datum_kezdet'),
					'ora_kezdet'        => $this->input->post('ora_kezdet'),
					'perc_kezdet'       => $this->input->post('perc_kezdet'),
					'datum_veg'         => $this->input->post('datum_veg'),
					'ora_veg'           => $this->input->post('ora_veg'),
					'perc_veg'          => $this->input->post('perc_veg'),
					'limit'             => $this->input->post('event_main_limit'),
					'active'            => $this->input->post('active'),
					'rss'               => $this->input->post('rss'),
					'fokep'             => $fokep,
					'shorttext'         => $this->input->post('rovid_oldal'),
					'project'           => $this->input->post('project'),
					'video'             => $this->input->post('video'),
					'guide'             => $this->input->post('guide'),
					'shortfile'         => $this->input->post('shortfile')
				);
				
				if($error = $this->mevents->modifyMainEvent($post)){
					$data['error'] = $error;
				}
			}
		}
		
		//új főesemény létrehozása
		if($do && $do == 'rogzites_main'){
			$config['upload_path'] = 'public/img/workshop/ENG/subjects/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = '1000';
			$config['overwrite'] = true;
			
		//	$this->upload->initialize($config);
			
			/*if(isset($_FILES, $_FILES['fokep']) && $_FILES['fokep'] != ''){
				if(!$this->upload->do_upload('thumb')){
					$data['error'] = $this->upload->display_errors('<p>', '</p>');
				} else {
					$fokep = $this->upload->file_name;
				}
			} else {
				$fokep = '';
			}*/
			if( isset($_FILES['fokep']) && $_FILES['fokep']["error"]==0 ){
				
				include('application/helpers/sajatfeltolto.php');
				
				$fokep = feltolt('fokep',$config['upload_path'],"big_".$_FILES['fokep']["name"],true);
				
				if(!$fokep){
					$data['error'] = "Kép feltöltési hiba";
				}else{
					exec('convert -resize 458 '.$fokep.' public/img/workshop/ENG/subjects/'.substr(basename($fokep),4));
					$fokep = substr(basename($fokep),4);
				}
			} else {
				$fokep = $this->input->post('fokep_eredeti');
			}
			
			if(!$data['error']){
				$post = array(
					'nev'               => $this->input->post('nev'),
					'leiras'            => substr($this->input->post('leiras'), 0, 500),
					'kep'               => $kep,
					'thumb'             => $thumb,
					'weboldal'          => $this->input->post('weboldal'),
					'sikeres_reg_oldal' => $this->input->post('sikeres_reg_oldal'),
					'sikeres_reg_mail'  => $this->input->post('sikeres_reg_mail'),
					'reg_torles_oldal'  => $this->input->post('reg_torles_oldal'),
					'datum_kezdet'      => $this->input->post('datum_kezdet'),
					'ora_kezdet'        => $this->input->post('ora_kezdet'),
					'perc_kezdet'       => $this->input->post('perc_kezdet'),
					'datum_veg'         => $this->input->post('datum_veg'),
					'ora_veg'           => $this->input->post('ora_veg'),
					'perc_veg'          => $this->input->post('perc_veg'),
					'limit'             => $this->input->post('event_main_limit'),
					'active'            => $this->input->post('active'),
					'lang'              => $this->muser->user['admin_lang'],
					
					'rss_date'          => time(),
					'rss'               => $this->input->post('rss')
				);
				
				if($error = $this->mevents->createMainEvent($post)){
					$data['error'] = $error;
				}
			}
		}
		
		//collecting pages
		$this->load->model('mpages');
		
		if(hun()){
			$category = 'események';
		} else {
			$category = 'events';
		}
		
		$data['event_pages'] = $this->mpages->get_category_pages($category, $this->muser->user['admin_lang'], true, 'page_title', 'asc');
		
		//collecting events
		$main_events = $this->mevents->getMainEvents($this->muser->user['admin_lang']);
		
		//creating json for the javascript
		foreach($main_events as $main_event){
			$main_event->events_list = $this->mevents->getEvents($main_event->event_main_id);
			$ujreszinfok = $this->db->query("SELECT urlname, project, video, guide, shortfile FROM events_new_main WHERE event_main_id = ".$main_event->event_main_id)->row();
			$main_event->urlname = $ujreszinfok->urlname;
			$main_event->project = $ujreszinfok->project;
			$main_event->video   = $ujreszinfok->video;
			$main_event->guide   = $ujreszinfok->guide;
			$main_event->shortfile = $ujreszinfok->shortfile;
			
		//	$main_event->shorttext = $elokepek->shorttext;
		
			if($main_event->events_list){
				foreach($main_event->events_list as $event){
					$event->reg_list = $this->mevents->getRegistrations($event->event_id);
				}
			}
		}
		
		$data['main_events_json'] = json_encode($main_events);
		
		$data['main_events'] = $main_events;
		
		//collecting event view types
		$event_views = $this->mevents->getEventViews();
		
		$data['event_views'] = $event_views;
		
		$klubtemak         = $this->db->query("SELECT url, menu_cim FROM archline_klub WHERE aktiv=1 AND nyelv='{$nyelv}' ORDER BY menu_cim")->result();
		$data['klubtemak'] = $klubtemak;
		
		$data['admin'] = true;
		$data['aktiv'] = 13;
		$data['tartalom'] = 'admin/workshop';
		$data['csik']  = array('home', 'admin');
		$data['javascript'] = array('jquery_ui', 'ui.datepicker-hu', 'jquery.numeric.pack');
		$data['style'] = array('jquery.ui');
		
		$this->load->view('site',$data);
	}
	
	function wsparkolo(){
		$irany = $this->uri->segment(3);
		$reg_id = $this->uri->segment(4);
		
		$this->db->query("UPDATE events_new_registrations SET parkolo=parkolo+({$irany}) WHERE events_new_registrations_id={$reg_id}");
		header("Location: ".$_SERVER["HTTP_REFERER"]);
	}
	
	function wsgep(){
		$irany = $this->uri->segment(3);
		$reg_id = $this->uri->segment(4);
		
		$this->db->query("UPDATE events_new_registrations SET gep=gep+({$irany}) WHERE events_new_registrations_id={$reg_id}");
		header("Location: ".$_SERVER["HTTP_REFERER"]);
	}
	
	function alklubtemak(){
		
		$nyelv = hun() ? "hun" : "eng";
		
		if($this->input->post("do")){
			$tema_id        = $this->input->post("tema_id");
			$uj["sorsz"]    = $this->input->post("sorsz");
			$uj["cim"]      = $this->input->post("cim");
			$uj["menu_cim"] = $this->input->post("menu_cim");
			$uj["page"]     = $this->input->post("page");
		//	$uj["pdf"]      = $_FILES["pdf"]["name"];
			$uj["aktiv"]    = ($this->input->post("aktiv")=="on") ? 1 : 0;
			
			if( $_FILES["pdf"]["error"]==0 ){
				include('application/helpers/sajatfeltolto.php');
				$pdf = feltolt('pdf',"public/downloads/hun/archlineklub/",$_FILES['pdf']["name"],true);
				
				if($pdf){
					$uj["pdf"] = basename($pdf);
				}
			}
			
			// módosítás
			if( is_numeric($tema_id) && $tema_id>0 ){
				$this->db->update('archline_klub',$uj,"tema_id={$tema_id}");
				//print "modosít: "; print_r($uj);
			}
			// új
			else{
				$uj["nyelv"] = $nyelv;
				$uj["url"]   = $this->input->post("url");
				$this->db->insert('archline_klub',$uj);
				//print "uj: "; print_r($uj);
			}
			
			//redirect("admin/alklubtemak");
		}
		
		$pcategory = hun() ? 'Események' : 'Events';
		$temak     = $this->db->query("SELECT * FROM archline_klub WHERE nyelv='{$nyelv}' ORDER BY sorsz DESC")->result();
		$esemlapok = $this->db->query("SELECT page_id, page_title FROM pages WHERE page_category='{$pcategory}' AND page_urls!='e-mail' AND del=0 ORDER BY page_title")->result();
		$utolso = $this->db->query("SELECT max(sorsz) as sorsz FROM archline_klub WHERE nyelv='{$nyelv}'")->row();
		
		$data['kovsorszam'] = $utolso->sorsz+1;
		$data['temak'] = $temak;
		$data['esemlapok'] = $esemlapok;
		$data['admin'] = true;
		$data['aktiv'] = 13;
		$data['tartalom'] = 'admin/alklubtemak';
		$data['csik']  = array('home', 'admin');
		$data['javascript'] = array('jquery_ui');
		$data['style'] = array('jquery.ui');
		
		$this->load->view('site',$data);
		
	}
	
	function collection2(){
		$this->load->model('mcollection2');
		
		$gyartolimit = array( "ita" => "2", "ger" => "itc"  );
		
		$adminlang = $this->muser->user['lang'];
		
		if( array_key_exists($adminlang, $gyartolimit) ){
			if(ita())
				$gyartok = $this->db->query("SELECT * FROM coll2_man WHERE deleted=0 AND group_id LIKE ';{$gyartolimit[$adminlang]};'")->result();
			else
				$gyartok[0] = $this->mcollection2->get_manBydir($gyartolimit[$adminlang]);
		}else{
			$gyartok = $this->mcollection2->get_gyartok();
		}
		
		$ordernev = hun() ? 'title_hun' : 'title_eng';
		
		foreach($gyartok as $gyarto){
			$gyarto->kategoria = $this->mcollection2->get_kategoriak($gyarto->dir);
			$gyarto->darab = 0;
			foreach($gyarto->kategoria as $kategoria){
				$kategoria->fajl  = $this->mcollection2->get_objektumok($kategoria->c_id,$ordernev.' ASC');
				if( !$kategoria->fajl )
					$kategoria->fajl = array();
				$kategoria->darab = count($kategoria->fajl);
				$gyarto->darab   += $kategoria->darab;
			}
		}
		
		
		switch($adminlang){
			case 'hun':  $urlelotag = 'http://www.archline.hu/'; break;
			case 'ita':  $urlelotag = 'http://www.archlinexp.com/it/'; break;
			case 'esp':  $urlelotag = 'http://www.archlinexp.com/es/'; break;
			default:  $urlelotag = 'http://www.archlinexp.com/'; break;
		}
		
		$brandgroup = false;
		if(ita())
			$brandgroup = $this->db->query("SELECT * FROM coll2_mangrp WHERE group_id=2")->row();
		elseif(hun()||eng())
			$brandgroup = $this->db->query("SELECT * FROM coll2_mangrp WHERE deleted=0")->result();
		
		$data['main_events_json'] = json_encode($gyartok);
		$data['gyartok']          = $gyartok;
		$data['brandgroup']       = $brandgroup;
		$data['tipusok']          = $this->db->query("SELECT * FROM coll2_types ORDER BY type ASC")->result();
		$data['archlinetipusok']  = $this->db->query("SELECT distinct(type_download) FROM coll2_types ORDER BY type_download")->result();
		
		$data['urlelotag']        = $urlelotag;
		
		$data['admin']=true;
		$data['aktiv']=11;
		
		$data['csik']       = array('home','admin');
		$data['javascript'] = array('jquery_ui', 'ui.datepicker-hu');
		$data['style']      = array('jquery.ui');
		$data['tartalom']   = 'admin/collection2';
	
		$this->load->view('site',$data);
	}
	
	function kategedit2(){
		$c_id    = $this->input->post('cid');
		$mid     = $this->input->post('mid');
		$nev_hun = $this->input->post('nev_hun');
		$nev_eng = $this->input->post('nev_eng');
		
		
		// kategória átnevezése
		if($c_id == "uj"){
			$this->db->insert('coll2_cat',array('m_id'=>$mid,'nev_hun'=>$nev_hun,'nev_eng'=>$nev_eng));
			$c_id = mysql_insert_id();
		}else{
			$this->db->update('coll2_cat',array('nev_hun'=>$nev_hun,'nev_eng'=>$nev_eng),"c_id={$c_id}");
		}
		
		
		// kategória kép csere
		if( $_FILES["katkep"]["error"]==0 ){
			include('application/helpers/sajatfeltolto.php');
			$hova  = "public/img/collection/category/";
			// korábbi kép törlése
			exec("rm public/img/collection/category/".$c_id.".jpg");
			$ujkatkep = $hova.$c_id.".jpg";
			feltolt("katkep",$hova,$c_id.".jpg",true);
			
			// átméretezés
			include('application/helpers/myimg_helper.php');
			kemeretezesvagassh($ujkatkep,$hova.$c_id."_182x152.jpg",182,152);
			kemeretezesvagassh($ujkatkep,$ujkatkep,182,131);
			chmod($ujkatkep,0777);
		}
		
		redirect('admin/collection2');
	}
	
	function delkateg2(){
		$cid = $this->uri->segment(3);
		
		if( $cid != "" && is_numeric($cid) )
			$this->db->update('coll2_cat',array('deleted'=>1),"c_id={$cid}");
		
		redirect('admin/collection2');
	}
	
	function gyartocsopedit2(){
		$group_id = $this->input->post('group_id');
		$nev      = $this->input->post('nev');
		
		$azon = "";
		$subject = str_replace(' ','-',strtolower($this->input->post('azon')));
		$pattern = '/[-_a-z0-9]*/';
		preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
		foreach($matches[0] as $m)
			if($m[0])
				$azon .= $m[0];
		
		if($group_id == "uj"){
			$this->db->insert('coll2_mangrp',array('azon'=>$azon,'nev'=>$nev));
		}else{
			$this->db->update('coll2_mangrp',array('nev'=>$nev),"group_id={$group_id}");
		}
		
		redirect('admin/collection2');
	}
	
	function delmangroup2(){
		$grpid = $this->uri->segment(3);
		
		if( $grpid != "" && is_numeric($grpid) )
			$this->db->update('coll2_mangrp',array('deleted'=>1),"group_id={$grpid}");
		
		redirect('admin/collection2');
	}
	
	function gyartoedit2(){
		include('application/helpers/sajatfeltolto.php');
		$mid  = $this->input->post('mid');
		$name = $this->input->post('name');
	//	$dir  = strtolower($this->input->post('dir'));
		
		$dir = "";
		
		if($mid == "uj"){
			$dir = urlazon($this->input->post('dir'));
			
			$tomb = array('name'=>$name,'dir'=>$dir);
			if( is_array($this->input->post('group_id')) && count($this->input->post('group_id')) > 0 ){
				$tomb['group_id'] = ";";
				foreach($this->input->post('group_id') as $v){
					$tomb['group_id'] .= $v.";";
				}
			}
			
			
			$this->db->insert('coll2_man',$tomb);
			mkdir("public/img/collection/".$dir."/");
			chmod("public/img/collection/".$dir."/",0777);
			
			mkdir("public/collection/".$dir."/");
			chmod("public/collection/".$dir."/",0777);
		}else{
			$tomb = array('name'=>$name);
			
			if( is_array($this->input->post('group_id')) && count($this->input->post('group_id')) > 0 ){
				$tomb['group_id'] = ";";
				foreach($this->input->post('group_id') as $v){
					$tomb['group_id'] .= $v.";";
				}
			}elseif((hun() || eng())){
				$tomb['group_id'] = null;
			}
			
			$this->db->update('coll2_man',$tomb,"id={$mid}");
			
			$this->load->model('mcollection2');
			$gyarto = $this->mcollection2->get_manById($mid);
			$dir    = $gyarto->dir;
		}
		
		
		// gyártó logó csere
		if( $_FILES["gyartokep"]["error"]==0 ){
			$hova  = "public/img/collection/".$dir."/";
			// korábbi kép törlése
			exec("rm public/img/collection/".$dir."/logo.png");
			$ujgylogo = $hova."logo2.png";
			feltolt("gyartokep",$hova,"logo2.png",true);
			
			// átméretezés
			include('application/helpers/myimg_helper.php');
		//	kepmeretezesvagas($ujgylogo,$hova,"logo.png",237,122);
			kemeretezesvagassh($ujgylogo,$hova."logo.png",239,122);
			exec("rm public/img/collection/".$dir."/logo2.png");
			chmod($hova."logo.png",0777);
		}
		
		
		redirect('admin/collection2');
	}
	
	function delman2(){
		$mid = $this->uri->segment(3);
		
		if( $mid != "" && is_numeric($mid) )
			$this->db->update('coll2_man',array('deleted'=>1),"id={$mid}");
		
		redirect('admin/collection2');
	}
	
	function coll2tipusedit(){
		include('application/helpers/sajatfeltolto.php');
		include('application/helpers/myimg_helper.php');
		$tipus = $this->input->post('tipus');
		$ujtipus['name_eng'] = $this->input->post('name_eng');
		$ujtipus['name_hun'] = $this->input->post('name_hun');
		$ujtipus['desc_eng'] = $this->input->post('desc_eng');
		$ujtipus['desc_hun'] = $this->input->post('desc_hun');
		
		if($tipus=="new"){
			$subject = str_replace(' ','-',strtolower($this->input->post('typeurl')));
			$pattern = '/[-_a-z0-9]*/';
			preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
			$typeurl = "";
			foreach($matches[0] as $m)
				if($m[0])
					$typeurl .= $m[0];
			
			if( !$typeurl ){
				print "Hiányos vagy hibás azonosító: ".$this->input->post('typeurl');
				return;
			}
			
			
			$ujtipus['type']          = $typeurl;
			$ujtipus['type_download'] = $this->input->post('type_download');
			$this->db->insert('coll2_types',$ujtipus);
		}
		else
			$this->db->update('coll2_types',$ujtipus,"type = '{$tipus}'");
		
		// képek feltöltése
		if( $_FILES["image_eng"]["error"]==0 ){							// angol kép
			$hova  = "public/img/collection/types/";
			// korábbi kép törlése
			exec("rm public/img/collection/types/{$tipus}.png");
			$ujtipuskep = $hova."{$tipus}.png";
			feltolt("image_eng",$hova,"{$tipus}.png",true);
			
			// átméretezés
			kemeretezesvagassh($ujtipuskep,$ujtipuskep,733,468);
			chmod($ujtipuskep,0777);
		}
		if( $_FILES["image_hun"]["error"]==0 ){							// magyar kép
			$hova  = "public/img/collection/types/";
			// korábbi kép törlése
			exec("rm public/img/collection/types/{$tipus}_hun.png");
			$ujtipuskep = $hova."{$tipus}_hun.png";
			feltolt("image_hun",$hova,"{$tipus}_hun.png",true);
			
			// átméretezés
			kemeretezesvagassh($ujtipuskep,$ujtipuskep,733,468);
			chmod($ujtipuskep,0777);
		}
		
		
		redirect('admin/collection2');
		
	}
	
	
	function delobjekt2(){
		$mid  = $this->uri->segment(3);
		$this->db->update('collection2',array('deleted'=>1),"o_id={$mid}");
		redirect('admin/collection2');
	}
	
	function shwrobjfiledel(){
		$fajl = base64_decode($this->uri->segment(3));
		$path = "public/collection/";
		$fajlinfok = explode('/',$fajl);
		
		$gyartodir = $fajlinfok[0];
		$objid     = $fajlinfok[1];
		$fajlnev   = $fajlinfok[2];
		
		// jogosultság ellenőrzése
		if(ita()){
			$brands = $this->db->query("SELECT * FROM coll2_man WHERE group_id LIKE '%;2;%' AND dir='{$gyartodir}'")->row();
			if(!$brands){
				print "jogosultsági hiba";
				return;
			}
		}elseif( !hun() && !eng() ){
			print "jogosultsági hiba";
			return;
		}
		
		if(!file_exists($path.$fajl)){
			print "A fájl nem található!";
			return;
		}
		
		exec("mv {$path}{$fajl} {$path}zz_trash/{$objid}__{$fajlnev}");
		
		$this->db->query("UPDATE coll2_ver SET deleted=0 WHERE fajl='{$fajlnev}' AND o_id={$objid}");
		
		redirect('admin/col2objedit/'.$objid);
	}

	function col2objedit(){
		$this->load->model('mcollection2');
		
		if($this->input->post('do')!=false && is_numeric($_POST['oid']) ){
			include('application/helpers/sajatfeltolto.php');
			include('application/helpers/myimg_helper.php');
			$o_id = $this->input->post('oid');
			
			$ujpr->title_hun    = $_POST["name_hun"];
			$ujpr->title_eng    = $_POST["name_eng"];
		/**/	$ujpr->desc_hun	= $_POST["objectdeschun"];
		/**/	$ujpr->desc_eng	= $_POST["objectdesceng"];
			$ujpr->c_id		    = $_POST["kategoria"];
			$ujpr->tipus	    = $_POST["tipus"];
			$ujpr->rendelheto   = ($_POST["rendelheto"]=="on") ? 1 : 0;
			
			// mentés
			$this->db->update("cadline2.collection2",$ujpr,"o_id=".$o_id);
			
			// név, leírás módosítás/beszúrás
			foreach($this->collectionlangs as $nyelv){
				if( !$_POST["name_".$nyelv] && !$_POST["objectdesc".$nyelv] )
					continue;
				
				$d_id = $this->db->query("SELECT d_id FROM coll2_desc WHERE lang='{$nyelv}' AND o_id=".$o_id)->row();
				$d_id = $d_id->d_id;
				
				$ujdesc->title = $_POST["name_".$nyelv];
				$ujdesc->desc  = $_POST["objectdesc".$nyelv];
				if(!$d_id){
					$ujdesc->o_id = $o_id;
					$ujdesc->lang = $nyelv;
					$this->db->insert("cadline2.coll2_desc",$ujdesc);
					unset($ujdesc->o_id, $ujdesc->lang);
				}
				else
					$this->db->update("cadline2.coll2_desc",$ujdesc,"d_id=".$d_id);
				
			}
			
			
			$object = $this->mcollection2->get_elem($o_id);
			$gyarto = $this->mcollection2->get_manById($object->m_id);
			
			
			// új fájl
			/*if( $_FILES["fajl"]["error"]==0 ){
				$hova  = "public/collection/".$gyarto->dir."/".$o_id."/";
				$ujfajl = $hova.$_FILES["fajl"]["name"];
				feltolt("fajl",$hova,$_FILES["fajl"]["name"],true);
				chmod($ujfajl,0777);
				
				if( $_POST["verzio"]!="" && is_numeric($_POST["verzio"]) ){
					$verzio->o_id    = $o_id;
					$verzio->version = $_POST['verzio'];
					$verzio->fajl    = $_FILES["fajl"]["name"];
					$this->db->insert('cadline2.coll2_ver',$verzio);
				}
			}*/
			
			// új kis kép
			/*if( $_FILES["kep"]["error"]==0 ){
				$hova  = "public/img/collection/".$gyarto->dir."/".$o_id."/";
				// korábbi kis képek törlése
				//exec("rm public/img/collection/".$gyarto->dir."/".$o_id."/*");	// ez konyvtarat nem torol
				$ujkep = $hova.$_FILES["kep"]["name"];
				feltolt("kep",$hova,$_FILES["kep"]["name"],true);
				kemeretezesvagassh($ujkep,$hova."zz_small.jpg",79,66);		// új kis kép
				kemeretezesvagassh($ujkep,$ujkep,70,68);					// kis kép
				chmod($jkep,0777);
			}*/
			
			// új nagy (és előnézeti) kép + kis kép
			if( $_FILES["nagykep"]["error"]==0 ){
				$hova  = "public/img/collection/".$gyarto->dir."/".$o_id."/big/";
				$hova2 = "public/img/collection/".$gyarto->dir."/".$o_id."/";
				// korábbi nagy kép törlése
				exec("rm public/img/collection/".$gyarto->dir."/".$o_id."/big/*");
				exec("rm public/img/collection/".$gyarto->dir."/".$o_id."/thumb/*");
				$ujnagykep = $hova.$_FILES["nagykep"]["name"];
				$ujelonezet = "public/img/collection/".$gyarto->dir."/".$o_id."/thumb/".$_FILES["nagykep"]["name"];
				feltolt("nagykep",$hova,$_FILES["nagykep"]["name"],true);
				
				kemeretezesvagassh($ujnagykep,$hova2."zz_big.jpg",480,400);			// új nagy kép
				kemeretezesvagassh($ujnagykep,$hova2."zz_thumb.jpg",182,152);		// új előnézeti kép
				kemeretezesvagassh($ujnagykep,$hova2."zz_small.jpg",79,66);		// új kis kép
			//	kemeretezesvagassh($ujnagykep,$ujkep,70,68);					// kis kép
				kemeretezesvagassh($ujnagykep,$ujnagykep,488,396);			// regi nagy kep
				kemeretezesvagassh($ujnagykep,$ujelonezet,182,131);			// regi elonezeti kep
				chmod($ujnagykep,0777);
			}
			
			// rendelhető elemek listájának frissítése
			$this->nemrendelhetoelemek();
			
			redirect('admin/collection2');
		}
		else{
			if(hun())
				$data['title'] = 'ARCHLine.XP Objektum szerkesztés';
			else
				$data['title'] = 'ARCHLine.XP Edit Object';
			$data['admin']=true;
			$data['aktiv']=11;
			$data['tartalom']='admin/col2objedit';
			$data['csik']=array('home','admin');
			
			$data['nyelvek'] = $this->collectionlangs;
			$data['tipusok'] = $this->db->query("SELECT * FROM coll2_types ORDER BY type ASC")->result();
			
			$oid    = $this->uri->segment(3);
			$object = $this->mcollection2->get_elem($oid);
			$gyarto = $this->mcollection2->get_manById($object->m_id);
			$verziok   = $this->db->query("SELECT fajl, version FROM coll2_ver WHERE o_id={$oid} AND deleted=0")->result_array();
			
			foreach($this->collectionlangs as $nyelv){
				$tempt = 'title_'.$nyelv;
				$tempd = 'desc_'.$nyelv;
				
				$tempobj = $this->db->query("SELECT title, `desc` FROM coll2_desc WHERE lang='{$nyelv}' AND o_id=".$oid)->row();
				$object->$tempt = $tempobj->title;
				$object->$tempd = $tempobj->desc;
			}
			
			
			function fajl_ev($array){
				$vals = array();
				foreach ($array as $value) {
					$vals[$value['fajl']] = $value['version'];
				}
				return $vals;
			}
			
			if( count($verziok)>0 ){
				$verziok2 = fajl_ev($verziok);
			}
			
			
			$data['group']   = $object;
			$data['gyarto']  = $gyarto;
			$data['verziok'] = $verziok2;
			$data['fajlok']  = scandir('public/collection/'.$gyarto->dir.'/'.$oid);
			
			$data['kategoriak'] = $this->mcollection2->get_kategoriak($gyarto->dir);
				
			$this->load->view('site',$data);
		}
	}
	
	function col2brandchange(){
		$elemid = $this->uri->segment(3);
		
		// módosítás
		if($this->input->post('do')!=false && is_numeric($elemid) ){
			$newbrandkategoria = explode("*",$this->input->post('newbrandkategoria'));
			$brandid  = $newbrandkategoria[0];
			$branddir = $newbrandkategoria[1];
			$category = $newbrandkategoria[2];
			
			$alapbol = $this->db->query("SELECT * FROM collection2 WHERE o_id=".$elemid)->row();
			$olddir  = $this->db->query("SELECT dir FROM coll2_man WHERE id=".$alapbol->m_id)->row();
			$olddir  = $olddir->dir;
			
			// kategória beállítása
			$this->db->update('collection2',array('c_id'=>$category,'m_id'=>$brandid),"o_id = ".$elemid);
			
			// fájlok átmásolása
			rename("public/img/collection/{$olddir}/{$elemid}","public/img/collection/{$branddir}/{$elemid}");
			rename("public/collection/{$olddir}/{$elemid}","public/collection/{$branddir}/{$elemid}");
			
			//exec("mv -R ".PATH_WEBSITE."public/img/collection/{$olddir}/{$elemid} ".PATH_WEBSITE."public/img/collection/{$branddir}/{$elemid}");
			redirect('admin/collection2');
		}
		// űrlap
		else{
			
			$gyartok = $this->db->query("SELECT * FROM coll2_man WHERE deleted=0 ORDER BY name")->result();
			$elemek = array();
			foreach($gyartok as $gyarto){
				$kategoriak = $this->db->query("SELECT * FROM coll2_cat WHERE m_id={$gyarto->id} AND deleted=0 ORDER BY nev_hun")->result();
				foreach($kategoriak as $kategoria){
					$elemek[$gyarto->id."*".$gyarto->dir."*".$kategoria->c_id] = $gyarto->name." :: ".$kategoria->nev_hun;
				}
			}
			
			$data['gyartok'] = $elemek;
			
			$data['elem']    = $this->db->query("SELECT * FROM collection2 WHERE o_id=".$elemid)->row();
			$mostanidir      = $this->db->query("SELECT dir FROM coll2_man WHERE id=".$data['elem']->m_id)->row();
			$data['mostani'] = $data['elem']->m_id."*".$mostanidir->dir."*".$data['elem']->c_id;
			
			$data['admin']    = true;
			$data['aktiv']    = 11;
			$data['tartalom'] = 'admin/col2brandchange';
			$data['csik']     = array('home','admin');
			
			$this->load->view('site',$data);
			
		}
		
	}
	
	
	// teljes kategóriát áttenni másik márkához
	function col2categorybrandchange(){
		$catid = $this->uri->segment(3);
		
		// módosítás
		if($this->input->post('do')!=false && is_numeric($catid) ){
			$newbrandkategoria = explode("*",$this->input->post('newbrandkategoria'));
			$brandid  = $newbrandkategoria[0];
			$branddir = $newbrandkategoria[1];
			$category = $newbrandkategoria[2];
			
			$katelemek = $this->db->query("SELECT * FROM collection2 WHERE c_id=".$catid)->result();
			$olddir  = $this->db->query("SELECT dir FROM coll2_man WHERE id=".$katelemek[0]->m_id)->row();
			$olddir  = $olddir->dir;
			
			// kategória beállítása
			$this->db->update('collection2',array('c_id'=>$category,'m_id'=>$brandid),"c_id = ".$catid);
			
			// fájlok átmásolása
			foreach($katelemek as $elem){
				rename("public/img/collection/{$olddir}/{$elem->o_id}","public/img/collection/{$branddir}/{$elem->o_id}");
				rename("public/collection/{$olddir}/{$elem->o_id}","public/collection/{$branddir}/{$elem->o_id}");
			}
			
			//exec("mv -R ".PATH_WEBSITE."public/img/collection/{$olddir}/{$elemid} ".PATH_WEBSITE."public/img/collection/{$branddir}/{$elemid}");
			redirect('admin/collection2');
		}
		// űrlap
		else{
			
			$gyartok = $this->db->query("SELECT * FROM coll2_man WHERE deleted=0 ORDER BY name")->result();
			$elemek = array();
			foreach($gyartok as $gyarto){
				$kategoriak = $this->db->query("SELECT * FROM coll2_cat WHERE m_id={$gyarto->id} AND deleted=0 ORDER BY nev_hun")->result();
				foreach($kategoriak as $kategoria){
					$elemek[$gyarto->id."*".$gyarto->dir."*".$kategoria->c_id] = $gyarto->name." :: ".$kategoria->nev_hun;
				}
			}
			
			$data['gyartok'] = $elemek;
			
			$data['elem']    = $this->db->query("SELECT * FROM coll2_cat WHERE c_id=".$catid)->row();
			$mostanidir      = $this->db->query("SELECT dir FROM coll2_man WHERE id=".$data['elem']->m_id)->row();
			$data['mostani'] = $data['elem']->m_id."*".$mostanidir->dir."*".$data['elem']->c_id;
			
			$data['admin']    = true;
			$data['aktiv']    = 11;
			$data['tartalom'] = 'admin/col2categorybrandchange';
			$data['csik']     = array('home','admin');
			
			$this->load->view('site',$data);
			
		}
		
	}
	
	// public/collection/nemrendelhetoelemek.txt újra generálása
	function nemrendelhetoelemek(){
		$nemrendelhetoelemekfajl = 'public/collection/nemrendelhetoelemek.txt';
		exec('rm '.$nemrendelhetoelemekfajl);
		exec('touch '.$nemrendelhetoelemekfajl);
		
		$gyartok = $this->db->query("SELECT id, dir FROM coll2_man")->result();
		$gyartoktmp = array();
		foreach($gyartok as $gyarto){
			$gyartoktmp[$gyarto->id] = $gyarto->dir;
		}
		$gyartok = $gyartoktmp;
		
		$elemek = $this->db->query("SELECT o_id, m_id FROM collection2 WHERE rendelheto=0 AND deleted=0")->result();
		
		$utvonal = 'public/collection/';
		foreach($elemek as $elem){
			$fajlokmappa = $utvonal.$gyartok[$elem->m_id]."/".$elem->o_id."/";
			$fajlok = scandir($fajlokmappa);
			unset($fajlok[0],$fajlok[1]);	// . és .. törlése
		/*	unset($fajlok[array_search('.', $fajlok)]);
			unset($fajlok[array_search('..', $fajlok)]);*/
			foreach($fajlok as $fajl){
				if(!is_dir($fajlokmappa.$fajl)){
					exec('echo "'.$fajl.'" >> '.$nemrendelhetoelemekfajl);
				}
			}
		}
	}
	
	function coll2stat(){
		$this->load->model('mcollection2');
		
		$gyartolimit = array( "ita" => "cadlinesw", "ger" => "itc" );
		$adminlang = $this->muser->user['lang'];
		
		if( array_key_exists($adminlang, $gyartolimit) ){
			$gyartok[0] = $this->mcollection2->get_manBydir($gyartolimit[$adminlang]);
		}else{
			$gyartok = $this->mcollection2->get_gyartok();
		}
		
		$statisztika = array();
		
		foreach($gyartok as $gyarto){
			$statisztika[$gyarto->name] = array();
			$statisztika[$gyarto->name]["letoltvedarab"] = 0;
			$statisztika[$gyarto->name]["megnezvedarab"] = 0;
			
			$kategoriak = $this->mcollection2->get_kategoriak($gyarto->dir);
			foreach($kategoriak as $kategoria){
				$parancs = "SELECT SUM(down) letoltve, SUM(`show`) megnezve FROM collection2 WHERE c_id=".$kategoria->c_id." AND deleted=0";
				$db = $this->db->query($parancs)->row();
				$statisztika[$gyarto->name][$kategoria->nev_eng]["letoltvedarab"] = $db->letoltve;
				$statisztika[$gyarto->name][$kategoria->nev_eng]["megnezvedarab"] = $db->megnezve;
				
				$statisztika[$gyarto->name]["letoltvedarab"] += $db->letoltve;
				$statisztika[$gyarto->name]["megnezvedarab"] += $db->megnezve;
				
			}
		}
		
	//	print "<pre>";
	//	print_r($statisztika);
		
		$this->load->library('Excel');
		
		$workbook = new Excel();
		
		//sending header and creating a worksheet
		$workbook->send('showroom_stat.xls');
		$workbook->setVersion(8);
		$worksheet =& $workbook->addWorksheet('Showroom Download Stats');

		//setting encoding
		$worksheet->setInputEncoding('UTF-8');

		//bold formating
		$fm_ttl =& $workbook->addFormat();
		$fm_ttl->setBold();
		$fm_ttl->setAlign('equal_space');
		
		//set the titles
		$worksheet->write(0, 0, 'Gyártó',    $fm_ttl);
		$worksheet->write(0, 1, 'Kategória', $fm_ttl);
		$worksheet->write(0, 2, 'Letöltve',  $fm_ttl);
		$worksheet->write(0, 3, 'Megtekintve', $fm_ttl);
		
		//populate the worksheet
		$i = 1;
		foreach($statisztika as $k=>$s)
		{
			$worksheet->write($i, 0, "");
			$worksheet->write($i, 1, "");
			$worksheet->write($i, 2, "");
			$worksheet->write($i, 3, "");
			
			$i++;
			
			$worksheet->write($i, 0, $k);
			$worksheet->write($i, 1, "összesen");
			$worksheet->write($i, 2, $s["letoltvedarab"]);
			$worksheet->write($i, 3, $s["megnezvedarab"]);
            $i++;
			
			foreach($s as $k2=>$s2){
				if( $k2 == "letoltvedarab" || $k2 == "megnezvedarab" )
					continue;
				
				$worksheet->write($i, 0, "");
				$worksheet->write($i, 1, $k2);
				$worksheet->write($i, 2, $s2["letoltvedarab"]);
				$worksheet->write($i, 3, $s2["megnezvedarab"]);
				$i++;
			}
		}

		$workbook->close();
		
	}
	
	function videok(){
		$nyelv = hun() ? "hun" : "eng";
		$oktatovideokt = $this->db->query("SELECT * FROM videos WHERE sorszam>0 AND nyelv='{$nyelv}' ORDER BY sorszam")->result();
		$oktatovideok = array();
		foreach($oktatovideokt as $video){
			$csoport = $video->csoport;
			if( !is_array($oktatovideok[$csoport]) )
				$oktatovideok[$csoport] = array();
			
			$oktatovideok[$csoport][] = $video;
		}
		
		$ovcsoportok = $this->db->query("SELECT * FROM videogroups WHERE nyelv='{$nyelv}'")->result();
		
		$data['oktatovideok'] = $oktatovideok;
		$data['ovcsoportok']  = $ovcsoportok;
		$data['admin']        = true;
		$data['aktiv']        = 5;
		
		$data['title'] = hun() ? 'ARCHLine.XP Oktatóvideók' : 'ARCHLine.XP videos';
        $data['tartalom']='admin/videok';
		
		$this->load->view('site',$data);
		
	}
	
	function set_oktatovideok(){
		// videók módosítása
		include('application/helpers/sajatfeltolto.php');
		include('application/helpers/myimg_helper.php');
		$videokdb = $this->input->post('videokdb');
		$lang = hun() ? "hun" : "eng";
		for($i=0;$i<$videokdb;$i++){
			$video = new stdClass();
			$video->vid_id  = $this->input->post('vid_id'.$i);
			$video->sorszam = $this->input->post('vidsorszam'.$i);
			$video->youtubeid = $this->input->post('vidyoutube'.$i);
			$video->kep     = $this->input->post('vidkep'.$i);
			$video->cim     = $this->input->post('vidcim'.$i);
			$video->leiras  = $this->input->post('vidleiras'.$i);
			$video->csoport = $this->input->post('csoport'.$i);
			$torles  = $this->input->post('viddel'.$i);
			
			
			$kepuj = 'vidkep'.$i;
			
			if( $torles == "on" )
				$video->sorszam = 0;
			
			
			$utvonal = 'public/img/welcome/'.$lang.'/';
			
		//	$this->kep3(&$kepuj,$utvonal,'vidkep'.$i);
			if ($_FILES['vidkep'.$i]["error"]==0){
				$kepuj = feltolt('vidkep'.$i,$utvonal,$_FILES['vidkep'.$i]["name"],true);
				kemeretezesvagassh($kepuj,$kepuj,60,48);
			}
			
			if( $kepuj != ('vidkep'.$i) ){
				$video->kep = $kepuj;
			}else{
				unset($video->kep);
			}
			unset($kepuj);
			
			if($video->vid_id){
				$this->db->update('videos',$video,"vid_id={$video->vid_id}");
		//		print "<br>".$this->db->last_query();
			}
		}
		
		
		// új videó
		$uj = $this->input->post('ujviddel');
		if( /*isset($_POST['ujviddel']) &&*/ $uj != "on" ){
			$record->sorszam = $this->input->post('ujvidsorszam');
			$record->youtubeid = $this->input->post('ujvidyoutube');
			$record->cim     = $this->input->post('ujvidcim');
			$record->leiras  = $this->input->post('ujvidleiras');
			$record->csoport = $this->input->post('ujvidcsoport');
			$record->nyelv   = $lang;
			
			$kepuj = '';
			
			$record->nyelv = $lang;
			
			$utvonal = 'public/img/welcome/'.$lang.'/';
			
			//$this->kep3(&$kepuj,$utvonal,'ujvidkep');
			if ($_FILES['ujvidkep']["error"]==0){
				$kepuj = feltolt('ujvidkep',$utvonal,$_FILES['ujvidkep']["name"],true);
				kemeretezesvagassh($kepuj,$kepuj,60,48);
			}
			
			if( $kepuj != '' ){
				$record->kep = $kepuj;
			}
			
			$this->db->insert('`videos`',$record);
		}
		
	//	print_r($_POST);
		
		redirect('admin/videok');
	}
	
	function set_videokcsoport(){
		// csoportok módosítása
		$csoportokdb = $this->input->post('csoportokdb');
		$lang = hun() ? "hun" : "eng";
		for($i=0;$i<$csoportokdb;$i++){
			$csoport = new stdClass();
			$csoport->vg_id  = $this->input->post('vg_id'.$i);
			$csoport->cim    = $this->input->post('csopcim'.$i);
			$csoport->leiras = $this->input->post('csopleiras'.$i);
			
			if($csoport->vg_id){
				$this->db->update('videogroups',$csoport,"vg_id={$csoport->vg_id}");
			}
		}
		
		$uj = $this->input->post('ujcsoportdel');
		if( $uj != "on" ){
			$record = new stdClass();
			$record->azon   = trim($this->input->post('ujcsopazon'),'#');
			$record->cim    = $this->input->post('ujcsopcim');
			$record->leiras = $this->input->post('ujcsopleiras');
			$record->nyelv  = $lang;
			
			$this->db->insert('videogroups',$record);
		}
		
		redirect('admin/videok');
	}
	
	function viewer(){
		$vendegek2 = $this->db->query( "SELECT cp_id, guestname, mappa FROM collection_projects WHERE userid='guest' AND deleted=0 GROUP BY guestname ORDER BY guestname ASC")->result();
		$projektek = array();
		
		foreach($vendegek2 as $vendeg){
			$vendeg->projektek = $this->db->query( "SELECT * FROM collection_projects WHERE userid='guest' AND guestname='{$vendeg->guestname}' AND deleted=0 AND cp_id IN (SELECT DISTINCT(cp_id) FROM collection_user WHERE userid='guest' AND deleted=0) ORDER BY nev ASC")->result();
			$vendeg->darab = 0;
			foreach($vendeg->projektek as $projekt){
				$projektek[] = $projekt;
				$projekt->fajlok  = $this->db->query( "SELECT * FROM collection_user WHERE cp_id={$projekt->cp_id} AND deleted=0 ORDER BY title ASC")->result();
				if( !$projekt->fajlok )
					$projekt->fajlok = array();
				$projekt->darab = count($projekt->fajlok);
				$vendeg->darab  += $projekt->darab;
			}
		}
		
		$data['guests'] = $vendegek2;
		$data['projektek'] = $projektek;
		/*$data['main_events_json'] = json_encode($vendegek2);*/
		
		$elemek = $this->db->query("SELECT cu_id, cp_id, title, `desc`, shared FROM collection_user WHERE `deleted`=0")->result();
		$data['elemek_json'] = json_encode($elemek);
		
		$data['admin']    = true;
		$data['aktiv']    = 15;
		$data['javascript'] = array('jquery_ui');
		$data['style']    = array('jquery.ui');
		$data['title']    = "ARCHLine View App edit";
		$data['tartalom'] = 'admin/viewer';
		$this->load->view('site', $data);
	}
	
	function viewguestnameedit(){
		$guestname = $this->input->post('guestname');
		$uj['guestname'] = $this->input->post('name');
		
		$this->db->update('collection_projects',$uj,'guestname="'.$guestname.'"');
		
		redirect('admin/viewer');
	}
	
	function viewguestnamedel(){
		$cp_id = $this->uri->segment(3);
		$guestnamet = $this->db->query("SELECT guestname, mappa FROM collection_projects WHERE cp_id={$cp_id}")->row();
		$guestname  = $guestnamet->guestname;
		$uj['deleted'] = 1;
		
		$this->db->update('collection_projects',$uj,'userid="guest" AND guestname="'.$guestname.'"');
		
		// kukába áttenni a projekteket
		$guestdir = current(explode('/',$guestnamet->mappa));
		$utvonal = "public/img/collection/users/guest/".$guestdir."/";
		$trash       = 'public/img/collection/users/trash/guest/';
		$guestmappa = scandir($utvonal);
		unset($guestmappa[0],$guestmappa[1]);
		foreach($guestmappa as $projekt){
			mkdir("{$trash}{$guestdir}");
			mkdir("{$trash}{$guestdir}/".$projekt);
			exec("cp -R {$utvonal}{$projekt} {$trash}{$guestdir}");
			exec("rm -R {$utvonal}{$projekt}");
		}
		
		redirect('admin/viewer');
	}
	
	function viewprojectnameedit(){
		$cp_id         = $this->input->post('cp_id');
		$uj['nev']     = $this->input->post('nev');
		$uj['autodel'] = ($this->input->post('autodel')=="on") ? 1 : 0;
		
		$this->db->update('collection_projects',$uj,'cp_id='.$cp_id);
		
		redirect('admin/viewer');
	}
	
	function viewguestprojectdel(){
		$cp_id = $this->uri->segment(3);
		$uj['deleted'] = 1;
		$this->db->update('collection_projects',$uj,'cp_id='.$cp_id);
		
		$infok = $this->db->query("SELECT mappa FROM collection_projects WHERE cp_id={$cp_id}")->row();
		$mappa = current(explode('/',$infok->mappa));
		$trash = 'public/img/collection/users/trash/guest/';
		$prutvonal = "public/img/collection/users/guest/".$infok->mappa;
		
		// kukába áttenni a projektet
		mkdir("{$trash}{$mappa}");
		mkdir($trash.$infok->mappa);
		exec("cp -R {$prutvonal} ".$trash.$mappa);
		exec("rm -R {$prutvonal}");
		
		redirect('admin/viewer');
	}
	
	function viewitemedit(){
		$cu_id     = $this->input->post('cu_id');
		$uj['title'] = $this->input->post('it_title');
		$uj['desc']  = $this->input->post('it_desc');
		$cp_id       = $this->input->post('it_cp_id');
		
		if($_FILES['ujfajl']['error']==0){
			include('application/helpers/sajatfeltolto.php');
			$sql = "SELECT mappa FROM collection_projects WHERE cp_id=(SELECT cp_id FROM collection_user WHERE cu_id={$cu_id})";
			$adatok = $this->db->query($sql)->row();
			$hova   = "public/img/collection/users/guest/".$adatok->mappa."/".$cu_id."/";
			$kepnev = $_FILES['ujfajl']["name"];
			
			if(feltolt('ujfajl',$hova,$kepnev,true)){
				include('application/helpers/myimg_helper.php');
				// kulonbozo kepmeretek letrehozasa
				exec("cp {$hova}{$kepnev} {$hova}1__big.jpg");
				exec("cp {$hova}{$kepnev} {$hova}1__1024.jpg");
				kemeretezesvagassh($hova.$kepnev,$hova."1__300.jpg",300,225);
				kemeretezesvagassh($hova.$kepnev,$hova."1__small.jpg",79,66);
				
				$uj['file'] = $kepnev;
			}else{
				print "A kep feltoltese kozben hiba tortent! Nem sikerult modositani az adatokat!";
				return;
			}
		}
		
		$adatok2 = $this->db->query("SELECT cp_id FROM collection_user WHERE cu_id={$cu_id}")->row();
		// más projektbe áthelyezés
		if($cp_id!=$adatok2->cp_id){
			$ujpr =  $this->db->query("SELECT * FROM collection_projects WHERE cp_id={$cp_id}")->row();
			$regipr =  $this->db->query("SELECT * FROM collection_projects WHERE cp_id=".$adatok2->cp_id)->row();
			
			$honnan = "public/img/collection/users/guest/".$regipr->mappa."/".$cu_id;
			$hova   = "public/img/collection/users/guest/".$ujpr->mappa;
			
			mkdir($hova."/".$cu_id);
			exec("cp -R {$honnan} {$hova}");
			exec("rm -R {$honnan}");
			
			if(file_exists($hova."/".$cu_id."/1__300.jpg"))
				$uj['cp_id'] = $cp_id;
		}
		
		$this->db->update('collection_user',$uj,'cu_id='.$cu_id);
		
		redirect('admin/viewer');
	}
	
	function viewitemdel(){
		$cu_id = $this->uri->segment(3);
		$uj['deleted'] = 1;
		$this->db->update('collection_user',$uj,'cu_id='.$cu_id);
		
		$infok = $this->db->query("SELECT mappa FROM collection_projects WHERE cp_id=(SELECT cp_id FROM collection_user WHERE cu_id={$cu_id})")->row();
		$trash = 'public/img/collection/users/trash/guest/';
		$elemutvonal = "public/img/collection/users/guest/".$infok->mappa."/".$cu_id;
		
		// attenni a trash/guest-be
		mkdir("{$trash}{$cu_id}");
		exec("cp -R {$elemutvonal} ".$trash);
		exec("rm -R {$elemutvonal}");
		
		redirect('admin/viewer');
	}
	
	function viewerstat(){
		$sql = "SELECT count(cu_id) db, nev FROM `collection_user` v INNER JOIN forum_user ON userid=user_id WHERE v.deleted=0 AND cp_id IN (SELECT cp_id FROM collection_projects WHERE deleted=0) GROUP BY nev";
		$ered = $this->db->query($sql)->result();
		print "<table>";
		foreach($ered as $v){
			print "<tr><td>".$v->nev.": </td><td>".$v->db." db elem</td></tr>";
		}
		print "</table>";
	}
	
	
	function crashlist(){
		$adatok = $this->db->query("SELECT * FROM crash WHERE deleted=0 ORDER BY datum DESC LIMIT 0,1000")->result();
		$data['adatok'] = $adatok;
		
		$data['javascript'] = array('jquery_ui','tablesorter/jquery.tablesorter.min','DataTables/media/js/jquery.dataTables');
		$data['style']    = array('jquery.ui','../js/tablesorter/themes/blue/style','../js/DataTables/media/css/demo_table');
		$data['admin']    = true;
		$data['title']    = "ARCHLine crash list";
		$data['tartalom'] = 'admin/crashlist';
		$this->load->view('site', $data);
	}
	
	function crashedit(){
		$id = $this->uri->segment(3);
		
		if( isset($_POST['do']) && $_POST['do']=='do' ){
			$uj['statusz'] = $this->input->post('statusz');
			$uj['info']    = $this->input->post('info');
			$this->db->update('crash',$uj,'id='.$id);
			redirect('admin/crashlist');
		}else{
			$data['crash'] = $this->db->query("SELECT * FROM crash WHERE id=".$id)->row();
			$this->load->view('admin/crashedit', $data);
		}
	}
	
	function crashdel(){
		$id = $this->uri->segment(3);
		$uj['deleted'] = 1;
		$this->db->update('crash',$uj,'id='.$id);
		redirect("admin/crashlist");
	}
	
	function serial2(){
		$adatok = $this->db->query("SELECT * FROM download_serial ORDER BY datum ASC")->result();
		$data['adatok'] = $adatok;
		
		$data['javascript'] = array('jquery_ui','DataTables/media/js/jquery.dataTables.min');
		$data['style']    = array('jquery.ui','../js/DataTables/media/css/demo_table');
		$data['admin']    = true;
		$data['tartalom'] = 'admin/serial2';
		$this->load->view('site', $data);
	}

	function kodgeneralohibak(){
		$hibalista = $this->db->query("SELECT * FROM `clusers`.`cl_aktkod_hibak` WHERE torolve=0 AND leiras NOT LIKE 'felvettem: UPDATE%'")->result();
		$data['hibalista'] = $hibalista;
		
		$data['javascript'] = array('jquery_ui','DataTables/media/js/jquery.dataTables.min');
		$data['style']    = array('jquery.ui','../js/DataTables/media/css/demo_table');
		$data['admin']    = true;
		$data['tartalom'] = 'admin/kodgeneralohibak';
		$this->load->view('site', $data);
	}
	
}

function hasonlito( $a, $b ){
	if ( $a->tulaj == $b->tulaj )
		return 0;
	if ( $a->tulaj < $b->tulaj )
		return -1;
	return 1;
}

function hasonlitovissza( $a, $b ){
	if ( $a->tulaj == $b->tulaj )
		return 0;
	if ( $a->tulaj > $b->tulaj )
		return -1;
	return 1;
}

?>