// JavaScript Document
/* Autor: RYV */

function najdiLabel(labely, sNazev) {
	for (var i = 0; i < labely.length; i++) {
		if (labely[i].htmlFor == sNazev)
			return labely[i].innerText;
	}

	return "";
}

function jenCisla(sHodnota) {
	var sCisla = "0123456789.";
	
	for (var i = 0; i < sHodnota.length; i++) {
	    if (sCisla.indexOf(sHodnota.charAt(i)) == -1)
	        return false;
 	}
 	
 	return true;
}

function odstranPocKoncNuly(sCislo) {
	var nPozTecka = sCislo.indexOf(".");
	
	// odstraním nuly na začátku
    while (sCislo.length > 1 && sCislo.charAt(0) == "0" && sCislo.charAt(1) != ".") {
		sCislo = sCislo.substring(1);
	}

	// odstraním nuly na konci za des. tečkou
	if (nPozTecka >= 0) {
	    while (sCislo.length > nPozTecka && sCislo.charAt(sCislo.length -1) == "0") {
			sCislo = sCislo.substr(0, sCislo.length - 1);
		}
	}
	
	return sCislo;
}

function shodnaHodnota(sHodnotaOptionu, sVybranaHodnota) {
	if (jenCisla(sHodnotaOptionu) && jenCisla(sVybranaHodnota)) {
		var nPozTecka = sHodnotaOptionu.indexOf(".");

		// parseInt pro řetězce "0008" a "0009" vrací 0!!!
	    // proto vyházím vodící nuly
	    // mohlo by se přepsat pomocí reg. výrazu
	    sHodnotaOptionu = odstranPocKoncNuly(sHodnotaOptionu);
	    sVybranaHodnota = odstranPocKoncNuly(sVybranaHodnota);

		if (nPozTecka != -1) {
			return (parseFloat(sHodnotaOptionu) == parseFloat(sVybranaHodnota));
		}
		else {
			return (parseInt(sHodnotaOptionu) == parseInt(sVybranaHodnota));
		}
	}
	
	return (sHodnotaOptionu == sVybranaHodnota);
}

function setSelectValue(elSelect, sHodnota) {
//alert(elSelect.id);
    if (elSelect == null || elSelect.options == null)
        return;

	for (k = 0; k < elSelect.options.length; k++) {
		if (shodnaHodnota(elSelect.options[k].value, sHodnota)) {
		    elSelect.selectedIndex = k;

			if (elSelect.name == "LQVENKZ" && elSelect.selectedIndex != 0 &&
				document.getElementById("nacteno") == null /* není POVHAV */) {
				nactiModely();
			}

		    break;
		}
	}
}

function vyplnHodnoty(nIndex, sNazev, sHodnota, sTyp, sName1, sName2) {
	// všechny labely
	var labely = document.getElementsByTagName("LABEL");
	var sId = sNazev;
//alert(sNazev + " - " + sTyp);
	if ((sTyp == "text" || sTyp == "hidden" || sTyp == "select") &&
		(sNazev != null && sNazev.length >= 1))
		sNazev = sNazev.substr(1);

	// nIndex musíme upravit na 4 místa
    var sCislo = (nIndex < 10) ?
                    "000" + nIndex :
                    (nIndex < 100) ?
                        "00" + nIndex :
                        (nIndex < 1000) ?
                            "0" + nIndex : nIndex;
    sCislo += " C";

	var el = document.getElementById(sName1 + "    -" + sCislo);

	if (el == null) {
    	return false;
	}

    el.value = sNazev.toLowerCase();

    if (sHodnota != null && sHodnota != "") {
       	document.getElementById(sName2 + "    -" + sCislo).value = sHodnota;
    }

	if (sTyp != "select") {
		document.getElementById("popis   -" + sCislo).innerText = najdiLabel(labely, sId);
	}
//alert("hotovo");
	return true;
}

function pisHodnoty(nIndex, sNazev, sHodnota, sTyp, sName1, sName2, sHodnoty) {
	// všechny labely
    var sHodn = "";

	var labely = document.getElementsByTagName("LABEL");
	var sId = sNazev;

	if (sTyp == "text" && sNazev != null && sNazev.length >= 1)
		sNazev = sNazev.substr(1);

	// nIndex musíme upravit na 4 místa
    var sCislo = (nIndex < 10) ?
                    "000" + nIndex :
                    (nIndex < 100) ?
                        "00" + nIndex :
                        (nIndex < 1000) ?
                            "0" + nIndex : nIndex;
    sCislo += " C";

    if (nIndex > 1) {
        sHodn += "\t";
    }

    sHodn +=  sName1 + "    -" + sCislo + ": " + sNazev.toLowerCase() +
                "\t " + sName2 + "    -" + sCislo + ": " + sHodnota;

    return sHodn;
}

