// version: 20060622
// Filtering table rows by drop-downs selection

var debugOn = false;
var dbg = null; // output HTML element reference

var notFoundMsg = null; // div with not found msg
var strNotFoundMsg = "{OKRES}<br>Ľutujeme, v tejto oblasti zatiaľ nie je služba Unikasa poskytovaná.";
var opacityInterval = null;
var currentOpacity = 1.0;
var currentlyHiding = false;

// Pocet stlpcov tabulky:
var NUM_COLS = 6;
var TABLE_ID = "dataTable";

// Column numbers (for getting the right table cells - starts at 0!):
var COL_MESTA = 1;
var COL_KRAJE = 4;
var COL_OKRESY = 5;

// ostatne stlcpe tabulky:
var COL_JEDNOTA = 0;
var COL_ULICA   = 2;
var COL_PSC     = 3;

// columns to display in the table - hide all the other columns:
var showColumns = [COL_MESTA, COL_ULICA, COL_PSC];

var strPleaseChoose = "Prosím zvoľte...";
var strSelOptDelimiter = "---";

var kraje = new Array();
var okresy = new Array();
var mesta = new Array();

var krajeOkresy = new Array(); // kraje obsahuju ktore okresy?
var krajeMesta = new Array(); // kraje obsahuju ktore mesta?
var okresyMesta = new Array(); // okresy obsahuju ktore mesta?

/*
Banská Štiavnica
Galanta
Kežmarok
Komárno
Krupina
Levice
Michalovce
Nitra
Nové Zámky
Poprad
Prievidza
Senec
Stropkov
Trebišov
Veľký Krtíš
Zlaté Moravce
Šaľa
Žarnovica
Žiar nad Hronom

*/

var abbrOkresy = { BA: "Bratislava", BB: "Banská Bystrica", BJ: "Bardejov", BN: "Bánovce nad Bebravou", BR: "Brezno", BS: "Banská Štiavnica", BY: "Bytča", CA: "Čadca", DK: "Dolný Kubín", DS: "Dunajská Streda", DT: "Detva", GA: "Galanta", GL: "Gelnica", HC: "Hlohovec", HE: "Humenné", IL: "Ilava", KA: "Krupina", KE: "Košice", KK: "Kežmarok", KM: "Kysucké Nové Mesto", KN: "Komárno", KS: "Košice - okolie", LC: "Lučenec", LE: "Levoča", LM: "Liptovský Mikuláš", LV: "Levice", MA: "Malacky", MI: "Michalovce", ML: "Medzilaborce", MT: "Martin", MY: "Myjava", NI: "Nitra", NM: "Nové Mesto nad Váhom", NO: "Námestovo", NR: "Nitra", NZ: "Nové Zámky", PB: "Považská Bystrica", PD: "Prievidza", PE: "Partizánske", PK: "Pezinok", PN: "Piešťany", PO: "Prešov", PP: "Poprad", PT: "Poltár", PU: "Púchov", PV: "Prešov", RA: "Revúca", RK: "Ružomberok", RS: "Rimavská Sobota", RV: "Rožňava", SA: "Šaľa", SB: "Sabinov", SC: "Senec", SE: "Senica", SI: "Skalica", SK: "Svidník", SL: "Stará Ľubovňa", SN: "Spišská Nová Ves", SO: "Sobrance", SP: "Stropkov", SV: "Snina", TA: "Trnava", TC: "Trenčín", TN: "Trenčín", TO: "Topoľčany", TR: "Turčianske Teplice", TS: "Tvrdošín", TT: "Trnava", TV: "Trebišov", VK: "Veľký Krtíš", VT: "Vranov nad Topľou", ZA: "Žilina", ZC: "Žarnovica", ZH: "Žiar nad Hronom", ZI: "Žilina", ZM: "Zlaté Moravce", ZV: "Zvolen" };

// --- debugging ---
function dbgOut(str) {
	if (debugOn && typeof dbg == "object") {
		dbg.value += str + "\n";
	}
}
// --- end debugging ---

// feature testing MSIE:
function isIE() {
	if (typeof document.media == "string" && document.all) {
		return true;
	} else {
		return false;
	}
}

// is needle in haystack?
function inArray(haystack, needle) {
	if (typeof haystack == "object" && haystack.constructor == Array) {
		for (var i in haystack) {
			if (haystack[i] == needle) {
				return true;
			}
		}
	}
	return false;
} // end: function inArray()

