function _card(&$PDOdb, &$object)
{
    global $langs, $conf, $user, $db;
    if (empty($user->rights->query->bdd->use_other_db)) {
        return '';
    }
    llxHeader();
    dol_fiche_head(array(), 'bdd', 'BDD');
    $tbs = new TTemplateTBS();
    $object->connect();
    $formCore = new TFormCore('auto', 'formBDD', 'post');
    echo $formCore->hidden('action', 'save');
    echo $formCore->hidden('id', $object->getId());
    echo $tbs->render('tpl/bdd.html', array(), array('object' => array('host' => $formCore->texte('', 'host', $object->host, 30, 128), 'db_name' => $formCore->texte('', 'db_name', $object->db_name, 30, 128), 'login' => $formCore->texte('', 'login', $object->login, 30, 128), 'password' => $formCore->texte('', 'password', $object->password, 30, 128), 'port' => $formCore->texte('', 'port', $object->port, 5, 5), 'charset' => $formCore->texte('', 'charset', $object->charset, 10, 128), 'db_type' => $formCore->combo('', 'db_type', $object->TDBType, $object->db_type)), 'view' => array('langs' => $langs, 'buttons' => $formCore->btsubmit($langs->trans('Delete'), 'bt_delete', '', 'butActionDelete') . '   ' . $formCore->btsubmit($langs->trans('Save'), 'bt_save'))));
    $formCore->end();
    dol_fiche_end();
    llxFooter();
}
function _card(&$PDOdb, &$object)
{
    global $langs, $conf, $user, $db;
    llxHeader();
    dol_fiche_head(array(), 'menu', 'Menu');
    $formCore = new TFormCore('auto', 'formMenu', 'post');
    echo $formCore->hidden('action', 'save');
    echo $formCore->hidden('id', $object->getId());
    $TQuery = array('0' => '----') + TQuery::getQueries($PDOdb);
    $TDashBoard = array('0' => '----') + TQDashBoard::getDashboard($PDOdb, '', 0, true);
    $tbs = new TTemplateTBS();
    echo $tbs->render('tpl/menu.html', array(), array('menu' => array('type_menu' => $formCore->combo('', 'type_menu', $object->TTypeMenu, $object->type_menu), 'tab_object' => $formCore->combo('', 'tab_object', $object->TTabObject, $object->tab_object), 'mainmenu' => $formCore->combo('', 'mainmenu', TQueryMenu::getMenu($PDOdb, 'main'), $object->mainmenu), 'leftmenu' => $formCore->combo('', 'leftmenu', TQueryMenu::getMenu($PDOdb, 'left'), $object->leftmenu), 'fk_query' => $formCore->combo('', 'fk_query', $TQuery, $object->fk_query), 'fk_dashboard' => $formCore->combo('', 'fk_dashboard', $TDashBoard, $object->fk_dashboard), 'title' => $formCore->texte('', 'title', $object->title, 80, 255), 'perms' => $formCore->texte('', 'perms', $object->perms, 80, 255)), 'view' => array('langs' => $langs, 'buttons' => $formCore->btsubmit($langs->trans('Delete'), 'bt_delete', '', 'butActionDelete') . '   ' . $formCore->btsubmit($langs->trans('Save'), 'bt_save'))));
    $formCore->end();
    dol_fiche_end();
    llxFooter();
}
function fiche(&$PDOdb, &$expedition, &$TImport)
{
    global $langs, $db;
    llxHeader();
    $head = shipping_prepare_head($expedition);
    $title = $langs->trans("Shipment");
    dol_fiche_head($head, 'dispatch', $title, 0, 'dispatch');
    enteteexpedition($expedition);
    echo '<br>';
    if ($expedition->statut == 0) {
        //Form pour import de fichier
        if ($conf->global->DISPATCH_USE_IMPORT_FILE) {
            $form = new TFormCore('auto', 'formimport', 'post', true);
            echo $form->hidden('action', 'SAVE');
            echo $form->hidden('id', $expedition->id);
            echo $form->fichier('Fichier à importer', 'file1', '', 80);
            echo $form->btsubmit('Envoyer', 'btsend');
            $form->end();
        }
        ?>
		<script>
			$(document).ready(function() {

				$('#lot_number').change(function() {
					var lot_number = $(this).val();

					$.ajax({
						url: 'script/interface.php',
						method: 'GET',
						data: {
							lot_number: lot_number,
							productid: $('#lineexpeditionid').find(':selected').attr('fk-product'),
							type:'get',
							get:'autocomplete_asset'
						}
					}).done(function(results) {
						var json_results = $.parseJSON(results);

						$('#numserie option').remove();
						cpt = 0;
						$.each(json_results, function(index) {
							var obj = json_results[index];
							cpt ++;
							$('#numserie').append($('<option>', {
								value: obj.serial_number,
								text: obj.serial_number + ' - ' + obj.qty + ' ' +obj.unite_string
							}));

							$('#quantity').val(obj.qty);
							if(obj.unite != 'unité(s)'){
								$('#quantity_unit').show();
								$('#units_lable').remove();
								$('#quantity_unit option[value='+obj.unite+']').attr("selected","selected");
							}
							else{
								$('#quantity_unit').hide();
								$('#quantity_unit option[value=0]').attr("selected","selected");
								$('#quantity').after('<span id="units_lable"> unité(s)</span>');
							}
						});
					});
				});
				
				$('#lineexpeditionid').change(function() {
					var productid = $(this).find(':selected').attr('fk-product');

					$.ajax({
						url: 'script/interface.php',
						method: 'GET',
						data: {
							productid: productid,
							type:'get',
							get:'autocomplete_lot_number'
						}
					}).done(function(results) {
						var json_results = $.parseJSON(results);

						$('#lot_number option').remove();
						
						$.each(json_results, function(index) {
							var obj = json_results[index];
							
							$('#lot_number').append($('<option>', {
								value: obj.lot_number,
								text: obj.label
							}));
						});
					});
				});
			});
		</script>
		<?php 
        //Form pour ajouter un équipement directement
        $DoliForm = new FormProduct($db);
        $form = new TFormCore('auto', 'formaddasset', 'post', true);
        echo $form->hidden('action', 'edit');
        echo $form->hidden('mode', 'addasset');
        echo $form->hidden('id', $expedition->id);
        $TLotNumber = array(' -- aucun produit sélectionné -- ');
        /*$sql = "SELECT DISTINCT(lot_number),rowid, SUM(contenancereel_value) as qty, contenancereel_units as unit FROM ".MAIN_DB_PREFIX."asset GROUP BY lot_number ORDER BY lot_number ASC";
        
        		$PDOdb->Execute($sql);
        		$Tres = $PDOdb->Get_All();
        		foreach($Tres as $res){
        			
        			$asset = new TAsset;
        			$asset->load($PDOdb, $res->rowid);
        			$asset->load_asset_type($PDOdb);
        			//pre($asset,true);exit;
        			$TLotNumber[$res->lot_number] = $res->lot_number." / ".$res->qty." ".(($asset->assetType->measuring_units == 'unit') ? 'unité(s)' : measuring_units_string($res->unit,$asset->assetType->measuring_units));
        		}
        		*/
        $TSerialNumber = array(' -- aucun lot sélectionné -- ');
        /*$sql = "SELECT DISTINCT(serial_number),contenancereel_value, contenancereel_units FROM ".MAIN_DB_PREFIX."asset ORDER BY serial_number ASC";
        		$PDOdb->Execute($sql);
        		while ($PDOdb->Get_line()) {
        			$TSerialNumber[$PDOdb->Get_field('serial_number')] = $PDOdb->Get_field('serial_number').' / '.$PDOdb->Get_field('contenancereel_value')." ".measuring_units_string($PDOdb->Get_field('contenancereel_units'),'weight');
        		}
        		*/
        echo 'Produit expédié<select id="lineexpeditionid" name="lineexpeditionid"><option value=""></option>';
        $TProduct = array('');
        $sql = "SELECT DISTINCT(ed.rowid),p.rowid as fk_product,p.ref,p.label ,ed.qty\n\t\t\t\tFROM " . MAIN_DB_PREFIX . "product as p\n\t\t\t\t\tLEFT JOIN " . MAIN_DB_PREFIX . "commandedet as cd ON (cd.fk_product = p.rowid)\n\t\t\t\t\tLEFT JOIN " . MAIN_DB_PREFIX . "expeditiondet as ed ON (ed.fk_origin_line = cd.rowid)\n\t\t\t\tWHERE ed.fk_expedition = " . $expedition->id . "";
        $PDOdb->Execute($sql);
        while ($obj = $PDOdb->Get_line()) {
            //$TProduct[$PDOdb->Get_field('rowid')] = $PDOdb->Get_field('ref').' - '.$PDOdb->Get_field('label');
            echo '<option value="' . $obj->rowid . '" fk-product="' . $obj->fk_product . '">' . $obj->ref . ' - ' . $obj->label . ' x ' . $obj->qty . '</option>';
        }
        echo '</select><br />';
        //echo $form->combo('Produit expédié', 'lineexpeditionid', $TProduct, '').'<br>';
        echo $form->combo('Numéro de Lot', 'lot_number', $TLotNumber, '') . '<br>';
        echo $form->combo('Numéro de série à ajouter', 'numserie', $TSerialNumber, '') . '<br>';
        echo $form->texte('Quantité', 'quantity', '', 10) . " " . $DoliForm->load_measuring_units('quantity_unit" id="quantity_unit', 'weight');
        echo $form->btsubmit('Ajouter', 'btaddasset');
        $form->end();
        echo '<br>';
    }
    tabImport($TImport, $expedition);
    llxFooter();
}
    }
    $TData[$row->fk_soc][$TMonth[(int) $row->month]] = (double) $row->total;
    $TData[$row->fk_soc]['total'] += (double) $row->total;
}
_get_company_object($TData);
//usort($TData, '_sort_company');
?>
	<style type="text/css">
		*[field=total],tr.liste_total td {
			font-weight: bold;
		}
	</style>
	<?php 