function analyzujInputy (bSimul) { 
    sHodnoty = "";
    // seznam všech inputu
    var inputy = document.getElementsByTagName("INPUT");
    var nIndex = 1;
    var sSeznamZpracRadii = ";";
    var sSeznamZaskrtnutychRadii = ";";

    for (var i = 0; i < inputy.length; i++) {
        var input = inputy[i];
        var sTyp = input.type;
        var sNazev = input.name;
        var sNazevZkr = "";

		// tlačítka neanalyzujem
		if (sTyp == "button") {
		    continue;
		}

		// seznamy neanalyzujem
		// zápis pomocí reg. výrazů nefunguje v FF
		// proto takto debilně
		//	var re = /^[_]{2}[.]*/;
		//if (re.test(sNazev)) {
		if (sNazev.length > 2 &&
			sNazev.substr(0, 2) == "__") {
		    continue;
		}

        if (sTyp == "radio") {
	       if (!(sSeznamZaskrtnutychRadii.indexOf(";" + sNazev + ";") >= 0)) {
				// nebylo dosud zpracováno, zpracuj ho
		       	sSeznamZpracRadii += sNazev + ";";

		       	if (input.checked) { 
					if (!vyplnHodnoty(nIndex, sNazev, input.value, "radio",
								 "__PTFNNM", "__PTFNVA")) {
						alert("Moc parametrů - " + nIndex + ". " + sNazev + " - " + input.value);
						return -1;
					}

					sSeznamZaskrtnutychRadii += sNazev + ";";
					nIndex++;
			   	}

//	           	nIndex++;
	       }

	       continue;
        }

        var sHodnota = (sTyp == "checkbox") ?
		                  (input.checked) ?
				            "A" : "N" :
			              input.value;

        // když nemáš name, tak mne nezajímáš
        if (sNazev == null)
	       continue;

        if (sNazev.length > 8)
            sNazevZkr = sNazev.substring(0, 8);
        else
            sNazevZkr = input.name;

        var sName1 = "__PTFNNM"; // pro název pole
        var sName2 = "__PTFNVA"; // pro hodnotu pole
        // tohle jsou políeka, do kterejch vyplnujeme, ty neanalyzujem
        if (sNazevZkr == sName1 || sNazevZkr == sName2)
            continue;

        // nezaškrtnutý checkboxy mne taky nezajímaj
        if (sTyp == "checkbox" && input.checked == false)
	       continue;

        if ((sTyp == "text") || (sTyp == "radio") || (sTyp == "checkbox") ||
			(sTyp == "hidden" && sNazev.substr(0, 1) == "^")) {
           if (!bSimul) {
	           if (!vyplnHodnoty(nIndex, sNazev, sHodnota, sTyp, sName1, sName2)) {
			   		alert("Moc parametrů - " + nIndex + ". " + sNazev + " - " + sHodnota);
			   		return -1;
				}
           }
           else {
               sHodnoty += pisHodnoty(nIndex, sNazev, sHodnota, sTyp, sName1,
                                      sName2, sHodnoty);
           }
	       nIndex++;
        }
    }

    if (bSimul) {
        alert(sHodnoty);
    }

    return nIndex;
}

function analyzujSelecty(nIndex) {
	var selecty = document.getElementsByTagName("SELECT");
    var sName1 = "__PTFNNM"; // pro název pole
    var sName2 = "__PTFNVA"; // pro hodnotu pole
//alert("select");
	for (var i = 0; i < selecty.length; i++) {
		var select = selecty[i];
		var sNazev = select.name;

		// seznamy neanalyzujem
		if (sNazev.length > 2 &&
			sNazev.substr(0, 2) == "__") {
		    continue;
		}

		// selecty, kde nebylo nic vybráno, mne nezajímaj
		if (select.selectedIndex == -1)
		    continue;

		sNazev = select.name;
		sHodnota = select.options[select.selectedIndex].value;
		sTyp = "select";
//alert(nIndex + ": " + sNazev + " - " + sHodnota);
		if (!vyplnHodnoty(nIndex, sNazev, sHodnota, sTyp, sName1, sName2)) {
			alert("Moc parametrů - " + nIndex + ". " + sNazev + " - " + sHodnota);
			break;
		}

		nIndex++;
	}
}

