<?php
/**
 * @package Flatnux_module_navigator
 * @author Alessandro Vernassa <speleoalex@gmail.com>
 * @copyright Copyright (c) 2011
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License
 */
#<fnmodule>navigator</fnmodule>
defined('_FNEXEC') or die('Restricted access');
global $_FN;
require_once "modules/navigator/section_functions.php";
if (file_exists("sections/{$_FN['mod']}/custom_functions.php"))
	require_once "sections/{$_FN['mod']}/custom_functions.php";
$file = FN_GetParam("file",$_GET,"flat");
if ((false === strpos($file,"..")) && $file != "" && file_exists("sections/{$_FN['mod']}/$file"))
{
	include "sections/{$_FN['mod']}/$file";
}
else
{


	$unirecid = FN_GetParam("id",$_GET,"html");
	$op = FN_GetParam("op",$_GET,"html");
//--config-->
	$config = FN_LoadConfig();

	$tables = explode(",",$config['tables']);
	$tablename_default = $tables[0];
	$tablename = $tables[0];
//--config--<
//--------------- creazione tabelle ------------------------------->
	if (!file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}") || !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}.php"))
	{
		$str_table = file_get_contents("modules/navigator/install/fn_files.php");
		$str_table = str_replace("fn_files",$tablename_default,$str_table);
		FN_Write($str_table,$_FN['datadir']."/".$_FN['database']."/$tablename_default.php");
	}

	if ($config['enable_history'] && !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}_versions.php"))
	{
		$Table = FN_XmlTable($tablename);
		if (!isset($Table->fields['recorddeleted']))
		{
			$tfield['name'] = "userupdate";
			$tfield['type'] = "varchar";
			$tfield['frm_show'] = "0";
			addxmltablefield($Table->databasename,$Table->tablename,$tfield,$Table->path);
		}

		$str_table = file_get_contents($_FN['datadir']."/".$_FN['database']."/$tablename_default.php");
		$str_table = str_replace("<primarykey>1</primarykey>","",$str_table);
		$str_table = str_replace("<tables>","<tables>
    <field>
		<name>idversions</name>
		<primarykey>1</primarykey>
		<extra>autoincrement</extra>
		<type>string</type>
	</field>",$str_table);
		FN_Write($str_table,$_FN['datadir']."/".$_FN['database']."/{$tablename_default}_versions.php");
	}
//------------------- tabella delle statistiche -------------------------
	if (!file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}"."_stat") || !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}"."_stat.php"))
	{
		//echo "<br>creazione statistiche $tablename_default";
		$sfields = array();
		$sfields[0]['name'] = "unirecid";
		$sfields[0]['primarykey'] = "1";
		$sfields[1]['name'] = "view";
		echo createxmltable($_FN['database'],$tablename_default."_stat",$sfields,$_FN['datadir']);
	}
//------------------- tabella delle ranks -------------------------
	if ($config['enableranks'] && !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}_"."ranks.php"))
	{
		$str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<?php exit (0)?>
<tables>
	<field>
		<name>unirecid</name>
		<primarykey>1</primarykey>
		<extra>autoincrement</extra>
		<frm_show>0</frm_show>
	</field>
	<field>
		<name>insert</name>
		<type>string</type>
		<frm_show>0</frm_show>
	</field>
	<field>
		<name>username</name>
		<type>string</type>
		<frm_show>0</frm_show>
		<frm_required>1</frm_required>
	</field>
	<field>
		<name>rank</name>
	</field>
	<field>
		<name>unirecidrecord</name>
		<frm_show>0</frm_show>
	</field>
	<indexfield>unirecidrecord</indexfield>
</tables>
";
		FN_Write($str,"{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}_"."ranks.php");
	}
//------------------- tabella permessi tabelle -------------------------
	if (!file_exists("{$_FN['datadir']}/{$_FN['database']}/fieldusers") || !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}"."_stat.php"))
	{
		$sfields = array();
		$sfields[0]['name'] = "unirecid";
		$sfields[0]['primarykey'] = "1";
		$sfields[0]['extra'] = "autoincrement";
		$sfields[1]['name'] = "username";
		$sfields[2]['name'] = "tablename";
		$sfields[3]['name'] = "table_unirecid";
		echo createxmltable($_FN['database'],"fieldusers",$sfields,$_FN['datadir']);
	}
//------------------- tabella permessi tabelle -------------------------
	if ($config['enable_permissions_each_records'] && $config['permissions_records_groups'] != "")
	{
		$tmp = explode(",",$config['permissions_records_groups']);
		foreach ($tmp as $group)
		{
			FN_CreateGroupIfNotExists($group);
		}
	}
//------------------- tabella commenti-------------------------
	if ($config['enablecomments'] && !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}"."_comments") || !file_exists("{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}"."_comments.php"))
	{
		$sfields = array();
		$sfields[0]['name'] = "unirecid";
		$sfields[0]['primarykey'] = "1";
		$sfields[0]['extra'] = "autoincrement";
		$sfields[0]['frm_show'] = "0";
		$sfields[1]['name'] = "insert";
		$sfields[1]['type'] = "string";
		$sfields[1]['defaultvalue'] = "";
		$sfields[1]['frm_show'] = "0";
		$sfields[3]['name'] = "username";
		$sfields[3]['type'] = "string";
		$sfields[3]['frm_show'] = "0";
		$sfields[3]['frm_required'] = "1";
		$sfields[4]['name'] = "title";
		$sfields[4]['frm_it'] = "Titolo";
		$sfields[4]['frm_i18n'] = "title";
		$sfields[4]['type'] = "string";
		$sfields[4]['frm_required'] = "1";
		$sfields[5]['name'] = "comment";
		$sfields[5]['frm_it'] = "Commento";
		$sfields[5]['frm_i18n'] = "comment";
		$sfields[5]['type'] = "text";
		$sfields[5]['frm_rows'] = "10";
		$sfields[5]['frm_required'] = "1";
		$sfields[5]['frm_cols'] = "80";
		$sfields[6]['name'] = "unirecidrecord";
		$sfields[6]['frm_show'] = "0";
		echo createxmltable($_FN['database'],"{$tablename_default}"."_comments",$sfields,$_FN['datadir']);
	}
//--------------- creazione tabelle -------------------------------<
	$recordsperpage = FN_GetParam("rpp",$_GET);
	if ($recordsperpage == "")
		$recordsperpage = $config['recordsperpage'];
	$config['search_orders'] = explode(",",$config['search_orders']);
	$config['search_options'] = explode(",",$config['search_options']);
	$config['navigate_groups'] = explode(",",$config['navigate_groups']);
	$config['search_fields'] = explode(",",$config['search_fields']);
	$config['search_partfields'] = explode(",",$config['search_partfields']);
