function DataGrid (_placeholderId) {
    this.browser = new BrowserDetect().browser;

    
	/* CSS CLASS NAMES */
	this.CLASS_DG_CONTAINER = "dgContainer" ;
	this.CLASS_DG_CONTAINER_HEADER = "dgContainerHeader" ;
	this.CLASS_DG_CONTAINER_BODY = "dgContainerBody" ;
	this.CLASS_DG_CONTAINER_FOOTER = "dgContainerFooter" ;
	this.CLASS_DG_TABLE = "dgTable" ;
	this.CLASS_DG_SPLITTER = "dgSplitter" ;
	this.CLASS_DG_SPLITTER_BACKGROUND = "dgSplitterBackground" ;
	this.CLASS_DG_MESSAGE = "dgMessage" ;
	this.CLASS_DG_PAGER = "dgPager" ;

	/* HTML OBJECTS */
	this.placeholder = document.getElementById (_placeholderId) ;
	if (!this.placeholder) {
		alert ("Ошибка получения контейнера!") ;
		return false ;
	}

	this.container = null ;
	this.titleHeader = null;
	this.header = null ;
	this.body = null ;
	this.footer = null ;
	this.isFooter = false ;
	this.pager = null ;
	this.splitter = null ;
	this.splitterBackground = null ;
	this.activeRow = null ;
	this.activeRowId = null ;
	this.activeRowHiddenValue = null;
	this.isMainPage = "0";
	this.addButton = null;

	this.tableCellSpacing = 1 ;

	this.tableCellPadding = {
		left : 5,
		right : 5,
		top : 5,
		bottom : 5
	}

	this.tableBorder = {
		left : 1,
		right : 1,
		top : 1,
		bottom : 0
	}

	this.headerBorder = {
		left : 0,
		right : 0,
		top : 0,
		bottom : 0
	}

	this.bodyBorder = {
		left : 0,
		right : 0,
		top : 0,
		bottom : 0
	}

	/* TABLE PROPERTIES */
	this.data = null ;
	this.widths = [] ;
	this.pageSize = 0 ;
	this.pagesCount = 5 ;
	this.currentPage = 1 ;
	this.initialColumnWidth = 100 ;
	this.columnsInfo = null;
	this.columnsInfoAs = null;
	this.isResizePossible = false ;
	this.isResize = false ;
	this.resizeColumn = null ;
	this.lastColumn = null ;
	this.scrollBarColumn = null ;
	this.startPosition = 0 ;
	this.finishPosition = 0 ;
	this.OnlyHead = 0;

	this.doGenerateHeader = DataGrid_doGenerateHeader ;
	this.doGenerateBody = DataGrid_doGenerateBody ;
	this.doGenerateFooter = DataGrid_doGenerateFooter ;
	this.doGenerateTable = DataGrid_doGenerateTable ;

	this.doWatchHeader = DataGrid_doWatchHeader ;
	this.doStartResize = DataGrid_doStartResize ;
	this.doResize = DataGrid_doResize ;
	this.doFinishResize = DataGrid_doFinishResize ;
	this.doSinchronizeScroll = DataGrid_doSinchronizeScroll ;
	this.doResizeTable = DataGrid_doResizeTable ;
	this.doRefreshHeader = DataGrid_doRefreshHeader ;
	this.doRefreshBody = DataGrid_doRefreshBody ;
	this.doRefreshTable = DataGrid_doRefreshTable ;
	this.doRefreshPagesCount = DataGrid_doRefreshPagesCount ;
	this.doChangePageSize = DataGrid_doChangePageSize ;
	this.doShowProcessingMessage = DataGrid_doShowProcessingMessage ;
	this.doHideProcessingMessage = DataGrid_doHideProcessingMessage ;
	this.doChangeCurrentPage = DataGrid_doChangeCurrentPage ;
	this.doRowClick = DataGrid_doRowClick ;
	this.doRowDoubleClick = DataGrid_doRowDoubleClick ;
	this.doDelPress = DataGrid_doDelPress;
	this.doAllClickWait = null;	

	/* PUBLIC METHODS */
	this.doInitLayout = DataGrid_doInitLayout ;
	this.doInitColumnWidth = DataGrid_doInitColumnWidth ;
	this.doGetHeaderData = DataGrid_doGetHeaderData ;
	this.doGenerateTitleHeader = DataGrid_doGenerateTitleHeader;
	this.doGetBodyData = DataGrid_doGetBodyData ;
	this.doGetData = DataGrid_doGetData ;
	this.doGetPagesCount = DataGrid_doGetPagesCount ;
	this.doUpdateData = DataGrid_doUpdateData;

	/* EVENTS */
	this.onRowClick = null ;
	this.onRowDoubleClick = null;
	
//****************************************************************************
//	TSOBKALO - BEGIN
//****************************************************************************
	
	this.url = "";
	this.datasourceName = "";
	this.isStoredProc = "0";
	this.keyName = "";
	this.keyValue = "";
	this.headerData = null;
	this.headerColWidth = null;

	this.datasourceType = "";
	this.orderValue = "";
	this.orderParam = "";
	this.orderField = null;
	
	this.whereValue = "";
	this.whereParam = "";
	this.whereString = "";

	this.pageAll = false;
	this.pageSize = 20;
	this.pageNum = 1;
	this.pageRowCount = 1;
	this.pageCount = 2;
	
	//	события	
	this.doInitTableHeader = DataGrid_doInitTableHeader;
	this.doGetTableData = DataGrid_doGetTableData;
	this.doGetTableKeyData = DataGrid_doGetTableKeyData;
	this.doAddFooterButton = DataGrid_doAddFooterButton;
	this.doAddParameter = DataGrid_doAddParameter;
	this.doUpdateWhereClause = DataGrid_doUpdateWhereClause;
	this.doRefreshPager = DataGrid_doRefreshPager;
	this.doGetRecordCount = DataGrid_doGetRecordCount;
	
	//параметры
	this.ParamsName = new Array();
	this.ParamsType = new Array();
	this.ParamsValue = new Array();
	this.FieldsName = new Array();
}


//обновление грида по параметрам
function DataGrid_doUpdateData() {
    
	alert(this.datasourceName);
	jQuery.ajax({
		data: {
			action: 'updatedatagrid',     
			paramsname: ForEach(this.ParamsName, ','), 
			paramstype: ForEach(this.ParamsType, ','),
			paramsvalue: ForEach(this.ParamsValue, ','),
			sqlfunction: this.datasourceName
		},
		type: "get",
		async: false,
		cache: false,
		url: this.url,
		dataType: "text",
		success: function(text){
			//
			alert(text);
		},
		error: function(obj){
			//
			alert('Ошибка обновления данных. База данных Премии не доступна');
			//alert ("Ошибка обновления данных. Невозможно подключиться к базе данных.") ;
			return false;
		}
	});
	
	this.doGetTableData();
}


function GetTimeStamp() {
    
	var date = new Date();
	var stamp = date.getTime();
	return stamp;
}


//	формирование заголовака грида / названия колонок
function DataGrid_doInitTableHeader() {
    
	var _obj = this;

	jQuery.ajax({
		data: {
			action: 'getheader', 
			datasourcename: this.datasourceName, 
			datasourcetype: this.datasourceType,
			paramsname: ForEach(this.ParamsName, ','), 
			paramstype: ForEach(this.ParamsType, ','),
			paramsvalue: ForEach(this.ParamsValue, ','),
			stamp: GetTimeStamp(),
			onlyhead: this.OnlyHead,
			isstoredproc: this.isStoredProc, 
			keyname: this.keyName, 
			keyvalue: this.keyValue
		},
		type: "get",
		async: false,
		cache: false,
		url: this.url,
		dataType: "json",
		success: function(json){
			//
			_obj.columnsInfo = new Array();
			_obj.columnsInfoAs = new Array();
			
			var Titles = new Array();
			Titles[0] = new Array();
			
			for(var colName in json[0]){
				var i = _obj.columnsInfo.length;
			
				var structTitle = json[0][colName].split('|');
				
				var titlename = structTitle[0];
				
				var titlewidth = _obj.initialColumnWidth;
				if( structTitle[1]){
					titlewidth = structTitle[1];
				}

				var fieldtype = 'VARCHAR';
				if( structTitle[2]){
					fieldtype = structTitle[2].toUpperCase();
				}
				
				var servicestype = 'DISPLAY';
				if( structTitle[3]){
					servicestype = structTitle[3];
				}
                if(servicestype != "NONE") {
				    Titles[0][colName] = titlename;
				}
				var needhelp = "0";
				if(structTitle[4]) {
				    needhelp = structTitle[4].split("=")[1];
				}
				
				_obj.columnsInfo[ i] = {'FieldName': '!', 'Width': _obj.initialColumnWidth, 'Caption': '+', 'FieldType': 'VARCHAR', 'FieldVisible': 'DISPLAY', 'HelpId' : '0'};
				_obj.columnsInfo[ i].FieldName = colName;
				_obj.columnsInfo[ i].Caption = titlename;
				_obj.columnsInfo[ i].Width = titlewidth;
				_obj.columnsInfo[ i].FieldType = fieldtype;
				_obj.columnsInfo[ i].FieldVisible = servicestype;
				_obj.columnsInfo[ i].HelpId = needhelp;
				
				_obj.columnsInfoAs[ colName] = {'Width': _obj.initialColumnWidth, 'Caption': '+', 'FieldType': 'VARCHAR', 'FieldVisible':'DISPLAY', 'HelpId' : '0'};
				_obj.columnsInfoAs[ colName].Caption = titlename;
				_obj.columnsInfoAs[ colName].Width = titlewidth;
				_obj.columnsInfoAs[ colName].FieldType = fieldtype;
				_obj.columnsInfoAs[ colName].FieldVisible = servicestype;
				_obj.columnsInfoAs[ colName].HelpId = needhelp;				
			}
			
			
			//_obj.headerData = json;
			_obj.headerData = Titles;
		},
		error: function(obj){
			//
			alert('Невозможно получить заголовки таблиц. База данных Премии не доступна');
			//alert("Невозможно получить заголовки таблиц. База данных не доступна.");
			return false;
		}
	});
	
	this.data = this.headerData;
	this.doGenerateTable();
}