// spustí se po odeslání formu
function analyzuj(bSimul) {
	try {
		// u nelansa datumů vyházím lomítka
		if (neLansaDatumy != null) {
			for (var i = 0; i < neLansaDatumy.length; i++) {
		    	var el = document.getElementById(neLansaDatumy[i]);
				el.value = el.value.odstranLomitka();
			}
		}
	}
	catch(e) {
	}
	finally {
		// vyházej dvojtečky z nelansovsky předávaných časů
		var elCasProhl = document.getElementById("YHHMMPR");
		
		if (elCasProhl != null) {
			var sCasProhl = elCasProhl.value;
			var nIdxDvojtecky = sCasProhl.indexOf(":");
			
			if (nIdxDvojtecky > 0) {
				elCasProhl.value = sCasProhl.substr(0, 2) + sCasProhl.substr(3, 2);
			}
		}

		// pro inputy s čísly s mezerami po 3, tj. inputy mající:
		// onchange="javascript: formatCisla(this)"
		// zas mezery vyházím

		var inputs = document.getElementsByTagName("INPUT");
		for (var i = 0; i < inputs.length; i++) {
		    if (inputs[i].getAttribute("onbeforedeactivate") == null) {
				continue;
			}

			var sOnbeforedeactivate = new String(inputs[i].getAttribute("onbeforedeactivate"));
			var sText = "formatCisla(this)";

			if (sOnbeforedeactivate.indexOf(sText) > -1) {
				vyhazejMezery(inputs[i]);
			}
		}

		var nIndex = analyzujInputy(bSimul);

		// nedošlo k chybě při zpracování inputů,
		// pokračuj zprac. selectů
		if (nIndex > -1) {
			analyzujSelecty(nIndex);
		}
	}
}

function zpracujRadioCheckbox(inputy, input, nOdkud) {
	// najde v __PTFNNM input s value == input.name
	// je-li odpovídající __PTFNVA == null, pak nezaškrtne, jinak zaškrtne pokud je value == input.value
	var sName1 = 	"__PTFNNM";
	var sName2 = "__PTFNVA";
	var sIndex = "";
	var sTyp = input.type;

    for (var i = inputy.length - 1; i >= nOdkud; i--) {
		if (inputy[i].name == "" || !(inputy[i].type == "text") )
			continue;

		if (inputy[i].name.indexOf(sName1) == -1 || inputy[i].value == "")
			continue;

		if (inputy[i].value.trim().toUpperCase() == input.name.trim().toUpperCase()) {
			sIndex = inputy[i].name.substr(sName1.length);
			sHodnota = document.getElementById(sName2 + sIndex).value;

            input.checked = ((sTyp == "radio" && (input.value.toUpperCase() == sHodnota.toUpperCase()) ||
                             (sTyp == "checkbox" && sHodnota.toUpperCase() == "A"))) ?
                                    true : false;

            // checkbox je s daným name ve formu jen jeden na rozdíl od radiobuttonů -
            // další inputy nemusím zpracovávat
            if (sTyp == "checkbox")
                return;
		}
	}
}

function zpracujText(inputy, input, nOdkud) { 
	// najde v __PTFNNM input s value == input.name.substr(1) - bez prefixu!
	// a dám mu hodnotu odpovídajícího __PTFNVA
	var sName1 = 	"__PTFNNM";
	var sName2 = "__PTFNVA";
	var sIndex = "";
	var sName = input.name.substr(1).toUpperCase();

    for (var i = inputy.length - 1; i >= nOdkud; i--) {
		if (inputy[i].name == "" || !(inputy[i].type == "text") )
			continue;

		if (inputy[i].name.indexOf(sName1) != 0 || inputy[i].value == "")
			continue;

		if (inputy[i].value.trim().toUpperCase() == sName) {
			sIndex = inputy[i].name.substr(sName1.length);
			sHodnota = document.getElementById(sName2 + sIndex).value;
			
			// pokud na input má být použito formátování čísel s mezerami,
			// použij ho
			var sOnbeforedeactivate = new String(inputy[i].getAttribute("onbeforedeactivate"));
			var sText = "formatCisla(this)";

			if (sOnbeforedeactivate.indexOf(sText) > -1) {
				formatCisla(inputy[i]);
			}
			else {
            	input.value = sHodnota;
			}

	        return;
		}
	}
}

function zpracujSelect(inputy, select, nOdkud) {
//alert("zpracujSelect");
	// najde v __PTFNNM input s value == input.name.substr(1) - bez prefixu!
	// a vyberu hodnotu odpovídajícího __PTFNVA
	var sName1 = 	"__PTFNNM";
	var sName2 = "__PTFNVA";
	var sIndex = "";
	var sName = input.name.substr(1).toUpperCase();
	var bNalezeno = false;

    for (var i = inputy.length - 1; i >= nOdkud; i--) {
		if (inputy[i].name == "" || !(inputy[i].type == "text") )
			continue;

		if (inputy[i].name.indexOf(sName1) != 0 || inputy[i].value == "")
			continue;

		if (inputy[i].value.trim().toUpperCase() == sName) {
			sIndex = inputy[i].name.substr(sName1.length);
			var elSelect = document.getElementById(sName2 + sIndex);

			if (elSelect != null) {
			    // nelansovský select
			    bNalezeno = true;
				sHodnota = document.getElementById(sName2 + sIndex).value;
			}

			setSelectValue(elSelect, poleHodnot[i][1]);
/*			for (var j = 0; j < elSelect.options.length; j++) {
				if (elSelect.options[j].value == poleHodnot[i], 1) {
				    elSelect.selectedIndex = j;
				    break;
				}
			}*/

           // input.selectedIndex = sHodnota;
            return;
		}
	}
}