//--config--<
	$downloadfile = FN_GetParam("downloadfile",$_GET);

	if (isset($_GET['mode']) && $_GET['mode'] == "go")
	{
		FNNAV_GoDownload($downloadfile);
	}

	$Table = FN_XmlForm($tablename_default);

	$Search = new xmldb_searchform($_FN['database'],$tablename,$_FN['datadir'],$_FN['lang'],$_FN['languages'],false);
	echo $Search->HtmlSearchForm();
	$Table->setlayoutTags("<div class=\"frm_title\">",":</div>","","<br />","<fieldset class=\"frm_group\" ><legend>","</legend>","</fieldset><br />");
	if ($config['enable_permissions_each_records'])
	{
		if (!isset($Table->formvals['groupview']))
		{
			$field = array();
			$field['name'] = 'groupview';
			$field['frm_i18n'] = 'limits the display of the content in these groups';
			$field['foreignkey'] = 'fn_groups';
			$field['fk_link_field'] = 'groupname';
			$field['fk_show_field'] = 'groupname';
			$field['frm_type'] = 'multicheck';
			$field['type'] = 'string';
			addxmltablefield($_FN['database'],$tablename,$field,$_FN['datadir']);
		}
		$Table->formvals['groupview']['frm_show'] = 1;
		if ($config['permissions_records_groups'] != "")
		{
			$allAllowedGroups = explode(",",$config['permissions_records_groups']);
			if (isset($Table->formvals['groupview']['options']))
			{
				foreach ($Table->formvals['groupview']['options'] as $k=> $v)
				{
					if (!in_array($v['value'],$allAllowedGroups))
					{
						unset($Table->formvals['groupview']['options'][$k]);
					}
				}
			}
		}
	}
	else
	{
		if (isset($Table->formvals['groupview']))
		{
			$Table->formvals['groupview']['frm_show'] = 0;
		}
	}

//-----------------------------principale ------------------------------------->
	echo "<div id=\"pageresults\">";
	if (FNNAV_CanViewRecords())
	{
		switch($op)
		{
			case "history" :
				$shownavigatebar = true;
				if ($config['enable_history'])
					FNNAV_ViewRecordHistory($unirecid,false,$shownavigatebar); // visualizza la pagina col record
				break;
			case "view" :
				$shownavigatebar = true;
				if (isset($_GET['embed']))
					$shownavigatebar = false;
				if (isset($_GET['inner']))
					$shownavigatebar = false;

				FNNAV_ViewRecordPage($unirecid,false,$shownavigatebar); // visualizza la pagina col record

				FNNAV_ViewComments($unirecid);
				break;
			case "viewcomments" :
				FNNAV_ViewComments($unirecid);
				break;
			case "writecomment" :
				FNNAV_WriteComment($unirecid);
				break;
			case "request" :
				FNNAV_Request($unirecid);
				break;
			case "edit" :
				FNNAV_EditRecordForm($unirecid,$Table); // form edita record

				break;
			case "new" :
				if (isset($_POST['xmldbsave']))
				{
					FNNAV_InsertRecord($Table);
					FNNAV_WriteSitemap();
				}
				else
				{
					FNNAV_NewRecordForm($Table); //  form nuovo record
				}
				break;
			case "users" :
				FNNAV_UsersForm($unirecid); //  form nuovo record
				break;
			case "delcomment" :
				FNNAV_DelComment($unirecid); //  form nuovo record
				break;
			case "del" :
				FNNAV_DelRecordForm($unirecid); //  form nuovo record
				break;
			case "updaterecord" :
				if (count($_POST) == 0 || isset($_POST['__NOSAVE']) || !isset($_POST['xmldbsave']))
				{
					FNNAV_EditRecordForm($unirecid,$Table);
				}
				else
				{
					FNNAV_UpdateRecord($Table); // esegue aggiornamento record
					FNNAV_GenerateRSS();
				}
				break;
			case "insertrecord" : // esegue inserimento record
				break;
			case "updatesitemap" :
				FNNAV_WriteSitemap();
				dprint_xml(file_get_contents("sitemap-$tablename.xml"));
				dprint_xml(file_get_contents("index-$tablename.html"));
				break;
			default :
				if (FN_IsAdmin() && isset($_GET["refresh_rss"]))
				{
					FNNAV_GenerateRSS();
				}
				echo FN_HtmlContent("sections/{$_FN['mod']}");
				FNNAV_ViewGridForm(); //griglia con tutti i records

				break;
		}
	}
	else
	{
		echo FN_i18n("you are not authorized to view the data");
	}
	echo "</div>";
//-----------------------------principale -------------------------------------<
}
/**
 *
 */
function FNNAV_ViewGridForm()
{
	global $_FN;
	//--config-->
	$config = FN_LoadConfig();
	$tables = explode(",",$config['tables']);
	$search_fields = $config['search_fields'] != "" ? explode(",",$config['search_fields']) : array();
	$search_partfields = $config['search_fields'] != "" ? explode(",",$config['search_partfields']) : array();
	$search_orders = $config['search_orders'] != "" ? explode(",",$config['search_orders']) : array();
	$navigate_groups = $config['navigate_groups'] != "" ? explode(",",$config['navigate_groups']) : array();
	$search_options = $config['search_options'] != "" ? explode(",",$config['search_options']) : array();
	$search_min = $config['search_min'] != "" ? explode(",",$config['search_min']) : array();

	//--config--<
	$recordsperpage = FN_GetParam("rpp",$_GET);
	if ($recordsperpage == "")
		$recordsperpage = $config['recordsperpage'];
	if (file_exists("sections/{$_FN['mod']}/top.php"))
	{
		include ("sections/{$_FN['mod']}/top.php");
	}
	$p = FN_GetParam("p",$_GET);
	$op = FN_GetParam("op",$_GET);
	$navigate = FN_GetParam("nav",$_GET);
	$results = FNNAV_GetResults($config);
	FNNAV_SearchForm($search_orders,$tables,$search_options,$search_min,$search_fields,$search_partfields);
	if ($config['navigate_groups'] != "")
	{
		echo "<div class=\"FNNAV_CategoryShow\" style=\"\">";
		if ($navigate != "1")
		{
			$linkpage = FNNAV_MakeLink(array("nav"=>1),"&amp;");
			echo "<a href=\"$linkpage\">".FN_Translate("browse by categories")."</a> "." <img alt=\"\" src=\"images/right.png\" />";
		}
		else
		{
			$linkpage = FN_RewriteLink("index.php?mod={$_FN['mod']}");
			echo "<a href=\"$linkpage\">".FN_Translate("hide categories")."</a>"." <img alt=\"\" src=\"images/right.png\" />";
		}
		echo "</div>";
	}

	//----------------barra si navigazione categorie--------------------------->
	if ($navigate == 1)
	{

		FNNAV_Navigate($results,$navigate_groups);
	}
	//----------------barra si navigazione categorie---------------------------<
	//-----------------------pagina con i risultati---------------------------->
	if (!empty($config['enable_export']))
	{
		echo "<a href=\"".FNNAV_MakeLink(array("export"=>1),"&amp;")."\">".FN_Translate("export to csv")."</a>";
	}
	echo "<div >";
	FNNAV_PrintList($results);
	echo "</div>";
	//-----------------------pagina con i risultati----------------------------<

	if (FNNAV_CanAddRecord())
	{
		$link = FNNAV_MakeLink(array("op"=>"new"),"&");
		echo "<div class=\"searchnewrecord\"><button class=\"button\" onclick=\"window.location='$link'\"><img style=\"vertical-align: middle;\" src=\"".FN_FromTheme("images/mime/doc.png")."\" alt=\"\" />&nbsp;<b>".FN_Translate("add new")."</b></button></div>";
	}
}

/**
 *
 * @global type $_FN
 * @param type $results
 * @param type $groups 
 */