//	формирование данных грида
function DataGrid_doGetTableData() {
    
	var _obj = this;
	//	
	jQuery.ajax({
		data: {
			action: 'getdata', 
			datasourcename: this.datasourceName, 
			datasourcetype: this.datasourceType,
			ordervalue: this.orderValue,
			orderparam: this.orderParam,
			wherevalue: this.whereValue,
			whereparam: this.whereParam,
			paramsname: ForEach(this.ParamsName, ','), 
			paramstype: ForEach(this.ParamsType, ','),
			paramsvalue: ForEach(this.ParamsValue, ','),
			pageall: this.pageAll ? "1" : "0",
			pagesize: this.pageSize,
			pagenum: this.pageNum,
			pagecount: this.pageCount,
			stamp: GetTimeStamp(),
			onlyhead: this.ParamsValue["OnlyHead"],
			isstoredproc: this.isStoredProc, 
			keyname: this.keyName, 
			keyvalue: this.keyValue
		},
		type: "get",
		async: false,
		cache: false,
		url: this.url,
		dataType: "json",
		success: function(json){
			//
			_obj.data = _obj.headerData.concat(json);
			//if(_obj.doAllClickEnd != null) { _obj.doAllClickEnd(); }
		},
		error: function(_obj, obj2, errTxt){
			alert('Невозможно получить данные. База данных Премии не доступна');
			//alert ("Невозможно получить данные. База данных недоступна.");
			//if(_obj.doAllClickEnd != null) { _obj.doAllClickEnd(); }
			return false;
		}
	});
	
	//
	this.doRefreshBody (this) ;
	this.doRefreshPager(this) ;
}
//	запрос количества записей
function DataGrid_doGetRecordCount() {
    
	var _obj = this;
	//
	jQuery.ajax({
		data: {
			action: 'getdata', 
			datasourcename: this.datasourceName, 
			paramsname: ForEach(this.ParamsName, ','), 
			paramstype: ForEach(this.ParamsType, ','),
			paramsvalue: ForEach(this.ParamsValue, ','),
			datasourcetype: this.datasourceType,
			ordervalue: this.orderValue,
			orderparam: this.orderParam,
			wherevalue: this.whereValue,
			whereparam: this.whereParam,
			getpagecount: "1",
			stamp: GetTimeStamp()
		},
		type: "get",
		async: false,
		cache: false,
		url: this.url,
		dataType: "json",
		success: function(json){
			//
			_obj.pageRowCount = json[0].rowcount;
			if( _obj.pageAll){
				_obj.pageCount = _obj.pageRowCount;
			}else{
				_obj.pageCount = Math.ceil(_obj.pageRowCount / _obj.pageSize);
			}
		},
		error: function(obj){
			//
			alert ("Ошибка базы данных.\n" + obj.responseText);
			return false;
		}
	});
	
	//
	//this.doRefreshBody (this) ;
	//this.doRefreshPager(this)
}

//  обновление пэйджера
function DataGrid_doRefreshPager() {
    
	//  если не используется пейджер
	if( !this.isFooter) return;
	//

	//	находим кол-во записей
	this.doGetRecordCount();
	if( this.pageAll){
		this.pageCount = this.pageRowCount;
	}else{
		this.pageCount = Math.ceil(this.pageRowCount / this.pageSize);
	}
	if( this.pageAll){
		this.pageNum = 1;
		jQuery("span.pagerPage", this.footer).html("&nbsp;" + this.pageRowCount + "&nbsp;");
		jQuery("span.pagerAll", this.footer).addClass("checked");
		jQuery("span.pagerNavigator", this.footer).css("display", "none");
	}else{
		jQuery("span.pagerPage", this.footer).html("&nbsp;" + this.pageNum + "&nbsp;стр.&nbsp;из&nbsp;" + this.pageCount + "&nbsp;");
		jQuery("span.pagerAll", this.footer).removeClass("checked");
		jQuery("span.pagerNavigator", this.footer).css("display", "inline");
	}
	$('<div>').oneTime("1s", doHide);
}
function doHide() {
    
    if(jQuery("#divWaitScreen").length > 0) {
        jQuery("#divWaitScreen").hide();
    }
}
function DataGrid_doGetTableKeyData(_keyValue) {
    
	this.keyValue = _keyValue;
	this.doGetTableData();
}

function DataGrid_doUpdateWhereClause(_value, _param) {
    
	this.whereValue = _value;
	this.whereParam = _param;
	this.doGetTableData();
}

function DataGrid_doAddFooterButton(obj) {
    
	jQuery(".footerbtncontainer", this.footer).append(obj);
}


//****************************************************************************
//	TSOBKALO - END
//****************************************************************************


