<?php
/**
 * Sono qui presenti le procedure fondamentali per la gestione del registro di VFront.
 * Il file è organizzato per aree e svolge numerose funzioni
 * 
 * @desc File per la gestione del registro di VFront
 * @package VFront
 * @subpackage Administration
 * @author M.Marcello Verona
 * @copyright 2007-2010 M.Marcello Verona
 * @version 0.96 $Id: gestione_tabelle_gruppi.php 952 2011-04-28 23:34:38Z marciuz $
 * @see gestione_registro.inc.php
 * @license http://www.gnu.org/licenses/gpl.html GNU Public License 
 */



include("../inc/conn.php");
include("../inc/layouts.php");
include("../inc/func.comuni.php");
include("../inc/func.tratta_campo.php");
include("../inc/func.frontend.php");

proteggi(3);

if(isset($_GET['conf_sub'])){
	
	include("../inc/func.tratta_campo_submask.php");
}





###############################################################################################
#
#		Da qui mostra le impostazioni della tabella
#		Con richiamo di funzione esterna per ogna campo.
#
###############################################################################################











/**
 * Da qui � possibile accedere alle impostazioni delle tabelle e eseguire operazioni rapide
 * sulla loro configurazione
 * 
 * @desc Genera il menu delle tabelle
 * @param unknown_type $gid
 * @param unknown_type $order
 */
function tab_menu($gid=0,$order='table_name'){
	
	global  $vmsql, $vmreg, $db1;
	
	
	switch($order){
		case 0: $order = "table_name"; break;
		case 1: $order = "data_modifica"; break;
		case 2: $order = "visibile"; break;
		case 3: $order = "id_table"; break;
		case 4: $order = "commento"; break;
		case 5: $order = "in_insert"; break;
		case 6: $order = "in_update"; break;
		case 7: $order = "in_delete"; break;
		case 8: $order = "n_sottomaschere"; break;
		default: $order = 'table_name'; 
	}
	
	if(isset($_GET['sort'])){
		
		$sort = ($_GET['sort']=="d") ?  "DESC" : "ASC";
	}
	else{
		$sort = "ASC";
	}
	
	// Richiama tutte le tabelle dati
	$sql_tab = "SELECT t.table_name,  t.visibile,  t.in_insert,  t.in_update, 
				 t.in_delete,  t.data_modifica,   t.id_table,  t.commento , t.table_type
				, (SELECT count(*) FROM {$db1['frontend']}{$db1['sep']}registro_submask s WHERE s.id_table=t.id_table) as n_sottomaschere
				FROM {$db1['frontend']}{$db1['sep']}registro_tab t
				WHERE gid=$gid
				ORDER BY t.table_type,  $order $sort ";
	$q_tab= $vmreg->query($sql_tab);
	$matrice_tab = $vmreg->fetch_assoc_all($q_tab);


	echo openLayout1(_("Table administration"),array("sty/admin.css","js/mostra_nascondi_id.js"));

	
	
	echo breadcrumbs(array("HOME","ADMIN","menu_registri.php"=>_("menu groups/registries"),""));

	echo "<h1>"._("Rules table group")." <span class=\"var\">$gid::".gid2nome_gruppo($gid)."</span></h1>\n";
	

	#############################################
	#
	#
	#	FUNZIONI RAPIDE
	#
	#
	
	echo "<div style=\"padding:5px 0 20px 0;\"><a href=\"javascript:;\" onclick=\"mostra_nascondi('tab-menu-rapide');\">"._("Quick functions")."</a></div>\n";
	
	echo "
	
		<div id=\"tab-menu-rapide\"  style=\"display:none\">
			<fieldset style=\"padding:10px;margin:10px;width:85%;\">
				<legend>"._("Quick settings")."</legend>
				<p><strong>"._("Visibility (SELECT)")."</strong>
					<a href=\"?gid=$gid&amp;mass=visibile_all\">"._("Allow from all tables")."</a> | 
					<a href=\"?gid=$gid&amp;mass=visibile_none\">"._("Deny from all tables")."</a></p>
				<p><strong>"._("INSERT")."</strong>
				<a href=\"?gid=$gid&amp;mass=insert_all\">"._("Allow in all tables")."</a> | 
					<a href=\"?gid=$gid&amp;mass=insert_none\">"._("Deny from all tables")."</a></p>
				<p><strong>"._("UPDATE")."</strong>
				<a href=\"?gid=$gid&amp;mass=update_all\">"._("Allow in all tables")."</a> | 
					<a href=\"?gid=$gid&amp;mass=update_none\">"._("Deny from all tables")."</a></p>
				<p><strong>"._("DELETE")."</strong>
				<a href=\"?gid=$gid&amp;mass=delete_all\">"._("Allow in all tables")."</a> | 
					<a href=\"?gid=$gid&amp;mass=delete_none\">"._("Deny from all tables")."</a>
				</p>
			</fieldset>
			<br/>
			<br/>
		</div>
		";
	
	
	
	
	echo "<table summary=\"tabelle db per utenti\" id=\"tab-tabelle\" >\n";
	
	$c=0;
	
	
	echo "\t<tr>\n";
	
	echo "\t\t<th>".table_sort(_('visible'),2,_('Table visibility setting'))."</th>\n";
	echo "\t\t<th>".table_sort(_('table'),0,_('Table name'))."</th>\n";
	echo "\t\t<th>".table_sort(_('Last settings'),1,_('Last date for this table setting'))."</th>\n";
	echo "\t\t<th>".table_sort(_('subforms'),8,_('number of subforms for this table'))."</th>\n";
	echo "\t\t<th>".table_sort(_('comment'),4,_('Table comment'))."</th>\n";
	echo "\t\t<th>".table_sort('insert',5,_('Permission for data insertion for this table by this group'))."</th>\n";
	echo "\t\t<th>".table_sort('update',6,_('Permission for data editing for this table by this group'))."</th>\n";
	echo "\t\t<th>".table_sort('delete',7,_('Permission for deleting data from this subform by this group'))."</th>\n";
	
	
	echo "\t</tr>\n";
	
	$inizia_vista=true;
	
	foreach($matrice_tab as $tab){
		
		$colore=(($c%2)==0) ? "c1":"c2";
		$c++;
		
		if($tab['data_modifica']>0) {
			$data_mod = date("Y-m-d H:i",$tab['data_modifica']);
			$color_href="";
			$title_href='';
		}
		else{
			$data_mod = "-";
			$color_href=" class=\"dafare\"";
			$title_href="title=\""._("This table is not configured yet")."\"";
		}
		
		 $n_sottomaschere = ($tab['n_sottomaschere']>0) ? "<strong>".$tab['n_sottomaschere']."</strong>" : "<span class=\"grigio\">".$tab['n_sottomaschere']."</span>";
		
		 
		 // SEPARATORE PER LE VISTE
		 
		 if($tab['table_type']=='VIEW' && $inizia_vista==true){
		 	
		 	echo "\t\t<tr class=\"separatore\" style=\"padding-top:50px;margin-top:10px;\">
		 		<td colspan=\"7\"><hr /><h2>"._("Tables views")."</h2></td>
		 		</tr>\n";
		 	
		 	$inizia_vista=false;
		 }
		 
		 
		 
		echo "\t\t<tr class=\"$colore\">
				<td>".high_si_no($tab['visibile'])."</td>
				
				<td><a $title_href $color_href href=\"".$_SERVER['PHP_SELF']."?det=".$tab['id_table']."&amp;gid=$gid\">".$tab['table_name']."</a></td>
				<td>".$data_mod."</td>
				<td>".$n_sottomaschere."</td>
				<td>".htmlentities($tab['commento'],ENT_QUOTES, FRONT_ENCODING)."</td>
				<td>".high_si_no($tab['in_insert'])."</td>
				<td>".high_si_no($tab['in_update'])."</td>
				<td>".high_si_no($tab['in_delete'])."</td>
			</tr>\n";
	}
	
	echo "</table>\n";

	echo closeLayout1();

}






/**
 * Genera il menu delle sottomaschere
 *
 * @param int $oid
 * @param int $order
 */
function submask_menu($oid=0,$order='nome_tabella'){
	
	global  $vmsql, $vmreg, $db1;

	$gid= (int) $_GET['gid'];
	
	switch($order){
		case 0: $order = "nome_tabella"; break;
		case 1: $order = "data_modifica"; break;
		case 2: $order = "sub_select"; break;
		case 3: $order = "sub_insert"; break;
		case 4: $order = "sub_update"; break;
		case 5: $order = "sub_delete"; break;
		default: $order = 'nome_tabella'; 
	}
	
	if(isset($_GET['sort'])){
		
		$sort = ($_GET['sort']=="d") ?  "DESC" : "ASC";
	}
	else{
		$sort = "ASC";
	}
	
	// Richiama tutte le tabelle dati
	$sql_tab = "SELECT id_submask,sub_select,sub_insert,sub_update,sub_delete,nome_tabella,
					campo_pk_parent,campo_fk_sub,orderby_sub,orderby_sub_sort,data_modifica
				FROM {$db1['frontend']}{$db1['sep']}registro_submask
				WHERE id_table=$oid
				ORDER BY $order $sort ";
	$q_tab= $vmreg->query($sql_tab);
	$matrice_tab = $vmreg->fetch_assoc_all($q_tab);


		
	echo "<h2>"._("Table subforms rules")." <span class=\"var\">".oid2name($oid)."</span></h2>\n";
	

	echo "<table summary=\"sottomaschere tabelle\" id=\"tab-sub-tabelle\" >\n";
	
	$c=0;
	
	
	echo "\t<tr>\n";
	
	echo "\t\t<th height=\"20\"><span class=\"help\" title=\""._("Table visibility setting")."\">"._("visible")."</span></th>\n";
	echo "\t\t<th><span class=\"help\" title=\""._("Table name")."\">"._("table")."</span></th>\n";
	echo "\t\t<th><span class=\"help\" title=\""._("Last date for this subform settings")."\">"._("Last settings")."</span></th>\n";
	echo "\t\t<th><span class=\"help\" title=\""._("Permission to insert data from this subform by this group")."\">"."insert"."</span></th>\n";
	echo "\t\t<th><span class=\"help\" title=\""._("Permission to edit data from this subform by this group")."\">"."update"."</span></th>\n";
	echo "\t\t<th><span class=\"help\" title=\""._("Permission to delete data from this subform by this group")."\">"."delete"."</span></th>\n";
	echo "\t\t<th>&nbsp;</th>\n";
	
	echo "\t</tr>\n";
	
	
	foreach($matrice_tab as $tab){
		
		$colore=(($c%2)==0) ? "c1":"c2";
		$c++;
		
		if($tab['data_modifica']>0) {
			$data_mod = date("Y-m-d H:i",$tab['data_modifica']);
			$color_href="";
			$title_href='';
		}
		else{
			$data_mod = "-";
			$color_href=" class=\"dafare\"";
			$title_href= htmlentities(_("This subform has not been configured yet"),ENT_QUOTES,FRONT_ENCODING);
		}
		
		echo "\t\t<tr class=\"$colore\">
				<td>".high_si_no($tab['sub_select'])."</td>
				<td><a title=\"$title_href\" $color_href href=\"".$_SERVER['PHP_SELF']."?det=$oid&amp;conf_sub=".$tab['id_submask']."&amp;a=3&amp;gid=".$_GET['gid']."\">".$tab['nome_tabella']."</a></td>
				<td>".$data_mod."</td>
				<td>".high_si_no($tab['sub_insert'])."</td>
				<td>".high_si_no($tab['sub_update'])."</td>
				<td>".high_si_no($tab['sub_delete'])."</td>
				<td><a href=\"javascript:;\" onclick=\"if(confirm('"._("Are you sure you delete this subform and its settings?\\n The operation can not be undone")."')){document.getElementById('id_submask').value='".$tab['id_submask']."';document.forms.elimina_submask.submit();}\">"._("Delete")."</a></td>
			</tr>\n";
	}
	
	echo "</table>\n";
	
	echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."?elimina_submask\" id=\"elimina_submask\" name=\"elimina_submask\" style=\"display:none;\">
	
		<input type=\"hidden\" name=\"id_del_submask\" id=\"id_submask\" value=\"0\" />
		<input type=\"hidden\" name=\"oid\" value=\"$oid\" />
		<input type=\"hidden\" name=\"gid\" value=\"$gid\" />
		
		</form>
		";

	
}





