/*
 * Filip Hladík, FG Forrest, a.s., 07/2008
 * 
 * proměnné v constructoru (tbl = new FG_fixTables(contId, clName, tableCounter):
 * contId -	ID objektu, ve kterém je div se scrollováním a v něm tabulka
 * clName - jméno třídy prvního TH v THEAD, který má zůstat fixnutý na svém místě
 * tableCounter - pořadí tabulky na stránce
 * 
 * veřejné metody třídy:
 * tbl.setThPadding() - zadání paddingu výsledných fixovaných buňěk (potřeba k správnému vypočítaní výšky a šířky)
 * tbl.fix() - přegeneruje fixovaný sloupec
 * 
 * v0.3
 * +++ fixovaný sloupec akceptuje šířku TH, které nahrazuje
 * +++ výsledný fixovaný sloupec, respektive každý div v něm, dostane className od rodičovského TR
 * +++ oprava: korekce výšky a šířky fixovaných buněk (počítání s paddinem)
 * 
 * v0.2
 * +++ přepočítávání řádků při zvětšování písma v prohlížeči
 * 
 * v0.1
 * +++ první verze
 * 
 * známé bugy:
 * -- špatné chování, pokud je text v TD a TH zarovnán vertikálně na střed (lépe vypadá, když je text zarovnán nahoru)
* -- pokud je na stránce použita knihovna jQuery a elementům na stránce jsou přidávány akce v rámci 
 *    $(document).ready(function(), je potřeba manuálně zavolat funkci na vytvoření divu před přiřazením všech ostatních akcí
 *    př.
 *    $(document).ready(function(){
 *    	table1.prepareDivForFix();	// manualni vytvoreni divu
 *    	// tady muzou byt dalsi akce
 *    	$("th").addClass("icon-close");
 *    }
 *    -- toto není bug, pouze konflikt a varování na správné pořadí volání funkcí této knihovny a funkcí jQuery
 * 
 * důležité:
 * 	- textsizedetector.js
 * 	- HTML strukturu v tomto formátu
 * 		<div contId>
 * 			<div - scrollovací>
 * 				<table>
 * 					<thead>
 * 						pokud máme TH v TBODY, je nutné přidat prvnímu TH v THEAD class clName, bude fixován spolu 
 * 						s TH z TBODY
 * 					</thead>
 * 					<tbody>
 * 						první buňka v řádku tabulky by měla být TH, skript fixuje pouze TH v TBODY (+ první TH.clName v THEAD)
 * 					</tbody>
 * 				</table>
 * 			</div>
 * 		</div>
 * 
 */

function FG_fixTables(contId, clName, tableCounter) {
// inner vars
	this.tblContainer = obj(contId);
	this.thInTheadFixedClass = clName;
	this.tableCounter = tableCounter;
	this.fixDivPrepared = false;
	this.horizontalPaddingSum = 0;
	this.verticalPaddingSum = 0;

// class methods
	// public
	this.fix = fix;
	this.setThPadding = setThPadding;
	
	// private
	this.gatherData = gatherData;
	this.generateFixedColumns = generateFixedColumns;
	this.prepareDivForFix = prepareDivForFix;
	

// methods definitions

	/* vertical, horizontal */
	function setThPadding(vertP, horP) {
		this.horizontalPaddingSum = horP;
		this.verticalPaddingSum = vertP;
	}
	
	function prepareDivForFix(){
		if (!this.fixDivPrepared && !obj("FG_fixTables_" + this.tableCounter)) {
			this.tblContainer.innerHTML += '<div id="FG_fixTables_' + this.tableCounter + '"></div>';
			this.fixDivPrepared = true;
		}
	}

	/* najde všechny TH v tabulce, které mají zůstat zafixovány */
	/* výsledkem je pole ve formátu [ [thObject, th.className], [thObject, th.className] ] */
	function gatherData() {
		var tblThs = new Array();
		var tblBody = tblHead = null;
		
		if (!this.tblContainer)
			return null;
		
		/* ths z tbody */
		tblBody = this.tblContainer.getElementsByTagName("tbody");
		if (!tblBody.length) 
			return null;
		
		var ths = tblBody[0].getElementsByTagName("th");
		for (var i = 0; i < ths.length; i++) {
			tblThs.push([ths[i], ths[i].className]);
			//ths[i].style.visibility = "hidden";
		}
		
		/* th z thead podle definované class */
		if (this.thInTheadFixedClass) {
			tblHead = this.tblContainer.getElementsByTagName("thead");
			if (tblHead.length) {
				ths = getElementsByClassName(tblHead[0], "th", this.thInTheadFixedClass);
				for (var i = 0; i < ths.length; i++) {
					tblThs.unshift([ths[i], ths[i].className]);
					//ths[i].style.visibility = "hidden";
				}
			}
		}
		return tblThs;
	}

	function fix(){
		this.prepareDivForFix();
		var dt = this.gatherData();
		if (!dt || !dt.length) 
			return;
		
		var str = this.generateFixedColumns(dt);
		obj("FG_fixTables_"+this.tableCounter).innerHTML = str;
	}
	
	function generateFixedColumns(arr) {
		var sb = new StringBuffer();
		sb.append('<div class="fixedColumn">');
		for (var i = 0; i < arr.length; i++) {
			var heightTh, widthTh;
			var additionalClass, rowClass;
			if (i + 1 < arr.length) {
			    //alert(arr[i + 1][0].offsetTop - arr[i][0].offsetTop);
				heightTh = (arr[i + 1][0].offsetTop - arr[i][0].offsetTop) - this.verticalPaddingSum - 1;
				heightTh += "px";
			}
			else {
				heightTh = "auto";
			}
			
			widthTh = arr[i][0].clientWidth - this.horizontalPaddingSum;
			
			rowClass = arr[i][0].parentNode.className;
			additionalClass = arr[i][1] ? ' ' + arr[i][1] : "";
			if (rowClass) {
				additionalClass += " "+rowClass;
			}
			sb.append('<div class="fixedRowItem'+additionalClass+'" style="top: ' + arr[i][0].offsetTop + 'px; height: '+heightTh+'; width: '+widthTh+'px;">');
			sb.append(arr[i][0].innerHTML);
			sb.append('</div>');
		}
		sb.append('</div>');
		return sb.getString();
	}
}

// stringbuffer class
function StringBuffer() {
	this.buffer = '';
	this.append = function(str) { this.buffer += str; }
	this.getString = function() { return this.buffer; }
}

// object handlers
function obj(id) { return document.getElementById(id); }

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for (var i=0; i<arrElements.length; i++) {
		oElement = arrElements[i];
		if (oRegExp.test(oElement.className)) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements);
}


/* toto nemá být součástí této "knihovny" 
function init() {
	var iBase = TextResizeDetector.addEventListener(onFontResize,null);
}
function onFontResize() {
	table1.fix();
}

//id of element to check for and insert control
TextResizeDetector.TARGET_ELEMENT_ID = 'root';
//function to call once TextResizeDetector has init'd
TextResizeDetector.USER_INIT_FUNC = init;

function fixTable(o) {
	o.fix();
}

*/