﻿// Tob beta 0.981
// 100526

function Tob(params){
	//defaults:
	this.name=''; //!!! WARNING :: to powinna byc nazwa instancji obiektu Tob ktory jest globalny. inaczej Tob nie bedzie dzialal
	this.caption='defCap';
	this.run='';
	this.fetchCounter=0;
	this.params=[];
	this.page=1;
	this.scope=25;//25
	this.tab=undefined;
	this.tabId=undefined;
	this.order="ASC";
	this.orderBy="";
	this.prepared=false; // czy tabela zostala juz przygotowana
	this.cols=params.cols;
	this.total=0;
	this.headerTab;
	this.fillWidth=true; // czy ma zajac 100% szerokosci
	this.autoFetch=false; // czy ladowac dane odrazu po inicjalizacji obiektu - automatycznie
	this.sortArr=new Array();
	this.uniVals=undefined; // tablica wartosci unikatowych kolumn do filtracji
	this.filterVals=undefined; // tablica wartosci wybranych do filtrowania ( na podstwie wartosci z powyszej tab )
	this.searchVals=undefined;
	this.rowIdColNum = 0; // numer indexu kolumny z tablicy this.cols, ta kolumna powinna zawierac unikatowe wartosci - zazwyczaj idiki pobrane z  bazy
	this.buttons = params.buttons;
	this.btnEls=undefined; // elementy guzikow na dole
        this.btnEls2=undefined; // elementy guzikow na gorze
        this.btnsPosition = 3; // pozycje guzików 1: dol; 2: gora; 3 dora i dol;
	this.selectedRowIds=new Array();
	this.selectedRowVals=new Array();
	this.selectMultiple=false; // czy mozna zaznaczac wiele wiersz na raz
	this.fetchedData=undefined; // dane jednej karty (aktualny widok tabeli) surowy json
	this.dataOb = {}; // dane jednej karty (aktualny widok) w postaci tablicy z kluczem rowID,colname 
	this.onRowSelect = function(p){}; // puste funkcje ktore nalezy nadpisac w razie potrzeby. przekazywany do nich param p to id zaznaczonego wiersza
	this.onRowDeselect = function(p){};
	this.onAfterFetch = function(){}; // funkcja wykonywana po zaciagnieciu danych do toba
	this.sepThead=false; // naglowek w osobnej tabeli
	this.tobWidth=undefined;
	this.selectAllColumn="id"; // kolumna ktora chcemy zaznaczyc
	this.csvFileName= undefined;
	this.csv = params.csv; // czy generowac csv
	this.formHasChanged=false; // czy zmienilo sie cos w formularzu toba?
	this.formCheckWarning=false; // czy sprawdzac zmiany w formularzu (onchange) przy zmianie strony
	if(params.formCheckWarning!=undefined)this.formCheckWarning=params.formCheckWarning;
	if(params.scope!=undefined)this.scope = params.scope;
	if(params.csvFileName!=undefined)
		this.csvFileName = params.csvFileName;
	
	
	if(params.onAfterFetch != undefined)
		this.onAfterFetch = params.onAfterFetch;	
	if(params.raport==true)
		this.raport=true;
	this.raportName=params.raportName;
	if(params.tobWidth!=undefined)
		this.tobWidth=params.tobWidth;
	if(params.selectMultiple!=undefined){
		this.selectMultiple=params.selectMultiple;
	}
	this.doZebraTab=params.zebraTab;
	if(params.sortArr!=undefined)
		this.sortArr=params.sortArr;
	if(params.fillWidth!=undefined)
		this.fillWidth=params.fillWidth;
		//alert(this.fillWidth);	
	this.selectableRows=params.selectableRows;	
	this.css={
		tobTabClass:"tobTab",
		tobHeaderTabClass:"tobHeaderTab",
		ascSortMarkerClass:"ascSortMarker",
		descSortMarkerClass:"descSortMarker",
		pageStatClass:"pageStat",
		buttonClass:"tobBtn",
		mainDivClass:"tobMainDiv"
		
	};
	this.markers={
		"red"	:	"templates/default/img/flag_red.png",
		"green"	:	"templates/default/img/flag_green.png",
		"blue"	:	"templates/default/img/flag_blue.png",
		"bolb"	:	"templates/default/img/bolb.png"
	};
	
	if(params.name!=undefined)
		this.name=params.name;
	else{
		alert('Tob error!\npole name nie może być puste');
	}	
	if(params.rowIdColNum!=undefined)
		this.rowIdColNum=params.rowIdColNum;
	
	if(params.caption!=undefined)
		this.caption=params.caption;
	if(params.run!=undefined)
		this.run=params.run;
	if(params.params!=undefined)				
		this.params=params.params;
	if(params.tabId!=undefined){
		this.tabId=params.tabId;
		if(document.getElementById(params.tabId)!=undefined)
			this.tab=getElById(params.tabId);
		else
			return;
	}	
	if(params.orderBy!=undefined)
		this.orderBy=params.orderBy;
	
	if(params.order!=undefined)
		this.order=params.order;
	if(params.autoFetch!=undefined)	
		this.autoFetch=params.autoFetch;
	if(params.onRowSelect!=undefined)
		this.onRowSelect=params.onRowSelect;	
	if(params.onRowDeselect!=undefined)
		this.onRowDeselect=params.onRowDeselect;
	
	this.hidePageStat = params.hidePageStat; // czy ukryc opcje pod tabela
	this.hideCaption = params.hideCaption;
		
	this.adminGroups = ["SUPERADMIN" , "ADMIN"];	// dla guzikow opcji - std. jesli wl. restriction to tylko dla tych userow, opcjonalnie podajemy tablice restrictToUserGroups:[...,...,...]
		
	this.lock = function(){
		//jak disable/enable 
		// dodaje przeslaniajacy polprzezroczysty div 
		tabOverlay=getElById(this.tabId+"_overlay");
		tabOverlay.style.display='block';
	}	
	this.unlock = function(){
		tabOverlay=getElById(this.tabId+"_overlay");
		tabOverlay.style.display='none';
	}
	this.clear = function(){
		var mainTab = document.getElementById(this.tabId);
		while(mainTab.tBodies[0].rows.length>0)
		mainTab.tBodies[0].deleteRow(-1);	
		
	
	}
	//przygotuj tabele i inne potrzebne tagi	
	this.prepTab = function(){
		//dodaj div otaczajacy tabele
		var scrollDiv=document.createElement("DIV");
		//scrollDiv.style.overflowY="scroll";
		//scrollDiv.style.position="relative";
		this.tab.className=this.css.tobTabClass;
		
		var mainDiv=document.createElement("DIV");
		mainDiv.className=this.css.mainDivClass;
		mainDiv.id=this.css.mainDivClass+"_"+this.tabId;
		var pageStatDiv=document.createElement("DIV");
		var tabOverlay = document.createElement("DIV");
		tabOverlay.style.zIndex='99'; // aby przyslonic warstwe okienek filtracji
		//mainDiv.style.background="white";
		mainDiv.style.position='relative';
		tabOverlay.id=this.tabId+"_overlay";
		tabOverlay.style.position='absolute';
		tabOverlay.style.left=0;
		tabOverlay.style.top=0;
		tabOverlay.style.height="100%";
		tabOverlay.style.width="100%";;
		
		tabOverlay.style.opacity=0.8;
		tabOverlay.style.fontSize="25px";
		
		tabOverlay.innerHTML="<table style='width:100%; height:100%; text-align:center; background:black'>"+
				"<tr style='background:none;'>"+
					"<td>"+
					"<img src='templates/default/img/spin_loader.gif'>"+
					"</td>"+
				"</tr>"+
				"</talbe>";
		tabOverlay.style.display='none';
		
		
		//dodanie tabeli
		this.tab.parentNode.insertBefore( mainDiv,this.tab);
		
		
		
		mainDiv.appendChild(this.tab);
		
		//dodadj scroll
		this.tab.parentNode.insertBefore( scrollDiv,this.tab);
		mainDiv.removeChild(this.tab);
		scrollDiv.appendChild(this.tab);
		
		
		
		var headDiv=document.createElement("DIV");
		var headTab=document.createElement("table");
		
		
		headTab.className=this.css.tobHeaderTabClass;
		headDiv.appendChild(headTab);

		if(this.tobWidth!=undefined)
			headTab.style.width=this.tobWidth+"px";
		// dodaj naglowki
		
		if(this.cols!=undefined){
		
		
			
				//dodatkowy thead dla glownej tabeli
				if(!this.sepThead){
						var thead2=this.tab.createTHead();
					//var thead=this.tab.createTHead();
					var hRow2=thead2.insertRow(-1);
					for(var i=0; i< this.cols.length; i++){
						if(this.cols[i]!=undefined && this.cols[i].hidden!=true){
							var th2=document.createElement('th');
							
							th2.style.width=this.cols[i].width+"px";
							var colSortMarker=document.createElement("DIV");
							colSortMarker.id=this.name+"_"+this.cols[i].name+"_sortMarker";
							
							var divLab=document.createElement('DIV');
							//th.innerHTML=this.cols[i].display;
							th2.appendChild(colSortMarker);
							if(this.cols[i].filterable==true){
								divLab.innerHTML+="<div class='filterBtn' onclick=\""+this.name+".makeFilterBox(event,'"+this.cols[i].name+"' )\"></div>";	
							}
							
							//divLab.innerHTML+=this.cols[i].display;
							if(this.cols[i].display!=undefined ){ // DODANIE NAGLOWKOW
								divLab.innerHTML+=this.cols[i].display; 
							}else{
								divLab.innerHTML+=this.cols[i].name;
							}
							th2.appendChild(divLab);				
							hRow2.appendChild(th2);	
							//th.setAttribute('cName', this.cols[i].name);
							if(this.cols[i].sortable==true){
								var sortCall=this.name+".changeSort('"+this.cols[i].name+"')";
								th2.setAttribute("sortCall", sortCall);
								$(th2).css('cursor', 'pointer');
								 								
								$(th2).click(function(){
									//alert($(this).attr('sortCall'));
									eval($(this).attr('sortCall'));
								});
							}	
							if(this.cols[i].search==true)
								//th2.innerHTML+="<strong>S</strong>";	
								divLab.innerHTML+="<div class='searchBtn' onclick=\""+this.name+".makeSearchBox(event,'"+this.cols[i].name+"' )\"></div>";	
						}
					}
				}else{
					var thead=headTab.createTHead();
			//var thead=this.tab.createTHead();
			var hRow=thead.insertRow(-1);
			for(var i=0; i< this.cols.length; i++){
				if(this.cols[i].hidden!=true){
					var th=document.createElement('th');
					
					th.style.width=this.cols[i].width+"px";
					var colSortMarker=document.createElement("DIV");
					colSortMarker.id=this.name+"_"+this.cols[i].name+"_sortMarker";
					
					var divLab=document.createElement('DIV');
					//th.innerHTML=this.cols[i].display;
					th.appendChild(colSortMarker);
					if(this.cols[i].filterable==true){
						divLab.innerHTML+="<div class='filterBtn' onclick=\""+this.name+".makeFilterBox(event,'"+this.cols[i].name+"' )\"></div>";	
					}
					
					if(this.cols[i].display!=undefined ){ // DODANIE NAGLOWKOW
						divLab.innerHTML+=this.cols[i].display;
					}else{
						divLab.innerHTML+=this.cols[i].name;
					}
					
					th.appendChild(divLab);				
					hRow.appendChild(th);	
					//th.setAttribute('cName', this.cols[i].name);
					th.setAttribute("onclick", this.name+".changeSort('"+this.cols[i].name+"')");
				}
			}
					
				}	
		
			
		}
				
		
		//dodaj caption i csv btn
		var csvBtn="";
		if(this.csv == true)
			csvBtn+="<a href='javascript:"+this.name+".toCSV()' class='exportCsv' title=\"header=[] body=[Generuj plik CSV] fade=[on]\"></a>";
		
		if(this.caption!=undefined && this.hideCaption!=1){
			tableCaption(headTab, this.caption+csvBtn);
		}
		
		if(this.buttons!=undefined){
			this.btnEls=new Array();
                        this.btnEls2=new Array();
			for(var i=0;i<this.buttons.length; i++){
				
					this.btnEls[i]=document.createElement('button');
                                        this.btnEls2[i]=document.createElement('button');
					if(this.buttons[i].label!=undefined){
                                            this.btnEls[i].innerHTML=this.buttons[i].label;
                                            this.btnEls2[i].innerHTML=this.buttons[i].label;
                                        }
					this.btnEls[i].className=this.css.buttonClass;
                                        this.btnEls2[i].className=this.css.buttonClass;
					if(this.buttons[i].hint!=undefined){
                                            this.btnEls[i].setAttribute("title", "header=[Pomoc] body=["+this.buttons[i].hint+"] fade=[on]" );
                                            this.btnEls2[i].setAttribute("title", "header=[Pomoc] body=["+this.buttons[i].hint+"] fade=[on]" );
                                        }
						
				if(this.buttons[i].restricted==undefined || this.buttons[i].restricted==0){	// jesli guzik publiczny
                                    if (this.btnsPosition & 2) {
                                        headDiv.appendChild(this.btnEls[i]);
                                    }
                                    if (this.btnsPosition & 1) {
                                        mainDiv.appendChild(this.btnEls2[i]);
                                    }
				}else{ // guzik z restrykcja

					if(modWorkMode=="e"){ //modWorkMode tworzone przez klase Module
                                              if (this.btnsPosition & 2) {
                                                    headDiv.appendChild(this.btnEls[i]);
                                              }
                                              if (this.btnsPosition & 1) {
                                                    mainDiv.appendChild(this.btnEls2[i]);
                                              }
					}

//                                      stara wersja restrykcji
//					if(this.buttons[i].restrictToUserGroups!=undefined){
//						// jesli sa przypisane do guzika grupy userow to uzych ich
//						if($.inArray(SKEL_USER_GROUP, this.buttons[i].restrictToUserGroups)>-1){
//							if (this.btnsPosition & 2) {
//                                                            headDiv.appendChild(this.btnEls[i]);
//                                                        }
//                                                        if (this.btnsPosition & 1) {
//                                                            mainDiv.appendChild(this.btnEls2[i]);
//                                                        }
//						}
//					}else if($.inArray(SKEL_USER_GROUP, this.adminGroups)>-1){ // SKEL_USER_GROUP - tworzona w klasie Skeleton
//						//domyslne grupy adminow
//						// dostepny dla zalogowanego usera
//						if (this.btnsPosition & 2) {
//                                                    headDiv.appendChild(this.btnEls[i]);
//                                                }
//                                                if (this.btnsPosition & 1) {
//                                                    mainDiv.appendChild(this.btnEls2[i]);
//                                                }
//					}
				}
			}

			
//			for(var i=0;i<this.buttons.length; i++){
//				
//				
//				var fun=this.buttons[i].onclick;
//							
//				this.btnEls[i].onclick=function(){
//					alert(fun);
//						fun.call(this, ['abc'])
//				};
//			} 
			//dodanie guzikow...
			
			var srids = this.selectedRowIds; 
			var instanceName=this.name;
		
			if(this.buttons[0]!=undefined){
				var fun0=this.buttons[0].onclick
				this.btnEls[0].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun0.call(this,arr);
				}
                                this.btnEls2[0].onclick = this.btnEls[0].onclick;
			}
			if(this.buttons[1]!=undefined){
				var fun1=this.buttons[1].onclick
				this.btnEls[1].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun1.call(this,arr);
				}
                                this.btnEls2[1].onclick = this.btnEls[1].onclick;
			}
			if(this.buttons[2]!=undefined){
				var fun2=this.buttons[2].onclick
				this.btnEls[2].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun2.call(this,arr);
				}
                                this.btnEls2[2].onclick = this.btnEls[2].onclick;
			}
			if(this.buttons[3]!=undefined){
				var fun3=this.buttons[3].onclick
				this.btnEls[3].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun3.call(this,arr);
				}
                                this.btnEls2[3].onclick = this.btnEls[3].onclick;
			}
			if(this.buttons[4]!=undefined){
				var fun4=this.buttons[4].onclick
				this.btnEls[4].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun4.call(this,arr);
				}
                                this.btnEls2[4].onclick = this.btnEls[4].onclick;
			}
			if(this.buttons[5]!=undefined){
				var fun5=this.buttons[5].onclick
				this.btnEls[5].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun5.call(this,arr);
				}
                                this.btnEls2[5].onclick = this.btnEls[5].onclick;
			}
			if(this.buttons[6]!=undefined){
				var fun6=this.buttons[6].onclick
				this.btnEls[6].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun6.call(this,arr);
				}
                                this.btnEls2[6].onclick = this.btnEls[6].onclick;
			}
                        if(this.buttons[7]!=undefined){
				var fun7=this.buttons[7].onclick
				this.btnEls[7].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun7.call(this,arr);
				}
                                this.btnEls2[7].onclick = this.btnEls[7].onclick;
			}
                        if(this.buttons[8]!=undefined){
				var fun8=this.buttons[8].onclick
				this.btnEls[8].onclick = function(){
					eval("var arr="+instanceName+".selectedRowIds");
					fun8.call(this,arr);
				}
                                this.btnEls2[8].onclick = this.btnEls[8].onclick;
			}
			if(this.buttons[9]!=undefined){
				alert("UWAGA\nTOB obsługuje aktualnie 8 Buttonów, jeśli potrzeba więcej - trzeba dopisać obsługę.");
			}
			
		}
		
		
		
		this.prepared=true;
		
		
		//mainDiv.appendChild(prevPageBtn);
		//mainDiv.appendChild(nextPageBtn);
		pageStatDiv.id=this.tabId+"_pageStat";
		pageStatDiv.className=this.css.pageStatClass;
		if(this.hidePageStat!=1)
			mainDiv.appendChild(pageStatDiv);
		
		mainDiv.insertBefore(headDiv,scrollDiv);
		mainDiv.appendChild(tabOverlay);
		//mainDiv.className="drsElement";
		
		if(this.fillWidth){
			if(mainDiv.offsetWidth==0)
				mainDiv.style.width='859px';
			else
				mainDiv.style.width=mainDiv.offsetWidth+"px";
                                //mainDiv.style.width='90%';
			///headDiv.style.width=mainDiv.offsetWidth+"px";
			headDiv.style.width=mainDiv.style.width;
			headTab.style.width=mainDiv.style.width;
			///this.tab.style.width=mainDiv.offsetWidth+"px";
			this.tab.style.width=mainDiv.style.width;
			//alert(mainDiv.style.width);
		}else{
			if(this.tobWidth!=undefined)
				mainDiv.style.width=this.tobWidth+"px";
		}
		
		
		// pobierz unikatowe wartosci kolumn do filtracji...
		// ustal dla jakich kolumn pobrac unikaty...
		var filterColNames="";
		var sep=",";
		var countFilterable=0;
		for(var i=0; i<this.cols.length; i++){
			if(this.cols[i]!=undefined && this.cols[i].filterable==true){
				if(countFilterable>0)filterColNames+=sep;
				filterColNames+=this.cols[i].name;
				countFilterable++;
			}	
				
		}
		if(countFilterable>0){
			var nm=this.name;
			var par={
				run: this.run+"_unique",
				autoParams: this.params.length,
				"filterColNames":filterColNames
			};
			for(var i=0;i<this.params.length; i++){
				par['param'+(i+1)]=this.params[i];
			}
			advAJAX.post({
				parameters:par
				,
				onSuccess:function(obj){
					//eval("var r=("+obj.responseText+")");
					eval(nm+".uniVals="+obj.responseText);				
				
				},
				
			onLoading:function(obj){ 
			 	disableForms();
		 		AJAX_IN_PROGRESS=true;
		 	},
		 	onComplete:function(obj){
		 		enableForms();
		 		AJAX_IN_PROGRESS=false;
		 	}
			});	
		}		
		
		
		this.headerTab=headTab;
		this.updatePageStat();
	
		
	}
	this.setCaption = function(cap){
		var csvBtn="";
		if(this.csv == true)
			csvBtn+="<a href='javascript:"+this.name+".toCSV()' class='exportCsv' title=\"header=[] body=[Generuj plik CSV] fade=[on]\"></a>";
		
			tableCaption(this.headerTab, cap+csvBtn);
	}
	this.selectDeselectAllFilterChcks=function(col){
		var vbox=getElById(this.name+"_"+col+"_filterVals");
		var ac=vbox.getElementsByTagName('input');
		var newVal = !ac[0].checked;
		for(var i=0; i<ac.length; i++){
			ac[i].checked=newVal;
		}
	}	
	this.makeSearchBox = function(e,col){
		e.stopPropagation();
		if(document.getElementById(this.name+"_"+col+"_searchBox")==undefined){
			var fbox=document.createElement("DIV");
			fbox.id=this.name+"_"+col+"_searchBox";
			fbox.className='searchBox';
			fbox.style.position='absolute';
			fbox.style.left=e.pageX+"px";
			fbox.style.top=e.pageY+"px";
			fbox.style.width='220px';
			//fbox.style.height='190px';
			//fbox.style.background='white';
			//fbox.style.border='1px solid #eee';
			fbox.innerHTML+="Wyszukiwanie<br>";
			var srchInp=document.createElement("input");
			srchInp.setAttribute("type", "text");
			srchInp.id=this.name+"_"+col+"_srchText";
			fbox.appendChild(srchInp);
			

			
			
			var closeBtn=document.createElement("Button");
			var applyBtn=document.createElement("Button");
			closeBtn.innerHTML="X";
			applyBtn.innerHTML="szukaj";
			closeBtn.onclick = function(){
				document.body.removeChild(fbox);

			}
			var instanceName=this.name;
			applyBtn.onclick = function(){
				eval(instanceName+".searchTob('"+col+"')");
				
			}
			fbox.appendChild(closeBtn);
			fbox.appendChild(applyBtn);
			document.body.appendChild(fbox);
			//onkeydown='submitOnEnterKey(event, \"shiftSrchDestAsr()\")'
			srchInp.setAttribute('onkeydown',"submitOnEnterKey(event, \""+instanceName+".searchTob('"+col+"') \")"); 
			srchInp.focus();
		}		
	}		
	
	this.makeFilterBox = function(e, col){
		//alert('filtering by col '+col);
		e.stopPropagation();
		if(document.getElementById(this.name+"_"+col+"_filterBox")==undefined){
			var fbox=document.createElement("DIV");
			fbox.id=this.name+"_"+col+"_filterBox";
			fbox.className='filterBox';
			fbox.style.position='absolute';
			fbox.style.left=e.pageX+"px";
			fbox.style.top=e.pageY+"px";
			fbox.style.width='220px';
			//fbox.style.height='190px';
			//fbox.style.background='white';
			//fbox.style.border='1px solid #eee';
			fbox.innerHTML+="Filtracja kolumny<br>";
			var chckAll=document.createElement("input");
			chckAll.setAttribute("type", "checkbox");
			chckAll.setAttribute('onclick', this.name+".selectDeselectAllFilterChcks('"+col+"')");
			chckAll.setAttribute('checked', true);
			
			
			var vbox=document.createElement("DIV"); // przechowuje wartosci
			vbox.id=this.name+"_"+col+"_filterVals";
			vbox.style.height='150px';
			vbox.style.borderTop="1px solid #eee";
			vbox.style.borderBottom="1px solid #eee";
			vbox.style.overflowY='scroll';
			fbox.appendChild(chckAll);
			fbox.innerHTML+=" zaznacz/odznacz wszystkie ";
			
			

			//if(this.filterVals!=undefined && this.filterVals['a']!=undefined)
			//alert(this.filterVals['a'].indexOf('3'));
			
			for(var j=0; j<this.uniVals[col].length ; j++){
				var chch="checked"; // checkbox checked
				if(this.filterVals!=undefined){
					if(this.filterVals[col]!=undefined){
						chch="";
					 	if(this.filterVals[col].indexOf(this.uniVals[col][j]+"")!=-1){
					 		chch='checked';
					 		//alert('jest '+this.uniVals[col][j]);
					 	}	
					}	
				}
				vbox.innerHTML+="<input type='checkbox' "+chch+" value='"+this.uniVals[col][j]+"' >"+this.uniVals[col][j]+"<br>";
			}
			fbox.appendChild(vbox);
			var closeBtn=document.createElement("Button");
			var applyBtn=document.createElement("Button");
			closeBtn.innerHTML="X";
			applyBtn.innerHTML="filtruj";
			closeBtn.onclick = function(){
				document.body.removeChild(fbox);

			}
			var instanceName=this.name;
			applyBtn.onclick = function(){
				eval(instanceName+".filterTob('"+col+"')");
				
			}
			fbox.appendChild(closeBtn);
			fbox.appendChild(applyBtn);
			
			document.body.appendChild(fbox);
		}		
		
	}
	this.searchTob = function(col){
		var srcInp=getElById(this.name+"_"+col+"_srchText");
		if(!srcInp)return;
		
	//		alert(col + " "+ srcInp.value);
		var srchText=srcInp.value.trim();
		if(srchText==""){
			errInfo('Proszę wprowadzić tekst wyszukiwania.');
			return;
		}
		if(this.searchVals==undefined){
			this.searchVals={};
		}
		this.searchVals[col]=srchText;
		document.body.removeChild(srcInp.parentNode);
		this.fetch();
		this.goToPage(1);
	}
	this.filterTob = function(col){
		var vbox=getElById(this.name+"_"+col+"_filterVals");
		if(!vbox)return;
		
		var chcks=vbox.getElementsByTagName('input');
		if(this.filterVals==undefined){
			this.filterVals={};
		}	
		this.filterVals[col]=new Array();
		var countChecked=0;
		for(var i=0; i<chcks.length; i++){
			if(chcks[i].checked){
				this.filterVals[col].push(chcks[i].value);
				countChecked++;
			}
		}
		if(countChecked==0)this.filterVals[col] = undefined;
		this.page=1;
		this.fetch();
		document.body.removeChild(vbox.parentNode);
	}
	// function fetch()
	this.fetch = function(){ 
		this.formHasChanged=false;

		if(!this.prepared)
			this.prepTab();
		// ponizsze zmienne sa potrzebne, inaczej wewnatrz onSuccess nie widac pol klasy Tob
		var tb=this.tab;
		var ht=this.headerTab;
		var ordBy=this.orderBy;
		var ord=this.order;
		var cls = this.cols;
		var colWidths=undefined;
		var instanceName=this.name;
		var filtVals=""; // wartosci kolumn
		var filtCols="";
		var srchVals="";
		var srchCols="";
		var rowICN=this.rowIdColNum;
		var sepTh=this.sepThead;
		var markerColors=this.markers;
		var datob = this.dataOb;
		var doAfterFetch = this.onAfterFetch;
		var zebraTab=this.doZebraTab;
		var selectableRows=this.selectableRows;
		datob = {};
		
		if(this.filterVals!=undefined){
			var count=0;
			for(var k in this.filterVals){
				if(this.filterVals[k]!=undefined){
					if(count>0){
						filtVals+="{~}";
						filtCols+="|";
					}
						
					filtVals+=this.filterVals[k].join("|");
					filtCols+=k;
					count++;
				}
		}
			
		}
		if(this.searchVals!=undefined){
			var count=0;
			for(var k in this.searchVals){
				if(count>0){
					srchCols+="|";
					srchVals+="|";
				}
				srchCols+=k;				
				srchVals+=this.searchVals[k];
				count++;	
			}
		}	

		if(this.cols!=undefined){
			colWidths=[];
                        var count=0;
			for(var i=0;i<this.cols.length; i++){				
				if(this.cols[i]!=undefined && this.cols[i].hidden!=true){
					//alert(this.cols[i].name);
					if(this.cols[i].width!=undefined){
						//colWidths[i]=this.cols[i].width
						//alert(this.cols[i].name);
						if(this.sepThead)
							colWidths[count]=this.headerTab.getElementsByTagName('th')[count].clientWidth; // pobierz wartosci bezposrednio z szerokosci naglowkow
						else	
							colWidths.push(this.cols[i].width);
						//alert(colWidths[i]);
					}else
						colWidths.push(10);
					count++;
				}
			}
		}
		getElById(this.tabId+"_overlay").style.display='block';
		//przygotuj info o sortowaniu
		var sortCols="";
		var sortOrd="";
		for(var i = 0 ; i < this.sortArr.length; i++){
			if(i>0){
				sortCols+="|";
				sortOrd+="|";
			}
			sortCols+=this.sortArr[i].sort;
			sortOrd+=this.sortArr[i].order;
		}
		
		var par={
			run: this.run,
			autoParams: this.params.length,
			page:this.page,
			scope:this.scope,
			orderBy:sortCols,
			order:sortOrd,
			filter:filtVals,
			filterCols:filtCols,
			searchVals:srchVals,
			searchCols:srchCols
		};
		if(this.raport==true){
			par['raport']=1;
			par['raportName']=this.raportName;
		}	
		for(var i=0;i<this.params.length; i++){
			par['param'+(i+1)]=this.params[i];
		}
		var colName2Index=new Object(); // tablica  assoc : nazwa kolumny -> index kolumny(widoczny)
		for (var i=0; i<cls.length;i++){
				if(cls[i]!=undefined)
				colName2Index[cls[i].name]=i;
		}
		
		advAJAX.post({
			parameters:par,
			onSuccess:function(obj){
				//alert(obj.responseText);
				//var res=null;
				eval("var res=("+obj.responseText+")");
				eval(instanceName+".fetchedData=("+obj.responseText+");");
				
				if(tb.tBodies[0]!=undefined){
					//tb.tBodies[0].innerHTML="";
					while(tb.tBodies[0].rows.length>0)
						tb.tBodies[0].removeChild(tb.tBodies[0].childNodes[0]);
				}
				
				var data=res.data;
				var data4ops={}; // tablica assoc nazwakolumny->wartosc (tylko dla br. wiersza);
				eval(instanceName+".total="+res.total); // set total
				
				for(var i=0;i<data.length;i++){
					//alert(i+ ">"+data[i]);
					if(i+1>res.total)break;
					var rowData=[];
					var formData=[];
					var rowBg="";
					var rowSelect='0'; // standardowo nie zaznaczaj wiersza
					for(var j=0; j<cls.length; j++){
						
						//obsluga zaznaczania wierszy na podstawie kolumny binarnej
						if(cls[j].rowSelector==true){
							if(data[i][j]=='1'){ // zaznacz wiersz
								rowSelect='1';
							}
						}
						
						data4ops[cls[j].name]=data[i][j];
						if(cls[j].hidden!=true && cls[j].form!=true){
							if(cls[j].marker==true ){//&& data[i][j]=="1"
								cls[j].color;
								var hnt="";
								if(cls[j].hint!=undefined )
									hnt=" TITLE=\"header=[Pomoc] body=["+cls[j].hint+"] fade=[on]\" ";
								else if(cls[j].display!=undefined)
									hnt=" TITLE=\"header=[Pomoc] body=["+cls[j].display+"] fade=[on]\" ";
								
								if(cls[j].thumb !=undefined && cls[j].thumb=='1'){
                                                                    if (data[i][j] != "") {
									if(cls[j].link!=undefined){
										
										
										data[i][j]="<a href='"+data[i][colName2Index[cls[j].link]]+"'><img  src='"+data[i][j]+"'  style='height: 30px;'></a>";
										
									}else{
										
										data[i][j]="<span><img  src='"+data[i][j]+"' style='height: 40px;'></span>";
										
									}
                                                                    } else {
                                                                        data[i][j] = "brak obrazu";
                                                                    }

								}else{
									
									if(markerColors[cls[j].icon]!=undefined ){
										if(data[i][j]=="1")
											data[i][j]="<img "+hnt+" src='"+markerColors[cls[j].icon]+"'>";
										else if(data[i][j]=="0")
											data[i][j]="";
									}else
										alert("Tob warning: brak zdefiniowanej ikony dla "+cls[j].icon);
								}
							}else if(cls[j].marker==true && data[i][j]=="0"){
								data[i][j]="";
							}else{
								if(cls[j].hint!=undefined ){
									hnt=" TITLE=\"header=[] body=["+data[i][colName2Index[cls[j].hint]]+"] fade=[on]\" ";
									data[i][j]="<div "+hnt+">"+data[i][j]+"</div>";
								}
								
							}
							
							if(cls[j].link!=undefined){
								data[i][j]="<a href='"+data[i][colName2Index[cls[j].link]]+"'>"+data[i][j]+"</a>";
							}


							
							rowData.push(data[i][j]);
						}else if(cls[j].hidden!=true && cls[j].form==true){
							//alert(data[i]);
							//alert(data[i][colName2Index[cls[j].defaultValue]]);
							//alert(cls[j].defaultValue);
							cls[j].defaultValueParsed=data[i][colName2Index[cls[j].defaultValue]]; // utowrzenie defaultValueParsed
							formData.push(cls[j]);
						}
						
						
						
					}	
					//datob[data[i][rowICN]] = data4ops;
					eval(instanceName+".dataOb["+data[i][rowICN]+"]=("+toJSON(data4ops)+")"); 
					//alert(toJSON(data4ops));
					//data[i][rowICN] - to jest zazwyczaj id wiersza (z bazy)
					var doOnClick=undefined;
					if(selectableRows!=0){
						doOnClick="tobSelRow(this,'"+instanceName+"')";
					}
					tobAddRow(instanceName,tb,rowData,doOnClick,data[i][rowICN],colWidths,formData,data4ops,rowSelect);	
					
				}
				
				if(data.length>0){
				
				
			// skoryguj szerokosci naglowkow... po zaladowaniu danych tabela mogla sie 'rozjechac'
			if(sepTh){
				for(var j=0; j<tb.getElementsByTagName('tr').length; j++){
				var count=0;	
				for(var i =0; i<cls.length; i++){
					if(cls[i].hidden!=true){
						
							//ht.getElementsByTagName('th')[count].style.width = (tb.getElementsByTagName('tr')[0].cells[count].clientWidth-2) +"px";
	
						var headerCell=ht.getElementsByTagName('th')[count];
						var tabCell=tb.getElementsByTagName('tr')[j].cells[count];
						if(tabCell!=undefined){
							headerCell.style.width=cls[i].width+"px";
							tabCell.style.width=cls[i].width+"px";
							
							//alert(headerCell.offsetWidth+ " offsetWidthts "+tabCell.offsetWidth);
							//alert(headerCell.clientWidth + " clientWidthts "+tabCell.clientWidth);
							//ponizej korekta szerokosci
							if(headerCell.clientWidth>tabCell.clientWidth){
								tabCell.style.width=(headerCell.clientWidth-1)+"px";
								tabCell.style.background='yellow';
							}else{
								headerCell.style.width=(tabCell.clientWidth-5)+"px";
								headerCell.style.background='orange';
							}
						}else alert('undef '+i);	
	
							count++;
						
					}else alert('hidden '+i);
				}
				
				
				}
			}
				}
				
				
				if(zebraTab!=0)
					eval(instanceName+".zebraTable()");
					
				eval(instanceName+".updatePageStat();"); // set total
				eval(instanceName+".showSelectedAfterFetch();");
				eval(instanceName+".showInitialSortOrders();");
				getElById(tb.id+"_overlay").style.display='none';
				
				doAfterFetch.call(this,null); // wywolanie funkcji afterfetch
				//eval("alert("+instanceName+".fetchCounter);");
				eval(instanceName+".fetchCounter++");
			},
			onLoading:function(obj){ 
			 	disableForms();
		 		AJAX_IN_PROGRESS=true;
		 	},
		 	onComplete:function(obj){
		 		enableForms();
		 		AJAX_IN_PROGRESS=false;
		 	
		 	}
		});
		
		
	}	
	this.setParams = function(p){
		//alert('setting params '+p);
		this.params=p;
	}
	this.showSelectedAfterFetch = function(){
		if(this.selectedRowIds.length>0){
			//alert(this.tab.tBodies[0].rows.length);
			
			try{
			for(var i =0;i<this.tab.tBodies[0].rows.length; i++){
				//alert(this.tab.tBodies[0].rows[i].getAttribute('rowid'));
				if(this.selectedRowIds.indexOf(parseInt(this.tab.tBodies[0].rows[i].getAttribute('rowid'),10))!=-1){
					this.tab.tBodies[0].rows[i].className="tobSRow";
					
				}else{
					if(this.tab.tBodies[0].rows[i].className=="tobSRow"){
						this.tab.tBodies[0].rows[i].className="";
					}
					
				}	
			}
			}catch(err){
				//alert('got an err'); // w ie wystepuje czasami
			}
			
		}
	}
	this.goToPage = function(pg){
		var totalPages=Math.round(this.total / this.scope);
		if(totalPages==0 && this.total>0)
		 totalPages=1;
		 else if(this.total> totalPages*this.scope)
			totalPages++;
			
		
		if(pg<1)
			pg=1;
			
		if(pg>totalPages)
			pg=totalPages;	
		this.page=pg;
		this.fetch();
		this.updatePageStat();
	}
	this.selectAll = function (){
		var tb=this.tab;
		var filtVals=""; // wartosci kolumn
		var filtCols="";
		var srchVals="";
		var srchCols="";
		var rowICN=this.rowIdColNum;
		var sepTh=this.sepThead;
		var markerColors=this.markers;
		var instanceName = this.name;
		var sri = this.selectedRowIds;
		if(this.filterVals!=undefined){
			var count=0;
			for(var k in this.filterVals){
				if(this.filterVals[k]!=undefined){
					if(count>0){
						filtVals+="{~}";
						filtCols+="|";
					}
						
					filtVals+=this.filterVals[k].join("|");
					filtCols+=k;
					count++;
				}
		}
			
		}
		if(this.searchVals!=undefined){
			var count=0;
			for(var k in this.searchVals){
				if(count>0){
					srchCols+="|";
					srchVals+="|";
				}
				srchCols+=k;				
				srchVals+=this.searchVals[k];
				count++;	
			}
		}	

		
		getElById(tb.id+"_overlay").style.display='block';
		//przygotuj info o sortowaniu
		var sortCols="";
		var sortOrd="";
		for(var i = 0 ; i < this.sortArr.length; i++){
			if(i>0){
				sortCols+="|";
				sortOrd+="|";
			}
			sortCols+=this.sortArr[i].sort;
			sortOrd+=this.sortArr[i].order;
		}
		
		var par={
			run: this.run,
			autoParams: this.params.length,
			page:this.page,
			scope:this.scope,
			orderBy:sortCols,
			order:sortOrd,
			filter:filtVals,
			filterCols:filtCols,
			searchVals:srchVals,
			searchCols:srchCols,
			selectAll:1,
			selectAllColumn:this.selectAllColumn
			
			};
		if(this.raport==true){
			par['raport']=1;
			par['raportName']=this.raportName;
		}	
		for(var i=0;i<this.params.length; i++){
			par['param'+(i+1)]=this.params[i];
		}
		
		advAJAX.post({
				parameters:par,
				onSuccess:function(obj){
					getElById(tb.id+"_overlay").style.display='none';
					eval("var allArr=("+obj.responseText+")");
					for(var i =0; i<allArr.length; i++){
						sri[i]=parseInt(allArr[i],10);
						
					}
				
					//eval(instanceName+".selectedRowIds = ("+obj.responseText+");");
					eval(instanceName+".showSelectedAfterFetch();");
					eval(instanceName+".updatePageStat()");
					
					//wywolaj onrowselect
					eval(instanceName+".onRowSelect.call(this,null )") ;
					
				}
			}
		);
	}

	
	this.nextPage = function(){
		if(this.formCheckWarning){
			if(this.formHasChanged){
				var tn=this.name;
				ask("Wygląda na to, że dane w tabeli zostały przez Ciebie zmienione. Czy napewno chcesz przejść na następną stronę? Zmienione dane z bieżącej strony zostaną utracone.","Ostrzeżenie", function(){eval(tn+".nextPageGo();");} , function(){});
			}else{
				this.nextPageGo();	
			}
		}else{
			this.nextPageGo();
		}
		
	}
	this.nextPageGo = function(){
		var totalPages=Math.round(this.total / this.scope);
		if(totalPages==0 && this.total>0)
		 totalPages=1;
		 else if(this.total> totalPages*this.scope)
			totalPages++;
		
		if(parseInt(this.page,10)<parseInt(totalPages,10)){
		this.page++;
		this.fetch();
		this.updatePageStat();
		}
		
	}
	this.prevPage = function(){
		if(this.formCheckWarning){
			if(this.formHasChanged){
				var tn=this.name;
				ask("Wygląda na to, że dane w tabeli zostały przez Ciebie zmienione. Czy napewno chcesz przejść na poprzednią stronę? Zmienione dane z bieżącej strony zostaną utracone.","Ostrzeżenie", function(){eval(tn+".prevPageGo();");} , function(){});
			}else{
				this.prevPageGo();	
			}
		}else{
			this.prevPageGo();
		}
		
	}
	this.prevPageGo = function(){
		if(this.page>1){
			this.page--;
			this.fetch();
			this.updatePageStat();
		}
	}
	this.updatePageStat = function(){ 
		var statDiv=document.getElementById(this.tabId+"_pageStat");
		
		
		var totalPages=Math.round(this.total / this.scope);
		if(totalPages==0 && this.total>0)
		 totalPages=1;
		else if(this.total> totalPages*this.scope)
			totalPages++;
		var pageInp="<input id='"+this.name+"_pageInp' type='text' value='"+this.page+"' onChange='"+this.name+".goToPage(this.value)'>"
		
		var viewStart=((this.page-1)*this.scope)+1;
		var viewEnd=(this.page)*this.scope;
		if(this.total==0)viewStart=0;
		/*var nextPageBtn=document.createElement("button");
		nextPageBtn.innerHTML='&gt;&gt;'
		var prevPageBtn=document.createElement("button");
		
		prevPageBtn.innerHTML='&lt;&lt;'
		nextPageBtn.setAttribute("onclick" ,this.name+".nextPage()");
		prevPageBtn.setAttribute("onclick" ,this.name+".prevPage()");
		statDiv.appendChild(prevPageBtn);
		*/
		var nextpg="<button onclick='"+this.name+".nextPage()' class='nextPage'>&raquo;</button>";
		var prevpg="<button onclick='"+this.name+".prevPage()' class='prevPage'>&laquo;</button>";
		var actTotal=this.total;
		if(viewEnd<actTotal)
			actTotal=viewEnd;
		if(statDiv!=undefined){
		statDiv.innerHTML=prevpg+"strona "+pageInp+" z "+totalPages+" "+ nextpg+" |  wyświetlam:"+viewStart+" do "+actTotal+" z "+this.total;
		statDiv.innerHTML+=" | zaznaczonych : "+this.selectedRowIds.length ;
		if(this.selectMultiple)statDiv.innerHTML+="| <a href='javascript:"+this.name+".selectAll()'>zaznacz wszystko</a>";
		if(this.selectedRowIds.length>0)statDiv.innerHTML+="| <a href='javascript:"+this.name+".deselectRows()'>odznacz wszystko</a>"
		statDiv.innerHTML+="| <a href='javascript:"+this.name+".fetch()'>odśwież</a>";
		if(this.searchVals!=undefined)
		statDiv.innerHTML+="| <a href='javascript:"+this.name+".resetSearch()'>zresetuj wyszukiwanie</a>";
		//inp.setAttribute("TITLE" , "header=[Pomoc] body=["+formData[i].hint+"] fade=[on]");
		if(this.formCheckWarning){
			if(!this.formHasChanged)
				statDiv.innerHTML+="<div TITLE='header=[Pomoc] body=[Formularz nie był edytowany]' style='float:right; width:20px; height:20px; background:url(templates/default/img/led_green.gif);margin-top:3px'></div>";
			else
				statDiv.innerHTML+="<div TITLE='header=[Pomoc] body=[Formularz został zmieniony]' style='float:right; width:20px; height:20px; background:url(templates/default/img/led_red.gif);margin-top:3px'></div>";	
		}	
		}
	}
	this.showInitialSortOrders = function(){
		// funkcja ma za zadanie pokazac sortmarkery zaraz po wczytaniu danych po raz pierwszy
		for(var i=0;i<this.sortArr.length; i++){
			
			var marker=getElById(this.name+"_"+this.sortArr[i].sort+"_sortMarker");
			//this.name+"_"+this.cols[i].name+"_sortMarker";
			if(this.sortArr[i].order=="ASC")
				marker.className=this.css.ascSortMarkerClass;
			else if(this.sortArr[i].order=="DESC")
				marker.className=this.css.descSortMarkerClass;
			var dots=" *";
			for(var j=0;j<i; j++){	
				dots+=" *";
			}
			marker.innerHTML=dots;
		}	
		
	}
	this.resetSearch = function(){
		
		this.searchVals=undefined;
		this.fetch();
		
	}
	this.changeSort = function(oname){ 
		/* starsza wersja jedno kolumnowa
		this.page=1;
		var marker=getElById(this.name+"_"+oname+"_sortMarker");
		if(this.orderBy==oname){
			if(this.order=="ASC"){
				this.order="DESC";
				
			}else{
				this.order="ASC";
				
			}				
		}else{
			this.orderBy = oname;
		}
		if(this.order=="ASC"){
			marker.className=this.css.ascSortMarkerClass;
		}else{
			marker.className=this.css.descSortMarkerClass;
		}
		this.fetch();
		*/
		this.page=1;
		if(this.sortArr.length>0){
			var found=false;
			var foundAt=-1;
			for(var i = 0; i< this.sortArr.length; i++){
					if(this.sortArr[i].sort == oname){ // jest juz w tablicy
						 found=true;
						 foundAt=i;
					}else{ // nie ma w tablicy
						//nic nie rob
						
					}
			}
			if(!found){
				//dodaj kolejny typ sortu
				this.sortArr[i]=new Object();
				this.sortArr[i].sort=oname;
				this.sortArr[i].order="ASC";
				 //alert('nema');				
			}else{
				
				 // zmien order lub wylacz calkiem sort dla tej kolumny
				 if(this.sortArr[foundAt].order=="ASC"){
				 	this.sortArr[foundAt].order="DESC";
				 }else if(this.sortArr[foundAt].order=="DESC"){
				 	//skasuj marker
				 	
				 	var marker=getElById(this.name+"_"+this.sortArr[foundAt].sort+"_sortMarker");
				 	marker.className="";
				 	marker.innerHTML="";
				 	//skasuj z tablicy
				 	this.sortArr[foundAt]=undefined;
				 	// utworz nowa tablice i podmien z sortArr
				 	var newArr = new Array();
				 	var n=0; // index nowej tablicy
				 	for(var j=0;j<this.sortArr.length; j++){
				 		if(this.sortArr[j]!=undefined){
				 			newArr[n]= this.sortArr[j];
				 			n++;
				 		}
				 	}
				 	//podmien tablice
				 	this.sortArr = newArr;
				 }
			}
			
		}else{ // pierwszy raz kliknieto sort
			this.sortArr[0]=new Object();
			this.sortArr[0].sort=oname;
			this.sortArr[0].order = "ASC";
			//alert('nema '+ oname);
		}
		//ustaw ikonki sortowanka
		for(var i=0;i<this.sortArr.length; i++){
			
			var marker=getElById(this.name+"_"+this.sortArr[i].sort+"_sortMarker");
			//this.name+"_"+this.cols[i].name+"_sortMarker";
			if(this.sortArr[i].order=="ASC")
				marker.className=this.css.ascSortMarkerClass;
			else if(this.sortArr[i].order=="DESC")
				marker.className=this.css.descSortMarkerClass;
			var dots=" *";
			for(var j=0;j<i; j++){	
				dots+=" *";
			}
			marker.innerHTML=dots;
		}	
		this.fetch();	
	}
	
	this.zebraTable=function(){
	//zebrowanie tabelek po filtracji...
	var tab=this.tab;
	
	if(tab==undefined)
		return;
		
	var tb=tab.getElementsByTagName('tbody')[0];
	if(tb==undefined)return;
	var visRows=new Array();
	var ile=0;
	for(var i=0; i<tb.rows.length;i++){
		if(tb.rows[i].style.display!='none'){
			visRows[ile]=tb.rows[i];
			ile++;
		}
	}
	for(var i=0;i<visRows.length;i++){
		if(visRows[i].className!="tobSRow"){
		if(i % 2!=0){
			visRows[i].className='zebra';
			
		}else{
			visRows[i].className='';
		}
		}
	}
	
	
	}
	this.getInputVals = function(){
		//this.tab
		var vals=new Object();
		var inps=this.tab.getElementsByTagName('input');
		for(var i=0; i<inps.length; i++){
			if(vals[inps[i].name]==undefined)vals[inps[i].name]=new Object();
			vals[inps[i].name][inps[i].getAttribute('rowId')]=new Object();
			vals[inps[i].name][inps[i].getAttribute('rowId')].value=inps[i].value;
		}
		var txtArs=this.tab.getElementsByTagName('textarea');
		for(var i=0; i<txtArs.length; i++){
			if(vals[txtArs[i].name]==undefined)vals[txtArs[i].name]=new Object();
			vals[txtArs[i].name][txtArs[i].getAttribute('rowId')]=new Object();
			vals[txtArs[i].name][txtArs[i].getAttribute('rowId')].value=txtArs[i].value;
		}
		var sls=this.tab.getElementsByTagName('select');
		for(var i=0; i<sls.length; i++){
			if(vals[sls[i].name]==undefined)vals[sls[i].name]=new Object();
			vals[sls[i].name][sls[i].getAttribute('rowId')]=new Object();
			vals[sls[i].name][sls[i].getAttribute('rowId')].value=sls[i].options[sls[i].selectedIndex].value;
			vals[sls[i].name][sls[i].getAttribute('rowId')].text =sls[i].options[sls[i].selectedIndex].text ;
		}
		return vals;
	}
	
	//autFetch
	if(this.autoFetch)
		this.fetch();
	this.deselectRows = function(){
		if(this.tab.tBodies[0]!=undefined)
		for(var i = 0; i < this.tab.tBodies[0].rows.length; i++){
			if(this.tab.tBodies[0].rows[i].className=="tobSRow"){
				this.tab.tBodies[0].rows[i].className="";
				this.tab.tBodies[0].rows[i].removeAttribute('tobSelectedRow');
			}
		}
		this.selectedRowIds=new Array();
		this.selectedRowVals=new Array();
		this.updatePageStat();
		this.onRowDeselect.call(this,null ) ;
	}	
	
	this.selectRow = function(id){ 
		// pozwala latwo zaznaczyc 1 wiersz o danym id(rowId)
		if(this.selectedRowIds[0]==id)
			return false;
		for(var i=0; i<this.tab.rows.length ; i++){
			if(parseInt(this.tab.rows[i].getAttribute('rowid'),10) == id ){
				tobSelRow(this.tab.rows[i], this.name);
			}
		}
		
		
	}
	this.toCSV = function (){
		
		if(!this.prepared)
			this.prepTab();
		// ponizsze zmienne sa potrzebne, inaczej wewnatrz onSuccess nie widac pol klasy Tob
		var tb=this.tab;
		var ht=this.headerTab;
		var ordBy=this.orderBy;
		var ord=this.order;
		var cls = this.cols;
		var colWidths=undefined;
		var instanceName=this.name;
		var filtVals=""; // wartosci kolumn
		var filtCols="";
		var srchVals="";
		var srchCols="";
		var rowICN=this.rowIdColNum;
		var sepTh=this.sepThead;
		var markerColors=this.markers;
		var datob = this.dataOb;
		var doAfterFetch = this.onAfterFetch;
		datob = {};
		if(this.filterVals!=undefined){
			var count=0;
			for(var k in this.filterVals){
				if(this.filterVals[k]!=undefined){
					if(count>0){
						filtVals+="{~}";
						filtCols+="|";
					}
						
					filtVals+=this.filterVals[k].join("|");
					filtCols+=k;
					count++;
				}
		}
			
		}
		if(this.searchVals!=undefined){
			var count=0;
			for(var k in this.searchVals){
				if(count>0){
					srchCols+="|";
					srchVals+="|";
				}
				srchCols+=k;				
				srchVals+=this.searchVals[k];
				count++;	
			}
		}	
		var csvCols="";
		var csvColLabs="";
		var csvColCount=0;
		if(this.cols!=undefined){
			for(var i=0;i<this.cols.length; i++){
				if(this.cols[i].csv==true){ 
					if(csvColCount>0){csvCols+="|"; csvColLabs+="|";}
						
					csvCols+=this.cols[i].name;
					csvColLabs+=skeletonize(this.cols[i].display);
					csvColCount++;
				}	
			}
		}
		getElById(this.tabId+"_overlay").style.display='block';
		//przygotuj info o sortowaniu
		var sortCols="";
		var sortOrd="";
		for(var i = 0 ; i < this.sortArr.length; i++){
			if(i>0){
				sortCols+="|";
				sortOrd+="|";
			}
			sortCols+=this.sortArr[i].sort;
			sortOrd+=this.sortArr[i].order;
		}
		
		var par={
			run: this.run,
			autoParams: this.params.length,
			page:this.page,
			scope:this.scope,
			orderBy:sortCols,
			order:sortOrd,
			filter:filtVals,
			filterCols:filtCols,
			searchVals:srchVals,
			searchCols:srchCols
		};
		if(this.csv==true){
			par['csv']=1;
			par['csv_file_name']=this.csvFileName;
		}	
		if(csvColCount>0){
			par['csvCols']=csvCols;
			par['csvColLabs']=csvColLabs;
			
		}
		
		for(var i=0;i<this.params.length; i++){
			par['param'+(i+1)]=this.params[i];
		}
		var colName2Index=new Object(); // tablica  assoc : nazwa kolumny -> index kolumny(widoczny)
		for (var i=0; i<cls.length;i++){
				colName2Index[cls[i].name]=i;
		}
		
		advAJAX.post({
			parameters:par,
			onSuccess:function(obj){
				//alert(obj.responseText);
				info("<center><a href='"+obj.responseText+"' class='download'></a> zapisz plik csv </center>","Export do pliku CSV",false , false);
				getElById(tb.id+"_overlay").style.display='none';
			}
		});		
		
	}
	
	this.formChanged=function(){
		
		this.formHasChanged=true;
		this.updatePageStat();
	}
	
	
}
/// end of Tob class