function FNNAV_Navigate($results,$groups)
{
	global $_FN;
	//--config-->
	$config = FN_LoadConfig();
	//--config--<
	$gresults = array();
	foreach ($results as $tablename=> $res)
	{
		if ($tablename == "")
			continue;
		$Table = FN_XmlForm($tablename);

		//----foreign key ---->
		$i = 0;
		if (is_array($res))
			foreach ($res as $item)
			{
				$data = $item;
				//$data = $Table->xmltable->GetRecordByPrimaryKey($item[$Table->xmltable->primarykey]);
				foreach ($groups as $group)
				{
					if (isset($Table->formvals[$group]['fk_show_field']))
					{
						$fs = $Table->formvals[$group]['fk_show_field'];
					}
					//echo "$group ";
					if ($group != "" && isset($data[$group]))
						$gresults[$group][$data[$group]] = isset($gresults[$group][$data[$group]]) ? $gresults[$group][$data[$group]] + 1 : 1;
					$i++;
				}
			}
		//dprint_r($gresults);
		echo "<div class=\"FNNAV_CategoryFilter\" >";
		foreach ($gresults as $groupname=> $group)
		{
			$fk = $Table->xmltable->fields[$groupname]->foreignkey;
			if (isset($Table->formvals[$groupname]['fk_link_field']))
				$pklink = $Table->formvals[$groupname]['fk_link_field'];
			else
				$pklink = "";
			if ($fk != "" && file_exists("{$_FN['datadir']}/{$_FN['database']}/$fk.php"))
			{

				$tablegroup = xmldb_table($_FN['database'],$fk,$_FN['datadir']);
			}
			echo "<div class=\"FNNAV_CategoryFilterItem\" style=\"\">";
			echo "<b>".$Table->formvals[$groupname]['title']."</b>";
			if (isset($_GET["nv_$groupname"]))
			{
				$link = FNNAV_MakeLink(array("nv_$groupname"=>null,"page"=>1));
				echo "&nbsp;&nbsp;<a href=\"$link\">[".FN_Translate("remove filter","aa")."]</a>";
			}
			echo "<div class=\"FNNAV_CategoryFilterItemContents\">";
			echo "<table cellpsdding=\"0\" cellspacing=\"0\">";
			$group2 = array();
			foreach ($group as $groupcontentsname=> $groupcontentsnums)
			{
				$tmp['total'] = $groupcontentsnums;
				$tmp['name'] = $groupcontentsname;
				$group2[] = $tmp;
			}
			$group2 = FN_ArraySortByKey($group2,"name");
			foreach ($group2 as $group)
			{
				$groupcontentsnums = $group['total'];
				$groupcontentsname = $group['name'];
				if ($groupcontentsname == "")
					$groupcontentstitle = "<span style=\"color:red\">[---]</span>";
				else
				{
					if ($pklink != "")
					{
						$restr = array($pklink=>$group['name']);
						$t = $tablegroup->GetRecord($restr);
						//dprint_r($restr);
						//dprint_r("t=".$groupcontentstitle=$t[$Table->xmltable->fields[$groupname]->fk_show_field]);
						//dprint_r($Table->xmltable->fields[$groupname]->fk_show_field);
						$ttitles = $groupname;
						if (isset($Table->xmltable->fields[$groupname]->fk_show_field))
							$ttitles = explode(",",$Table->xmltable->fields[$groupname]->fk_show_field);
						$groupcontentstitle = "";
						$sep = "";
						foreach ($ttitles as $tt)
						{
							if (isset($t[$tt]) && $t[$tt] != "")
							{
								$groupcontentstitle .= $sep.$t[$tt];
								$sep = " &bull; ";
							}
						}
						if ($groupcontentstitle == "")
							$groupcontentstitle = $group['name'];
					}
					else
						$groupcontentstitle = $group['name'];
				}
				$link = FNNAV_MakeLink(array("nv_$groupname"=>"$groupcontentsname","page"=>1));
				echo "<tr><td valign=\"top\" style=\"color:#297ddd\">($groupcontentsnums)</td><td  valign=\"top\"><a href=\"$link\">$groupcontentstitle</a></td></tr>";
			}
			echo "</table>";
			echo "</div>";
			echo "</div>";
		}
		echo "</div>";
		//----foreign key ----<
	}
}

/**
 * 
 * @param $orders
 * @param $tables
 * @param $config['search_options']
 */