function DataGrid_doInitColumnWidth() {
    
	var length = 0 ;
	for (var key in this.data [0]) {
		if (key.toUpperCase () != "ID") {
			length++ ;
		}
}
	//
	this.widths.length = length ;

	var dataWidth = 0 ;
	for (var i = 0 ; i < length ; i++) {

		if ( !this.widths [i]) {
			this.widths [i] = parseInt( this.columnsInfo[i + 1].Width);
		}

		if (this.widths [i]) {
			if (this.browser == "Firefox") {
				this.header.childNodes [0].rows [0].cells [i].childNodes [0].style.width = (parseInt (this.widths [i]) - this.tableCellPadding.left - this.tableCellPadding.right) + "px" ;
				this.header.childNodes [0].rows [0].cells [i].style.width = this.widths [i] ;

				for (var j = 0 ; j < this.body.childNodes [0].rows.length ; j++) {
					this.body.childNodes [0].rows [j].cells [i].childNodes [0].style.width = (parseInt (this.widths [i]) - this.tableCellPadding.left - this.tableCellPadding.right) + "px" ;
					this.body.childNodes [0].rows [j].cells [i].style.width = this.widths [i] ;
				}
			}
else if (this.browser == "Explorer" || this.browser == "Opera" || this.browser == "Chrome") {
    //this.header.childNodes[0].rows[0].cells[i].style.width  = this.widths[i];    
    jQuery(this.header.childNodes[0].rows[0].cells[i]).attr("width", this.widths[i] + "px" );
				if (this.body.childNodes [0].rows.length) {
					this.body.childNodes [0].rows [0].cells [i].style.width = this.widths [i] ;
				}
			}
		}
		else {
		
			if (this.browser == "Firefox") {
				this.header.childNodes [0].rows [0].cells [i].style.width = (this.initialColumnWidth - this.tableCellPadding.left - this.tableCellPadding.right) + "px" ;
				this.header.childNodes [0].rows [0].cells [i].style.width = this.initialColumnWidth + "px" ;

				for (var j = 0 ; j < this.body.childNodes [0].rows.length ; j++) {
					this.body.childNodes [0].rows [j].cells [i].childNodes [0].style.width = (this.initialColumnWidth - this.tableCellPadding.left - this.tableCellPadding.right) + "px" ;
					this.body.childNodes [0].rows [j].cells [i].style.width = this.initialColumnWidth + "px" ;
				}
			}
        else if (this.browser == "Explorer" || this.browser == "Opera" || this.browser == "Chrome") {
            //this.header.childNodes[0].rows[0].cells[i].style.width = this.initialColumnWidth + "px";
            jQuery(this.header.childNodes[0].rows[0].cells[i]).attr("width", this.initialColumnWidth + "px");
				if (this.body.childNodes [0].rows.length) {
					this.body.childNodes [0].rows [0].cells [i].style.width = this.initialColumnWidth + "px" ;
				}
			}
			this.widths [i] = this.header.childNodes [0].rows [0].cells [i].style.width ;
		}
        dataWidth += parseInt(jQuery( this.header.childNodes[0].rows[0].cells[i]).attr("width")) + ((this.browser == "Explorer") ? 0 : this.tableCellSpacing);
        //dataWidth += parseInt (this.header.childNodes [0].rows [0].cells [i].style.width) + ((this.browser == "Explorer") ? 0 : this.tableCellSpacing) ;
    }
	dataWidth += (this.browser == "Explorer") ? 0 : this.tableBorder.left + this.tableBorder.right ;

	//this.doRefreshHeader(this);

	if (this.browser == "Explorer") {
		this.scrollBarColumn.style.width = (this.body.offsetWidth - this.body.clientWidth + this.tableCellSpacing) + "px" ;
	}
	else {
		this.scrollBarColumn.style.width = (this.body.offsetWidth - this.body.clientWidth) + "px" ;
	}

	var lastColumnWidth = this.header.clientWidth - dataWidth - parseInt (this.scrollBarColumn.style.width) ;

	this.lastColumn.style.width = (lastColumnWidth <= 0) ? "0px" : lastColumnWidth + "px" ;

	if (this.browser == "Firefox") {
		for (var i = 0 ; i < this.body.childNodes [0].rows.length ; i++) {
			this.body.childNodes [0].rows [i].cells [this.lastColumn.cellIndex].childNodes [0].style.width = (parseInt (this.lastColumn.style.width) -  this.tableCellPadding.left - this.tableCellPadding.right) + "px" ;
			this.body.childNodes [0].rows [i].cells [this.lastColumn.cellIndex].style.width = this.lastColumn.style.width ;
		}
		this.doRefreshBody (this) ;
	}
	else if (this.browser == "Explorer" || this.browser == "Opera" || this.browser == "Chrome") {
		if (this.browser == "Explorer") {
			if (this.body.childNodes [0].rows.length) {
				this.body.childNodes [0].rows [0].cells [this.lastColumn.cellIndex].style.width = (parseInt (this.lastColumn.style.width) + this.tableCellSpacing) + "px" ;
			}
		}
		else {
			if (this.body.childNodes [0].rows.length) {
				this.body.childNodes [0].rows [0].cells [this.lastColumn.cellIndex].style.width = this.lastColumn.style.width ;
			}
		}
	}
}

//  генерация заголовка грида
function DataGrid_doGenerateHeader() {
    
	this.header = document.createElement ("DIV") ;
	this.header.className = this.CLASS_DG_CONTAINER_HEADER ;

	var table = document.createElement ("TABLE") ;
	table.className = this.CLASS_DG_TABLE ;

	var row = table.insertRow (0) ;
	
	//

	var cell = null ;
	for (var key in this.data [0]) {
		//	отсекаем поле ID
		if (key.toUpperCase () != "ID") {
			cell = document.createElement ("TH") ;
			//cell.innerHTML = "<div>" + this.data [0][key] + "</div>" ;
			//cell.style.width = '300px';
			//jQuery(cell).attr("width","300px");
            
			cell.className = "field";
			if(this.columnsInfoAs[key].HelpId == "0"){
			    cell.innerHTML = "<div><span fieldname='" + key + "'>" + this.data [0][key] + "</span></div>" ;
            }
            else {
                cell.innerHTML = "<div><img src='img/new/grid/question_gray.gif' helpid='" + this.columnsInfoAs[key].HelpId + "' onclick='CallHelp(this, event)' onmouseout='HideHelp()' style='cursor: pointer; margin-right: 4px;'/><span fieldname='" + key + "'>" + this.data[0][key] + "</span></div>";
            }
			var obj = this ;
			cell.onmousemove = function (_evt) {
				var evt = (obj.browser == "Explorer") ? window.event : _evt ;
				obj.doWatchHeader (evt, obj) ;
			}

			cell.onmousedown = function (_evt) {
				if (obj.isResizePossible) {
					var evt = (obj.browser == "Explorer") ? window.event : _evt ;
					obj.doStartResize (evt, obj) ;
				}
				else {
					return false ;
				}
			}

			row.appendChild (cell) ;
		}

	}

	var _obj = this;
	
	jQuery("th.field div", row).css({
		"margin-right": "15px"
	});

	jQuery("th.field span", row).css({
		//"margin-right": "15px",
		"cursor": "pointer"
	})
	.hover(
		function(){
			jQuery(this).addClass("sortactive");
		}, 
		function(){
			jQuery(this).removeClass("sortactive");
		}
	)
	.bind("click", {}, function(){
		//
		var fieldname = jQuery(this).attr("fieldname");
		if( !fieldname) return;
		
		jQuery(_obj.orderField).removeClass("order" + _obj.orderParam);

		//	напрсавление сортировки	
		if(_obj.orderValue != fieldname) {
			_obj.orderParam = "asc";
		}else{
			if( _obj.orderParam == "asc"){
				_obj.orderParam = "desc";
			}else{
				_obj.orderParam = "asc";
			}
		}
		
		_obj.orderField = this;
		jQuery(_obj.orderField).addClass("order" + _obj.orderParam);
		
		//	запоминаем поле для сортровки
		_obj.orderValue = fieldname;
		//	обновляем данные грида
		_obj.doGetTableData();
		
	});

	cell = document.createElement ("TH") ;
	cell.innerHTML = "<DIV></DIV>" ;
	this.lastColumn = cell ;
	row.appendChild (cell) ;

	cell = document.createElement ("TH") ;
	cell.innerHTML = "" ;
	this.scrollBarColumn = cell ;
	row.appendChild (cell) ;

	this.header.appendChild (table) ;
}

function DataGrid_doGenerateTitleHeader(strTitle) {
    
    this.titleHeader = document.createElement("DIV");
	this.titleHeader.className = "dgContainerTitleHeader";

	var table = document.createElement("TABLE");
	table.className = "titleTableContainer";

	var row = table.insertRow(0);
	
	var cellImg = document.createElement("td");
	cellImg.className = "inheaderimg";
	
	var img = document.createElement("img");
	//img.attributes;	
	img.src = "img/arrow.gif";
	cellImg.appendChild(img);
	
	//убираем оранжевую стрелку из диайна
	//row.appendChild(cellImg);
	
	var cellText = document.createElement("td");
	cellText.innerText = strTitle;
	cellText.className = "inheadertext";
	
	row.appendChild(cellText);
	
	this.titleHeader.appendChild(table);	 
}

//  генерация теля грида
function DataGrid_doGenerateBody() {
    
	this.body = document.createElement ("DIV") ;
	this.body.className = this.CLASS_DG_CONTAINER_BODY ;

	var table = document.createElement ("TABLE") ;
	table.className = this.CLASS_DG_TABLE ;

	var row = null ;
	var cell = null ;

	for (var i = 1 ; i < this.data.length ; i++) {
		row = table.insertRow (table.rows.length) ;
		
		for (var key in this.data [i]) {
			if (key.toUpperCase () != "ID" && this.columnsInfo[i].FieldVisible != "NONE") {
				cell = document.createElement ("TD") ;
				if(this.columnsInfo[i].FieldType == "BIT"){
				    cell.innerHTML = "<DIV><input type='checkbox' style='readonly' id='chbx" + i +"' cheched='" + this.data [i][key] + "</DIV>" ;
				    //cell.innerHTML = "<span class='pagerAll'></span>" ;
				}
				else {
				    cell.innerHTML = "<DIV>" + this.data[i][key] + "</DIV>";
				}
				row.appendChild (cell) ;
			}
			else {
				row.rowId = this.data [i][key] ;				
			}
		}

		cell = document.createElement ("TD") ;
		cell.innerHTML = "<DIV></DIV>" ;
		row.appendChild (cell) ;

		row.onclick = function (_evt) {
			var evt = (obj.browser == "Explorer") ? window.event : _evt ;
			var activeRow = this ;
			obj.doRowClick (evt, obj, activeRow) ;		
		}
		row.ondblclick = function (_evt) {
		    var evt = (obj.browser == "Explorer") ? window.event : _evt ;
			var activeRow = this ;
			obj.doRowDoubleClick (evt, obj, activeRow) ;
		}
	}

	var obj = this ;
	this.body.onscroll = function (_evt) {
		var evt = (obj.browser == "Explorer") ? window.event : _evt ;
		obj.doSinchronizeScroll (evt, obj) ;
	}

	this.body.appendChild (table) ;
}

