Location: PHPKode > scripts > PHP DataGrid > datagrid.class.php
<?php
################################################################################
##              -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =-                 #
## --------------------------------------------------------------------------- #
##  PHP DataGrid version 4.2.8 (01.10.2008)                                    #
##  Author & developer:     Leumas Naypoka <hide@address.com>                #
##  Developers:             Zewa           <http://www.softic.at>              #
##                          Fcallez        <http://www.innovavirtual.org>      #
##  Lisence:    GNU GPL                                                        #
##  Site:       http://phpbuilder.blogspot.com                                 #
##  Copyright:  Leumas Naypoka (c) 2006-2008. All rights reserved.             #
##                                                                             #
##  Additional modules (embedded):                                             #
##  -- openWYSIWYG 1.01 (free cross-browser)            http://openWebWare.com #
##  -- PEAR::DB 1.7.11 (PHP Ext. & Application Repository) http://pear.php.net #
##  -- JS AFV 1.0.3 (JS Auto From Validator)    http://phpbuilder.blogspot.com #
##  -- overLIB 4.21 (JS library)            http://www.bosrup.com/web/overlib/ #
##  -- FPDF v.1.53 (PDF files generator)                   http://www.fpdf.org #
##  -- JsCalendar v.1.0 (DHTML/JavaScript Calendar)     http://www.dynarch.com #
##  -- AutoSuggest v.2.1.3 (AJAX autocomplete) http://www.brandspankingnew.net #
##                                                                             # 
################################################################################
## +---------------------------------------------------------------------------+
## | 1. Creating & Calling:                                                    | 
## +---------------------------------------------------------------------------+
##  *** define a relative (virtual) path to datagrid.class.php file and "pear" 
##  *** directory (relatively to the current file)
##  *** RELATIVE PATH ONLY ***
//
//  define ("DATAGRID_DIR", "");                     /* Ex.: "datagrid/" */ 
//  define ("PEAR_DIR", "pear/");                    /* Ex.: "datagrid/pear/" */
//
//  require_once(DATAGRID_DIR.'datagrid.class.php');
//  require_once(PEAR_DIR.'PEAR.php');
//  require_once(PEAR_DIR.'DB.php');
##
##  *** creating variables that we need for database connection 
//  $DB_USER='name';            /* usually like this: prefix_name             */
//  $DB_PASS='';                /* must be already enscrypted (recommended)   */
//  $DB_HOST='localhost';       /* usually localhost                          */
//  $DB_NAME='dbName';          /* usually like this: prefix_dbName           */
//
//  ob_start();
##  *** (example of ODBC connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('odbc://root:hide@address.com'));
##  *** (example of Oracle connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('oci8://root:hide@address.com:1521/mydatabase)); 
##  *** (example of PostgreSQL connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('pgsql://root:hide@address.com/mydatabase)); 
##  === (Examples of connections to other db types see in "docs/pear/" folder)
//  $db_conn = DB::factory('mysql');  /* don't forget to change on appropriate db type */
//  $result_conn = $db_conn->connect(DB::parseDSN('mysql://'.$DB_USER.':'.$DB_PASS.'@'.$DB_HOST.'/'.$DB_NAME));
//  if(DB::isError($result_conn)){ die($result_conn->getDebugInfo()); }  
##  *** put a primary key on the first place 
//  $sql = "SELECT primary_key, field_1, field_2 ... FROM tableName ;";
##  *** set encoding and collation (default: utf8/utf8_unicode_ci)
/// $dg_encoding = "utf8";
/// $dg_collation = "utf8_unicode_ci";
/// $dgrid->SetEncoding($dg_encoding, $dg_collation);
##  *** set needed options and create a new class instance 
//  $debug_mode = false;        /* display SQL statements while processing */    
//  $messaging = true;          /* display system messages on a screen */ 
//  $unique_prefix = "abc_";    /* prevent overlays - must be started with a letter */
//  $dgrid = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
##  *** set data source with needed options
//  $default_order_field = "field_name_1 [, field_name_2...]";
//  $default_order_type = "ASC|DESC [, ASC|DESC...]";
//  $dgrid->DataSource($db_conn, $sql, $default_order_field, $default_order_type);	    
##
##
## +---------------------------------------------------------------------------+
## | 2. General Settings:                                                      | 
## +---------------------------------------------------------------------------+
##  *** set interface language (default - English)
##  *** (en) - English     (de) - German     (se) - Swedish   (hr) - Bosnian/Croatian
##  *** (hu) - Hungarian   (es) - Espanol    (ca) - Catala    (fr) - Francais
##  *** (nl) - Netherlands/"Vlaams"(Flemish) (it) - Italiano  (pl) - Polish
##  *** (ch) - Chinese     (sr) - Serbian    (bg) - Bulgarian (pb) - Brazilian Portuguese
##  *** (ar) - Arabic      (tr) - Turkish    (cz) - Czech     (ro/ro_utf8) - Romanian
##  *** (gk) - Greek       (he) - Hebrew     (ru_utf8) - Russian
/// $dg_language = "en";  
/// $dgrid->SetInterfaceLang($dg_language);
##  *** set direction: "ltr" or "rtr" (default - "ltr")
/// $direction = "ltr";
/// $dgrid->SetDirection($direction);
##  *** set layouts: "0" - tabular(horizontal) - default, "1" - columnar(vertical), "2" - customized 
/// $layouts = array("view"=>"0", "edit"=>"1", "details"=>"1", "filter"=>"1"); 
/// $dgrid->SetLayouts($layouts);
/// $details_template = "<table><tr><td>{field_name_1}</td><td>{field_name_2}</td></tr>...</table>";
/// $dgrid->SetTemplates("","",$details_template);
##  *** set modes for operations ("type" => "link|button|image") 
##  *** "byFieldValue"=>"fieldName" - make the field to be a link to edit mode page
/// $modes = array(
///     "add"	  =>array("view"=>true, "edit"=>false, "type"=>"link", "show_add_button"=>"inside|outside"),
///     "edit"	  =>array("view"=>true, "edit"=>true,  "type"=>"link", "byFieldValue"=>""),
///     "cancel"  =>array("view"=>true, "edit"=>true,  "type"=>"link"),
///     "details" =>array("view"=>true, "edit"=>false, "type"=>"link"),
///     "delete"  =>array("view"=>true, "edit"=>true,  "type"=>"image")
/// );
/// $dgrid->SetModes($modes);
##  *** allow scrolling on datagrid
/// $scrolling_option = false;
/// $dgrid->AllowScrollingSettings($scrolling_option);  
##  *** set scrolling settings (optional)
/// $scrolling_width = "90%";
/// $scrolling_height = "100%";
/// $dgrid->setScrollingSettings($scrolling_width, $scrolling_height);
##  *** allow multirow operations
//  $multirow_option = true;
//  $dgrid->AllowMultirowOperations($multirow_option);
/// $multirow_operations = array(
///     "delete"  => array("view"=>true),
///     "details" => array("view"=>true),
///     "my_operation_name" => array("view"=>true, "flag_name"=>"my_flag_name", "flag_value"=>"my_flag_value", "tooltip"=>"Do something with selected", "image"=>"image.gif")
/// );
/// $dgrid->SetMultirowOperations($multirow_operations);  
##  *** set CSS class for datagrid
##  *** "default" or "blue" or "gray" or "green" or "pink" or your own css file 
/// $css_class = "default";
/// $dgrid->SetCssClass($css_class);
##  *** set variables that used to get access to the page (like: my_page.php?act=34&id=56 etc.) 
/// $http_get_vars = array("act", "id");
/// $dgrid->SetHttpGetVars($http_get_vars);
##  *** set other datagrid/s unique prefixes (if you use few datagrids on one page)
##  *** format (in which mode to allow processing of another datagrids)
##  *** array("unique_prefix"=>array("view"=>true|false, "edit"=>true|false, "details"=>true|false));
/// $anotherDatagrids = array("abcd_"=>array("view"=>true, "edit"=>true, "details"=>true));
/// $dgrid->SetAnotherDatagrids($anotherDatagrids);  
##  *** set DataGrid caption
/// $dg_caption = "My Favorite Lovely PHP DataGrid";
/// $dgrid->SetCaption($dg_caption);
##
##
## +---------------------------------------------------------------------------+
## | 3. Printing & Exporting Settings:                                         | 
## +---------------------------------------------------------------------------+
##  *** set printing option: true(default) or false 
/// $printing_option = true;
/// $dgrid->AllowPrinting($printing_option);
##  *** set exporting option: true(default) or false and relative (virtual) path
##  *** to export directory (relatively to datagrid.class.php file).
##  *** Ex.: "" - if we use current datagrid folder
/// $exporting_option = true;
/// $exporting_directory = "";               
/// $dgrid->AllowExporting($exporting_option, $exporting_directory);
/// $exporting_types = array("excel"=>"true", "pdf"=>"true", "xml"=>"true");
/// $dgrid->AllowExportingTypes($exporting_types);
##
##
## +---------------------------------------------------------------------------+
## | 4. Sorting & Paging Settings:                                             | 
## +---------------------------------------------------------------------------+
##  *** set sorting option: true(default) or false 
/// $sorting_option = true;
/// $dgrid->AllowSorting($sorting_option);               
##  *** set paging option: true(default) or false 
/// $paging_option = true;
/// $rows_numeration = false;
/// $numeration_sign = "N #";
/// $dgrid->AllowPaging($paging_option, $rows_numeration, $numeration_sign);
##  *** set paging settings
/// $bottom_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
/// $top_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
//  $pages_array = array("10"=>"10", "25"=>"25", "50"=>"50", "100"=>"100", "250"=>"250", "500"=>"500", "1000"=>"1000");
/// $default_page_size = 10;
/// $paging_arrows = array("first"=>"|&lt;&lt;", "previous"=>"&lt;&lt;", "next"=>"&gt;&gt;", "last"=>"&gt;&gt;|");
/// $dgrid->SetPagingSettings($bottom_paging, $top_paging, $pages_array, $default_page_size, $paging_arrows);
##
##
## +---------------------------------------------------------------------------+
## | 5. Filter Settings:                                                       | 
## +---------------------------------------------------------------------------+
##  *** set filtering option: true or false(default)
/// $filtering_option = true;
/// $show_search_type = true;
/// $dgrid->AllowFiltering($filtering_option, $show_search_type);
##  *** set aditional filtering settings
##  *** tips: use "," (comma) if you want to make search by some words, for ex.: hello, bye, hi
/// $fill_from_array = array("0"=>"No", "1"=>"Yes");  /* as "value"=>"option" */
/// $filtering_fields = array(
///     "Caption_1"=>array("type"=>"textbox", "table"=>"tableName_1", "field"=>"fieldName_1|,fieldName_2", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_2"=>array("type"=>"textbox", "autocomplete"=>"false", "handler"=>"modules/autosuggest/test.php", "maxresults"=>"12", "shownoresults"=>"false", "table"=>"tableName_1", "field"=>"fieldName_1|,fieldName_2", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_3"=>array("type"=>"dropdownlist", "order"=>"ASC|DESC", "table"=>"tableName_2", "field"=>"fieldName_2", "source"=>"self"|$fill_from_array, "show"=>"", "condition"=>"", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_4"=>array("type"=>"calendar", "table"=>"tableName_3", "field"=>"fieldName_3", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
/// );
/// $dgrid->SetFieldsFiltering($filtering_fields);
##
## 
## +---------------------------------------------------------------------------+
## | 6. View Mode Settings:                                                    | 
## +---------------------------------------------------------------------------+
##  *** set view mode table properties
/// $vm_table_properties = array("width"=>"90%");
/// $dgrid->SetViewModeTableProperties($vm_table_properties);  
##  *** set columns in view mode
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
##  ***      "barchart" : number format in SELECT SQL must be equal with number format in max_value
/// $fill_from_array = array("0"=>"Banned", "1"=>"Active", "2"=>"Closed", "3"=>"Removed"); /* as "value"=>"option" */
/// $vm_colimns = array(
///     "FieldName_1"=>array("header"=>"Name_A", "type"=>"label",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_2"=>array("header"=>"Name_B", "type"=>"image",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "target_path"=>"uploads/", "default"=>"default_image.ext", "image_width"=>"50px", "image_height"=>"30px", "magnify"=>"false"),
///     "FieldName_3"=>array("header"=>"Name_C", "type"=>"linktoview", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_4"=>array("header"=>"Name_D", "type"=>"linktoedit", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_5"=>array("header"=>"Name_E", "type"=>"linktodelete", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_6"=>array("header"=>"Name_F", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"{0}"),
///     "FieldName_7"=>array("header"=>"Name_G", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"mailto:{0}"),
///     "FieldName_8"=>array("header"=>"Name_H", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"http://mydomain.com?act={0}&act={1}&code=ABC"),
///     "FieldName_9"=>array("header"=>"Name_I", "type"=>"money",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "sign"=>"$", "decimal_places"=>"2", "dec_separator"=>".", "thousands_separator"=>","),
///     "FieldName_10"=>array("header"=>"Name_J", "type"=>"password",   "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_11"=>array("header"=>"Name_K", "type"=>"barchart",   "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field"=>"field_name", "maximum_value"=>"value"),
///     "FieldName_12"=>array("header"=>"Name_L", "type"=>"enum",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "source"=>$fill_from_array),
/// );
/// $dgrid->SetColumnsInViewMode($vm_colimns);
##  *** set auto-genereted columns in view mode
//  $auto_column_in_view_mode = false;
//  $dgrid->SetAutoColumnsInViewMode($auto_column_in_view_mode);
##
##
## +---------------------------------------------------------------------------+
## | 7. Add/Edit/Details Mode Settings:                                        | 
## +---------------------------------------------------------------------------+
##  *** set add/edit mode table properties
/// $em_table_properties = array("width"=>"70%");
/// $dgrid->SetEditModeTableProperties($em_table_properties);
##  *** set details mode table properties
/// $dm_table_properties = array("width"=>"70%");
/// $dgrid->SetDetailsModeTableProperties($dm_table_properties);
##  ***  set settings for add/edit/details modes
//  $table_name  = "table_name";
//  $primary_key = "primary_key";
//  $condition   = "table_name.field = ".$_REQUEST['abc_rid'];
//  $dgrid->SetTableEdit($table_name, $primary_key, $condition);
##  *** set columns in edit mode   
##  *** first letter:  r - required, s - simple (not required)
##  *** second letter: t - text(including datetime), n - numeric, a - alphanumeric,
##                     e - email, f - float, y - any, l - login name, z - zipcode,
##                     p - password, i - integer, v - verified, c - checkbox, u - URL
##  *** third letter (optional): 
##          for numbers: s - signed, u - unsigned, p - positive, n - negative
##          for strings: u - upper,  l - lower,    n - normal,   y - any
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
##  *** Ex.: type = textbox|textarea|label|date(yyyy-mm-dd)|datedmy(dd-mm-yyyy)|datetime(yyyy-mm-dd hh:mm:ss)|datetimedmy(dd-mm-yyyy hh:mm:ss)|time(hh:mm:ss)|image|password|enum|print|checkbox
##  *** make sure your WYSIWYG dir has 777 permissions
/// $fill_from_array = array("0"=>"No", "1"=>"Yes", "2"=>"Don't know", "3"=>"My be"); /* as "value"=>"option" */
/// $em_columns = array(
///     "FieldName_1"  =>array("header"=>"Name_A", "type"=>"textbox",    "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_2"  =>array("header"=>"Name_B", "type"=>"textarea",   "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "edit_type"=>"simple|wysiwyg", "resizable"=>"false", "rows"=>"7", "cols"=>"50"),
///     "FieldName_3"  =>array("header"=>"Name_C", "type"=>"label",      "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_4"  =>array("header"=>"Name_D", "type"=>"date",       "req_type"=>"rt", "width"=>"187px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "calendar_type"=>"popup|floating"),
///     "FieldName_5"  =>array("header"=>"Name_E", "type"=>"datetime",   "req_type"=>"st", "width"=>"187px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "calendar_type"=>"popup|floating"),
///     "FieldName_6"  =>array("header"=>"Name_F", "type"=>"time",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_7"  =>array("header"=>"Name_G", "type"=>"image",      "req_type"=>"st", "width"=>"220px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "target_path"=>"uploads/", "max_file_size"=>"100000|100K|10M|1G", "image_width"=>"120px", "image_height"=>"90px", "magnify"=>"false", "file_name"=>"", "host"=>"local|remote"),
///     "FieldName_8"  =>array("header"=>"Name_H", "type"=>"password",   "req_type"=>"rp", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_9"  =>array("header"=>"Name_I", "type"=>"enum",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "source"=>"self"|$fill_from_array, "view_type"=>"dropdownlist(default)|radiobutton", "radiobuttons_alignment"=>"horizontal|vertical", "multiple"=>"false", "multiple_size"=>"4"),
///     "FieldName_10" =>array("header"=>"Name_J", "type"=>"print",      "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_11" =>array("header"=>"Name_K", "type"=>"checkbox",   "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "true_value"=>1, "false_value"=>0),
///     "FieldName_12" =>array("header"=>"Name_L", "type"=>"file",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "target_path"=>"uploads/", "max_file_size"=>"100000|100K|10M|1G", "file_name"=>"File_Name", "host"=>"local|remote"),
///     "FieldName_13" =>array("header"=>"Name_M", "type"=>"link",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "target"=>"_new", "href"=>"http://mydomain.com?act={0}&act={1}&code=ABC"),
///     "FieldName_14" =>array("header"=>"Name_N", "type"=>"foreign_key","req_type"=>"ri", "width"=>"210px", "title"=>"", "readonly"=>"false", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true"),
///     "FieldName_15" =>array("header"=>"",       "type"=>"hidden",     "req_type"=>"st", "default"=>"default_value", "visible"=>"true", "unique"=>"false"),
///     "validator"    =>array("header"=>"Name_O", "type"=>"validator",  "req_type"=>"rv", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "visible"=>"true", "on_js_event"=>"", "for_field"=>"", "validation_type"=>"password|email"),
///     "delimiter"    =>array("inner_html"=>"<br>"),
/// );
/// $dgrid->SetColumnsInEditMode($em_columns);
##  *** set auto-genereted columns in edit mode
//  $auto_column_in_edit_mode = false;
//  $dgrid->SetAutoColumnsInEditMode($auto_column_in_edit_mode);
##  *** set foreign keys for add/edit/details modes (if there are linked tables)
##  *** Ex.: "field_name"=>"CONCAT(field1,','field2) as field3" 
##  *** Ex.: "condition"=>"TableName_1.FieldName > 'a' AND TableName_1.FieldName < 'c'"
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
/// $foreign_keys = array(
///     "ForeignKey_1"=>array("table"=>"TableName_1", "field_key"=>"FieldKey_1", "field_name"=>"FieldName_1", "view_type"=>"dropdownlist(default)|radiobutton|textbox", "radiobuttons_alignment"=>"horizontal|vertical", "condition"=>"", "order_by_field"=>"", "order_type"=>"ASC|DESC", "on_js_event"=>""),
///     "ForeignKey_2"=>array("table"=>"TableName_2", "field_key"=>"FieldKey_2", "field_name"=>"FieldName_2", "view_type"=>"dropdownlist(default)|radiobutton|textbox", "radiobuttons_alignment"=>"horizontal|vertical", "condition"=>"", "order_by_field"=>"", "order_type"=>"ASC|DESC", "on_js_event"=>"")
/// ); 
/// $dgrid->SetForeignKeysEdit($foreign_keys);
##
##
## +---------------------------------------------------------------------------+
## | 8. Bind the DataGrid:                                                     | 
## +---------------------------------------------------------------------------+
##  *** bind the DataGrid and draw it on the screen
//  $dgrid->WriteCssClass();    /* call of this method between HTML <HEAD> elements */
//  $dgrid->Bind();        
//  ob_end_flush();
##
################################################################################   