$formCore = new TFormCore('auto', 'form2', 'get');
$headsearch = $formCore->hidden('mode', $mode);
$headsearch .= $formCore->combo($langs->trans('Year'), 'year', $TYear, $year);
$headsearch .= $formCore->btsubmit($langs->trans('Ok'), 'bt_ok');
$listeview = new TListviewTBS('CAClientMonth');
print $listeview->renderArray($PDOdb, $TData, array('liste' => array('titre' => $langs->transnoentitiesnoconv('CAClientMonth'), 'head_search' => $headsearch), 'type' => $ColFormat, 'title' => array('client' => $langs->transnoentitiesnoconv('Company'), 'total' => $langs->transnoentitiesnoconv('Total'), 'year' => $langs->transnoentitiesnoconv('Year')), 'math' => $ColTotal, 'export' => array('CSV')));
$formCore->end();
dol_fiche_end();
llxFooter();
function _sort_company(&$a, &$b)
{
    $r = strcasecmp($a->name, $b->name);
    return empty($r) ? 0 : $r / abs($r);
}
function _get_company_object(&$TRender)
{
    global $db, $conf, $langs, $user;
    dol_include_once('/societe/class/societe.class.php');
function fiche(&$dashboard, $action = 'edit', $withHeader = true)
{
    global $langs, $conf, $user, $db;
    $PDOdb = new TPDOdb();
    $form = new TFormCore();
    $cell_height = 200;
    $tab_object = GETPOST('tab_object');
    $table_element = GETPOST('table_element');
    $fk_object = GETPOST('fk_object');
    if (empty($table_element)) {
        if ($tab_object == 'thirdparty') {
            $table_element = 'societe';
        } else {
            if ($tab_object == 'project') {
                $table_element = 'projet';
            } else {
                $table_element = $tab_object;
            }
        }
    }
    if ($withHeader) {
        llxHeader('', 'Query DashBoard', '', '', 0, 0, array('/query/js/dashboard.js', '/query/js/jquery.gridster.min.js'), array('/query/css/dashboard.css', '/query/css/jquery.gridster.min.css'));
        $head = TQueryMenu::getHeadForObject($tab_object, $fk_object);
        dol_fiche_head($head, 'tabQuery' . GETPOST('menuId'), 'Query');
        print_fiche_titre($dashboard->title);
    } else {
        if (GETPOST('for_incusion') > 0) {
            ?>
		<div class="querydashboard">
			<link rel="stylesheet" type="text/css" title="default" href="<?php 
            echo dol_buildpath('/query/css/dashboard.css', 1);
            ?>
">
			<link rel="stylesheet" type="text/css" title="default" href="<?php 
            echo dol_buildpath('/query/css/jquery.gridster.min.css', 1);
            ?>
">
			<script type="text/javascript" src="<?php 
            echo dol_buildpath('/query/js/dashboard.js', 1);
            ?>
"></script>
			<script type="text/javascript" src="<?php 
            echo dol_buildpath('/query/js/jquery.gridster.min.js', 1);
            ?>
"></script>

		<?php 
        } else {
            ?>
<html>
			<head>
				<meta charset="UTF-8">
				<link rel="stylesheet" type="text/css" href="<?php 
            echo dol_buildpath('/theme/eldy/style.css.php?lang=fr_FR&theme=eldy', 1);
            ?>
">
				<link rel="stylesheet" type="text/css" title="default" href="<?php 
            echo dol_buildpath('/query/css/dashboard.css', 1);
            ?>
">
				<link rel="stylesheet" type="text/css" title="default" href="<?php 
            echo dol_buildpath('/query/css/jquery.gridster.min.css', 1);
            ?>
">

				<script type="text/javascript" src="<?php 
            echo dol_buildpath('/includes/jquery/js/jquery.min.js', 1);
            ?>
"></script>
				<script type="text/javascript" src="<?php 
            echo dol_buildpath('/query/js/dashboard.js', 1);
            ?>
"></script>
				<script type="text/javascript" src="<?php 
            echo dol_buildpath('/query/js/jquery.gridster.min.js', 1);
            ?>
"></script>
				<style type="text/css">
					.pagination { display : none; }
					<?php 
            if ((int) GETPOST('allow_gen') != 1) {
                echo '.notInGeneration { display : none; }';
            }
            ?>

					table.liste tr.impair,table.liste tr.pair,table.liste tr.liste_titre,div.titre {
						font-size: 12px;
					}
				</style>
			</head>
		<body >
		<?php 
        }
    }
    ?>
	<script type="text/javascript">
		var MODQUERY_INTERFACE = "<?php 
    echo dol_buildpath('/query/script/interface.php', 1);
    ?>
";
		
		$(document).ready(function(){ //DOM Ready
			
			gridster_width = Math.round($('.gridster').innerWidth() / 5);
			if(gridster_width<50) gridster_width = 240;
			
		    $(".gridster ul").gridster({
		        widget_margins: [10, 10]
		        ,widget_base_dimensions: [gridster_width, <?php 
    echo $cell_height;
    ?>
]
		        ,min_cols:3
		        ,min_rows:5
		        ,serialize_params: function($w, wgd) { 
		        	return { posx: wgd.col, posy: wgd.row, width: wgd.size_x, height: wgd.size_y, k : $w.attr('data-k') } 
		        }
		        <?php 
    if ($action == 'edit') {
        ?>
,resize: {
		            enabled: true
		            ,max_size: [4, 4]
		            ,min_size: [1, 1]
		        }
		        
		       
		       <?php 
    }
    ?>
		    })<?php 
    if ($action == 'view') {
        echo '.data(\'gridster\').disable()';
    }
    ?>
;
		
			var gridster = $(".gridster ul").gridster().data('gridster');
		
			$('#addQuery').click(function() {
				
				var fk_query = $('select[name=fk_query]').val();
				
				$.ajax({
					url: MODQUERY_INTERFACE
					,data: {
						put:'dashboard-query'
						,fk_query : fk_query
						,fk_qdashboard:<?php 
    echo $dashboard->getId();
    ?>
					}
					,dataType:'json'
					
				}).done(function(data) {
					
					var title = $('select[name=fk_query] option:selected').text();
					
					gridster.add_widget('<li data-k="'+data+'">'+title+'</li>',1,1,1,1);	
				});
				
			});
			
			$('#saveDashboard').click(function() {
				
				var $button = $(this);
				
				$button.hide();
				
				$.ajax({
					url: MODQUERY_INTERFACE
					,data: {
						put:'dashboard'
						,id:<?php 
    echo $dashboard->getId();
    ?>
						,title:$('input[name=title]').val()
						,fk_usergroup:$('select[name=fk_usergroup]').val()
						,send_by_mail:$('select[name=send_by_mail]').val()
						,hook:$('select[name=hook]').val()
						,use_as_landing_page:$('select[name=use_as_landing_page]').val()
						,refresh_dashboard:$('input[name=refresh_dashboard]').val()
					}
					
				}).done(function(data) {
				   <?php 
    if ($dashboard->getId() > 0) {
        ?>
$.ajax({
							url: MODQUERY_INTERFACE
							,data: {
								put:'dashboard-query-link'
								,TCoord:gridster.serialize( )
								,fk_qdashboard:<?php 
        echo $dashboard->getId();
        ?>
							}
							,dataType:'json'
							
					  }).done(function(data) {
					  	$button.show();
					  });
						
						<?php 
    } else {
        echo 'document.location.href="?action=view&id="+data;';
    }
    ?>
					  	
		              
				});
				
			});
		
		});
		
		function delTile(idTile) {
			$('li[tile-id='+idTile+']').css('opacity',.5);
			
			$.ajax({
				url: MODQUERY_INTERFACE
				,data: {
					put:'dashboard-query-remove'
					,id : idTile
				}
				,dataType:'json'
				
			}).done(function(data) {
				$('li[tile-id='+idTile+']').toggle();
				//document.location.hre
			});
			
		}
			
	</script>
	<?php 
    if ($action == 'edit') {
        ?>
<div><?php 
        $TQuery = TQuery::getQueries($PDOdb);
        echo $form->texte($langs->trans('Title'), 'title', $dashboard->title, 50, 255);
        $formDoli = new Form($db);
        echo ' - ' . $langs->trans('LimitAccessToThisGroup') . ' : ' . $formDoli->select_dolgroups($dashboard->fk_usergroup, 'fk_usergroup', 1) . '/' . $langs->trans('UseAsLandingPage') . $formDoli->selectarray('use_as_landing_page', array($langs->trans('No'), $langs->trans('Yes')), $dashboard->use_as_landing_page);
        echo $form->combo(' - ' . $langs->trans('SendByMailToThisGroup'), 'send_by_mail', $dashboard->TSendByMail, $dashboard->send_by_mail);
        echo $form->combo(' - ' . $langs->trans('ShowThisInCard'), 'hook', $dashboard->THook, $dashboard->hook);
        echo $form->number('<br />' . $langs->trans('RefreshDashboard'), 'refresh_dashboard', $dashboard->refresh_dashboard, 20, 1, 0);
        ?>
			<a href="#" class="butAction" id="saveDashboard"><?php 
        echo $langs->trans('SaveDashboard');
        ?>
</a>
		</div>
		<?php 
        if ($dashboard->getId() > 0) {
            ?>
		<div>
			<?php 
            $TQuery = TQuery::getQueries($PDOdb);
            echo $form->combo('', 'fk_query', $TQuery, 0);
            ?>
			<a href="#" class="butAction" id="addQuery"><?php 
            echo $langs->trans('AddThisQuery');
            ?>
</a>
		</div>
		
		<?php 
        }
    } else {
        if (!empty($conf->global->QUERY_SHOW_PDF_TRANSFORM)) {
            echo '<div style="text-align:right" class="notInGeneration"><a class="butAction" style=";z-index:999;" href="download-dashboard.php?uid=' . $dashboard->uid . '">' . $langs->trans('Download') . '</a></div>';
        }
    }
    ?>
		
	
	<div class="gridster">
	    <ul>
	    	<?php 
    foreach ($dashboard->TQDashBoardQuery as $k => &$cell) {
        echo '<li tile-id="' . $cell->getId() . '" data-k="' . $k . '" data-row="' . $cell->posy . '" data-col="' . $cell->posx . '" data-sizex="' . $cell->width . '" data-sizey="' . $cell->height . '" ' . ($withHeader ? '' : 'style="overflow:hidden;"') . '>';
        if ($action == 'edit') {
            echo '<a style="position:absolute; top:3px; right:3px; z-index:999;" href="javascript:delTile(' . $cell->getId() . ')">' . img_delete('DeleteThisTile') . '</a>';
        } else {
            echo '<a style="position:absolute; top:3px; right:3px; z-index:999;" href="' . dol_buildpath('/query/query.php?action=run-in&id=' . $cell->query->getId(), 1) . '">' . img_picto($langs->trans('Run'), 'object_cron.png') . '</a>';
        }
        if ($cell->query->type == 'LIST') {
            $cell->query->type = 'SIMPLELIST';
        }
        if (!empty($cell->query)) {
            if (!$withHeader) {
                echo $cell->query->run(false, $cell->height * $cell_height, $table_element, $fk_object, 0);
            } else {
                echo $cell->query->run(false, $cell->height * $cell_height, $table_element, $fk_object);
            }
        }
        echo '</li>';
    }
    ?>
	        
	
	    </ul>
	</div>
	
	<div style="clear:both"></div>

	<?php 
    if ($dashboard->refresh_dashboard > 0 && !$withHeader) {
        echo "<script type=\"text/javascript\">\n";
        echo "   // Automatically refresh\n";
        echo "   setInterval(\"window.location.reload()\"," . 60000 * $dashboard->refresh_dashboard . ");\n";
        echo "</script>\n";
    }
    ?>
	
	<?php 
    if ($withHeader) {
        if ($dashboard->getId() > 0) {
            print dol_buildpath('/query/dashboard.php?action=run&uid=' . $dashboard->uid, 2);
        }
        dol_fiche_end();
        llxFooter();
    } else {
        if (GETPOST('for_incusion') > 0) {
            ?>
</div><?php 
        } else {
            ?>
		</body></html>
		<?php 
        }
    }
}
 private function setSearch(&$TEntete, &$TParam)
 {
     global $langs;
     if (empty($TParam['search'])) {
         return array();
     }
     $TSearch = array();
     $form = new TFormCore();
     $nb_search_in_bar = 0;
     if (!empty($TParam['search'])) {
         foreach ($TEntete as $key => $libelle) {
             // init
             if (empty($TSearch[$key])) {
                 $TSearch[$key] = '';
             }
         }
     }
     foreach ($TParam['search'] as $key => $param_search) {
         $value = isset($_REQUEST['TListTBS'][$this->id]['search'][$key]) ? $_REQUEST['TListTBS'][$this->id]['search'][$key] : '';
         $typeRecherche = is_array($param_search) && isset($param_search['recherche']) ? $param_search['recherche'] : $param_search;
         if (is_array($typeRecherche)) {
             $typeRecherche = array('' => ' ') + $typeRecherche;
             $fsearch = $form->combo('', 'TListTBS[' . $this->id . '][search][' . $key . ']', $typeRecherche, $value);
         } else {
             if ($typeRecherche === 'calendar') {
                 $fsearch = $form->calendrier('', 'TListTBS[' . $this->id . '][search][' . $key . ']', $value, 10, 10);
             } else {
                 if ($typeRecherche === 'calendars') {
                     $fsearch = $form->calendrier('', 'TListTBS[' . $this->id . '][search][' . $key . '][deb]', isset($value['deb']) ? $value['deb'] : '', 10, 10) . ' ' . $form->calendrier('', 'TListTBS[' . $this->id . '][search][' . $key . '][fin]', isset($value['fin']) ? $value['fin'] : '', 10, 10);
                 } else {
                     if (is_string($typeRecherche)) {
                         $fsearch = $TParam['search'][$key];
                     } else {
                         $fsearch = $form->texte('', 'TListTBS[' . $this->id . '][search][' . $key . ']', $value, 15, 255);
                     }
                 }
             }
         }
         if (!empty($TEntete[$key]) || $TParam['type'] == 'chart') {
             $TSearch[$key] = $fsearch;
             $nb_search_in_bar++;
         } else {
             $libelle = !empty($TParam['title'][$key]) ? $TParam['title'][$key] : $key;
             $TParam['liste']['head_search'] .= '<div>' . $libelle . ' ' . $fsearch . '</div>';
         }
     }
     $search_button = ' <a href="#" onclick="TListTBS_submitSearch(this);" class="list-search-link">' . $TParam['liste']['picto_search'] . '</a>';
     if (!empty($TParam['liste']['head_search'])) {
         $TParam['liste']['head_search'] .= '<div align="right">' . $langs->trans('Search') . ' ' . $search_button . '</div>';
     }
     if ($nb_search_in_bar > 0) {
         end($TSearch);
         list($key, $v) = each($TSearch);
         $TSearch[$key] .= $search_button;
     } else {
         $TSearch = array();
     }
     return $TSearch;
 }
function fiche_preview(&$object, &$TData)
{
    global $langs, $user, $db, $conf;
    //var_dump($_REQUEST);exit;
    $origin = GETPOST('origin');
    $head = null;
    if ($object->element == 'propal') {
        $head = propal_prepare_head($object);
    } else {
        $head = commande_prepare_head($object);
    }
    if (empty($user->rights->importdevis->myactions)) {
        accessforbidden();
        exit;
    }
    $form = new Form($db);
    llxHeader();
    $title = $langs->trans('Import');
    if ($origin == 'propal') {
        dol_fiche_head($head, 'importdevis', $title, 0, 'propal');
    } else {
        dol_fiche_head($head, 'importdevis', $title, 0, 'commande');
    }
    ?>
		<style type="text/css">
			#table_before_import tr.title_line td.for_line > * {
				display:none;
			}
			
			#table_before_import tr.line_line td.for_title > * {
				display:none;
			}
			
			.for_line select{
				white-space:normal;
				width:300px;
			}
			.ui-dialog {
			    overflow: visible !important;  /* or 'visible' whatever */
			}
		</style>
		
		<script type="text/javascript">
			$(function() {
				var old_type;
				
				$('#to_parse .type select').unbind().click(function() { old_type = $(this).val(); }).change(function() {
					switchClass($(this));
				});
				
				$( "#pop-edit-product-link" ).dialog({
			      modal: true,
			      autoOpen: false,
			      title:"Lier un produit à cette ligne",
			      buttons: {
			        "Lier ce produit": function() {
			        	
			          var fk_product = $('#fk_product_to_link').val() ;
			          var k = $(this).attr('k');	
			          $input = $('tr[k='+k+'] input[rel=fk_product]');
			         //console.log($input);
			         
			          $.ajax({
			          	url:"<?php 
    echo dol_buildpath('/product/ajax/products.php', 1);
    ?>
?action=fetch&id="+fk_product
			          	,dataType:'json'
			          }).done(function(product) {
			          	
			          	$('span[rel="ref-product"][k='+k+']').html(product.ref);
			          	$input.val(fk_product);
			          	console.log(product);
			          	
			          });
			        		
			          $( this ).dialog( "close" );
			        }
			      }
			    });
				
				function switchClass(element)
				{
					var type_value = $(element).val();
	
					if (type_value == 'title') 
					{
						$(element).parent().parent().addClass('liste_titre title_line');
						$(element).parent().parent().removeClass('line_line');
					}
					else 
					{
						$(element).parent().parent().addClass('line_line');
						$(element).parent().parent().removeClass('liste_titre title_line');
						
						if (old_type == 'title' && type_value == 'line')
						{
							while (element.length > 0)
							{
								element = $(element).parent().parent().next().find('td.type').children('select');
								
								if (element.val() == 'title') break;
								
								element.children('option[value=nomenclature]').attr('selected', true);
							}
							
						}
					}
				}
			});
			
			var imp_is_all_check = true;
			function checkAndUncheckAllImport()
			{
				if (imp_is_all_check)
				{
					imp_is_all_check = false;
					$("#to_parse tr .check_imp").attr('checked', false).prop('checked', false);
				}
				else
				{
					imp_is_all_check = true;
					$("#to_parse tr .check_imp").attr('checked', true).prop('checked', true);
				}
			}
			
			function edit_product_link(k) {
				$div = $('#pop-edit-product-link');
				$div.attr('k', k);
				
				$div.dialog('open');
			}
			
		</script>
		<div id="pop-edit-product-link" class="ui-dialog"  >
			<?php 
    $form->select_produits('', 'fk_product_to_link');
    ?>
		</div>
		<table id="table_before_import" width="100%" class="border">
			<tr>
				<td width="25%"><?php 
    echo $langs->trans('Ref');
    ?>