var _temp_obj;
function getDataAfterSecond() {    
    _temp_obj.doGetTableData();
}

//	формирование подвала грида
function DataGrid_doGenerateFooter() {

    var obj = this;

    this.footer = document.createElement("DIV");
    this.footer.className = this.CLASS_DG_CONTAINER_FOOTER;

    this.message = document.createElement("SPAN");
    this.message.className = this.CLASS_DG_MESSAGE;

    var table = document.createElement("TABLE");
    table.cellPadding = "0";
    table.cellSpacing = "0";

    var row = table.insertRow(0);

    //	добавляем pager
    cell = DataGrid_FooterAddPager(row);

    /*	//	кнопка фильтра
    cell = document.createElement ("TD") ;
    cell.className = "dgFilter";
    cell.style.whiteSpace = "nowrap" ;
    cell.style.verticalAlign = "top" ;
    row.appendChild (cell) ;
    */

    //	клик флага ВСЕ
    jQuery("span.pagerAll", cell).bind("click", {}, function() {
        obj.pageAll = !obj.pageAll;
        DataGrid_FooterPageManagementButtonPressed(obj);
    });
    //	первая страница
    DataGrid_FooterBindActionToButton(cell, obj, "span.pagerFirst",
	    "./img/new/grid/ico_first_hover.gif", "./img/new/grid/ico_first.gif",
	    function() { obj.pageNum = 1; });
    //	следующая страница
    DataGrid_FooterBindActionToButton(cell, obj, "span.pagerNext",
		"./img/new/grid/ico_next_hover.gif", "./img/new/grid/ico_next.gif",
	    function() { if (obj.pageNum < obj.pageCount) { obj.pageNum = obj.pageNum + 1; } });
    //	предыдущая страница
    DataGrid_FooterBindActionToButton(cell, obj, "span.pagerPrev",
	    "./img/new/grid/ico_prev_hover.gif", "./img/new/grid/ico_prev.gif",
	    function() { if (obj.pageNum > 1) { obj.pageNum = obj.pageNum - 1; } });
    //	последняя страница
    DataGrid_FooterBindActionToButton(cell, obj, "span.pagerLast",
		"./img/new/grid/ico_last_hover.gif", "./img/new/grid/ico_last.gif",
		function() { obj.pageNum = obj.pageCount; });
    //	клик на фильтр
    jQuery("span.dgFilter", cell)
	    .hover( function() {jQuery("span", this).addClass("divFindHover");},
	            function() {jQuery("span", this).removeClass("divFindHover");}
	);
    jQuery("span.refresh", cell)
    	.hover( function() {jQuery("span", this).addClass("divFindHover");},
	            function() {jQuery("span", this).removeClass("divFindHover");}
	);
    jQuery("span.refresh", cell).bind("click", {}, function() {
        if (obj.activeRow != null) {
            var tableActiveRowId = obj.activeRowId;
            obj.doUpdateWhereClause(obj.whereString);
            obj.activeRow = jQuery("#" + obj.placeholder.id + " tr[rowId=" + tableActiveRowId + "]");
            obj.activeRowId = tableActiveRowId;
            jQuery("#" + obj.placeholder.id + " tr[rowId=" + tableActiveRowId + "]").addClass("active");
        }
    });


    //	добавляем контейнер для кнопок
    var cell = document.createElement("TD");
    cell.className = "footerbtncontainer";
    cell.style.width = "100%";
    cell.innerHTML = "&nbsp;";
    row.appendChild(cell);

    this.footer.appendChild(table);
}

function DataGrid_FooterAddPager(row) {
    cell = document.createElement("TD");
    cell.id = "dgPager";
    cell.style.whiteSpace = "nowrap";
    cell.style.verticalAlign = "top";
    row.appendChild(cell);

    var st = "<span class='pagerAll divFooterTextColor' >Все</span>";
    st = st + "<span class='pagerNavigator' >";
    st = st + "<span class='pagerFirst' ><img src='./img/new/grid/ico_first.gif' border='0' width='14px' height='14px' /></span>";
    st = st + "<span class='pagerPrev' ><img src='./img/new/grid/ico_prev.gif' border='0' width='14px' height='14px' /></span>";
    st = st + "<span class='pagerPage divFooterTextColor' >&nbsp;" + this.pageNum + "&nbsp;из&nbsp;" + this.pageCount + "</span>";
    st = st + "<span class='pagerNext' ><img src='./img/new/grid/ico_next.gif' border='0' width='14px' height='14px' /></span>";
    st = st + "<span class='pagerLast' ><img src='./img/new/grid/ico_last.gif' border='0' width='14px' height='14px' /></span>";
    st = st + "</span>";
    st = st + "<span class='dgFilter' ><span class='divFooterTextColor'>Поиск</span></span>";
    st = st + "<span><span class='divFooterTextColor'>| </span></span>";
    st = st + "<span class='refresh' ><span class='divFooterTextColor'>Обновить</span></span>"
    //st = st + "<span class='dgFilter' ><img src='./images/grid/ico_filter.gif' border='0' width='14px' height='14px' /></span>";
    cell.innerHTML = st;
    return cell;
}

//Приявязать функцию обработки нажатия на кнопку футера
function DataGrid_FooterBindActionToButton(cell, grid, strButtonSelector, strPathToBtnIcoHovered,
	    strPathToBtnIcoNormal, funcSetPageNum) {

    jQuery(strButtonSelector, cell).bind("click", {}, function() {
        funcSetPageNum();
        DataGrid_FooterPageManagementButtonPressed(grid);
    })
	.hover(
		function() {
		    jQuery("img", this).attr("src", strPathToBtnIcoHovered);
		},
		function() {
		    jQuery("img", this).attr("src", strPathToBtnIcoNormal);
		}
	    );
}
	
//Базовая ф-циональность нажатия на кнопку футера
function DataGrid_FooterPageManagementButtonPressed(grid) {
    if (jQuery("#fromtree").length > 0) jQuery("#fromtree").val("0");
    if (jQuery("#divWaitScreen").length > 0) {
        jQuery("#divWaitScreen").show();
        _temp_obj = grid;
        //С версией jQuery из js.new не происходит вызов ф-ции делегата getDataAfterSecond в jQuery().oneTime()
        $('<div>').oneTime( "1s", getDataAfterSecond );
    }
    else {
        obj.doGetTableData();
    }
}

function DataGrid_doChangePageSize(_evt, _obj) {
    
	var target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ;
	_obj.pageSize = parseInt (target.options [target.selectedIndex].value) ;

	_obj.doGetBodyData () ;
}

function DataGrid_doGenerateTable() {
    
	/* CREATE TABLE */
    if (this.data) {
        this.doGenerateHeader();
        this.doGenerateBody();
        this.doGenerateFooter();
	}
	else {		
		return false ;
	}

	var obj = this ;

	/* CREATE SPLITTER BACKGROUND */
	this.splitterBackground = document.createElement ("DIV") ;
	this.splitterBackground.className = this.CLASS_DG_SPLITTER_BACKGROUND ;

	/* CREATE SPLITTER */
	this.splitter = document.createElement ("DIV") ;
	this.splitter.className = this.CLASS_DG_SPLITTER ;

	

	/* CREATE CONTAINER */
	this.container = document.createElement ("DIV") ;
	this.container.className = this.CLASS_DG_CONTAINER ;
	
	jQuery(this.placeholder).bind("resize", function(_evt) {
	    var evt = (obj.browser == "Explorer") ? window.event : _evt ;
	    obj.doResizeTable (evt, obj) ;
	});
	
	this.container.appendChild (this.splitter) ;
	this.container.appendChild (this.splitterBackground) ;
	if(this.titleHeader != null) {
	    this.container.appendChild (this.titleHeader) ;
	}
	this.container.appendChild (this.header) ;
	this.container.appendChild (this.body) ;
	this.container.appendChild (this.footer) ;

	if (this.isFooter) {
		this.footer.style.display = "block" ;
	}
	else {
		this.footer.style.display = "none" ;
	}

	jQuery(this.container).css({"width": this.placeholder.clientWidth + "px","height": this.placeholder.clientHeight});
    
    //jQuery(this.container).css("height", this.placeholder.clientHeight + "px");

	this.placeholder.appendChild (this.container) ;

	this.doInitLayout();
}