////////////////////////////////////////////////////////////////////////////////
//
// Not documented:
// -----------------------------------------------------------------------------
// Property : first_field_focus_allowed   = true|false;
//  --//--  : hide_grid_before_serach     = true|false;  /* put it before Bind() method */
//  --//--  : "pre_addition"              => "" and "post_addition"=>"" attributes in view mode for labels and in add/edit/details modes for textboxes, checkboxes
//  --//--  : "autocomplete"              => "on|off" attribute for textboxes in add/edit modes (default - "on")
//  --//--  : mode_after_update           = ""|"edit";
//  --//--  : "on_item_created"           => "function_name" attributes in view/add/edit/details modes for customized work with field value.
//                                          This function must be defined with 1 parameter, that will get fild's data.
//                                          Ex.: function function_name($field_value){ ... return $new_field_value;}
//  --//--  : NoDataFoundText             = ""; displays a text on empty dataset
//
// Method   : ExecuteSQL() 
//            use it after DataSource() method only (after the using DataSource() need to be recalled)
//    		  $dSet = $dgrid->ExecuteSQL("SELECT * FROM tblPresidents WHERE tblPresidents.CountryID = ".$_GET['f_rid']."");
//    		  while($row = $dSet->fetchRow()){
//        	    for($c = 0; ($c < $dSet->numCols()); $c++){ echo $row[$c]." "; }
//        	    echo "<br>";
//    		  }
//  --//--  : SelectSqlItem()
//            $presidents = $dgrid->SelectSqlItem("SELECT COUNT(tblPresidents.presidentID) FROM tblPresidents WHERE tblPresidents.CountryID = ".$_GET['f_rid']."");
//  --//--  : AllowHighlighting(true|false);
//  --//--  : SetJsErrorsDisplayStyle("all"|"each");
//  --//--  : GetNextId();
//  --//--  : GetCurrentId();
//  --//--  : SetHeadersInColumnarLayout("Field Name", "Field Value");
//  --//--  : SetDgMessages("add", "update", "delete");
//
// Feature  : onSubmitMyCheck
//      	<script type='text/javascript'>
//            function unique_prefix_onSubmitMyCheck(){
//              return true;
//      	}	
//      	</script>
//  --//--  : "on_js_event"=>"onchange='formAction(\"\", \"\", \"".$dgrid->uniquePrefix."\", \"".$dgrid->HTTP_URL."\", \"".$_SERVER['QUERY_STRING']."\")'" 
//  --//--  : Bind(true|false) - draw DataGrid on the screen on not
//      
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//
// Tricks:
// -----------------------------------------------------------------------------
// 1. Set default value, that disappears on focus:
//      "default"=>"http://www.website.com", "on_js_event"=>"onBlur='if(this.value == \"\") this.value = \"http://www.website.com\"; this.style.color=\"#f68d6f\";' onClick='if(this.value==\"http://www.website.com\") this.value=\"\"; this.style.color=\"#000000\";'",
//
// 2. Set uniquie value for uploading image:
//     a) "file_name"=>"img_".((isset($_GET['prfx_mode']) && ($_GET['prfx_mode'] == "add")) ? $dgrid->GetNextId() : $dgrid->GetCurrentId())
//     b) "file_name"=>"img_".((isset($_GET['prfx_mode']) && ($_GET['prfx_mode'] == "add")) ? $dgrid->GetRandomString("10") : $dgrid->GetCurrentId())
//
// 3. Make auto-submition for filtering fileds:
//      "on_js_event"=>"onchange='document.getElementById(\"...prefix..._ff_onSUBMIT_FILTER\").click();'"
//
// 4. Make a field text colored according to condition (in SQL statement):
//      if (product='flooring', CONCAT('<SPAN style=\"background-color:yellow\">',product,'</SPAN>'),product) as ProductColored,
//
// 5. Change the field's data on fly (for "on_item_created" field's attribute):
//      function setColor($field_value){
//        if(strlen($field_value) > 5){
//            return "<font color='red'>".$field_value."</font>";
//        }else{
//            return "<font color='blue'>".$field_value."</font>";        
//        }
//      }
//
// 6. Change the field's type on fly (for "on_item_created" field's attribute):
//      function setColor($field_value, $field_property_type){
//        if(strlen($field_value) > 5){
//            return "<font color='red'>".$field_value."</font>";
//        }else{
//            $field_property_type = "linktoview";
//            return "<font color='blue'>".$field_value."</font>";        
//        }
//      }
//
// 8. Customized filtering: write filter field with empty table name and field: (..."table"=>"", "field"=>"xxx",...)
//    Then use $my_field = isset($_GET['prefix__ff__xxx']) ? $_GET['prefix__ff__xxx'] : "";
//    Use $my_field in SQL SELECT for your own filtering
//
////////////////////////////////////////////////////////////////////////////////