function FNNAV_SearchForm($orders,$tables,$search_options,$search_min,$search_fields,$search_partfields = "")
{
	global $_FN;
	$q = FN_GetParam("q",$_GET);
	$order = FN_GetParam("order",$_GET);
	$desc = FN_GetParam("desc",$_GET);
	//--config-->
	$config = FN_LoadConfig();
	$config['search_fields'] = explode(",",$config['search_fields']);
	$config['search_orders'] = explode(",",$config['search_orders']);
	$config['search_min'] = explode(",",$config['search_min']);
	$config['search_partfields'] = explode(",",$config['search_partfields']);
	$config['search_options'] = explode(",",$config['search_options']);
	//--config--<
	if ($order == "")
	{
		$order = $config['defaultorder'];
		if ($desc == "")
			$desc = 1;
	}
	//$tableproduct = new XMLTable($_FN['database'],"os_caves",$_FN['datadir']);
	//$tablearchives = new XMLTable($_FN['database'],"os_cavetype",$_FN['datadir']);
	//$archives = $tablearchives->GetRecords();
	//$tabletypes = new XMLTable($_FN['database'],"os_areas",$_FN['datadir']);
	//$types = $tabletypes->GetRecords();
	foreach ($tables as $tablename)
	{
		$_tables[$tablename] = FN_XmlForm($tablename);
	}
	echo "<div class=\"FNNAV_searchform\" style=\"\">";
	echo "<fieldset>";
	echo "<legend>".FN_Translate("search")."</legend>";
	echo "<form name=\"filter\" method=\"get\">";
	echo "<input type=\"hidden\"name=\"mod\" value=\"{$_FN['mod']}\" /> ";
	if (isset($_GET['nav']))
		echo "<input type=\"hidden\"name=\"nav\" value=\"1\" /> ";
	//------------------------------table rules-------------------------------->
	if ($config['table_rules'])
	{
		if (!file_exists("{$_FN['datadir']}/{$_FN['database']}/{$config['table_rules']}.php"))
		{
			$xml = '<?php exit(0);?>
<tables>
	<field>
		<name>rule</name>
		<primarykey>1</primarykey>
		<frm_show>0</frm_show>
		<extra>autoincrement</extra>
	</field>
	<field>
		<name>title</name>
		<frm_i18n>rule title</frm_i18n>
		<frm_multilanguages>auto</frm_multilanguages>
		<frm_show>1</frm_show>
	</field>	
	<field>
		<name>query</name>
		<frm_i18n>query</frm_i18n>
		<frm_type>text</frm_type>
		<frm_cols>80</frm_cols>
		<frm_rows>10</frm_rows>
		<frm_show>1</frm_show>
	</field>
	<field>
		<name>function</name>
		<frm_i18n>function</frm_i18n>
		<frm_show>1</frm_show>
	</field>
</tables>';
			FN_Write($xml,"{$_FN['datadir']}/{$_FN['database']}/{$config['table_rules']}.php");
		}

		$tablerules = FN_XmlForm($config['table_rules']);
		echo "<div class=\"navigatorformtitle\" ><span>".FN_Translate("shows only")." :</span></div>";
		echo "<select name = \"rule\" >";
		echo "<option value=\"\">---</option>";
		$rules = $tablerules->xmltable->GetRecords();
		foreach ($rules as $rule)
		{
			//$rule = $tablerules->GetRecordTranslated($rule);
			$s = (!empty($_GET['rule']) && $_GET['rule'] == $rule['rule']) ? "selected=\"selected\"" : "";
			echo "<option $s value=\"{$rule['rule']}\" >{$rule['title']}</option>";
		}
		echo "</select>";
	}
	//------------------------------table rules--------------------------------<
	//--------------------------------text------------------------------------->
	echo "<div class=\"navigatorformtitle\" ><span>".FN_Translate("text").":</span><input size=\"15\" name=\"q\" value=\"$q\"/></div>";
	//--------------------------------text-------------------------------------<
	//----------------------search exact phrase-------------------------------->
	foreach ($search_fields as $min)
	{
		if (isset($_tables[$tablename]->formvals[$min]))
		{
			$minval = FN_GetParam("sfield_$min",$_GET);
			echo "<div class=\"navigatorformtitle\" ><span>{$_tables[$tablename]->formvals[$min]['title']} =:</span><input size=\"15\" name=\"sfield_$min\" value=\"$minval\"/>";
			if (isset($_tables[$tablename]->formvals[$min]['frm_suffix']))
				echo $_tables[$tablename]->formvals[$min]['frm_suffix'];
			echo "</div>";
		}
	}
	//----------------------search exact phrase--------------------------------<
	//------------- looking for a part of the text ---------------------------->
	foreach ($config['search_partfields'] as $partf)
	{
		if (isset($_tables[$tablename]->formvals[$partf]))
		{
			//dprint_r($_tables[$tablename]->formvals[$partf]);
			$pfval = FN_GetParam("spfield_$partf",$_GET);
			echo "<div class=\"navigatorformtitle\" ><span>{$_tables[$tablename]->formvals[$partf]['title']} :</span><input size=\"15\" name=\"spfield_$partf\" value=\"$pfval\"/>";
			if (isset($_tables[$tablename]->formvals[$partf]['frm_suffix']))
				echo $_tables[$tablename]->formvals[$partf]['frm_suffix'];

			echo "</div>";
		}
	}
	//------------------ looking for a part of the text -----------------------<
	//-------------------------- minimun value -------------------------------->
	foreach ($config['search_min'] as $min)
	{
		//dprint_r($_tables[$tablename]->formvals);
		if (isset($_tables[$tablename]->formvals[$min]))
		{
			$minval = FN_GetParam("min_$min",$_GET);
			echo "<div class=\"navigatorformtitle\" ><span>{$_tables[$tablename]->formvals[$min]['title']} &gt;:</span><input size=\"15\" name=\"min_$min\" value=\"$minval\"/>";
			if (isset($_tables[$tablename]->formvals[$min]['frm_suffix']))
				echo $_tables[$tablename]->formvals[$min]['frm_suffix'];
			echo "</div>";
		}
	}
	//-------------------------- minimun value --------------------------------<
	//------------------------- search filters --------------------------------<
	foreach ($config['search_options'] as $option)
	{
		foreach ($tables as $tablename)
		{
			if (isset($_tables[$tablename]->formvals[$option]['options']))
			{
				$optiontitle = $_tables[$tablename]->formvals[$option]['title'];
				echo "<div class=\"navigatorformtitle\" ><span>$optiontitle:</span></div>";
				if (is_array($_tables[$tablename]->formvals[$option]['options']))
					foreach ($_tables[$tablename]->formvals[$option]['options'] as $c)
					{
						$title = $c['title'];
						$value = $c['value'];
						$getid = "s_opt_{$option}_{$tablename}_{$c['value']}";
						$ck = "";
						if (isset($_GET[$getid]))
							$ck = "checked=\"checked\"";
						echo "<input name = \"$getid\" type=\"checkbox\" $ck />&nbsp;".$title."";
					}
			}
		}
	}
	//------------------------- search filters --------------------------------<
	//----------------------------- order by ---------------------------------->
	if (count($orders) > 0)
	{
		echo "<div class=\"navigatorformtitle\"><span>".FN_Translate("order by").": </span><select name=\"order\">";
		foreach ($orders as $o)
		{
			$tt = "frm_{$_FN['lang']}";
			if (isset($_tables[$tablename]->xmltable->fields[$o]->$tt))
				$no = $_tables[$tablename]->xmltable->fields[$o]->$tt;
			elseif (isset($_tables[$tablename]->xmltable->fields[$o]->frm_i18n))
			{
				$no = FN_Translate($_tables[$tablename]->xmltable->fields[$o]->frm_i18n);
			}
			else
				$no = $_tables[$tablename]->xmltable->fields[$o]->title;
			if ($order == $o)
				$s = "selected=\"selected\"";
			else
				$s = "";
			echo "\n<option $s value=\"$o\">$no</option>";
		}
		echo "</select>";
		echo "</div>";
		$ck = ($desc == "") ? "" : "checked=\"checked\"";
		echo "<br />".FN_Translate("reverse order (from largest to smallest)")." <input onclick=\"filter.submit()\" name=\"desc\" value=\"1\" type = \"checkbox\" $ck />";
	}
	//----------------------------- order by ----------------------------------<
	echo "<button class=\"searchbutton\" type=\"submit\" >".FN_Translate("search")."</button>";
	// if (!empty($_GET['q']))
	echo "<button class=\"searchbutton\" onclick=\"window.location='".FN_RewriteLink("index.php?mod={$_FN['mod']}","&")."';return false;\" >".FN_Translate("new search")."</button>";

	echo "</form>";
	echo "</fieldset>";

	echo "</div>";
}

/**
 * 
 * @param string $tablename
 * @param string $res
 */