function DataGrid_doInitLayout() {
    
	this.header.style.width = (this.container.clientWidth - this.headerBorder.left - this.headerBorder.right) + "px" ;
	this.body.style.width = (this.container.clientWidth - this.bodyBorder.left - this.bodyBorder.right) + "px" ;
	var theader = 0;
	if(this.titleHeader != null) { theader = this.titleHeader.offsetHeight; }
	if((this.container.clientHeight - theader - this.header.offsetHeight - this.bodyBorder.top - this.bodyBorder.bottom - this.footer.offsetHeight) > 0){
		this.body.style.height = (this.container.clientHeight - theader - this.header.offsetHeight - this.bodyBorder.top - this.bodyBorder.bottom - this.footer.offsetHeight) + "px";
	}
	this.header.childNodes [0].style.width = this.header.clientWidth + "px" ;
	this.body.childNodes [0].style.width = this.body.clientWidth + "px" ;

	this.doInitColumnWidth();
}

function DataGrid_doWatchHeader(_evt, _obj) {
	var target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ;
	if (target.tagName == "TH") {
		target = target.childNodes [0] ;
	}

	if (_obj.isResize && _obj.browser == "Firefox") {
		_obj.doResize (_evt, _obj) ;
	}
	else {
		if (target.parentNode.offsetWidth - ((_obj.browser == "Firefox") ? _evt.layerX : _evt.offsetX) < 15) {
			target.parentNode.style.cursor = "e-resize" ;
			_obj.isResizePossible = true ;
		}
		else {
			target.parentNode.style.cursor = "default" ;
			_obj.isResizePossible = false ;
		}
	}
}

function DataGrid_doResize(_evt, _obj) {
    
	var target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ;

	if (_obj.isResize) {
		document.body.style.cursor = "e-resize" ;
		_obj.splitter.style.left = (_obj.browser == "Explorer" || _obj.browser == "Opera") ? _evt.x : _evt.clientX ;
	}
}

function DataGrid_doStartResize(_evt, _obj) {
    
	_obj.isResize = true ;

	var target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ;
	if (target.tagName == "TH") {
		target = target.childNodes [0] ;
	}

	_obj.resizeColumn = target.parentNode ;

	_obj.startPosition = _evt.screenX ;

	/*
	_obj.splitterBackground.style.display = "block" ;
	_obj.splitterBackground.style.height = _obj.header.offsetHeight ;
	_obj.splitterBackground.style.width = _obj.header.offsetWidth ;
	_obj.splitterBackground.style.top = 0 ;
	_obj.splitterBackground.style.left = 0 ;
	*/

	_obj.splitter.style.display = "block" ;
	_obj.splitter.style.height = _obj.container.offsetHeight ;
	_obj.splitter.style.width = "3px" ;
	_obj.splitter.style.top = 0 ;
	_obj.splitter.style.left = _obj.resizeColumn.offsetLeft + _obj.resizeColumn.offsetWidth - (3 - _obj.tableCellSpacing) / 2 ;

	document.onselectstart = function (_evt) {
		if (_obj.browser == "Chrome" || _obj.browser == "Firefox" || _obj.browser == "Opera") {
			_evt.preventDefault () ;
		}
		return false ;
	} ;

	document.body.onmousemove = function (_evt) {
		var evt = (_obj.browser == "Explorer") ? window.event : _evt ;
		_obj.doResize (evt, _obj) ;
	}

	document.body.onmouseup = function (_evt) {
		var evt = (_obj.browser == "Explorer") ? window.event : _evt ;
		_obj.doFinishResize (evt, _obj) ;
	} ;
}

function DataGrid_doFinishResize(_evt, _obj) {
    
	if (_obj.isResize) {
		_obj.splitter.style.display = "none" ;
		_obj.splitterBackground.style.display = "none" ;

		_obj.isResize = false ;
		_obj.finishPosition = _evt.screenX ;

		var dWidth = _obj.finishPosition - _obj.startPosition ;
		var resizeColumnWidth = parseInt (_obj.resizeColumn.style.width) + dWidth ;

		_obj.widths [_obj.resizeColumn.cellIndex] = (resizeColumnWidth <= 100) ? 0 : resizeColumnWidth ;

		_obj.doInitColumnWidth () ;
	
		document.body.onmousemove = "" ;
		document.body.onmouseup = "" ;

		document.body.style.cursor = "default" ;
	}
}

function DataGrid_doSinchronizeScroll(_evt, _obj) {
    
	_obj.header.scrollLeft = _obj.body.scrollLeft ;
}

function DataGrid_doResizeTable(_evt, _obj) {
    jQuery(this.container).css({ "width": this.placeholder.clientWidth + "px", "height": this.placeholder.clientHeight });    

    var theaderWidth = 0;
    var theaderHeight = 0;    
	if(_obj.titleHeader != null) { theaderHeight = _obj.titleHeader.offsetHeight; theaderWidth = _obj.titleHeader.offsetWidth; }
	var width = _obj.container.clientWidth - _obj.headerBorder.left - _obj.headerBorder.right ;
	_obj.header.style.width = (width < 0) ? "0px" : width + "px" ;

	width = _obj.container.clientWidth - _obj.bodyBorder.left - _obj.bodyBorder.right ;
	_obj.body.style.width = (width < 0) ? "0px" : width + "px";
//	_obj.footer.style.width = (width < 0) ? "0px" : width + "px";

	var height = _obj.container.clientHeight - theaderHeight - _obj.header.offsetHeight - _obj.bodyBorder.top - _obj.bodyBorder.bottom - _obj.footer.offsetHeight ;
	_obj.body.style.height = (height < 0) ? "0px" : height + "px" ;

	_obj.header.childNodes [0].style.width = _obj.header.clientWidth + "px" ;
	_obj.body.childNodes[0].style.width = _obj.body.clientWidth + "px";
//	_obj.footer.childNodes[0].style.width = _obj.footer.clientWidth + "px";

	_obj.doInitColumnWidth () ;
}

function DataGrid_doGetHeaderData() {
	/* это метод обработки данных. тут колбэком должен вызываться метод обновления заголовка таблицы */
    /* сейчас это просто фэйк. код внутри функции можно смело удалить */
    
	var obj = this ;
	if (this.data == tblData) {
		this.data = tblData2 ;
	}
	else {
		this.data = tblData ;
	}

	this.doShowProcessingMessage ("Processing...") ;
	this.doRefreshHeader (obj) ; // это метод для колбэка, еще надо вставить подготовку массива данных.
}

function DataGrid_doRefreshHeader(_obj) {
    
	_obj.doHideProcessingMessage () ;

	var lastColumnWidth = _obj.lastColumn.style.width ;
	var scrollBarColumnWidth = _obj.scrollBarColumn.style.width ;

	_obj.header.innerHTML = "" ;

	var table = document.createElement ("TABLE") ;
		table.className = this.CLASS_DG_TABLE ;

	var row = table.insertRow (0) ;

	var cell = null ;

	var i = 0 ;
	for (var key in _obj.data [0]) {
		if (key.toUpperCase () != "ID") {
			cell = document.createElement ("TH") ;
			cell.innerHTML = "<DIV>" + _obj.data [0][key] + "</DIV>" ;
			
			cell.style.cursor = "pointer";

			if (_obj.widths [i]) {
				cell.style.width = _obj.widths [i] ;
			}
			else {
				cell.style.width = _obj.initialColumnWidth + "px" ;
			}
			i++ ;

			var obj = _obj ;
			cell.onmousemove = function (_evt) {
				var evt = (obj.browser == "Explorer") ? window.event : _evt ;
				obj.doWatchHeader (evt, obj) ;
			}
			cell.onmousedown = function (_evt) {
				if (obj.isResizePossible) {
					var evt = (obj.browser == "Explorer") ? window.event : _evt ;
					obj.doStartResize (evt, obj) ;
				}
				else {
					return false ;
				}
			}

			row.appendChild (cell) ;
		}
	}

	cell = document.createElement ("TH") ;
	cell.innerHTML = "<DIV></DIV>" ;
	cell.style.width = lastColumnWidth ;
	_obj.lastColumn = cell ;
	row.appendChild (cell) ;

	cell = document.createElement ("TH") ;
	cell.innerHTML = "<DIV></DIV>" ;
	cell.style.width = scrollBarColumnWidth ;
	
	_obj.scrollBarColumn = cell ;
	row.appendChild (cell) ;

	_obj.header.appendChild (table) ;
}

function DataGrid_doGetBodyData() {
    
	/* это метод обработки данных. тут колбэком должен вызываться метод обновления тела таблицы */
	/* сейчас это просто фэйк. код внутри функции можно смело удалить */

	var obj = this ;
	if (this.data == tblData) {
		this.data = tblData2 ;
	}
	else {
		this.data = tblData ;
	}

	this.doShowProcessingMessage ("Processing...") ;
	
	//
	
	this.doRefreshBody (obj) ; // это метод для колбэка, еще надо вставить подготовку массива данных.

}