Class DataGrid
{
    //==========================================================================
    // Data Members
    //==========================================================================
    // unique prefixes ---------------------------------------------------------
    public $uniquePrefix;
    public $unique_random_prefix;

    // directory ---------------------------------------------------------------
    public $directory;

    // language ----------------------------------------------------------------
    public $lang_name;
    public $lang;

    // caption -----------------------------------------------------------------
    public $caption;

    // rows and columns data members -------------------------------------------
    public $rows;
    public $row_lower;
    public $row_upper;
    public $columns;            
    public $col_lower;
    public $col_upper;

    // http get vars -----------------------------------------------------------    
    public $http;
    public $port;
    public $server_name;
    public $HTTP_URL;
    public $http_get_vars;
    public $another_datagrids;

    // data source -------------------------------------------------------------
    public $db_handler;
    public $sql;
    public $sql_view;
    public $sql_group_by;
    public $data_set;
    
    // signs -------------------------------------------------------------------
    public $amp;
    public $nbsp;
    
    // encoding & direction ----------------------------------------------------
    public $encoding;
    public $collation;
    public $direction;

    // layout style ------------------------------------------------------------
    public $layouts;  
    public $layout_type;

    // templates ---------------------------------------------------------------
    public $templates;
    
    // paging variables --------------------------------------------------------
    public $pages_total;
    public $page_current;
    public $default_page_size;
    public $req_page_size;
    public $paging_allowed;
    public $rows_numeration;
    public $numeration_sign;           
    public $lower_paging;
    public $upper_paging;
    public $pages_array;
    public $first_arrow;
    public $previous_arrow;
    public $next_arrow;
    public $last_arrow;    
    public $limit_start;
    public $limit_size;
    public $rows_total;

    // sorting variables -------------------------------------------------------
    public $sort_field;
    public $sort_type;
    public $default_sort_field;    
    public $default_sort_type;    
    public $sorting_allowed;
    public $sql_sort;

    // filtering variables -----------------------------------------------------
    public $filtering_allowed;
    public $show_search_type;
    public $filter_fields;
    public $hide_display;

    // columns style parameters ------------------------------------------------            
    public $wrap;

    // css style ---------------------------------------------------------------            
    public $row_highlighting_allowed;
    public $css_class;
    public $rowColor;
    protected $is_css_class_written;

    // table style parameters --------------------------------------------------                        
    public $tblAlign;
    public $tblWidth;
    public $tblBorder;
    public $tblBorderColor;
    public $tblCellSpacing;
    public $tblCellPadding;
    
    // datagrid modes ----------------------------------------------------------                        
    public $modes;
    public $mode_after_update;
    public $mode;
    protected $rid;
    public $rids;
    public $tbl_name;
    public $primary_key;
    public $condition;
    public $foreign_keys_array;    
    public $columns_view_mode;
    public $columns_edit_mode;
    public $sorted_columns;

    // printing & exporting ----------------------------------------------------                        
    public $printing_allowed;
    public $exporting_allowed;
    public $exporting_directory;
    protected $exporting_types;

    // debug mode --------------------------------------------------------------                        
    public $debug;
    public $start_time;
    public $end_time;

    // message -----------------------------------------------------------------                        
    public $act_msg;
    public $messaging;
    public $is_error;
    public $errors;
    public $is_warning;
    public $warnings;
    public $dg_messages;
    public $NoDataFoundText;

    // browser & system types --------------------------------------------------
    public $platform;
    public $browser_name;
    public $browser_version;
    
    // scrolling ---------------------------------------------------------------
    public $scrolling_option;
    public $scrolling_width;
    public $scrolling_height;

    // header names ------------------------------------------------------------
    public $field_header;
    public $field_value_header;

    // hide --------------------------------------------------------------------
    public $hide_grid_before_serach;

    // summarize ---------------------------------------------------------------
    public $summarize_columns;
    
    // multirow ----------------------------------------------------------------
    public $multirow_allowed;
    public $multi_rows;
    public $multirow_operations_array;

    // first field focus -------------------------------------------------------
    public $first_field_focus_allowed;

    // javascript errors display style -----------------------------------------
    public $js_validation_errors;
    
    //==========================================================================
    // PUBLIC MEMBER FUNCTIONS 
    //==========================================================================
    //--------------------------------------------------------------------------
    // Default class constructor 
    //--------------------------------------------------------------------------
    function __construct($debug_mode = false, $messaging = true, $unique_prefix = "", $datagrid_dir = "datagrid/"){        

        $this->debug = (($debug_mode == true) || ($debug_mode == "true")) ? true : false ;
        
        // start calculating running time of a script
        $this->start_time = 0;
        $this->end_time = 0;
        if($this->debug){
            $this->start_time = $this->GetFormattedMicrotime();
        }        

        // unique prefixes -----------------------------------------------------
        $this->SetUniquePrefix($unique_prefix);
        
        // directory -----------------------------------------------------------
        $this->directory = $datagrid_dir;

        // language ------------------------------------------------------------
        $this->lang_name = "en";
        $this->lang = array();
        $this->lang['total'] = "Total";
        $this->lang['wrong_parameter_error'] = "Wrong parameter in [<b>_FIELD_</b>]: _VALUE_";        

        // caption -------------------------------------------------------------        
        $this->caption = "";

        // rows and columns data members ---------------------------------------
        $this->http = $this->GetProtocol();
        $this->port = $this->GetPort();
        $this->server_name = $this->GetServerName();
        $this->HTTP_URL = str_replace("///", "//", $this->http.$this->server_name.$this->port.$_SERVER['PHP_SELF']);

        // http get vars -------------------------------------------------------        
        $this->http_get_vars = "";
        $this->another_datagrids = "";

        // css style  ----------------------------------------------------------        
        $this->row_highlighting_allowed = true;
        $this->css_class = "default";
        $this->rowColor = array();
        $this->is_css_class_written = false;

        // signs ---------------------------------------------------------------
        $this->amp = "&amp;";        
        $this->nbsp = ""; //&nbsp;       
        
        $this->rows = 0;
        $this->row_lower = 0;
        $this->row_upper = 0;
        $this->columns = 0;            
        $this->col_lower = 0;
        $this->col_upper = 0;

        // encoding & direction ------------------------------------------------
        $this->encoding = "utf8";
        $this->collation = "utf8_unicode_ci";
        $this->direction = "ltr";
        
        $this->layouts['view']   = "0";
        $this->layouts['edit']   = "1";
        $this->layouts['filter'] = "1";
        $this->layouts['show']   = "1";
        $this->layout_type = "view";
        
        // templates -----------------------------------------------------------
        $this->templates['view'] = "";
        $this->templates['edit'] = "";
        $this->templates['show'] = "";
        
        $this->pages_total = 0;
        $this->page_current = 0;
        $this->pages_array = array("10"=>"10", "25"=>"25", "50"=>"50", "100"=>"100", "250"=>"250", "500"=>"500", "1000"=>"1000");
        $this->first_arrow    = "|&lt;&lt;";
        $this->previous_arrow = "&lt;&lt;";
        $this->next_arrow     = "&gt;&gt;";
        $this->last_arrow     = "&gt;&gt;|";
        $this->default_page_size = 10;
        $this->req_page_size = 10;                
        $this->paging_allowed = true;
        $this->rows_numeration = false;
        $this->numeration_sign = "N #";       
        $this->lower_paging['results'] = false;
        $this->lower_paging['results_align'] = "left";
        $this->lower_paging['pages'] = false;        
        $this->lower_paging['pages_align'] = "center";
        $this->lower_paging['page_size'] = false;
        $this->lower_paging['page_size_align'] = "right";
        $this->upper_paging['results'] = false;
        $this->upper_paging['results_align'] = "left";
        $this->upper_paging['pages'] = false;        
        $this->upper_paging['pages_align'] = "center";
        $this->upper_paging['page_size'] = false;
        $this->upper_paging['page_size_align'] = "right";
        $this->limit_start = 0;
        $this->limit_size = $this->req_page_size;
        $this->rows_total = 0;
        
        $this->sort_field = "";
        $this->sort_field_by = "";
        $this->sort_field_type = "";
        $this->sort_type = "";
        $this->default_sort_field = array();
        $this->default_sort_type = array();
        $this->sorting_allowed = true;
        $this->sql_view = "";
        $this->sql_group_by = "";
        $this->sql = "";
        $this->sql_sort = "";
        
        $this->filtering_allowed = false;
        $this->show_search_type = true;        
        $this->filter_fields = array();
        $this->hide_display = "";
        
        $this->tblAlign['view'] = "center";         $this->tblAlign['edit'] = "center";         $this->tblAlign['details'] = "center";
        $this->tblWidth['view'] = "90%";            $this->tblWidth['edit'] = "70%";            $this->tblWidth['details'] = "60%";
        $this->tblBorder['view'] = "1";             $this->tblBorder['edit'] = "1";             $this->tblBorder['details'] = "1";
        $this->tblBorderColor['view'] = "#000000";  $this->tblBorderColor['edit'] = "#000000";  $this->tblBorderColor['details'] = "#000000";
        $this->tblCellSpacing['view'] = "0";        $this->tblCellSpacing['edit'] = "0";        $this->tblCellSpacing['details'] = "0";
        $this->tblCellPadding['view'] = "0";        $this->tblCellPadding['edit'] = "0";        $this->tblCellPadding['details'] = "0";
        
        // datagrid modes ------------------------------------------------------
        $this->modes["add"]     = array("view"=>true, "edit"=>false, "type"=>"link", "show_add_button"=>"inside");
        $this->modes["edit"]    = array("view"=>true, "edit"=>true,  "type"=>"link", "byFieldValue"=>"");
        $this->modes["cancel"]  = array("view"=>true, "edit"=>true,  "type"=>"link");
        $this->modes["details"] = array("view"=>true, "edit"=>false, "type"=>"link");
        $this->modes["delete"]  = array("view"=>true, "edit"=>true,  "type"=>"image");            

        $this->mode = "view";
        $this->mode_after_update = "";
        $this->rid = "";
        $this->rids = "";
        $this->tbl_name ="";
        $this->primary_key = 0;
        $this->condition = "";

        $this->foreign_keys_array = array();
        
        $this->columns_view_mode = array();
        $this->columns_edit_mode = array();
        $this->sorted_columns = array();
              
        $this->printing_allowed = true;
        $this->exporting_allowed = false;
        $this->exporting_directory = "";
        $this->exporting_types = array("excel"=>"true", "pdf"=>"true", "xml"=>"true");
        
        $this->wrap = "wrap";

        // scrolling -----------------------------------------------------------
        $this->scrolling_option = false;
        $this->scrolling_width = "90%";
        $this->scrolling_height = "100%";

        // header names --------------------------------------------------------
        $this->field_header = "";
        $this->field_value_header = "";

        // hide ----------------------------------------------------------------
        $this->hide_grid_before_serach = false;
        
        $this->summarize_columns = array();
        
        $this->multirow_allowed = false;
        $this->multi_rows = 0;
        $this->multirow_operations_array = array();        
        $this->multirow_operations_array['delete'] = array("view"=>true);
        $this->multirow_operations_array['details'] = array("view"=>true);

        $this->first_field_focus_allowed = false;

        // message -------------------------------------------------------------
        $this->act_msg = "";

        if($this->debug) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
        $this->messaging = (($messaging == true) || ($messaging == "true")) ? true : false ;        
        $this->is_error = false;
        $this->errors = array();
        $this->is_warning = false;
        $this->warnings = array();
        $this->dg_messages = array();
        $this->dg_messages['add'] = "";
        $this->dg_messages['update'] = "";
        $this->dg_messages['delete'] = "";

        // javascript errors display style -------------------------------------
        $this->js_validation_errors = "true";

        // set browser definitions  
        $this->SetBrowserDefinitions();
    }

    //--------------------------------------------------------------------------
    // Class destructor
    //--------------------------------------------------------------------------    
    function __destruct()
    {
		// echo 'this object has been destroyed';
    }

    //--------------------------------------------------------------------------
    // Set encoding
    //--------------------------------------------------------------------------
    function SetEncoding($dg_encoding = "", $dg_collation = ""){
        $this->encoding = ($dg_encoding != "") ? $dg_encoding : $this->encoding;
        $this->collation = ($dg_collation != "") ? $dg_collation : $this->collation;
    }

    //--------------------------------------------------------------------------
    // Set data source 
    //--------------------------------------------------------------------------
    function DataSource($db_handl, $sql = "", $start_order = "", $start_order_type = ""){        
        // clear sql statment
        $sql = str_replace("\n", " ", $sql);    // new row
        $sql = str_replace("\t", " ", $sql);    // tabulation
        $sql = str_replace(chr(13), " ", $sql); // CR sign
        $sql = str_replace(chr(10), " ", $sql); // LF sign
        $sql = str_replace(";", "", $sql);       
        
        // get preliminary Primary Key
        $p_key = explode(" ", $sql);
        $p_key = str_replace(",", "", $p_key[1]);
        $p_key = explode(".", $p_key);
        $this->primary_key = $p_key[count($p_key)-1];
        
        $req_sort_field = $this->GetVariable('sort_field');
        $req_sort_field_by = $this->GetVariable('sort_field_by');
        $req_sort_field_type = $this->GetVariable('sort_field_type');
        $sort_field = ($req_sort_field_by != "") ? $req_sort_field_by : $req_sort_field ;
        $req_sort_type = $this->GetVariable('sort_type');
        $this->db_handler = $db_handl;       
        $this->db_handler->setFetchMode(DB_FETCHMODE_ORDERED);
        $numeric_sort = false;

        // handle SELECT SQL statement
        $this->sql_view = $sql;         
        if($this->LastSubStrOccurence($this->sql_view, "from ") < $this->LastSubStrOccurence($this->sql_view, "where ")){
            // handle SELECT statment with sub-SELECTs and SELECT without WHERE
            $ind = strpos(strtolower($this->sql_view), "group by");
            if($ind){
                $prefix = substr($sql, 0, $ind); 
                $suffix = substr($sql, $ind);                 
                $this->sql_view = $prefix." ";
                $this->sql_group_by = $suffix;                
            }else{
                $this->sql_view .= " WHERE 1=1 ";
            }            
        }else if($this->LastSubStrOccurence($this->sql_view, "where ") == ""){
            $this->sql_view .= " WHERE 1=1 ";
        }else{
            $ind = strpos(strtolower($this->sql_view), "group by");
            if($ind){                   
                $prefix = substr($sql, 0, $ind); 
                $suffix = substr($sql, $ind);                 
                $this->sql_view = $prefix." ";
                $this->sql_group_by = $suffix;
            }
        }
        $this->sql = $this->sql_view.$this->sql_group_by;
        
        // set default order
        if($start_order != ""){
            $default_sort_field = explode(",", $start_order);
            $default_sort_type = explode(",", $start_order_type);
            for($ind=0; $ind < count($default_sort_field); $ind++){
                $this->default_sort_field[$ind] = trim($default_sort_field[$ind]);
                if(isset($default_sort_type[$ind])){
                    if((strtolower(trim($default_sort_type[$ind])) == "asc") || (strtolower(trim($default_sort_type[$ind])) == "desc")){
                        $this->default_sort_type[$ind] = trim($default_sort_type[$ind]);
                    }else{
                        $this->default_sort_type[$ind] = "ASC";
                        $this->AddWarning('$default_order_type', $start_order_type);
                    }
                }else{
                    $this->default_sort_type[$ind] = "ASC";
                }
            }
        }else{
            $this->default_sort_field[0] = "1";
            $this->default_sort_type[0] = "ASC";
        }
        // create ORDER BY part of sql statment
        if($req_sort_field){            
            if(!substr_count($this->sql, "ORDER BY")){
                if($req_sort_field_type == "numeric"){
                    $this->sql_sort = " ORDER BY ABS(".$sort_field.") ".$req_sort_type;     
                    $numeric_sort = true;
                }else{
                    $this->sql_sort = " ORDER BY ".$sort_field." ".$req_sort_type;     
                }                
            }else{
              $this->sql_sort = " , ".$sort_field." ".$req_sort_type;
            }
        }else if($start_order != ""){
            $this->sql_sort = " ORDER BY ".$this->GetOrderByList();
        }else{
            $this->sql_sort = " ORDER BY 1 ASC";            
        }
        
        $this->GetDataSet($this->sql_sort, "", "", $sort_field, $numeric_sort);
        
        // check if the preliminary key is a Primary Key
        if(strtolower($this->GetFieldInfo(0, 'type', 1)) != "int"){
            $this->AddWarning($this->primary_key, "Check this field carefully, it may be not a Primary Key!");
        }
    }    

    //--------------------------------------------------------------------------
    // Set Language
    //--------------------------------------------------------------------------
    function SetInterfaceLang($lang_name = ""){
        $default_language = false;
        if(($lang_name != "") && (strlen($lang_name) == 2)){ $this->lang_name = $lang_name; }
        if (file_exists($this->directory.'languages/'.$this->lang_name.'.php')) {            
            include_once($this->directory.'languages/'.$this->lang_name.'.php');
            if(function_exists('setLanguage')){
                $this->lang = setLanguage();
            }else{
                if($this->debug){ echo "<label class='".$this->css_class."_class_error_message no_print'>Your language interface option is turned on, but the system was failed to open correctly stream: <b>'".$this->directory."languages/lang.php'</b>. <br>The structure of the file is corrupted or invalid. Please check it or return the language option to default value: <b>'en'</b>!</label><br>"; }
                $default_language = true;
            }
    	}else{
            if((strtolower($lang_name) != "en") && ($this->debug)){
                echo "<label class='".$this->css_class."_class_error_message no_print'>Your language interface option is turned on, but the system was failed to open stream: <b>'".$this->directory."languages/".$lang_name.".php'</b>. <br>No such file or directory. Please check it or return the language option to default value: <b>'en'</b>!</label><br>";
            }
            $default_language = true;                    
    	}
               
        if($default_language){
            $this->lang['='] = "=";  // "equal"; 
            $this->lang['>'] = ">";  // "bigger"; 
            $this->lang['<'] = "<";  // "smaller";            
            $this->lang['add'] = "Add";
            $this->lang['add_new'] = "+ Add New";
            $this->lang['add_new_record'] = "Add new record"; 
            $this->lang['add_new_record_blocked'] = "Security check: attempt of adding a new record! Check your settings, the operation is not allowed!";
            $this->lang['adding_operation_completed'] = "The adding operation completed successfully!";
            $this->lang['adding_operation_uncompleted'] = "The adding operation uncompleted!";
            $this->lang['and'] = "and";
            $this->lang['any'] = "any";                         
            $this->lang['ascending'] = "Ascending"; 
            $this->lang['back'] = "Back";
            $this->lang['cancel'] = "Cancel";
            $this->lang['cancel_creating_new_record'] = "Are you sure you want to cancel creating new record?";
            $this->lang['check_all'] = "Check All";
            $this->lang['clear'] = "Clear";                
            $this->lang['create'] = "Create";
            $this->lang['create_new_record'] = "Create new record";            
            $this->lang['current'] = "current";
            $this->lang['delete'] = "Delete";
            $this->lang['delete_record'] = "Delete record";
            $this->lang['delete_record_blocked'] = "Security check: attempt of deleting a record! Check your settings, the operation is not allowed!";
            $this->lang['delete_selected'] = "Delete selected";
            $this->lang['delete_selected_records'] = "Are you sure you want to delete the selected records?";
            $this->lang['delete_this_record'] = "Are you sure you want to delete this record?";                             
            $this->lang['deleting_operation_completed'] = "The deleting operation completed successfully!";
            $this->lang['deleting_operation_uncompleted'] = "The deleting operation uncompleted!";                                    
            $this->lang['descending'] = "Descending";
            $this->lang['details'] = "Details";
            $this->lang['details_selected'] = "View selected";                                    
            $this->lang['edit'] = "Edit";                
            $this->lang['edit_selected'] = "Edit selected";
            $this->lang['edit_record'] = "Edit record"; 
            $this->lang['edit_selected_records'] = "Are you sure you want to edit the selected records?";               
            $this->lang['errors'] = "Errors";            
            $this->lang['export_to_excel'] = "Export to Excel";
            $this->lang['export_to_pdf'] = "Export to PDF";
            $this->lang['export_to_xml'] = "Export to XML";
            $this->lang['field'] = "Field";
            $this->lang['field_value'] = "Field Value";
            $this->lang['file_find_error'] = "Cannot find file: <b>_FILE_</b>. <br>Check if this file exists and you use a correct path!";                                                
            $this->lang['file_opening_error'] = "Cannot open a file. Check your permissions.";            
            $this->lang['file_writing_error'] = "Cannot write to file. Check writing permissions.";
            $this->lang['file_invalid file_size'] = "Invalid file size: ";
            $this->lang['file_uploading_error'] = "There was an error while uploading, please try again!";
            $this->lang['file_deleting_error'] = "There was an error while deleting!";
            $this->lang['first'] = "first";
            $this->lang['handle_selected_records'] = "Are you sure you want to handle the selected records?";
            $this->lang['hide_search'] = "Hide Search";            
            $this->lang['last'] = "last";
            $this->lang['like'] = "like";
            $this->lang['like%'] = "like%";  // "begins with"; 
            $this->lang['%like'] = "%like";  // "ends with";
            $this->lang['%like%'] = "%like%";  // "ends with";
            $this->lang['loading_data'] = "loading data...";            
            $this->lang['max'] = "max";                            
            $this->lang['next'] = "next";
            $this->lang['no'] = "No";
            $this->lang['no_data_found'] = "No data found";
            $this->lang['no_data_found_error'] = "No data found! Please, check carefully your code syntax!<br>It may be case sensitive or there are some unexpected symbols.";                                
            $this->lang['no_image'] = "No Image";
            $this->lang['not_like'] = "not like";
            $this->lang['of'] = "of";
            $this->lang['operation_was_already_done'] = "The operation was already completed! You cannot retry it again.";            
            $this->lang['or'] = "or";            
            $this->lang['pages'] = "Pages";                    
            $this->lang['page_size'] = "Page size";
            $this->lang['previous'] = "previous";
            $this->lang['printable_view'] = "Printable View";
            $this->lang['print_now'] = "Print Now";            
            $this->lang['print_now_title'] = "Click here to print this page";
            $this->lang['record_n'] = "Record # ";
            $this->lang['refresh_page'] = "Refresh Page";
            $this->lang['remove'] = "Remove";
            $this->lang['reset'] = "Reset";                        
            $this->lang['results'] = "Results";
            $this->lang['required_fields_msg'] = "<font color='#cd0000'>*</font> Items marked with an asterisk are required";            
            $this->lang['search'] = "Search";
            $this->lang['search_d'] = "Search"; // (description)
            $this->lang['search_type'] = "Search type";
            $this->lang['select'] = "select";
            $this->lang['set_date'] = "Set date";
            $this->lang['sort'] = "Sort";
            $this->lang['total'] = "Total";
            $this->lang['turn_on_debug_mode'] = "For more information, turn on debug mode.";
            $this->lang['uncheck_all'] = "Uncheck All";
            $this->lang['unhide_search'] = "Unhide Search";
            $this->lang['unique_field_error'] = "The field _FIELD_ allows only unique values - please reenter!";
            $this->lang['update'] = "Update";
            $this->lang['update_record'] = "Update record";
            $this->lang['update_record_blocked'] = "Security check: attempt of updating a record! Check your settings, the operation is not allowed!";
            $this->lang['updating_operation_completed'] = "The updating operation completed successfully!";
            $this->lang['updating_operation_uncompleted'] = "The updating operation uncompleted!";                                    
            $this->lang['upload'] = "Upload";            
            $this->lang['view'] = "View";
            $this->lang['view_details'] = "View details";
            $this->lang['warnings'] = "Warnings";
            $this->lang['with_selected'] = "With selected";
            $this->lang['wrong_field_name'] = "Wrong field name";
            $this->lang['wrong_parameter_error'] = "Wrong parameter in [<b>_FIELD_</b>]: _VALUE_";
            $this->lang['yes'] = "Yes";
        }
    }

    //--------------------------------------------------------------------------
    // Set direction
    //--------------------------------------------------------------------------
    function SetDirection($direction = "ltr"){
        $this->direction = $direction;
    }

    //--------------------------------------------------------------------------
    // Set layouts
    //--------------------------------------------------------------------------
    function SetLayouts($layouts = ""){
        $this->layouts['view']   = (isset($layouts['view'])) ? $layouts['view'] : "0";
        $this->layouts['edit']   = (isset($layouts['edit'])) ? $layouts['edit'] : "0";
        $this->layouts['show']   = (isset($layouts['details'])) ? $layouts['details'] : "1";
        $this->layouts['filter'] = (isset($layouts['filter'])) ? $layouts['filter'] : "0";        
    }

    //--------------------------------------------------------------------------
    // Set templates for customized layouts
    //--------------------------------------------------------------------------
    function SetTemplates($view = "", $add_edit = "", $details = ""){
        $this->templates['view'] = $view;
        $this->templates['edit'] = $add_edit;
        $this->templates['show'] = $details;
    }

    //--------------------------------------------------------------------------
    // Set mode add/edit/cancel/delete
    //--------------------------------------------------------------------------
    function SetModes($parameters){
        $this->modes = array();
        if(is_array($parameters)){
            foreach($parameters as $modeName => $modeValue){
                $this->modes[$modeName] = $modeValue;
            }            
        }
        $this->mode = "view";
    }  	    

    //--------------------------------------------------------------------------
    // Allow scrolling settings
    //--------------------------------------------------------------------------
    function AllowScrollingSettings($scrolling_option = false){
        $this->scrolling_option = (($scrolling_option == true) || ($scrolling_option == "true")) ? true : false ;        
    }

    //--------------------------------------------------------------------------
    // Set scrolling settings
    //--------------------------------------------------------------------------
    function setScrollingSettings($width="", $height=""){
        if($width != "") $this->scrolling_width = $width;
        if($height != "") $this->scrolling_height = $height;
    }

    //--------------------------------------------------------------------------
    // Allow multirow operations
    //--------------------------------------------------------------------------
    function AllowMultirowOperations($multirow_option = false){
        $this->multirow_allowed = (($multirow_option == true) || ($multirow_option == "true")) ? true : false ;
    }

    //--------------------------------------------------------------------------
    // Set multirow operations
    //--------------------------------------------------------------------------    
    function SetMultirowOperations($multirow_operations = ""){
        if(is_array($multirow_operations)){                
            foreach($multirow_operations as $fldName => $fldValue){
                $this->multirow_operations_array[$fldName] = $fldValue;
            }
        }        
    }

    //--------------------------------------------------------------------------
    // Set css class
    //--------------------------------------------------------------------------
    function SetCssClass($class = "default"){        
        $this->css_class = $class;
    }
    
    //--------------------------------------------------------------------------
    // Set Http Get Vars
    //--------------------------------------------------------------------------
    function SetHttpGetVars($http_get_vars = ""){
        $this->http_get_vars = $http_get_vars;
    }

    //--------------------------------------------------------------------------
    // Set Other DataGrids
    //--------------------------------------------------------------------------
    function SetAnotherDatagrids($another_datagrids = ""){
        $this->another_datagrids = $another_datagrids;
    }

    //--------------------------------------------------------------------------
    // Set title for datagrid
    //--------------------------------------------------------------------------
    function SetCaption($dg_caption = ""){
        $this->caption = $dg_caption;
    }

    //--------------------------------------------------------------------------
    // Allow exporting functions
    //--------------------------------------------------------------------------
    function AllowPrinting  ($option = true) { $this->printing_allowed  = (($option == true) || ($option == "true")) ? true : false ; }    
    function AllowExporting ($option = true, $exporting_directory = "") { $this->exporting_allowed = (($option == true) || ($option == "true")) ? true : false ; $this->exporting_directory = $exporting_directory; }
    function AllowExportingTypes($exporting_types = ""){
        if(is_array($exporting_types)){
            $this->exporting_types["excel"] = (isset($exporting_types["excel"]) && (($exporting_types["excel"] == true) || ($exporting_types["excel"] == "true"))) ?  true : false;
            $this->exporting_types["pdf"]   = (isset($exporting_types["pdf"]) && (($exporting_types["pdf"] == true) || ($exporting_types["pdf"] == "true"))) ?  true : false;
            $this->exporting_types["xml"]   = (isset($exporting_types["xml"]) && (($exporting_types["xml"] == true) || ($exporting_types["xml"] == "true"))) ?  true : false;
        }    
    }

    //--------------------------------------------------------------------------
    // Set sorting settings
    //--------------------------------------------------------------------------    
    function AllowSorting   ($option = true) { $this->sorting_allowed   = (($option == true) || ($option == "true")) ? true : false ; }    

    //--------------------------------------------------------------------------
    // Set paging settings
    //--------------------------------------------------------------------------    
    function AllowPaging($option = true, $rows_numeration = false, $numeration_sign = "N #"){
        $this->paging_allowed = (($option == true) || ($option == "true")) ? true : false ;
        $this->rows_numeration = $rows_numeration;
        $this->numeration_sign = $numeration_sign;       
    }

    function SetPagingSettings($lower=false, $upper=false, $pages_array=false, $default_page_size="", $paging_arrows=""){
        if(($lower == true) || ($lower == "true")){
            if($lower['results']) $this->lower_paging['results'] = $lower['results'];
            if($lower['results_align']) $this->lower_paging['results_align'] = $lower['results_align'];
            if($lower['pages']) $this->lower_paging['pages'] = $lower['pages'];            
            if($lower['pages_align']) $this->lower_paging['pages_align'] = $lower['pages_align'];
            if($lower['page_size']) $this->lower_paging['page_size'] = $lower['page_size'];
            if($lower['page_size_align']) $this->lower_paging['page_size_align'] = $lower['page_size_align'];
        }
        if(($upper == true) || ($upper == "true")){
            if($upper['results']) $this->upper_paging['results'] = $upper['results'];
            if($upper['results_align']) $this->upper_paging['results_align'] = $upper['results_align'];
            if($upper['pages']) $this->upper_paging['pages'] = $upper['pages'];            
            if($upper['pages_align']) $this->upper_paging['pages_align'] = $upper['pages_align'];
            if($upper['page_size']) $this->upper_paging['page_size'] = $upper['page_size'];
            if($upper['page_size_align']) $this->upper_paging['page_size_align'] = $upper['page_size_align'];
        }
        if($pages_array){
            if(is_array($pages_array) && (count($pages_array) > 0)){
                $first_key = "";
                foreach($pages_array as $key => $val){
                    if($first_key == "") {$first_key = $key;};
                    if (intval($pages_array[$key]) == 0) $pages_array[$key] = 1;
                }
                $this->pages_array = $pages_array;
                $this->req_page_size = ($pages_array[$first_key] > 0) ? $pages_array[$first_key] : $this->req_page_size;                
            }
        }
        if(($default_page_size != "") && ($default_page_size > 0)) { $this->default_page_size = $this->req_page_size = $default_page_size; }
    
        if($paging_arrows != ""){
            if(is_array($paging_arrows) && (count($paging_arrows) > 0)){
                $this->first_arrow    = (isset($paging_arrows["first"])) ? $paging_arrows["first"] : $this->first_arrow;
                $this->previous_arrow = (isset($paging_arrows["previous"])) ? $paging_arrows["previous"] : $this->previous_arrow;
                $this->next_arrow     = (isset($paging_arrows["next"])) ? $paging_arrows["next"] : $this->next_arrow;
                $this->last_arrow     = (isset($paging_arrows["last"])) ? $paging_arrows["last"] : $this->last_arrow;
            }
        }        
    }

    //--------------------------------------------------------------------------
    // Set filtering settings
    //--------------------------------------------------------------------------
    function AllowFiltering ($option = false, $show_search_type = "true"){
        $this->filtering_allowed = (($option == true) || ($option == "true")) ? true : false ;
        $this->show_search_type  = (($show_search_type == true) || ($show_search_type == "true")) ? true : false ;
    }
    
    function SetFieldsFiltering($filter_fields_array = ""){
        $req_selSearchType = $this->GetVariable('_ff_selSearchType');
        $req_onSUBMIT_FILTER = $this->GetVariable('_ff_onSUBMIT_FILTER');
        
        if(is_array($filter_fields_array)){
            foreach($filter_fields_array as $fldName => $fldValue){
                $this->filter_fields[$fldName] = $fldValue;
            }                   
            if($req_onSUBMIT_FILTER != ""){
                $search_type_start = "AND";
                if($req_selSearchType == "0"){
                    $search_type = "AND";                    
                }else{
                    $search_type = "OR";
                }
                if(!substr_count(strtolower($this->sql_view), "where") && !substr_count(strtolower($this->sql_view), "having")) $this->sql_view .= " WHERE 1=1 ";
                foreach($filter_fields_array as $fldName => $fldValue){
                    $table_field_name = "";                    
                    $fldValue_fields = str_replace(" ", "", $fldValue['field']);
                    $fldValue_fields = explode(",", $fldValue_fields);
                    
                    foreach($fldValue_fields as $fldValue_field){
                        // ignore filter field if there was empty 'table' or 'field' attribute
                        if((trim($fldValue['table']) == "") || (trim($fldValue['field']) == "")) { continue; }
                        $table_field_name = $fldValue['table']."_".$fldValue_field;
                        if(isset($_REQUEST[$this->uniquePrefix."_ff_".$table_field_name]) && ($_REQUEST[$this->uniquePrefix."_ff_".$table_field_name] !== "")){                        
                            $filter_field_operator =  $table_field_name."_operator";                        
                            if(isset($fldValue['case_sensitive']) && ($fldValue['case_sensitive'] != true)){
                                $fldTableField = $this->GetLcaseFooByDbType()."(".(($fldValue['table'] != "") ? $fldValue['table']."." : "" ).$fldValue_field.")";
                                $fldTableFieldName = $this->StrToLower($_REQUEST[$this->uniquePrefix."_ff_".$table_field_name]);
                            }else{
                                $fldTableField = (($fldValue['table'] != "") ? $fldValue['table']."." : "" ).$fldValue_field;                            
                                $fldTableFieldName = $_REQUEST[$this->uniquePrefix."_ff_".$table_field_name];
                            }
                            if(isset($fldValue['comparison_type']) && (strtolower($fldValue['comparison_type']) == "numeric")){
                                $left_geresh =""; 
                            }else{
                                $left_geresh ="'"; 
                            }                            
                                
                            // split by separated words if user splitted them by ","
                            $splitted_fldTableFieldName = split(",",$fldTableFieldName);
                            $separated_word_count = 0;
                            if(count($splitted_fldTableFieldName) > 0) $this->sql_view .= " ".$search_type_start." ( ";
                            foreach($splitted_fldTableFieldName as $separated_word){
                                $separated_word = trim($separated_word);                                                                
                                if($separated_word_count > 0 ){ $this->sql_view .= " OR "; }
                                $requested_filter_field_operator = isset($_REQUEST[$this->uniquePrefix."_ff_".$filter_field_operator]) ? $_REQUEST[$this->uniquePrefix."_ff_".$filter_field_operator] : "";
                                if($requested_filter_field_operator != ""){                                
                                    if(isset($fldValue['comparison_type']) && (strtolower($fldValue['comparison_type']) == "binary")) $comparison_type = "BINARY";
                                    else $comparison_type ="";
                                    
                                    // To be sure SQL understands our quotation
                                    if(substr_count($requested_filter_field_operator, "like") > 0){
                                        $separated_word = str_replace('\"', mysql_real_escape_string('\\\"'), $separated_word); // double quotation mark 
                                        $separated_word = str_replace("\'", mysql_real_escape_string("\\\'"), $separated_word); // single quotation mark
                                    }else{
                                        $separated_word = str_replace('\"', mysql_real_escape_string('\\"'), $separated_word); // double quotation mark 
                                        $separated_word = str_replace("\'", mysql_real_escape_string("\\'"), $separated_word); // single quotation mark                                        
                                    }
                                    
                                    if($requested_filter_field_operator == "like"){
                                        $this->sql_view .= " $fldTableField ".$requested_filter_field_operator." ".$comparison_type." '%".$separated_word."%'";
                                    }else if($requested_filter_field_operator == "like%"){
                                        $this->sql_view .= " $fldTableField ".substr($requested_filter_field_operator, 0, 4)." ".$comparison_type." '".$separated_word."%'";
                                    }else if($requested_filter_field_operator == "%like"){
                                        $this->sql_view .= " $fldTableField ".substr($requested_filter_field_operator, 1, 4)." ".$comparison_type." '%".$separated_word."'";
                                    }else if($requested_filter_field_operator == "%like%"){
                                        $this->sql_view .= " $fldTableField ".substr($requested_filter_field_operator, 1, 4)." ".$comparison_type." '%".$separated_word."%'";
                                    }else{
                                        $this->sql_view .= " $fldTableField ".$requested_filter_field_operator." $left_geresh".$separated_word."$left_geresh ";
                                    }
                                }else{
                                    $this->sql_view .= " $fldTableField = $left_geresh".$separated_word."$left_geresh ";                                    
                                }                                                        
                                $separated_word_count++;                                
                            }
                            if(count($splitted_fldTableFieldName) > 0) $this->sql_view .= " ) ";
                            if($search_type_start !== $search_type){ $search_type_start = $search_type; }
                        }                    
                    }                    
                }
                $this->DataSource($this->db_handler, $this->sql_view);
            }
        }        
    }
    
    //--------------------------------------------------------------------------
    // Set view mode table properties
    //--------------------------------------------------------------------------    
    function SetViewModeTableProperties($vmt_properties = ""){        
        if(is_array($vmt_properties) && (count($vmt_properties) > 0)){
            if(isset($vmt_properties['width'])) $this->tblWidth['view'] = $vmt_properties['width'];    
        }
    }

    //--------------------------------------------------------------------------
    // Set columns in view mode
    //--------------------------------------------------------------------------    
    function SetColumnsInViewMode($columns = ""){
        unset($this->columns_view_mode);
        $this->columns_edit_mode = array();
        if(is_array($columns)){        
            foreach($columns as $fldName => $fldValue){
                $this->columns_view_mode[$fldName] = $fldValue;
            }
        }
    }

    //--------------------------------------------------------------------------
    // Set auto-generated columns in view mode
    //--------------------------------------------------------------------------    
    function SetAutoColumnsInViewMode($auto_columns = ""){
        if(($auto_columns == true) || ($auto_columns == "true")){
            unset($this->columns_view_mode);
            if($this->db_handler->isError($this->data_set) == 1){
                $this->is_error = true;
                $this->AddErrors();
            }else{
                $fields = $this->data_set->tableInfo();
                for($ind=0; $ind < $this->data_set->numCols(); $ind++){                
                    $this->columns_view_mode[$fields[$ind]['name']] =
                    array("header"  =>$fields[$ind]['name'],
                        "type"      =>"label",
                        "align"     =>"left",
                        "width"     =>"210px",
                        "wrap"      =>"wrap",
                        "tooltip"   =>false,
                        "text_length"=>"-1",
                        "case"      =>"normal",
                        "summarize" =>false,
                        "visible"   =>"true"
                    );
                }                
            }
        }
    }

    //--------------------------------------------------------------------------
    // Set add/edit/details mode table properties
    //--------------------------------------------------------------------------    
    function SetEditModeTableProperties($emt_properties = ""){        
        if(is_array($emt_properties) && (count($emt_properties) > 0)){
            if(isset($emt_properties['width'])) $this->tblWidth['edit'] = $emt_properties['width'];    
        }
    }

    //--------------------------------------------------------------------------
    // Set details mode table properties
    //--------------------------------------------------------------------------    
    function SetDetailsModeTableProperties($dmt_properties = ""){        
        if(is_array($dmt_properties) && (count($dmt_properties) > 0)){
            if(isset($dmt_properties['width'])) $this->tblWidth['details'] = $dmt_properties['width'];    
        }
    }
    
    //--------------------------------------------------------------------------
    // Set editing table & primary key id
    //--------------------------------------------------------------------------
    function SetTableEdit($tbl_name, $field_name, $condition = ""){
        $this->tbl_name = $tbl_name;
        $this->primary_key = $field_name;
        $this->condition = $condition;
    }

    //--------------------------------------------------------------------------
    // Set columns in add/edit/details mode
    //--------------------------------------------------------------------------    
    function SetColumnsInEditMode($columns = ""){
        unset($this->columns_edit_mode);                    
        if(is_array($columns)){
            foreach($columns as $fldName => $fldValue){
                $this->columns_edit_mode[$fldName] = $fldValue;
            }
        }
    }

    //--------------------------------------------------------------------------
    // Set auto-generated columns in add/edit/details mode
    //--------------------------------------------------------------------------    
    function SetAutoColumnsInEditMode($auto_columns = ""){
        if(($auto_columns == true) || ($auto_columns == "true")){
            unset($this->columns_edit_mode);        
            $sql  = " SELECT * FROM ".$this->tbl_name." ";
            $dSet = $this->db_handler->query($sql);
            if($this->db_handler->isError($this->data_set) == 1){
                $this->is_error = true;
                $this->AddErrors();
            }else{
                $fields = $dSet->tableInfo();            
                for($ind=0; $ind < $dSet->numCols(); $ind++){
                    if($fields[$ind]['name'] != $this->primary_key){
                        // get required simbol
                        $required_simbol = ($this->IsFieldRequired($fields[$ind]['name'])) ? "r" : "s";
                        // get field view type & view type 
                        $type_view = "texbox";
                        switch (strtolower($fields[$ind]['type'])){
                            case 'int':     // int: TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT, TINY, SHORT, LONG, LONGLONG, INT24
                                $type_simbol = "i"; break;            
                            case 'real':    // real: FLOAT, DOUBLE, DECIMAL, NUMERIC
                                $type_simbol = "f"; break;            
                            case 'null':    // empty: NULL            
                                $type_simbol = "t"; break;
                            case 'string':  // string: CHAR, VARCHAR, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT, ENUM, SET, VAR_STRING
                            case 'blob':    // blob: TINYBLOB, MEDIUMBLOB, LONGBLOB, BLOB, TEXT
                            case 'date':    // date: DATE
                            case 'timestamp':    // date: TIMESTAMP
                            case 'year':    // date: YEAR
                            case 'time':    // date: TIME
                                $type_simbol = "t"; break;                        
                            case 'datetime':    // date: DATETIME
                                $type_view = "datetime";
                                $type_simbol = "t"; break;
                            default:
                                $type_simbol = "t"; break;
                        }
                        // get required-type simbols
                        $req_type_simbols = $required_simbol."".$type_simbol;
                        // get field maxlength
                        $field_maxlength = ($fields[$ind]['len'] <= 0) ? "" : $fields[$ind]['len'];                    
                        $this->columns_edit_mode[$fields[$ind]['name']] =
                        array("header"  =>$fields[$ind]['name'],
                            "type"      =>"$type_view",
                            "req_type"  =>"$req_type_simbols",
                            "width"     =>"210px",
                            "maxlength" =>"$field_maxlength",
                            "title"     =>$fields[$ind]['name'],
                            "readonly"  =>false,
                            "visible"   =>"true"                            
                        );                    
                    }
                }                        
            }            
        }
    }

    //--------------------------------------------------------------------------
    // Set set foreign keys editing
    //--------------------------------------------------------------------------    
    function SetForeignKeysEdit($foreign_keys_array = ""){
        if(is_array($foreign_keys_array)){                
            foreach($foreign_keys_array as $fldName => $fldValue){
                $this->foreign_keys_array[$fldName] = $fldValue;
            }
        }
    }

    //--------------------------------------------------------------------------
    // Bind data and draw DG
    //--------------------------------------------------------------------------
    function Bind($show = true){                               
        $this->SetInterfaceLang();
        $this->SetCommonJavaScript();
        
        $req_mode = $this->GetVariable('mode');
        $req_rid = $this->GetVariable('rid');
        $req_new = $this->GetVariable('new');
        $req_page_size = $this->GetVariable('page_size');
        $req_sort_field = $this->GetVariable('sort_field');
        $req_sort_field_by = $this->GetVariable('sort_field_by');
        $req_sort_field_type = $this->GetVariable('sort_field_type');
        $sort_field = ($req_sort_field_by != "") ? $req_sort_field_by : $req_sort_field ;
        $req_sort_type = $this->GetVariable('sort_type');
        $req_print = $this->GetVariable('print');

        // protect datagrid from a Hack Attacks
        if($this->SecurityCheck()){
            // VIEW mode processing 
            if(($req_mode == "") || (($req_mode == "view") && ($req_sort_field_type == "numeric"))){
                if($req_sort_field_type == "numeric") $numeric_sort = true; else $numeric_sort = false;
                $this->GetDataSet($this->sql_sort, "", "", $req_sort_field_type, $numeric_sort);
                $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);
            }
            
            // DELETE mode processing 
            if(($req_mode == "delete") && ($req_rid != "")){          
                $this->rid = $req_rid;
                if($req_print != true){
                    $this->DeleteRow($this->rid);
                }
                $this->sql = $this->sql_view;
                $this->GetDataSet($this->sql_sort);
                $this->mode = "view";          
            }
            
            // UPDATE mode processing 
            if($req_mode == "update"){
                $this->rid = $req_rid;
                if($req_print != true){
                    if($req_new != 1){
                        $this->UpdateRow($this->rid);
                    }else{
                        $this->AddRow();
                        $this->mode_after_update = "";
                    }                
                }
                if(($req_new != 1) && ($this->mode_after_update == "edit")){
                    $req_mode = "edit";
                    $this->mode = "edit";
                }else{
                    $this->sql = $this->sql_view;
                    $this->GetDataSet($this->sql_sort);
                    $this->mode = "view";
                }
            }            
    
            // EDIT & DETAILS modes processing 
            if((($req_mode == "edit") || ($req_mode == "details")) && ($req_rid != "")){
                if($req_new == 1){
                    $this->data_set = $this->db_handler->query($this->sql);            
                }
                $this->rid = $req_rid;
                $this->AllowSorting(false);
                $this->AllowPaging(false);            
                $this->sql_sort = " ORDER BY " . $this->primary_key . " DESC";
                if(($this->layouts['view'] == "0") && ($this->layouts['edit'] == "1") && ($req_mode == "details")){
                    $this->rids = explode("-", $this->rid);
                    // if we have more that 1 row selected
                    if(count($this->rids) > 1){ 
                        $where = "WHERE ".$this->primary_key." IN ('-1' ";
                        foreach ($this->rids as $key){ if($key != "") $where .= ", '".$key."' "; }
                        $where .= ") ";
                        $this->multi_rows = count($this->rids);
                    }else{
                        $where = "WHERE ".$this->primary_key." = '".$req_rid."' ";    
                    }
                    if($this->condition != ""){ $where .= " AND ". $this->condition; }
                    $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);
                    //$this->sql_sort = ""; we need this sorted for multi-rows editing
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where;                 
                }else if(($this->layouts['view'] == "0") && ($this->layouts['edit'] == "1") && ($req_mode == "edit")){
                    $this->rids = explode("-", $this->rid);
                    // if we have more that 1 row selected
                    // mr_1
                    if(count($this->rids) > 1){ 
                        $where = "WHERE ".$this->primary_key." IN ('-1' ";
                        foreach ($this->rids as $key){ if($key != "") $where .= ", '".$key."' "; }
                        $where .= ") ";
                        $this->multi_rows = count($this->rids);
                    }else{
                        $where = "WHERE ".$this->primary_key." = '".$req_rid."' ";    
                    }
                    if($this->condition != ""){ $where .= " AND ". $this->condition; }                     
                    $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);                
                    //$this->sql_sort = ""; we need this sorted for multi-rows editing
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where; 
                }else if(($this->layouts['view'] == "0") && ($this->layouts['edit'] == "0") && ($req_mode == "details")){                
                    // if we have more that 1 row selected
                    $this->rids = explode("-", $this->rid);
                    if(count($this->rids) > 1){ 
                        $where = "WHERE ".$this->primary_key." IN ('-1' ";
                        foreach ($this->rids as $key){ if($key != "") $where .= ", '".$key."' "; }
                        $where .= ") ";
                        $this->multi_rows = count($this->rids);
                    }else{
                        $where = "WHERE ".$this->primary_key." = '".$req_rid."' ";    
                    }
                    $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);
                    $this->sql_sort = "";
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where; 
                }else if(($this->layouts['view'] == "0") && ($this->layouts['edit'] == "0") && ($req_mode == "edit")){
                    $view_limit = "";                
                    if($this->condition != ""){ 
                        $where = "WHERE ". $this->condition; 
                    } else { 
                        $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size); 
                        $where = "WHERE ".$this->primary_key." >= '".$req_rid."' ";
                    }                    
                    if($req_sort_field != "") $this->sql_sort = " ORDER BY ".(($req_sort_field_type == "numeric") ? " ABS (".$sort_field.")" : $sort_field)." ".$req_sort_type;
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where;
                }else{
                    $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);                
                    $where = "WHERE ".$this->primary_key." = '".$req_rid."' ";
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where;                 
                }            
    
                $this->GetDataSet($this->sql_sort, $view_limit, $this->mode_after_update);
                if($req_mode == "edit") $this->mode = "edit";
                else $this->mode = "details";           
            }
    
            // CANCEL mode processing 
            if($req_mode == "cancel"){
                $this->rid = "";
                $this->sql = $this->sql_view;
                $this->GetDataSet($this->sql_sort);            
                $this->mode = "view";
            }    
    
            // ADD mode processing 
            if($req_mode == "add"){
                $this->mode_after_update = "";
                // we don't need multirow option allowed when we add new record
                $this->multirow_allowed = false;
                if(($this->layouts['view'] == "0") && ($this->layouts['edit'] == "0")){
                    // we need
                    $view_limit = "";
                    if($this->condition != "") $where = " WHERE ". $this->condition;
                    else $where = "";
                    $this->sql = "SELECT * FROM $this->tbl_name ".$where;                
                }else{
                    $view_limit = "";
                    $this->sql = "SELECT * FROM $this->tbl_name ";                
                }
                $this->sql_sort = " ORDER BY " . $this->primary_key . " DESC";
                $this->GetDataSet($this->sql_sort, $view_limit);
                $this->rid = -1;
                $this->AllowSorting(false);
                $this->AllowPaging(false);
                $this->mode = "edit";
            }            
        }else{
            // VIEW mode processing 
            if($req_mode == ""){
                if($req_sort_field_type == "numeric") $numeric_sort = true; else $numeric_sort = false;
                $this->GetDataSet($this->sql_sort, "", "", $req_sort_field_type, $numeric_sort);
                $view_limit = $this->SetSqlLimitByDbType("0", $req_page_size);
            }
            if($this->debug){
                echo "<br><center><label class='default_class_error_message'>Wrong parameters were passed! Possible Hack attack!</label></center><br>";
            }else{
                echo "<br><center><label class='default_class_error_message'>Wrong parameters were passed!</label></center><br>";                
            }
        }
        
        $this->DisplayErrors();
        $this->DisplayWarnings();        
        $this->DisplayDataSent();        
        
        if($this->data_set){            
            if(($this->mode === "edit") || ($this->mode === "add")){
                $this->layout_type = "edit";
                $this->AllowHighlighting(false);
            }else if($this->mode === "details"){
                $this->layout_type = "show";
                $this->AllowHighlighting(false);
            }else {
                $this->layout_type = "view";
            }
            
            // sort columns by mode order
            $this->SortColumns($this->mode);

            if($show == true){
                $this->WriteCssClass();
                if($this->layouts[$this->layout_type] == "0"){
                    $this->DrawTabular();
                }else if($this->layouts[$this->layout_type] == "1"){
                    $this->DrawColumnar();
                }else if($this->layouts[$this->layout_type] == "2"){
                    $this->DrawCustomized();                
                }else{
                    $this->DrawTabular();
                }
            }
        }
        
        $this->SetCommonJavaScriptEnd();
        // finish calculating running time of a script
        if($this->debug){
            $this->end_time = $this->GetFormattedMicrotime();
            echo "<br><center><label class='default_class_label'>Total running time: ".round((float)$this->end_time - (float)$this->start_time, 6)." sec.</label></center>";
        }        
    }

    ////////////////////////////////////////////////////////////////////////////
    //
    // Non documented
    //
    ////////////////////////////////////////////////////////////////////////////
    
    //--------------------------------------------------------------------------
    // ExecuteSQL - returns dataSet after executing custom SQL statement
    //--------------------------------------------------------------------------
    function ExecuteSQL($sql = ""){
        $dataSet = "";
        if($this->db_handler){
            if($sql != ""){
                $this->SetEncodingOnDatabase();
                $dataSet = & $this->db_handler->query($sql);
            }
            if($this->debug){
                if($this->db_handler->isError($dataSet) == 1){ $debugInfo = "<tr><td>".$dataSet->getDebugInfo()."</td></tr>"; } else { $debugInfo = ""; };
                echo "<table width='".$this->tblWidth[$this->mode]."'><tr><td align='left'><label class='".$this->css_class."_class_label'><b>sql: </b>".$sql."</label></td></tr>".$debugInfo."</table><br>";
            }               
        }else{
            $this->AddWarning('ExecuteSQL() method', 'This method must be called after DataSource() method only!');
        }
        return $dataSet;               
    }

    //--------------------------------------------------------------------------
    // SelectSqlItem - return the first field after executing custom SELECT SQL statement
    //--------------------------------------------------------------------------
    function SelectSqlItem($sql = ""){
        $dataField = "";
        if($this->db_handler){       
            if($sql != ""){
                $this->SetEncodingOnDatabase();
                $this->db_handler->setFetchMode(DB_FETCHMODE_ORDERED); 
                $dataSet = & $this->db_handler->query($sql);
                if($dataSet->numCols() > 0){
                   $row = $dataSet->fetchRow();
                   $dataField = $row[0];
                }
                if($this->debug){
                    if($this->db_handler->isError($dataSet) == 1){ $debugInfo = "<tr><td>".$dataSet->getDebugInfo()."</td></tr>"; } else { $debugInfo = ""; };
                    echo "<table width='".$this->tblWidth[$this->mode]."'><tr><td align='left'><label class='".$this->css_class."_class_label'><b>select sql (".$this->StrToLower($this->lang['total']).": ".$dataSet->numCols().") </b>".$sql."</label></td></tr>".$debugInfo."</table><br>";
                }              
            }
        }else{
            $this->AddWarning('SelectSqlItem() method', 'This method must be called after DataSource() method only!');
        }
        return $dataField;               
    }
    
    function AllowHighlighting($option = true){ $this->row_highlighting_allowed = (($option == true) || ($option == "true")) ? true : false ; }    

    //--------------------------------------------------------------------------
    // Set javascript errors display style
    //--------------------------------------------------------------------------
    function SetJsErrorsDisplayStyle($display_style = "all"){        
        $this->js_validation_errors = ($display_style == "all") ? "true" : "false";
    }    

    //--------------------------------------------------------------------------
    // Get current Id
    //--------------------------------------------------------------------------
    protected function GetCurrentId(){
        return ($this->rid != "") ? $this->rid : $this->GetVariable('rid');
    }

    //--------------------------------------------------------------------------
    // Get next Id
    //--------------------------------------------------------------------------
    function GetNextId(){
        if(isset($this->db_handler)){
            // need to be declined if creating new row was cancelied
            // return $this->db_handler->nextId("'".$this->tbl_name."'");            
            $sql  = " SELECT MAX(".$this->primary_key.") as max_id FROM ".$this->tbl_name." ";
            $dSet = $this->db_handler->query($sql);
            if($row = $dSet->fetchRow()){
                return $row[0]+1;
            }
        }else{
            return "-1";        
        }        
    } 

    //--------------------------------------------------------------------------
    // Set messages
    //--------------------------------------------------------------------------
    function SetDgMessages($add_message = "", $update_message = "", $delete_message = ""){
        $this->dg_messages['add'] = $add_message;
        $this->dg_messages['update'] = $update_message;
        $this->dg_messages['delete'] = $delete_message;
    }

    //--------------------------------------------------------------------------
    // Set header names in columnar layout
    //--------------------------------------------------------------------------
    function SetHeadersInColumnarLayout($field_header = "", $field_value_header = ""){
        $this->field_header = $field_header;
        $this->field_value_header = $field_value_header;
    }
    
    //--------------------------------------------------------------------------
    // Write css class
    //--------------------------------------------------------------------------
    function WriteCssClass(){
        if(!$this->is_css_class_written){
            $req_print = $this->GetVariable('print');

            echo "\n<!-- DataGrid CSS definitions - START -->";
            $this->SetMediaPrint();
            $this->DefineCssClass();
            // if we in Print Mode
            if($req_print == true){
                $this->rowColor[0] = "";
                $this->rowColor[1] = "";            
                $this->rowColor[2] = ""; // dark
                $this->rowColor[3] = ""; // light
                $this->rowColor[4] = ""; // row mouse over lighting
                $this->rowColor[5] = ""; // on mouse click
                $this->rowColor[6] = ""; // header (th main) column
                $this->rowColor[7] = ""; // selected row mouse over lighting
                echo "\n<!--[if IE]><link rel='stylesheet' type='text/css' href='".$this->directory."css/style_print_IE.css'><![endif]-->";            
                echo "\n<link rel='stylesheet' type='text/css' href='".$this->directory."css/style_print.css'>";            
            }else{
                echo "\n<!--[if IE]><link rel='stylesheet' type='text/css' href='".$this->directory."css/style_".$this->css_class."_IE.css'><![endif]-->";            
                echo "\n<link rel='stylesheet' type='text/css' href='".$this->directory."css/style_".$this->css_class.".css'>";            
            }
            echo "\n<!-- DataGrid CSS definitions - END -->\n\n";            
            $this->is_css_class_written = true;            
        }
    }


    //==========================================================================
    // PROTECTED MEMBER FUNCTIONS 
    //==========================================================================
    //--------------------------------------------------------------------------
    // Set unique names
    //--------------------------------------------------------------------------
    protected function SetUniquePrefix($unique_prefix = ""){
        $this->uniquePrefix = $unique_prefix;
        $this->unique_random_prefix = $this->GetRandomString("5");
    }

    //--------------------------------------------------------------------------
    // Set css class
    //--------------------------------------------------------------------------
    protected function DefineCssClass(){        
        if(strtolower($this->css_class) == "green"){
                $this->rowColor[0] = "#ffffff";   
                $this->rowColor[1] = "#e4f5ef";            
                $this->rowColor[2] = "#ffffff";
                $this->rowColor[3] = "#e4f5ef";
                $this->rowColor[4] = "#d4e5df";
                $this->rowColor[5] = "#d4e5df";
                $this->rowColor[6] = "#c6d7cf"; // header (th main) column
                $this->rowColor[7] = "#d4e5df"; // selected row mouse over lighting
                echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/common/grippie.png) #ddd no-repeat center 2px; }</style>";                                
        }else if(strtolower($this->css_class) == "gray") {
                $this->rowColor[0] = "#f9f9f9";
                $this->rowColor[1] = "#f0f0f0";            
                $this->rowColor[2] = "#f0f0f0";
                $this->rowColor[3] = "#dedede";
                $this->rowColor[4] = "#FEFFE8";
                $this->rowColor[5] = "#FEFFE8";
                $this->rowColor[6] = "#dedede"; // header (th main) column
                $this->rowColor[7] = "#FEFFE8"; // selected row mouse over lighting
                echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/common/grippie.png) #ddd no-repeat center 2px; }</style>";                
        }else if(strtolower($this->css_class) == "blue"){
                $this->rowColor[0] = "#f7f9fb";
                $this->rowColor[1] = "#ffffff";            
                $this->rowColor[2] = "#d9e3f1";
                $this->rowColor[3] = "#e4ecf7"; 
                $this->rowColor[4] = "#FEFFE8";
                $this->rowColor[5] = "#FEFFE8";
                $this->rowColor[6] = "#cdd9ea"; // header (th main) column
                $this->rowColor[7] = "#FEFFE8"; // selected row mouse over lighting
                echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/common/grippie.png) #ddd no-repeat center 2px; }</style>";
        }else if(strtolower($this->css_class) == "pink"){
                 $this->rowColor[0] = "#F8F7EF";
                $this->rowColor[1] = "#F8F7EF";            
                $this->rowColor[2] = "#333333"; //edit td dark
                $this->rowColor[3] = "#F8F7EF"; //edit td light
                $this->rowColor[4] = "#e4e2d3";
                $this->rowColor[5] = "#E7E3C7";
                $this->rowColor[6] = "#FFCFB4"; // header (th main) column
                $this->rowColor[7] = "#e4e2d3"; // selected row mouse over lighting
                echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/common/grippie.png) #ddd no-repeat center 2px; }</style>";
        }else{
                $this->rowColor[0] = "#fcfaf6";  
                $this->rowColor[1] = "#ffffff";            
                $this->rowColor[2] = "#ebeadb"; // dark
                $this->rowColor[3] = "#ebeadb"; // light
                $this->rowColor[4] = "#e2f3fc"; // row mouse over lighting 
                $this->rowColor[5] = "#fdfde7"; // on mouse click 
                $this->rowColor[6] = "#e2e0cb"; // header (th main) column
                $this->rowColor[7] = "#f9f9e3"; // selected row mouse over lighting
                echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/common/grippie.png) #eee no-repeat center 2px; }</style>";                
        }        
    }

    //--------------------------------------------------------------------------
    // get DataSet
    //--------------------------------------------------------------------------
    protected function GetDataSet($fsort = "", $limit = "", $mode = "", $sort_field = "", $numeric_sort = false){
        $this->SetEncodingOnDatabase();

        // we need this stupid operation to get a total number of rows in our query
        $this->SetTotalNumberRows("", "", $mode);        

        // we need this stupid operation to change field's offset on field's name
        if(($numeric_sort == true) && ($sort_field != "")){
            $this->data_set = & $this->db_handler->query($this->SetSqlByDbType($this->sql, $fsort, " LIMIT 0, 1"));            
            $this->sql_sort = str_replace("ABS(".$sort_field.")", "ABS(".$this->GetFieldName($sort_field-1).")", $this->sql_sort);
        }

        if($limit == ""){
            $limit = $this->SetSqlLimitByDbType();
            $this->data_set = & $this->db_handler->query($this->SetSqlByDbType($this->sql, $fsort, $limit));
        }

        if($this->db_handler->isError($this->data_set) == 1){
            $this->is_error = true;
            $this->AddErrors();
        }

        $this->rows = $this->NumberRows();
        $this->columns = $this->NumberCols();
        
        if($this->debug){
            echo "<table width='".$this->tblWidth[$this->mode]."'><tr><td align='left' class='".$this->css_class."_class_error_message no_print' style='COLOR: #333333;'><b>search sql (".$this->StrToLower($this->lang['total']).": ".$this->rows.") </b>". $this->sql.$fsort." ".$limit."</td></tr></table><br>";
        }

        $this->row_lower = 0;
        $this->row_upper = $this->rows;

        $this->col_lower = 0;
        $this->col_upper = $this->columns;        
    }

    //--------------------------------------------------------------------------
    // ger ORDER BY fields list
    //--------------------------------------------------------------------------
    protected function GetOrderByList(){
        $orderByList = "";
        for($ind=0; $ind < count($this->default_sort_field); $ind++){
            if($ind != 0) $orderByList .= ",";
            $orderByList .= " ".$this->default_sort_field[$ind]." ".$this->default_sort_type[$ind];
        }
        return $orderByList;
    }

    //--------------------------------------------------------------------------
    // perform security check from a Hack Attacks
    //--------------------------------------------------------------------------
    protected function SecurityCheck(){
        // check rid variable
        $req_rid = $this->GetVariable('rid');
        if(eregi("'", $req_rid) || eregi('"', $req_rid) || eregi("%27", $req_rid) || eregi("%22", $req_rid)){
            return false;
        }
        // check query string
        $query_string = strtolower(rawurldecode($_SERVER['QUERY_STRING']));
        $bad_string = array("%20union%20", "/*", "*/union/*", "+union+", "load_file", "outfile", "document.cookie", "onmouse", "<script", "<iframe", "<applet", "<meta", "<style", "<form", "<img", "<body", "<link", "_GLOBALS", "_REQUEST", "_GET", "_POST", "include_path", "prefix", "http://", "https://", "ftp://", "smb://" );
        foreach ($bad_string as $string_value){
            if (strstr($query_string, $string_value )){
                return false;
            }
        }
        return true;
    }    

    //--------------------------------------------------------------------------
    // set encoding and collation on database
    //--------------------------------------------------------------------------
    protected function SetEncodingOnDatabase(){
        $sql_variables = array(
                'character_set_client'  =>$this->encoding,
                'character_set_server'  =>$this->encoding,
                'character_set_results' =>$this->encoding,
                'character_set_database'=>$this->encoding,
                'character_set_connection'=>$this->encoding,
                'collation_server'      =>$this->collation,
                'collation_database'    =>$this->collation,
                'collation_connection'  =>$this->collation
        );
        foreach($sql_variables as $var => $value){
            $sql = "SET $var=$value;";
            $this->db_handler->query($sql);
        }        
    }

    //--------------------------------------------------------------------------
    // table drawing functions 
    //--------------------------------------------------------------------------
    protected function ShowCaption() {
        echo ($this->caption != "") ? "<div class='".$this->css_class."_class_caption'>". $this->caption ."</div><p></p>".chr(13) : "";
    }

    protected function TblOpen($style=""){
        if($this->scrolling_option == true) {
            $width = ($this->mode == "view") ?  "100%" : $this->tblWidth[$this->mode];
        }else{
            $width = $this->tblWidth[$this->mode];
        }
        $horizontal_align = ($this->tblAlign[$this->mode] == "center") ? "margin-left: auto; margin-right: auto;" : "";
        echo "<table dir='".$this->direction."' class='".$this->css_class."_class_table' style='".$horizontal_align."' width='".$width."' ".$style.">".chr(13);
        echo $this->TbodyOpen();
    }    

    protected function TblClose(){
        echo $this->TbodyClose();        
        echo "</table>".chr(13);
    }

    protected function ScrollDivOpen(){
        if($this->scrolling_option == true){
            echo "<center><div style='TEXT-ALIGN:center; PADDING:0px; WIDTH:".$this->scrolling_width."; HEIGHT:".$this->scrolling_height."; overflow:auto;'>";
            echo chr(13);
        }
    }

    protected function ScrollDivClose(){
        if($this->scrolling_option == true){        
            echo "</div></center>"; echo chr(13);
        }
    }

    protected function HideDivOpen(){
        $req_onSUBMIT_FILTER = $this->GetVariable('_ff_onSUBMIT_FILTER');
        if(($this->hide_grid_before_serach == true) && !($req_onSUBMIT_FILTER != "")){            
            echo "<div style='display: none;'>"; echo chr(13);
        }        
    }

    protected function HideDivClose(){
        $req_onSUBMIT_FILTER = $this->GetVariable('_ff_onSUBMIT_FILTER');        
        if(($this->hide_grid_before_serach == true) && !($req_onSUBMIT_FILTER != "")){            
            echo "</div>"; echo chr(13);
        }        
    }

    protected function TbodyOpen() { echo "<tbody>".chr(13);  }    
    protected function TbodyClose(){ echo "</tbody>".chr(13); }
    
    protected function RowOpen($id, $rowColor = "", $height=""){
        $req_print = $this->GetVariable('print');
        $text = "<tr class='class_tr' style='background-color: ".$rowColor.";' id='".$this->uniquePrefix."row_".$id."' ";       
        if($height != "") { $text .= "height='".$height."' "; };
        if($req_print != true){
            if($this->row_highlighting_allowed){
                $text .= " onclick=\"onMouseClickRow('".$this->uniquePrefix."','".$id."','".$this->rowColor[5]."', '".$this->rowColor[1]."', '".$this->rowColor[0]."');\" ";
                $text .= " onmouseover=\"onMouseOverRow('".$this->uniquePrefix."','".$id."','".$this->rowColor[4]."', '".$this->rowColor[7]."');\" ";
                $text .= " onmouseout=\"onMouseOutRow('".$this->uniquePrefix."','".$id."','".$rowColor."','".$this->rowColor[5]."');\" ";
            }            
        }else{
            $text .= " ";
        }
        $text .= ">".chr(13);
        echo $text;        
    }
    
    protected function RowClose(){
        echo "</tr>".chr(13);
    }
    
    protected function MainColOpen($