<?php


class Table_View {


	/**
	 * Uniq name for all application, data will be saved in cache (session).
	 */
	var $_name;

	/**
	 * Data_Source class - model to get data for table
	 *   Data_Source->get_list( $params );// pagenav, filters, etc
	 *   Data_Source->get_item( $key );// get one item by key
	 */
	var $_source;

	/**
	 * Column names list
	 */
	var $_cols;

	/**
	 * Params from pagenav, filters, etc.
	 *   pagenav params:
	 *     'limitstart'
	 *     'limit'
	 */
	var $_url_params;
	var $_url_params_default;

	var $_filters;
	var $_params;
	var $_tbl_class;


	function __construct( $name, $source ) {
		$this->_name = $name;
		$this->_source = $source;
		$this->_cols = $this->_source->get_cols();
		$this->_filters = array();
		$this->_params = array();
		$this->_url_params = array();
		$this->_tbl_class = 'tbl-view';
		$this->_base_url_params = array();

		$this->_url_params_default['limitstart'] = 0;
		$this->_url_params_default['limit'] = 10;
		$this->_url_params_default['order_by'] = 'ID';
		$this->_url_params_default['order_dir'] = 'ASC';
		$this->_url_params = V::extend($this->_url_params_default, $this->_url_params);

		$this->_load_params();// load from session cache
		$this->_fetch_params();// fetch from request
		$this->_save_params();// save in session cache
	}


	function get_url_param_source() {
		$url_param_source = $this->get_param('url_param_source');
		if (!$url_param_source) $url_param_source = $_GET;
		return $url_param_source;
	}


	function set_search_field_prefix( $prefix ) {
		$this->set_param('search_field_prefix', $prefix);
	}


	function get_search_field_prefix() {
		return V::get('search_field_prefix', "f_", $this->_params);
	}


	function set_edit_field_prefix( $prefix ) {
		$this->set_param('edit_field_prefix', $prefix);
	}


	function get_edit_field_prefix() {
		return V::get('edit_field_prefix', "e_", $this->_params);
	}


	function _fetch_params() {
		$url_param_source = $this->get_url_param_source();

		if (isset($url_param_source['limitstart'])) $this->set_url_param('limitstart', $url_param_source['limitstart']);
		if (isset($url_param_source['order_by'])) $this->set_url_param('order_by', $url_param_source['order_by']);
		if (isset($url_param_source['order_dir'])) $this->set_url_param('order_dir', $url_param_source['order_dir']);

		// search
		foreach ($this->_cols as $field_name) {
			$this->_url_params_default[$this->get_search_field_prefix() . $field_name] = '%';
		}

		// first set values from GET
		$prefix = $this->get_search_field_prefix();
		foreach ($this->_cols as $field_name) {
			if (isset($_GET[$prefix . $field_name])) {
				$this->set_url_param($prefix . $field_name, $_GET[$prefix . $field_name]);
			}
		}
		// POST override value from GET
		if (!empty($_POST)) {
			foreach ($_POST as $k => $v) {
				if (substr($k, 0, 2) == 'f_') {
					$field_name = substr($k, 2);
					if (in_array($field_name, $this->_cols)) {
						$this->set_url_param($prefix . $field_name, $v);
					}
				}
			}
		}
	}


	function _save_params() {
		if (empty($_SESSION[$this->_name])) $_SESSION[$this->_name] = array();
		$_SESSION[$this->_name]['params'] = $this->_params;
		$_SESSION[$this->_name]['url_params'] = $this->_url_params;
	}


	function _load_params() {
		if (!empty($_SESSION[$this->_name])) {
			if (!empty($_SESSION[$this->_name]['params'])) {
				foreach ($_SESSION[$this->_name]['params'] as $key => $val) {
					$this->_params[$key] = $val;
				}
			}
			if (!empty($_SESSION[$this->_name]['url_params'])) {
				foreach ($_SESSION[$this->_name]['url_params'] as $key => $val) {
					$this->_url_params[$key] = $val;
				}
			}
		}
	}