function DataGrid_doRefreshBody(_obj) {
    
	var obj = _obj ;
	_obj.doHideProcessingMessage () ;

	_obj.body.innerHTML = "" ;

	var table = document.createElement ("TABLE") ;
		table.className = _obj.CLASS_DG_TABLE ;

	var row = null ;
	var cell = null ;

	var j = 0 ;
	for (var i = 1 ; i < _obj.data.length ; i++) {
		row = table.insertRow (table.rows.length) ;
		j = 0 ;
		for (var key in _obj.data [i]) {
			if (key.toUpperCase () != "ID") 
			{
			    //if(key == "rowcount") { _obj.pageRowCount = _obj.data [i][key]; continue; }
			    if(!this.columnsInfoAs[key].FieldVisible || this.columnsInfoAs[key].FieldVisible != "NONE"){
				    cell = document.createElement ("TD") ;
				    if (_obj.widths [j]) {
					    cell.style.width = _obj.widths [j] ;
				    } else {
					    cell.style.width = _obj.initialColumnWidth + "px" ;
				    }								
				    //cell.innerHTML = "<DIV><A onmouseover = 'this.style.textDecoration = \"underline\"' onmouseout = 'this.style.textDecoration = \"none\"'>" + _obj.data [i][key] + "</A></DIV>" ;
				    if(this.columnsInfoAs[key]){
				        switch (this.columnsInfoAs[key].FieldType.toUpperCase()) {
				            case "BIT":
				                var checked = '';
				                if(this.data [i][key] == 1){
				                    checked = ' checked ';
				                    cell.innerHTML = '<div class="checkcontainer"><img class="checkimg" src="img/new/grid/ico_check_on.gif" /></div>';
				                }
				                //cell.innerHTML = '<div style="/*text-align:center;*/padding-left:40px;"><input type="checkbox" ' + checked + '/ value=' + this.data [i][key]  + ' onclick="return false;"></div>';
				                else{
				                    cell.innerHTML = '<div class="checkcontainer"><img class="checkimg" src="img/new/grid/ico_check_off.gif" /></div>';
                                }
                                break;
                            case "OPENNEWWINDOW":
                                if(this.data [i][key] == 1){				                    
				                    cell.innerHTML = "<div class='imgcontainer'><a href='javascript:OpenFrameWithDetail(" + _obj.data[i]['Map'] + "," + _obj.data[i]['PictureId'] + "," + _obj.data[i]['Id'] + ")' class='smallimage'>&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";
				                }
				                //cell.innerHTML = '<div style="/*text-align:center;*/padding-left:40px;"><input type="checkbox" ' + checked + '/ value=' + this.data [i][key]  + ' onclick="return false;"></div>';
//				                else{
//				                    cell.innerHTML = '<div class="imgcontainer"></div>';
//                                }
                                break;
                            case "EDITINPUT":
                                cell.innerHTML = "<div class='checkcontainer'><input type='text' style='width: 40px; border: 1px solid #c4c4c4' value='" + _obj.data [i][key] + "' /></div>" ;
                                break;
                            default:
                                cell.innerHTML = "<div title='" + this.data[i][key] + "'>" + _obj.data[i][key] + "</div>";
                                break;
				        }
				    }
				    row.appendChild (cell) ;
    			    
			        j++ ;
			    }
			    else {			        
			        //row.hiddenVal = _obj.data[i][key];
			        jQuery(row).attr(key, _obj.data[i][key]);
			    }					
			}
			else {
				row.rowId = _obj.data [i][key] ;
			}	
		}

		cell = document.createElement ("TD") ;
		cell.innerHTML = "<DIV></DIV>" ;
		row.appendChild (cell) ;

		row.style.cursor = "pointer";

		row.onclick = function (_evt) {
			var evt = (obj.browser == "Explorer") ? window.event : _evt ;
			var activeRow = this ;
			obj.doRowClick (evt, obj, activeRow) ;
		}
		row.ondblclick = function (_evt) {
		    var evt = (obj.browser == "Explorer") ? window.event : _evt ;
			var activeRow = this ;
			obj.doRowDoubleClick (evt, obj, activeRow) ;
		}		

        
	}    
	_obj.body.appendChild (table) ;
	if("#" + _obj.placeholder.id + " input.addhandler") {
	    
	}
	jQuery(table).bind("keyup", function(event) { WorkWithKeyBoard(event, _obj); });

	if (_obj.browser == "Explorer") {
	    if(_obj.body.offsetWidth == 0){ 
	        _obj.scrollBarColumn.style.width = (_obj.body.clientWidth - _obj.body.clientWidth + _obj.tableCellSpacing) + "px" ;
	     } else {	     
		    _obj.scrollBarColumn.style.width = (_obj.body.offsetWidth - _obj.body.clientWidth + _obj.tableCellSpacing) + "px" ;
		 }
	}
	else {
		_obj.scrollBarColumn.style.width = (_obj.body.offsetWidth - _obj.body.clientWidth) + "px" ;
	}
	if (_obj.browser == "Firefox") {
		if (_obj.body.childNodes [0].rows.length) {
			_obj.lastColumn.style.width = (_obj.body.childNodes [0].rows [0].cells [_obj.lastColumn.cellIndex].clientWidth) + "px" ;
		}
	}
	else {
		if (_obj.body.childNodes [0].rows.length) {
			_obj.lastColumn.style.width = (_obj.body.childNodes [0].rows [0].cells [_obj.lastColumn.cellIndex].clientWidth + _obj.tableCellSpacing) + "px" ;
		}
	}
	
	jQuery('tr:odd', table).addClass('odd');	
}

function DataGrid_doGetData() {
    
	/* это метод обработки данных. тут колбэком должен вызываться метод обновления таблицы */
	/* сейчас это просто фэйк. код внутри функции можно смело удалить */

	var obj = this ;
	if (this.data == tblData) {
		this.data = tblData2 ;
	}
	else {
		this.data = tblData ;
	}

	this.doShowProcessingMessage ("Processing...") ;
	this.doRefreshTable (obj) ; // это метод для колбэка, еще надо вставить подготовку массива данных.

}

function DataGrid_doRefreshTable(_obj) {
    
	_obj.doHideProcessingMessage () ;

	_obj.doRefreshHeader (_obj) ;
	_obj.doRefreshBody (_obj) ;
	_obj.doInitColumnWidth () ;
}

function DataGrid_doGetPagesCount() {
    
	/* это метод обработки данных. тут колбэком должен вызываться метод обновления таблицы */
	/* сейчас это просто фэйк. код внутри функции можно смело удалить */

	var obj = this ;
	if (this.pagesCount == 5) {
		this.pagesCount == 10 ;
	}
	else {
		this.pagesCount == 5 ;
	}

	this.doShowProcessingMessage ("Processing...") ;
	this.doRefreshPagesCount (obj) ; // это метод для колбэка, еще надо вставить подготовку массива данных.
}

function DataGrid_doRefreshPagesCount(_obj) {
    
	var obj = _obj ;

	this.doHideProcessingMessage ("Processing...") ;

	_obj.pager.innerHTML = "" ;

	var html = "" ;
	for (var i = 0 ; i < _obj.pagesCount ; i++) {
		if (i + 1 == _obj.currentPage) {
			html += "<A href='javascript: void (0)' number='" + (i + 1) + "'><STRONG>" + (i + 1) + "</STRONG></A>" ;
		}
		else {
			html += "<A href='javascript: void (0)' number='" + (i + 1) + "'>" + (i + 1) + "</A>" ;
		}
		if (i + 1 != _obj.pagesCount) {
			html += "&nbsp;|&nbsp;" ;
		}
	}

	_obj.pager.innerHTML = html ;

	var links = _obj.pager.getElementsByTagName ("A") ;

	for (var i = 0 ; i < links.length ; i++) {
		links [i].onclick = function (_evt) {
			var evt = (obj.browser == "Explorer") ? window.event : _evt ;
			obj.doChangeCurrentPage (evt, obj) ;
		}
	}
}

function DataGrid_doChangeCurrentPage(_evt, _obj) {
    
	var target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ;

	_obj.currentPage = target.getAttribute ("number") ;
	_obj.doRefreshPagesCount (_obj) ;
	_obj.doGetBodyData () ;
}

function DataGrid_doShowProcessingMessage(_messageText) {
    
	this.message.innerHTML = _messageText ;
	this.message.style.display = "block" ;
}

function DataGrid_doHideProcessingMessage() {
    
	this.message.innerHTML = "" ;
	this.message.style.display = "none" ;
}