function FNNAV_HtmlItem($tablename,$pk)
{
	global $_FN;
	//--config-->
	$config = FN_LoadConfig();
	$titles = explode(",",$config['titlefield']);
	//--config--<

	$tablename_default = $tablename;
	$Table = FN_XmlForm($tablename);
	$data = $Table->xmltable->GetRecordByPrimaryKey($pk);
	$photo = isset($data[$config['image_titlefield']]) ? $data[$config['image_titlefield']] : "";
	if ($photo != "")
	{
		$photo = "{$_FN['datadir']}/fndatabase/{$tablename}/{$data[$Table->xmltable->primarykey]}/{$config['image_titlefield']}/{$data[$config['image_titlefield']]}";
	}
	elseif (file_exists("sections/{$_FN['mod']}/default.png"))
	{
		$photo = "sections/{$_FN['mod']}/default.png";
	}
	else
		$photo = "modules/navigator/default.png";
	if (empty($config['image_size']))
		$config['image_size'] = 100;
	if (file_exists("thumb.php"))
		$img = "thumb.php?h={$config['image_size']}&w={$config['image_size']}&f=".$photo;
	else
		$img = "$photo";
	$arch = "";
	$arch = FN_Translate("$tablename");
	$html = "<div class=\"searchresultBox\" ><div class=\"searchresult1\" >";
	$html .= "<img alt=\"\" src='{$_FN['siteurl']}$img' />";
	$html .= "</div><div  class=\"searchresult2\" >";
	$dettlink = FNNAV_MakeLink(array("op"=>"view","id"=>$pk),"&amp;");
	$titlename = "";
	foreach ($titles as $titleitem)
		if (isset($data[$titleitem]))
			$titlename .= "{$data[$titleitem]}&nbsp;";
		else
		{
			$titlename = each($data);
			$titlename = $titlename[1];
		}
	$html .= "<a title=\"$titlename\" href=\"$dettlink\">".FN_FixEncoding($titlename)."</a>";
	//---icone--->
	$html .= "</div><div  class=\"searchresult3\">";
	$html .= " ";
	foreach ($Table->formvals as $field)
	{
		if (isset($field['gridicononexists']) && $field['gridicononexists'] != "" && isset($data[$field['name']]) && $data[$field['name']] != "")
		{
			$html .= "\n<img border=\"0\" alt=\"".$field['name']."\" src=\"{$_FN['siteurl']}".$field['gridicononexists']."\" /> ";
		}
	}
	$html .= "</div><div   class=\"searchresult4\">";
	//-------------------------------valori----------------------------------->
	$row = $data;
	$t = FN_XmlForm($tablename);

	$linkdetails = "index.php?mod={$_FN['mod']}&amp;op=view&amp;id=".$row[$t->xmltable->primarykey];
	$linkdetails = FN_RewriteLink($linkdetails);
	if ($config['enablecomments'])
	{
		$tablelinks = FN_XmlForm($tablename."_comments");
		$numcommenti = $tablelinks->xmltable->GetNumRecords(array("unirecidrecord"=>$row[$t->xmltable->primarykey]));
		$html .= "\n<div class=\"searchresultcomments\" ><a href=\"$linkdetails#___comments\">".FN_Translate("comments","Aa")." : $numcommenti</a></div>";
	}
	if ($config['enableranks'])
	{
		$htmlrank = FNNAV_HtmlRank($row[$t->xmltable->primarykey],true,$tablename);
		$html .= "\n<div  class=\"searchresultrank\">".FN_Translate("rank")." : ".$htmlrank."</div>";
	}
	$colsuffix = "1";
	$html .= "</div>"; //searchresults4
	$html .= "<div class=\"searchresultitems\">";
	foreach ($Table->formvals as $field)
	{
		if (isset($field['frm_showinlist']) && $field['frm_showinlist'] != 0)
			if (isset($row[$field['name']]) && $row[$field['name']] != "")
			{
				$row[$field['name']] = html_entity_decode($row[$field['name']]);
				$html .= "<div class=\"searchresultitem searchresult{$field['frm_type']} searchresult{$field['name']}\">";
				switch($field['frm_type'])
				{
					case "image" :
						$h = $w = "";
						$hh = $ww = "64";
						if (isset($field['thumb_listwidth']) && $field['thumb_listwidth'] != "")
						{
							$w = "width=\"".$field['thumb_listwidth']."\"";
							$ww = intval($field['thumb_listwidth']);
						}
						if (isset($field['thumb_listheight']) && $field['thumb_listheight'] != "")
						{
							$hh = intval($field['thumb_listheight']);
							$h = "height=\"".$field['thumb_listheight']."\"";
						}
						$fileimage = "{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}/".$row[$t->xmltable->primarykey]."/".$field['name']."/".$row[$field['name']];
						$filethumb = "{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}/".$row[$t->xmltable->primarykey]."/".$field['name']."/thumbs/".$row[$field['name']].".jpg";
						break;
					case "youtubelink" :
						//http://i3.ytimg.com/vi/vbrd56jFpc0/hqdefault.jpg
						$h = $w = "";
						$hh = $ww = "64";
						if (isset($field['thumb_listwidth']) && $field['thumb_listwidth'] != "")
						{
							$w = "width=\"".$field['thumb_listwidth']."\"";
							$ww = intval($field['thumb_listwidth']);
						}
						if (isset($field['thumb_listheight']) && $field['thumb_listheight'] != "")
						{
							$hh = intval($field['thumb_listheight']);
							$h = "height=\"".$field['thumb_listheight']."\"";
						}
						$c = "vi";
						$value = $row[$field['name']];
						$code = explode("/v/",$value);
						if (!isset($code[1]))
						{
							$code = explode("?v=",$value);
							$c = "vi";
						}
						//print_r($code);
						if (isset($code[1]))
						{
							$code = $code[1];
							if (false !== strstr($code,"&"))
								$code = substr($code,0,strpos($code,"&"));
							if (false !== strstr($code,"?"))
								$code = substr($code,0,strpos($code,"?"));
							if ($code != "")
							{
								
							}
							$th = "http://i3.ytimg.com/$c/$code/hqdefault.jpg";
						}
						else
						{
							$th = "http://code.google.com/intl/it-IT/apis/youtube/images/player_apis_small.png";
						}
						$html .= "\n<img  $w $h  src=\"$th\" title=\"\"/>";
						break;
					case "file" :
						$filedownload = "{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}/".$row[$t->xmltable->primarykey]."/".$field['name']."/".$row[$field['name']];
						$html .= "\n<a href=\"$filedownload\" >".$row[$field['name']]."</a>";
						break;
					case "link" :
						//$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
						$valueh = $row[$field['name']];
						if (!preg_match("/^http:\\/\\//is",$valueh))
							$valueh = "http://$valueh";
						$valuehs = str_replace("http://","",$valueh);
						$valuehs = explode("/",$valuehs);
						$valuehs = substr($valuehs[0],0,25);
						$html .= "\n<b>".$field['title']."</b>: <a title=\"$valueh\" target=\"_blank\" href=\"$valueh\">{$valuehs}</a>";
						break;
					case "html" :
						//$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
						$html .= "\n<b>".$field['title']."</b>: $value";
						break;
					case "datetime" :
						$valueh = $row[$field['name']];
						$time = strtotime($valueh);
						$dateformat = "y-mm-dd 00:00:00";
						if (!empty($field['frm_dateformat']))
							$dateformat = $field['frm_dateformat'];
						if (!empty($field['view_dateformat']))
							$dateformat = $field['view_dateformat'];
						$dateformat = str_replace("y","Y",$dateformat);
						$dateformat = str_replace("00:00:00","H:i:s",$dateformat);
						$dateformat = str_replace("00:00","H:i",$dateformat);
						$dateformat = str_replace("00","H",$dateformat);
						$dateformat = str_replace("mm","m",$dateformat);
						$dateformat = str_replace("dd","d",$dateformat);
						$strformdate = date($dateformat,$time);
						$html .= "\n<b>".$field['title']."</b>:$strformdate";
						break;

					default :
						if (preg_match("/html/is",$field['frm_type']))
						{
							$html .= "\n<b>".$field['title']."</b>: $value";
						}
						else
						{
							if (isset($field['foreignkey']))
							{
								$r = array();
								$tablefk = xmldb_table($_FN['database'],$field['foreignkey'],$_FN['datadir']);
								$f = $field['fk_link_field']."|".str_replace(",","|",$field['fk_show_field']);
								//dprint_r($tablefk->fields);
								if (isset($tablefk->fields[$field['fk_show_field']."_{$_FN['lang']}"]))
									$f .= "|".str_replace(",","|",$field['fk_show_field'])."_{$_FN['lang']}";
								//dprint_r($f);
								$r[$field['fk_link_field']] = $row[$field['name']];
								$vs = $tablefk->GetRecords($r,false,false,false,false,$f);
								//dprint_r($r);
								$value = isset($vs[0]) ? $vs[0] : null;
								$showfields = explode(",",$field['fk_show_field']);
								$sep = "";
								$valuetit = "";
								foreach ($showfields as $showfield)
								{
									if (isset($value[$showfield."_{$_FN['lang']}"]))
										$valuetit .= $sep.$value[$showfield."_{$_FN['lang']}"];
									else
										$valuetit .= $sep.$value[$showfield];
									$sep = " ";
								}
								$value = $valuetit;
							}
							else
								$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
							$html .= "\n".$field['title'].":&nbsp;$value ";
							if (isset($Table->formvals[$field['name']]['frm_suffix']))
								$html .= $Table->formvals[$field['name']]['frm_suffix'];
						}
						break;
				}
				$html .= "</div>";
			}
	}
	$html .= "</div>";
	//-------------------------------valori-----------------------------------<
	$html .= "</div><div class=\"searchresultfooter\">";
	$html .= "<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/mime/doc.png")."' alt='' border='0' />&nbsp;<a href=\"$dettlink\">".FN_Translate("view")."</a>";
	if (FNNAV_IsAdminRecord($row,$tablename,$_FN['database']))
	{
		$link = FNNAV_MakeLink(array("op"=>"edit","id"=>$row[$t->xmltable->primarykey]),"&");
		$html .= "&nbsp;<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/modify.png")."' alt='' border='0' /><a href=\"$link\" >&nbsp;".FN_Translate("modify")."</a>";
	}
	else
	{
		if ($_FN['user'] != "")
		{
			$link = FNNAV_MakeLink(array("op"=>"edit","id"=>$row[$t->xmltable->primarykey]),"&");
			$html .= "&nbsp;<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/modify.png")."' alt='' border='0' /><a href=\"$link\">&nbsp;".FN_Translate("modify")."</a>";
		}
	}
	if (FNNAV_IsAdminRecord($row,$tablename,$_FN['database']) && !empty($config['enable_delete']))
	{
		$link = FNNAV_MakeLink(array("op"=>"del","id"=>$row[$t->xmltable->primarykey]),"&");
		$html .= "<br /><img style=\"vertical-align:middle\" src='".FN_FromTheme("images/delete.png")."' alt='' border='0' /><a href=\"javascript:check('$link');\" >&nbsp;".FN_Translate("delete")."</a>";
	}
	$html .= "</div>";
	if (file_exists("sections/{$_FN['mod']}/pdf.php"))
		$html .= " <div class=\"pdf\"><a title=\"PDF\"  href=\"{$_FN['siteurl']}pdf.php?mod={$_FN['mod']}&amp;id=$pk\"><img style=\"vertical-align:middle;border:0px\" src=\"{$_FN['siteurl']}images/mime/pdf.png\" alt=\"\" /></a></div>";
	return $html;
}

