<?php

class adminproduktController extends baseadminController {

  function __construct() {

    $this->controller_name 	= 'Produkty';
    $this->controller_fname = 'adminprodukt';
    $this->controller_info 	= 'Správa produktů.';
    $this->entita_classname = 'Produkt';
    parent::__construct();

  }

  public function filtr($args) {

    $this->registry->html_view = 'Controller: ' . __CLASS__ . ', metoda '. __METHOD__;
    $this->setView();

  }

  public function seznam($args) {

    $table_id = 'seznamProdukty';
		$entita = new $this->entita_classname();

    $this->registry->jscript->addJqFunction('"#'.$table_id.'"', 'tablesorter','','','','','','document_ready');

    $query = $entita->getAllQuery();
    $filtr_query = array();
    $this->setFilter($filtr_query, $entita);
    $this->myOrder($filtr_query, $entita);
    $strankovani = $this->addLimit($query, $filtr_query ,$entita);
		$query = array_merge($query,$filtr_query);

    $result = dibi::query($query);
    $zaznamy = $result->fetchAll();
    unset($result);

    foreach($zaznamy as $key=>$value) {
    	$zaznamy[$key]['CENA'] = Tools::numberFromDb($value['CENA']);
    	$zaznamy[$key]['CENA_S'] = Tools::numberFromDb($value['CENA_S']);
    }

    array_walk($zaznamy,
      'Tools::addLink',
      array('UPRAVIT' => array(
          'link' => Tools::controllerlink($this->controller_fname, 'upravit'),
          'addindex' => 'ID',
          'text'	 => ICO_UPRAVIT
        ),
        'NAHLED' => array(
        	'target'	=> 'blank',
          'link' => Tools::controllerlink('produkty'),
          'addindex' => 'REWRITE_LINK',
          'text'	 => ICO_NAHLED
        )
      )
    );

    $hlavicka = array(
      'ID' 		=> 'Id',
    	'KATALOG_CISLO' => 'Kat.&nbsp;č.',
      'NAZEV' => 'Název',
      'CENA'	=> 'Cena',
    	'CENA_S'	=> '+dan',
    	'KUSU'	=> 'Ks',
      'S_NAZEV' => 'Stav',
      'UPRAVIT' => '',
    	'NAHLED' => '',
    );

    $obsah_css = array(
      'ID' 			=> 'a_c',
    	'CENA'	=> 'a_r',
    	'CENA_S'	=> 'a_r',
    	'KUSU'	=> 'a_r',
      'S_NAZEV' => 'a_c',
      'UPRAVIT' => 'a_c',
    	'NAHLED' => 'a_c',
    );

    $hlavicka_css = array(
      'UPRAVIT' => 'nosort',
    	'NAHLED'  => 'nosort',
    );
    $this->thCss($hlavicka_css);

    $this->html = $this->getTable($table_id, $hlavicka, $zaznamy,
      array('class' => 'seznam tablesorter', 'summary' => $this->controller_name ),
      $obsah_css, array('ID', 'NAHLED'), $hlavicka_css, '', $entita->filtry, false
    );
		$this->html .= '<div class="strankovani">'.$strankovani.'</div></form>';
    $this->setView();

  }

  public function pridat($args) {

    $form_id = 'PridatProduktForm';
    $entita = new Produkt();

    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {
    	if (isset($_POST['uloz_pokracuj'])) {
      	if (Validate::entita($entita, true) !== false) {
          $entita->setFromPost();
          if (intval($_POST['pocet_kusu']) == 0) {
          	$entita->neomezeno = true;
          }

          $entita->insert();
          $redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('kategorie', $entita->id));
          Tools::setMessage('Záznam '.$entita->nazev.' byl přidán', CSS_MESS, 1);
        }
    	  else {
        	$valid_err = Validate::error();
        	Tools::setMessage('Špatně vyplněné údaje'.$valid_err, 'err_mess', 1);
        	$redirect = Tools::ControllerLink($this->controller_fname,'pridat');
      	}
        
        Tools::redirect($redirect);
        die;
      }
      else {
        $valid_err = Validate::error();
        Tools::setMessage('Špatně vyplněné údaje'.$valid_err, 'err_mess', CSS_ERR);
  		}
  	}
    