function tobSelRow(r,tobName){ //alert(r +" "+tobName);
	var idColNum=eval(tobName+".rowIdColNum");
	var cols=eval(tobName+".cols");
	var fdata= eval(tobName+".fetchedData.data");
	eval("var sepTh="+tobName+".sepThead");
	for(var i=0;i<cols.length; i++){
		//alert(r.rowIndex);
		if(sepTh){
			eval(tobName+".selectedRowVals['"+cols[i].name+"'] = '"+fdata[r.rowIndex][i]+"'; ");
		}else{
			eval(tobName+".selectedRowVals['"+cols[i].name+"'] = '"+fdata[r.rowIndex-1][i]+"'; "); // -1 bo jest thead a w nim jeden wiersz...
		}	
	}
	
	
		
	if(r.className=="tobSRow"){ // odznacz
		r.className="";
		if(r.hasAttribute('tobSelectedRow'));
			r.removeAttribute('tobSelectedRow');
			
		//usun id wiersza z tablicy zaznaczen
		var remId=r.getAttribute('rowid');
		var tmpArr=new Array();
		eval("var sri=("+tobName+".selectedRowIds)");
		for(var i = 0; i<sri.length; i++){
			if(sri[i]!=remId)
				tmpArr.push(sri[i]);
		}	
		//podmien tablice
		//alert("rem id"+remId+"\n"+tmpArr);
		eval(tobName+".selectedRowIds=["+tmpArr+"];");	
			
		eval(tobName+".zebraTable()");
		eval(tobName+".selectedRowVals=new Array();"); // wyczysc tablice
		
		eval(tobName+".onRowDeselect.call(this, "+remId+")");
	}else{//zaznacz
		
		
		//dodaj id wiersza do zaznaczonych
		eval("var multiple="+tobName+".selectMultiple");
		if(multiple){
			eval("var sri = "+tobName+".selectedRowIds");
			if($.inArray(parseInt(r.getAttribute('rowid'),10), sri)==-1){
			
				eval(tobName+".selectedRowIds.push("+parseInt(r.getAttribute('rowid'),10)+");");
			}
			
		}else{
			eval(tobName+".selectedRowIds=[]");// nowa tablica
			
			eval(tobName+".selectedRowIds.push("+r.getAttribute('rowid')+");");
			
			eval("var tab="+tobName+".tab");
			for(var i = 0; i<tab.tBodies[0].rows.length; i++){
				if(tab.tBodies[0].rows[i].className=="tobSRow"){
					tab.tBodies[0].rows[i].className="";
					if(tab.tBodies[0].rows[i].hasAttribute('tobSelectedRow'));
						tab.tBodies[0].rows[i].removeAttribute('tobSelectedRow');
				}	
			}
			eval(tobName+".zebraTable();");
		}	
		r.className="tobSRow";
		r.setAttribute('tobSelectedRow', '1');
		eval(tobName+".onRowSelect.call(this, "+r.getAttribute('rowid')+")");
	}
	eval(tobName+".updatePageStat()");
}