</td>
				<td colspan="3"><div style="vertical-align: middle"><div class="inline-block floatleft refid"><?php 
    echo $object->ref;
    ?>
</div></div></td>
			</tr>
			<tr>
				<td><?php 
    echo $langs->trans('Company');
    ?>
</td>MO-1
				<td colspan="3"><?php 
    echo $object->thirdparty->getNomUrl(1);
    ?>
</td>
			</tr>
			<tr>
				<td colspan="4">
					
						<?php 
    $PDOdb = new TPDOdb();
    $formCore = new TFormCore('auto', 'to_parse', 'post');
    echo $formCore->hidden('action', 'import_data');
    echo $formCore->hidden('id', $object->id);
    echo $formCore->hidden('origin', $origin);
    echo $formCore->hidden('token', $_SESSION['newtoken']);
    echo $formCore->hidden('data', base64_encode(serialize($TData)));
    ?>
							<table class="border" width="100%">
								<tr class="liste_titre">
									<th onclick="javascript:checkAndUncheckAllImport();" style="cursor:pointer;" title="sélectionner/désélectionner tous">Imp.</th>
									<th>Type</th>
									<?php 
    if ($conf->subtotal->enabled) {
        ?>
<th>Niveau</th><?php 
    }
    ?>
									<th>Produit</th>
									<th>Label</th>
									<th>Qté</th>
									<?php 
    if (!empty($conf->global->PRODUCT_USE_UNITS)) {
        ?>
<th>Unité</th><?php 
    }
    ?>
									<th>Prix Achat</th>
									<th>Prix</th>
									<?php 
    if (!empty($conf->global->IMPORTPROPAL_USE_MAJ_ON_NOMENCLATURE)) {
        ?>
									<th>Ligne d'origine</th>
									<?php 
    }
    ?>
								</tr>
							<?php 
    if (!empty($conf->global->IMPORTPROPAL_USE_MAJ_ON_NOMENCLATURE)) {
        $TPropalDet = array();
        foreach ($object->lines as $line) {
            $label = !empty($line->label) ? $line->label : $line->desc;
            $label .= ' (qté : ' . $line->qty . ', total HT : ' . $line->total_ht . ')';
            $TPropalDet[$line->id] = $label;
        }
    }
    $class = '';
    //var_dump($TData);
    $TWorkstation = TWorkstation::getWorstations($PDOdb);
    foreach ($TData as $k => &$row) {
        //var_dump($row);MO-1
        $workstation = new TWorkstation();
        //var_dump($workstation->loadBy($PDOdb, $row['workstation'], 'code'));
        //var_dump($workstation);exit;
        if (!empty($row['ref'])) {
            $res = $workstation->loadBy($PDOdb, $row['ref'], 'code');
            if ($res > 0) {
                $row['type'] = 'workstation';
                $id_workstation = $workstation->getId();
                //var_dump($workstation);
            }
        }
        $type = $row['type'];
        if ($type == 'title') {
            $class = '';
            print '<tr class="' . $class . ' liste_titre title_line">';
            print '<td>' . $formCore->checkbox1('', 'TData[' . $k . '][to_import]', 1, true, '', 'check_imp') . '</td>';
            print '<td class="type">' . $form->selectarray('TData[' . $k . '][type]', getTypeLine(), $row['type']) . '</td>';
            print '<td class="for_title">' . $form->selectarray('TData[' . $k . '][level]', getLevelTitle(), $row['level']) . '</td>';
            print '<td class="for_line">';
            //$form->select_produits(0, 'TData['.$k.'][fk_product]');
            print '</td>';
            print '<td>' . $formCore->texte('', 'TData[' . $k . '][label]', $row['label'], 50, 255) . '</td>';
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][qty]', $row['qty'], 3, 20) . '</td>';
            if (!empty($conf->global->PRODUCT_USE_UNITS)) {
                print '<td class="for_line"></td>';
            }
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][price]', $row['price'], 10, 20) . '</td>';
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][price]', $row['price'], 10, 20) . '</td>';
        } elseif ($type == 'workstation') {
            //var_dump($type);
            $class = '';
            print '<tr class="' . $class . ' workstation_line">';
            print '<td>' . $formCore->checkbox1('', 'TData[' . $k . '][to_import]', 1, true, '', 'check_imp') . '</td>';
            print '<td class="type">' . $form->selectarray('TData[' . $k . '][type]', getTypeLine(), $row['type']) . '</td>';
            print '<td></td>';
            print '<td class="for_line">';
            echo $formCore->combo('', 'TData[' . $k . '][fk_workstation]', $TWorkstation, $id_workstation);
            print '</td>';
            print '<td>' . $row['workstation'] . '</td>';
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][qty]', $row['qty'], 3, 20) . '</td>';
            if (!empty($conf->global->PRODUCT_USE_UNITS)) {
                print '<td class="for_line"></td>';
            }
            print '<td></td>';
            print '<td></td>';
        } else {
            $class = $class == 'impair' ? 'pair' : 'impair';
            print '<tr class="line_line ' . $class . '" k="' . $k . '">';
            print '<td>' . $formCore->checkbox1('', 'TData[' . $k . '][to_import]', 1, true, '', 'check_imp') . '</td>';
            print '<td class="type">' . $form->selectarray('TData[' . $k . '][type]', getTypeLine(), $row['type']) . '</td>';
            if ($conf->subtotal->enabled) {
                print '<td class="for_title">' . $form->selectarray('TData[' . $k . '][level]', getLevelTitle(), $row['level']) . '</td>';
            }
            print '<td class="for_line">';
            if (!empty($row['product_ref'])) {
                $p = new Product($db);
                $p->fetch(null, $row['product_ref']);
                $fk_product = $p->id;
            } else {
                $fk_product = 0;
            }
            print '<span rel="ref-product" k="' . $k . '">' . ($fk_product > 0 ? $p->getNomUrl(1) : 'N/A') . '</span> <a href="javascript:edit_product_link(' . $k . ')">' . img_edit('Changer le produit de destination') . '</a>';
            //$form->select_produits($fk_product, 'TData['.$k.'][fk_product]');
            echo $formCore->hidden('TData[' . $k . '][fk_product]', $fk_product, ' rel="fk_product" ');
            echo $formCore->hidden('TData[' . $k . '][product_ref]', $row['product_ref'], ' rel="product_ref" ');
            print '</td>';
            print '<td>' . $formCore->texte('', 'TData[' . $k . '][label]', $row['label'], 80, 255);
            print '<table>';
            print '<tr>';
            print '<td>Longueur : ' . $formCore->texte('', 'TData[' . $k . '][length]', $row['length'], 15, 255) . '</td>';
            print '<td>Largeur : ' . $formCore->texte('', 'TData[' . $k . '][width]', $row['width'], 15, 255) . '</td>';
            print '<td>Hauteur : ' . $formCore->texte('', 'TData[' . $k . '][height]', $row['height'], 15, 255) . '</td>';
            print '<td>Poids : ' . $formCore->texte('', 'TData[' . $k . '][weight]', $row['weight'], 15, 255) . '</td>';
            print '</tr>';
            print '</table>';
            print '</td>';
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][qty]', $row['qty'], 3, 20) . '</td>';
            if (!empty($conf->global->PRODUCT_USE_UNITS)) {
                print '<td class="for_line">' . $form->selectUnits($row['fk_unit'], 'TData[' . $k . '][fk_unit]', 1) . '</td>';
            }
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][buy_price]', $row['buy_price'], 10, 20) . '</td>';
            print '<td class="for_line">' . $formCore->texte('', 'TData[' . $k . '][price]', $row['price'], 10, 20) . '</td>';
        }
        if (!empty($conf->global->IMPORTPROPAL_USE_MAJ_ON_NOMENCLATURE)) {
            print '<td class="for_line">' . $form->selectarray('TData[' . $k . '][fk_propaldet]', $TPropalDet, '', 1) . '</td>';
        }
        print '</tr>';
    }
    //exit;
    ?>
							</table>
							<div class="tabsAction">
								<?php 
    echo $langs->trans('DeleteLinesBeforeImport');
    ?>
 <input id="delete_lines_before_import" name="delete_lines_before_import" type="checkbox" value="1" />
								<input class="button" type="submit" value="<?php 
    echo $langs->trans('Import');
    ?>