	function set_cols( $cols ) {
		$this->_cols = $cols;
	}


	function set_base_url_params( $url_params ) {
		$this->_base_url_params = $url_params;
	}


	function set_param( $key, $value ) {
		$this->_params[$key] = $value;
	}


	function get_param( $key ) {
		return V::get($key, '', $this->_params);
	}


	function set_url_param( $key, $value ) {
		$this->_url_params[$key] = $value;
	}


	function get_url_param( $key ) {
		$default = V::get($key, '', $this->_url_params_default);
		return V::get($key, $default, $this->_url_params);
	}


	function add_filter( $field_name, $filter ) {
		$this->_filters[$field_name] = $filter;
	}


	/**
	 * @return array of url params for App::link function.
	 */
	function to_html_link_params( $params = array() ) {
		$ret = array();
		$base_url_params = V::extend($this->_base_url_params, $this->_url_params);
		$url_params = V::extend($base_url_params, $params);
		foreach ($url_params as $k => $v) {
			if (substr($k, 0, 2) == 'f_') {// search field prefix
				if ($v != '%') {
					$ret [$k] = $v;
				}
			} else {
				if (isset($this->_url_params_default[$k]) && $this->_url_params_default[$k] == $url_params[$k]) {
					
				} else {
					$ret [$k] = $v;
				}
			}
		}
		return $ret;
	}


	function search_field_to_html( $field_name, $value ) {
		$out = '';
		$type = $this->_source->get_field_sql_type($field_name);
		if (!$type) {
			return $out;
		}
		$out .= App::field_search($this->get_search_field_prefix() . $field_name, $type, $value, array('class'=>'i'));
		return $out;
	}


	function edit_field_to_html( $field_name, $value ) {
		$out = '';
		$type = $this->_source->get_field_sql_type($field_name);
		if (!$type) {
			return $value;
		}
		$out .= App::field($this->get_edit_field_prefix() . $field_name, $type, $value, array('class'=>'i'));
		return $out;
	}


	function edit_form_to_html( $edit_id ) {
		$out = '';
		$back_link = App::link("wróć", $this->to_html_link_params(), array('title'=>"wróć do tabeli", 'ico_after_text'=>'back'));
		$edit_id = intval($edit_id);
		if ($edit_id <= 0) {
			return '<p class="err">' . "Bledny parametr ID" . '<br />' . $back_link . '</p>';
		}
		$item = $this->_fetch_item($edit_id);
		if (!$item) {
			return '<p class="err">' . "Rekord ID=" . $edit_id . " nie istnieje" . '<br />' . $back_link . '</p>';
		}

		// allow edit callback?
		$out_msg = '';
		$out_error = '';

		if (!empty($_POST['sent']) && $_POST['sent'] == '1') {
			$affected = $this->_source->save_item($item, $_POST, $this->get_edit_field_prefix());
			if ($affected < 0) {
				$out_error .= "Blad podczas edytowania rekordu - nic nie zmieniono";
			} else {
				if ($affected == 2) {
					$out_msg .= "Zmieniono rekord [".$item->ID."]";
				}
				else if ($affected == 1) {
					$out_msg .= "Zmieniono rekord [".$item->ID."] (Error: nie zapisano hostorii)";
				}
				if ($out_msg) {
					$out .= '<p>' . $out_msg . " - " . $back_link . '</p>';
					return $out;
				}
			}
		}

		$params = array('_tbl_task'=>'hist', '_edit_id'=>$item->ID);
		$hist_link = App::link("historia", $this->to_html_link_params($params), array('title'=>"Historia", 'ico_after_text'=>'history'));
		$out .= '<b>' . "Edycja rekordu " . $item->ID . '</b>' . " - " . $hist_link . " - " . $back_link . '<br />';

		if ($out_error) {
			$out .= '<p>' . $out_error . '</p>';
		}

		$out .= '<form action="" method="POST">';
		$out .= '<table class="' . $this->_tbl_class . '" cellspacing="0" cellpadding="0" border="1">';
		$out .= '<tfoot>';
			$out .= '<tr>';
				$out .= '<td colspan="2" style="text-align:left">';
					$out .= '<input type="hidden" name="' . "sent" . '" value="' . "1" . '" />';
					$out .= '<input type="submit" value="' . "Zapisz" . '" />';
				$out .= '</td>';
			$out .= '</tr>';
		$out .= '</tfoot>';
		$out .= '<tbody>';
		foreach ($this->_cols as $field_name) {
			$field_label = $field_name;
			$field_value = $item->$field_name;
			if ($field_name != 'ID') {// donw allow edit ID field
				if ($this->_source->field_allow_write($field_name)) {
					if (isset($_POST[$this->get_edit_field_prefix() . $field_name])) {
						$field_value = $_POST[$this->get_edit_field_prefix() . $field_name];
					}
					$field_value = $this->edit_field_to_html($field_name, $field_value);
				}
			}
			$out .= '<tr>';
				$out .= '<th>' . $field_label . '</th>';
				$out .= '<td>' . $field_value . '</td>';
			$out .= '</tr>';
		}
		$out .= '</tbody>';
		$out .= '</table>';
		$out .= '</form>';
		return $out;
	}