    $this->registry->jscript->addScript('function getRewrUrl(entita){
    	var nazev = entita.value;
		$.post("'.URL.'admin/ajaxvalidate",{akce: "getProdURL", nazev: nazev },
      		function(data){
        		if (data != "FALSE"){
					$("#rewrite_link").val(data); 
					$("#'.$form_id.'").validate().element("#rewrite_link");
 				}
  			}
  		);
	}
    ');

        
      $this->registry->jscript->addScript('function changeDan(val){
    		$.post("'.URL.'admin/ajaxvalidate",{akce: "getTax", id: val },
          		function(data){
            		if (data != "FALSE"){
    					$("#dan_value").val(data);
    					var cena_bez = $("#cena").val();  					
    					cena_bez = cena_bez.replace(/,/,".");
    					if (cena_bez != 0) {
    						var cena_s = Math.ceil(data*cena_bez);	
    						cena_s = cena_s.toFixed(2);
    						cena_s = cena_s.replace(\'.\',",");
    						$("#cena_s").val(cena_s);
      					}
     				}
      			}
      		);
    	}
        ');
        
        $this->registry->jscript->addScript('function getPrices(check){
        	if (check == true) {
        		if ($("#cena_s").val() != ""){
        			return false;
        		}
      		}
      		var dan = $("#dan_value").val();
      		var cena_bez = $("#cena").val();
      		cena_bez = cena_bez.replace(/,/,".");
      		if (cena_bez != 0) {
      			var cena_s = Math.ceil(dan*cena_bez);	
      			cena_s = cena_s.toFixed(2);
      			cena_s = cena_s.replace(\'.\',",");			
      			$("#cena_s").val(cena_s);
      		}
      	}
        ');
    
        $this->registry->jscript->addScript('function getPricesFree(){
    		var dan = $("#dan_value").val();
    		var cena_s = $("#cena_s").val();
    		cena_s = cena_s.replace(/,/,".");
    		if (cena_s != 0) {
    			var cena_bez = Math.floor(cena_s/dan);	
    			cena_bez = cena_bez.toFixed(2);
    			cena_bez = cena_bez.replace(\'.\',",");
    			$("#cena").val(cena_bez);
    		}
    	}
    ');

    
    $this->registry->jscript->addScript('function titleCopy(){
		var name = $("#nazev").val();
		$("#meta_title").val(name);
		$("#'.$form_id.'").validate().element("#meta_title");
	}
    ');

    $this->registry->jscript->addScript('function descCopy(){
		var popis = $("#popis_kratky").val();
		$("#meta_description").val(popis);
		$("#'.$form_id.'").validate().element("#meta_description");
	}
    ');

    $this->registry->jscript->addScript(TINY_PRODUCT_INIT);

    $this->registry->jscript->addScript('$(function() {
			$("#sleva_od").datepicker({showOn: \'button\', buttonImage: \''.URL.'image/calendar.gif\', buttonImageOnly: true});
			$("#sleva_do").datepicker({showOn: \'button\', buttonImage: \''.URL.'image/calendar.gif\', buttonImageOnly: true});
		});
		function setLOV(id,name) {
  		$("#id_vyr").val(id);
  		$("#name_vyr").val(name);
  		self.tb_remove();
		}
		function closeLOV() {
  		self.tb_remove();
		}
	');

    
//    $entita->newStates();
//    $entita->stateDiffValidate();
    
    $form = new Form($form_id, '', 'post', array('class' => 'myForm'));
    $form->setEntitaRef($entita);
    if (isset($_POST['refresh'])) {
    	$form->setValue($_POST);
    }
    $form->openFieldset('Přidat produkt');
    $form->addLabel(MY, 'nazev', array());
    $form->addInput('text', 'nazev', MY,array('onblur' => 'getRewrUrl(this);'), MY,true);

    $form->addLabel(MY, 'rewrite_link',array(), 'Hodnota která bude identifikovat produkt v URL adrese. Může obsahovat pouze písmena a-z, číslice, podtržítko(_) a pomlžku (-)');
    $form->addInput('text', 'rewrite_link', MY,array('onblur' => 'getRewrUrl(this);'), MY,true);

    $form->addLabel(MY, 'katalog_cislo',array());
    $form->addInput('text', 'katalog_cislo', MY,array(), MY,true);

    $form->addLabel(MY, 'popis_kratky');
    $form->addTextarea('popis_kratky', MY, false, array('class' => 'vetsi'),MY);
    $form->addTag('br');
    
    $form->addLabel(MY, 'popis_dlouhy');
    $form->addTextarea('popis_dlouhy', MY, false, array('class' => 'mceAdvanced'));
    $form->addTag('br');
    
    $form->closeFieldset();
    $form->openFieldset('Cena a slevy');
    
    $form->addLabel(MY, 'id_dan');
    $default_dan = 1;
    $form->openSelect('id_dan', MY, array('onchange' => 'changeDan(this.value);'), MY);
    $dan = new Dan();
    $zaznamy = $dan->getToSelect();
    foreach($zaznamy as $row){
      $form->addOption($row['ID'],$row['NAZEV'],'','', array('title' => $row['POPIS']));
      if ($row['ID'] == $default_dan) {
        $hodnota_dan = $row['KOEFICIENT'];
      }
    }
    $form->closeSelect(true);
    $form->addInput('hidden','dan_value',@$hodnota_dan);

    $form->addLabel(MY, 'cena');
    $form->addInput('text', 'cena', MY,array('onblur' => 'getPrices(true);', 'class' => 'a_r'), MY);
    $form->addInput('button','calc','Dopočítat cenu s DPH',array('onclick' => 'getPrices();'), array(), true);

    $form->addLabel('Cena s DPH', 'cena_s',array());
    $form->addInput('text', 'cena_s', MY,array('class' => 'a_r'));
    $form->addInput('button','calc','Dopočítat cenu bez DPH',array('onclick' => 'getPricesFree();'), array(), true);

    $form->addLabel('Recyklační<br /> poplatek', 'recyklacni_poplatek');
    $form->addInput('text', 'recyklacni_poplatek', MY,array('class' => 'a_r'), array(), true);
    $form->addTag('br');

    $form->addLabel('Autorský<br /> poplatek', 'autorsky_poplatek');
    $form->addInput('text', 'autorsky_poplatek', MY,array('class' => 'a_r'), array(), true);
    $form->addTag('br');

    $form->addLabel(MY, 'pocet_kusu',array(), 'Počet dosputných kusů, který se zobrazí návštěvníkům. 
    	Pokud není produkt omezen počtem, nechte pole prázdné');
    $form->addInput('text', 'pocet_kusu', MY,array('class' => 'a_r'), MY, true);
    
    $form->addTag('br');
    $form->addLabel(MY, 'sleva_procent',array());
    $form->addInput('text', 'sleva_procent', MY,array('class' => 'a_r'), MY, true);

    $form->addLabel(MY, 'sleva_pocet',array(), 'Počet slevněných kusů. Pokud je pole prázdné, není sleva množstevně omezená.');
    $form->addInput('text', 'sleva_pocet', MY,array('class' => 'a_r'), $entita->validate['sleva_pocet'], true);
    
    $form->addLabel(MY, 'sleva_od',array(), 'Zadejte datum ve formátu dd.mm.rrrr');
    $form->addInput('text', 'sleva_od', MY,array('class' => 'a_r'), MY, true);

    $form->addLabel(MY, 'sleva_do',array(), 'Zadejte datum ve formátu dd.mm.rrrr');
    $form->addInput('text', 'sleva_do', MY,array('class' => 'a_r'), MY, true);

    $form->closeFieldset();
    $form->openFieldset('Meta informace');

    $form->addLabel(MY, 'meta_title', array(), 'Zobrazuje se v záhlaví stránky');
    $form->addInput('text', 'meta_title', MY,array(), MY);
    $form->addInput('button','nazev_kopi','Zkopírovat název',array('onclick' => 'titleCopy();'));
    $form->addInput('button','popis_kopi','Zkopírovat krátký popis',array('onclick' => 'descCopy();'), array(), true);

    $form->addLabel(MY, 'meta_keywords', array(), 'Klíčová slova pro vyhledávače. Jednotlivá slova oddělte čárkami');
    $form->addInput('text', 'meta_keywords', MY,array('class' => 'vetsi'), MY,true);

    $form->addLabel(MY, 'meta_description', array(), 'Popis stránky pro vyhledávače.');
    $form->addInput('text', 'meta_description', MY,array('class' => 'vetsi'), MY,true);

    $form->closeFieldset();
    $form->openFieldset('Ostatní');
    
    $form->addLabel(MY, 'id_zaruka');
    $form->openSelect('id_zaruka', MY, array(), MY);
    $zaruka = new Zaruka();
    $zaznamy = $zaruka->getToSelect();
    foreach($zaznamy as $row) {
      $form->addOption($row['ID'],$row['NAZEV'],'', '', array('title' => $row['POPIS']));
    }
    $form->closeSelect(true);

    $form->addLabel(MY, 'id_expedice');
    $form->openSelect('id_expedice', MY, array(), MY);
    $expedice = new Expedice();
    $zaznamy = $expedice->getToSelect();
    foreach($zaznamy as $row) {
      $form->addOption($row['ID'],$row['NAZEV'],'', '', array('title' => $row['POPIS']));
    }
    $form->closeSelect(true);

    $form->addLabel(MY, 'id_vyr' );
    $form->addInput('hidden','id_vyr', MY, array(), MY);
    $form->openTag('a', array('href' => 'http://mvc/admin/lovrequest/vyrobci?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=450&width=700', 'class' => 'thickbox'));
    $form->addInput('text','name_vyr', MY, array('readonly' => 'readonly'));
    $form->addInnerHTML(' Vybrat');
    $form->closeTag('a');
    $form->addTag('br');

    $form->addLabel(MY, 'priorita');
    $form->openSelect('priorita', MY, array(), MY);
    for($i = 0;$i <= 10;$i++) {
      $form->addOption($i,'&nbsp;'.$i);
    }
    $form->closeSelect(true);    

    $form->addLabel(MY, 'stav' );
    $form->stateSelect($entita, true,MY);

    $form->openTag('div', array('class' => 'bb_l'));
    $form->addTag('hr',array('class' => 'fcleaner '));
    $form->addInput('submit', 'uloz_pokracuj', 'Uložit');
    $form->addInput('submit', 'refresh', 'Obnovit s daty');
    $form->addInput('reset', 'reset', 'Vrátit změny');
    $form->closeTag('div');
    $form->closeFieldset();
    $form->closeForm();

    $this->html = $form->get();
    $this->setView('content.tpl');

  }

  public function upravit ($args) {

    if (is_numeric(@$args[0])) {
  		$type = 'info';
  		$id   =  @$args[0];
  	}
  	else {
  		$type = @$args[0];
  		$id   = @$args[1];
  		unset($args[0]);
  		$args = Tools::arrayRecount($args);
  	}

		$entita = new $this->entita_classname();
		$entita->loadById($id);

  	$my_menu = array();
		$my_menu['info']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'info'.DIRSEP.$id;
  	$my_menu['info']['name'] = 'Základní informace';

		$my_menu['obrazek']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'obrazek'.DIRSEP.$id;
  	$my_menu['obrazek']['name'] = 'Obrázky';

		$my_menu['kategorie']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'kategorie'.DIRSEP.$id;
  	$my_menu['kategorie']['name'] = 'Kategorie';

		$my_menu['atributy']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'atributy'.DIRSEP.$id;
  	$my_menu['atributy']['name'] = 'Atributy';

		$my_menu['vlastnosti']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'vlastnosti'.DIRSEP.$id;
  	$my_menu['vlastnosti']['name'] = 'Vlastnosti';

  	$my_menu['soubory']['link'] = URL.'adminprodukt'.DIRSEP.'upravit'.DIRSEP.'soubory'.DIRSEP.$id;
  	$my_menu['soubory']['name'] = 'Soubory';

		switch($type) {

			case 'info':
			default:
				$type = 'info';
				$my_menu['info']['link'] = '#curr_tab';
        $ret = $this->upravit_info($entita, $args);
      break;

			case 'obrazek':
				$ret = $this->upravit_obrazek($entita, $args);
				break;

			case 'kategorie':
				$ret = $this->upravit_kategorie($entita, $args);
				break;

			case 'atributy':
				$ret = $this->upravit_atributy($entita, $args);
				break;

			case 'vlastnosti':
				$ret = $this->upravit_vlastnosti($entita, $args);
				break;

			case 'soubory':
				$ret = $this->upravit_soubory($entita, $args);
				break;

		}

  	$sp_menu= '<div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
  		<h2>Produkt: '.$entita->nazev.'</h2>
  		<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">';
  	foreach($my_menu as $key=>$item) {
  		$class = 'ui-state-default ui-corner-top';
  		if ($key == $type) {
  			$class .= ' ui-tabs-selected ui-state-active';
  		}
  		$sp_menu .= '<li class="'.$class.'"><a href="'.$item['link'].'">'.$item['name'].'</a></li>';
  	}
  	$sp_menu .= '</ul><br />';

		$this->html .= $sp_menu;
		$this->html .= $ret.'</div>';
    $this->setView('content.tpl');

  }
  
	private function upravit_info($entita, $args) {

		$id = $args[0];
		$form_id = 'UpravitProduktForm';
    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {

     	if (isset($_POST['uloz_pokracuj'])) {
       	if (Validate::entita($entita) !== false) {
          $entita->setFromPost();
          if (intval($_POST['pocet_kusu']) == 0) {
          	$entita->neomezeno = true;
          }

          $entita->update();
          $redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('info', $entita->id));
          Tools::setMessage('Záznam '.$entita->nazev.' byl upraven', CSS_MESS, 1);
					}
     	    else {
          	$valid_err = Validate::error();
            Tools::setMessage('Špatně vyplněné údaje'.$valid_err, 'err_mess', CSS_ERR);
            $redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('info', $entita->id));
        	}

          Tools::redirect($redirect);
          die;
        }
    	}
    
      $this->registry->jscript->addScript('function getRewrUrl(entita){
      	var nazev = entita.value;
      	if (nazev != old_nazev && nazev != old_link) {
      		$.post("'.URL.'admin/ajaxvalidate",{akce: "getProdURL", nazev: nazev },
           		function(data){
             		if (data != "FALSE"){
      				$("#rewrite_link").val(data);
      				$("#'.$form_id.'").validate().element("#rewrite_link");
       			}
        		}
        	);
        }
        else {
        	$("#rewrite_link").val(old_link);
      		$("#'.$form_id.'").validate().element("#rewrite_link");
      	}
    }');
        
        $this->registry->jscript->addScript('function changeDan(val){
    		$.post("'.URL.'admin/ajaxvalidate",{akce: "getTax", id: val },
          		function(data){
            		if (data != "FALSE"){
    					$("#dan_value").val(data);
    					var cena_bez = $("#cena").val();  					
    					cena_bez = cena_bez.replace(/,/,".");
    					if (cena_bez != 0) {
    						var cena_s = Math.ceil(data*cena_bez);	
    						cena_s = cena_s.toFixed(2);
    						cena_s = cena_s.replace(\'.\',",");
    						$("#cena_s").val(cena_s);
      					}
     				}
      			}
      		);
    	}
        ');
        
        $this->registry->jscript->addScript('function getPrices(check){
        	if (check == true) {
        		if ($("#cena_s").val() != ""){
        			return false;
        		}
      		}
      		var dan = $("#dan_value").val();
      		var cena_bez = $("#cena").val();
      		cena_bez = cena_bez.replace(/,/,".");
      		if (cena_bez != 0) {
      			var cena_s = Math.ceil(dan*cena_bez);	
      			cena_s = cena_s.toFixed(2);
      			cena_s = cena_s.replace(\'.\',",");			
      			$("#cena_s").val(cena_s);
      		}
      	}
        ');
    
        $this->registry->jscript->addScript('function getPricesFree(){
    		var dan = $("#dan_value").val();
    		var cena_s = $("#cena_s").val();
    		cena_s = cena_s.replace(/,/,".");
    		if (cena_s != 0) {
    			var cena_bez = Math.floor(cena_s/dan);	
    			cena_bez = cena_bez.toFixed(2);
    			cena_bez = cena_bez.replace(\'.\',",");
    			$("#cena").val(cena_bez);
    		}
    	}
        ');
        
        $this->registry->jscript->addScript('function titleCopy(){
    		var name = $("#nazev").val();
    		$("#meta_title").val(name);
    		$("#'.$form_id.'").validate().element("#meta_title");
    	}
        ');
    
        $this->registry->jscript->addScript('function descCopy(){
    		var popis = $("#popis_kratky").val();
    		$("#meta_description").val(popis);
    		$("#'.$form_id.'").validate().element("#meta_description");
    	}
        ');
    
        $this->registry->jscript->addScript(TINY_PRODUCT_INIT);

        $this->registry->jscript->addScript('$(function() {
    			$("#sleva_od").datepicker({showOn: \'button\', buttonImage: \''.URL.'image/calendar.gif\', buttonImageOnly: true});
    			$("#sleva_do").datepicker({showOn: \'button\', buttonImage: \''.URL.'image/calendar.gif\', buttonImageOnly: true});
    		});
    		function setLOV(id,name) {
      		$("#id_vyr").val(id);
      		$("#name_vyr").val(name);
      		self.tb_remove();
    		}
    		function closeLOV() {
      		self.tb_remove();
    		}
    	');

//        $entita->newStates();
//        $entita->stateDiffValidate();

        $form_val = $entita->loadById($id);
        $form = new Form($form_id, '', 'post', array('class' => 'myForm'));
        $form->setEntitaRef($entita);
				$form->setValue($form_val);
//načíst a vypočítat cenu s daní, info o výrobci, ....přepočítat slevu

        $form->openFieldset('Upravit produkt - základní informace');
        $form->addLabel(MY, 'nazev', array());
        $form->addInput('text', 'nazev', MY,array('onblur' => 'getRewrUrl(this);'), MY,true);
    
        $form->addLabel(MY, 'rewrite_link',array(), 'Hodnota která bude identifikovat produkt v URL adrese. Může obsahovat pouze písmena a-z, číslice, podtržítko(_) a pomlžku (-)');
        $form->addInput('text', 'rewrite_link', MY,array('onblur' => 'getRewrUrl(this);'), MY,true);
        
        $this->registry->jscript->addScript('var old_nazev = "'.$entita->nazev.'";');
        $this->registry->jscript->addScript('var old_link  = "'.$entita->rewrite_link.'";');

        $form->addLabel(MY, 'katalog_cislo',array());
        $form->addInput('text', 'katalog_cislo', MY,array(), MY,true);
    
        $form->addLabel(MY, 'popis_kratky');
        $form->addTextarea('popis_kratky', MY, false, array('class' => 'vetsi'),MY);
        $form->addTag('br');
        
        $form->addLabel(MY, 'popis_dlouhy');
        $form->addTextarea('popis_dlouhy', MY, false, array('class' => 'mceAdvanced'));
        $form->addTag('br');
        
        $form->closeFieldset();
        $form->openFieldset('Cena a slevy');
        
        $form->addLabel(MY, 'id_dan');
        $default_dan = 1;
        $form->openSelect('id_dan', MY, array('onchange' => 'changeDan(this.value);'), MY);
        $dan = new Dan();
        $zaznamy = $dan->getToSelect();
        foreach($zaznamy as $row){
          $form->addOption($row['ID'],$row['NAZEV'],'','', array('title' => $row['POPIS']));
          if ($row['ID'] == $default_dan) {
            $hodnota_dan = $row['KOEFICIENT'];
          }
        }
        $form->closeSelect(true);
        $form->addInput('hidden','dan_value',@$hodnota_dan);
    
        $form->addLabel(MY, 'cena');
        $form->addInput('text', 'cena', number_format($form_val['cena'],2, ',', ''),array('onblur' => 'getPrices(true);', 'class' => 'a_r'), MY);
        $form->addInput('button','calc','Dopočítat cenu s DPH',array('onclick' => 'getPrices();'), array(), true);
    
        $form->addLabel('Cena s DPH', 'cena_s',array());
        $form->addInput('text', 'cena_s', number_format(ceil($hodnota_dan*$form_val['cena']),2, ',', ''),array('class' => 'a_r'));
        $form->addInput('button','calc','Dopočítat cenu bez DPH',array('onclick' => 'getPricesFree();'), array(), true);
    
        $form->addLabel('Recyklační<br /> poplatek', 'recyklacni_poplatek');
        $form->addInput('text', 'recyklacni_poplatek', Tools::numberFromDb($form_val['recyklacni_poplatek']),array('class' => 'a_r'), MY, true);
        $form->addTag('br');
    
        $form->addLabel('Autorský<br /> poplatek', 'autorsky_poplatek');
        $form->addInput('text', 'autorsky_poplatek', Tools::numberFromDb($form_val['autorsky_poplatek']),array('class' => 'a_r'), MY, true);
        $form->addTag('br');
    
        $form->addLabel(MY, 'pocet_kusu',array(), 'Počet dosputných kusů, který se zobrazí návštěvníkům. 
        	Pokud není produkt omezen počtem, nechte pole prázdné');
        $form->addInput('text', 'pocet_kusu', MY,array('class' => 'a_r'), MY, true);
        
        $form->addTag('br');
        $form->addLabel(MY, 'sleva_procent',array());
        $form->addInput('text', 'sleva_procent', Tools::numberFromDb($entita->sleva_procent*100),array('class' => 'a_r'), MY, true);
    
        $form->addLabel(MY, 'sleva_pocet',array(), 'Počet slevněných kusů. Pokud je pole prázdné, není sleva množstevně omezená.');
        $form->addInput('text', 'sleva_pocet', MY,array('class' => 'a_r'), $entita->validate['sleva_pocet'], true);
        
        $form->addLabel(MY, 'sleva_od',array(), 'Zadejte datum ve formátu dd.mm.rrrr');
        $form->addInput('text', 'sleva_od', Tools::dateToCZ($entita->sleva_od),array('class' => 'a_r'), MY, true);
    
        $form->addLabel(MY, 'sleva_do',array(), 'Zadejte datum ve formátu dd.mm.rrrr');
        $form->addInput('text', 'sleva_do', Tools::dateToCZ($entita->sleva_do),array('class' => 'a_r'), MY, true);
    
        $form->closeFieldset();
        $form->openFieldset('Meta informace');
    
        $form->addLabel(MY, 'meta_title', array(), 'Zobrazuje se v záhlaví stránky');
        $form->addInput('text', 'meta_title', MY,array(), MY);
        $form->addInput('button','nazev_kopi','Zkopírovat název',array('onclick' => 'titleCopy();'));
        $form->addInput('button','popis_kopi','Zkopírovat krátký popis',array('onclick' => 'descCopy();'), array(), true);
    
        $form->addLabel(MY, 'meta_keywords', array(), 'Klíčová slova pro vyhledávače. Jednotlivá slova oddělte čárkami');
        $form->addInput('text', 'meta_keywords', MY,array('class' => 'vetsi'), MY,true);
    
        $form->addLabel(MY, 'meta_description', array(), 'Popis stránky pro vyhledávače.');
        $form->addInput('text', 'meta_description', MY,array('class' => 'vetsi'), MY,true);
    
        $form->closeFieldset();
        $form->openFieldset('Ostatní');
        
        $form->addLabel(MY, 'id_zaruka');
        $form->openSelect('id_zaruka', MY, array(), MY);
        $zaruka = new Zaruka();
        $zaznamy = $zaruka->getToSelect();
        foreach($zaznamy as $row) {
          $form->addOption($row['ID'],$row['NAZEV'],'', '', array('title' => $row['POPIS']));
        }
        $form->closeSelect(true);
    
        $form->addLabel(MY, 'id_expedice');
        $form->openSelect('id_expedice', MY, array(), MY);
        $expedice = new Expedice();
        $zaznamy = $expedice->getToSelect();
        foreach($zaznamy as $row) {
          $form->addOption($row['ID'],$row['NAZEV'],'', '', array('title' => $row['POPIS']));
        }
        $form->closeSelect(true);

        $form->addLabel(MY, 'id_vyr' );
        $form->addInput('hidden','id_vyr', MY, array(), MY);
        $form->openTag('a', array('href' => 'http://mvc/admin/lovrequest/vyrobci?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=450&width=700', 'class' => 'thickbox'));
        $form->addInput('text','name_vyr', $entita->name_vyr, array('readonly' => 'readonly'));
        $form->addInnerHTML(' Vybrat');
        $form->closeTag('a');
        $form->addTag('br');

        $form->addLabel(MY, 'priorita');
        $form->openSelect('priorita', MY, array(), MY);
        for($i = 0;$i <= 10;$i++) {
          $form->addOption($i,'&nbsp;'.$i);
        }
        $form->closeSelect(true);    

        $form->addLabel(MY, 'stav' );
        $form->stateSelect($entita, false,MY);

        $form->openTag('div', array('class' => 'bb_l'));
        $form->addTag('hr',array('class' => 'fcleaner '));
        $form->addInput('submit', 'uloz_pokracuj', 'Uložit');
        $form->addInput('reset', 'reset', 'Vrátit změny');
        $form->closeTag('div');
        $form->closeFieldset();
        $form->closeForm();

        return $form->get();
 
	}

	private function upravit_obrazek($entita, $args){

		$id = $args[0];
		$del_en = true;
		if (is_numeric(@$args[1])) {
			$obr_id = $args[1];
			$akce = 'update';
		}
		elseif (@$args[1] == 'posun') {
			$akce = 'posun';
			$obr_id = $args[3];

			$result = dibi::query('SELECT PORADI FROM OBRAZEK_PRODUKTU WHERE ID_PROD = %i AND ID = %i', $id, $obr_id);
			$poradi = $result->fetchSingle();
			dibi::begin();

			if (@$args[2] == 'nahoru') {
				dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI + IF (ID = %i, -1, 1) WHERE ID_PROD = %i AND PORADI IN (%i,%i)',
					$obr_id, $id, $poradi, $poradi -1);
				if (dibi::affectedRows() == 2) {
					dibi::commit();
					Tools::setMessage('Obrázek byl přesunut', '', 1);
				}
				else {
					dibi::rollback();
					Tools::setMessage('Obrázek není kam přesunout', '', 1);
				}
			}
			elseif (@$args[2] == 'dolu') {
				dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI + IF (ID = %i, 1, -1) WHERE ID_PROD = %i AND PORADI IN (%i,%i)',
					$obr_id, $id, $poradi, $poradi +1);
				if (dibi::affectedRows() == 2) {
					dibi::commit();
					Tools::setMessage('Obrázek byl přesunut', '', 1);
				}
				else {
					dibi::rollback();
					Tools::setMessage('Obrázek není kam přesunout', '', 1);
				}
			}

			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('obrazek', $id));
			Tools::redirect($redirect);
      die;
		}
		elseif (@$args[1] == 'smazat') {

			if ($this->registry->picture_delete_enable) {
  			$obr_id = @$args[2];
  			try {
  				$result = dibi::query('SELECT SOUBOR, PORADI FROM OBRAZEK_PRODUKTU WHERE ID = %i', $obr_id);
  				if (count($result) !=  1) {
  					throw new AppliException(2,'Obrázek neexistuje!');
  				}
  				$r = $result->fetchAll();
  				$row = $r[0];
  				dibi::begin();
  				dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI - 1 WHERE PORADI > 
  					%i AND ID_PROD = %i', $row['PORADI'], $id);
  				dibi::query('DELETE FROM OBRAZEK_PRODUKTU WHERE ID = %i', $obr_id);
  				dibi::commit();
  				Tools::deleteFile($row['SOUBOR'],PATH_PRODUKT);
  				Tools::deleteFile($row['SOUBOR'],PATH_PRODUKT.PATH_NAHLED);
  				Tools::setMessage('Obrázek byl smazán', '', 1);
  			}
  			catch(AppliException $e) {
  				Tools::setMessage('Chyba', '', 1);
  				$e->checkLevel(2);
  			}
  			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('obrazek', $id));
  			Tools::redirect($redirect);
        die;
			}
			else {
				$akce = 'insert';
				Tools::setMessage('Nelze smazat obrázek bez potvrzení. Pokud jej chcete opravdu smazat, klikněte na příslušnou ikonu.');
			}

		}
		else{
			$akce = 'insert';
		}

		$this->registry->addPersistent('picture_delete_enable', $del_en, 1);

		$form_id = 'UpravitProduktObrazekForm';
		$obr = new Obrazekproduktu();

    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {
			$obr->id_prod = $entita->id;
   		if ($akce == 'insert') {
   			if (!empty($_FILES['new_img']['name'])) {
      		dibi::begin();
      		if(is_numeric($_POST['poradi'])) {
      			dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI + 1 WHERE PORADI >= %i AND ID_PROD = %i', $_POST['poradi'], $id);
      		}
      		else {
      			unset($_POST['poradi']);
      		}

      		$obr->setFromPost();
      		$obr->insert();
      		$name = $id.'_'.dibi::insertId();
      		try {
        		$soubor = Tools::moveUploadedImage('new_img', PATH_PRODUKT, $name );
        		Tools::pictureResize($soubor, PATH_PRODUKT, PATH_NAHLED, 2);
       			$obr->soubor = $soubor;
       			$obr->update();
       			dibi::commit();
       			Tools::setMessage('Obrázek byl uložen.', '', 1);
      		}
					catch(AppliException $e) {
						Tools::setMessage('Chyba', '', 1);
						$e->checkLevel(2);
						dibi::rollback();
					}
      	}
   		}
      elseif ($akce == 'update'){
      	$obr->loadById($obr_id);
      	dibi::begin();

      	if ($_POST['poradi'] > $obr->poradi) {
      		dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI - 1 WHERE PORADI > %i AND PORADI <= %i AND ID_PROD = %i',$obr->poradi, $_POST['poradi'], $id);
      	}
      	elseif ($_POST['poradi'] < $obr->poradi) {
      		dibi::query('UPDATE OBRAZEK_PRODUKTU SET PORADI = PORADI + 1 WHERE PORADI >= %i AND PORADI < %i AND ID_PROD = %i',$_POST['poradi'] , $obr->poradi , $id);
      	}
      	$obr->setFromPost();

      	try {
      		if (!empty($_FILES['new_img']['name'])) {
      			$name = $obr->soubor;
        		$soubor = Tools::moveUploadedImage('new_img', PATH_PRODUKT, $name , true);
        		Tools::pictureResize($soubor, PATH_PRODUKT, PATH_NAHLED, 2);
       			$obr->soubor = $soubor;
      		}       			
       		$obr->update();
       		dibi::commit();
       		Tools::setMessage('Záznam byl změněn.', '', 1);
      	}
				catch(AppliException $e) {
					Tools::setMessage('Chyba', '', 1);
					$e->checkLevel(2);
					dibi::rollback();
				}
      }

			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('obrazek', $id));
			Tools::redirect($redirect);
      die;
    }

    $this->registry->jscript->addScript('function titleCopy(){
			var name = $("#titulek").val();
			$("#alt").val(name);
			$("#'.$form_id.'").validate().element("#alt");
		}
    ');


  	$form = new Form($form_id, '', 'post', array('class' => 'myForm'));
    $form->setEntitaRef($obr);

    if ($akce != 'update') {
  		$form->openFieldset('Nahrát obrázek');  
      $form->addLabel('Přidat obrázek', 'new_img');
      $form->addInput('file', 'new_img', MY,array(), array('accept' => 'jpg|jpeg|gif|png'),true);
  
      $form->addLabel(MY, 'titulek', array(), 'Titulek se zobrazí po najetí myší nad obrázek');
  		$form->addInput('text', 'titulek', MY, array(), MY,true);
  
      $form->addLabel(MY, 'alt',array(),'Alternativní text - je zobrazen, pokud je vypnuto načítnání obrázku v prohlížeči, nebo nelze obrázek načíst');
  		$form->addInput('text', 'alt', MY, array(), MY);
  		$form->addInput('button', 'copy', 'Zkopírovat titulek', array('onclick' => 'titleCopy();'),array(), true);
/*
  		$form->addLabel(MY, 'id_par', array(),'Rozměry na které bude obrázek upraven.');
  		$form->openSelect('id_par', 2);
      $result = dibi::query('SELECT * FROM [PARAMETRY_OBRAZKU]');
  		foreach($result as $item) {
  			$form->addOption($item['ID'], $item['NAZEV'].' - Š: '.$item['SIRKA'].' V:'.$item['VYSKA']);
  		}
			$form->closeSelect(true);
*/
    	$form->addLabel(MY, 'poradi');
  		$form->openSelect('poradi', 'end');
      $result = dibi::query('SELECT IF(ISNULL(MAX(PORADI)), "1", (MAX(PORADI))) AS PORADI FROM OBRAZEK_PRODUKTU WHERE ID_PROD = %i;', $id);
      $max = $result->fetchSingle();
  		for($i = 1; $i <= $max; $i++) {
  			$form->addOption($i, '&nbsp;'.$i.'&nbsp;');
  		}
			$form->addOption('end', 'Na konec');
  		$form->closeSelect(true);
/*
  		$form->addLabel('Miniatura', 'mini_typ');
  		$form->openSelect('mini_typ', 2);
      $minityp = array('Obdelník ', 'Čtverec');
  		foreach($minityp as $key=>$value) {
  			$form->addOption($key, $value);
  		}
  		$form->closeSelect(true);
*/
      $form->addLabel(MY, 'stav' );
      $form->stateSelect($obr, true, 1);

      $form->openTag('div', array('class' => 'bb_l'));
      $form->addTag('hr',array('class' => 'fcleaner '));
      $form->addInput('submit', 'uloz', 'Uložit');
      $form->closeTag('div');
      $form->closeFieldset();
    }
    else {
    	$form_val = $obr->loadById($obr_id);
    	$form->setValue($form_val);
  		$form->openFieldset('Upravit obrázek');

    	$form->addLabel('Obrázek', '');
  		$form->addInnerHTML('<img src="'.URL.PATH_PRODUKT.PATH_NAHLED.$obr->soubor.'" width="300" />');
  		$form->addTag('br');;
      $form->addLabel(MY, 'titulek', array(), 'Titulek se zobrazí po najetí myší nad obrázek');
  		$form->addInput('text', 'titulek', MY, array(), MY,true);
  
      $form->addLabel(MY, 'alt',array(),'Alternativní text - je zobrazen, pokud je vypnuto načítnání obrázku v prohlížeči, nebo nelze obrázek načíst');
  		$form->addInput('text', 'alt', MY, array(), MY);
  		$form->addInput('button', 'copy', 'Zkopírovat titulek', array('onclick' => 'titleCopy();'),array(), true);
    	$form->addLabel(MY, 'poradi');
  		$form->openSelect('poradi', MY);
      $result = dibi::query('SELECT IF(ISNULL(MAX(PORADI)), "1", (MAX(PORADI))) AS PORADI FROM OBRAZEK_PRODUKTU WHERE ID_PROD = %i;', $id);
      $max = $result->fetchSingle();
  		for($i = 1; $i <= $max; $i++) {
  			$form->addOption($i, '&nbsp;'.$i.'&nbsp;');
  		}
  		$form->closeSelect(true);
  		$form->addLabel('Změnit obrázek', 'new_img');
      $form->addInput('file', 'new_img', MY,array(), array('accept' => 'jpg|jpeg|gif|png'),true);
/*
			$form->addInnerHTML('<br />&nbsp;&nbsp;&nbsp;Následující hodnoty se uplatní pouze v případě, že nahrávate nový soubor<br /><br />');

			$form->addLabel(MY, 'id_par', array(), 'Rozměry na které bude obrázek upraven.');
  		$form->openSelect('id_par', MY);
      $result = dibi::query('SELECT * FROM [PARAMETRY_OBRAZKU]');
  		foreach($result as $item) {
  			$form->addOption($item['ID'], $item['NAZEV'].' - Š: '.$item['SIRKA'].' V:'.$item['VYSKA']);
  		}
  		$form->closeSelect(true);

  		$form->addLabel('Miniatura', 'mini_typ');
  		$form->openSelect('mini_typ', 2);
      $minityp = array('Obdelník ', 'Čtverec');
  		foreach($minityp as $key=>$value) {
  			$form->addOption($key, $value);
  		}
  		$form->closeSelect(true);
*/
      $form->openTag('div', array('class' => 'bb_l'));
      $form->addTag('hr',array('class' => 'fcleaner '));
      $form->addInput('submit', 'upravit', 'Upravit');
      $form->addInput('button', 'zrusit', 'Zrušit', 
      	array('onclick' => 'window.location.href = \''.Tools::controllerlink($this->controller_fname, 'upravit', array('obrazek', $id )).'\'";') );
      $form->addInput('reset', 'reset', 'Vrátit změny');
      $form->closeTag('div');
      $form->closeFieldset();
    }
        
    $form->openFieldset('Upravit obrázky');

		$result = dibi::query('SELECT OP.ID, OP.SOUBOR, OP.TITULEK, OP.ALT, OP.PORADI,
			S.NAZEV AS S_NAZEV FROM ['.$obr->table.'] OP
    	INNER JOIN STAV AS S ON S.STAV_ID = OP.STAV AND ENTITA = %s
			WHERE OP.ID_PROD = %i ORDER BY PORADI', $obr->table, $id);
		$zaznamy = $result->fetchAssoc('ID');

		foreach($zaznamy as $key=>$value) {
			$zaznamy[$key]['IMG'] = '<a href="'.URL.PATH_PRODUKT.$value['SOUBOR'].'" class="thickbox" title="'.$value['TITULEK'].'" rel="test"><img src="'.URL.PATH_PRODUKT.PATH_NAHLED.$value['SOUBOR'].'" alt="'.$value['ALT'].'" width=100 /></a>';
		}
    array_walk($zaznamy,
      'Tools::addLink',
      array(
        'DOLU' => array(
          'link' => Tools::controllerlink($this->controller_fname, 'upravit', array('obrazek', $id, 'posun','dolu')),
          'addindex' => 'ID',
          'text'	 => ICO_DOLU
        ),
        'NAHORU' => array(
          'link' => Tools::controllerlink($this->controller_fname, 'upravit', array('obrazek', $id, 'posun','nahoru')),
          'addindex' => 'ID',
          'text'	 => ICO_NAHORU
        ),
				'UPRAVIT' => array(
          'link' => Tools::controllerlink($this->controller_fname, 'upravit', array('obrazek', $id)),
          'addindex' => 'ID',
          'text'	 => ICO_UPRAVIT
        ),
				'SMAZAT' => array(
        	'click'=> 'var x=confirm(\'Chcete obrázek opravdu smazat ?\');if (x==false) {return false}',
          'link' => Tools::controllerlink($this->controller_fname, 'upravit', array('obrazek', $id, 'smazat')),
          'addindex' => 'ID',
          'text'	 => ICO_SMAZAT
        )
      )
    );
		$hlavicka = array(
			'ID' => 'Id',
			'IMG' => 'Náhled',
			'PORADI' => 'Pořadí',
			'S_NAZEV' => 'Stav',
  		'DOLU' 	 => '',
  		'NAHORU' => '',
			'UPRAVIT'=> '',
			'SMAZAT'=> ''
		);
    $obsah_css = array(
      'ID' 			=> 'a_c',
    	'NAZEV'	=> 'a_r',
    	'PORADI' => 'a_c'
    );

    $hlavicka_css = array(
    	'SMAZAT'  => 'nosort',
    );
    $table = $this->getTable('seznamObrazku', $hlavicka, $zaznamy,
      array('class' => 'seznam', 'summary' => $this->controller_name ),
      $obsah_css, array('ID', 'SMAZAT'), $hlavicka_css);

//		$table = $this->getTable('seznam', $hlavicka, $zaznamy);

    $form->addInnerHTML($table);
    $form->closeFieldset();

		$formular = $form->get();

    return $formular;

	}

	private function upravit_kategorie($entita, $args){

		$id = $args[0];
		$form_id = 'UpravitProduktKategorieForm';
    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {

     	if (isset($_POST['uloz'])) {
  			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('kategorie', $id));
  			$kat_post = array();
  			$kat_db = array();
  			foreach($_POST as $key=>$value) {
  				if ($value == 'on') {
  					$kat_post[] = $key;
  				}
  			}
  			$result = dibi::query('SELECT KP.ID_KAT FROM [KAT_PROD] KP WHERE KP.ID_PROD = %i', $id);
       	foreach($result as $item) {
  				$kat_db[] = $item['ID_KAT'];
  			}
  
  			$insert_diff = array_diff($kat_post, $kat_db);
  			$delete_diff = array_diff($kat_db, $kat_post);
  			
  			dibi::begin();
  			if (count($insert_diff) > 0) {
    			$query = array();
    			$query[] = 'INSERT INTO KAT_PROD (ID_PROD, ID_KAT) VALUES ';
    			$update_array = array();
       	  foreach($insert_diff as $item) {
    				$update_array[] = '('.intval($id).', '.$item.')';
    			}
    			array_push($query, implode(',', $update_array));
  				dibi::query($query);
  			}
  			if (count($delete_diff) > 0) {
  				dibi::query('DELETE FROM KAT_PROD WHERE ID_PROD = %i AND ID_KAT IN (%i)', $id, $delete_diff);
  			}
  			
  			dibi::commit();
				Tools::setMessage('Záznam byl změněn.', '', 1);
        Tools::redirect($redirect);
        die;
      }
    }
    
    $entita->loadById($id);
  
  	$form = new Form($form_id, '', 'post', array('class' => 'myForm'));
    $form->setEntitaRef($entita);

    $form->openFieldset('Zařazení produktu v kategoriích');
    $form->openTag('h1');
    $form->addInnerHTML('Produkt: '.$entita->nazev);
    $form->closeTag();

    $form->openTag('div', array('class' => 'bb_l'));
		$result = dibi::query('SELECT K.ID, CONCAT(REPEAT("&nbsp;&rarr;&nbsp;", K.HLOUBKA - 1),K.NAZEV) AS TEXT,
			IF(KP.ID > 0, "1", "0") AS AKTIVNI
			FROM KATEGORIE K
			LEFT JOIN KAT_PROD KP ON KP.ID_KAT = K.ID AND KP.ID_PROD = %i
			WHERE K.ID > 1 ORDER BY LEVA', $id);
    foreach($result as $item) {
    	$form->addInput('checkbox', $item['ID'], $item['AKTIVNI']);
    	$form->addInnerHTML($item['TEXT']);
    	$form->addTag('br');
    }
    $form->closeTag();
    
    $form->openTag('div', array('class' => 'bb_l'));
    $form->addTag('hr',array('class' => 'fcleaner '));
    $form->addInput('submit', 'uloz', 'Uložit');
    $form->addInput('reset', 'reset', 'Vrátit změny');
    $form->closeTag('div');
    $form->closeFieldset();
    $form->closeForm();
    
	   return $form->get();

	}

	private function upravit_atributy($entita, $args){

		$id = $args[0];
		$form_id = 'UpravitProduktAtributForm';
    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {

     	if (isset($_POST['uloz'])) {
  			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('atributy', $id));
  			if (!is_array(@$_POST['id_hatr'])) {
  				$hatr_post = array();
  			}
  			else {
  				$hatr_post = $_POST['id_hatr'];
  			}
  			$hatr_db = array();

  			$result = dibi::query('SELECT KH.ID_HATR FROM KOMBINACE_HODNOTA KH WHERE KH.ID_PROD = %i', $id);
       	foreach($result as $item) {
  				$hatr_db[] = $item['ID_HATR'];
  			}
  
  			$insert_diff = array_diff($hatr_post, $hatr_db);
  			$delete_diff = array_diff($hatr_db, $hatr_post);

  			dibi::begin();
  			if (count($insert_diff) > 0) {
    			$query = array();
    			$query[] = 'INSERT INTO KOMBINACE_HODNOTA (ID_PROD, ID_HATR) VALUES ';
    			$update_array = array();
       	  foreach($insert_diff as $item) {
    				$update_array[] = '('.intval($id).', '.$item.')';
    			}
    			array_push($query, implode(',', $update_array));
  				dibi::query($query);
  			}
  			if (count($delete_diff) > 0) {
  				dibi::query('DELETE FROM KOMBINACE_HODNOTA WHERE ID_PROD = %i AND ID_HATR IN (%i)', $id, $delete_diff);
  			}

  			dibi::commit();
				Tools::setMessage('Atributy a hodnoty byly uloženy.', '', 1);
        Tools::redirect($redirect);
        die;
     	}
    }

    $this->registry->jscript->addScript('function changeValue() {
    	var atr_id = $("#atribut").val();
    	if (atr_id != ""){
			$.post("'.URL.'admin/ajaxvalidate",{akce: "getAtribValue", id: atr_id },
      		function(data){
        		if (data != "FALSE"){
					$("#hodnoty_atributu").html(data); 
 				}
  			}
  		);
    	}
		}');

	  $this->registry->jscript->addScript('
    function removeItem(my_el) {
    	$(my_el).parent().parent().remove();
    	atrChange = true;
    }');
    
    $this->registry->jscript->addScript('
    function addValue() {
    	if (addToTable == false) {
    		$("#AtributyHodnoty tbody").html("");
    		addToTable = true;
			}
    	var hatr_id = $("#hodnoty_atributu").val();
    	var hatr_name = $("#hodnoty_atributu :selected").text();
    	var atr_id = $("#atribut").val();
    	var atr_name = $("#atribut :selected").text();

    	if (hatr_id == null || hatr_id == "není" || hatr_id == "") {
    		alert("Vyberte hodnotu!");
			}
			else {
				var my = $("#id_atr_"+atr_id).val();
				if (my == undefined) {
      		var radek = \'<tr class="zaznamy"><td><input id="id_atr_\'+atr_id+\'" type="hidden" name="id_atr_\'+atr_id+\'" value="\'+atr_id+\'"/><input id="id_hatr[]" type="hidden" name="id_hatr[]" value="\'+hatr_id+\'"/>\'+atr_name+\'</td><td>\'+hatr_name+\'</td><td  class="a_c" colspan="2"><input type="button" onclick="removeItem(this);" value="Odebrat"></td></tr>\';
      		$("#AtributyHodnoty tbody").append(radek);
      		$("#hodnoty_atributu").effect("transfer",{to: "#AtributyHodnoty"}, 500 );
      		atrChange = true;
      	}
      	else {
      		alert("Atribut "+atr_name+" už je použit. Nelze vložit 2 hodnoty pro jeden atribut! \nPokud chcete vložit jinou hodnotu, musíte nejprve odstranit stávající.");
      	}
			}
		}
		var atrChange = false;
		');

    $entita->loadById($id);
  	$form = new Form($form_id, '', 'post', array('class' => 'myForm'));
    $form->setEntitaRef($entita);
    $form->openFieldset('Atributy produktu');

    $form->openTag('div', array('class' => 'cont_left'));
    $form->addLabel('Zvolte atribut');
    $form->addTag('br');
    $form->addTag('br');
    $form->openSelect('atribut','',array('onchange' => 'changeValue();'));
    $result = dibi::query('SELECT * FROM ATRIBUT WHERE STAV = 1 ORDER BY NAZEV');
    $prvni = '';
   	foreach($result as $item) {
   		if (empty($prvni)) {
   			$prvni = $item;
   		}
	 		$form->addOption($item['ID'], $item['NAZEV']);
    }
    $form->closeSelect(true);

    $form->addLabel('Vyberte hodnotu');
    $form->addTag('br');
    $form->addTag('br');
    $form->openSelect('hodnoty_atributu', '', array('size' => '10'));
	  @$result = dibi::query('SELECT * FROM HODNOTA_ATRIBUTU WHERE ID_ATR = %i AND STAV = 1 ORDER BY HODNOTA', $prvni['ID']);
    $prvni = '';

   	foreach($result as $item) {
	 		$form->addOption($item['ID'], $item['HODNOTA'], '', '', array('ondblclick' => 'addValue()'));
    }
    $form->closeSelect(true);

    $form->addInput('button', 'pridat', 'Přidat hodnotu', array('onclick' => 'addValue()'));
    $form->closeTag();

    $form->openTag('div', array('class' => 'cont_right'));

    $form->addInnerHTML('<h3>Atributy a hodnoty produktu:</h3><table id="AtributyHodnoty" cellspacing="0" class="seznam a_l" summary="Hodnoty atributů produktu">
    	<thead><tr><th class=" ui-corner-tl">Atribut</th><th>Hodnota</th><th><th class="ui-corner-tr"></th></tr></thead><tbody>');
    $result = dibi::query('SELECT KH.ID, A.ID AS A_ID , HA.ID AS HA_ID, A.NAZEV, HA.HODNOTA FROM KOMBINACE_HODNOTA KH
			INNER JOIN HODNOTA_ATRIBUTU HA ON HA.ID = KH.ID_HATR
			INNER JOIN ATRIBUT A ON A.ID = HA.ID_ATR
			WHERE KH.ID_PROD = %i', $id);

    if (count($result) > 0) {
    	foreach($result as $item) {
    		$this->registry->jscript->addScript('var addToTable = true;');
    		$form->addInnerHTML('<tr class="zaznamy"><td>');
    		$form->addInput('hidden', 'id_atr_'.$item['A_ID'], $item['A_ID']);
    		$form->addInput('hidden', 'id_hatr[]', $item['HA_ID']);
    		$form->addInnerHTML($item['NAZEV'].'</td><td>'.$item['HODNOTA'].'</td>
    			<td  class="a_c" colspan="2"><input type="button" onclick="removeItem(this);" value="Odebrat"></td></tr>');
    	}
    }
    else {
    	$this->registry->jscript->addScript('var addToTable = false;');
      $form->addInnerHTML('<tr class="zaznamy"><td colspan="4">Produkt nemá žádné atributy a hodnoty</td></tr>');
    }
    $form->addInnerHTML('</tbody></table>');

    $form->openTag('div', array('class' => 'bb_c'));
    $form->addInput('submit', 'uloz', 'Uložit');
    $form->addInput('button', 'reset', 'Vrátit změny', array('onclick' => 'location.reload()'));
    $form->closeTag('div');

    $form->addTag('hr', array('class' => 'cleaner'));;
    $form->closeTag('div');

    $form->closeFieldset();
    $form->closeForm();

	   return $form->get();

	}

	private function upravit_vlastnosti($entita, $args){

		$id = $args[0];
		$form_id = 'UpravitProduktVlastnostForm';
    if ( $this->registry->form_send AND !isset($_POST['refresh']) ) {

     	if (isset($_POST['uloz'])) {
  			$redirect = Tools::ControllerLink($this->controller_fname,'upravit', array('vlastnosti', $id));
  			if (!is_array(@$_POST['vl_hodnota'])) {
  				$vla_post = array();
  			}
  			else {
  				$vla_post = $_POST['vl_hodnota'];
  			}
  			foreach($vla_post as $key=>$value) {
  				if (empty($value)) {
  					unset($vla_post[$key]);
  				}
  			}
  			$vla_db = array();

  			$result = dibi::query('SELECT V.ID, V.NAZEV, KV.HODNOTA FROM KOMBINACE_VLASTNOST KV
					INNER JOIN VLASTNOST V ON V.ID = KV.ID_VLA
					WHERE KV.ID_PROD = %i', $id);
       	foreach($result as $item) {
  				$vla_db[$item['ID']] = $item['HODNOTA'];
  			}

  			$insert_diff = array_diff($vla_post, $vla_db);
  			$delete_diff = array_diff($vla_db, $vla_post);

  			dibi::begin();
     	  foreach($delete_diff as $key=>$value) {
  				if (isset($insert_diff[$key])) {
  					dibi::query('UPDATE KOMBINACE_VLASTNOST SET HODNOTA = %s WHERE ID_PROD = %i AND ID_VLA = %i',
  					$insert_diff[$key], $id, $key);
  					unset($insert_diff[$key]);
  					unset($delete_diff[$key]);
  				}
  				else {
  					$delete_diff[$key] = $key;
  				}
  			}

  			if (count($insert_diff) > 0) {
    			$query = array();
    			$query[] = 'INSERT INTO KOMBINACE_VLASTNOST (ID_PROD, ID_VLA, HODNOTA) VALUES ';
    			$update_array = array();
       	  foreach($insert_diff as $key=>$item) {
    				$update_array[] = '('.intval($id).', '.$key.', "'.$item.'")';
    			}
    			array_push($query, implode(',', $update_array));
  				dibi::query($query);

  			}
  			if (count($delete_diff) > 0) {
  				dibi::query('DELETE FROM KOMBINACE_VLASTNOST WHERE ID_PROD = %i AND ID_VLA IN (%i)', $id, $delete_diff);
  			}

  			dibi::commit();
				Tools::setMessage('Vlastnosti byly uloženy.', '', 1);
        Tools::redirect($redirect);
        die;
     	}
    }

	  $this->registry->jscript->addScript('
    function removeItem(my_el) {
    	$(my_el).parent().parent().remove();
    	atrChange = true;
    }');

    $this->registry->jscript->addScript('
    function addRow() {
    	if (addToTable == false) {
    		$("#Vlastnosti tbody").html("");
    		addToTable = true;
			}
    	var vla_id = $("#vlastnost").val();
    	var vla_name = $("#vlastnost :selected").text();

    	var my = $("#id_vla_"+vla_id).val();
    	if (my == undefined) {
    		var radek = \'<tr class="zaznamy"><td><input id="id_vla_\'+vla_id+\'" type="hidden" name="id_vla_\'+vla_id+\'" value="\'+vla_id+\'"/>\'+vla_name+\'</td><td  class="a_r"><input name="vl_hodnota[\'+vla_id+\']" type="text" maxlength="100" value=""></td><td>\'+jednotka[vla_id]+\'</td><td  class="a_c" colspan="2"><input type="button" onclick="removeItem(this);" value="Odebrat"></td></tr>\';
    		$("#Vlastnosti tbody").append(radek);
    		$("#vlastnost").effect("transfer",{to: "#Vlastnosti"}, 500 );
    		atrChange = true;
    	}
    	else {
    		alert("Vlastnost "+vla_name+" už je použita. Nelze vložit 2 hodnoty pro jedenu vlastnost!");
    	}
		}
		var atrChange = false;
		');

    $entita->loadById($id);
  	$form = new Form($form_id, '', 'post', array('class' => 'myForm'));
    $form->setEntitaRef($entita);
    $form->openFieldset('Vlastnosti produktu');

    $form->openTag('div', array('class' => 'cont_left'));
    $form->addLabel('Zvolte atribut');
    $form->addTag('br');
    $form->addTag('br');
    $form->openSelect('vlastnost','');
    $result = dibi::query('SELECT * FROM VLASTNOST WHERE STAV = 1 ORDER BY NAZEV');
    $prvni = '';
		$jednotky = 'var jednotka = new Array();'.NEWLINE;
   	foreach($result as $item) {
   		if (empty($prvni)) {
   			$prvni = $item;
   		}
   		$jednotky .= 'jednotka['.$item['ID'].'] = "'.$item['JEDNOTKA'].'";'.NEWLINE;
	 		$form->addOption($item['ID'], $item['NAZEV']);
    }
    $form->closeSelect(true);
		$this->registry->jscript->addScript($jednotky);

    $form->addInput('button', 'pridat', 'Přidat vlastnost', array('onclick' => 'addRow()'));
    $form->closeTag();

    $form->openTag('div', array('class' => 'cont_right'));

    $form->addInnerHTML('<h3>Vlastnosti produktu:</h3><table id="Vlastnosti" cellspacing="0" class="seznam a_l" summary="Hodnoty atributů produktu">
    	<thead><tr><th class=" ui-corner-tl">Vlastnost</th><th>Hodnota</th><th>Jedn.</th><th><th class="ui-corner-tr"></th></tr></thead><tbody>');
    $result = dibi::query('SELECT V.ID, V.NAZEV, KV.HODNOTA, V.JEDNOTKA FROM KOMBINACE_VLASTNOST KV
			INNER JOIN VLASTNOST V ON V.ID = KV.ID_VLA
			WHERE KV.ID_PROD = %i ORDER BY NAZEV', $id);

    if (count($result) > 0) {
    	foreach($result as $item) {
    		$this->registry->jscript->addScript('var addToTable = true;');
    		$form->addInnerHTML('<tr class="zaznamy"><td>');
    		$form->addInput('hidden', 'id_vla_'.$item['ID'], $item['ID']);
    		//$form->addInput('hidden', 'vlastnost[]', $item['ID']);
    		$form->addInnerHTML($item['NAZEV'].'</td><td  class="a_r"><input name="vl_hodnota['.$item['ID'].']" type="text" maxlength="100" value="'.$item['HODNOTA'].'"></td><td>'.$item['JEDNOTKA'].'</td>
    			<td  class="a_c" colspan="2"><input type="button" onclick="removeItem(this);" value="Odebrat"></td></tr>');
    	}
    }
    else {
    	$this->registry->jscript->addScript('var addToTable = false;');
      $form->addInnerHTML('<tr class="zaznamy"><td colspan="5">Produkt nemá žádné vlastnosti</td></tr>');
    }
    $form->addInnerHTML('</tbody></table>');

    $form->openTag('div', array('class' => 'bb_c'));
    $form->addInput('submit', 'uloz', 'Uložit');
    $form->addInput('button', 'reset', 'Vrátit změny', array('onclick' => 'location.reload()'));
    $form->closeTag('div');

    $form->addTag('hr', array('class' => 'cleaner'));;
    $form->closeTag('div');

    $form->closeFieldset();
    $form->closeForm();

	   return $form->get();
		
	}
	
	private function upravit_soubory($entita, $args){
		
	}
}

?>