// get the key for the value in needle 
function arrayGetKey(haystack, needle) {
	for (var key in haystack) {
		if (haystack[key] == needle) {
			return key;
		}
	}
	return false;
}

// Check whether obj is an object AND an HTMLTableElement instance?
function isTableRef (obj) {
	if (typeof obj == "object" && obj.rows) {
		return true;
	} else {
		return false;
	}
} // end: function isTableRef()

// Check whether obj is an object AND an HTMLTableRowElement instance?
function isTableRowRef(obj) {
	if (typeof obj == "object" && obj.cells) {
		return true;
	} else {
		return false;
	}
} // end: function isTableRowRef()

function makeAllTableRowsVisible(tableRef) {
	if (isTableRef(tableRef)) {
		tableRef.style.display = "none";
		for (var i = 0; i < tableRef.rows.length; i++) {
			var row = tableRef.rows.item(i);
			//alert(row.style.display); 
			row.className = "visibleRow";
		}
		return true;
	} else {
		return false;
	}
} // end: function makeAllTableRowsVisible()

// Check if this table row has any TH elements as children:
function hasThChildren(rowRef) {
	if (isTableRowRef(rowRef)) {
		var ths = rowRef.getElementsByTagName("th");
		if (ths.length > 0) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
} // end: function hasThChildren()

function hideRowsNotHavingValueInCell(tableRef, colNum, value) {

	var t = tableRef;
	if (isTableRef(t)) {
		for (var i = 0; i < t.rows.length; i++) {
			var row = t.rows.item(i);
			// Skip table header:
			if (i == 0 && hasThChildren(row)) continue;
			
			// get cells
			//alert(row);
			var cells = row.getElementsByTagName("td");
			//alert(cells.length);
			var cellValue = cells[colNum].innerHTML;
			if (cellValue != value) {
				row.className = "invisibleRow";
			}
		}
		
	} else {
		return false;
	}
}


// postupne znizuje opacity pocas skryvania notFoundMsg boxu:
function lowerOpacity() {
	var temp;
	if (currentOpacity > 0) {
		temp = currentOpacity - 0.2;
		temp = temp.toFixed(2);
		notFoundMsg.style.opacity = "" + temp + "";
		notFoundMsg.style.filter = "alpha (opacity=" + (temp * 100) + ")";
		currentOpacity -= 0.2;
	} else {
		notFoundMsg.style.display = "none";
		notFoundMsg.style.opacity = "1";
		notFoundMsg.style.filter = "alpha (opacity=100)";
		currentOpacity = 1;
		clearInterval(opacityInterval);
		currentlyHiding = false;
	}
}

// postupne skryje notFoundMsg box:
function hideNotFoundMsgBox() {
	if (!currentlyHiding) {
		if (typeof notFoundMsg == "object") {
			currentlyHiding = true;
			opacityInterval = setInterval("lowerOpacity()", 75);
		}
	}
}

// skryje tabulku s datami:
function hideDataTable() {
	var t = document.getElementById(TABLE_ID);
	t.style.display = "none";
}

// Fill a drop-down (select) list with options:
function fillDropDown(selId, arrValues) {
	
	arrValues.sort();
	
	var selElement = document.getElementById(selId);
	selElement.options.length = 0;
	
	// First option: "please choose..."
	selElementNewOpt = document.createElement("option");
	selElementNewOpt.innerHTML = window.strPleaseChoose;
	selElementNewOpt.setAttribute("value", window.strPleaseChoose);
	selElement.appendChild(selElementNewOpt);
	
	// Second option: "(delimiter)"
	selElementNewOpt = document.createElement("option");
	selElementNewOpt.innerHTML = window.strSelOptDelimiter;
	selElementNewOpt.setAttribute("value", window.strSelOptDelimiter);
	selElement.appendChild(selElementNewOpt);
	
	var selElementNewOpt = null;
	
	for (var i = 0; i < arrValues.length; i++) {
		selElementNewOpt = document.createElement("option");
		selElementNewOpt.setAttribute("id", selId + "" + i);
		selElementNewOpt.setAttribute("value", arrValues[i]);
		selElementNewOpt.innerHTML = arrValues[i];
		selElement.appendChild(selElementNewOpt);
		selElementNewOpt = null;
	}
	selElement.style.width = "150px";
			
} // end: function fillDropDown()

// najdi kraj pre zadany okres:
function getKrajForOkres(okres) {
	for (var kraj in krajeOkresy) {
		if (inArray(krajeOkresy[kraj], okres)) {
			return kraj;
		}
	}
}


function getKrajForMesto(mesto) {
	for (var kraj in krajeMesta) {
		if (inArray(krajeMesta[kraj], mesto)) {
			return kraj;
		}
	}
}

function getOkresForMesto(mesto) {
	for (var okres in okresyMesta) {
		if (inArray(okresyMesta[okres], mesto)) {
			return okres;
		}
	}
}

// Function for removing items from selOkres select box after
function removeSelOkresSelMestoItemsNotIn(kraj) {

	if (kraj == window.strPleaseChoose || kraj == window.strSelOptDelimiter) {
		//fillDropDown("selKraj", kraje);
		fillDropDown("selOkres", okresy);
		fillDropDown("selMesto", mesta);
		
	} else {
		// fill drop down with the right items:
		fillDropDown("selOkres", krajeOkresy[kraj]);
		fillDropDown("selMesto", krajeMesta[kraj]);
	}

} // end: function removeSelOkresSelMestoItemsNotIn()

function removeSelMestoItemsNotIn(okres) {
	//alert(okres);
	if (okres != window.strPleaseChoose && okres != window.strSelOptDelimiter) {
		// fill drop down with the right items:
		fillDropDown("selMesto", okresyMesta[okres]);

		// after Okres was selected, select the appropriate Kraj:
		var selKraj = document.getElementById("selKraj");
		selectItem(selKraj, getKrajForOkres(okres));
	} else {
		fillDropDown("selOkres", okresy);
		fillDropDown("selMesto", mesta);
	}
 
} // end: function removeSelMestoItemsNotIn()


// select specified item in a select element drop down
function selectItem(selElement, strItem) {
	if (typeof selElement == "object" && selElement.options) {
		for (var i = 0; i < selElement.options.length; i++) {
			if (selElement.options[i].innerHTML == strItem) {
				selElement.selectedIndex = i;
				return;
			}
		}
	}
}

// select Kraj and Okres according to selected Mesto
function selectKrajAndOkres(mesto) {
	if (mesto == window.strPleaseChoose || mesto == window.strSelOptDelimiter) {
		fillDropDown("selKraj", kraje);
		fillDropDown("selOkres", okresy);
		fillDropDown("selMesto", mesta);
	} else {
		var selKraj = document.getElementById("selKraj");
		var selOkres = document.getElementById("selOkres");
		
		selectItem(selKraj, getKrajForMesto(mesto));
		selectItem(selOkres, getOkresForMesto(mesto));
	}
}


// After drop-down selection, filter the table
// (hide rows not containing specified value in the specified column)
function filterTable(tableId, filterByCol, filterByVal) {
	var table = document.getElementById(tableId);
	// Check if it's a table:
	if (isTableRef(table)) {

		// make all table rows visible:
		makeAllTableRowsVisible(table);
		
		if (filterByVal == window.strPleaseChoose || filterByVal == window.strSelOptDelimiter) {
			table.style.display = "none";
			return true;
		}
		
		// Iterate through the table and compare contents of cells in the specified column with the filterByVal value
		hideRowsNotHavingValueInCell(table, filterByCol, filterByVal);
		
		if (isIE()) {
			table.style.display = "block"; // MSIE didn't eat "table"
		} else {
			table.style.display = "table";		
		}
		
		return true;
		
	} else { // Element is not a table:
		return false;
	} // end: if typeof == table...
	
} // end: function

// called from timeout - necessary because of IE bugs
function temp(okres) {
	var selOkres = document.getElementById("selOkres");
	var selKraj = document.getElementById("selKraj");
	selectItem(selOkres, okres);
	selectItem(selKraj, getKrajForOkres(okres));
	selOkres.onchange();
}

function imgMapClickSelOkres(areaEl) {
	hideNotFoundMsgBox();
	var okres = areaEl.getAttribute("alt");
	fillDropDown("selOkres", okresy);
	setTimeout("temp('"+ okres +"')", 200); // I hate IE
}

function imgMapClickOkresNotFound(areaEl) {
	var okres = areaEl.getAttribute("alt");
	if (typeof notFoundMsg == "object") {
		notFoundMsg.innerHTML = strNotFoundMsg.replace("{OKRES}", "<strong>" + okres + "</strong>");
		notFoundMsg.style.display = "block";
	}
}

function callFilterTableOnChange(selectElementId) {
	var sel = document.getElementById(selectElementId);
	if (typeof sel == "object" && sel.options) { // is it a select element?
		var filterByVal = sel.options.item(sel.selectedIndex).innerHTML;
		
		var filterByCol = 0;
		if (selectElementId == "selMesto") {
			filterByCol = COL_MESTA;
		} else if (selectElementId == "selOkres") {
			filterByCol = COL_OKRESY;
		} else if (selectElementId == "selKraj") {
			filterByCol = COL_KRAJE;
		}
		
		return filterTable(TABLE_ID, filterByCol, filterByVal);
		
	} else {
		return false;
	}
} // end: function


// Tato funkcia tu je kvoli chybnemu spravaniu MSIE, ktory "nestihal" reagovat 
// na zmeny v SELECT elementoch a tvrdohlavo pri pokuse pristupovat k vlastnosti 
// HTMLSelectElement.selectedIndex vyhadzoval chybu; po pouziti timeout-u je to
// uz v poriadku (Michal S. - 21. 6. 2006 12:17:58)
function workaround(objID) {
	var obj = document.getElementById(objID);
	//alert(obj.constructor);
	if (objID == "selKraj") {
		removeSelOkresSelMestoItemsNotIn(obj.options[obj.selectedIndex].getAttribute("value"));
	} else if (objID == "selOkres") {
		var str = obj.options[obj.selectedIndex].getAttribute("value");
		removeSelMestoItemsNotIn(str);
	} else if (objID == "selMesto") {
		var str = obj.options[obj.selectedIndex].getAttribute("value");
		selectKrajAndOkres(str);
	}
}

// handle onchange events of the select boxes:
function onchangeHandler() {
	//debugger;
	hideNotFoundMsgBox();
	var id = this.getAttribute("id");
	setTimeout("workaround('"+ id +"')", 200); // I hate MSIE...see above
	callFilterTableOnChange(id);
}

// handle onclick events of area elements:
function areaOnClickHandler() {
	//debugger;
	var id = new String(this.getAttribute("id"));
	id = id.replace("okres", "");
	
	var okres = abbrOkresy[id];
	if (inArray(okresy, okres)) {
		// existuju zastupenia v tomto okrese:
		imgMapClickSelOkres(this);
	} else {
		// neexistuju zastupenia v tomto okrese:
		imgMapClickOkresNotFound(this);
	}
	return false;
}

// main function - executes on document load:
function doIt() {

	if (debugOn) {
		window.dbg = document.getElementById("dbgOut");
	}
	
	var formPlace = document.getElementById("formPlace");
	formPlace.innerHTML = '<form id="selectRows"><table><tr><td>Kraj:</td><td>Okres:</td><td>Mesto:</td></tr><tr><td><select id="selKraj"></select></td><td><select id="selOkres"></select></td><td><select id="selMesto"></select></td></tr></table></form>';
	var row = null;
	var cells = null;
	
	var cellKraj = null;
	var kraj = "";
	
	var cellOkres = null;
	var okres = "";
	
	var cellMesto = null;
	var mesto = "";
	
	var j = 0;
	
	var dataTable = document.getElementById(TABLE_ID);
	//alert(dataTable.rows.length);
	
	dataTable.style.display = "none";
	
	// Iterate through all table rows and collect data:
	for (var i = 0; i < dataTable.rows.length; i++) {
		
		// Get current table row:
		row = dataTable.rows[i];

		// Set ID for every table row for easier manipulation later:
		row.setAttribute("id", "row" + i);
		
		// Skip table header, but hide the cells:
		var headerCells = row.getElementsByTagName("th");
		if (headerCells.length > 0) {
			for (j = 0; j < headerCells.length; j++) {
				headerCells.item(j).className = "col" + (j+1);
				if (!inArray(showColumns, j)) {
					headerCells.item(j).style.width = "1px";
					headerCells.item(j).style.display = "none";
					headerCells.item(j).style.visibility = "hidden";
				}
			}
			continue;
		}

		// Get all cells of the current row:
		cells = row.getElementsByTagName("td");
		
		
		if (cells.length == NUM_COLS) {
		
			// fill all the arrays:
			cellKraj = cells.item(COL_KRAJE);
			kraj = cellKraj.innerHTML;
			if (!inArray(kraje, kraj)) {
				kraje[kraje.length] = kraj; 		//dbgOut("kraje[" + (kraje.length-1) + "] = \"" + kraj + "\" // assigned");
				krajeOkresy[kraj] = new Array(); 	//dbgOut("krajeOkresy[\""+ kraj +"\"] array created.");
				krajeMesta[kraj] = new Array(); 	//dbgOut("krajeMesta[\""+ kraj +"\"] array created.");
				//console.log(kraj + " (" + kraje.length + ") [row: " + i + "]");
			}

			var cellOkres = cells.item(COL_OKRESY);
			var okres = cellOkres.innerHTML;
			if (!inArray(okresy, okres)) {
				okresy[okresy.length] = okres;		//dbgOut("okresy[" + (okresy.length-1) + "] = \"" + okres + "\" // assigned");
				krajeOkresy[kraj][krajeOkresy[kraj].length] = okres;	//dbgOut("krajeOkresy[\"" + kraj + "\"][" + (krajeOkresy[kraj].length-1) + "] = \"" + okres + "\"");
				okresyMesta[okres] = new Array();	//dbgOut("okresyMesta[\"" + okres + "\"] = new Array()");
				//console.log(okres + " (" + okresy.length + ")");
			}
			
			var cellMesto = cells.item(COL_MESTA);
			var mesto = cellMesto.innerHTML;
			if (!inArray(mesta, mesto)) {
				mesta[mesta.length] = mesto;		//dbgOut("mesta[" + (mesta.length-1) + "] = \"" + mesto + "\";");
				krajeMesta[kraj][krajeMesta[kraj].length] = mesto;	//dbgOut("krajeMesta[\"" + kraj + "\"]["+ (krajeMesta[kraj].length-1) +"]  = \"" + mesto + "\";");
				okresyMesta[okres][okresyMesta[okres].length] = mesto;	//dbgOut("okresyMesta[\"" + okres + "\"][" + (okresyMesta[okres].length-1) + "] = \"" + mesto + "\";");
				//console.log(mesto + " (" + mesta.length + ") [row: " + i + "]");
			}
			
			//dbgOut(" -- " + i + " -- ");

			for (j = 0; j < cells.length; j++) {
				cells.item(j).className = "col" + (j+1);
				if (!inArray(showColumns, j)) {
					cells.item(j).style.width = "1px";
					cells.item(j).style.display = "none";
					cells.item(j).style.visibility = "hidden";
				}
			}
			kraj = okres = mesto = "";
			
		} // end: if cells.length
	}
	
	// --- //

	// Fill dropdown lists:
	fillDropDown("selKraj", kraje);
	fillDropDown("selOkres", okresy);
	fillDropDown("selMesto", mesta);
	
	// Assign event handlers:
	var dropDownLists = new Array("selKraj", "selOkres", "selMesto");
	for (var i = 0; i < dropDownLists.length; i++) {
		var sel = document.getElementById(dropDownLists[i]);
		if (typeof sel == "object" && sel.options) {
			// assigning here:
			sel.onchange = onchangeHandler;
		}
	} // end: for
	
	// image mapa - poporidavame title atributy a nstavime ID-cka area elementom
	var map = document.getElementById("map");
	var areas = map.getElementsByTagName("area");
	var area = null;
	var alt = "";
	for (var i = 0; i < areas.length; i++) {
		area = areas.item(i);
		alt = area.getAttribute("alt");
		area.setAttribute("title", alt);
		//console.log("arrayGetKey(abbrOkresy, \""+alt+"\"): " + arrayGetKey(abbrOkresy, alt));
		area.setAttribute("id", "okres" + arrayGetKey(abbrOkresy, alt));
		area.onclick = areaOnClickHandler;
		area = null;
	}
	
	notFoundMsg = document.getElementById("notFoundMsg");
	
} // end: function doIt - main function

function doItIfYouCan() {
	var tempNum = 1.00;
	if (document.getElementsByTagName && tempNum.toFixed) {
		doIt();
	}
}

// Initialize the thing - trigger the main function:
//window.onload = doItIfYouCan;