function DataGrid_doRowClick(_evt, _obj, _activeRow) {
    
    //
    var target;
    if(_evt) {
	    target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ; 
	}

	if (_obj.activeRow) {
	    jQuery(_obj.activeRow).removeClass('active');
	}
	
	jQuery(_obj.placeholder).find("tr.active").removeClass('active');
	
	_obj.activeRow = _activeRow ;
	jQuery(_obj.activeRow).addClass('active');
	_obj.activeRowId = _activeRow.rowId ;
	_obj.activeRowHiddenValue = _activeRow.hiddenVal;

	if (_obj.onRowClick) {
		_obj.onRowClick () ;
	}
}

function DataGrid_doRowDoubleClick (_evt, _obj, _activeRow) {
    //
    var target;
    if(_evt) {
	    target = (_obj.browser == "Explorer") ? _evt.srcElement : _evt.target ; 
	}
	if (_obj.onRowDoubleClick) {
		_obj.onRowDoubleClick () ;
	}
}

function doMakeFilterDiv(obj_grid, area) {
    
	//return;
    var d = document.createElement("div");
    d.id = area + "divFilter";
    d.style.classname = 'divFilter';
    d.style.position='absolute';
    d.style.left = '320px';
    d.style.top = '320px';
    d.style.width = '490px';
    d.style.zIndex = '10';
    d.style.display = 'block';
    d.style.backgroundColor = 'white';
    d.style.padding = '20px';
    d.style.textAlign = 'center';
    d.style.border = '1px solid #898FB1';
    d.style.display = 'none';
//    var tableFilter = document.createElement ("table");
//    var row = tableFilter.insertRow(0) ;
//    var cell = document.createElement ("TD");
//    cell.innerHTML = "Поле";
//    row.appendChild (cell) ;
//    cell = document.createElement ("TD");
//    cell.innerHTML = "Действие";
//    row.appendChild (cell) ;
//    cell = document.createElement ("TD");
//    cell.innerHTML = "Значение";
//    row.appendChild (cell) ;
//    d.appendChild(tableFilter);
    //
    d.innerHTML = GetTableField(obj_grid, area);
    //
    document.body.appendChild(d);
    //jQuery(".dgContainerFooter", this.footer).append("<div class = 'Filter'></div>");
//    jQuery("#" + area + " .dgContainerFooter").append("<div class = 'Filter'></div>");
	
	
    //*** jQuery(".dgFilter", obj_grid.footer).append("<input class='btnFilterShow' style='backgroung-color:white; background-image:url(images/butdec.gif);width:12px;height:8px;' type = 'button' value = ''/>");
    //
//    jQuery(".Filter", obj_grid.footer).append("<label class='stringWhereLabel' style='float:none;'></label><input class='ClearFilter' style='border: 1px solid #000000' style='float:none;display:inline;margin-top:5px;' type='button' value='Очистить фильтр'/>");
    
    //alert("&nbsp;&nbsp;&nbsp;&nbsp;<input class='btnFilterShow' style='border:1px solid black;' type = 'button' value = 'Фильтр'/>");
    
	/***
    jQuery("#" + area + " .btnFilterShow").click(function(){
	    jQuery("#" + area + "divFilter").css('display', 'block');
	});
	***/
	
//	jQuery("span.dgFilter", this.footer).bind("click", {}, function(){
//	    jQuery("#" + area + "divFilter").css('display', 'block');
//	});
	
//    jQuery("span.dgFilter", obj_grid.footer).click(function(){
//	    jQuery("#" + area + "divFilter").css('display', 'block');
//	});
//	
//	jQuery("#" + area + "divFilter .btnFilterHide").click(function(){
//	    jQuery("#" + area + "divFilter").css("display", "none");
//	});
//	        
//	jQuery("#" + area + "divFilter .btnUseFilter").click(function(){            
//	    jQuery("#" + area + "divFilter").css("display", "none");
//	});
//	       
//	jQuery("#" + area + "divFilter .btnUseFilter").click(function(){
//	    if(UseFilter(area, obj_grid)) {
//	        jQuery("#" + area + "divFilter").css("display", "none");
//	        jQuery("#" + area + " .Filter").css("display", "block");	    
//	    
//	    
//	        var con = jQuery("div.dgContainerFooter");
//	        jQuery("#" + area + " .dgContainerFooter").css("height", "55px");
//	        jQuery("#" + area + " .dgContainer").css("height", con.offsetHeight);
//	    }
//	});
//	        
//	jQuery("#" + area + " .ClearFilter").click(function(){
//	    obj_grid.doUpdateWhereClause("");
//	    jQuery("#" + area + " .stringWhereLabel").css("display", "none");
//	    jQuery("#" + area + " .Filter").css("display", "none");
//	    jQuery("#" + area + " .dgContainerFooter").css("height","25px");
//	    jQuery("#" + area + " .dgContainerFooter").css("margin-top","0px");
//	    jQuery(".tableFilter input").val("");
//	    jQuery(".tableFilter select").val("");
////	    var HeightArea = jQuery("#" + area).attr("offsetHeight");
////	    var topSplit = jQuery("#" + area).attr("top");
////	    jQuery("#" + area).css("height",HeightArea-20);
////	    jQuery("div.dgContainerFooter").css("height", "15px");
////	    jQuery("#" + area + "#SplitterHorizontal").css("top", topSplit-50);
//	});
}