	function create_form_to_html() {
		$out = '';
		$back_link = App::link("wróć", $this->to_html_link_params(), array('title'=>"wróć do tabeli", 'ico_after_text'=>'back'));

		// allow edit callback?

		if (!empty($_POST['sent']) && $_POST['sent'] == '1') {
			$insert_id = $this->_source->add_item($_POST, $this->get_edit_field_prefix());
			if ($insert_id > 0) {
				$out .= '<p>' . "Dodano nowy rekord [" . $insert_id . "]" . " - " . $back_link;
				$params = array('_tbl_task'=>'edit', '_edit_id'=>$insert_id);
				$edit_link = App::link("[" . $insert_id . "]", $this->to_html_link_params($params), array('title'=>"wróć do tabeli", 'ico_after_text'=>'edit'));
				$out .= " lub edytuj rekord " . $edit_link . '</p>';
				return $out;
			}
		}

		$out .= '<b>' . "Dodawanie nowego rekordu " . '</b>' . " - " . $back_link . '<br />';

		$out .= '<form action="" method="POST">';
		$out .= '<table class="' . $this->_tbl_class . '" cellspacing="0" cellpadding="0" border="1">';
		$out .= '<tfoot>';
			$out .= '<tr>';
				$out .= '<td colspan="2" style="text-align:left">';
					$out .= '<input type="hidden" name="' . "sent" . '" value="' . "1" . '" />';
					$out .= '<input type="submit" value="' . "Zapisz" . '" />';
				$out .= '</td>';
			$out .= '</tr>';
		$out .= '</tfoot>';
		$out .= '<tbody>';
		foreach ($this->_cols as $field_name) {
			$field_label = $field_name;
			$field_value = '';
			if ($field_name != 'ID') {// donw allow edit ID field
				if ($this->_source->field_allow_create($field_name)) {
					if (isset($_POST[$this->get_edit_field_prefix() . $field_name])) {
						$field_value = $_POST[$this->get_edit_field_prefix() . $field_name];
					}
				}
				$field_value = $this->edit_field_to_html($field_name, $field_value);
			}
			$out .= '<tr>';
				$out .= '<th>' . $field_label . '</th>';
				$out .= '<td>' . $field_value . '</td>';
			$out .= '</tr>';
		}
		$out .= '</tbody>';
		$out .= '</table>';
		$out .= '</form>';
		return $out;
	}