/**
 * 
 * @param string $tablename
 * @param string $res
 */
function FNNAV_HtmlList($tablename,$pk)
{
	global $_FN;
	//--config-->
	$config = FN_LoadConfig();
	$tables = explode(",",$config['tables']);
	$tablename_default = $tables[0];
	$search_fields = $config['search_fields'] != "" ? explode(",",$config['search_fields']) : array();
	$search_partfields = $config['search_fields'] != "" ? explode(",",$config['search_partfields']) : array();
	$search_orders = $config['search_orders'] != "" ? explode(",",$config['search_orders']) : array();
	$navigate_groups = $config['navigate_groups'] != "" ? explode(",",$config['navigate_groups']) : array();
	$search_options = $config['search_options'] != "" ? explode(",",$config['search_options']) : array();
	$search_min = $config['search_min'] != "" ? explode(",",$config['search_min']) : array();
	//--config--<

	$Table = FN_XmlForm($tablename);
	$data = $Table->xmltable->GetRecordByPrimaryKey($pk);
	$photo = isset($data[$config['image_titlefield']]) ? $data[$config['image_titlefield']] : "";
	if ($photo != "")
	{
		$photo = "{$_FN['datadir']}/fndatabase/{$tablename_default}/{$data[$Table->xmltable->primarykey]}/{$config['image_titlefield']}/{$data[$config['image_titlefield']]}";
	}
	else
		$photo = "modules/{$_FN['sectionvalues']['type']}/default.png";
	if (file_exists("thumb.php"))
		$img = "thumb.php?h=80&w=100&f=".$photo;
	else
		$img = "$photo";
	$arch = "";
	$arch = FN_Translate("$tablename");
	$html = "<div  class=\"searchresultlist2\" >";
	//$html .= "<img src='$img' border='0' />";
	$html .= "";
	//$html .= "<b>$arch</b>&nbsp;:&nbsp;";
	$dettlink = FNNAV_MakeLink(array("op"=>"view"));
	//FN_RewriteLink("?mod={$_FN['mod']}&amp;op=view&amp;id=$pk");
	$titles = explode(",",$config['titlefield']);
	$titlename = "";
	foreach ($titles as $titleitem)
		if (isset($data[$titleitem]))
			$titlename .= "{$data[$titleitem]}&nbsp;";
		else
		{
			$titlename = each($data);
			$titlename = $titlename[1];
		}
	$html .= "<a title=\"$titlename\" href=\"$dettlink\">$titlename</a>";
	//---icone--->
	$html .= "</div><div  class=\"searchresultsearchresultlist3\">";
	$html .= " ";
	foreach ($Table->formvals as $field)
	{
		if (isset($field['gridicononexists']) && $field['gridicononexists'] != "" && isset($data[$field['name']]) && $data[$field['name']] != "")
		{
			$html .= "\n<img border=\"0\" alt=\"".$field['name']."\" src=\"{$_FN['siteurl']}".$field['gridicononexists']."\" /> ";
		}
	}
	$html .= "</div><div   class=\"searchresultsearchresultlist4\">";
	//---icone---<
	// inserito / aggiornato da ...   --->
	$html .= "";
	if (isset($data['insert']) && $data['insert'] != "")
	{
		$html .= "Inserito :<em>".fn_GetDateTime($data['insert'])." da {$data['username']}</em>";
		if ($data['update'] != "" && $data['insert'] != $data['update'])
		{
			$html .= " ".FN_Translate("updated")." :<em>".fn_GetDateTime($data['update']);
			if ($data['userupdate'] != "")
				$html .= " ".FN_i18n("from")." {$data['userupdate']}";
			$html .= "</em>";
		}
	}
	// inserito / aggiornato da ...   ---<
	//-------------------------------valori----------------------------------->

	$row = $data;
	$t = FN_XmlForm($tablename);
	$linkdetails = "index.php?mod={$_FN['mod']}&amp;op=view&amp;id=".$row[$t->xmltable->primarykey];
	$linkdetails = FN_RewriteLink($linkdetails);
	if ($config['enablecomments'])
	{
		$tablelinks = FN_XmlForm($tablename."_comments");
		$numcommenti = $tablelinks->xmltable->GetNumRecords(array("unirecidrecord"=>$row[$t->xmltable->primarykey]));
		$html .= "\n<div class=\"searchresultcomments\" ><a href=\"$linkdetails#___comments\">".FN_Translate("comments")." : $numcommenti</a></div>";
	}
	if ($config['enableranks'])
	{
		$htmlrank = FNNAV_HtmlRank($row[$t->xmltable->primarykey],true,$tablename);
		$html .= "\n<div  class=\"searchresultrank\">".FN_Translate("rank")." : ".$htmlrank."</div>";
	}
	$colsuffix = "1";
	//for ( $col = 0;$col <= 1;$col++  )
	//{
	$html .= "</div>"; //searchresults4
	$html .= "<div class=\"searchresultitemsgrid\">";
	foreach ($Table->formvals as $field)
	{
		//dprint_r($field);
		if (isset($field['frm_showinlist']) && $field['frm_showinlist'] != 0)
			if (isset($row[$field['name']]) && $row[$field['name']] != "")
			{
				$row[$field['name']] = html_entity_decode($row[$field['name']]);
				$html .= "<div class=\"searchresultitem searchresult{$field['frm_type']} searchresult{$field['name']}\">";
				switch($field['frm_type'])
				{
					case "image" :
						$h = $w = "";
						$hh = $ww = "64";
						if (isset($field['thumb_listwidth']) && $field['thumb_listwidth'] != "")
						{
							$w = "width=\"".$field['thumb_listwidth']."\"";
							$ww = intval($field['thumb_listwidth']);
						}
						if (isset($field['thumb_listheight']) && $field['thumb_listheight'] != "")
						{
							$hh = intval($field['thumb_listheight']);
							$h = "height=\"".$field['thumb_listheight']."\"";
						}
						break;
					case "youtubelink" :
						//http://i3.ytimg.com/vi/vbrd56jFpc0/hqdefault.jpg
						$h = $w = "";
						$hh = $ww = "64";
						if (isset($field['thumb_listwidth']) && $field['thumb_listwidth'] != "")
						{
							$w = "width=\"".$field['thumb_listwidth']."\"";
							$ww = intval($field['thumb_listwidth']);
						}
						if (isset($field['thumb_listheight']) && $field['thumb_listheight'] != "")
						{
							$hh = intval($field['thumb_listheight']);
							$h = "height=\"".$field['thumb_listheight']."\"";
						}
						$c = "vi";
						$value = $row[$field['name']];
						$code = explode("/v/",$value);
						if (!isset($code[1]))
						{
							$code = explode("?v=",$value);
							$c = "vi";
						}
						//print_r($code);
						if (isset($code[1]))
						{
							$code = $code[1];
							if (false !== strstr($code,"&"))
								$code = substr($code,0,strpos($code,"&"));
							if (false !== strstr($code,"?"))
								$code = substr($code,0,strpos($code,"?"));
							if ($code != "")
							{
								
							}
							$th = "http://i3.ytimg.com/$c/$code/hqdefault.jpg";
						}
						else
						{
							$th = "http://code.google.com/intl/it-IT/apis/youtube/images/player_apis_small.png";
						}
						$html .= "\n<img  $w $h  src=\"$th\" title=\"\"/>";
						break;
					case "file" :
						$filedownload = "{$_FN['datadir']}/{$_FN['database']}/{$tablename_default}/".$row[$t->xmltable->primarykey]."/".$field['name']."/".$row[$field['name']];
						$html .= "\n<a href=\"$filedownload\" >".$row[$field['name']]."</a> ";
						break;
					case "link" :
						//$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
						$valueh = $row[$field['name']];
						if (!preg_match("/^http:\\/\\//is",$valueh))
							$valueh = "http://$valueh";
						$valuehs = str_replace("http://","",$valueh);
						$valuehs = explode("/",$valuehs);
						$valuehs = substr($valuehs[0],0,25);
						$html .= "<span>".$field['title'].":</span> <a title=\"$valueh\" target=\"_blank\" href=\"$valueh\">{$valuehs}</a> ";
						break;
					case "html" :
						//$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
						$html .= "<span>".$field['title'].":</span> $value ";
						break;
					default :
						if (preg_match("/html/is",$field['frm_type']))
						{
							$html .= "<span>".$field['title'].":</span> $value ";
						}
						else
						{
							if (isset($field['foreignkey']))
							{
								$r = array();
								$tablefk = FN_XmlTable($field['foreignkey']);
								$f = $field['fk_link_field']."|".str_replace(",","|",$field['fk_show_field'])."|".str_replace(",","|",$field['fk_show_field'])."_{$_FN['lang']}";
								//dprint_r($f);
								$r[$field['fk_link_field']] = $row[$field['name']];
								$vs = $tablefk->GetRecords($r,false,false,false,false,$f);
								$value = isset($vs[0]) ? $vs[0] : null;
								if (isset($value[$field['fk_show_field']."_{$_FN['lang']}"]))
									$value = $value[$field['fk_show_field']."_{$_FN['lang']}"];
								else
									$value = $value[$field['fk_show_field']];
							}
							else
								$value = FNNAV_MakeBr(FNNAV_SecureHtml($row[$field['name']]));
							$html .= "<span>".$field['title'].":</span> $value ";
							if (isset($Table->formvals[$field['name']]['frm_suffix']))
								$html .= $Table->formvals[$field['name']]['frm_suffix'];
						}
						break;
				}
				$html .= "</div> ";
			}
	}
	$html .= "</div>";
	//}
	//-------------------------------valori-----------------------------------<
	/*
	  if ( $data['attachment1'] != "" && file_exists($data['attachment1']) )
	  {
	  $dimg = fn_GetIconByFilename($data['attachment1']);
	  $size = fn_byteConvert(@filesize($data['attachment1']));
	  $href = "index.php?mod={$_FN['mod']}&amp;addtocart={$data[$t->xmltable->primarykey]}";
	  $href = amo_link(array("addtocart"=>$data[$t->xmltable->primarykey]),"&amp;");
	  $html .= "<br /><img style=\"vertical-align:middle\" src=\"$dimg\" alt =\"\"/>&nbsp;<a  href=\"$href\"  >Aggiungi al carrello ( $size )</a>";
	  }
	 */
	$html .= "<div class=\"searchresultfooterlist\">";
	$html .= "<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/mime/doc.png")."' alt='' border='0' />&nbsp;<a href=\"$dettlink\">".FN_Translate("view")."</a>";
	if (FNNAV_IsAdminRecord($row,$tablename,$_FN['database']))
	{
		$link = FNNAV_MakeLink(array("op"=>"edit","id"=>$row[$t->xmltable->primarykey]),"&");
		$html .= "&nbsp;<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/modify.png")."' alt='' border='0' /><a href=\"$link\" >&nbsp;".FN_Translate("modify")."</a>";
		if (!empty($config['enable_delete']))
			$html .= "&nbsp;<img src='".FN_FromTheme("images/delete.png")."' alt='' border='0' /><a href='#' onclick=\"check('?mod={$_FN['mod']}&amp;id=".$row [$t->xmltable->primarykey]."&amp;op=del')\" >".FN_Translate("delete")."</a>";
	}
	else
	{
		$link = FNNAV_MakeLink(array("op"=>"edit","id"=>$row[$t->xmltable->primarykey]),"&");
		if ($_FN['user'] != "")
			$html .= "&nbsp;<img style=\"vertical-align:middle\" src='".FN_FromTheme("images/modify.png")."' alt='' border='0' /><a href=\"$link\">&nbsp;".FN_Translate("modify")."</a>";
	}
	//$html .= "&nbsp;&nbsp;&nbsp;<a href=\"".FN_RewriteLink("index.php?mod={$_FN['mod']}&amp;op=view&amp;id={$data[$t->xmltable->primarykey]}")."\">[" . FN_Translate("view") . "]</a>";
	$html .= "</div>";
	//$html .= "</div>";
	return $html;
}