function doGetJSon(obj_grid) {
    
        obj_grid.ParamsValue["OnlyHead"] = '1';
        var myjson = null;
    	jQuery.ajax({
		data: {
		    action: 'getheader', 
		    datasourcename: obj_grid.datasourceName, 
		    datasourcetype: obj_grid.datasourceType,
		    paramsname: ForEach(obj_grid.ParamsName, ','), 
		    paramstype: ForEach(obj_grid.ParamsType, ','),
		    paramsvalue: ForEach(obj_grid.ParamsValue, ','),
		    stamp: GetTimeStamp(),
		    onlyhead: '1'
		},
		type: "get",
		async: false,
		cache: false,
		url: obj_grid.url,
		dataType: "json",
		success: function(json){
			//
			myjson = json;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//
			alert('Ошибка получения информации. База данных Премии не доступна');
			//alert("Ошибка получения информации. База данных недоступна.");
			return false;
		}
	    });
	    
	    return myjson;
	}

	function GetTableField(obj, area) {
	    
	    var html = "";
	    var newJson = doGetJSon(obj);
	    html += "<table class='tableFilter'>";
	    html += "<tr><td>Поле</td><td>Действие</td><td>Значение</td></tr>";
	    //
	    for (var key in newJson[0]) 
	    {
            if(key.toUpperCase() != "ID")
            {
                obj.FieldsName[key] = newJson[0][key];                
                html += "<tr><td>";
                html += "<label>" + newJson[0][key].split("|")[0] + "</label></td><td>";
                html += "<select id = '" + area + key + "select' class = '" + key + "selectClass' onchange=selectEffectChange('" + key + "',this," + area + ") style='width:100px;'>";
                html += "<option value=''></option>";
                html += "<option value='equal'>равен</option>";
                html += "<option value='like'>содержит</option>";
                //html += "<option value='between'>между</option>";
                //html += "<option value='from'>больше</option>";
                //html += "<option value='to'>меньше</option>";
                html += "</select>"
                html += "</td><td>";
                html += "<div class = '" + key + "divBetweenFilter' style = 'display:none;'>";
                html += "<table cellpadding='0' cellspacing='3'><tr><td>с</td><td>";
                html += "<input class = '" + key + "fromFilter' style='width:130px;border:1px solid #000;'/>";
                html += "</td></tr><tr><td>до</td><td>";
                html += "<input class = '" + key + "toFilter' style='width:130px;border:1px solid #000;'/>";
                html += "</td></tr></table>"
                html += "</div>";
                html += "<div class = '" + key + "divLikeFilter' style='width:100%; display:none;display:block;border:1px solid #000;'>";
                html += "<input class = '" + key + "likeFilter'/>";
                html += "</div>";
                html += "</td></tr>";
            }
	    }
	    html += "</table>";
	    html += "<button class='btnUseFilter buttonImage' style='background-color:#ffffff;margin-top:20px;'>Применить</button>&nbsp;&nbsp;"; 
	    html += "<button class='btnFilterHide buttonImage' style='background-color:#ffffff;margin-top:20px;'>Закрыть</button>&nbsp;&nbsp;"; 
	    
	    html = html;
        return html;
	}

	function selectEffectChange(key, obj, area) {
	    
	    switch (obj.value){
	        case "equal": {
	            jQuery("#" + area.id + "divFilter ." + key + "divBetweenFilter").css("display", "none");
	            jQuery("#" + area.id + "divFilter ." + key + "divLikeFilter").css("display", "block");
	            break;
	        }
	        case "like": {
	            jQuery("#" + area.id + "divFilter ." + key + "divBetweenFilter").css("display", "none");
	            jQuery("#" + area.id + "divFilter ." + key + "divLikeFilter").css("display", "block");
	            break;    
	        }
	        case "between": {
	            jQuery("#" + area.id + "divFilter ." + key + "divBetweenFilter").css("display", "block");
	            jQuery("#" + area.id + "divFilter ." + key + "divLikeFilter").css("display", "none");
	            break;    
	        }
	        case "from": {
	            jQuery("#" + area.id + "divFilter ." + key + "divBetweenFilter").css("display", "none");
	            jQuery("#" + area.id + "divFilter ." + key + "divLikeFilter").css("display", "block");
	            break;    
	        }
	        case "to": {
	            jQuery("#" + area.id + "divFilter ." + key + "divBetweenFilter").css("display", "none");
	            jQuery("#" + area.id + "divFilter ." + key + "divLikeFilter").css("display", "block");
	            break;    
	        }   
	    }
	}

	function UseFilter(_area, _obj_grid) {
	    
	    var wherepartrus = "";
	    var wherepart = "";
	    var _key = "";
	    var flag = true;
	    //
	    //alert("#" + _area + "divFilter" + " .tableFilter");	    
	    jQuery("#" + _area + "divFilter" + " .tableFilter").find("select").each(function(){
            
            _key = this.id;
            _key = _key.substring(_area.length,_key.length-6);
            //alert(_key);
            if(this.value != "")
            {
                flag = GetWherePartForField(_area, _key);
                wherepart += GetWherePartForField(_area, _key) + " and ";
                wherepartrus += GetWherePartRusForField(_area, _key, _obj_grid) + " ; ";
            }
        });
        if(!flag) { 
            alert("Введена длинная строка поиска. Попробуйте оптимизировать поиск.");
            return false; }        
        wherepart += " 7 = 7 ";        
        //jQuery("#" + _area + " .stringWhereLabel").attr("innerText","Фильтр: " + wherepart.substring(0,wherepart.length-11));
        jQuery("#" + _area + " .stringWhereLabel").attr("innerText","Фильтр: " + wherepartrus);

	    _obj_grid.ParamsValue['OnlyHead'] = '0'; 
	    _obj_grid.OnlyHead = '0'; 
	    _obj_grid.doUpdateWhereClause(wherepart);
	    _obj_grid.whereString = wherepart;
        _obj_grid.pageNum = 1;
		_obj_grid.doGetTableData();
        jQuery("#" + _area + " .stringWhereLabel").css("display", "inline");
	    jQuery("#" + _area + "divFilter .ClearFilter").css("display", "inline");

	    jQuery("#" + _area + "divFilter").css("display", "none");
	    jQuery("#" + _area + " .dgContainerFooter").css("height","25px");
//	    if(_obj_grid.isMainPage == "1") {
//	        jQuery("#" + _area + " .dgContainerFooter").css("margin-top","-30px");
//	    }
        return true;         
	}

	function GetWherePartForField(_area, _key) {
	    
	    var key = _key;
	    var id = _key;
	    var str = "";
	    if(jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value")) {
	        if(jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value").length > 30) {	        
	        return false;
	        }
	    }
	    if(jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value")) {
	        if(jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value").length > 30) {	        
	        return false;
	        }
	    }
	    if(jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value")){
	        if(jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value").length > 30) {	            
	            return false;
	        }
	    }
	    var inpLikeVal = jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value").replace(/'/g, "");
	    var inpFromVal = jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value").replace(/'/g, "");
	    var inpToVal = jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value").replace("'", ""); //document.getElementById(id + "toFilter");
	    var selVal = jQuery("#" + _area + _key + "select").attr("value");//document.getElementById(id + "selectFilterEffect");
	    //var selfield = document.getElementById(id + "selectFilterField").className;
	    //alert(jQuery("#" + _area + _key + "select").attr("value"));
	    switch (selVal){
	        case "equal": {
	            if(inpLikeVal != "")
	                str = id + " = '" + inpLikeVal + "'";
	            break;
	        }
	        case "like": {
	            if(inpLikeVal != "")
	                str = id + " like '%" + inpLikeVal + "%'";
	            break;
	        }
	        case "between": {
	            if((inpFromVal != "")||(inpToVal == ""))
	                str = id + " > '" + inpFromVal + "' and " + id + " < '" + inpToVal + "' ";
	            break;    
	        }
	        case "from": {
	            if(inpLikeVal != "")
	                str = id + " > '" + inpLikeVal + "'";
	            break;    
	        }
	        case "to": {
	            if(inpLikeVal != "")
	                str = id + " < '" + inpLikeVal + "'";
	            break;    
	        }   
	    }
	    if(str == "") str = " 1 = 1 ";
	    return str;
	}

	function GetWherePartRusForField(_area, _key, _obj) {
	    
	    var key = _key;
	    var id = _key;
	    var str = "";
	    var grid_obj =  jQuery("#" + _area + " .dgContainer");
	    if(jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value")) {
	        if(jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value").length > 30) {	        
	        return false;
	        }
	    }
	    if(jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value")) {
	        if(jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value").length > 30) {	        
	        return false;
	        }
	    }
	    if(jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value")){
	        if(jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value").length > 30) {	            
	            return false;
	        }
	    }
	    var inpLikeVal = jQuery("#" + _area + "divFilter ." + _key + "likeFilter").attr("value").replace("'", "");
	    var inpFromVal = jQuery("#" + _area + "divFilter ." + _key + "fromFilter").attr("value");
	    var inpToVal = jQuery("#" + _area + "divFilter ." + _key + "toFilter").attr("value"); //document.getElementById(id + "toFilter");
	    var selVal = jQuery("#" + _area + _key + "select").attr("value");//document.getElementById(id + "selectFilterEffect");
	    //var selfield = document.getElementById(id + "selectFilterField").className;
	    //alert(jQuery("#" + _area + _key + "select").attr("value"));

	    switch (selVal){
	        case "equal": {
	            if(inpLikeVal != "")
	                str = _obj.FieldsName[id] + " равно '" + inpLikeVal + "'";
	            break;
	        }
	        case "like": {
	            if(inpLikeVal != "")
	                str = _obj.FieldsName[id] + " содержит '" + inpLikeVal + "'";
	            break;
	        }
	        case "between": {
	            if((inpFromVal != "")||(inpToVal == ""))
	                str = _obj.FieldsName[id] + " больше '" + inpFromVal + "' и " + _obj.FieldsName[id] + " меньше '" + inpToVal + "' ";
	            break;    
	        }
	        case "from": {
	            if(inpLikeVal != "")
	                str = _obj.FieldsName[id] + " больше '" + inpLikeVal + "'";
	            break;    
	        }
	        case "to": {
	            if(inpLikeVal != "")
	                str = _obj.FieldsName[id] + " меньше '" + inpLikeVal + "'";
	            break;    
	        }   
	    }
	    if(str == "") str = " 1 = 1 ";
	    return str;
	}

	function DataGrid_doAddParameter(name, type, value) {
	    
	    this.ParamsName[name] = name;
	    this.ParamsType[name] = type;
	    this.ParamsValue[name] = value.replace(",", "^");
	}

	function DataGrid_doDelPress(obj) {
	    
        obj.click();
    }

    function WorkWithKeyBoard(evt, obj) {
        
        var key = getKey(evt);        
        //alert(key);
        switch (key) {
            case 38:
                var isActiveRow = jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr.active");
                if(isActiveRow.prev().length > 0) {                    
                    obj.activeRow = isActiveRow[0];
                    jQuery(obj.placeholder).find(".dgContainerBody")[0].scrollTop = isActiveRow.prev()[0].offsetTop;
                    jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr").not(isActiveRow.prev()).removeClass("active");
                    isActiveRow.prev().addClass("active");
                    obj.doRowClick(evt, obj, jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr.active")[0]);
                }
	            break;
	        case 40:
	            var isActiveRow = jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr.active");
                if(isActiveRow.next().length > 0) {                    
                    obj.activeRow = isActiveRow[0];
                    jQuery(obj.placeholder).find(".dgContainerBody")[0].scrollTop = isActiveRow.next()[0].offsetTop;
                    jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr").not(isActiveRow.next()).removeClass("active");
                    isActiveRow.next().addClass("active");
                    obj.doRowClick(evt, obj, jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr.active")[0]);
                }
	            break;
	        case 13: //
	            if(obj.addButton != null) obj.addButton.click();
	            //obj.doRowClick(evt, obj, jQuery(obj.placeholder).find("." + obj.CLASS_DG_TABLE + " tr.active")[0]);
	            break;
	        default:	            
	            break;
	    }
    } 