" />
							</div>
							<?php 
    $formCore->end();
    ?>
				</td>
			</tr>
		</table>
	<?php 
    dol_fiche_end();
    llxFooter();
}
function fiche(&$query)
{
    global $langs, $conf, $user;
    llxHeader('', 'Query', '', '', 0, 0, array('/query/js/query.js'), array('/query/css/query.css'));
    dol_fiche_head($query->title);
    if ($query->expert == 1) {
        if (!empty($query->sql_fields)) {
            $TField = explode_brackets($query->sql_fields);
            $query->TField = $TField;
        }
    }
    ?>
	<script type="text/javascript">
		var MODQUERY_INTERFACE = "<?php 
    echo dol_buildpath('/query/script/interface.php', 1);
    ?>
";
		var MODQUERY_QUERYID = <?php 
    echo $query->getId();
    ?>
;
		var MODQUERY_EXPERT = <?php 
    echo (int) $query->expert;
    ?>
;
		var MODQUERY_PREFIX = "<?php 
    echo MAIN_DB_PREFIX;
    ?>
";
		
		var select_equal = '<select sql-act="operator"> '
					+ '<option value=""> </option>'
					
					+ '<option value="LIKE">LIKE</option>'
					/*+ '<option value="=">=</option>'*/
					+ '<option value="!=">!=</option>'
					+ '<option value="&lt;">&lt;</option>'
					+ '<option value="&lt;=">&lt;=</option>'
					+ '<option value="&gt;">&gt;</option>'
					+ '<option value="&gt;=">&gt;=</option>'
					+ '<option value="IN">IN</option>'
					+ '</select>';
					
		var select_mode	= '<select sql-act="mode"> '
					+ '<option value="value">valeur</option>'
					+ '<option value="var">variable</option>'
					+ '<option value="function">fonction</option>'
					+ '</select> <input type="text" value="" sql-act="value" />';
			
		var select_null	= '<select sql-act="null"> '
					+ '<option value=""></option>'
					+ '<option value="1"><?php 
    echo $langs->transnoentities('YesAllowTestOnNull');
    ?>
</option>'
					+ '</select>';
			
		var select_order	= '<select sql-act="order"> '
					+ '<option value=""> </option>'
					+ '<option value="ASC">Ascendant</option>'
					+ '<option value="DESC">Descendant</option>'
					+ '</select>';
			
		var select_filter	= '<select sql-act="filter"> '
					+ '<option value="">Libre</option>'
					+ '<option value="calendar">Date</option>'
					+ '<option value="calendars">Dates</option>'
					+ '</select>';
			
		
			
		var select_hide	= '<select sql-act="hide"> '
					+ '<option value=""> </option>'
					+ '<option value="1"><?php 
    echo $langs->trans('Hidden');
    ?>
</option>'
					+ '</select>';
			
		var select_group	= '<select sql-act="group"> '
					+ '<option value=""> </option>'
					+ '<option value="1">Groupé</option>'
					+ '</select>';
		
		var select_total	= '<select sql-act="total"> '
					+ '<option value=""> </option>'
					+ '<option value="sum"><?php 
    echo $langs->trans('Total');
    ?>
</option>'
					+ '<option value="groupsum"><?php 
    echo $langs->trans('TotalGroup');
    ?>
</option>'
					+ '<option value="average"><?php 
    echo $langs->trans('Average');
    ?>
</option>'
					+ '<option value="count"><?php 
    echo $langs->trans('CountOf');
    ?>
</option>'
					+ '</select>';
					
		var select_total_group_field = '<select sql-act="field-total-group">'
						<?php 
    foreach ($query->TField as $field) {
        echo ' + \'<option value="' . _getFieldName($field) . '">' . _getFieldName($field) . '</option>\' ';
    }
    ?>
						+'</select>';
			
		var select_type	= '<select sql-act="type"> '
					+ '<option value=""> </option>'
					+ '<option value="number">Nombre</option>'
					+ '<option value="integer">Entier</option>'
					+ '<option value="datetime">Date/Heure</option>'
					+ '<option value="date">Date</option>'
					+ '<option value="hour">Heure</option>'
					+ '</select>';
					
		var select_function	= '<input type="text" size="10" sql-act="function" value="" placeholder="<?php 
    echo $langs->trans('FunctionToApply');
    ?>
" /><select sql-act="function-select"> '
					+ '<option value=""> </option>'
					+ '<option value="SUM(@field@)"><?php 
    echo $langs->trans('Sum');
    ?>
</option>'
					+ '<option value="ROUND(@field@,2)"><?php 
    echo $langs->trans('Round2dec');
    ?>
</option>'
					+ '<option value="COUNT(@field@)"><?php 
    echo $langs->trans('CountOf');
    ?>
</option>'
					+ '<option value="MIN(@field@)"><?php 
    echo $langs->trans('Minimum');
    ?>
</option>'
					+ '<option value="MAX(@field@)"><?php 
    echo $langs->trans('Maximum');
    ?>
</option>'
					+ '<option value="MONTH(@field@)"><?php 
    echo $langs->trans('Month');
    ?>
</option>'
					+ '<option value="YEAR"><?php 
    echo $langs->trans('Year');
    ?>
</option>'
					+ '<option value="DATE_FORMAT(@field@, \'%m/%Y\')"><?php 
    echo $langs->trans('YearMonth');
    ?>
</option>'
					//+ '<option value="FROM_UNIXTIME(@field@,\'%H:%i\')">Timestamp</option>'
					+ '<option value="SEC_TO_TIME(@field@)"><?php 
    echo $langs->trans('Timestamp');
    ?>
</option>'
					//+ '<option value="(@field@ / 3600)">/ 3600</option>'
					+ '</select>';
		
		var select_class = '<input type="text" size="10" sql-act="class" value="" placeholder="<?php 
    echo $langs->trans('Classname');
    ?>
" /><select sql-act="class-select"> '
						+ '<option value=""> </option>'

			<?php 
    foreach ($query->TClassName as $class => $label) {
        echo ' +\'<option value="' . $class . '">' . $label . '</option>\'';
    }
    ?>
			+ '</select>';

		var select_method = '<input type="text" size="10" sql-act="class-method" value="" placeholder="<?php 
    echo $langs->trans('Method');
    ?>
" /><select sql-act="class-method-select"> '
						+ '<option value=""> </option>'

			<?php 
    if (!empty($query->TMethodName)) {
        foreach ($query->TMethodName as $method => $label) {
            echo ' +\'<option value="' . $method . '">' . $label . '</option>\'';
        }
    }
    ?>
			+ '</select>';
		
		function _init_query() {
			
			<?php 
    if ($query->getId() > 0) {
        if ($query->expert == 2) {
            echo 'showQueryPreview(' . $query->getId() . ');';
            init_js($query);
        } else {
            if ($query->expert == 1) {
                echo 'showQueryPreview(' . $query->getId() . ');';
                if (!empty($query->TField)) {
                    foreach ($query->TField as $field) {
                        list($f, $t) = _getFieldAndTableName($field);
                        if (!empty($t)) {
                            $field = $t . '.' . $f;
                        } else {
                            $field = $f;
                        }
                        echo ' refresh_field_param("' . $field . '","' . $t . '"); ';
                    }
                }
                init_js($query);
            } else {
                foreach ($query->TTable as $table) {
                    echo 'addTable("' . $table . '"); ';
                }
                if (empty($query->TField) && !empty($query->sql_fields)) {
                    $query->TField = explode(',', $query->sql_fields);
                }
                //$TField =
                if (!empty($query->TField)) {
                    foreach ($query->TField as $field) {
                        echo ' checkField("' . $field . '"); ';
                    }
                    echo 'showQueryPreview(' . $query->getId() . ');';
                }
                init_js($query);
                if (!empty($query->TJoin)) {
                    foreach ($query->TJoin as $t => $join) {
                        ?>
							$("td[rel=from] select[jointure='<?php 
                        echo $t;
                        ?>
']").val("<?php 
                        echo $join[0];
                        ?>
");
							$("td[rel=to] select[jointure-to='<?php 
                        echo $t;
                        ?>
']").val("<?php 
                        echo $join[1];
                        ?>
");
							
							TJoin['<?php 
                        echo $t;
                        ?>
'] = ["<?php 
                        echo $join[0];
                        ?>
", "<?php 
                        echo $join[1];
                        ?>
"]; 
							<?php 
                    }
                }
                ?>
					refresh_sql();
					<?php 
            }
        }
    }
    ?>
		}
		
	</script>
	
	<form name="formQuery" id="formQuery">
		<input type="hidden" name="id" value="<?php 
    echo $query->getId();
    ?>
" />
		
	<div>
		<?php 
    if ($query->getId() > 0 && !empty($user->rights->query->all->expert)) {
        ?>
<div style="float:right;z-index:999; position:relative; top:40px;"><?php 
        if ($query->expert == 0) {
            ?>
<a class="butAction" href="?action=set-expert&id=<?php 
            echo $query->getId();
            ?>
"><?php 
            echo $langs->trans('setExpertMode');
            ?>
</a><?php 
        } else {
            if ($query->expert == 2) {
                ?>
<a class="butAction" href="?action=set-expert&id=<?php 
                echo $query->getId();
                ?>
"><?php 
                echo $langs->trans('setExpertMode');
                ?>
</a><?php 
                ?>
<br /><br /><a class="butAction" href="?action=unset-expert&id=<?php 
                echo $query->getId();
                ?>
"><?php 
                echo $langs->trans('unsetExpertMode');
                ?>
</a><?php 
            } else {
                ?>
<a class="butAction" href="?action=set-free&id=<?php 
                echo $query->getId();
                ?>
"><?php 
                echo $langs->trans('setExpertFreeMode');
                ?>
</a><?php 
                ?>
<br /><br /><a class="butAction" href="?action=unset-expert&id=<?php 
                echo $query->getId();
                ?>
"><?php 
                echo $langs->trans('unsetExpertMode');
                ?>
</a><?php 
            }
        }
        ?>
<br /><br /><a class="butAction" href="?action=clone&id=<?php 
        echo $query->getId();
        ?>
"><?php 
        echo $langs->trans('cloneQuery');
        ?>
</a><?php 
        ?>
<br /><br /><a class="butAction" href="?action=export&id=<?php 
        echo $query->getId();
        ?>
"><?php 
        echo $langs->trans('ExportQuery');
        ?>
</a><?php 
        ?>
</div><?php 
    }
    ?>
		<div id="query_header" style="padding: 0 20px 20px 0; background-color: #fff;z-index:1;">
			<?php 
    echo $langs->trans('Title');
    ?>
 : 
			<input type="text" name="title" size="80" value="<?php 
    echo $query->title;
    ?>
" />
			<?php 
    $form = new TFormCore();
    if (!empty($user->rights->query->bdd->use_other_db)) {
        dol_include_once('/query/class/bddconnector.class.php');
        $PDOdb = new TPDOdb();
        $formCoreBDD = new TFormCore();
        if ($query->getId() > 0) {
            $formCoreBDD->Set_typeaff('view');
        }
        echo $formCoreBDD->combo(' - ' . $langs->trans('BDD'), 'fk_bdd', TBDDConnector::getCombo($PDOdb, true), $query->fk_bdd);
    }
    echo $form->combo('- ' . $langs->trans('Type') . ' : ', 'type', $query->TGraphiqueType, $query->type);
    echo '- ' . $langs->trans('XAxis') . ' : <select name="xaxis" initValue="' . $query->xaxis . '"></select>';
    ?>
			<input class="button" type="button" id="save_query" value="<?php 
    echo $langs->trans('SaveQuery');
    ?>
" />
		</div>
		<?php 
    if ($query->getId() > 0 && !$query->expert) {
        ?>
		<div>
			<?php 
        echo $langs->trans('AddOneOfThisTables');
        ?>
 : <select id="tables"></select>
			<input class="button" type="button" id="add_this_table" value="<?php 
        echo $langs->trans('AddThisTable');
        ?>
" />
		</div>
		
		<div id="selected_tables">
			
		</div>
		<?php 
    }
    ?>
	</div>
	<?php 
    if ($query->getId() > 0 && $query->expert != 2) {
        ?>
			<div class="selected_fields">
				<div class="border" id="fields"><div class="liste_titre"><?php 
        echo $langs->trans('FieldsOrder');
        ?>
</div></div>
			</div>
			<?php 
    }
    if ($query->getId() > 0) {
        ?>
	<div id="results" style="display:<?php 
        echo $query->expert > 0 ? 'block' : 'none';
        ?>
;">
		<div>
		<?php 
        echo $langs->trans('Fields');
        ?>
<br />
		<textarea id="sql_query_fields" name="sql_fields" <?php 
        echo $query->expert == 2 ? ' style="width:700px;height:100px;" ' : '';
        ?>
><?php 
        echo htmlentities($query->sql_fields, 0, ini_get("default_charset"));
        ?>
</textarea>
		</div>
		
		<div>
		<?php 
        echo $langs->trans('From');
        ?>
<br />
		<textarea id="sql_query_from" name="sql_from" <?php 
        echo $query->expert == 2 ? 'style="width:700px;height:100px;"' : '';
        ?>
><?php 
        echo htmlentities($query->sql_from, 0, ini_get("default_charset"));
        ?>
</textarea>
		</div>
		
		<div>
		<?php 
        echo $langs->trans('Where');
        ?>
<br />
		<textarea id="sql_query_where" name="sql_where" <?php 
        echo $query->expert == 2 ? 'style="width:700px;height:200px;"' : '';
        ?>
><?php 
        echo htmlentities($query->sql_where, 0, ini_get("default_charset"));
        ?>
</textarea>
		
		<?php 
        if ($query->expert > 0) {
            echo $langs->trans('AfterWhere');
            ?>
<br /><textarea id="sql_query_afterwhere" name="sql_afterwhere" <?php 
            echo $query->expert == 2 ? 'style="width:700px;height:100px;"' : '';
            ?>
><?php 
            echo htmlentities($query->sql_afterwhere, 0, ini_get("default_charset"));
            ?>
</textarea><?php 
        } else {
            ?>
<input type="hidden" id="sql_query_afterwhere" name="sql_afterwhere" value="" /><?php 
        }
        ?>
		
		</div>
	</div>
	
	<div style="clear:both; border-top:1px solid #000;"></div>
	<?php 
        if ($query->getId() > 0 && $query->expert != 2) {
            ?>
		<div class="selected_fields_view">
			<div class="border" id="fieldsview"><div class="liste_titre"><?php 
            echo $langs->trans('FieldsView');
            ?>
</div></div>
		</div>
		<?php 
        }
        ?>
	<div id="previewRequete" style="display: none;">
		<iframe src="#" width="100%" bgcolor="#fff" frameborder="0" onload="this.height = this.contentWindow.document.body.scrollHeight + 'px'"></iframe>
	</div>
	
	<?php 
    }
    ?>
	</form>
	
	
	
	<?php 
    dol_fiche_end();
    llxFooter();
}
function _fiche(&$PDOdb, &$dispatch)
{
    global $db, $conf, $langs;
    llxHeader();
    $form = new TFormCore('auto', 'asset', 'post');
    echo $form->hidden('action', 'save');
    echo $form->hidden('id', $dispatch->fk_object);
    echo $form->hidden('type_object', $dispatch->type_object);
    $object = _header($dispatch->fk_object, $dispatch->type_object);
    $pListe[0] = "Sélectionnez une ligne";
    foreach ($object->lines as $k => &$line) {
        $label = !empty($line->label) ? $line->label : $line->libelle;
        if (empty($label) && !empty($line->desc)) {
            $label = $line->desc;
        }
        $pListe[$line->id] = $k + 1 . '/ ' . $label;
    }
    print count($dispatch->TDispatchAsset) . ' équipement(s) lié(s)<br />';
    ?>
	<table width="100%" class="border">
		<tr class="liste_titre">
			<?php 
    if (GETPOST('type_object') !== 'ticketsup') {
        print '<td>Ligne concernée</td>';
    }
    ?>
			<td>Equipement</td>
			<?php 
    if (!empty($conf->global->USE_LOT_IN_OF)) {
        ?>
<td>Numéro de Lot</td><?php 
    }
    print '<td>DLUO</td>';
    ?>
			<?php 
    if ($conf->global->clinomadic->enabled) {
        ?>
				<td>IMEI</td>
				<td>Firmware</td>
				<?php 
    }
    ?>
			<td>&nbsp;</td>
		</tr>
		
	<?php 
    foreach ($dispatch->TDispatchAsset as $k => &$da) {
        if ($da->to_delete) {
            continue;
        }
        $class = $class == 'pair' ? 'impair' : 'pair';
        ?>
<tr class="<?php 
        echo $class;
        ?>
">
			<?php 
        if (GETPOST('type_object') !== 'ticketsup') {
            echo '<td>' . $pListe[$da->fk_object] . '</td>';
        }
        ?>
			<td><?php 
        echo $da->asset->getNomUrl(1, 0, 1);
        ?>
</td>
			<td><?php 
        echo $da->asset->lot_number;
        ?>
</td>
			<?php 
        if (!empty($conf->global->USE_LOT_IN_OF)) {
            ?>
<td><?php 
            echo $da->asset->dluo ? dol_print_date($da->asset->dluo) : 'N/A';
            ?>
</td><?php 
        }
        ?>
			
			
			
			<?php 
        if ($conf->global->clinomadic->enabled) {
            ?>
				<td>IMEI</td>
				<td>Firmware</td>
				<?php 
        }
        ?>
			<td><?php 
        if ($object->statut == 0 || $type_object == 'contrat') {
            echo '<a href="?action=delete-line&k=' . $k . '&id=' . $object->id . '&type_object=' . $dispatch->type_object . '">' . img_delete() . '</a>';
        }
        ?>
</td>
		</tr>
		
		<?php 
    }
    $formproduct = new FormProduct($db);
    if ($object->statut == 0 || $type_object == 'contrat') {
        ?>
<tr style="background-color: lightblue;">
			<?php 
        if (GETPOST('type_object') !== 'ticketsup') {
            echo '<td>' . $form->combo('', 'TLine[-1][fk_object]', $pListe, '') . '</td>';
        }
        ?>
			<td><?php 
        echo $form->texte('', 'TLine[-1][serial_number]', '', 30);
        ?>
</td>
			<?php 
        if (!empty($conf->global->USE_LOT_IN_OF)) {
            ?>
<td>&nbsp;</td><?php 
        }
        ?>
			<td>&nbsp;</td>
			<?php 
        if ($conf->global->clinomadic->enabled) {
            ?>
				<td>&nbsp;</td>
				<td>&nbsp;</td>
				<?php 
        }
        ?>
			<td>Nouveau
			</td>
	</tr><?php 
    }
    ?>
	</table>
	<script type="text/javascript">
		$(document).ready(function() {
			    $( "input[name='TLine[-1][serial_number]']" ).autocomplete({
			      source: "<?php 
    echo dol_buildpath('/dispatch/script/interface.php', 1);
    ?>
?get=serial_number",
			      minLength: 1,
			      select: function( event, ui ) {
			        
			      }
			    });
		});
		
			
		</script>
	<?php 
    echo $form->btsubmit($langs->trans('Save'), 'bt_new');
    dol_fiche_end();
    $form->end();
    llxFooter();
}
        if (empty($format)) {
            continue;
        }
        $TFormat[$format] = $format;
    }
}
// Example with a yes / no select
$var = !$var;
print '<tr ' . $bc[$var] . '>';
print '<td>' . $langs->trans("IMPORTPROPAL_FORMAT") . '</td>';
print '<td align="center" width="20">&nbsp;</td>';
print '<td align="right" width="300">';
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<input type="hidden" name="action" value="set_IMPORTPROPAL_FORMAT">';
print $form->textwithpicto($formabricot->combo('', 'IMPORTPROPAL_FORMAT', $TFormat, $conf->global->IMPORTPROPAL_FORMAT), $langs->transnoentitiesnoconv('IMPORTPROPAL_FORMAT_INFO'), -1);
print '<input type="submit" class="button" value="' . $langs->trans("Modify") . '">';
print '</form>';
print '</td></tr>';
$var = !$var;
print '<tr ' . $bc[$var] . '>';
print '<td>' . $langs->trans("IMPORTPROPAL_USE_MAJ_ON_NOMENCLATURE") . '</td>';
print '<td align="center" width="20">&nbsp;</td>';
print '<td align="center" width="300">';
print ajax_constantonoff('IMPORTPROPAL_USE_MAJ_ON_NOMENCLATURE');
print '</td></tr>';
$var = !$var;
print '<tr ' . $bc[$var] . '>';
print '<td>' . $langs->trans("CREATE_PRODUCT_FROM_IMPORT") . '</td>';
print '<td align="center" width="20">&nbsp;</td>';
print '<td align="center" width="300">';
function _fiche(&$ATMdb, &$control, $mode = 'view', $editValue = false)
{
    global $db, $langs;
    llxHeader('', $langs->trans('AssetAddControl'), '', '');
    $TBS = new TTemplateTBS();
    $form = new TFormCore();
    $form->Set_typeaff($mode);
    $TForm = array('id' => $control->getId(), 'libelle' => $form->texte('', 'libelle', $control->libelle, 50, 255), 'type' => $form->combo('', 'type', TAssetControl::$TType, $control->type), 'question' => $form->texte('', 'question', $control->question, 120, 255));
    $TFormVal = _fiche_value($ATMdb, $editValue);
    $TVal = _liste_valeur($ATMdb, $control->getId(), $control->type);
    print $TBS->render('./tpl/control.tpl.php', array('TVal' => $TVal), array('co' => $TForm, 'FormVal' => $TFormVal, 'view' => array('mode' => $mode, 'editValue' => $editValue, 'type' => $control->type, 'url' => dol_buildpath('/of/control.php', 1))));
    llxFooter();
}