/**
 * 
 * @param unknown_type $results
 */
function FNNAV_PrintList($results)
{
	global $_FN;
	//--config-->
	$config = FN_LoadConfig();
	$tables = explode(",",$config['tables']);
	$tablename = $tables[0];
	//--config--<
	$viewmode = FN_GetParam("viewmode",$_GET);
	if ($viewmode == "")
		$viewmode = $config['default_view_mode'];
	$page = FN_GetParam("page",$_GET);
	$recordsperpage = FN_GetParam("rpp",$_GET);
	if ($recordsperpage == "")
		$recordsperpage = $config['recordsperpage'];
	if (is_array($results))
	{
		echo "<div class=\"navigatorresults\">";
		foreach ($results as $tablename=> $res)
		{
			$t = FN_XmlForm($tablename);
			if (is_array($res) && ($c = count($res)) > 0)
			{
				//---------------------calcolo paginazione -------------------->
				$htmlpages = "";
				if ($page == "")
					$page = 1;
				$num_records = count($res);
				//echo "num_records=$num_records ";
				$numPages = ceil($num_records / $recordsperpage);
				$start = ($page * $recordsperpage - $recordsperpage) + 1;
				$end = $start + $recordsperpage - 1;

				if ($end > $num_records)
					$end = $num_records;
				//---------------------calcolo paginazione --------------------<
				//---------------------tabella paginazione -------------------->
				$htmlpages .= "<div class=\"FNNAV_pages\">";

				//risultati per pagina ---->
				$htmlpages .= "<span>".FN_Translate("results per page").":</span>";
				for ($rpp = $config['recordsperpage']; $rpp <= $config['recordsperpage'] * 3; $rpp += $config['recordsperpage'])
				{
					$linkpage = FNNAV_MakeLink(array("rpp"=>$rpp),"&amp;");
					$cl = "";
					if ($rpp == $recordsperpage)
						$cl = "class=\"nv_selected\"";
					$htmlpages .= "<a $cl onclick=\"call_ajax('$linkpage','pageresults');return false\" href=\"$linkpage\">$rpp</a>&nbsp;";
				}
				$htmlpages .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				//risultati per pagina ----<
				if ($page > 1)
				{
					$linkpage = FNNAV_MakeLink(array("page"=>$page - 1,"addtocart"=>null),"&amp;");
					$htmlpages .= "<a href=\"$linkpage\">".FN_Translate("previous")."</a>&nbsp;";
				}
				else
					$htmlpages .= "<a class=\"disabled\" href=\"#\">".FN_Translate("previous")."</a>&nbsp;";
				$max_pages = 8;
				$startpage = $page;
				$scarto = $startpage / $max_pages;
				if ($scarto != 0)
				{
					$scarto = $startpage % $max_pages;
					$startpage -=($scarto);
					if ($page < $startpage)
						$startpage = $page;
					if ($startpage < 1)
						$startpage = 1;
				}
				$ii = $startpage;
				for ($i = $startpage; $i <= $numPages; $i++)
				{
					if ($ii >= $startpage + $max_pages)
						break;
					$linkpage = FNNAV_MakeLink(array("page"=>$i,"addtocart"=>null),"&amp;");
					$hclass = "";
					if ($page == $i)
						$hclass = "class=\"nv_selected\"";
					$htmlpages .= "<a $hclass onclick=\"call_ajax('$linkpage','pageresults');return false\" href=\"$linkpage\">$i</a>&nbsp;";
					$ii++;
				}
				if ($page < $numPages)
				{
					$linkpage = FNNAV_MakeLink(array("page"=>$page + 1,"addtocart"=>null),"&amp;");
					$htmlpages .= "<a onclick=\"call_ajax('$linkpage','pageresults');return false\" href=\"$linkpage\">".FN_Translate("next")."</a>&nbsp;";
				}
				else
					$htmlpages .= "<a class=\"disabled\" href=\"#\">".FN_Translate("next")."</a>&nbsp;";
				if ($viewmode == "icon")
				{
					$linkpage = FNNAV_MakeLink(array("viewmode"=>"list"),"&amp;");
					$htmlpages .= "<a title=\"".FN_Translate("icon view")."\" onclick=\"call_ajax('$linkpage','pageresults');return false\" href=\"$linkpage\" ><img style=\"vertical-align:middle;border:0px\" src=\"modules/{$_FN['sectionvalues']['type']}/icons.png\" /></a>";
				}
				else
				{
					$linkpage = FNNAV_MakeLink(array("viewmode"=>"icon"),"&amp;");
					$htmlpages .= "<a title=\"".FN_Translate("list view")."\" onclick=\"call_ajax('$linkpage','pageresults');return false\" href=\"$linkpage\" ><img style=\"vertical-align:middle;border:0px\" src=\"modules/{$_FN['sectionvalues']['type']}/list.png\" /></a>";
				}
				$htmlpages .= " - ".FN_Translate("search results","Aa")."  $start - $end  ".FN_i18n("of")." $num_records"."";
				$htmlpages .= "</div>";
				//---------------------tabella paginazione --------------------<

				echo "<div>";
				echo $htmlpages;  // print pages
				$viewmode = FN_GetParam("viewmode",$_GET);
				if ($viewmode == "")
					$viewmode = $config['default_view_mode'];
				for ($c = $start - 1; $c <= $end - 1 && isset($res[$c]); $c++)
				{
					if ($viewmode != "list")
					{
						echo "<div class=\"searchresult\">";
						$html = FNNAV_HtmlItem($tablename,$res[$c][$t->xmltable->primarykey]);
						echo $html;
						echo "</div>";
					}
					else
					{
						echo "<div class=\"searchresultlist\">";
						$html = FNNAV_HtmlList($tablename,$res[$c][$t->xmltable->primarykey]);
						echo $html;
						echo "</div>";
					}
				}
				if ($config['enable_rss'] && !empty($_FN['rss_link']))
					echo "<div><a href=\"{$_FN['rss_link']}\"><img src=\"modules/navigator/rss.png\"  alt=\"rss\"/></a></div>";
				echo $htmlpages; // print pages


				echo "</div>";
			}
			else
			{
				echo "{$_FN['sectionvalues']['title']} : ".FN_i18n("no result");
			}
		}
		echo "</div>";
	}
	//echo "</div>";
}
?>