function checkSeznam(inputy) {
    var sPrefix = "__PTFNNM";
    for (var i = inputy.length - 1; i >= 0; i--) {
        if (inputy[i].name.indexOf(sPrefix) == 0) {
            return true;
        }
    }

    return false;
}

// provede se při načítání formu, hodnoty se naplní do formulářových polí
function nahrajHodnotyZeSeznamu() { 
    // seznam všech inputu
    var inputy = document.getElementsByTagName("INPUT");
	var selecty = document.getElementsByTagName("SELECT");

    if (!checkSeznam(inputy))
        return;

    var sName1Prefix = "__PTFNNM"; // pro název pole
    var sName2Prefix = "__PTFNVA"; // pro hodnotu pole

    for (var i = 0; i < inputy.length; i++) {
    	input = inputy[i];
	    var sTyp = inputy[i].type;
	    var sName = input.name;

        if (sTyp == "radio" || sTyp == "checkbox") {
            zpracujRadioCheckbox(inputy, input, i + 1);
            continue;
        }

        if (sTyp == "text" &&
            sName.indexOf(sName1Prefix) == -1 &&
            sName.indexOf(sName2Prefix) == -1) {
            zpracujText(inputy, input, i + 1);
            continue;
        }

		for (i = 0; i < selecty.length; i++) {
		    var select = selecty[i];
			zpracujSelect(selecty, select, i);
		}
    }
}

function nahrajHodnotyZPole() {
	var inputy = document.getElementsByTagName("INPUT");
	var selecty = document.getElementsByTagName("SELECT");
	var elSelModel = document.getElementById("QVENKM");
	var sValue = "-1";

	for (x = 0; x < poleHodnot.length; x++) { 
		var elInput = null;

    	if (poleHodnot[x][0] == "") {
        	continue;
		}

	    var elInput = document.getElementById(poleHodnot[x][0]);
	    if (elInput == null) { 
	        elInput = document.getElementById(poleHodnot[x][0] + "1");
			var bNalezeno = false;

			if (elInput == null && selecty != null) {
				for (var j = 0; j < selecty.length;  j++) {
					if (selecty[j].name.substring(1) == poleHodnot[x][0]) {
						setSelectValue(selecty[j], poleHodnot[x][1]);
						bNalezeno = true;
						break;
					}
				}

	    		continue;
			}
			
			if (!bNalezeno) {
//				alert("Proměnná " + poleHodnot[x][0] + "není v poli hodnot");
			}
	    }

		if (elInput != null) {
			var sTyp = elInput.type;

			if (sTyp == "text" || sTyp == "hidden") {
			    // pokud je textové pole, nahraď "&amp;" za "&".
				elInput.value = (sTyp == "hidden") ?
									poleHodnot[x][1] :
									poleHodnot[x][1].replace(/&amp;/g, "&");

				if (sTyp == "text") {
           			// pokud na input má být použito formátování čísel s mezerami,
					// použij ho
					var sOnbeforedeactivate = new String(elInput.getAttribute("onbeforedeactivate"));
					var sText = "formatCisla(this)";

					if (sOnbeforedeactivate.indexOf(sText) > -1) {
						formatCisla(elInput);
					}
				}
			}
			else {
			    if (sTyp == "radio") {
			        // je více radiobuttonů se stejným názvem, musím najít všecky
		    	    j = 1;
		        	elInput = document.getElementById(poleHodnot[x][0] + j);

				    while (elInput != null) {
						elInput.checked = (elInput.value == poleHodnot[x][1]);
						j++;
						elInput = document.getElementById(poleHodnot[x][0] + j);
					}
				}
				else {
				    if (sTyp == "checkbox") {
				    	elInput.checked = (poleHodnot[x][1] == "A");
					}
					else {
						if (elInput.tagName == "SELECT") {
						//    alert("b");
							setSelectValue(elInput, poleHodnot[x][1]);
						//	alert("c");
						}
					}
				}
			}
		}
	}
}


function nahrajList() { 
	// zjištění, zda existuje pole s hodnotama
	try {
	    nahrajHodnotyZPole();
	}
	catch (e) {
	//alert("chyba");
	    nahrajHodnotyZeSeznamu();
	}
}