	function hist_to_html( $id ) {
		$out = '';
		$back_link = App::link("wróć", $this->to_html_link_params(), array('title'=>"wróć do tabeli", 'ico_after_text'=>'back'));
		$edit_id = intval($id);
		if ($id <= 0) {
			return '<p class="err">' . "Bledny parametr ID" . '<br />' . $back_link . '</p>';
		}

		$item = $this->_fetch_item($edit_id);
		if (!$item) {
			return '<p class="err">' . "Rekord ID=" . $edit_id . " nie istnieje" . '<br />' . $back_link . '</p>';
		}

		$out .= '<p><b>' . "Historia edycji rekordu " . $item->ID . '</b>' . " - " . $back_link . '</p>';

		$items = $this->_fetch_hist_items($id);
		$item->ID_USERS2 = 0;
		array_unshift($items, $item);

		$out .= '<style type="text/css">' . "
.tbl-view .hist-current td {background-color:#FFEDD5; border-bottom:2px solid red;}
.tbl-view .hist-empty {color:#666;}
.tbl-view .hist-not-empty {background-color:#eee;}
		" . '</style>';

		$out .= '<table class="' . $this->_tbl_class . '" cellspacing="0" cellpadding="0" border="1">';
		$out .= '<thead>';
			$out .= '<tr id="item-' . $item->ID . '">';
			foreach ($this->_cols as $field_name) {
				$out .= '<td>';
					$out .= $field_name;
				$out .= '</td>';
			}
			$out .= '</tr>';
		$out .= '</thead>';
		$out .= '<tbody>';
		foreach ($items as $item) {
			$cls = '';
			if ($item->ID_USERS2 == 0) {
				$cls = ' class="hist-current"';
			}
			$out .= '<tr' . $cls . '>';
			foreach ($this->_cols as $field_name) {
				$cls = '';
				$val = '&nbsp;';
				if (isset($item->$field_name)) {
					$val = $item->$field_name;
				}
				if ($field_name != 'ID') {
					$cls = ($val == 'N/S;')? 'hist-empty' : 'hist-not-empty';
				}
				if ($cls) $cls = ' class="' . $cls . '"';
				$out .= '<td' . $cls . '>';
					$out .= $val;
				$out .= '</td>';
			}
			$out .= '</tr>';
		}
		if (count($items) < 2) {
			$out .= '<tr id="item-' . $item->ID . '">';
				$out .= '<td colspan="' . count($this->_cols) . '">' . "Brak danych w tabeli HIST" . '</td>';
			$out .= '</tr>';
		}
		$out .= '</tbody>';
		$out .= '</table>';
		return $out;
	}


	function _view_col_is_hidden( $col_name ) {
		if (array_key_exists($col_name, $_SESSION[$this->_name]['hidden_cols'])) {
			return $_SESSION[$this->_name]['hidden_cols'][$col_name];
		}
	}


	function _view_col_hide( $col_name ) {
		$_SESSION[$this->_name]['hidden_cols'][$col_name] = true;
	}


	function _view_col_show( $col_name ) {
		unset($_SESSION[$this->_name]['hidden_cols'][$col_name]);
	}


	function config_form_to_html() {
		$url_param_source = $this->get_url_param_source();
		if (!empty($url_param_source['_hide_col'])) {
			if ($url_param_source['_hide_col'] != 'ID') {
				$this->_view_col_hide($url_param_source['_hide_col']);
			}
		}
		if (!empty($url_param_source['_show_col'])) {
			if ($url_param_source['_show_col'] != 'ID') {
				$this->_view_col_show($url_param_source['_show_col']);
			}
		}
		$out = '';
		$back_link = App::link("wróć", $this->to_html_link_params(), array('title'=>"wróć do tabeli", 'ico_after_text'=>'back'));
		$out .= '<p><b>' . "Konfiguracja tabeli " . '</b>' . " - " . $back_link . '</p>';
		$out .= '<table class="tbl-view" cellspacing="0" cellpadding="0" border="1">';
		foreach ($this->_cols as $field_name) {
			$out .= '<tr>';
				$out .= '<td>' . $field_name . '</td>';
				$out .= '<td>';
				if ($field_name != 'ID') {
					if ($this->_view_col_is_hidden($field_name)) {
						$link_params = array('_tbl_task'=>'config', '_show_col'=>$field_name);
						$out .= App::link("show", $this->to_html_link_params($link_params), array('class'=>'btn'));
					} else {
						$link_params = array('_tbl_task'=>'config', '_hide_col'=>$field_name);
						$out .= App::link("hide", $this->to_html_link_params($link_params), array('class'=>'btn'));
					}
				}
				$out .= '</td>';
			$out .= '</tr>';
		}
		$out .= '</table>';
		return $out;
	}


	function table_to_html() {
		$out = '';
		if (empty($this->_cols)) {
			trigger_error("No cols set in " . __CLASS__, E_USER_NOTICE);
			return $out;
		}
		$items = $this->_fetch_items();
		$total = $this->_fetch_total();

		$out .= '<style type="text/css">' . "
.order-dir {color:blue; text-decoration:none; font-weight:bold;}
 .order-dir:hover {}
.order-current {color:red;}
 .order-current:hover {}

.tbl-view .find td.selected {border-bottom: 2px solid red;}
.tbl-view tbody tr.selected td {background-color:#FFEDD5;}
.tbl-view-txt-zwin tbody td {white-space:nowrap; max-width:200px; overflow:hidden;}
.tbl-view .tbl-cell-links,
.tbl-view .config td,
.tbl-view .config th{background-color:#D7EED7;}
		" . '</style>';
		$out .= '<form action="" method="POST">';
		$out .= '<table class="' . $this->_tbl_class . '" cellspacing="0" cellpadding="0" border="1">';
		$out .= '<thead>';
		$out .= '<tr>';
			$out .= '<td class="tbl-cell-links">';
				// TODO: tbl config, perm edit?
				$link_params = array('_tbl_task'=>'create');
				$out .= ' '.App::link("Add", $this->to_html_link_params($link_params), array('ico'=>'add', 'title'=>"Dodaj nowy rekord"));

				$link_params = array('_tbl_task'=>'config');
				$js = "jQuery(this).parents('thead').find('.config').toggle(); return false;";
				$out .= ' '.App::link("konfiguracja", $this->to_html_link_params($link_params), array('ico'=>'excel', 'title'=>"Konfiguracja", 'onclick'=>$js));
			$out .= '</td>';
		foreach ($this->_cols as $field_name) {
			if ($this->_view_col_is_hidden($field_name)) {
				continue;
			}
			$cur_order_by = false;
			$cur_order_by_link = '';
			// order by field
			if ($this->get_url_param('order_by') == $field_name) {
				$cur_order_by = true;
				if ($this->get_url_param('order_dir') == 'DESC') {
					$cur_order_by_link .= App::link("^", $this->to_html_link_params(array('order_by'=>$field_name, 'order_dir'=>'ASC')), array('title'=>"asc", 'class'=>"order-dir order-current"));
				} else {
					$cur_order_by_link .= App::link("v", $this->to_html_link_params(array('order_by'=>$field_name, 'order_dir'=>'DESC')), array('title'=>"desc", 'class'=>"order-dir order-current"));
				}
			} else {
				$cur_order_by_link .= App::link("^", $this->to_html_link_params(array('order_by'=>$field_name, 'order_dir'=>'ASC')), array('title'=>"asc", 'class'=>"order-dir"));
				$cur_order_by_link .= " ";
				$cur_order_by_link .= App::link("v", $this->to_html_link_params(array('order_by'=>$field_name, 'order_dir'=>'DESC')), array('title'=>"desc", 'class'=>"order-dir"));
			}

			$out .= '<td>';
				// TODO: if set header for this column
				$out .= str_replace('_', ' ', $field_name);
				if ($cur_order_by_link) {
					$out .= " " . '<nobr>' . $cur_order_by_link . '</nobr>';
				}
			$out .= '</td>';
		}
		$out .= '</tr>';
		$out .= '<tr class="config" style="display:none">';
			$out .= '<td>' . "&nbsp;" . '</td>';
			foreach ($this->_cols as $field_name) {
				if ($this->_view_col_is_hidden($field_name)) {
					continue;
				}
				$out .= '<th>';
				if ($field_name != 'ID') {
					if (!$this->_view_col_is_hidden($field_name)) {
						$link_params = array('_tbl_task'=>'config', '_hide_col'=>$field_name);
						$out .= App::link("x", $this->to_html_link_params($link_params), array('title'=>"Ukryj kolumnę " . $field_name, 'ico'=>'del.png'));
					}
				}
				$out .= '</th>';
			}
		$out .= '</tr>';
		$out .= '<tr class="config" style="display:none">';
			$out .= '<td colspan="' . (count($this->_cols) + 1) . '">';// TODO: visible cols count
				// widok: full, line
				$js = "var tbl=jQuery(this).parents('table:first');tbl.toggleClass('tbl-view-txt-zwin');if(tbl.hasClass('tbl-view-txt-zwin')){jQuery(this).attr('title','Pełny tekst')}else{jQuery(this).attr('title','krótki tekst')};return false;";
				$link_params = array('_tbl_task'=>'config', 'widok'=>"full");
				$out .= App::link("tekst", $this->to_html_link_params($link_params), array('title'=>"Pełny tekst", 'onclick'=>$js));
			$out .= '</td>';
		$out .= '</tr>';
		if ($this->get_param('show_search')) {
			$out .= '<tr class="find">';
				$out .= '<td>';
					$out .= '<input type="image" value="' . "Szukaj" . '" src="' . "icon/search.png" . '" title="' . "Szukaj" . '" />';
					// TODO: add clear btn for this form
					$filter_selected = false;
					foreach ($this->_cols as $field_name) {
						$val = $this->get_url_param($this->get_search_field_prefix() . $field_name);
						if ($val != '%') $filter_selected = true;
					}
					if ($filter_selected) {
						$out .= '<input type="image" value="' . "Czyść" . '" src="' . "icon/del.png" . '" title="' . "Czyść" . '" onclick="return reset_search_form(this);" />';
					}
				$out .= '</td>';
				foreach ($this->_cols as $field_name) {
					if ($this->_view_col_is_hidden($field_name)) {
						continue;
					}
					$val = $this->get_url_param($this->get_search_field_prefix() . $field_name);
					$cls = '';
					if ($val != '%') $cls .= 'selected';
					if ($cls) $cls = ' class="' . $cls . '"';
					$out .= '<td'.$cls.'>';
						// TODO: filters for this field
						$out .= $this->search_field_to_html($field_name, $val);
					$out .= '</td>';
				}
			$out .= '</tr>';
		}
		$out .= '</thead>';
		$out .= '<tfoot>';
			$out .= '<td colspan="' . (count($this->_cols) + 1) . '">';// TODO: visible cols count
				$page_nav = new stdClass();
				$page_nav->total = $total;
				$page_nav->limit = $this->_url_params['limit'];
				$page_nav->current = $this->_url_params['limitstart'];
				$page_nav->offset_prev = $page_nav->current - $page_nav->limit;
				if ($page_nav->offset_prev < 0) $page_nav->offset_prev = 0;
				$page_nav->offset_next = $page_nav->current + $page_nav->limit;
				$page_nav->offset_end = floor($total / $page_nav->limit) * $page_nav->limit;

				$link_params = array('limitstart'=>0);
				$out .= App::link("&lt;&lt;", $this->to_html_link_params($link_params), array('class'=>'btn'));

				$link_params = array('limitstart'=>$page_nav->offset_prev);
				$out .= ' '.App::link("&lt; -" . $page_nav->limit, $this->to_html_link_params($link_params), array('class'=>'btn'));

				$out .= ' <b>' . $page_nav->current . '</b> <i title="' . "wszystkich " . $page_nav->total . '">(' . $page_nav->total . ')</i> ';

				$link_params = array('limitstart'=>$page_nav->offset_next);
				$out .= ' '.App::link("+" . $page_nav->limit . " &gt;", $this->to_html_link_params($link_params), array('class'=>'btn'));

				$link_params = array('limitstart'=>$page_nav->offset_end);
				$out .= ' '.App::link("&gt;&gt;", $this->to_html_link_params($link_params), array('class'=>'btn'));
			$out .= '</td>';
		$out .= '</tfoot>';
		$out .= '<tbody>';
		foreach ($items as $item) {
			$out .= '<tr id="item-' . $item->ID . '">';
				$out .= '<td>';
					// edit - allow edit callback?
					$link_params = array('_tbl_task'=>'edit', '_edit_id'=>$item->ID);
					$out .= ' '.App::link("Edit", $this->to_html_link_params($link_params), array('ico'=>'edit.png', 'title'=>"Edytuj " . $item->ID));
					// hist
					$link_params = array('_tbl_task'=>'hist', '_edit_id'=>$item->ID);
					$out .= ' '.App::link("Historia", $this->to_html_link_params($link_params), array('ico'=>'history', 'title'=>"Historia rekordu " . $item->ID));
				$out .= '</td>';
			foreach ($this->_cols as $field_name) {
				if ($this->_view_col_is_hidden($field_name)) {
					continue;
				}
				$out .= '<td>';
				if (isset($item->$field_name)) {
					$out .= $item->$field_name;
				} else {
					$out .= '&nbsp;';
				}
				$out .= '</td>';
			}
			$out .= '</tr>';
		}
		$out .= '</tbody>';
		$out .= '</table>';
		$out .= '</form>';
		$out .= '<script type="text/javascript">' . "
jQuery(document).ready(function(){
	jQuery('." . $this->_tbl_class . "').addClass('tbl-view-txt-zwin');
	jQuery('." . $this->_tbl_class . " tbody tr').click(function(){
		jQuery(this).toggleClass('selected');
		console.log( jQuery(this).attr('id') )
	});
});
function reset_search_form(n){
	console.log(n)
	var p=jQuery(n).parents('.find:first');
	console.log(p)
	if (!p) return false;
	p.find('td').removeClass('selected');
	fields=p.find('input').val('%');
	fields=p.find('select').each(function(ind,field){
		switch (field.type.toLowerCase()){
			case 'text':
				field.value='%';
				break;
			case 'select-one':
//				field.options[0].selected = true;
//				break;
			case 'select-multiple':
				for (z = 0; z < field.options.length; z++) {
					field.options[z].selected = false;
					if (field.options[z].hasAttribute('selected')) {
						field.options[z].removeAttribute('selected');
					}
				}
				// select first element
				field.options[0].selected = true;
				field.options[0].setAttribute('selected', 'selected');
				break;
			default:
		}
	});
	return false;
}
		" . '</script>';
		return $out;
	}


	/**
	 * @param '_tbl_task' ('edit', 'hist', 'create', 'config')
	 * @param '_edit_id'
	 */
	function to_html() {
		$url_param_source = $this->get_url_param_source();

		$_tbl_task = $url_param_source['_tbl_task'];
		switch ($_tbl_task) {
			case 'edit':
				return $this->edit_form_to_html($url_param_source['_edit_id']);
				break;
			case 'hist':
				return $this->hist_to_html($url_param_source['_edit_id']);
				break;
			case 'create':
				return $this->create_form_to_html();
				break;
			case 'config':
				return $this->config_form_to_html();
				break;
			default:
				return $this->table_to_html();
		}
	}


	function &_fetch_items() {
		return $this->_source->get_items($this->_url_params);
	}


	function &_fetch_item( $id ) {
		return $this->_source->get_item($id);
	}


	function &_fetch_hist_items( $id ) {
		return $this->_source->get_hist_items($id);
	}


	function _fetch_total() {
		return $this->_source->get_total($this->_url_params);
	}


}