function tobAddRow(tobName, tabEl, rowVals, doOnClick, rowId, widths,formData,data4ops, rowSelect){//alert(data4ops['colEnable']);
	//alert(rowVals.join("|")+rowSelect);

	//alert(rowVals.join("|")+" "+rowVals.length);
	var clsName=undefined;
	var tbody=null;
	if(tabEl.tBodies[0]==undefined){
		tbody=document.createElement('tbody');
		tabEl.appendChild(tbody);
	}else
		tbody=tabEl.tBodies[0];
			
	var newRow=document.createElement('tr'); // to nie dziala w ie 
	
	tbody.appendChild(newRow);
	if(rowId!=undefined && rowId!=null)
		newRow.setAttribute("rowId",rowId);
	//var newRow=tabEl.insertRow(-1); 
	for(var i = 0 ; i<rowVals.length; i++){
		var ncell=newRow.insertCell(-1);
		
			ncell.innerHTML=(rowVals[i]);
		if(widths!=undefined){
			//alert(widths[i]+"px");
			if(widths[i]!=undefined)
			ncell.style.width=widths[i]+"px";
		}
	}		
	
	for(var i = 0 ; i<formData.length; i++){
		var ncell=newRow.insertCell(-1);
		//alert(formData.);
			switch(formData[i].type){
				case "text":
					var defVal="";
					if(formData[i].defaultValueParsed!=undefined)
						defVal=formData[i].defaultValueParsed;
					else if(formData[i].defaultValue!=undefined)
						defVal=formData[i].defaultValue;
					var inp=document.createElement("INPUT");
					inp.setAttribute("type", "text");
					//alert(defVal);
					inp.value=defVal;
					
					
					
					inp.style.width=formData[i].width+"px";
					inp.name=formData[i].name;
					inp.setAttribute('rowId', rowId);
					inp.onclick=new Function("e","e.stopPropagation();");
					if(formData[i].hint!=undefined)
						inp.setAttribute("TITLE" , "header=[Pomoc] body=["+formData[i].hint+"] fade=[on]");
					if(formData[i].maxNumVal!=undefined){
						if(data4ops[formData[i].maxNumVal]!=undefined)
							inp.setAttribute("maxNumVal", data4ops[formData[i].maxNumVal]);
						else
							inp.setAttribute("maxNumVal", formData[i].maxNumVal);
						
					}
					if(formData[i].minNumVal!=undefined){
						inp.setAttribute("minNumVal", formData[i].minNumVal);
					}
					
					
					if(formData[i].defaultValue!=undefined){
						if(data4ops[formData[i].defaultValue]!=undefined)
							inp.setAttribute("defaultValue", data4ops[formData[i].defaultValue]);
						else
							inp.setAttribute("defaultValue", formData[i].defaultValue);
					}
					if(formData[i].validate!=undefined){
						switch(formData[i].validate){
							case "integer":
								inp.onblur 		= function(){onlyInteger(this);}; 
								//inp.onkeyup 	= function(){onlyInteger(this);};
								
								//inp.onkeydown 	= function(){onlyInteger(this);alert(this);};
							break;
							case "currency":
								
								inp.onblur 		= function(){
										onlyCurrency(this);
										
										var max=this.getAttribute("maxNumVal");
										//alert(data4ops[max]);
										if(max!=undefined){
											if(data4ops[max]!=undefined){ 
												maxNum=data4ops[max];
												if(parseFloat(this.value)>parseFloat(maxNum))
													this.value=maxNum;
											}else{
												if(parseFloat(this.value)>parseFloat(max))
													this.value=max;
											}													
										}
										
										var min=this.getAttribute("minNumVal");
										if(min!=undefined){
											if(parseInt(this.value,10)<min)
												this.value=min;											
										}
								};
							break;
						}
					}
						if(formData[i].colEnable!=undefined)
                                                    
						if(data4ops[formData[i].colEnable]!=undefined){
                                                    
							if(data4ops[formData[i].colEnable]=="1"){
								//zostaw wlaczony
								//alert('ENABLE this'+formData[i].name);
							}else{
								//wylacz
								inp.setAttribute("disabled", true);
								//alert('disable this'+formData[i].name);
								
							}
					}
					
					ncell.appendChild(inp);
					
				break;
				case "date":
					var defVal="";
					if(formData[i].defaultValueParsed!=undefined)
						defVal=formData[i].defaultValueParsed;
					else if(formData[i].defaultValue!=undefined)
						defVal=formData[i].defaultValue;
					//var html="<input style='width:"+formData[i].width+"px' type='text' name='"+formData[i].name+"_"+rowId+"' value='"+defVal+"'>";
					var inp=document.createElement("INPUT");
					inp.setAttribute("type", "text");
					inp.value=defVal;
					inp.style.width=formData[i].width+"px";
					inp.name=formData[i].name;
					inp.setAttribute('rowId', rowId);
					inp.onclick=new Function("e","e.stopPropagation();");
					if(formData[i].validate!=undefined){
						switch(formData[i].validate){
							case "integer":
								inp.onblur 		= function(){onlyInteger(this);}; 
								//inp.onkeyup 	= function(){onlyInteger(this);};
								
								//inp.onkeydown 	= function(){onlyInteger(this);alert(this);};
							break;
							case "currency":
								inp.onblur 		= function(){onlyCurrency(this);};
							break;
						}
					}
					
					ncell.appendChild(inp);
					$(inp).datepicker();
				break;
				case "textarea":
					var defVal="";
					if(formData[i].defaultValueParsed!=undefined)
						defVal=formData[i].defaultValueParsed;
					else if(formData[i].defaultValue!=undefined)
						defVal=formData[i].defaultValue;
					//var html="<input style='width:"+formData[i].width+"px' type='text' name='"+formData[i].name+"_"+rowId+"' value='"+defVal+"'>";
					var inp=document.createElement("TEXTAREA");
					inp.setAttribute("type", "text");
					inp.value=defVal;
					inp.style.width=formData[i].width+"px";
					inp.style.height=formData[i].height+"px";
					
					inp.name=formData[i].name;
					inp.setAttribute('rowId', rowId);
					inp.onclick=new Function("e","e.stopPropagation();");
					
					ncell.appendChild(inp);
				break;
				case "select":
					
					var defVal="";
					if(formData[i].defaultValueParsed!=undefined)
						defVal=formData[i].defaultValueParsed;
					else if(formData[i].defaultValue!=undefined)
						defVal=formData[i].defaultValue;
					//var html="<input style='width:"+formData[i].width+"px' type='text' name='"+formData[i].name+"_"+rowId+"' value='"+defVal+"'>";
					var inp=document.createElement("SELECT");
					inp.setAttribute("type", "text");
					inp.value=defVal;
					inp.style.width=formData[i].width+"px";
					inp.options[inp.options.length]=new Option("wybierz...", '');
					
					if(formData[i].colValue!=undefined ){
						if(data4ops[formData[i].colValue]!=undefined){//alert(data4ops[formData[i].colValue]);
							defVal=data4ops[formData[i].colValue];			
						}
					}
					if(formData[i].colEnable!=undefined){ 
						if(data4ops[formData[i].colEnable]!=undefined){  
							if(data4ops[formData[i].colEnable]=="1"){
								//zostaw wlaczony
								//alert('ENABLE this'+formData[i].name);
							}else{
								//wylacz
								inp.setAttribute("disabled", true);
								//alert('disable this'+formData[i].name);
								
							}
					}
							
					}
							
					for(var x=0;x<formData[i].options.length;x++){
						inp.options[inp.options.length]=new Option(formData[i].options[x][1],formData[i].options[x][0]);
						if(defVal==formData[i].options[x][0])
							inp.options[inp.options.length-1].setAttribute('selected', 'true');
						
					}
					
					inp.name=formData[i].name;
					inp.setAttribute('rowId', rowId);
					inp.onclick=new Function("e","e.stopPropagation();");
					
					ncell.appendChild(inp);
					
				break;
				
				case "buttons":
					var html="";
					var nbr=document.createElement('NOBR');
					ncell.appendChild(nbr);
					for(var n=0; n<formData[i].buttons.length; n++){
						var  btn=document.createElement("BUTTON");
						btn.id=tobName+"_"+formData[i].buttons[n].name+"_"+rowId;
						btn.innerHTML=formData[i].buttons[n].label;
						var f=formData[i].buttons[n].onclick;
	
						btn.onclick = new Function("e","e.stopPropagation();("+f+").call(this,\""+toJSON(data4ops)+"\");"); //czary mary :D
						if(formData[i].buttons[n].hint!=undefined){
							btn.setAttribute("TITLE" , "header=[Pomoc] body=["+formData[i].buttons[n].hint+"] fade=[on]");
						}
						
						if(formData[i].colEnable!=undefined){ 
						if(data4ops[formData[i].colEnable]!=undefined){  
							if(data4ops[formData[i].colEnable]=="1"){
								//zostaw wlaczony
								//alert('ENABLE this'+formData[i].name);
							}else{
								//wylacz
								btn.setAttribute("disabled", true);
								//alert('disable this'+formData[i].name);
								
							}
						}
						}
						nbr.appendChild(btn);
					}
				break;
				default:	
					ncell.innerHTML=(formData[i].type);
				break;
			}
			if(inp!=undefined){ //cr
				inp.setAttribute('onchange', tobName+".formChanged()");
				
				if(formData[i].indicator!=undefined){
					if(data4ops[formData[i].indicator]=="1"){							
						//ncell.innerHTML= "<nobr>"+ncell.innerHTML+"<img TITLE=\"header=[Pomoc] body=["+formData[i].indicatorText+"] fade=[on]\" src='templates/default/img/bolb.png'></nobr>";
						var el=document.createElement("div");
						//el.innerHTML="<img TITLE=\"header=[Pomoc] body=["+formData[i].indicatorText+"] fade=[on]\" src='templates/default/img/bolb.png'>";
						var nbr=document.createElement("NOBR");
						nbr.innerHTML+="<img TITLE=\"header=[Pomoc] body=["+formData[i].indicatorText+"] fade=[on]\" src='templates/default/img/bolb.png'>";
						nbr.insertBefore(ncell.childNodes[0], nbr.childNodes[0]);
						ncell.appendChild(nbr); 
					}	
				}
				
			}
		if(widths!=undefined){
			ncell.style.width=widths[i]+"px";
		}
	}
		
	if(doOnClick!=undefined && doOnClick!=null){
		//newRow.setAttribute('onclick', doOnClick);
		$(newRow).click(function(){
			eval(doOnClick);
		});
	}
	if(clsName!=undefined && clsName!=null){
		newRow.className=clsName;
	}
	if(rowSelect=="1"){
		tobSelRow(newRow, tobName);
		
	}	

}
function toJSON(ob){
	var json="{";
	var count=0;
	for(var k in ob){
		if(k!='undefined'){
		if(count>0) json+=",";
		json+="'"+k+"': '"+ob[k]+"'";
		
		count++;
		}
	}
	json+="}";
	//alert(json);
	return json;
}
//<![CDATA[

