<?php
/*
Slovenski narečni atlas / Slovenian dialectal atlas
    Copyright (C) 2017  Gregor Šajn

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends CI_Controller {

	function __construct() 
	{
		parent::__construct();

		$this->url=base_url().'admin/';

		$this->load->model('admin_model');
		$this->load->model('home_model');
    }

	public function index()
	{
		$data=array(
			'title'=>'Nadzorna plošča',
		);

		$this->check_user();
		
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['subjects']=$this->home_model->subjects(false);
		$data['tab']='my_profile';

		//check session

		if(isset($_SESSION['errfields']))
		{
			$data['errfields'] = $_SESSION['errfields'];
			unset($_SESSION['errfields']);
		}

		if(isset($_SESSION['status']))
		{
			$data['status'] = $_SESSION['status'];
			unset($_SESSION['status']);
		}

		
		$this->load_master_view('admin/edit_my_profile_view.php',$data);
	}

	function login()
	{
		$data=array(
			'title'=>'Prijava',
			'uri'=>$this->url.'post_login',
			'error'=>'',
		);

		$this->load_master_view('admin/login_view.php',$data);
	}

	function post_login()
	{
		$data['username']=$this->input->post('username',true);
		$data['password']=$this->input->post('password',true);

		//check if user is in db
		$user=$this->admin_model->perform_login($data['username'],$data['password']);

		if($user)
		{
			//user exists - create session and redirect
			$this->session->set_userdata(array(
				'uid'=>$user['id'],
				'name'=>$user['name'],
				'lastname'=>$user['lastname'],
				'username'=>$user['username'],
				'sess_expiration'=>$user['sess_expiration'],
			));

			redirect('admin');
		}
		else
		{
			//user doesn't exist, return error
			$data=array(
				'title'=>'Prijava',
				'uri'=>$this->url.'post_login',
				'errfields'=>'Vnesli ste napačno uporabniško ime ali geslo!',
			);

			$this->load_master_view('admin/login_view.php',$data);
		}
	}

	function logout()
	{
		//destroy session and redirect to login
		$this->session->sess_destroy();

		redirect('admin/login');
	}

	function post_edit_my_profile()
	{
		$pass1=(string)$this->input->post('pass1',true);
		$pass2=(string)$this->input->post('pass2',true);
		$id_user=$this->input->post('id_user',true);

		if($pass1=='' or $pass2=='')
		{
			$data['errfields']['not_equal']='Obe vnosni polji za geslo morata biti izpolnjeni!';
		}
		else
		{
			if(strcmp($pass1,$pass2)!==0)
			{
				$data['errfields']['not_equal']='Gesli se ne ujemata!';
			}
			else
			{
				if(strlen($pass1)<6)
				{
					$data['errfields']['pass_short']='Geslo mora vsebovati najmanj 6 znakov!';
				}
			}
		}

		if(!isset($data['errfields']))
		{
			//make hash
			$hash=password_hash($pass1,PASSWORD_DEFAULT);

			//update db
			$this->db->where('id',$id_user);
			$this->db->update('users',array('password_hash'=>$hash));

			$data['status']='ok';

			//set to session
			$_SESSION['status']=$data['status'];
		}
		else
		{
			//set to session
			$_SESSION['errfields']=$data['errfields'];
		}

		redirect($this->url);
	}


	function edit_content()
	{
		$this->check_user();

		$data=array(
			'title'=>'Urejanje vsebine',
		);

		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['subjects']=$this->home_model->subjects(false);
		$data['tab']='subjects_words';

		if(isset($_SESSION['status']))
		{
			$data['status'] = $_SESSION['status'];
			unset($_SESSION['status']);
		}

		
		$this->load_master_view('admin/subjects_view.php',$data);
	}

	function add_subject()
	{
		$this->check_user();

		//load basic data
		$data['title']='Dodajanje teme';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='subjects_words';

		$data['errfields']=$this->session->flashdata('errfields');

		$data['subject']=array('title'=>'');

		$this->load_master_view('admin/add_subject_view.php',$data);
	}

	function post_add_subject()
	{

		$title=$this->input->post('title',true);
		$save_close=$this->input->post('save_close',true);

		//save post to session
		$data=array(
			'title'=>$title,
		);

		$this->session->set_flashdata('add_subject',$data);

		//check

		if(!$title)
		{
			$data['errfields']['no_title']='Naziv teme je prazen!';
		}
		else
		{
			$exists=$this->admin_model->subject_title_exists($title,0);
			if($exists)
			{
				$data['errfields']['title_exists']='Tema s tem nazivom že obstaja!';
			}
		}


		if(!isset($data['errfields']))
		{
			$this->db->insert('subjects',$data);
			$id_subject=$this->db->insert_id();

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'edit_content/');
			}
			else
			{
				redirect($this->url.'edit_subject/'.$id_subject);
			}

			
		}
		else
		{

			$this->session->set_flashdata('errfields',$data['errfields']);

			redirect($this->url.'add_subject/');
		}
	}


	function edit_subject()
	{
		$this->check_user();

		$id_subject=$this->uri->segment(3);

		//load basic data
		$data['title']='Urejanje teme';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);

		$data['subject']=$this->admin_model->subject($id_subject);
		$data['tab']='subjects_words';

		if($data['subject'])
		{
			//load words
			$data['words']=$this->home_model->subject_words($id_subject,false);

			foreach($data['words'] as &$word)
			{
				$word['modal_image_target']='#modal_image-'.$word['id'];
				$word['modal_comment_target']='#modal_comment-'.$word['id'];
			}

			$data['view_images']=$this->load->view('admin/image_popup_view.php',$data,true);
			$data['view_comments']=$this->load->view('admin/comment_popup_view.php',$data,true);

			if(isset($_SESSION['errfields']))
			{
				$data['errfields'] = $_SESSION['errfields'];
				unset($_SESSION['errfields']);
			}

			if(isset($_SESSION['status']))
			{
				$data['status'] = $_SESSION['status'];
				unset($_SESSION['status']);
			}


			$this->load_master_view('admin/edit_subject_view.php',$data);
		}
		else
		{
			$data['tab']='words_subjects';
			$data['text']='Izbran vnos teme ne obstaja!';
			$data['link_back']=$this->url.'edit_content';
			$this->load_Master_view('no_content_error.php',$data);
		}	
	}

	function subject_delete()
	{
		$this->check_user();

		$id_subject=$this->uri->segment(3);

		//check links
		$subject_links=$this->admin_model->subject_links($id_subject);

		if($subject_links)
		{
			$data['errfields']['links']="Tema ima povezave: <ul>
				<li>Besede: ".$subject_links."</li>
			</ul>";
		}

		if(!isset($data['errfields']))
		{
			//delete possible subject_locations
			/*$this->db->select('*');
			$this->db->from('subject_locations');
			$this->db->where('id_subject',$id_subject);
			$subject_locations=$this->db->get()->result_array();

			foreach($subject_locations as $entry)
			{
				$this->db->where('id',$entry['id']);
				$this->db->delete('subject_locations');
			}*/

			//remove subject
			$this->db->where('id',$id_subject);
			$this->db->delete('subjects');

			$data['status']='ok';

			$_SESSION['status']=$data['status'];

			redirect($this->url.'edit_content/');
		}
		else
		{
			$_SESSION['errfields']=$data['errfields'];

			redirect($this->url.'/edit_subject/'.$id_subject);
		}	
	}

	function add_word()
	{
		$this->check_user();

		$id_subject=$this->uri->segment(3);

		//load basic data
		$data['title']='Dodajanje besede';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='subjects_words';

		//subject data
		$data['subject']=$this->admin_model->subject($id_subject);

		$data['errfields']=$this->session->flashdata('errfields');

		$data['word']=array(
			'title'=>'',
			'image'=>'',
			'comment'=>'',
			'id_subject'=>$id_subject,
		);

		$this->load_master_view('admin/add_word_view.php',$data);
	}

	function post_add_word()
	{
		$this->check_user();

		$id_subject=$this->input->post('id_subject',true);
		$title=$this->input->post('title',true);
		$save_close=$this->input->post('save_close',true);

		if($title=='')
		{
			$data['errfields']['no_title']='Naziv besede je prazen!';
		}
		else
		{
			$exists=$this->admin_model->words_title_exists($title,$id_word,$id_subject);
			if($exists)
			{
				$data['errfields']['title_exists']='Beseda s tem nazivom v tej temi že obstaja!';
			}
		}

		if($_FILES and !isset($data['errfields']))
		{
			//image
			if($_FILES['image_file']['size'])
			{
				$image_file_type = pathinfo($_FILES["image_file"]["name"],PATHINFO_EXTENSION);
	
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $title);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$image_dir = "images/words/";
				$image_file = $image_dir.basename(strtolower($file_name).'_'.time().'.'.$image_file_type);
				$image_upload_ok = 1;

				// Check if image file is a actual image or fake image
				if(isset($_POST["submit"])) 
				{
				    $check = getimagesize($_FILES["image_file"]["tmp_name"]);
				    if($check === false) {
				    	$data['errfields']['not_image']='Izbrana slika ni slika!';
				        $image_upload_ok = 0;
				    }
				}
				if (file_exists($image_file)) 
				{
					$data['errfields']['image_exists']='Slika že obstaja!';
				    $image_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["image_file"]["size"] > 5000000) {
					$data['errfields']['image_size']='Slika je prevelika, največja velikost slike je 5 MB!';
				    $image_upload_ok = 0;
				}
				//tip datoteke
				if($image_file_type != "jpg" && $image_file_type != "png" && $image_file_type != "jpeg" && $image_file_type != "PNG" && $image_file_type != "JPEG" && $image_file_type != "JPG" && $image_file_type != "GIF"
				&& $image_file_type != "gif" ) {
					$data['errfields']['image_format']='Izbrana slika ni ustreznega slikovnega formata! Dovoljeni so jpg, png, jpeg in gif formati.';
				    $image_upload_ok = 0;
				}
				//
				if ($image_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["image_file"]["tmp_name"], $image_file)) 
					{
						$data['image']=$image_file;
				    }
				    else 
				    {
				    	$data['errfields']['image_not_uploaded']='Slika se ni pravilno naložila!';
				    }
				}
			}

			//comment
			if($_FILES['comment_file']['size'])
			{
				$comment_file_type = pathinfo($_FILES["comment_file"]["name"],PATHINFO_EXTENSION);
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $title);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$comment_dir = "comments/";
				$comment_file = $comment_dir.basename(strtolower($file_name).'_'.time().'.'.$comment_file_type);
				$comment_upload_ok = 1;

				// Check if image file is a actual image or fake image
				if (file_exists($comment_file)) 
				{
					$data['errfields']['comment_exists']='Komentar že obstaja!';
				    $comment_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["comment_file"]["size"] > 10000000) {
					$data['errfields']['comment_size']='Komentar je prevelik, največja velikost datoteke je 10 MB!';
				    $comment_upload_ok = 0;
				}
				//tip datoteke
				if($comment_file_type != "pdf" && $comment_file_type != "PDF") {
					$data['errfields']['comment_format']='Izbrani komentar ni ustreznega formata! Dovoljen je samo PDF format.';
				    $comment_upload_ok = 0;
				}
				//
				if ($comment_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["comment_file"]["tmp_name"], $comment_file)) 
					{
						$data['comment']=$comment_file;
				    }
				    else 
				    {
				    	$data['errfields']['comment_not_uploaded']='Komentar se ni pravilno naložil!';
				    }
				}
			}
		}

		if(!isset($data['errfields']))
		{
			$data['id_subject']=$id_subject;
			$data['title']=$title;

			//update 
			$this->db->insert('words',$data);
			$id_word=$this->db->insert_id();

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'edit_subject/'.$id_subject);
			}
			else
			{
				redirect($this->url.'edit_word/'.$id_word);
			}

		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);
			redirect($this->url.'add_word/'.$id_subject);
		}

		
	}

	function edit_word()
	{
		$this->check_user();

		$id_word=$this->uri->segment(3);

		//load basic data
		$data['title']='Urejanje besede';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='subjects_words';

		$data['word']=$this->admin_model->word($id_word);

		if($data['word'])
		{
			$data['subject']=$this->admin_model->subject($data['word']['id_subject']);

			
			//next request
			if(isset($_SESSION['errfields']))
			{
				$data['errfields'] = $_SESSION['errfields'];
				unset($_SESSION['errfields']);
			}
			if(isset($_SESSION['status']))
			{
				$data['status'] = $_SESSION['status'];
				unset($_SESSION['status']);
			}

			$this->load_master_view('admin/edit_word_view.php',$data);	
		}
		else
		{
			$data['text']='Izbran vnos besede ne obstaja!';
			$data['link_back']=$this->url.'edit_content';
			$this->load_master_view('no_content_error.php',$data);
		}
	}

	function post_edit_word()
	{
		$this->check_user();

		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);
		$title=$this->input->post('title',true);
		$save_close=$this->input->post('save_close',true);

		if($title=='')
		{
			$data['errfields']['no_title']='Naziv besede je prazen!';
		}
		else
		{
			$exists=$this->admin_model->words_title_exists($title,$id_word,$id_subject);
			if($exists)
			{
				$data['errfields']['title_exists']='Beseda s tem nazivom v tej temi že obstaja!';
			}
		}

		if($_FILES and !isset($data['errfields']))
		{
			//image
			if($_FILES['image_file']['size'])
			{
				$image_file_type = pathinfo($_FILES["image_file"]["name"],PATHINFO_EXTENSION);
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $title);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$image_dir = "images/words/";
				$image_file = $image_dir.basename(strtolower($file_name).'_'.time().'.'.$image_file_type);
				$image_upload_ok = 1;

				// Check if image file is a actual image or fake image
				if(isset($_POST["submit"])) 
				{
				    $check = getimagesize($_FILES["image_file"]["tmp_name"]);
				    if($check === false) {
				    	$data['errfields']['not_image']='Izbrana slika ni slika!';
				        $image_upload_ok = 0;
				    }
				}
				if (file_exists($image_file)) 
				{
					$data['errfields']['image_exists']='Slika že obstaja!';
				    $image_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["image_file"]["size"] > 5000000) {
					$data['errfields']['image_size']='Slika je prevelika, največja velikost slike je 5 MB!';
				    $image_upload_ok = 0;
				}
				//tip datoteke
				if($image_file_type != "jpg" && $image_file_type != "png" && $image_file_type != "jpeg" && $image_file_type != "PNG" && $image_file_type != "JPEG" && $image_file_type != "JPG" && $image_file_type != "GIF"
                    && $image_file_type != "gif" ) {
					$data['errfields']['image_format']='Izbrana slika ni ustreznega slikovnega formata! Dovoljeni so jpg, png, jpeg in gif formati.';
				    $image_upload_ok = 0;
				}
				//
				if ($image_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["image_file"]["tmp_name"], $image_file)) 
					{
						//dodaj še v bazo
						$this->db->where('id',$id_word);
						$this->db->update('words',array('image'=>$image_file));
				    }
				    else 
				    {
				    	$data['errfields']['image_not_uploaded']='Slika se ni pravilno naložila!';
				    }
				}
			}

			//comment
			if($_FILES['comment_file']['size'])
			{
				$comment_file_type = pathinfo($_FILES["comment_file"]["name"],PATHINFO_EXTENSION);
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $title);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$comment_dir = "comments/";
				$comment_file = $comment_dir.basename(strtolower($file_name).'_'.time().'.'.$comment_file_type);
				$comment_upload_ok = 1;

				// Check if image file is a actual image or fake image
				if (file_exists($comment_file)) 
				{
					$data['errfields']['comment_exists']='Komentar že obstaja!';
				    $comment_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["comment_file"]["size"] > 10000000) {
					$data['errfields']['comment_size']='Komentar je prevelik, največja velikost datoteke je 10 MB!';
				    $comment_upload_ok = 0;
				}
				//tip datoteke
				if($comment_file_type != "pdf" && $comment_file_type != "PDF") {
					$data['errfields']['comment_format']='Izbrani komentar ni ustreznega formata! Dovoljen je samo PDF format.';
				    $comment_upload_ok = 0;
				}
				//
				if ($comment_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["comment_file"]["tmp_name"], $comment_file)) 
					{
						//dodaj še v bazo
						$this->db->where('id',$id_word);
						$this->db->update('words',array('comment'=>$comment_file));
				    }
				    else 
				    {
				    	$data['errfields']['comment_not_uploaded']='Komentar se ni pravilno naložil!';
				    }
				}
			}
		}

		
		
		if(!isset($data['errfields']))
		{
			//update 
			$this->db->where('id',$id_word);
			$this->db->update('words',array('title'=>$title));

			$data['status']='ok';

			$_SESSION['status']=$data['status'];

			if(isset($save_close))
			{
				redirect($this->url.'edit_subject/'.$id_subject);
			}
		}
		else
		{
			$_SESSION['errfields']=$data['errfields'];
		}

		redirect($this->url.'edit_word/'.$id_word);	

	}

	function word_delete()
	{
		$this->check_user();

		$id_word=$this->uri->segment(3);

		$word=$this->admin_model->word($id_word);

		if($word)
		{
			$links=$this->admin_model->word_links($id_word);

			if($links)
			{
				$data['errfields']['links']="Beseda ima povezave (lekseme): <ul>";
				foreach($links as $link)
				{
					$data['errfields']['links'].="<li>".$link['title']."</li>";
				}

				$data['errfields']['links'].='</ul>';
			}

			if(!isset($data['errfields']))
			{
				//remove file
				if($word['image'])
				{
					if(unlink($word['image']))
					{
						//empty field in db
						$this->db->where('id',$id_word);
						$this->db->update('words',array('image'=>''));
					}
					else
					{
						$data['errfields']['no_delete']='Prišlo je do napake pri brisanju slike!';
					}
				}
				
				if($word['comment'])
				{
					if(unlink($word['comment']))
					{
						//empty field in db
						$this->db->where('id',$id_word);
						$this->db->update('words',array('comment'=>''));
					}
					else
					{
						$data['errfields']['no_delete']='Prišlo je do napake pri brisanju komentarja!';
					}
				}
				

				if(!isset($data['errfields']))
				{
					//perform delete
					$this->db->where('id',$id_word);
					$this->db->delete('words');

					$data['status']='ok';
					$_SESSION['status']=$data['status'];

					redirect($this->url.'edit_subject/'.$word['id_subject']);
				}
				else
				{
					$_SESSION['errfields']=$data['errfields'];
					redirect($this->url.'edit_word/'.$id_word);
				}
			}
			else
			{
				$_SESSION['errfields']=$data['errfields'];
				redirect($this->url.'edit_word/'.$id_word);
			}
		}
		else
		{
			$data['tab']='words_subjects';
			$data['text']='Izbran vnos besede ne obstaja!';
			$data['link_back']=$this->url.'edit_content';
			$this->load_Master_view('no_content_error.php',$data);
		}
	}


	function transcriptions()
	{
		$this->check_user();

		$data=array(
			'title'=>'Fonetični zapisi',
		);

		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);

		$data['id_subject']=$this->session->flashdata('id_subject_trans');
		$data['id_word']=$this->session->flashdata('id_word_trans');
		$data['id_lexem']=$this->session->flashdata('id_lexem_trans');
		$data['id_location']=$this->session->flashdata('id_location_trans');

		//load transcriptions
		$data['transcriptions']=$this->admin_model->transcriptions($data['id_word'],$data['id_location'],$data['id_subject'],0,$data['id_lexem']);

		//load view
		$data['view']=$this->load->view('admin/transcriptions_list_view.php',$data,true);

		$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');
		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($data['id_subject'],'select');
		$data['lexems']=array(0=>'Izberite leksem')+$this->admin_model->titles($data['id_word']);
		$data['locations']=array(0=>'Izberite kraj')+$this->admin_model->locations($data['id_subject']);
		$data['tab']='transcriptions';

		$data['status']=$this->session->flashdata('status');

		$this->load_master_view('admin/transcriptions_view.php',$data);
	}
	
	function add_transcription()
	{
		$this->check_user();

		//load basic data
		$data['title']='Dodajanje fonetičnega zapisa';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='transcriptions';

		//get dialects 
		$transcription=$this->session->flashdata('add_transcription');

		$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');
		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($transcription['id_subject'],'select');
		$data['lexems']=array(0=>'Izberite leksem')+$this->admin_model->word_lexems($transcription['id_word'],'select');
		$data['locations']=array(0=>'Izberite kraj')+$this->admin_model->locations($transcription['id_subject']);


		$data['errfields']=$this->session->flashdata('errfields');

		if($transcription)
		{
			$data['transcription']=$transcription;
		}
		else
		{
			$data['transcription']=array(
				'trans_text'=>'',
				'phonetic_writing'=>'',
				'id_subject'=>0,
				'id_word'=>0,
				'id_lexem'=>0,
				'id_location'=>0,
			);
		}

		$this->load_master_view('admin/add_transcription_view.php',$data);
	}

	function post_add_transcription()
	{
		$id_word=$this->input->post('words',true);
		$id_subject=$this->input->post('subjects',true);
		$id_lexem=$this->input->post('lexems_select',true);
		$id_location=$this->input->post('locations',true);
		$phonetic_writing=$this->input->post('phonetic_writing',true);
		$trans_text=$this->input->post('trans_text',true);
		$save_close=$this->input->post('save_close',true);

		//save post to session
		$data=array(
			'id_word'=>$id_word,
			'id_subject'=>$id_subject,
			'id_lexem'=>$id_lexem,
			'id_location'=>$id_location,
			'phonetic_writing'=>$phonetic_writing,
			'trans_text'=>$trans_text,
		);

		$this->session->set_flashdata('add_transcription',$data);

		//check
		if($phonetic_writing=='')
		{
			$data['errfields']['no_phonetic_writing']='Fonetični zapis je prazen!';
		}
		if(!$id_word)
		{
			$data['errfields']['no_word']='Izberite besedo!';
		}
		if(!$id_lexem)
		{
			$data['errfields']['no_lexem']='Izberite leksem!';
		}
		if(!$id_location)
		{
			$data['errfields']['no_location']='Izberite kraj!';
		}

		//check if transcription for this place and this word exists
		if(!isset($data['errfields']))
		{
			$exists=$this->admin_model->transcriptions($id_word,$id_location,0,0,$id_lexem);
		}
		
		if($exists)
		{
			$data['errfields']['word_location_exists']='Fonetični zapis za to besedo in leksem na tej lokaciji že obstaja!';
		}

		if($_FILES and !isset($data['errfields']))
		{
			//audio
			if(isset($_FILES['audio_file']) and $_FILES['audio_file']['size'])
			{
				$audio_file_type = pathinfo($_FILES["audio_file"]["name"],PATHINFO_EXTENSION);
	
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $phonetic_writing);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$audio_dir = "audio/";
				$audio_file = $audio_dir.basename(strtolower($file_name).'_'.time().'.'.$audio_file_type);
				$audio_upload_ok = 1;

				// Check if image file is a actual image or fake image
				if (file_exists($audio_file)) 
				{
					$data['errfields']['audio_exists']='Ta zvočna datoteka že obstaja!';
				    $audio_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["audio_file"]["size"] > 50000000) {
					$data['errfields']['audio_size']='Zvočna datoteka je prevelika, največja velikost datoteke je 50 MB!';
				    $audio_upload_ok = 0;
				}
				//tip datoteke
				if($audio_file_type != "mp3" && $audio_file_type != "MP3") {
					$data['errfields']['audio_format']='Izbrana zvočna datoteka ni ustreznega formata! Dovoljen je samo mp3 format.';
				    $audio_upload_ok = 0;
				}
				//
				if ($audio_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["audio_file"]["tmp_name"], $audio_file)) 
					{
						$data['audio']=$audio_file;
				    }
				    else 
				    {
				    	$data['errfields']['audio_not_uploaded']='Zvočan datoteka se ni pravilno naložila!';
				    }
				}
			}
		}

		if(!isset($data['errfields']))
		{
			unset($data['id_subject']);
			unset($data['id_word']);

			$this->db->insert('transcriptions',$data);
			$id_transcription=$this->db->insert_id();

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'transcriptions/');
			}
			else
			{
				redirect($this->url.'edit_transcription/'.$id_transcription);
			}
		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);

			redirect($this->url.'add_transcription/');
		}
	}
	


	function edit_transcription()
	{
		$this->check_user();

		$id_transcription=$this->uri->segment(3);

		$data['transcription']=$this->admin_model->transcription($id_transcription);

		//load basic data
		$data['title']='Urejanje fonetičnega zapisa';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='transcriptions';

		if($data['transcription'])
		{
			//load data
			$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');
			$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($data['transcription']['id_subject'],'select');
			$data['lexems']=array(0=>'Izberite besedo')+$this->admin_model->word_lexems($data['transcription']['id_word'],'select');
			$data['locations']=array(0=>'Izberite kraj')+$this->admin_model->locations($data['transcription']['id_subject']);

			$data['errfields']=$this->session->flashdata('errfields');
			$data['status']=$this->session->flashdata('status');

			$this->load_master_view('admin/edit_transcription_view.php',$data);
		}
		else
		{
			$data['tab']='transcriptions';
			$data['text']='Izbran vnos fonetičnega zapisa ne obstaja!';
			$data['link_back']=$this->url.'transcriptions';
			$this->load_Master_view('no_content_error.php',$data);
		}	
	}

	function post_edit_transcription()
	{
		$this->check_user();
		$data=array();

		$id=$this->input->post('id',true);
		$id_word=$this->input->post('words',true);
		$id_subject=$this->input->post('subjects',true);
		$id_lexem=$this->input->post('lexems_select',true);
		$id_location=$this->input->post('locations',true);
		$phonetic_writing=$this->input->post('phonetic_writing',true);
		$trans_text=$this->input->post('trans_text',true);
		$save_close=$this->input->post('save_close',true);

		if($phonetic_writing=='')
		{
			$data['errfields']['no_phonetic_writing']='Fonetični zapis je prazen!';
		}
		if(!$id_word)
		{
			$data['errfields']['no_word']='Izberite besedo!';
		}
		if(!$id_lexem)
		{
			$data['errfields']['no_lexem']='Izberite leksem!';
		}
		if(!$id_location)
		{
			$data['errfields']['no_location']='Izberite lokacijo!';
		}

		//check if transcription for this place and this lexem exists
		if(!isset($data['errfields']))
		{
			$exists=$this->admin_model->transcriptions($id_word,$id_location,0,$id,$id_lexem);
		}
		
		if($exists)
		{
			$data['errfields']['word_location_exists']='Fonetični zapis za to besedo in leksem na tej lokaciji že obstaja!';
		}


		if($_FILES and !isset($data['errfields']))
		{
			//audio
			if(isset($_FILES['audio_file']) and $_FILES['audio_file']['size'])
			{
				$audio_file_type = pathinfo($_FILES["audio_file"]["name"],PATHINFO_EXTENSION);
	
				$file_name = preg_replace('/[^a-zA-Z0-9\-\._]/','', $phonetic_writing);
				$file_name = preg_replace('/\s+/', '_', $file_name);
				$audio_dir = "audio/";
				$audio_file = $audio_dir.basename(strtolower($file_name).'_'.time().'.'.$audio_file_type);
				$audio_upload_ok = 1;
				// Check if image file is a actual image or fake image
				if (file_exists($audio_file)) 
				{
					$data['errfields']['audio_exists']='Ta zvočna datoteka že obstaja!';
				    $audio_upload_ok = 0;
				}
				//velikost datoteke
				if ($_FILES["audio_file"]["size"] > 50000000) {
					$data['errfields']['audio_size']='Zvočna datoteka je prevelika, največja velikost datoteke je 50 MB!';
				    $audio_upload_ok = 0;
				}
				//tip datoteke
				if($audio_file_type != "mp3" && $audio_file_type != "MP3") {
					$data['errfields']['audio_format']='Izbrana zvočna datoteka ni ustreznega formata! Dovoljen je samo mp3 format.';
				    $audio_upload_ok = 0;
				}
				//
				if ($audio_upload_ok != 0) 
				{
					if(move_uploaded_file($_FILES["audio_file"]["tmp_name"], $audio_file)) 
					{
						//dodaj še v bazo
						$data['audio']=$audio_file;
				    }
				    else 
				    {
				    	$data['errfields']['audio_not_uploaded']='Zvočan datoteka se ni pravilno naložila!';
				    }
				}
			}
		}

		if(!isset($data['errfields']))
		{
			$db_data=array(
				'phonetic_writing'=>$phonetic_writing,
				'id_lexem'=>$id_lexem,
				'id_location'=>$id_location,
				'trans_text'=>$trans_text,
			);

			//update 
			$this->db->where('id',$id);
			$this->db->update('transcriptions',$db_data+$data);

			$data['status']='ok';


			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'transcriptions');
			}
		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);
		}

		redirect($this->url.'edit_transcription/'.$id);	

	}

	function transcription_delete()
	{
		$this->check_user();

		$id_transcription=$this->uri->segment(3);

		$data=$this->admin_model->transcription($id_transcription);

		if($data)
		{
			//unlink audio
			if($data['audio'])
			{
				unlink($data['audio']);
			}

			//remove transcription
			$this->db->where('id',$id_transcription);
			$this->db->delete('transcriptions');

			$data['status']='ok';
			//to session
			$_SESSION['status']=$data['status'];

			redirect($this->url.'transcriptions');
		}
		else
		{
			$data['tab']='transcriptions';
			$data['text']='Izbran vnos fonetičenga zapisa ne obstaja!';
			$data['link_back']=$this->url.'transcriptions';
			$this->load_Master_view('no_content_error.php',$data);
		}
	}

	function locations()
	{
		$this->check_user();

		$data=array(
			'title'=>'Lokacije',
		);

		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);

		$data['locations']=$this->admin_model->locations_all();
		$data['tab']='locations';

		if(isset($_SESSION['status']))
		{
			$data['status'] = $_SESSION['status'];
			unset($_SESSION['status']);
		}

		$this->load_master_view('admin/locations_view.php',$data);
	}

	function add_location()
	{
		$this->check_user();

		//load basic data
		$data['title']='Dodajanje lokacije';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='locations';

		//get dialects 
		$location=$this->session->flashdata('add_location');

		$data['dialects']=array(0=>'Izberite narečno skupino')+$this->admin_model->dialects('options');
		$data['subdialects']=array(0=>'Izberite narečje')+$this->admin_model->subdialects($location['id_dialect'],'options');
		$data['subsubdialects']=array(0=>'Izberite podnarečje')+$this->admin_model->subsubdialects($location['id_subdialect'],'options');

		$data['subjects']=$this->admin_model->subjects();
        $data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');

		$data['errfields']=$this->session->flashdata('errfields');

		//var_dump($data);

		if($location)
		{
			$data['location']=$location;
		}
		else
		{
			$data['location']=array(
				'name'=>'',
				'short_name'=>'',
				'lat'=>'',
				'long'=>'',
				'id_dialect'=>0,
				'id_subdialect'=>0,
				'id_subsubdialect'=>0,
                'id_subject'=>''
			);
		}

		$this->load_master_view('admin/add_location_view.php',$data);
	}

	function post_add_location()
	{
		$name=$this->input->post('name',true);
		$short_name=$this->input->post('short_name',true);
		$lat=$this->input->post('lat',true);
		$long=$this->input->post('long',true);
		$id_dialect=$this->input->post('dialects',true);
		$id_subdialect=$this->input->post('subdialects',true);
		$id_subsubdialect=$this->input->post('subsubdialects',true);
        $id_subject=$this->input->post('subject',true);
		$save_close=$this->input->post('save_close',true);


		//save post to session
		$data=array(
			'name'=>$name,
			'short_name'=>$short_name,
			'lat'=>$lat,
			'long'=>$long,
			'id_dialect'=>$id_dialect,
			'id_subdialect'=>$id_subdialect,
			'id_subsubdialect'=>$id_subsubdialect,
            'id_subject'=>$id_subject
		);

		$this->session->set_flashdata('add_location',$data);

		if(!$name)
		{
			$data['errfields']['name']='Ime kraja je prazno!';
		}
		elseif($this->admin_model->location_exists('name',$name, $id_subject))
		{
			$data['errfields']['name']='Ime kraja za to temo že obstaja!';
		}

		if(!$short_name)
		{
			$data['errfields']['short_name']='Kratek naziv kraja je prazen!';
		}
		elseif($this->admin_model->location_short_name_exists($short_name, $id_subject))
		{
			$data['errfields']['short_name']='Kratek naziv kraja za to temo že obstaja!';
		}

        if(!$id_subject)
        {
            $data['errfields']['no_subject']="Izberite temo!";
        }

		if(!$lat)
		{
			$data['errfields']['lat']='Zemljepisna širina (lat) je prazna!';
		}
		else
		{	
			$lat=str_replace(',','.',$lat);

			if((int)$lat==0)
			{
				$data['errfields']['lat']='Zemljepisna širina (lat) ne sme biti 0!';
			}
			if(!is_numeric($lat))
			{
				$data['errfields']['lat']='Zemljepisna širina (lat) mora biti številska vrednost!';
			}
		}
		if(!$long)
		{
			$data['errfields']['long']='Zemljepisna dolžina (long) je prazna!';
		}
		else
		{
			$long=str_replace(',','.',$long);

			if((int)$long==0)
			{
				$data['errfields']['long']='Zemljepisna dolžina (long) ne sme biti 0!';
			}
			if(!is_numeric($long))
			{
				$data['errfields']['long']='Zemljepisna dolžina (long) mora biti številska vrednost!';
			}
		}


		if(!$id_dialect)
		{
			$data['errfields']['id_dialect']='Izberite narečno skupino!';
		}
		if(!$id_subdialect)
		{
			$data['errfields']['id_subdialect']='Izberite narečje!';
		}

        if($lat and $long)
        {
            if($this->admin_model->coordinates_exists($lat,$long,$id_location, $id_subject))
            {
                $data['errfields']['coordinates']='Na teh koordinatah za to temo že obstaja kraj!';
            }
        }

		if(!isset($data['errfields']))
		{
			if($data['id_subsubdialect']==0)
			{
				$data['id_subsubdialect']=NULL;
			}
			$this->db->insert('locations',$data);
			$id_location=$this->db->insert_id();

			//add possible subject_locations

			foreach($id_subjects as $key=>$id_subject)
			{	
				$db_data=array(
					'id_location'=>$id_location,
					'id_subject'=>$id_subject,
					'checked'=>1,
				);
				//$this->db->insert('subject_locations',$db_data);
			}

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'locations/');
			}
			else
			{
				redirect($this->url.'edit_location/'.$id_location);
			}
			
		}
		else
		{

			$this->session->set_flashdata('errfields',$data['errfields']);

			redirect($this->url.'add_location/');
		}
	}

	function edit_location()
	{
		$this->check_user();

		$id_location=$this->uri->segment(3);

		$data['location']=$this->admin_model->location($id_location);

		//load basic data
		$data['title']='Urejanje lokacije';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='locations';

		if($data['location'])
		{	
			$data['dialects']=array(0=>'Izberite narečno skupino')+$this->admin_model->dialects('options');
			$data['subdialects']=array(0=>'Izberite narečje')+$this->admin_model->subdialects($data['location']['id_dialect'],'options');
			$data['subsubdialects']=array(0=>'Izberite podnarečje')+$this->admin_model->subsubdialects($data['location']['id_subdialect'],'options');

			$data['subjects']=$this->admin_model->subjects();

			//$data['subject_locations']=$this->admin_model->subject_locations($id_location);


			$data['errfields']=$this->session->flashdata('errfields');
			$data['status']=$this->session->flashdata('status');

			$this->load_master_view('admin/edit_location_view.php',$data);
		}
		else
		{
			$data['tab']='locations';
			$data['text']='Izbran vnos lokacije ne obstaja!';
			$data['link_back']=$this->url.'locations';
			$this->load_Master_view('no_content_error.php',$data);
		}	
	}

	function post_edit_location()
	{
		$this->check_user();

		$id_location=$this->input->post('id',true);
		$name=$this->input->post('name',true);
		$short_name=$this->input->post('short_name',true);
		$lat=$this->input->post('lat',true);
		$long=$this->input->post('long',true);
		$id_dialect=$this->input->post('dialects',true);
		$id_subdialect=$this->input->post('subdialects',true);
		$id_subsubdialect=$this->input->post('subsubdialects',true);
        $id_subject=$this->input->post('subject',true);
		$save_close=$this->input->post('save_close',true);

		$subjects=$this->input->post('subjects',true);

		if(!$name)
		{
			$data['errfields']['name']='Ime kraja je prazno!';
		}


		if(!$short_name)
		{
			$data['errfields']['short_name']='Kratek naziv kraja je prazen!';
		}
		elseif($this->admin_model->location_short_name_exists($short_name,$id_location))
		{
			$data['errfields']['short_name']='Kratek naziv kraja kraja že obstaja!';
		}

		if(!$lat)
		{
			$data['errfields']['lat']='Zemljepisna širina (lat) je prazna!';
		}
		else
		{
			$lat=str_replace(',','.',$lat);

			if((int)$lat==0)
			{
				$data['errfields']['lat']='Zemljepisna širina (lat) ne sme biti 0!';
			}
			
			//check again
			if(!is_numeric($lat))
			{
				$data['errfields']['lat']='Zemljepisna širina (lat) mora biti številska vrednost!';
			}
		}
		if(!$long)
		{
			$data['errfields']['long']='Zemljepisna dolžina (long) je prazna!';
		}
		else
		{
			$long=str_replace(',','.',$long);

			if((int)$long==0)
			{
				$data['errfields']['long']='Zemljepisna dolžina (long) ne sme biti 0!';
			}
			if(!is_numeric($long))
			{
				$data['errfields']['long']='Zemljepisna dolžina (long) mora biti številska vrednost!';
			}
		}

        if($lat and $long)
        {
            if($this->admin_model->coordinates_exists($lat,$long,$id_location, $id_subject))
            {
                $data['errfields']['coordinates']='Na teh koordinatah za to temo že obstaja kraj!';
            }
        }

		if(!isset($data['errfields']))
		{
			//get all
			/*$this->db->select('*');
			$this->db->from('subject_locations');
			$this->db->where('id_location',$id_location);
			$subject_locations=$this->db->get()->result_array();

			$all_locations=array();
			foreach($subject_locations as $subject_location)
			{
					$all_locations[$subject_location['id']]=$subject_location['id'];
			}

			foreach($subjects as $key=>$id_subject)
			{	
				//check if this exists
				$this->db->select('*');
				$this->db->from('subject_locations');
				$this->db->where('id_location',$id_location);
				$this->db->where('id_subject',$id_subject);
				$exist=$this->db->get()->row_array();

				if($exist)
				{
					$this->db->where('id',$exist['id']);
					$this->db->update('subject_locations',array('checked'=>1));

					unset($all_locations[$exist['id']]);
				}
				else //insert new
				{
					$db_data=array(
						'id_location'=>$id_location,
						'id_subject'=>$id_subject,
						'checked'=>1,
					);
					$this->db->insert('subject_locations',$db_data);
				}
			}

			//check if any entries have to be deleted
			foreach($all_locations as $id=>$location)
			{
				$this->db->where('id',$id);
				$this->db->delete('subject_locations');
			}*/


			$db_data=array(
				'name'=>$name,
				'short_name'=>$short_name,
				'lat'=>$lat,
				'long'=>$long,
				'id_dialect'=>$id_dialect,
				'id_subdialect'=>$id_subdialect,
				'id_subsubdialect'=>$id_subsubdialect?$id_subsubdialect:NULL,
                'id_subject'=>$id_subject
			);

			//update
			$this->db->where('id',$id_location);
			$this->db->update('locations',$db_data);

			//get data
			$data['location']=$this->admin_model->location($id_location);

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'locations');
			}

		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);
		}

		redirect($this->url.'edit_location/'.$id_location);
	}

	function location_delete()
	{
		$this->check_user();

		$id_location=$this->uri->segment(3);

		//get links
		$links=$this->admin_model->locations_links($id_location);

		if($links)
		{
			$data['errfields']['links']="Lokacija ima povezave (fonetične zapise): <ul>";
			foreach($links as $link)
			{
				$data['errfields']['links'].="<li class='ZRCola'>".$link['phonetic_writing']."</li>";
			}

			$data['errfields']['links'].='</ul>';
		}

		if(!isset($data['errfields']))
		{
			//delete possible subject_locations
			$this->db->select('*');
			$this->db->from('subject_locations');
			$this->db->where('id_location',$id_location);
			$subject_locations=$this->db->get()->result_array();

			foreach($subject_locations as $entry)
			{
				$this->db->where('id',$entry['id']);
				$this->db->delete('subject_locations');
			}

			//perform delete
			$this->db->where('id',$id_location);
			$this->db->delete('locations');

			$data['status']='ok';
			$this->session->set_flashdata('status',$data['status']);

			redirect($this->url.'locations');
		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);
			redirect($this->url.'edit_location/'.$id_location);
		}
	}

	function users()
	{
		$this->check_user();

		$data=array(
			'title'=>'Uporabniki',
		);

		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['users']=$this->admin_model->users();
		$data['tab']='my_profile';

		if(isset($_SESSION['status']))
		{
			$data['status'] = $_SESSION['status'];
			unset($_SESSION['status']);
		}

		$this->load_master_view('admin/users_view.php',$data);
	}

	function add_user()
	{
		$this->check_user();

		$data = array(
		   'username' =>'',
		   'sess_expiration'=>60,
		);

		$this->db->insert('users', $data); 
		$id_user=$this->db->insert_id();

		redirect($this->url.'edit_user/'.$id_user);
	}


	function edit_user()
	{
		$this->check_user();

		$id_user=$this->uri->segment(3);

		//load basic data
		$data['title']='Urejanje uporabnika';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);

		$data['user']=$this->admin_model->user($id_user);
		$data['tab']='my_profile';

		if($data['user'])
		{

			if(isset($_SESSION['errfields']))
			{
				$data['errfields'] = $_SESSION['errfields'];
				unset($_SESSION['errfields']);
			}

			if(isset($_SESSION['status']))
			{
				$data['status'] = $_SESSION['status'];
				unset($_SESSION['status']);
			}


			$this->load_master_view('admin/edit_user_view.php',$data);
		}
		else
		{
			$data['text']='Izbran vnos uporabnika ne obstaja!';
			$data['link_back']=$this->url.'users';
			$this->load_Master_view('no_content_error.php',$data);
		}	

	}

	function post_edit_user()
	{
		$username=(string)$this->input->post('username',true);
		$name=(string)$this->input->post('name',true);
		$lastname=(string)$this->input->post('lastname',true);
		$pass1=(string)$this->input->post('pass1',true);
		$pass2=(string)$this->input->post('pass2',true);
		$id_user=$this->input->post('id_user',true);

		if($username=='')
		{
			$data['errfields']['no_username']='Uporabniško ime je prazno!';
		}
		else
		{
			//check if profile with this username exists
			if($this->admin_model->username_exists($id_user,$username))
			{
				$data['errfields']['username_exists']='Uporabnik s tem uporabniškim imenom že obstaja!';
			}
		}

		if($pass1=='' or $pass2=='')
		{
			$data['errfields']['not_equal']='Obe vnosni polji za geslo morata biti izpolnjeni!';
		}
		else
		{
			if(strcmp($pass1,$pass2)!==0)
			{
				$data['errfields']['not_equal']='Gesli se ne ujemata!';
			}
			else
			{
				if(strlen($pass1)<6)
				{
					$data['errfields']['pass_short']='Geslo mora vsebovati najmanj 6 znakov!';
				}
			}
		}

		if(!isset($data['errfields']))
		{
			//make hash
			$hash=password_hash($pass1,PASSWORD_DEFAULT);

			$db_data=array(
				'password_hash'=>$hash,
				'username'=>$username,
				'name'=>$name,
				'lastname'=>$lastname,
			);

			//update db
			$this->db->where('id',$id_user);
			$this->db->update('users',$db_data);

			$data['status']='ok';

			//set to session
			$_SESSION['status']=$data['status'];
		}
		else
		{
			//set to session
			$_SESSION['errfields']=$data['errfields'];
		}

		redirect($this->url.'edit_user/'.$id_user);	
	}

	function user_delete()
	{
		$this->check_user();

		$id_user=(int)$this->input->post('id_user',true);

		if($id_user)
		{
			//remove subject
			$this->db->where('id',$id_user);
			$this->db->delete('users');

			$data['status']='ok';

			$_SESSION['status']=$data['status'];

            $data['status']='ok';

            echo json_encode($data);

		}
		else
		{
			$_SESSION['errfields']='Tega uporabnika ni mogoče izbrisati!';

			redirect($this->url.'/edit_user/'.$id_user);
		}	
	}

	function lexems()
	{
		$this->check_user();

		$data=array(
			'title'=>'Leksemi',
		);

		$data['id_subject']=$this->session->flashdata('id_subject_lexems');

		$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');
		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($data['id_subject'],'select');

		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);

		$data['lexems']=$this->admin_model->lexems();
		$data['tab']='lexems';

		$data['view']=$this->load->view('admin/lexems_list_view.php',$data,true);

		$data['status']=$this->session->flashdata('status');

		$this->load_master_view('admin/lexems_view.php',$data);
	}

	function add_lexem()
	{
		$this->check_user();

		//load basic data
		$data['title']='Dodajanje leksema';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='lexems';

		//get data from session
		$lexem=$this->session->flashdata('add_lexem');

		//load words, subjects
		$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');

		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($lexem['id_subject'],'select');

		$data['errfields']=$this->session->flashdata('errfields');

		if($lexem)
		{
			$data['lexem']=$lexem;
		}
		else
		{
			$data['lexem'] = array(
			    'title' => '',
			    'id_word'=>0,
			    'id_subject'=>0,
			    'icon1'=>'',
                'icon2'=>'',
                'icon3'=>'',
                'icon4'=>'',
			    'icon_color1'=>'',
                'icon_color2'=>'',
                'icon_color3'=>'',
                'icon_color4'=>'',
                'icon_size1'=>'',
                'icon_size2'=>'',
                'icon_size3'=>'',
                'icon_size4'=>'',
                'star'=>0,
			);
		}

		$this->load_master_view('admin/lexem_add_view.php',$data);
	}

	function post_add_lexem()
	{
		$id_word=$this->input->post('words',true);
		$id_subject=$this->input->post('subjects',true);
		$title=$this->input->post('title',true);
		$icon1=$this->input->post('icon1',true);
		$icon_color1=$this->input->post('icon_color1',true);
        $icon_size1=$this->input->post('icon_size1',true);
        $icon2=$this->input->post('icon2',true);
        $icon_color2=$this->input->post('icon_color2',true);
        $icon_size2=$this->input->post('icon_size2',true);
        $icon3=$this->input->post('icon3',true);
        $icon_color3=$this->input->post('icon_color3',true);
        $icon_size3=$this->input->post('icon_size3',true);
        $icon4=$this->input->post('icon4',true);
        $icon_color4=$this->input->post('icon_color4',true);
        $icon_size4=$this->input->post('icon_size4',true);
        $star=$this->input->post('star',true);
        $save_close=$this->input->post('save_close',true);

        $star = $star === 'on' ? 1 : 0;

		//save post to session
		$data=array(
			'title'=>$title,
			'id_word'=>$id_word,
			'id_subject'=>$id_subject,
			'icon1'=>$icon1,
			'icon_color1'=>$icon_color1,
            'icon_size1'=>$icon_size1,
            'icon2'=>$icon2,
            'icon_color2'=>$icon_color2,
            'icon_size2'=>$icon_size2,
            'icon3'=>$icon3,
            'icon_color3'=>$icon_color3,
            'icon_size3'=>$icon_size3,
            'icon4'=>$icon4,
            'icon_color4'=>$icon_color4,
            'icon_size4'=>$icon_size4,
            'star'=>$star
		);

		$this->session->set_flashdata('add_lexem',$data);

		//check

		if(!$title)
		{
			$data['errfields']['no_title']="Leksem je prazen!";
		}

		if(!$id_word)
		{
			$data['errfields']['no_word']="Izberite besedo!";
		}

		if(!$icon1)
		{
			$data['errfields']['no_icon']="Simbol leksema je prazen!";
		}
		else
		{
			$icon1=preg_replace('/\s+/', '', $icon1);
		}

		if(!$icon_color1)
		{
			$icon_color1="#000000";
		}

		if(!isset($data['errfields']))
		{
			if($this->admin_model->lexem_title_exists(0,$data['title'],$data['id_subject'],$data['id_word']))
			{
				$data['errfields']['title_exists']="Tak leksem za to besedo že obstaja!";
			}
		}

		if(!isset($data['errfields']))
		{
			unset($data['id_subject']);
			$this->db->insert('lexems',$data);
			$id_lexem=$this->db->insert_id();


			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'lexems/');
			}
			else
			{
				redirect($this->url.'edit_lexem/'.$id_lexem);
			}

			//var_dump($data);
		}
		else
		{

			$this->session->set_flashdata('errfields',$data['errfields']);

			redirect($this->url.'add_lexem/');
            var_dump($data);
		}
	}

	function edit_lexem()
	{
		$this->check_user();

		$id=$this->uri->segment(3);

		//load basic data
		$data['title']='Urejanje leksema';
		$data['user_title']=$this->session->userdata['name'].' '.$this->session->userdata['lastname'];
		$data['user']=$this->admin_model->user($this->session->userdata['uid']);
		$data['tab']='lexems';

		$data['lexem']=$this->admin_model->lexem($id);

		if($data['lexem'])
		{
			//load words, subjects
			$data['subjects']=array(0=>'Izberite temo')+$this->home_model->subjects('select');
			$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($data['lexem']['id_subject'],'select');

			$data['errfields']=$this->session->flashdata('errfields');
			$data['status']=$this->session->flashdata('status');

			$this->load_master_view('admin/lexem_edit_view.php',$data);	
		}
		else
		{
			$data['text']='Izbran vnos leksema ne obstaja!';
			$data['link_back']=$this->url.'lexems';
			$this->load_master_view('no_content_error.php',$data);
		}
	}

	function post_edit_lexem()
	{
		$id=$this->input->post('id',true);
        $id_word=$this->input->post('words',true);
        $id_subject=$this->input->post('subjects',true);
        $title=$this->input->post('title',true);
        $icon1=$this->input->post('icon1',true);
        $icon_color1=$this->input->post('icon_color1',true);
        $icon_size1=$this->input->post('icon_size1',true);
        $icon2=$this->input->post('icon2',true);
        $icon_color2=$this->input->post('icon_color2',true);
        $icon_size2=$this->input->post('icon_size2',true);
        $icon3=$this->input->post('icon3',true);
        $icon_color3=$this->input->post('icon_color3',true);
        $icon_size3=$this->input->post('icon_size3',true);
        $icon4=$this->input->post('icon4',true);
        $icon_color4=$this->input->post('icon_color4',true);
        $icon_size4=$this->input->post('icon_size4',true);
        $star=$this->input->post('star',true);
        $save_close=$this->input->post('save_close',true);

        $star = $star === 'on' ? 1 : 0;

		//check
		if(!$title)
		{
			$data['errfields']['no_title']="Leksem je prazen!";
		}

		if(!$id_word)
		{
			$data['errfields']['no_word']="Izberite besedo!";
		}

		if(!$icon1)
		{
			$data['errfields']['no_icon']="Simbol leksema je prazen!";
		}
		else
		{
			$icon1=preg_replace('/\s+/', '', $icon1);
		}

		if(!$icon_color1)
		{
			$icon_color1="#000000";
		}

		if(!isset($data['errfields']))
		{
			if($this->admin_model->lexem_title_exists(0,$title,$id_subject,$id_word))
			{
				$data['errfields']['title_exists']="Tak leksem za to besedo že obstaja!";
			}
		}

		if(!isset($data['errfields']))
		{
			$db_data=array(
                'title'=>$title,
                'id_word'=>$id_word,
                'icon1'=>$icon1,
                'icon_color1'=>$icon_color1,
                'icon_size1'=>$icon_size1,
                'icon2'=>$icon2,
                'icon_color2'=>$icon_color2,
                'icon_size2'=>$icon_size2,
                'icon3'=>$icon3,
                'icon_color3'=>$icon_color3,
                'icon_size3'=>$icon_size3,
                'icon4'=>$icon4,
                'icon_color4'=>$icon_color4,
                'icon_size4'=>$icon_size4,
                'star'=>$star
			);

			$this->db->where('id',$id);
			$this->db->update('lexems',$db_data);

			$data['status']='ok';

			$this->session->set_flashdata('status',$data['status']);

			if(isset($save_close))
			{
				redirect($this->url.'lexems/');
			}
		}
		else
		{

			$this->session->set_flashdata('errfields',$data['errfields']);
		}

		redirect($this->url.'edit_lexem/'.$id);
	}

	function lexem_delete()
	{
		$this->check_user();

		$id=$this->uri->segment(3);

		//get links
		$links=$this->admin_model->lexem_links($id);

		if($links)
		{
			$data['errfields']['links']="Leksem ima povezave (fonetične zapise): <ul>";
			foreach($links as $link)
			{
				$data['errfields']['links'].="<li class='ZRCola'>".$link['phonetic_writing']."</li>";
			}

			$data['errfields']['links'].='</ul>';
		}

		if(!isset($data['errfields']))
		{
			//perform delete
			$this->db->where('id',$id);
			$this->db->delete('lexems');

			$data['status']='ok';
			$this->session->set_flashdata('status',$data['status']);

			redirect($this->url.'lexems');
		}
		else
		{
			$this->session->set_flashdata('errfields',$data['errfields']);
			redirect($this->url.'edit_lexem/'.$id);
		}
	}


	function ajax_lexem_delete()
	{
		$this->check_user();

		$id=(int)$this->input->post('id_lexem',true);

		//check links
		$links=$this->admin_model->lexem_links($id);

		if($links)
		{
			$data['errfields']['links']="Leksem ima povezave (fonetične zapise): <ul>";
			foreach($links as $link)
			{
				$data['errfields']['links'].="<li class='ZRCola'>".$link['phonetic_writing']."</li>";
			}

			$data['errfields']['links'].='</ul>';
		}

		if(!isset($data['errfields']))
		{
			//remove location
			$this->db->where('id',$id);
			$this->db->delete('lexems');

			$data['status']='ok';
		}	
	
		echo json_encode($data);
	}

	
	function ajax_edit_subject_save()
	{
		$this->check_user();

		$id_subject=(int)$this->input->post('id',true);
		$title=$this->input->post('title',true);

		if($title=='')
		{
			$data['errfields']['no_title']='Naziv teme je prazen!';
		}
		else
		{
			$exists=$this->admin_model->subject_title_exists($title,$id_subject);
			if($exists)
			{
				$data['errfields']['title_exists']='Tema s tem nazivom že obstaja!';
			}
		}

		if(!isset($data['errfields']))
		{
			//update
			$this->db->where('id',$id_subject);
			$this->db->update('subjects',array('title'=>$title));

			$data['status']='ok';
		}

		echo json_encode($data);
	}

	function ajax_word_delete()
	{
		$this->check_user();

		$id_word=(int)$this->input->post('id_word',true);

		$word=$this->admin_model->word($id_word);

		//check links
		$links=$this->admin_model->word_links($id_word);

		if($links)
		{
			$data['errfields']['links']="Beseda ima povezave (lekseme): <ul>";
			foreach($links as $link)
			{
				$data['errfields']['links'].="<li>".$link['title']."</li>";
			}

			$data['errfields']['links'].='</ul>';
		}

		if(!isset($data['errfields']))
		{
			if($word['image'])
			{
				//remove file
				if(unlink($word['image']))
				{
					//empty field in db
					$this->db->where('id',$id_word);
					$this->db->update('words',array('image'=>''));
				}
				else
				{
					$data['errfields']['no_delete']='Prišlo je do napake pri brisanju slike!';
				}
			}

			if($word['comment'])
			{
				if(unlink($word['comment']))
				{
					//empty field in db
					$this->db->where('id',$id_word);
					$this->db->update('words',array('comment'=>''));

					$data['status']='ok';
				}
				else
				{
					$data['errfields']['no_delete']='Prišlo je do napake pri brisanju komentarja!';
				}
			}

			if(!isset($data['errfields']))
			{
				//remove image
				$this->db->where('id',$id_word);
				$this->db->delete('words');

				$data['status']='ok';
			}
		}

		echo json_encode($data);
	}

	function ajax_image_delete()
	{
		$this->check_user();

		$id_word=(int)$this->input->post('id_word',true);
		$image=(string)$this->input->post('image',true);


		if(!$id_word)
		{
			$data['errfields']['no_id']='Neveljaven vnos!';
		}
		if(!$image)
		{
			$data['errfields']['image']='Ni obstoječe slike!';
		}

		if(!isset($data['errfields']))
		{
			chmod($image,0755);
			//remove file
			if(unlink($image))
			{
				//empty field in db
				$this->db->where('id',$id_word);
				$this->db->update('words',array('image'=>''));

				$data['status']='ok';
			}
			else
			{
				$data['errfields']['no_delete']='Prišlo je do napake pri brisanju!';
			}
		}

		echo json_encode($data);
	}

	function ajax_comment_delete()
	{
		$this->check_user();

		$id_word=(int)$this->input->post('id_word',true);
		$comment=(string)$this->input->post('comment',true);


		if(!$id_word)
		{
			$data['errfields']['no_id']='Neveljaven vnos!';
		}
		if(!$comment)
		{
			$data['errfields']['comment']='Ni obstoječega komentarja!';
		}

		if(!isset($data['errfields']))
		{

			if(unlink($comment))
			{
				//empty field in db
				$this->db->where('id',$id_word);
				$this->db->update('words',array('comment'=>''));

				$data['status']='ok';
			}
			else
			{
				$data['errfields']['no_delete']='Prišlo je do napake pri brisanju!';
			}
		}

		echo json_encode($data);
	}

	function ajax_icon_delete()
	{
		$this->check_user();

		$id_transcription=(int)$this->input->post('id_transcription',true);
		$icon=(string)$this->input->post('icon',true);


		if(!$id_transcription)
		{
			$data['errfields']['no_id']='Neveljaven vnos!';
		}
		if(!$icon)
		{
			$data['errfields']['image']='Ni obstoječe slike!';
		}

		if(!isset($data['errfields']))
		{
			//remove file
			if(unlink($icon))
			{
				//empty field in db
				$this->db->where('id',$id_transcription);
				$this->db->update('transcriptions',array('icon'=>''));

				$data['status']='ok';
			}
			else
			{
				$data['errfields']['no_delete']='Prišlo je do napake pri brisanju!';
			}
		}

		echo json_encode($data);
	}

	function ajax_change_subject_lexems()
	{
		$id_subject=$this->input->post('id_subject',true);

		$this->session->set_flashdata('id_subject_lexems',$id_subject);

		//load words
		$data=array();

		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($id_subject,'select');

		//load transcriptions
		$data['lexems']=$this->admin_model->lexems(0,$id_subject);

		//load view
		$data['view']=$this->load->view('admin/lexems_list_view.php',$data,true);

		$data['status']='ok';

		echo json_encode($data);
	}

	function ajax_change_word_lexems()
	{
		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);

		//load transcriptions
		$data['lexems']=$this->admin_model->lexems($id_word,$id_subject);

		//load view
		$data['view']=$this->load->view('admin/lexems_list_view.php',$data,true);

		$data['status']='ok';
		
		echo json_encode($data);
	}

	function ajax_change_subject()
	{
		$id_subject=$this->input->post('id_subject',true);
		$id_location=$this->input->post('id_location',true);

		//save to session
		$this->session->set_flashdata('id_subject_trans',$id_subject);

		//load words
		$data=array();

		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($id_subject,'select');
		$data['locations']=array(0=>'Izberite kraj')+$this->admin_model->locations($id_subject);
		/*
		$data['locations']=array();
		foreach($locations as $id=>$location)
		{
			$data['locations'][$id]=array(
					'id'=>$id,
					'title'=>$location,
				);
		}
		*/

		//load transcriptions
		$data['transcriptions']=$this->admin_model->transcriptions(0,$id_location,$id_subject);

		//load view
		$data['view']=$this->load->view('admin/transcriptions_list_view.php',$data,true);

		$data['status']='ok';

		echo json_encode($data);
	}

	function ajax_load_transcriptions()
	{
		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);
		$id_location=$this->input->post('id_location',true);


		//save to session
		$this->session->set_flashdata('id_word_trans',$id_word);

		//load transcriptions
		$data['transcriptions']=$this->admin_model->transcriptions($id_word,$id_location,$id_subject);

		//load titles
		$data['titles']=array(0=>'Izberite leksem')+$this->admin_model->titles($id_word);

		//load view
		$data['view']=$this->load->view('admin/transcriptions_list_view.php',$data,true);

		$data['status']='ok';
		
		echo json_encode($data);
	}

	function ajax_update_transcriptions_titles()
	{
		$id_lexem=$this->input->post('id_lexem',false);
		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);
		$id_location=$this->input->post('id_location',true);

		//save to session
		$this->session->set_flashdata('id_lexem_trans',$id_word);

		//load transcriptions
		$data['transcriptions']=$this->admin_model->transcriptions($id_word,$id_location,$id_subject,0,$id_lexem);

		//load view
		$data['view']=$this->load->view('admin/transcriptions_list_view.php',$data,true);

		$data['status']='ok';
		
		echo json_encode($data);
	}

	function ajax_change_location()
	{
		$id_lexem=$this->input->post('id_lexem',false);
		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);
		$id_location=$this->input->post('id_location',true);

		//save to session
		$this->session->set_flashdata('id_location_trans',$id_word);

		//load transcriptions
		$data['transcriptions']=$this->admin_model->transcriptions($id_word,$id_location,$id_subject,0,$id_lexem);

		//load view
		$data['view']=$this->load->view('admin/transcriptions_list_view.php',$data,true);

		$data['status']='ok';
		
		echo json_encode($data);
	}

	function ajax_update_words()
	{
		$id_subject=$this->input->post('id_subject',true);

		//load words
		$data=array();

		$data['words']=array(0=>'Izberite besedo')+$this->home_model->subject_words($id_subject,'select');
		$data['locations']=array(0=>'Izberite kraj')+$this->admin_model->locations($id_subject);

		$data['status']='ok';

		echo json_encode($data);
	}

	function ajax_update_lexems()
	{
		$id_word=$this->input->post('id_word',true);
		$id_subject=$this->input->post('id_subject',true);

		//load words
		$data=array();

		$data['lexems']=array(0=>'Izberite leksem')+$this->admin_model->word_lexems($id_word,$id_subject,'select');

		$data['status']='ok';

		echo json_encode($data);
	}

	function ajax_location_delete()
	{
		$this->check_user();

		$id_location=(int)$this->input->post('id_location',true);

		//check links
		$links=$this->admin_model->locations_links($id_location);

		if($links)
		{
			$data['errfields']['links']="Lokacija ima povezave (fonetične zapise): <ul>";
			foreach($links as $link)
			{
				$data['errfields']['links'].="<li class='ZRCola'>".$link['phonetic_writing']."</li>";
			}

			$data['errfields']['links'].='</ul>';
		}

		if(!isset($data['errfields']))
		{
			//delete possible subject_locations
			/*$this->db->select('*');
			$this->db->from('subject_locations');
			$this->db->where('id_location',$id_location);
			$subject_locations=$this->db->get()->result_array();

			foreach($subject_locations as $entry)
			{
				$this->db->where('id',$entry['id']);
				$this->db->delete('subject_locations');
			}*/
			
			//remove location
			$this->db->where('id',$id_location);
			$this->db->delete('locations');

			$data['status']='ok';
		}	
	
		echo json_encode($data);
	}

	function ajax_transcription_delete()
	{
		$this->check_user();

		$id_transcription=(int)$this->input->post('id_transcription',true);

		$transcription=$this->admin_model->transcription($id_transcription);

		//remove audio and icon
		if($transcription['audio'])
		{
			unlink($transcription['audio']);
		}

		//remove transcription
		$this->db->where('id',$id_transcription);
		$this->db->delete('transcriptions');

		$data['status']='ok';
				
	
		echo json_encode($data);
	}

	function ajax_audio_delete()
	{
		$this->check_user();

		$id_transcription=(int)$this->input->post('id_transcription',true);
		$audio=(string)$this->input->post('audio',true);


		if(!$id_transcription)
		{
			$data['errfields']['no_id']='Neveljaven vnos!';
		}
		if(!$audio)
		{
			$data['errfields']['audio']='Ni obstoječega zvočenga posnetka!';
		}

		if(!isset($data['errfields']))
		{

			if(unlink($audio))
			{
				//empty field in db
				$this->db->where('id',$id_transcription);
				$this->db->update('transcriptions',array('audio'=>''));

				$data['status']='ok';
			}
			else
			{
				$data['errfields']['no_delete']='Prišlo je do napake pri brisanju!';
			}
		}

		echo json_encode($data);
	}

	function ajax_update_subdialects()
	{
		$id_dialect=$this->input->post('id_dialect',true);

		//load words
		$data=array();

		$data['subdialects']=array(0=>'Izberite narečje')+$this->admin_model->subdialects($id_dialect,'options');

		$data['status']='ok';

		echo json_encode($data);
	}

	function ajax_update_subsubdialects()
	{
		$id_subdialect=$this->input->post('id_subdialect',true);

		//load words
		$data=array();

		$data['subsubdialects']=array(0=>'Izberite podnarečje')+$this->admin_model->subsubdialects($id_subdialect,'options');

		$data['status']='ok';

		echo json_encode($data);
	}

	private function load_master_view($page,$data)
	{
		$this->load->view('header.php',$data);
		$this->load->view($page,$data);
		$this->load->view('footer.php',$data);
	}

	private function check_user()
	{
		if(!isset($this->session->userdata['uid']))
		{
			redirect('admin/login');
		}
	} 

	function fill_dialects()
	{
		$dialects=array(
			'gorenjska narečna skupina'=>array(
				'gorenjsko narečje'=>array(
					'vzhodnogorenjsko podnarečje'=>'vzhodnogorenjsko podnarečje',
				),
				'selško narečje'=>array(),
			),
			'dolenjska narečna skupina'=>array(
				'dolenjsko narečje'=>array(
					'vzhodnodolenjsko podnarečje'=>'vzhodnodolenjsko podnarečje',
				),
				'severnobelokranjsko narečje'=>array(),
				'južnobelokranjsko narečje'=>array(),
				'kostelsko narečje'=>array(),
				'mešani kočevski govori'=>array(),
			),
			'štajerska narečna skupina'=>array(
				'srednjesavinjsko narečje'=>array(),
				'zgornjesavinjsko narečje'=>array(
					'solčavsko podnarečje'=>'solčavsko podnarečje',
				),
				'srednještajersko narečje'=>array(),		
				'južnopohorsko narečje'=>array(
					'kozjaško podnarečje'=>'kozjaško podnarečje',
				),
				'kozjansko-bizeljsko narečje'=>array(),
				'posavsko narečje'=>array(
					'zagorsko-trboveljsko podnarečje'=>'zagorsko-trboveljsko podnarečje',
					'laško podnarečje '=>'laško podnarečje ',
					'sevniško-krško podnarečje'=>'sevniško-krško podnarečje',
				),
			),
			'panonska narečna skupina'=>array(
				'prekmursko narečje '=>array(),
				'slovenskogoriško narečje'=>array(),
				'prleško narečje '=>array(),
				'haloško narečje'=>array(),
			),
			'koroška narečna skupina'=>array(
				'severnopohorsko-remšniško narečje'=>array(),
				'mežiško narečje'=>array(),
				'podjunsko narečje'=>array(),
				'rožansko narečje'=>array(),
				'obirsko narečje'=>array(),
				'ziljsko narečje'=>array(
					'kranjskogorsko podnarečje'=>'kranjskogorsko podnarečje',
				),
			),
			'primorska narečna skupina'=>array(
				'rezijansko narečje'=>array(),
				'obsoško narečje'=>array(),
				'tersko narečje'=>array(),
				'nadiško narečje'=>array(),
				'briško narečje'=>array(),
				'kraško narečje'=>array(
					'banjško podnarečje'=>'banjško podnarečje',
				),
				'istrsko narečje'=>array(
					'rižansko podnarečje'=>'rižansko podnarečje',
					'šavrinsko podnarečje'=>'šavrinsko podnarečje',
				),
				'notranjsko narečje'=>array(),
				'čiško narečje'=>array(),
			),
			'rovtarska narečna skupina'=>array(
				'tolminsko narečje'=>array(
					'baško podnarečje'=>'baško podnarečje',
				),
				'cerkljansko narečje'=>array(),
				'poljansko narečje'=>array(),
				'škofjeloško narečje'=>array(),
				'črnovrško narečje'=>array(),
				'horjulsko narečje'=>array(),
			),
		);

		foreach($dialects as $key=>$dialect)
		{
			//insert main
			$db_data=array(
				'name'=>$key,
				'type'=>1,
				'id_parent'=>NULL,
			);
			$this->db->insert('dialects',$db_data);
			$id_dialect=$this->db->insert_id();

			foreach($dialect as $subkey=>$subdialect)
			{
				//insert sub
				$db_data=array(
					'name'=>$subkey,
					'type'=>2,
					'id_parent'=>$id_dialect,
				);
				$this->db->insert('dialects',$db_data);
				$id_subdialect=$this->db->insert_id();

				foreach($subdialect as $subsubkey=>$subsubdialect)
				{
					//insert 
					$db_data=array(
						'name'=>$subsubkey,
						'type'=>3,
						'id_parent'=>$id_subdialect,
					);
					$this->db->insert('dialects',$db_data);
				}
			}
		}

		echo "done!";
	}
}