<script type="text/javascript">
	function call_ajax(url, div)
	{
		var xsreq;
		loading(div);
		if (window.XMLHttpRequest) {
			xsreq = new XMLHttpRequest();
		}
		else if (window.ActiveXObject) {
			xsreq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (xsreq) {
			xsreq.onreadystatechange = function() {
				try {
					ajDone(url, div, xsreq);
				} catch (e) {
					alert(e)
				}
			};
			xsreq.open("POST", url, true);
			xsreq.send("");
		}
	}
	function ajDone(url, div, xsreq)
	{
		if (xsreq.readyState == 4)
		{
			//alert (div);
			try {
				var d = document.getElementsByTagName('body')[0];
				var olddiv = document.getElementById("__fnloading");
				d.removeChild(olddiv);
			} catch (e) {
				alert(e);
			}

			var output = xsreq.responseText;
			var el = document.createElement("div");
			el.innerHTML = output;
			var nodes = el.getElementsByTagName('div');
			for (var i = 0; i < nodes.length; i++) {
				if (nodes[i].id == div)
				{
					document.getElementById(div).innerHTML = nodes[i].innerHTML;
				}
			}
			nodes = el.getElementsByTagName('span');
			for (var i = 0; i < nodes.length; i++) {
				if (nodes[i].id == div)
				{
					document.getElementById(div).innerHTML = nodes[i].innerHTML;
				}
			}
		}
	}
	function getScrollY() {
		var scrOfX = 0, scrOfY = 0;
		if (typeof(window.pageYOffset) == 'number') {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return scrOfY;
		//return [ scrOfX, scrOfY ];
	}
	function getScrollX() {
		var scrOfX = 0, scrOfY = 0;
		if (typeof(window.pageYOffset) == 'number') {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return scrOfX;
	}
	function loading(_div)
	{
		try {
			var d = document.getElementsByTagName('body')[0];
			var olddiv = document.getElementById("__fnloading");
			d.removeChild(olddiv);
		} catch (e) {
		}



		var div;
		div = document.createElement('div');
		div.innerHTML = 'loading...';
		div.setAttribute('id', "__fnloading");
		oHeight = document.getElementsByTagName('body')[0].clientHeight + getScrollY();
		oWidth = document.getElementsByTagName('body')[0].clientWidth + getScrollX();
		oHeight = oHeight + "px";
		oWidth = oWidth + "px";
		try {
			div.style.backgroundColor = '#000000';
			div.style.color = '#ffffff';
			div.style.zIndex = '8';
			div.style.display = 'block';
			div.style.position = 'absolute';
			div.style.width = oWidth;
			div.style.height = "auto";
			div.style.top = '0px';
			div.style.left = '0px';
			div.style.textAlign = 'center';
			div.style.opacity = '0.5';
			div.style.filter = 'alpha(opacity=50)';
		}
		catch (e)
		{
		}
		div.innerHTML = "<div style=\"color:#ffffff;margin-top:" + getScrollY() + "px\" ><br />loading...<br /><br /><img  src='<?php echo "modules/navigator/"?>loading.gif' /><br /><br /></div>";

		//document.getElementById(_div).appendChild(div);
		document.getElementsByTagName('body')[0].appendChild(div);
	}
</script>