// Using DragResize is simple!
// You first declare a new DragResize() object, passing its own name and an object
// whose keys constitute optional parameters/settings:

var dragresize = new DragResize('dragresize',
 { minWidth: 50, minHeight: 50, minLeft: 20, minTop: 20, maxLeft: 600, maxTop: 600 });

// Optional settings/properties of the DragResize object are:
//  enabled: Toggle whether the object is active.
//  handles[]: An array of drag handles to use (see the .JS file).
//  minWidth, minHeight: Minimum size to which elements are resized (in pixels).
//  minLeft, maxLeft, minTop, maxTop: Bounding box (in pixels).

// Next, you must define two functions, isElement and isHandle. These are passed
// a given DOM element, and must "return true" if the element in question is a
// draggable element or draggable handle. Here, I'm checking for the CSS classname
// of the elements, but you have have any combination of conditions you like:

dragresize.isElement = function(elm)
{
 if (elm.className && elm.className.indexOf('drsElement') > -1) return true;
};
dragresize.isHandle = function(elm)
{
 if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true;
};

// You can define optional functions that are called as elements are dragged/resized.
// Some are passed true if the source event was a resize, or false if it's a drag.
// The focus/blur events are called as handles are added/removed from an object,
// and the others are called as users drag, move and release the object's handles.
// You might use these to examine the properties of the DragResize object to sync
// other page elements, etc.

dragresize.ondragfocus = function() { };
dragresize.ondragstart = function(isResize) { };
dragresize.ondragmove = function(isResize) { };
dragresize.ondragend = function(isResize) { };
dragresize.ondragblur = function() { };

// Finally, you must apply() your DragResize object to a DOM node; all children of this
// node will then be made draggable. Here, I'm applying to the entire document.
dragresize.apply(document);

//]]>