/**
 * Mostra la linguetta di dettaglio dei campi per l'amministrazione delle tabelle
 * 
 * @desc Dettaglio per le tabelle
 * @param int $oid
 * @param int $gid
 */
function tab_dett($oid,$gid=0){
	
	global  $vmsql, $vmreg, $db1;
	
	
	$oid= (int) $oid;
	
	$gid= (int) $gid;
	
	
	# Is table or view?
	$q_tipo=$vmreg->query("SELECT table_type FROM {$db1['frontend']}{$db1['sep']}registro_tab WHERE id_table=$oid");
	list($tipo_tab) = $vmreg->fetch_row($q_tipo);
	
	
	# Info table
	$sql_tab = "SELECT rb.*
				FROM {$db1['frontend']}{$db1['sep']}registro_tab rb 
				WHERE rb.id_table=$oid";
	
	$q_tab=$vmreg->query($sql_tab);
	$info=$vmreg->fetch_assoc($q_tab);
	
	
	# PK
	$array_pk=prendi_all_PK(oid2name($oid));

	
	# Prende le FK
	# Individua i campi coinvolti in una relazione esterna e tabella.campo a cui � legato


	list($array_fk,$colref_fk)=prendi_FK($oid);
	
	
	# Inizia a prendere i campi
	
	
	$sql_cols = "SELECT  id_reg,
						id_table,
						column_name,
						column_default,
						is_nullable,
						data_type,
						character_maximum_length,
						column_type,
						extra,
						in_tipo,
						in_default,
						in_visibile,
						in_richiesto,
						in_suggest,
						in_table,
						jstest,
						commento,
						alias_frontend
						
						
						FROM {$db1['frontend']}{$db1['sep']}registro_col 
						WHERE id_table=$oid 
						ORDER BY ordinal_position";
	
	$q_cols=$vmreg->query($sql_cols);
	
	$matrice_col=$vmreg->fetch_assoc_all($q_cols);
	
	$matrice_rev=$vmreg->reverse_matrix($matrice_col);


	// INFO GENERALI PER LA TABELLA
	$ks=array('visibile','in_insert','in_duplica','in_update','in_delete','in_export',
	'in_import','permetti_allegati','permetti_link',
	'permetti_allegati_ins','permetti_allegati_del',
	'permetti_link_ins','permetti_link_del');

	$def=array();
	for($i=0;$i<count($ks);$i++){

		$iii = (string) $info[$ks[$i]];
		$def[$ks[$i]]= (in_array($iii, array("1","t"))) ? "checked=\"checked\" " : "";
	}

	$def['permetti_allegati_display']= (in_array((string) $info['permetti_allegati'], array("1","t"))) ? "" : "none";
	$def['permetti_link_display']= (in_array((string) $info['permetti_link'], array("1","t"))) ? "" : "none";

	
	
	###############################################
	#
	#	Inizia a stampare
	#
	
	$files= array("sty/admin.css","js/mostra_hid.js","js/mostra_nascondi_id.js", 
					"js/test_query.js","sty/linguette.css","js/open_window.js","js/admin_orderby.js"); //,"js/test_campi.js"); 
	
	$files[]="js/scriptaculous/lib/prototype.js";
	$files[]="js/scriptaculous/src/scriptaculous.js";
	$files[]="js/jscolor/jscolor.js";
	
	echo openLayout1(_("Table Administration"),$files);
	

	
	echo breadcrumbs(array("HOME","ADMIN",
					"menu_registri.php"=>_("menu groups/registries"),
					"gestione_tabelle_gruppi.php?gid=$gid" => _("settings registry id")." $gid"));


	$see_now=($_SESSION['user']['livello']==3) ? " - <a href=\"../scheda.php?oid=$oid\" title=\"See now\">"._('See')."</a>\n" : "\n";
	
	if($info['table_type']=='VIEW'){
		echo "\n<h1>"._("View settings")." <span class=\"verde\">".$info['table_name']."</span> "._("for")." <span class=\"verde\">".$gid."</span><span class=\"grigio\">::</span><span class=\"verde\">".gid2nome_gruppo($gid)."</span> $see_now</h1>\n";
	}
	else{
		echo "\n<h1>"._("Table settings")." <span class=\"var\">".$info['table_name']."</span> "._("for")." <span class=\"var\">".$gid."</span><span class=\"grigio\">::</span><span class=\"var\">".gid2nome_gruppo($gid)."</span> $see_now</h1>\n";
	}
	
	
	// Feedback
	if(isset($_GET['feed'])){
		switch($_GET['feed']){
			
			case 'ok_gen': $feed_str="<p class=\"feed-mod-ok\">"._("General settings corrctly modified")."</p>\n";
			break;
			
			case 'ok_gen_trasversale': $feed_str="<p class=\"feed-mod-ok\">"._("General settings for all groups set successfully")."</p>\n";
			break;
			
			case 'ko_gen': $feed_str="<p class=\"feed-mod-ko\">"._("Error editing general settings")."</p>\n";
			break;			
			
			case 'ok_campi': $feed_str="<p class=\"feed-mod-ok\">"._("Fields settings updated successfully")."</p>\n";
			break;
			
			case 'ko_campi': $feed_str="<p class=\"feed-mod-ko\">"._("No change to the settings for the fields")."</p>\n";
			break;	
					
			case 'ok_sub_upd': $feed_str="<p class=\"feed-mod-ok\">"._("Subforms settings updated successfully")."</p>\n";
			break;
			
			case 'ko_sub_upd': $feed_str="<p class=\"feed-mod-ko\">"._("No changes in the submask settings")."</p>\n";
			break;
			
			default: $feed_str="";
		}
		
		echo $feed_str;
	}
		
	
	
	if(!isset($_GET['a']) || $_GET['a']=='1'){
		
		$attiva = 'tabella-gen';
		
		$classe_eti['gen']='attiva';
		$classe_eti['campi']='disattiva';
		$classe_eti['mask']='disattiva';
		$classe_eti['campisort']='disattiva';
		$classe_eti['pulsanti']='disattiva';
			
		
	}
	else if($_GET['a']=='2'){
		
		$attiva = 'tabella-campi';
		
		$classe_eti['gen']='disattiva';
		$classe_eti['campi']='attiva';
		$classe_eti['mask']='disattiva';
		$classe_eti['campisort']='disattiva';
		$classe_eti['pulsanti']='disattiva';
		
		
	}else if($_GET['a']=='3'){
		
		$attiva = 'tabella-sottomaschere';
		
		$classe_eti['gen']='disattiva';
		$classe_eti['campi']='disattiva';
		$classe_eti['mask']='attiva';
		$classe_eti['campisort']='disattiva';
		$classe_eti['pulsanti']='disattiva';
	}
	else if($_GET['a']=='4'){
		
		$attiva = 'campi-sort';
		
		$classe_eti['gen']='disattiva';
		$classe_eti['campi']='disattiva';
		$classe_eti['mask']='disattiva';
		$classe_eti['campisort']='attiva';
		$classe_eti['pulsanti']='disattiva';
	}
	else if($_GET['a']=='5'){
		
		$attiva = 'tabella-pulsanti';
		
		$classe_eti['gen']='disattiva';
		$classe_eti['campi']='disattiva';
		$classe_eti['mask']='disattiva';
		$classe_eti['campisort']='disattiva';
		$classe_eti['pulsanti']='attiva';
	}
	
	
	?>
	
	<script type="text/javascript">
		// <!-- 
	
		var divs = new Array('tabella-gen','tabella-campi','campi-sort','tabella-sottomaschere','tabella-pulsanti');
	
		var attiva = '<?php echo $attiva;?>';
		
		function eti(ido){
			
			for (i=0;i<divs.length;i++){
				$(divs[i]).style.display='none';
				$('li-'+divs[i]).className='disattiva';
			}
			
			// attiva il selezionato
			$(ido).style.display='';
			$('li-'+ido).className='attiva';
			
		}
	
		// -->
	</script>
	
	<?php
	
	
	
	// Apre il box etichette
	
	// attiva disattiva
	
	
	
	echo 
	"<div id=\"box-etichette\">
		
		<ul class=\"eti-var-gr\">
			<li onclick=\"eti('tabella-gen');\" id=\"li-tabella-gen\" class=\"{$classe_eti['gen']}\" >"._("General settings")."</li>
			<li onclick=\"eti('tabella-campi');\" id=\"li-tabella-campi\" class=\"{$classe_eti['campi']}\" >"._("Fields settings")."</li>
			<li onclick=\"eti('campi-sort');\" id=\"li-campi-sort\" class=\"{$classe_eti['campisort']}\" >"._("Fields sort order")."</li>
			<li onclick=\"eti('tabella-sottomaschere');\" id=\"li-tabella-sottomaschere\" class=\"{$classe_eti['mask']}\" >"._("Subforms settings")."</li>
			<li onclick=\"eti('tabella-pulsanti');\" id=\"li-tabella-pulsanti\" class=\"{$classe_eti['pulsanti']}\" >"._("Custom buttoms")."</li>
		</ul>
	</div>
		";
	
	
	
	// CAMPI TABELLA:
	list($campi_tabella,$in_tipo01) = prendi_colonne_frontend($oid,"column_name,in_tipo",false);
	
	
	##############################################################
	#
	#	 FORM IMPOSTAZIONI GENERALI
	#
	#
	#
	
	
	
	$st_gen = (!isset($_GET['a']) || $_GET['a']==1) ? "" : "display:none;"; 
	
	echo "
	
	<div class=\"tabella-gen\" id=\"tabella-gen\" style=\"$st_gen\" >
	
	<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">\n";
	
	
	
	// TABLE ALIAS
	$table_alias= (isset($info['table_alias'])) ? $vmreg->escape($info['table_alias']) : '';
	
	echo "<div id=\"table_alias_cont\">\n";
	echo "<label for=\"table_alias\">"._('Table alias').": </label>";
	echo "<input name=\"table_alias\" id=\"table_alias\" type=\"text\" maxlength=\"100\" size=\"40\" value=\"$table_alias\" />\n";
	echo "<div class=\"info-campo\">"._("Show a different name for the table. If blank shows the original name.")."</div>\n";
	echo "</div>\n";
	
	
	##########################################
	#
	#	ORDERBY BLOCK
	
	
	
	
	echo "
		<div id=\"orderby_tn\">\n";
	
	$array_orderby=explode(",",$info['orderby']);
	$array_orderby_sort=explode(",",$info['orderby_sort']);
	
	$c=0;
	
	do{
		
		$label_text = ($c==0) ? _("Sort by:") : _("and order by:");
		
		echo"
			<div id=\"orderby_tn{$c}\" >
			
				<label for=\"orderby{$c}\" id=\"lab_orderby{$c}\">".$label_text."</label>
				<select name=\"orderby[]\" id=\"orderby{$c}\" >
				";
			
				for($x=0;$x<count($matrice_rev['column_name']);$x++){
					
					$sel = ($matrice_rev['column_name'][$x]==$array_orderby[$c]) ? "selected=\"selected\"" : "";
					
					// se anche chiave primaria, scrivilo
					$pk = ($matrice_rev['column_name'][$x]==$info['campo_pk']) ? " (". _("primary key") .")" : "";
					
					echo "\t\t<option value=\"".$matrice_rev['column_name'][$x]."\" $sel >".$matrice_rev['column_name'][$x]." $pk</option>\n";		
				}
				
			echo "
				</select>
				";
			
			$sel_sort['ASC'] = ($array_orderby_sort[$c]=='ASC') ? "selected=\"selected\"" : "";
			$sel_sort['DESC'] = ($array_orderby_sort[$c]=='DESC') ? "selected=\"selected\"" : "";
			
			$display_remove = ($c==0) ? "style=\"display:none\"" : "";
			
			echo "
			
				<select name=\"orderby_sort[]\" id=\"orderby_sort{$c}\" >
					<option value=\"ASC\" ".$sel_sort['ASC'].">"._("Ascending")."</option>
					<option value=\"DESC\" ".$sel_sort['DESC'].">"._("Descending")."</option>
				</select>
				<span class=\"fakelink\" onclick=\"$(this).up().remove()\" $display_remove >"._('Remove')."</span>
			</div>"; 
			
		$c++;
			
	} while ($c<count($array_orderby));
	
	
	
	echo "</div>\n";	

	echo "<span class=\"fakelink\" onclick=\"add_orderby()\" >"._('Add order by')."</span>\n";
	// fine blocco ORDERBY
			
			
		echo "
		
		<div class=\"info-campo\">"._("Field will be sorted in the default table order")."</div>
		
		<input type=\"hidden\" name=\"visibile\" id=\"visibile-hid\" value=\"0\" />
		<input type=\"checkbox\" name=\"visibile\" id=\"visibile\" value=\"1\" ".$def['visibile']."/>
		<label for=\"visibile\">"._("Table visible")."</label>
		<div class=\"info-campo\">"._("Set whether this table should be visible for this group")."</div>
		
		";
		
		if($info['table_type']=='VIEW'){
			
			
			/*echo "
			<input type=\"hidden\" name=\"in_insert\" id=\"in_insert-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_insert\" id=\"in_insert\" value=\"0\"  disabled=\"disabled\" />
			<label for=\"in_insert\">Inserisci record (INSERT)</label>
			<div class=\"info-campo\">Disabilitato in quanto vista</div>
			";*/
			echo "
			<input type=\"hidden\" name=\"in_insert\" id=\"in_insert-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_insert\" id=\"in_insert\" value=\"1\"  ".$def['in_insert']." />
			<label for=\"in_insert\">"._("Insert records (INSERT)")."</label>
			<div class=\"info-campo\">"._("Allow users from this group to insert new records")."</div>
			";
			
			
			// PRENDE LA DEFINIZIONE VISTA E CERACA JOIN PER IMPOSTARE IL DELETE SI|NO
			$IS=new iSchema();
			$VIEW_UP=$IS->view_is_updatable($info['table_name']);
			
			// IMPOSTAZIONI PER LA MODIFICABILTA' DEI DATI NELLA VISTA (prese dalla definizione della vista stessa)
			
			if($VIEW_UP){
				
				echo "
			
			<input type=\"hidden\" name=\"in_update\" id=\"in_update-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_update\" id=\"in_update\"  value=\"1\" ".$def['in_update']." />
			<label for=\"in_update\">"._("Modify records (UPDATE)")."</label>
			<div class=\"info-campo\">"._("Allow users this group to update existing records")."</div>
			
				";
			}
			else{
				echo "
				
				<input type=\"hidden\" name=\"in_update\" id=\"in_update-hid\" value=\"0\" />
				<input type=\"checkbox\" name=\"in_update\" id=\"in_update\" value=\"0\"  disabled=\"disabled\" />
				<label for=\"in_update\">"._("Modify records (UPDATE)")."</label>
				<div class=\"info-campo\">"._("Disabled in views")."</div>
				
				";
			}
			
			
			
				
				
			if($VIEW_UP){
				
				echo "
				
				<input type=\"hidden\" name=\"in_delete\" id=\"in_delete-hid\" value=\"0\" />
				<input type=\"checkbox\" name=\"in_delete\" id=\"in_delete\" value=\"1\" ".$def['in_delete']." />
				<label for=\"in_delete\">"._("Delete records (DELETE)")."</label>
				<div class=\"info-campo\">"._("Allow users in this group to delete records")."</div>
				";
			}
			else{
				
				echo "
				
				<input type=\"hidden\" name=\"in_delete\" id=\"in_delete-hid\" value=\"0\" />
				<input type=\"checkbox\" name=\"in_delete\" id=\"in_delete\" value=\"0\"  disabled=\"disabled\" />
				<label for=\"in_delete\">"._("Delete records (DELETE)")."</label>
				<div class=\"info-campo\">"._("Disabled in views with JOIN")."</div>
				";
			}
		
		
		}
		// SE invece la tabella � una normale BASE TABLE
		else{
			
				echo "
			<input type=\"hidden\" name=\"in_insert\" id=\"in_insert-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_insert\" id=\"in_insert\" value=\"1\" ".$def['in_insert']." onclick=\"if(this.checked){\$('cont-duplica').style.display='';} else {\$('cont-duplica').style.display='none';}\" />
			<label for=\"in_insert\">"._("Insert records (INSERT)")."</label>
			<div class=\"info-campo\">"._("Allow users from this group to insert new records")."</div>
			";
				
			$style_duplica = ($def['in_insert']=='') ? "display:none;" : '';
				
			echo "
			<div id=\"cont-duplica\" style=\"margin-left:40px;$style_duplica\">
				<input type=\"hidden\" name=\"in_duplica\" id=\"in_duplica-hid\" value=\"0\" />
				<input type=\"checkbox\" name=\"in_duplica\" id=\"in_duplica\" value=\"1\" ".$def['in_duplica']."/>
				<label for=\"in_duplica\">"._("Duplicate record (depending on INSERT permission)")."</label>
				<div class=\"info-campo\">"._("Allow users in this group to duplicate existing records")."</div>
			</div>
			";
			
			echo "
			<input type=\"hidden\" name=\"in_update\" id=\"in_update-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_update\" id=\"in_update\" value=\"1\" ".$def['in_update']."/>
			<label for=\"in_update\">"._("Modify records (UPDATE)")."</label>
			<div class=\"info-campo\">"._("Allow users this group to update existing records")."</div>
			
			<input type=\"hidden\" name=\"in_delete\" id=\"in_delete-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"in_delete\" id=\"in_delete\" value=\"1\" ".$def['in_delete']."/>
			<label for=\"in_delete\">"._("Delete records (DELETE)")."</label>
			<div class=\"info-campo\">"._("Allow this group to delete records")."</div>
			
			
			";
		}
		
		echo "
		
		<input type=\"hidden\" name=\"in_export\" id=\"in_export-hid\" value=\"0\" />
		<input type=\"checkbox\" name=\"in_export\" id=\"in_export\" value=\"1\" ".$def['in_export']."/>
		<label for=\"in_export\">"._("Allow data export")."</label>
		<div class=\"info-campo\">"._("Allow this group to export data")."</div>
		
		";
		
		
			
		$import_check= ($info['table_type']=='VIEW') ? "disabled=\"disabled\"" : '';
		
		echo "
		
		<input type=\"hidden\" name=\"in_import\" id=\"in_import-hid\" value=\"0\" />
		<input type=\"checkbox\" name=\"in_import\" id=\"in_import\" value=\"1\" ".$def['in_import']." $import_check />
		<label for=\"in_import\">"._("Allow data import")."</label>
		<div class=\"info-campo\">"._("Disabled in views")."</div>
		
		";
		
		
		
		
		// IN CASO DI VISTA IMPOSTA ESPLICITAMENTE LA CHIAVE PRIMARIA DELLA TABELLA
		
		if($info['table_type']=='VIEW'){
			
			echo "<label for=\"view_pk\">"._("Set primary key")."</label> ";
			echo "<select id=\"view_pk\" name=\"view_pk\">\n";
	
	
			foreach($campi_tabella as $k=>$campo){
				
				$view_pk_sel = ($info['view_pk']==$campo)? "selected=\"selected\"": "";
				
				echo "<option value=\"$campo\" $view_pk_sel>".$campo."</option>\n";
				
			}
			
			echo "</select>
			<div class=\"info-campo\">"._("In this view you must explicitly define the primary key")."</div>\n";
		}
		
		
		
		echo "
		
		<fieldset style=\"width:60%;margin-bottom:20px; padding:15px;\">
			<legend>"._("Attachments and link")."</legend>
		";
		
		
		// IN CASO DI VISTA IMPOSTA ESPLICITAMENTE LA FONTE PER ALLEGATI E LINK
		
		if($info['table_type']=='VIEW'){
			
			$tabelle_db=prendi_tabelle($_GET['gid']);
			echo "<select id=\"fonte_al\" name=\"fonte_al\">\n";
	
	
			foreach($tabelle_db as $k=>$tab){
				
				$view_fonte_sel = ($info['fonte_al']==$tab['table_name'])? "selected=\"selected\"": "";
				
				echo "<option value=\"{$tab['table_name']}\" $view_fonte_sel>".$tab['table_name']."</option>\n";
				
			}
			
			echo "</select>
			<div class=\"info-campo\">"._("In this view you must define which table should be read or used to add attachments and links")."</div>\n";
		
		}
		
			
		echo "
			<input type=\"hidden\" name=\"permetti_allegati\" id=\"permetti_allegati-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"permetti_allegati\" id=\"permetti_allegati\" value=\"1\" ".$def['permetti_allegati']." onclick=\";if(this.checked){document.getElementById('opzioni_allegati').style.display='';}else{document.getElementById('opzioni_allegati').style.display='none';}\" />
			<label for=\"permetti_allegati\">"._("Table with attachments")."</label>
			<div class=\"info-campo\">"._("Allows you to attach files (documents or images) to records in this table")."</div>
			
			
				<div id=\"opzioni_allegati\" style=\"display:{$def['permetti_allegati_display']}\">
					<input type=\"hidden\" name=\"permetti_allegati_ins\" id=\"permetti_allegati_ins-hid\" value=\"0\" />
					<input type=\"checkbox\" name=\"permetti_allegati_ins\" id=\"permetti_allegati_ins\" value=\"1\" ".$def['permetti_allegati_ins']."/>
					<label for=\"permetti_allegati_ins\">"._("Allow insertion of attachments")."</label>
					
					<br />
					
					
					<input type=\"hidden\" name=\"permetti_allegati_del\" id=\"permetti_allegati_del-hid\" value=\"0\" />
					<input type=\"checkbox\" name=\"permetti_allegati_del\" id=\"permetti_allegati_del\" value=\"1\" ".$def['permetti_allegati_del']."/>
					<label for=\"permetti_allegati_del\">"._("Allow deletions of attachments")."</label>
					
				</div>
			
			
			
			<input type=\"hidden\" name=\"permetti_link\" id=\"permetti_link-hid\" value=\"0\" />
			<input type=\"checkbox\" name=\"permetti_link\" id=\"permetti_link\" value=\"1\" ".$def['permetti_link']." onclick=\";if(this.checked){document.getElementById('opzioni_link').style.display='';}else{document.getElementById('opzioni_link').style.display='none';}\"  />
			<label for=\"permetti_link\">"._("Table with link")."</label>
			<div class=\"info-campo\">"._("Allow links and attachments for this table")."</div>
			
				<div id=\"opzioni_link\" style=\"display:{$def['permetti_link_display']}\">
					<input type=\"hidden\" name=\"permetti_link_ins\" id=\"permetti_link_ins-hid\" value=\"0\" />
					<input type=\"checkbox\" name=\"permetti_link_ins\" id=\"permetti_link_ins\" value=\"1\" ".$def['permetti_link_ins']."/>
					<label for=\"permetti_link_ins\">"._("Allow link insertion")."</label>
					
					<br />
					
					
					<input type=\"hidden\" name=\"permetti_link_del\" id=\"permetti_link_del-hid\" value=\"0\" />
					<input type=\"checkbox\" name=\"permetti_link_del\" id=\"permetti_link_del\" value=\"1\" ".$def['permetti_link_del']."/>
					<label for=\"permetti_link_del\">"._("Allow link deletion")."</label>
					
				</div>
			
		</fieldset>
		<br /><br />
		<input type=\"hidden\" name=\"oid\" value=\"$oid\" />
		<input type=\"hidden\" name=\"gid\" value=\"$gid\" />
		<input id=\"trasversale\" type=\"hidden\" name=\"trasversale_gen\" value=\"0\" />
		
		<input type=\"submit\" name=\"invia_gen\" value=\""._("Save general setting")."\" />
		
		&nbsp;&nbsp;&nbsp;
		
		<input type=\"button\" onclick=\"if(confirm('"._("Warning! Do you really want to change the settings in this way for all groups?")."')){ document.getElementById('trasversale').value='1';submit();}\" name=\"invia_gen_trasversale\" value=\""._("Save general settings for all groups")."\" />
	
	</form>
	
	</div>\n";
		
	//-- fine impostazioni generali
	
	
	
	
	######################################################################################
	#
	#	IMPOSTAZIONI CAMPI SORT
	#
	#
	
	
	$st_sub = (isset($_GET['a']) && $_GET['a']==4) ? "" : "display:none;"; 
	
	echo "<div class=\"campi-sort\" id=\"campi-sort\" style=\"$st_sub\">\n";
	
	
	echo "<h3>"._("Field order")."</h3>\n";
	
	echo "<p>"._("Through this dialogue you can change the order of table fields in the view tab. (Fields in gray are currently set as invisible.) <br /> To change the field order, select the field label and drag it to the desired position")."</p>
	 <form name=\"ripristina\" method=\"post\" action=\"rpc.sortcampi.php?ripristina\" >
	 
	 <input type=\"hidden\" name=\"url\" value=\"".htmlentities($_SERVER['QUERY_STRING'])."\" />
	 <input type=\"hidden\" name=\"oid\" value=\"$oid\" />
	 <input type=\"button\" onclick=\"submit()\" value=\""._("Reset to default order")."\" name=\"ripristina1\" />
	 
	 </form>\n";
	
	
	/* OLD SETTINGS (only vertical)
	
	list($id_reg_sort,$campi_tabella_sort,$in_visibile_sort) = prendi_colonne_frontend($oid,"id_reg,column_name,in_visibile",false);
	
	
	echo "<p id=\"list-info\" >&nbsp;</p>";
	
	echo "<div><ul id=\"firstlist\" style=\"width:200px;\">\n";
	
	
	
	foreach($campi_tabella_sort as $k=>$campo){
		
		$classe_sort = ($in_visibile_sort[$k]=='1') ? "campi-float-blu":"campi-float-grigio";
		
		echo "<li id=\"item_{$id_reg_sort[$k]}\" class=\"$classe_sort\">".$campo."</li>\n";
		
	}
	
	echo "</ul></div>";
	
	
	echo "<script type=\"text/javascript\">
 // <![CDATA[
			Sortable.create('firstlist', 
							{onUpdate:function()
								{new Ajax.Updater('list-info', '".dirname($_SERVER['PHP_SELF'])."/rpc.sortcampi.php?det=$oid&gid=$gid', 
									{onComplete:function(request){}, 
									parameters:Sortable.serialize('firstlist'), 
									evalScripts:true, 
									asynchronous:true});
									setTimeout(\"$('list-info').innerHTML = '&nbsp;'; \", 3000 );
								}
							})
 // ]]>
	</script>";

	*/
	
	
	
	
	/* NEW SETTINGS (2 columns ) */
	
	

	list($id_reg_sort,
		 $campi_tabella_sort,
		 $in_visibile_sort,
		 $data_type,
		 $in_tipo,
		 $maxsize,
		 $in_line) = prendi_colonne_frontend($oid,"id_reg,
		 										   column_name,
		 										   in_visibile,
		 										   data_type,
		 										   in_tipo,
		 										   character_maximum_length,
		 										   in_line",true);
	
	
	$next=1;
	$i=0;
	$li=array(1=>array(),2=>array());
	
	foreach($campi_tabella_sort as $k=>$campo){
		
		$tipo = ($in_tipo[$i]=='' || $in_tipo[$i]==null) ? $data_type[$i] : $in_tipo[$i];
		
		$classe_sort = ($in_visibile_sort[$k]=='1') ? "campi-float-blu":"campi-float-grigio";
		
		if($in_line[$i]!=''){
			
			if(intval($in_line[$i])===0){
				$li[1][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
				$li[2][]=null;
				$next=1;
			}
			else{
				
				if($next==1){
					$li[1][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
					$next=2;
				}
				else{
					$li[2][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
					$next=1;
				}
			}
		}
		else{
		
			if( (($tipo=='varchar' || $tipo=='char') && $maxsize>100)
				|| ($tipo=='text' || $tipo=='mediumtext' || $tipo=='longtext')
				|| ($tipo=='richtext')
				|| ($tipo=='select_from')
                || (strtolower($tipo)=='varchar2')
				|| ($in_visibile_sort[$i]==0)
				){
				
				$li[1][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
				$li[2][]=null;
				$next=1;			
			}
			else{
				if($next==1){
					$li[1][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
					$next=2;
				}
				else{
					$li[2][]=array($id_reg_sort[$i],$campi_tabella_sort[$i],$tipo);
					$next=1;
				}
			}
		}
		
		$i++;
	}
	
	
	echo "<p id=\"list-info\" >&nbsp;</p>";
	
	?>
		
	<div class="colonna-cont">
			<div class="colonna">
			<ul class="sortabledemo" id="firstlist">
			
			<?php 
			
			foreach ($li[1] as $l){
				
				echo "\t\t<li class=\"item\" id=\"li1_".$l[0]."\">
					<div class=\"handle\">".$l[1]."</div> ".$l[2]."
				</li>
				";
				
			}
			?>
			</ul>
		</div>
		<div class="colonna">
			<ul class="sortabledemo" id="secondlist">
				<?php 
			
				foreach ($li[2] as $l){
				
				if($l==null){ echo "\t\t<li class=\"item-null\" >&nbsp;</li>\n"; }
				else{
						
					echo "\t\t<li class=\"item\" id=\"li2_".$l[0]."\">
						<div class=\"handle\">".$l[1]."</div> ".$l[2]."
					</li>
					";	
				}
			}
			?>
			</ul>
		</div>
	</div>
	 
	 <script type="text/javascript">
	 // <![CDATA[
	 
	   Sortable.create("firstlist",
	   	    {dropOnEmpty:true,
		      containment:["firstlist","secondlist"],
		      constraint:false,
		      onUpdate:function(){
		     		new Ajax.Updater('list-info',"rpc.sortcampi.php?getsort",
		     			{
		     				method:'post',
		     				postBody: Sortable.serialize('firstlist')+"&"+Sortable.serialize('secondlist')+"&oid=<?php echo $oid;?>",
		     				evalScripts:true, 
		     				asynchronous:true
		     			});
		     			setTimeout("$('list-info').innerHTML = '&nbsp;'; ", 3000 );
		     		}
		      });
	      
	      
	   Sortable.create("secondlist",
	   	    {dropOnEmpty:true,
		      containment:["firstlist","secondlist"],
		      constraint:false,
		      onUpdate:function(){
		     		new Ajax.Updater('list-info',"rpc.sortcampi.php?getsort",
		     			{
		     				method:'post',
		     				postBody: Sortable.serialize('firstlist')+"&"+Sortable.serialize('secondlist')+"&oid=<?php echo $oid;?>",
		     				evalScripts:true, 
		     				asynchronous:true
		     			});
		     			setTimeout("$('list-info').innerHTML = '&nbsp;'; ", 3000 );
		     		}
		      });
	
	 // ]]>
	 </script>
 
 	<?php
	
	echo "</div>\n";
	
	
	
	//-- fine campi-sort
	
	
	##############################################################
	#
	#	 FORM IMPOSTAZIONI SOTTOMASCHERE
	#
	#
	#
	
	
	
	$sottomaschere = prendi_sottomaschere($oid,true);
	

	
	
	
	$st_sub = (isset($_GET['a']) && $_GET['a']==3) ? "" : "display:none;"; 
	
	echo "<div class=\"tabella-sottomaschere\" id=\"tabella-sottomaschere\" style=\"$st_sub\">\n";
	
	echo "<p><a href=\"javascript:;\" onclick=\"mostra_nascondi('nuova-sottomaschera');\">"._("New subforms")."</a></p>\n";
	
		echo "<div id=\"nuova-sottomaschera\" style=\"display:none;\">\n";
		
			echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">
			
			
				 <select size=\"13\" multiple=\"multiple\" name=\"new_submask[]\">
				 ";
			
			$tabelle = prendi_tabelle($gid);
			
			for($i=0;$i<count($tabelle);$i++){
				
				// test sull'esuistanza delle sottomaschere
				$SUB_esiste = (isset($sottomaschere['nome_tabella']) && in_array($tabelle[$i]['table_name'],$sottomaschere['nome_tabella'])) ? true:false;
					
				if($tabelle[$i]['id_table']!=$oid && !$SUB_esiste)
					echo "\t\t\t<option value=\"".$tabelle[$i]['id_table']."\">".$tabelle[$i]['table_name']."</option>\n";
				
			}
			
			echo "
				 </select>
				
				 <input type=\"hidden\" name=\"oid\" value=\"$oid\" />
				 <input type=\"hidden\" name=\"gid\" value=\"$gid\" />
				 
				<br /><br />
				<input type=\"submit\" name=\"sottomaschere\" value=\""._("Create new subform")."\" />
			</form>\n";
		

	
		echo "</div>\n";
		
		
		## COPIA LE SOTTOMASCHERE
		
		$mat_gruppi_sub = prendi_gruppi($_GET['gid']);
	
		if(count($mat_gruppi_sub)>0){
		
			echo "<form name=\"copia_sottomaschere\" action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">\n";
		
			$sel_gruppi_sub="\t<select name=\"copia_sub_gid\" id=\"copia_sub_gid\" >\n";
			
			
			foreach ($mat_gruppi_sub as $k=>$ar){
				
				$sel_gruppi_sub.="\t\t<option value=\"".$ar['gid']."\">".$ar['gid']. " - ". $ar['nome_gruppo']."</option>\n";
			}
			
			$sel_gruppi_sub.="</select>";
			
			$confirm_cp_sub ="if(confirm('"._("If you copy the subforms settings from another group the currents will be completely overwritten.\\n The operation is not recoverable.\\nWant to proceed?")."')){submit();}";
			echo "<input type=\"hidden\" name=\"copia_sottomaschere\" value=\"1\" />\n";
			echo "<input type=\"hidden\" name=\"det\" value=\"".$_GET['det']."\" />\n";
			echo "<input type=\"hidden\" name=\"gid\" value=\"".$_GET['gid']."\" />\n";
			echo _("Apply the subform settings of group:")." $sel_gruppi_sub  <input type=\"button\" onclick=\"$confirm_cp_sub\" name=\"copia\" value=\" "._("Apply")." \" />\n";
			
			echo "</form>\n";
			
			unset($mat_gruppi_sub);
			unset($confirm_cp_sub);
		}
		
		
	// sottomaschere esistenti:
	
	if(count($sottomaschere)==0){
		
		echo "<p><strong>"._("There are no subforms available for this table/group")."</strong></p>\n";
		
		
		
		if($info['table_type']=='VIEW'){
		
				
				$tabelle_elenco=prendi_tabelle(intval($_GET['gid']));
				
				
				
				echo "<form action=\"".$_SERVER['PHP_SELF']."?det=".$_GET['det']."&amp;gid=".$_GET['gid']."\" method=\"post\" >\n";
				
				echo _("Clone from table:")." <select name=\"id_tabella\">\n";
				
				for($i=0;$i<count($tabelle_elenco);$i++){
					
					echo "<option value=\"".$tabelle_elenco[$i]['id_table']."\">".$tabelle_elenco[$i]['table_name']."</option>\n";
				}
				
				echo "</select>\n";
				echo " <input type=\"hidden\" name=\"clona_sottomaschere_vista\" value=\"1\" />\n";
				echo " <input type=\"hidden\" name=\"id_vista\" value=\"".$_GET['det']."\" />\n";
				echo " <input type=\"button\" onclick=\"submit();\" name=\"clona_impostazioni\" value=\" "._("clone settings")." \" />\n";
				
				echo "</form>\n";
		}
		
		
	}
	else{
		
		submask_menu($oid);
		
	}
		
	
	// Dettagli sottomaschera
	
	if(isset($_GET['conf_sub'])){
		
		// creca l'id della submaschera nei risultati
		$k_sub= array_search($_GET['conf_sub'],$sottomaschere['id_submask']);
		
		
		
		echo "<h3 style=\"margin-top:60px;border-bottom:1px solid #CCC;width:75%;\">"._("Subform general settings")." <span class=\"var\">".$sottomaschere['nome_tabella'][$k_sub]."</span></h3>\n";
		
		echo "<strong>"._("Link between tables")."</strong>: \n";
		
		
		
		
		echo "<form name=\"sub_gen\" action=\"".$_SERVER['PHP_SELF']."?mod_sub_gen\" method=\"post\">\n";
		
		
		#######################################################################
		#
		#
		#	 riferimenti e FK
		
		// prendo le FK
		$rif_sub = prendi_FK($sottomaschere['nome_tabella'][$k_sub],intval($_GET['gid']));
		
		$rif_sub_k=null;
		
		// ce ne sono riferite alla tabella in oggetto?
		for($i=0;$i<count($rif_sub[1]);$i++){
			
			if(preg_match("/^{$info['table_name']}\.[\w]+/",$rif_sub[1][$i])){
				
				$rif_sub_k = $i;
			}
		}
		
		if(!is_null($rif_sub_k)){
			
			$parent_consigliata = substr( $rif_sub[1][$rif_sub_k] ,  strpos($rif_sub[1][$rif_sub_k],".")+1  );
			$this_consigliata = $rif_sub[0][$rif_sub_k];
		}
		
		
		
		echo $info['table_name'].".";
		
		echo "<select name=\"sub_gen[sub_pk_parent]\">\n";
		
		// PRENDI LE COLONNE
		
		list($colonne_parent) = prendi_colonne_frontend($oid,'column_name',false);
		
		list($colonne_this) = prendi_colonne_frontend($sottomaschere['nome_tabella'][$k_sub],'column_name',false,0);
		
		
		
		
		// TESTA LA VISIBILITA' DEL CAMPO
		
		$campo_attuale_fk= $sottomaschere['campo_pk_parent'][$k_sub];
		
		$PK_fk= prendi_PK_oid($oid);
		
		/*var_dump($PK_fk);
		var_dump($sottomaschere);*/
		
		if($campo_attuale_fk!=$PK_fk[0] && $campo_attuale_fk!=''){
			
			$sql_vis_fk="SELECT in_visibile FROM {$db1['frontend']}{$db1['sep']}registro_col 
						WHERE id_table='$oid' AND column_name='$campo_attuale_fk'";
			$q_vis_fk=$vmreg->query($sql_vis_fk);
			
			list($in_visibile_fk)=$vmreg->fetch_row($q_vis_fk);
			
			$campo_fk_visibile = ($in_visibile_fk) ? true:false;
			
		}
		else{
			$campo_fk_visibile=true;
		}
		
		
		

		for($i=0;$i<count($colonne_parent);$i++){
			
			$aggiunta_sub_parent = ($parent_consigliata==$colonne_parent[$i]) ?	 " (consigliata)" : "";
			
			$sel_sub_parent = ($colonne_parent[$i]==$sottomaschere['campo_pk_parent'][$k_sub]) ? "selected=\"selected\"" :"";
			
			echo "\t\t<option value=\"".$colonne_parent[$i]."\" $sel_sub_parent>".$colonne_parent[$i].$aggiunta_sub_parent."</option>\n";
		}
		
		echo "</select>\n";
		
		
		
		echo " ---<strong>&gt;</strong> ".$sottomaschere['nome_tabella'][$k_sub].".";
		
		echo "<select name=\"sub_gen[sub_fk_this]\">\n";
		
		$OPT_SUB_THIS="";
		$OPT_SUB_THIS_ORDER="";
		
		for($j=0;$j<count($colonne_this);$j++){
			
			$aggiunta_sub_this = ($this_consigliata==$colonne_this[$j]) ?	 " (consigliata)" : "";
			
			$sel_sub_this = ($colonne_this[$j]==$sottomaschere['campo_fk_sub'][$k_sub]) ? "selected=\"selected\"" :"";
			
			$sel_sub_this_ord = ($colonne_this[$j]==$sottomaschere['orderby_sub'][$k_sub]) ? "selected=\"selected\"" :"";

			
			$OPT_SUB_THIS.= "\t\t<option value=\"".$colonne_this[$j]."\" $sel_sub_this>".$colonne_this[$j].$aggiunta_sub_this."</option>\n";
			$OPT_SUB_THIS_ORDER.= "\t\t<option value=\"".$colonne_this[$j]."\" $sel_sub_this_ord>".$colonne_this[$j]."</option>\n";
		}
		
		echo $OPT_SUB_THIS;
		
		echo "</select><div class=\"info-campo\">"._("Set the connection between the table records and the subform records")."</div>\n";
		
		
		
		
		
		// MOSTRA AVVISO IN CASO DI CAMPO NON VISIBILE
		
		if(!$campo_fk_visibile){
			
			echo "<span style=\"color:red;font-weight:bold;\">
				"._("WARNING! The selected field in the parent table is not the primary key and is not set as visible!")." "._('When you set a field that is not the primary key, it must be visible. In this case the connection to the table will not work <br /> Set the field as visible (can also be a hidden field) from the Field Settings')."</span><br /><br />\n";
		}
		//---------------------------------------------
		
		
		
		
		
		
		$sub_select_check= ($sottomaschere['sub_select'][$k_sub]=='1') ? "checked=\"checked\"" : "";
		$sub_insert_check= ($sottomaschere['sub_insert'][$k_sub]=='1') ? "checked=\"checked\"" : "";
		$sub_update_check= ($sottomaschere['sub_update'][$k_sub]=='1') ? "checked=\"checked\"" : "";
		$sub_delete_check= ($sottomaschere['sub_delete'][$k_sub]=='1') ? "checked=\"checked\"" : "";
		$tipo_vista_check1= ($sottomaschere['tipo_vista'][$k_sub]=='tabella') ? "checked=\"checked\"" : "";
		$tipo_vista_check2= ($sottomaschere['tipo_vista'][$k_sub]=='scheda') ? "checked=\"checked\"" : "";
		
		$sel_orderby_sub_sort_ASC = ($sottomaschere['orderby_sub_sort'][$k_sub]=="ASC") ? "selected=\"selected\"" : "";
		$sel_orderby_sub_sort_DESC = ($sottomaschere['orderby_sub_sort'][$k_sub]=="DESC") ? "selected=\"selected\"" : "";
		
		// imposta un default su SCHEDA
		if($tipo_vista_check1=='' && $tipo_vista_check2=='') 
			$tipo_vista_check2="checked=\"checked\"";
		
		
		echo "
		
		<label for=\"nome_frontend\">"._("Subform name")."</label><br/> 
		<input type=\"text\" name=\"sub_gen[nome_frontend]\"  id=\"nome_frontend\" value=\"".$sottomaschere['nome_frontend'][$k_sub]."\" maxlength=\"240\" size=\"35\" />
		<div class=\"info-campo\">"._("Subform name shown to users")."</div>
		";
		
		
		/*<label for=\"tipo_vista_1\">Modalit&agrave; di visualizzazione dei dati</label><br/>
		<input type=\"radio\" name=\"sub_gen[tipo_vista]\"  id=\"tipo_vista_1\"  value=\"scheda\" $tipo_vista_check2 /> "._("Form")."
		<input type=\"radio\" name=\"sub_gen[tipo_vista]\"  id=\"tipo_vista_2\" value=\"tabella\" $tipo_vista_check1 /> "._("Table")."
		<div class=\"info-campo\">Modalit&agrave; di visualizzazione dei dati</div>*/
		
		echo "<input type=\"hidden\" name=\"sub_gen[tipo_vista]\"  id=\"tipo_vista_1\"  value=\"scheda\" />\n";

		echo "
		<input type=\"hidden\" name=\"sub_gen[sub_select]\" value=\"0\" />
		<input type=\"checkbox\" name=\"sub_gen[sub_select]\" id=\"sub_select\" value=\"1\" $sub_select_check/>
		<label for=\"sub_select\">"._("Visible (SELECT)")."</label>
		<div class=\"info-campo\">"._("Sets whether submask can be visible for this group")."</div>
		
		<input type=\"hidden\" name=\"sub_gen[sub_insert]\" value=\"0\" />
		<input type=\"checkbox\" name=\"sub_gen[sub_insert]\" id=\"sub_insert\" value=\"1\" $sub_insert_check/>
		<label for=\"sub_insert\">"._("Insert privileges")."</label>
		<div class=\"info-campo\">"._("Sets whether records can be inserted via subforms")."</div>
		
		<input type=\"hidden\" name=\"sub_gen[sub_update]\" value=\"0\" />
		<input type=\"checkbox\" name=\"sub_gen[sub_update]\" id=\"sub_update\" value=\"1\" $sub_update_check/>
		<label for=\"sub_update\">"._("Update privileges")."</label>
		<div class=\"info-campo\">"._("Sets whether records can be updated via subforms")."</div>
		
		<input type=\"hidden\" name=\"sub_gen[sub_delete]\" value=\"0\" />
		<input type=\"checkbox\" name=\"sub_gen[sub_delete]\" id=\"sub_delete\" value=\"1\" $sub_delete_check/>
		<label for=\"sub_delete\">"._("Delete privileges")."</label>
		<div class=\"info-campo\">"._("Sets whether records can be deleted")."</div>
		
		<label for=\"orderby_sub\">"._("Order subform records by:")."</label>
		<select id=\"orderby_sub\" name=\"sub_gen[orderby_sub]\">
			$OPT_SUB_THIS_ORDER
		</select>
		
		<select id=\"orderby_sub_sort\" name=\"sub_gen[orderby_sub_sort]\">
			<option value=\"ASC\" $sel_orderby_sub_sort_ASC>"._("Ascending")."</option>
			<option value=\"DESC\" $sel_orderby_sub_sort_DESC>"._("Descending")."</option>
		</select>		
		<div class=\"info-campo\">"._("Set the sort criteria for the subform")."</div>
		
		
		
		<label for=\"max_records\">"._("Max records in the subform")."</label><br/> 
		<input type=\"text\" name=\"sub_gen[max_records]\"  id=\"max_records\" value=\"".$sottomaschere['max_records'][$k_sub]."\" maxlength=\"3\" size=\"5\" />
		<div class=\"info-campo\">"._("Maximum number of records for the subform. You should not set this number too high, as it could slow down loading of the subform.")."</div>
		
		<input type=\"hidden\" name=\"sub_gen[id_submask]\" value=\"".$sottomaschere['id_submask'][$k_sub]."\" />
		<input type=\"hidden\" name=\"sub_gen[oid]\" value=\"".intval($_GET['det'])."\" />
		<input type=\"hidden\" name=\"sub_gen[gid]\" value=\"".intval($_GET['gid'])."\" />
		
		<input type=\"submit\" name=\"invia_sub_generali\" value=\""._("Save subform general settings")."\" />
		
		";
		
		echo "</form>\n";
		
		
		
		
		
		
		
		###############################################################################################################
		#
		#	IMPOSTAZIONE CAMPI PER LA SOTTOMASCHERA
		#
		#
		#
		
		
		if($sottomaschere['data_modifica'][$k_sub]!=''){
		
			echo "<a name=\"submask_field\"></a>\n";
		
			echo "<h3 style=\"margin-top:60px;border-bottom:1px solid #CCC;width:75%;\">"._("Setting for subform fields")." <span class=\"var\">".$sottomaschere['nome_tabella'][$k_sub]."</span></h3>\n";
		
		
			echo "\t<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."?gid=".$_GET['gid']."&amp;mod_sub_campi\">\n";
	
		
		
			# Inizia a prendere i campi
			
			
			$sql_sub_cols = "SELECT  c.*
								
								FROM {$db1['frontend']}{$db1['sep']}registro_submask_col c, {$db1['frontend']}{$db1['sep']}registro_submask t
								WHERE t.nome_tabella='".$sottomaschere['nome_tabella'][$k_sub]."'
								AND t.id_table=$oid
								AND t.id_submask = c.id_submask
								ORDER BY c.ordinal_position";
			
			$q_sub_cols=$vmreg->query($sql_sub_cols);
			
			$matrice_sub_col=$vmreg->fetch_assoc_all($q_sub_cols);
			
			$matrice_sub_rev=$vmreg->reverse_matrix($matrice_sub_col);
			
			$array_sub_pk=prendi_all_PK($sottomaschere['nome_tabella'][$k_sub],0);
					   
			while(list($k,$array_sub_val)=each($matrice_sub_col)){
				
				
				if($array_sub_val['column_name']==$sottomaschere['campo_fk_sub'][$k_sub]){
					
					
					echo tratta_campo_submask($array_sub_val, $array_sub_pk, $rif_sub[0], $rif_sub[1],$sottomaschere['campo_pk_parent'][$k_sub],$oid);
					
			
				}
				else{
					echo tratta_campo_submask($array_sub_val, $array_sub_pk, $rif_sub[0], $rif_sub[1]);
				}
			}
			
			echo "\t\t<input type=\"hidden\" name=\"oid\" value=\"".intval($_GET['det'])."\" />\n";
			echo "\t\t<input type=\"hidden\" name=\"gid\" value=\"".intval($_GET['gid'])."\" />\n";
			
			echo "\t\t<input type=\"hidden\" name=\"id_submask\" value=\"".intval($_GET['conf_sub'])."\" />\n";
			
			echo "\t\t<input type=\"button\" name=\"invia_campi\" value=\""._("Save field settings")."\" onclick=\"submit()\" />\n";
			
			echo "\t</form>\n";
			
		}
		
		
	}
	
	
	echo "</div>\n";
	
		
	//-- fine impostazioni sottomaschere
	
	
	
	
	
	
	
	
	
	
	
	
	##############################################################
	#
	#	 FORM IMPOSTAZIONI PULSANTI SPECIALI
	#
	#
	#
	
	$st_sub = (isset($_GET['a']) && $_GET['a']==5) ? "" : "display:none;"; 
	
	echo "<div class=\"tabella-pulsanti\" id=\"tabella-pulsanti\" style=\"$st_sub\">\n";
	
	$q_pulsanti=$vmreg->query("SELECT * FROM {$db1['frontend']}{$db1['sep']}button WHERE id_table=$oid");
	
	$n_button=$vmreg->num_rows($q_pulsanti);
	
	$qstring_button=$_SERVER['PHP_SELF']."?det=".intval($_GET['det'])."&amp;gid=".intval($_GET['gid'])."&amp;a=5";
	
		
		
		
	// Form new|modify button
	
	if(isset($_GET['modbutton'])){
		
		$q_button=$vmreg->query("SELECT * FROM {$db1['frontend']}{$db1['sep']}button WHERE id_button=".intval($_GET['modbutton']));
		
		$RSb=$vmreg->fetch_assoc($q_button);
		
		$display_form=true;
		$display_table=false;
		
		$button_reset="<input type=\"button\" id=\"button_reset\" value=\" "
					._('Cancel')." \" onclick=\"location.href='".
					$_SERVER['PHP_SELF']."?det=".$_GET['det']."&amp;gid=".$_GET['gid']."&amp;a=5'\" />";
					
		$sel_button_type=array();
	
		$sel_button_type[0]= ($RSb['button_type']=='link_self') ? "selected=\"selected\"" :'';
		$sel_button_type[1]= ($RSb['button_type']=='link_blank') ? "selected=\"selected\"" :'';
		$sel_button_type[2]= ($RSb['button_type']=='link_shadow') ? "selected=\"selected\"" :'';
		
		
	}
	else{
		
		echo "<p><span class=\"fakelink\" onclick=\"mostra_nascondi('form_new_button_cont')\">"
		._("Create new button")."</span></p>";
		
		$RSb=array();
		$RSb['definition']='';
		
		$display_form=false;
		$display_table=true;
		
		$button_reset="<input type=\"button\" id=\"button_reset\" value=\" "
					._('Cancel')." \" onclick=\"nascondi('form_new_button_cont');\" />";
					
		$sel_button_type=array('','','');
		
	}
	
	$legend_new_button = (isset($_GET['modbutton'])) ? _('Modify custom button') : _('New custom button');
	
	$button_bg_color = (isset($_GET['modbutton'])) ? str_replace("#",'',$RSb['background']) : 'CFF2FF';
	$button_color = (isset($_GET['modbutton'])) ? str_replace("#",'',$RSb['color']) : '000000';
	
	$button_name = (isset($_GET['modbutton'])) ? $RSb['button_name'] : '';
	
	$button_action_label = (isset($_GET['modbutton'])) ? _('Modify button') : _('Create new button');
	$button_action_name = (isset($_GET['modbutton'])) ? 'modbutton' : 'newbutton';
	$button_action_value = (isset($_GET['modbutton'])) ? intval($_GET['modbutton']) : '1';
	
	
	$show_form_button = ($display_form) ? "" : "style=\"display:none\"";
	
	
	// Adv option - only shadowbox
	if(isset($RSb['button_type']) && $RSb['button_type']=='link_shadow'){
		
		$adv_opt=true;
		
		$opt1=explode("&",$RSb['settings']);
		
		if(is_array($opt1)){
			
			foreach ($opt1 as $val) {

				if(strstr($val,"=")!==false){

					list($k,$v)=explode("=",$val);
					$adv_settings[$k]=$v;
				}
			}
		}
		
	}
	else{
		$adv_opt=false;
	}
	
	$button_opt_height=(isset($_GET['modbutton']) && isset($adv_settings['height'])) ?  $adv_settings['height'] : '';
	$button_opt_width=(isset($_GET['modbutton']) && isset($adv_settings['width'])) ? $adv_settings['width'] : '';
	
	$vis_adv_option=($adv_opt) ? '':'display:none';
	
	$campi_tabella_pc=array();
	
	for($i=0;$i<count($campi_tabella);$i++){
		
		$campi_tabella_pc[]=$campi_tabella[$i];
		
		if($in_tipo01[$i]=='select_from'){
			$campi_tabella_pc[]=$campi_tabella[$i].":label";
		}
	}
	
	echo "
	<div id=\"form_new_button_cont\" $show_form_button>
	
		<form id=\"form_new_button\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">
	
		
			<fieldset id=\"form_new_button_fs\" style=\"max-width:780px;\">
				
				<legend>".$legend_new_button."</legend>
	
				
				<p>
					<label for=\"button_name\">"._('Button label').":</label>
					<input type=\"text\" size=\"25\" name=\"button[button_name]\" id=\"button_name\" value=\"$button_name\" />	
				</p>
				
				<p>
					<label for=\"button_type\">"._('Button type').":</label>
					<select id=\"button_type\" name=\"button[button_type]\" onchange=\"if($(this).value=='link_shadow'){ $('advanced_buttons_opt').show();} else{ $('advanced_buttons_opt').hide();} \" >
						<option value=\"link_blank\" {$sel_button_type[1]}>"._('Open dynamic link in new window')."</option>
						<option value=\"link_self\" {$sel_button_type[0]}>"._('Open dynamic link in same window')."</option>
						<option value=\"link_shadow\" {$sel_button_type[2]}>"._('Open dynamic link on shadowbox layer')."</option>
					</select>	
					
				</p>
				
				<div id=\"advanced_buttons_opt\" style=\"$vis_adv_option\">
				
					<p>
						<label for=\"button_opt_height\">height</label>
						<input type=\"text\" name=\"button_opt[height]\" size=\"10\" id=\"button_opt_height\" value=\"$button_opt_height\" /> px
					</p>
					
					<p>
						<label for=\"button_opt_width\">width</label>
						<input type=\"text\" name=\"button_opt[width]\" size=\"10\" id=\"button_opt_width\" value=\"$button_opt_width\" /> px
					</p>
				
				</div>
				
				<p>
					<label for=\"button_bg_color\">"._('Background color for the button').":</label>
					<input class=\"color\" type=\"text\" size=\"10\" name=\"button[background]\" id=\"button_bg_color\" value=\"$button_bg_color\" />	
				</p>
				
				<p>
					<label for=\"button_color\">"._('Label color for the button').":</label>
					<input class=\"color\" type=\"text\" size=\"10\" name=\"button[color]\" id=\"button_color\" value=\"$button_color\" />	
				</p>
				
				
				<div>
					<div style=\"float:left; width:480px;\">
						<label for=\"button_definition\">"._('Link definition').":</label><br />
						<textarea cols=\"60\" rows=\"3\" id=\"button_definition\" name=\"button[definition]\">".$RSb['definition']."</textarea>			
						<div class=\"info-campo\">"
							._('The link (with or without http://) to be opened by the button')."<br />"
							._('You can insert here variables referring to the table, with double braces {{  }}, ')."<br />"
							._('for example http://www.google.com/?q={{your_field_name}} , or')
							._('xml/your_table_name/id/{{ID}}/')."
						</div>
							
					</div>
					
					<div style=\"float:left; width:140px; border-left:1px solid #999;padding-left:1em;\">
					
						"._('Available fields').":<br />".
						
						"<ul><li>{{".implode("}}</li><li>{{",$campi_tabella_pc)."}}</li></ul>
							
							
					
					</div>
				
				</div>
				
				<p style=\"clear:left\">
					<input type=\"hidden\" name=\"button[id_table]\" value=\"".intval($_GET['det'])."\" />
					<input type=\"hidden\" name=\"$button_action_name\" value=\"$button_action_value\" />
					<input type=\"hidden\" name=\"gid\" value=\"".intval($_GET['gid'])."\" />
					<input type=\"submit\" id=\"button_submit\" value=\" ".$button_action_label." \" />	
					
					$button_reset	
				</p>
	
			</fieldset>
	
		</form>
	
	</div>";
		
		
		
		
		
		
		
		
		
		
		
	if($n_button==0){
		
		echo "<p><strong>"._('There are no custom buttons for this table')."</strong></p>\n";
	}
	else{
		
		$show_button_table = ($display_table) ? "" : "style=\"display:none\"";
		
		// mostra riepilogo pulsanti
		
		echo "<table summary=\"buttons\" id=\"table-buttons\" $show_button_table class=\"table-alt\" >\n";
		
		echo "
		<tr>
			<th>ID</th>
			<th>"._('name')."</th>
			<th>"._('type')."</th>
			<th>"._('modify')."</th>
			<th>"._('delete')."</th>
		</tr>\n";
		
		$c=0;
		
		while($RSpp=$vmreg->fetch_assoc($q_pulsanti)){
			
			$class_gr=($c%2==0) ? "class=\"gr\"" :'';
			
			echo "
			<tr $class_gr>
				<td>".$RSpp['id_button']."</td>
				<td>".$RSpp['button_name']."</td>
				<td>".$RSpp['button_type']."</td>
				<td><a href=\"".$qstring_button."&amp;modbutton=".$RSpp['id_button']."\">"._('modify')."</a></td>
				<td><a href=\"".$qstring_button."&amp;delbutton=".$RSpp['id_button']."\">"._('delete')."</a></td>
			</tr>\n";
			
			$c++;
		}
		
		echo "</table>\n";
	}
	
	
	echo "</div>\n";
	
	//-- fine impostazioni pulsanti speciali
	
	
	
	
	
	
	
	
	###############################################################################
	#
	# FORM campi
	#
	
	$st_campi = (isset($_GET['a']) && $_GET['a']==2) ? "" : "display:none;"; 
	
	echo "<div id=\"tabella-campi\" class=\"tabella-campi\" style=\"$st_campi\">\n";
	
	
	if(isset($_GET['feed']) && $_GET['feed']=='copia_ok'){
		
		echo "<p class=\"feed-mod-ok\">"._("Field settings copied successfully")."</p>\n";
		
	}
	
	// COPIA IMPOSTAZIONI DA ALTRO GRUPPO
	
	$mat_gruppi = prendi_gruppi($_GET['gid']);
	
		if(count($mat_gruppi)>0){
		
		echo "\t<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\" id=\"form_copia_campi\">\n"; 
		
		
		
		$sel_gruppi="\t<select name=\"copia_campi_gid\" id=\"copia_campi_gid\" >\n";
		
		
		foreach ($mat_gruppi as $k=>$ar){
			
			$sel_gruppi.="\t\t<option value=\"".$ar['gid']."\">".$ar['gid']. " - ". $ar['nome_gruppo']."</option>\n";
		}
		
		$sel_gruppi.="</select>";
		
		$confirm_cp ="if(confirm('"._("If you copy the subforms settings from another group the currents will be completely overwritten.\\n The operation is not recoverable.\\nWant to proceed?")."')){submit();}";
		echo "<input type=\"hidden\" name=\"copia_campi\" value=\"1\" />\n";
		echo "<input type=\"hidden\" name=\"det\" value=\"".$_GET['det']."\" />\n";
		echo "<input type=\"hidden\" name=\"gid\" value=\"".$_GET['gid']."\" />\n";
		echo _("Copy field setting from group:")." $sel_gruppi  <input type=\"button\" onclick=\"$confirm_cp\" name=\"copia\" value=\" "._('Apply')." \" />\n";
		
		echo "</form>\n";
		
		unset($mat_gruppi);
	}
	
	//------------------------------------
	
	
	echo "\t<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">\n";
	
	
					   
	while(list($k,$array_val)=each($matrice_col)){
		
		echo tratta_campo($array_val, $array_pk, $array_fk, $colref_fk);
	}
	
	echo "\t\t<input type=\"hidden\" name=\"oid\" value=\"$oid\" />\n";
	
	echo "\t\t<input type=\"hidden\" name=\"gid\" value=\"$gid\" />\n";
	
	echo "\t\t<input id=\"trasversale_campi\" type=\"hidden\" name=\"trasversale_campi\" value=\"0\" />\n";
	
	
	echo "\t\t<input type=\"hidden\" name=\"risposta_sql_all\" id=\"risposta_sql_all\" value=\"\" />\n";

	
	
	echo "\t\t<input type=\"button\" name=\"invia_campi\" value=\""._("Save field settings")."\" onclick=\"submit();\" />\n "; //onclick=\"if(test_campi()=='1'){submit();}else{alert('Alcune impostazioni SQL sembrano errate, oppure si � lasciato vuoto un campo SQL. Prego verificare');}\" />
		
	echo "\t\t<input type=\"button\" onclick=\"if(confirm('"
	     ._("Warning! Do you really want to change the settings in this way for all groups?") 
	     ."')){ document.getElementById('trasversale').value='1';submit();}\" name=\"invia_gen_trasversale\" "
	     ."value=\"". _("Save field settings for all groups") ."\" />\n";
	
	
	
	echo "\t</form>\n";
	
	echo "</div>\n";
	
	
	echo closeLayout1();
}




// ----------------------------------  FINE FUNZIONI  -----------------------------------------




















// --------------------------------- AZIONI ---------------------------------------------------












###################################################################################################
#
## INSERIMENTO INFO GENERALI DI TABELLA
#
if(isset($_POST['invia_gen']) || isset($_POST['trasversale_gen'])){
	
	
	$_dati_gen=$vmreg->recursive_escape($_POST);

	// case VIEW
	if(!isset($_dati_gen['in_duplica'])) $_dati_gen['in_duplica']=0;
	
	$clausola_view_pk = (isset($_dati_gen['view_pk'])) ? "view_pk='".$_dati_gen['view_pk']."'," : "";
	$clausola_view_fonte_al = (isset($_dati_gen['fonte_al'])) ? "fonte_al='".$_dati_gen['fonte_al']."'," : "";
	
	
	$sql_gen="UPDATE {$db1['frontend']}{$db1['sep']}registro_tab 
				SET orderby='".implode(",",$_dati_gen['orderby'])."', 
					orderby_sort='".implode(",",$_dati_gen['orderby_sort'])."', 
					visibile=".intval($_dati_gen['visibile']).",
					in_insert=".intval($_dati_gen['in_insert']).",
					in_duplica=".intval($_dati_gen['in_duplica']).",
					in_update=".intval($_dati_gen['in_update']).",
					in_delete=".intval($_dati_gen['in_delete']).",
					in_export=".intval($_dati_gen['in_export']).",
					in_import=".intval($_dati_gen['in_import']).",
					permetti_allegati=".intval($_dati_gen['permetti_allegati']).",
					permetti_allegati_ins=".intval($_dati_gen['permetti_allegati_ins']).",
					permetti_allegati_del=".intval($_dati_gen['permetti_allegati_del']).",
					permetti_link=".intval($_dati_gen['permetti_link']).",
					permetti_link_ins=".intval($_dati_gen['permetti_link_ins']).",
					permetti_link_del=".intval($_dati_gen['permetti_link_del']).",
					table_alias='".$_dati_gen['table_alias']."',
					$clausola_view_pk
					$clausola_view_fonte_al
					data_modifica=".time()."
				WHERE id_table=".intval($_dati_gen['oid']);
	
	if($_dati_gen['trasversale_gen']=='1'){
		
		$q_sub_trasv=$vmreg->query("SELECT table_name FROM {$db1['frontend']}{$db1['sep']}registro_tab WHERE id_table=".intval($_dati_gen['oid']));
		
		list($table_name)=$vmreg->fetch_row($q_sub_trasv);
		
		$sql_gen.=" OR table_name='$table_name'";
	}
	

	
	$q_gen=$vmreg->query($sql_gen);
	
	if($vmreg->affected_rows($q_gen)>0){
		if($_dati_gen['trasversale_gen']=='1'){
			
			header("Location: ".$_SERVER['PHP_SELF']."?gid=".$_dati_gen['gid']."&feed=ok_gen_trasversale&det=".$_dati_gen['oid']."&a=1");
		}
		else{
			
			header("Location: ".$_SERVER['PHP_SELF']."?gid=".$_dati_gen['gid']."&feed=ok_gen&det=".$_dati_gen['oid']."&a=1");
		}
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?gid=".$_dati_gen['gid']."&feed=ko_gen&det=".$_dati_gen['oid']."&a=1");
	}
	
	exit;
}



###################################################################################################
#
## COPIA IMPOSTAZIONI DEI CAMPI DA UN GUPPO AD UN ALTRO
#
else if(isset($_POST['copia_campi'])){
	
	require_once("./gestione_registro.inc.php");
	
	// prendi id_tabella di destinazione
	$nome_tabella_fonte = oid2name($_POST['det']);
	$oid_tabella_fonte= name2oid($nome_tabella_fonte,$_POST['copia_campi_gid']);
	
	$esito_copia= copia_impostazione_campi($oid_tabella_fonte,$_POST['det']);
	
	if($esito_copia)
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$_POST['det']."&gid=".$_POST['gid']."&a=2&feed=copia_ok");
	exit;
	
}




###################################################################################################
#
## COPIA IMPOSTAZIONI DELLE SOTTOMASCHERE DA UN GUPPO AD UN ALTRO
#
else if(isset($_POST['copia_sottomaschere'])){
	
	require_once("./gestione_registro.inc.php");
	
	// prendi id_tabella di destinazione
	$nome_tabella_fonte = oid2name($_POST['det']);
	$oid_tabella_fonte= name2oid($nome_tabella_fonte,$_POST['copia_sub_gid']);
	
	copia_impostazione_sottomaschere($_POST['gid'],$_POST['copia_sub_gid'],$oid_tabella_fonte,$_POST['det']);
	
	header("Location: ".$_SERVER['PHP_SELF']."?det=".$_POST['det']."&gid=".$_POST['gid']."&a=3&feed=copia_ok");
	exit;
	
}





###################################################################################################
#
## CLONAZIONE IMPOSTAZIONI SOTTOMASCHERE DA TABELLA A VISTA AD ESSA RELATIVA
#
else if(isset($_POST['clona_sottomaschere_vista'])){
	
	require_once("./gestione_registro.inc.php");
	
	$ID_TABELLA_ORIGINE= (int) $_POST['id_tabella'];
	$ID_VISTA_DESTINAZIONE= (int) $_POST['id_vista'];
	
	copia_sottomaschere_viste($ID_VISTA_DESTINAZIONE,$ID_TABELLA_ORIGINE);
	
	header("Location: ".$_SERVER['PHP_SELF']."?det=".$ID_VISTA_DESTINAZIONE."&gid=".$_GET['gid']."&a=3");
	exit;
	
}



###################################################################################################
#
## INSERIMENTO INFO SOTTOMASCHERE DI TABELLA
#
else if(isset($_POST['sottomaschere'])){
	
	require_once("./gestione_registro.inc.php");
	
	
	$_dati_gen=$vmreg->recursive_escape($_POST);
	
	$aff=0;
	
	for($i=0;$i<count($_dati_gen['new_submask']);$i++){
		
		$esito_inizializzazione_sub = inizializza_sottomaschera($_dati_gen['oid'], oid2name($_dati_gen['new_submask'][$i]));
	}
	
	
	
	if($esito_inizializzazione_sub){
		header("Location: ".$_SERVER['PHP_SELF']."?gid=".$_dati_gen['gid']."&feed=ok_new_sub&det=".$_dati_gen['oid']."&a=3");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?gid=".$_dati_gen['gid']."&feed=ko_new_sub&det=".$_dati_gen['oid']."&a=3");
	}
	
	
	exit;
}


###################################################################################################
#
## INSERIMENTO INFO CAMPI DELLA  TABELLA
#

else if(isset($_POST['campo'])){
	
	$gid=(int) $_POST['gid'];
	
	$campo=$vmreg->recursive_escape($_POST['campo']);
	
	# contatore per le righe coinvolte
	$affected=0;
	
	foreach($campo as $k=>$val){

		if(!isset($val['in_tipo'])) $val['in_tipo']='';

		$sql="UPDATE {$db1['frontend']}{$db1['sep']}registro_col 
			  SET in_visibile='".$val['in_visibile']."',
			  in_richiesto='".$val['in_richiesto']."',
			  in_suggest='".$val['in_suggest']."',
			  in_tipo='".$val['in_tipo']."',
			  in_table='".$val['in_table']."',
			  alias_frontend='".$val['alias_frontend']."'
				";
				
			if(isset($val['tipo_altro']) || isset($val['hid_enum'])){
				
				// Caso selezione tra valori indicati
				if($val['in_tipo']=="select"){
					$val['tipo_altro']=str_replace(array("\\r","\\n"),array("","[|]"),$val['tipo_altro']);
				}
				elseif ($val['in_tipo']=="select_enum" ){
					$val['tipo_altro']=str_replace(array("\\r","\\n",","),array("","","[|]"),$val['hid_enum']);
				}

				$altro=$val['tipo_altro'];
				
			}
			else{
				$altro=null;
			}
			
			if($altro!==null){
				$sql.=", in_default='".$altro."'
				";
			}
			
			if(isset($val['extra']) && $val['in_tipo']=="hidden"){
				
				$sql.=", extra='".$val['extra']."' ";
			}
			
			
			$sql.=" WHERE id_reg=".intval($k);
		
//			echo $sql;
			
			$q_campi=$vmreg->query($sql,true);
			
			$affected+= $vmreg->affected_rows($q_campi);
			
		}
		
		
	
	
	if($affected>0){
		header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ok_campi&det=".intval($_POST['oid'])."&a=2");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ko_campi&det=".intval($_POST['oid'])."&a=2");
	}
		
	
	exit;
}

###############################################################################################
#
#		MODIFICA IMPOSTAZIONI GENERALI DELLA SOTTOMASCHERA
#
#

else if(isset($_GET['mod_sub_gen']) && isset($_POST['sub_gen'])){
	
	
	$dati_gen_sub =	$vmreg->recursive_escape($_POST['sub_gen']);
	
	$sql_update_sub = sprintf("UPDATE ".$db1['frontend'].$db1['sep']."registro_submask 
					   SET sub_select=%d,
					    sub_insert=%d,
					    sub_update=%d,
					    sub_delete=%d,
					    nome_frontend='%s',
					    campo_pk_parent='%s',
					    campo_fk_sub='%s',
					    orderby_sub='%s',
					    orderby_sub_sort='%s',
					    max_records=%d,
					    data_modifica='%d',
					    tipo_vista='%s'
					   
					   WHERE id_submask=%d
										   
					   ",
						$dati_gen_sub['sub_select'],
						$dati_gen_sub['sub_insert'],
						$dati_gen_sub['sub_update'],
						$dati_gen_sub['sub_delete'],
						$dati_gen_sub['nome_frontend'],
						$dati_gen_sub['sub_pk_parent'],
						$dati_gen_sub['sub_fk_this'],
						$dati_gen_sub['orderby_sub'],
						$dati_gen_sub['orderby_sub_sort'],
						$dati_gen_sub['max_records'],
						time(),
						$dati_gen_sub['tipo_vista'],
						$dati_gen_sub['id_submask']);
						
	$q_sub_up=$vmreg->query($sql_update_sub);
	
	$aff_sub_upd=$vmreg->affected_rows($q_sub_up);

	$gid= (int) $dati_gen_sub['gid'];

	if($aff_sub_upd>0){
		header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ok_sub_upd&det=".intval($dati_gen_sub['oid'])."&conf_sub=".intval($dati_gen_sub['id_submask'])."&a=3");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ko_sub_upd&det=".intval($dati_gen_sub['oid'])."&conf_sub=".intval($dati_gen_sub['id_submask'])."&a=3");
	}
	
	
	
	exit;
}


#############################################################
#
#	MODIFICA CAMPI DELLA SOTTOMASCHERA
#
#

else if(isset($_GET['mod_sub_campi']) && isset($_POST['campo_sub'])){
	
	
	$campo_sub=$vmreg->recursive_escape($_POST['campo_sub']);
	
	
	$gid=(int) $_GET['gid'];
	
	$ID_SUBMASK = (int) $_POST['id_submask'];
	
	
	
	# contatore per le righe coinvolte
	$affected=0;
	
	$vmreg->begin();
	
	foreach($campo_sub as $k=>$val){

		if(!isset($val['in_tipo'])) $val['in_tipo']='';

		$sql="UPDATE {$db1['frontend']}{$db1['sep']}registro_submask_col
			  SET in_visibile='".$val['in_visibile']."',
			  in_richiesto='".$val['in_richiesto']."',
			  in_tipo='".$val['in_tipo']."',
			  alias_frontend='".$val['alias_frontend']."'
				";
				
			if(isset($val['tipo_altro'])){
				
				// Caso selezione tra valori indicati
				if($val['in_tipo']=="select"){
					$altro=str_replace(array("\\r","\\n"),array("","[|]"),$val['tipo_altro']);
				}
				else $altro=$val['tipo_altro'];
				
			}
			elseif(isset($val['in_default'])){
				
				$altro=$val['in_default'];
			}
			else{
				$altro=null;
			}
			
			if($altro!==null)
			$sql.=", in_default='".$altro."'
			";
			
			$sql.=" WHERE id_reg_sub=".intval($k);
		
//			echo "\n\n$sql\n\n";
			
			$q_campi=$vmreg->query($sql,true);
			
			$affected+= $vmreg->affected_rows($q_campi);
		}
		
		
		
		
		if($affected>0){
			$vmreg->commit();
			header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ok_sub_upd&det=".intval($_POST['oid'])."&conf_sub=".intval($_POST['id_submask'])."&a=3");
		}
		else{
			
			$vmreg->rollback();
			header("Location: ".$_SERVER['PHP_SELF']."?gid=$gid&feed=ko_sub_upd&det=".intval($_POST['oid'])."&conf_sub=".intval($_POST['id_submask'])."&a=3");
		}
		
	
	exit;
	
	
}



# Funzioni di modifica di massa
else if(isset($_GET['mass']) && is_numeric($_GET['gid'])){
	
	
	
	switch($_GET['mass']){
	
		case 'visibile_all': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET visibile=1 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'visibile_none': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET visibile=0 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'insert_all': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_insert=1 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'insert_none': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_insert=0 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'update_all': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_update=1 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'update_none': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_update=0 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'delete_all': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_delete=1 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
		case 'delete_none': 
			$q_mass=$vmreg->query("UPDATE {$db1['frontend']}{$db1['sep']}registro_tab SET in_delete=0 WHERE gid=".intval($_GET['gid']));
			$esito=$vmreg->affected_rows($q_mass);
		break;
	
	}
	
	if(isset($esito) && $esito>0){
		
		header("Location: ".$_SERVER['PHP_SELF']."?gid=".intval($_GET['gid'])."&feed=ok_mass");
		exit;
	}
	
}

// -- Fine funzioni modifica di massa

else if(isset($_POST['id_del_submask'])){
	
	// elimina la sottomaschera
	
	$q=$vmreg->query("DELETE FROM ".$db1['frontend'].$db1['sep']."registro_submask WHERE id_submask=".intval($_POST['id_del_submask']));
	
	header("Location: ".$_SERVER['PHP_SELF']."?det=".intval($_POST['oid'])."&gid=".intval($_POST['gid'])."&a=3");
	exit;
}



###################################################
#
#	ACTIONS NEW BUTTON
#
else if(isset($_POST['newbutton'])){
	

	$button_data=$vmreg->recursive_escape($_POST['button']);
	
	
	$button_data['button_name'] = ($button_data['button_name']=='') ? "CustomButton" : $button_data['button_name'];
	
	// opt
	if(intval($_POST['button_opt']['height'])>0 && intval($_POST['button_opt']['width'])>0){
		
		$settings="height=".intval($_POST['button_opt']['height'])."&width=".intval($_POST['button_opt']['width']);
	}
	else{
		$settings='';
	}
	
	$sql_ins_b=sprintf("INSERT INTO {$db1['frontend']}{$db1['sep']}button (button_type, button_name, color, background, definition, id_table, id_utente, settings)
						VALUES ('%s','%s','%s','%s','%s',%d, %d,'%s') ",
						$button_data['button_type'],
						$button_data['button_name'],
						$button_data['color'],
						$button_data['background'],
						$button_data['definition'],
						$button_data['id_table'],
						$_SESSION['user']['uid'],
						$settings
						);
						
	$q_ins_but=$vmreg->query($sql_ins_b);
	
	if($vmreg->affected_rows($q_ins_but)==1){
		
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$button_data['id_table']."&gid=".$_POST['gid']."&a=5&feedins=ok");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$button_data['id_table']."&gid=".$_POST['gid']."&a=5&feedins=ko");
	}
	
	exit;
}


else if(isset($_POST['modbutton'])){
	
	$button_data=$vmreg->recursive_escape($_POST['button']);
	
	$button_data['button_name'] = ($button_data['button_name']=='') ? "CustomButton" : $button_data['button_name'];
	
	// opt
	if(intval($_POST['button_opt']['height'])>0 && intval($_POST['button_opt']['width'])>0){
		
		$settings="height=".intval($_POST['button_opt']['height'])."&width=".intval($_POST['button_opt']['width']);
	}
	else{
		$settings='';
	}
	
	
	$sql_ins_b=sprintf("UPDATE {$db1['frontend']}{$db1['sep']}button SET button_type='%s', button_name='%s', color='%s', 
						background='%s', definition='%s', id_table=%d, id_utente=%d, settings='%s' 
						WHERE id_button=%d ",
						$button_data['button_type'],
						$button_data['button_name'],
						$button_data['color'],
						$button_data['background'],
						$button_data['definition'],
						$button_data['id_table'],
						$_SESSION['user']['uid'],
						$settings,
						$_POST['modbutton']
						);
						
	$q_ins_but=$vmreg->query($sql_ins_b);
	
	if($vmreg->affected_rows($q_ins_but)==1){
		
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$button_data['id_table']."&gid=".$_POST['gid']."&a=5&feedmod=ok");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$button_data['id_table']."&gid=".$_POST['gid']."&a=5&feedmod=ko");
	}
	
	exit;
}

else if(isset($_GET['delbutton'])){
	
	$sql_add= (!is_admin()) ? " AND id_utente=".$_SESSION['user']['uid'] : '';
	
	$q_del_b=$vmreg->query("DELETE FROM {$db1['frontend']}{$db1['sep']}button WHERE id_button=".intval($_GET['delbutton'])." $sql_add");
	
	if($vmreg->affected_rows($q_del_b)==1){
		
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$_GET['det']."&gid=".$_GET['gid']."&a=5&feeddel=ok");
	}
	else{
		header("Location: ".$_SERVER['PHP_SELF']."?det=".$_GET['det']."&gid=".$_GET['gid']."&a=5&feeddel=ko");
	}
}









if(isset($_GET['det']) && (int) $_GET['det']>0){
	
	// mostra i dettagli della tabella
	$oid= (int) $_GET['det'];
	tab_dett($oid,$_GET['gid']);
}
else{
	
	$gid= (int) $_GET['gid'];
	
	// se � selezionato l'ordine
	if(isset($_GET['ord'])) {
		
		tab_menu($gid,intval($_GET['ord']));  
	}
	else{
		
		tab_menu($gid);  
	}
	
	// mostra la lista tabelle
	
}


?>