function InitDatePickerValues() {
    switch (GetFormLanguage()) {
        case 'en':
            // En is default
            $.datepicker.regional['en'] = {
                changeYear: true,
                yearRange: 'c-120:c+10'
            };
            break;

        default: // sk a default
            $.datepicker.regional['sk'] = {
                closeText: 'Zavrieť',
                prevText: '&#x3c;Predchádzajúci',
                nextText: 'Nasledujúci&#x3e;',
                currentText: 'Dnes',
                monthNames: ['Január', 'Február', 'Marec', 'Apríl', 'Máj', 'Jún',
                'Júl', 'August', 'September', 'Október', 'November', 'December'],
                monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Máj', 'Jún',
                'Júl', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'],
                dayNames: ['Nedeľa', 'Pondelok', 'Utorok', 'Streda', 'Štvrtok', 'Piatok', 'Sobota'],
                dayNamesShort: ['Ned', 'Pon', 'Uto', 'Str', 'Štv', 'Pia', 'Sob'],
                dayNamesMin: ['Ne', 'Po', 'Ut', 'St', 'Št', 'Pia', 'So'],
                weekHeader: 'Ty',
                //dateFormat: 'dd.mm.yy',
                firstDay: 1,
                isRTL: false,
                showMonthAfterYear: false,
                yearSuffix: '',
                changeYear: true,
                yearRange: 'c-120:c+10'
            };
    }

    $.datepicker.setDefaults($.datepicker.regional['sk']);
}

$(document).ready(function() {
    //dekoracia mailto:
    var inputValues = $('form').find('[ID]:input');
    inputValues.each(function() {
        var inputValue = $(this);
        if (inputValue.hasClass("xsd_anyURI")) {
            var val = xmlHelper.fromXmlAnyURI(inputValue.val());
            inputValue.val(val);
        }
    });
});

/* OnlineLookup */
var fistOption = "prosím vyberte...";
var fistOptionEN = "please select...";
var autocompleteLength = 15;

function GetOlineLookupUri(url) {
    try {
        if (onlineLookupUri != undefined) {
            return onlineLookupUri;
        }
    } catch (err) { }

    return url;
}

function GetOnlineLookupSlovakValue() {
    try {
        if (onlineLookupSlovakValue != undefined) {
            return onlineLookupSlovakValue;
        }
    } catch (err) { }

    return "Slovenská republika";
}

////////////////////kaskady////////////////
//zoznam novych CLID

var clidKraj = "CL000023";
var clidOkres = "CL000024";
var clidObec = "CL000025";
var clidUlica = "CL010144";
var clidDruhVozidla = "JISCD0023";
var clidDruhKaroserie = "JISCD0024";
var clidDymovost = "JISCD0020";
var clidEmisie = "JISCD0021";
var clidZvuk = "JISCD0022";
var clidBrzdy = "JISCD0019";
var clidKategoriaVozidla = "JISCD0003";

function ESDAdresaFillerStatMesto(stat, obec, url) {
    var staty = Array();
    var obce = Array();

    url = GetOlineLookupUri(url);

    stat.each(function () {
        staty.push($(this));
    });

    obec.each(function () {
        obce.push($(this));
    });

    for (var i = 0; i < staty.length; i++) {
        var adresaFillerStatMesto = new AdresaFillerStatMesto(staty[i], obce[i], url);
        adresaFillerStatMesto.Display();
    }
}

function ESDAdresaFillerStatKrajOkresMesto(stat, kraj, okres, obec, url) {
    var staty = Array();
    var kraje = Array();
    var okresy = Array();
    var obce = Array();

    url = GetOlineLookupUri(url);

    stat.each(function () {
        staty.push($(this));
    });

    kraj.each(function () {
        kraje.push($(this));
    });

    okres.each(function () {
        okresy.push($(this));
    });

    obec.each(function () {
        obce.push($(this));
    });

    for (var i = 0; i < staty.length; i++) {
        var adresaFillerStatKrajOkresMesto = new AdresaFillerStatKrajOkresMesto(staty[i], kraje[i], okresy[i], obce[i], url);
        adresaFillerStatKrajOkresMesto.Display();
    }
}

function ESDAdresaFillerKrajOkresMestoUlica(kraj, okres, obec, ulica, url) {
    var kraje = Array();
    var okresy = Array();
    var obce = Array();
    var ulice = Array();

    url = GetOlineLookupUri(url);

    kraj.each(function () {
        kraje.push($(this));
    });

    okres.each(function () {
        okresy.push($(this));
    });

    obec.each(function () {
        obce.push($(this));
    });

    ulica.each(function () {
        ulice.push($(this));
    });

    for (var i = 0; i < kraje.length; i++) {
        var adresaFillerKrajOkresMestoUlica = new AdresaFillerKrajOkresMestoUlica(kraje[i], okresy[i], obce[i], ulice[i], url);
        adresaFillerKrajOkresMestoUlica.Display();
    }
}

function ESDAdresaFillerStatKrajOkresMestoUlica(stat, kraj, okres, obec, ulica, url) {
    var staty = Array();
    var kraje = Array();
    var okresy = Array();
    var obce = Array();
    var ulice = Array();

    url = GetOlineLookupUri(url);

    stat.each(function () {
        staty.push($(this));
    });

    kraj.each(function () {
        kraje.push($(this));
    });

    okres.each(function () {
        okresy.push($(this));
    });

    obec.each(function () {
        obce.push($(this));
    });

    ulica.each(function () {
        ulice.push($(this));
    });

    for (var i = 0; i < staty.length; i++) {
        var adresaFillerStatKrajOkresMestoUlica = new AdresaFillerStatKrajOkresMestoUlica(staty[i], kraje[i], okresy[i], obce[i], ulice[i], url);
        adresaFillerStatKrajOkresMestoUlica.Display();
    }
}


/* Samotna implementacia scriptov */
var AdresaFillerStatMesto = function(stat, obec, url) {
    var obecBind = false;
    var oldValueStat = stat.val();
    var oldValueObec = obec.val();
    var readOnlyMode = stat.attr("disabled") != undefined &&
        obec.attr("disabled") != undefined;
    var dataFormFile = new Array();

    stat.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    obec.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    this.Display = function () {
        var selectedStat = stat.find("option:selected");
        oldValueStat = stat.val();
        if (selectedStat.text() == GetOnlineLookupSlovakValue()) {
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            if (!readOnlyMode) {
                AdresaFiller.disableOptions(new Array(obec));
            }

            $(document).ready(function() {
                ObecBind();
            });

            Initialize(false);
        } else {
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        }
    }

    stat.keydown(function(data) {
        if (data.which == 9) {
            data.preventDefault();
            stat.blur();

            var focusables = $(":focusable").sort(compareByTabIndex);
            var current = focusables.index(stat);
            var next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);

            next.focus();
        }
    });


    stat.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            return;
        }

        var statNewValue =  stat.val();
        if (oldValueStat == statNewValue) {
            return;
        }

        oldValueStat = statNewValue;

        if ($(data.target).find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            ObecBind();
            AdresaFiller.removeOptions(new Array(obec));
            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
        } else {
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            oldValueObec = null;;
            obec.val("");
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        }
    });

    function ObecBind() {
        if (!obecBind) {
            obecBind = true;
            obec.bind("change", function (obecData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                if (obec.val() == "")
                    AdresaFiller.restartCodeListItems(obec, undefined, undefined, true);
            });
        }
    }

    function Initialize(fromFile) {
        if (fromFile) {
            var obecFileValue = AdresaFiller.getFieldValue(dataFormFile, obec);
            var statFileValue = AdresaFiller.getFieldValue(dataFormFile, stat);
            oldValueStat = statFileValue == null ? null : statFileValue.value;
            oldValueObec = obecFileValue == null ? null : obecFileValue.value;
        }

        AdresaFiller.removeOptions(new Array(obec));
        AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, oldValueObec, false, true);
        if (!readOnlyMode) {
            AdresaFiller.enableOptions(new Array(obec));
        }
    }

    $("form").on("loadedFromXmlCompleted", function (event) {
        if (stat.find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            if (!readOnlyMode) {
                AdresaFiller.disableOptions(new Array(obec));
            }

            ObecBind();
            Initialize(true);
        } else {
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            oldValueStat = stat.val();
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        }
        dataFormFile = new Array();
    });
}

var AdresaFillerStatKrajOkresMesto = function(stat, kraj, okres, obec, url) {
    var krajBind = false;
    var okresBind = false;
    var obecBind = false;
    var dataFormFile = new Array();

    var oldValueStat = null;
    var oldValueKraj = kraj.val();
    var oldValueOkres = okres.val();
    var oldValueObec = obec.val();

    var readOnlyMode = stat.attr("disabled") != undefined &&
        kraj.attr("disabled") != undefined &&
        okres.attr("disabled") != undefined &&
        obec.attr("disabled") != undefined;

    stat.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    kraj.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    okres.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    obec.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    this.Display = function() {

        var selectedStat = stat.find("option:selected");
        oldValueStat = stat.val();
        if (selectedStat.text() == GetOnlineLookupSlovakValue()) {
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }

            $(document).ready(function() {
                KrajBind();
                OkresBind();
                ObecBind();
            });

            Initialize(false);
        } else {
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
    }

    stat.keydown(function(data) {
        if (data.which == 9) {
            data.preventDefault();
            stat.blur();

            var focusables = $(":focusable").sort(compareByTabIndex);
            var current = focusables.index(stat);
            var next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);

            next.focus();
        }
    });

    stat.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            return;
        }

        var statNewValue = stat.val();
        if (oldValueStat == statNewValue) {
            return;
        }

        oldValueStat = statNewValue;

        if ($(data.target).find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);

            KrajBind();
            OkresBind();
            ObecBind();

            AdresaFiller.removeOptions(new Array(kraj, okres, obec));
            AdresaFiller.disableOptions(new Array(okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }
            AdresaFiller.sendRequestCodeListItems(kraj, clidKraj, url, stat.val(), null, true, true);

            if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, null, true, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(okres));
                }
            }
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(obec));
                }
            }
        } else {
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            oldValueKraj = null;
            oldValueOkres = null;
            oldValueObec = null;

            okres.val("");
            obec.val("");
            kraj.val("");

            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
    });

    function KrajBind() {
        if (!krajBind) {
            krajBind = true;
            kraj.bind("change", function(data) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var krajNewValue = kraj.val();

                if (oldValueKraj != krajNewValue) {

                    oldValueKraj = krajNewValue;
                    oldValueOkres = null;
                    oldValueObec = null;
                    AdresaFiller.removeOptions(new Array(okres, obec));
                    okres.change();
                    obec.change();
                    AdresaFiller.disableOptions(new Array(obec, okres));
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres));
                    }

                    if (data.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(okres));
                        }
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            if (!readOnlyMode) {
                                AdresaFiller.enableOptions(new Array(obec));
                            }
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        }
                    } else {
                        AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, $(data.target).val(), null, true, true);
                    }
                }
                if (krajNewValue == "")
                    AdresaFiller.restartCodeListItems(kraj, undefined, undefined, true);
            });
        }
    }

    function OkresBind() {
        if (!okresBind) {
            okresBind = true;
            okres.bind("change", function(okresData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var okresNewValue = okres.val();

                if (oldValueOkres != okresNewValue) {

                    oldValueOkres = okresNewValue;
                    oldValueObec = null;

                    AdresaFiller.removeOptions(new Array(obec));
                    obec.change();
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres, obec));
                    }
                    if (okresData.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(obec));
                        }
                    } else
                        AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, $(okresData.target).val(), null, true, true);
                }
                if (okresNewValue == "")
                    AdresaFiller.restartCodeListItems(okres, undefined, undefined, true);
            });
        }
    }

    function ObecBind() {
        if (!obecBind) {
            obecBind = true;
            obec.bind("change", function (obecData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                if (obec.val() == "")
                    AdresaFiller.restartCodeListItems(obec, undefined, undefined, true);
            });
        }
    }

    function Initialize(fromFile) {
        if (fromFile) {
            var statFileValue = AdresaFiller.getFieldValue(dataFormFile, stat);
            var obecFileValue = AdresaFiller.getFieldValue(dataFormFile, obec);
            var krajFileValue = AdresaFiller.getFieldValue(dataFormFile, kraj);
            var okresFileValue = AdresaFiller.getFieldValue(dataFormFile, okres);
            oldValueKraj = krajFileValue == null ? null : krajFileValue.value;
            oldValueOkres = okresFileValue == null ? null : okresFileValue.value;
            oldValueObec = obecFileValue == null ? null : obecFileValue.value;
            oldValueStat = statFileValue == null ? null : statFileValue.value;
        }

        AdresaFiller.removeOptions(kraj);
        AdresaFiller.sendRequestCodeListItems(kraj, clidKraj, url, oldValueStat, oldValueKraj, false, true);
        if (!readOnlyMode) {
            AdresaFiller.enableOptions(new Array(kraj));
        }

        if (kraj.val() != "" && kraj.val() != null) {
            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, oldValueKraj, oldValueOkres, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(okres));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, oldValueOkres, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(okres));
                }
            } else {
                AdresaFiller.removeOptions(okres);
            }
        }

        if (oldValueOkres != "" && oldValueOkres != null) {
            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, oldValueOkres, oldValueObec, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, oldValueObec, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(obec));
                }
            } else {
                AdresaFiller.removeOptions(obec);
            }
        }
    }

    $("form").on("loadedFromXmlCompleted", function(event) {
        if (stat.find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }

            KrajBind();
            OkresBind();
            ObecBind();

            Initialize(true);
        } else {
            oldValueStat = stat.val();
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
        dataFormFile = new Array();
    });
}

var AdresaFillerStatKrajOkresMestoUlica = function (stat, kraj, okres, obec, ulica, url) {
    var krajBind = false;
    var okresBind = false;
    var obecBind = false;
    var ulicaBind = false;
    var dataFormFile = new Array();

    var oldValueStat = null;
    var oldValueKraj = kraj.val();
    var oldValueOkres = okres.val();
    var oldValueObec = obec.val();

    var readOnlyMode = stat.attr("disabled") != undefined &&
        kraj.attr("disabled") != undefined &&
        okres.attr("disabled") != undefined &&
        obec.attr("disabled") != undefined;

    stat.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    kraj.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    okres.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    obec.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    this.Display = function () {

        var selectedStat = stat.find("option:selected");
        oldValueStat = stat.val();
        if (selectedStat.text() == GetOnlineLookupSlovakValue()) {
            UlicaBind(true);
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }

            $(document).ready(function () {
                KrajBind();
                OkresBind();
                ObecBind();
            });

            Initialize(false);
        } else {
            UlicaBind(false);
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
    }

    stat.keydown(function (data) {
        if (data.which == 9) {
            data.preventDefault();
            stat.blur();

            var focusables = $(":focusable").sort(compareByTabIndex);
            var current = focusables.index(stat);
            var next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);

            next.focus();
        }
    });

    stat.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            return;
        }

        var statNewValue = stat.val();
        if (oldValueStat == statNewValue) {
            return;
        }

        oldValueStat = statNewValue;

        if ($(data.target).find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            UlicaBind(true);
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);

            KrajBind();
            OkresBind();
            ObecBind();

            AdresaFiller.removeOptions(new Array(kraj, okres, obec));
            AdresaFiller.disableOptions(new Array(okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }
            AdresaFiller.sendRequestCodeListItems(kraj, clidKraj, url, stat.val(), null, true, true);

            if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, null, true, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(okres));
                }
            }
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(obec));
                }
            }
        } else {
            UlicaBind(false);
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            oldValueKraj = null;
            oldValueOkres = null;
            oldValueObec = null;

            okres.val("");
            obec.val("");
            kraj.val("");

            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
    });

    function KrajBind() {
        if (!krajBind) {
            krajBind = true;
            kraj.bind("change", function (data) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var krajNewValue = kraj.val();

                if (oldValueKraj != krajNewValue) {

                    oldValueKraj = krajNewValue;
                    oldValueOkres = null;
                    oldValueObec = null;
                    AdresaFiller.removeOptions(new Array(okres, obec));
                    okres.change();
                    obec.change();
                    AdresaFiller.disableOptions(new Array(obec, okres));
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres));
                    }

                    if (data.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(okres));
                        }
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            if (!readOnlyMode) {
                                AdresaFiller.enableOptions(new Array(obec));
                            }
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        }
                    } else {
                        AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, $(data.target).val(), null, true, true);
                    }
                }
                if (krajNewValue == "")
                    AdresaFiller.restartCodeListItems(kraj, undefined, undefined, true);
            });
        }
    }

    function OkresBind() {
        if (!okresBind) {
            okresBind = true;
            okres.bind("change", function (okresData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var okresNewValue = okres.val();

                if (oldValueOkres != okresNewValue) {

                    oldValueOkres = okresNewValue;
                    oldValueObec = null;

                    AdresaFiller.removeOptions(new Array(obec));
                    obec.change();
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres, obec));
                    }
                    if (okresData.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(obec));
                        }
                    } else
                        AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, $(okresData.target).val(), null, true, true);
                }
                if (okresNewValue == "")
                    AdresaFiller.restartCodeListItems(okres, undefined, undefined, true);
            });
        }
    }

    function ObecBind() {
        if (!obecBind) {
            obecBind = true;
            obec.bind("change", function (obecData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                if (obec.val() == "")
                    AdresaFiller.restartCodeListItems(obec, undefined, undefined, true);
            });
        }
    }

    function UlicaBind(autocompleteEnabled) {
        if (autocompleteEnabled) {
            if (!ulicaBind) {
                ulicaBind = true;
                ulica.autocomplete({
                    search: function() {
                        $(this).addClass('working');
                    },
                    open: function() {
                        $(this).removeClass('working');
                    },
                    source: function(request, response) {
                        var data = 'id=' + clidUlica + '&sSearch=' + request.term + '&formId=' + GetFormIdFromMetadata() + '&pluginId=' + GetPluginIdFromMetadata() + "&lookupSource=ESD&bSortable_1=true&iSortCol_0=1&iDisplayLength=" + autocompleteLength;
                        if (obec.val() != null && obec.val() != "") {
                            data += '&parentId=' + obec.val();
                        }

                        $.ajax({
                            type: 'GET',
                            async: true,
                            url: GetLookupUri(),
                            data: data,
                            dataType: "jsonp",
                            success: (function(data) {
                                var autocompleteData = new Array();
                                for (var i = 0; i < data.aaData.length; i++) {
                                    autocompleteData.push({ label: data.aaData[i][1], value: data.aaData[i][1], code: data.aaData[i][0] });
                                }

                                response(autocompleteData);
                            })
                        });
                    }
                });
            }
        } else {
            try { 
                ulica.autocomplete("destroy");
                ulicaBind = false;
            } catch (err) { }
        }
    }

    function Initialize(fromFile) {
        if (fromFile) {
            var statFileValue = AdresaFiller.getFieldValue(dataFormFile, stat);
            var obecFileValue = AdresaFiller.getFieldValue(dataFormFile, obec);
            var krajFileValue = AdresaFiller.getFieldValue(dataFormFile, kraj);
            var okresFileValue = AdresaFiller.getFieldValue(dataFormFile, okres);
            oldValueKraj = krajFileValue == null ? null : krajFileValue.value;
            oldValueOkres = okresFileValue == null ? null : okresFileValue.value;
            oldValueObec = obecFileValue == null ? null : obecFileValue.value;
            oldValueStat = statFileValue == null ? null : statFileValue.value;
        }

        AdresaFiller.removeOptions(new Array(kraj));
        AdresaFiller.sendRequestCodeListItems(kraj, clidKraj, url, oldValueStat, oldValueKraj, false, true);
        if (!readOnlyMode) {
            AdresaFiller.enableOptions(new Array(kraj));
        }

        if (kraj.val() != "" && kraj.val() != null) {
            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, oldValueKraj, oldValueOkres, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(okres));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, oldValueOkres, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(okres));
                }
            } else {
                AdresaFiller.removeOptions(new Array(okres));
            }
        }

        if (oldValueOkres != "" && oldValueOkres != null) {
            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, oldValueOkres, oldValueObec, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, oldValueObec, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(obec));
                }
            }
            else {
                AdresaFiller.removeOptions(new Array(obec));
            }
        }
    }

    $("form").on("loadedFromXmlCompleted", function (event) {
        if (stat.find("option:selected").text() == GetOnlineLookupSlovakValue()) {
            UlicaBind(true);
            kraj = AdresaFiller.convertTextboxToComboboxCodeListItems(kraj);
            okres = AdresaFiller.convertTextboxToComboboxCodeListItems(okres);
            obec = AdresaFiller.convertTextboxToComboboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj));
            }

            KrajBind();
            OkresBind();
            ObecBind();

            Initialize(true);
        } else {
            UlicaBind(false);
            oldValueStat = stat.val();
            kraj = AdresaFiller.convertComboboxToTextboxCodeListItems(kraj);
            okres = AdresaFiller.convertComboboxToTextboxCodeListItems(okres);
            obec = AdresaFiller.convertComboboxToTextboxCodeListItems(obec);
            AdresaFiller.disableOptions(new Array(kraj, okres, obec));
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(kraj, obec, okres));
            }
        }
        dataFormFile = new Array();
    });
}

var AdresaFillerKrajOkresMestoUlica = function(kraj, okres, obec, ulica, url) {
    var krajBind = false;
    var okresBind = false;
    var obecBind = false;
    var ulicaBind = false;
    var dataFormFile = new Array();

    var oldValueKraj = kraj.val();
    var oldValueOkres = okres.val();
    var oldValueObec = obec.val();

    var readOnlyMode = kraj.attr("disabled") != undefined &&
        okres.attr("disabled") != undefined &&
        obec.attr("disabled") != undefined;

    kraj.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    okres.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    obec.change(function(data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    this.Display = function() {
        UlicaBind();
        AdresaFiller.disableOptions(new Array(kraj, okres, obec));
        if (!readOnlyMode) {
            AdresaFiller.enableOptions(new Array(kraj));
        }

        $(document).ready(function() {
            KrajBind();
            OkresBind();
            ObecBind();
        });

        Initialize(false);
    }

    function KrajBind() {
        if (!krajBind) {
            krajBind = true;
            kraj.bind("change", function(data) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var krajNewValue = kraj.val();

                if (oldValueKraj != krajNewValue) {

                    oldValueKraj = krajNewValue;
                    oldValueOkres = null;
                    oldValueObec = null;
                    AdresaFiller.removeOptions(new Array(okres, obec));
                    okres.change();
                    obec.change();
                    AdresaFiller.disableOptions(new Array(obec, okres));
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres));
                    }

                    if (data.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(okres));
                        }
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            if (!readOnlyMode) {
                                AdresaFiller.enableOptions(new Array(obec));
                            }
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        }
                    } else {
                        AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, $(data.target).val(), null, true, true);
                    }
                }
                if (krajNewValue == "")
                    AdresaFiller.restartCodeListItems(kraj, undefined, undefined, true);
            });
        }
    }

    function OkresBind() {
        if (!okresBind) {
            okresBind = true;
            okres.bind("change", function(okresData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                var okresNewValue = okres.val();

                if (oldValueOkres != okresNewValue) {

                    oldValueOkres = okresNewValue;
                    oldValueObec = null;

                    AdresaFiller.removeOptions(new Array(obec));
                    obec.change();
                    if (!readOnlyMode) {
                        AdresaFiller.enableOptions(new Array(kraj, okres, obec));
                    }
                    if (okresData.target.value == "") {
                        if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, null, true, true);
                        } else {
                            AdresaFiller.disableOptions(new Array(obec));
                        }
                    } else
                        AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, $(okresData.target).val(), null, true, true);
                }
                if (okresNewValue == "")
                    AdresaFiller.restartCodeListItems(okres, undefined, undefined, true);
            });
        }
    }

    function ObecBind() {
        if (!obecBind) {
            obecBind = true;
            obec.bind("change", function(obecData) {
                if ($(this).data('newValue') != undefined) {
                    return;
                }

                if (obec.val() == "")
                    AdresaFiller.restartCodeListItems(obec, undefined, undefined, true);
            });
        }
    }

    function UlicaBind() {
        if (!ulicaBind) {
            ulicaBind = true;
            ulica.autocomplete({
                search: function() {
                    $(this).addClass('working');
                },
                open: function() {
                    $(this).removeClass('working');
                },
                source: function(request, response) {
                    var data = 'id=' + clidUlica + '&sSearch=' + request.term + '&formId=' + GetFormIdFromMetadata() + '&pluginId=' + GetPluginIdFromMetadata() + "&lookupSource=ESD&bSortable_1=true&iSortCol_0=1&iDisplayLength=" + autocompleteLength;
                    if (obec.val() != null && obec.val() != "") {
                        data += '&parentId=' + obec.val();
                    }

                    $.ajax({
                        type: 'GET',
                        async: true,
                        url: GetLookupUri(),
                        data: data,
                        dataType: "jsonp",
                        success: (function(data) {
                            var autocompleteData = new Array();
                            for (var i = 0; i < data.aaData.length; i++) {
                                autocompleteData.push({ label: data.aaData[i][1], value: data.aaData[i][1], code: data.aaData[i][0] });
                            }

                            response(autocompleteData);
                        })
                    });
                }
            });
        }
    }

    function Initialize(fromFile) {
        if (fromFile) {
            var obecFileValue = AdresaFiller.getFieldValue(dataFormFile, obec);
            var krajFileValue = AdresaFiller.getFieldValue(dataFormFile, kraj);
            var okresFileValue = AdresaFiller.getFieldValue(dataFormFile, okres);
            oldValueKraj = krajFileValue == null ? null : krajFileValue.value;
            oldValueOkres = okresFileValue == null ? null : okresFileValue.value;
            oldValueObec = obecFileValue == null ? null : obecFileValue.value;
        }

        if (kraj.val() != "" && kraj.val() != null) {
            AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, oldValueKraj, oldValueOkres, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(okres));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres))) {
                AdresaFiller.sendRequestCodeListItems(okres, clidOkres, url, null, oldValueOkres, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(okres));
                }
            } else {
                AdresaFiller.removeOptions(new Array(okres));
            }
        }

        if (oldValueOkres != "" && oldValueOkres != null) {
            AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, oldValueOkres, oldValueObec, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(obec));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(kraj, okres, obec))) {
                AdresaFiller.sendRequestCodeListItems(obec, clidObec, url, null, oldValueObec, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(obec));
                }
            } else {
                AdresaFiller.removeOptions(new Array(obec));
            }
        }
    }

    $("form").on("loadedFromXmlCompleted", function (event) {
        UlicaBind();
        AdresaFiller.disableOptions(new Array(kraj, okres, obec));
        if (!readOnlyMode) {
            AdresaFiller.enableOptions(new Array(kraj));
        }

        Initialize(true);

        dataFormFile = new Array();
    });
}

function AdresaFiller() {

}

AdresaFiller.getFirstOption= function()
{
    var firstOptionText = '';

    switch (GetFormLanguage()) {
        case 'en':
            firstOptionText = fistOptionEN;
            break;
        default: // sk a default
            firstOptionText = fistOption;
    }

    return firstOptionText;
}

AdresaFiller.removeOptions = function (selectBoxies) {
    $.each(selectBoxies, function () {
        var selectBox = $(this);
        selectBox.empty();
    });
}

AdresaFiller.disableOptions = function (selectBoxies) {
    $.each(selectBoxies, function () {
        var selectBox = $(this);
        selectBox.attr('disabled', 'disabled');
    });
}

AdresaFiller.enableOptions = function (selectBoxies) {
    $.each(selectBoxies, function () {
        var selectBox = $(this);
        selectBox.removeAttr('disabled');
    });
}

AdresaFiller.restartCodeListItems = function (item, absoluteXpath, layoutRow, removeAll) {
    if (absoluteXpath == undefined) {
        var xPathClass = item.siblings(".XPathClass");
        if (xPathClass.length > 0) {
            absoluteXpath = xPathClass.html();
        }
    }

    if (layoutRow == undefined) {
        layoutRow = item.closest(".layoutRow");
    }

    if (item.length == 0 || absoluteXpath == undefined || layoutRow.length == 0) {
        return;
    }

    //ak sa jedna o NonCodeListData (mal by byt textbox), tak je nutne schovat
    if (absoluteXpath.indexOf("/NonCodelistData") != -1) {
        var xpath = absoluteXpath.substring(0, absoluteXpath.indexOf("/NonCodelistData"));
        layoutRow.find(".XPathClass").each(function () {
            var xpathInfo = $(this);
            if (absoluteXpath != xpathInfo.html() && xpathInfo.html().length >= xpath.length && xpathInfo.html().substring(0, xpath.length) == xpath) {
                var foundItem = xpathInfo.siblings("select,input");
                if (foundItem.length == 0) {
                    return true;
                }

                var cell = foundItem.closest('.cell');
                cell.addClass('hiddenSection');
                cell.ToggleValidators(true);
                foundItem.val("");
            }
        });
    } else {
        var xpath = absoluteXpath.substring(0, absoluteXpath.indexOf("/Codelist"));
        layoutRow.find(".XPathClass").each(function () {
            var xpathInfo = $(this);
            if (xpathInfo.html().length >= xpath.length && xpathInfo.html().substring(0, xpath.length) == xpath) {
                var foundItem = xpathInfo.siblings("select,input");
                if (foundItem.length == 0) {
                    return true;
                }

                if (xpathInfo.html().indexOf("/NonCodelistData") != -1) {
                    var cell = foundItem.closest('.cell');
                    cell.addClass('hiddenSection');
                    cell.ToggleValidators(true);
                    foundItem.val("");
                } else {
                    var cell = foundItem.closest('.cell');
                    cell.removeClass('hiddenSection');
                    cell.ToggleValidators(false);
                }
                if (removeAll) {
                    foundItem.val("");
                }
            }
        });
    }
}

AdresaFiller.convertComboboxToTextboxCodeListItems = function (item) {

    var xPathClass = item.siblings(".XPathClass");
    if (xPathClass.length == 0) {
        return item;
    }

    var layoutRow = item.closest(".layoutRow");
    var xpath = xPathClass.html();

    //ak je to uz combobox, tak musi vypnut validatory na comboboxe a skrytom poli
    if (item.prop("tagName").toLowerCase() == 'input') {
        AdresaFiller.restartCodeListItems(item, xpath, layoutRow, false);

        return item;
    }

    var actualItem = null;

    //ak je naozaj zmena jeden na druhy
    if (xpath.indexOf("/Codelist") != -1) {
        xpath = xpath.substring(0, xpath.indexOf("/Codelist"));
        var itemCell = item.closest('.cell');
        itemCell.addClass('hiddenSection');
        itemCell.ToggleValidators(true);
        AdresaFiller.removeOptions(new Array(item));

        layoutRow.find(".XPathClass").each(function () {
            var xpathInfo = $(this);
            if (xPathClass.html() == xpathInfo.html()) {
                return true;
            }

            if (xpathInfo.html().length >= xpath.length && xpathInfo.html().substring(0, xpath.length) == xpath) {
                if (xpathInfo.html().indexOf("/CodelistItem/ItemName") != -1) {
                    var foundValueItem = xpathInfo.siblings("input");
                    var itemReferenceCell = foundValueItem.closest('.cell');
                    itemReferenceCell.addClass('hiddenSection');
                    itemReferenceCell.ToggleValidators(true);
                    foundValueItem.val("");
                    return true;
                }

                if (xpathInfo.html().indexOf("/NonCodelistData") != -1) {
                    var foundItem = xpathInfo.siblings("input");
                    if (foundItem.length > 0) {
                        //musi zviditelnit
                        var fieldContentCell = foundItem.closest('.cell');                     
                        fieldContentCell.removeClass('hiddenSection');
                        fieldContentCell.ToggleValidators(false);
                        actualItem = foundItem;
                    }
                }
            }
        });
    }

    return actualItem;
}

AdresaFiller.convertTextboxToComboboxCodeListItems = function (item) {
    var xPathClass = item.siblings(".XPathClass");
    if (xPathClass.length == 0) {
        return item;
    }

    var layoutRow = item.closest(".layoutRow");
    var xpath = xPathClass.html();


    if (item.prop("tagName").toLowerCase() == 'select') {
        AdresaFiller.restartCodeListItems(item, xpath, layoutRow, false);

        return item;
    }

    var actualItem = null;

    if (xpath.indexOf("/NonCodelistData") != -1) {
        xpath = xpath.substring(0, xpath.indexOf("/NonCodelistData"));
        var itemCell = item.closest('.cell');
        itemCell.addClass('hiddenSection');
        itemCell.ToggleValidators(true);
        layoutRow.find(".XPathClass").each(function () {
            var xpathInfo = $(this);
            if (xPathClass.html() != xpathInfo.html() && xpathInfo.html().length >= xpath.length && xpathInfo.html().substring(0, xpath.length) == xpath) {
                var foundItem = xpathInfo.siblings("select,input");
                if (foundItem.length > 0) {
                    var fieldContentCell = foundItem.closest('.cell');
                    fieldContentCell.removeClass('hiddenSection');
                    fieldContentCell.ToggleValidators(false);
                    item.val("");

                    if (foundItem.prop("tagName").toLowerCase() == "select") {
                        actualItem = foundItem;
                        fieldContentCell.removeClass('hiddenSection');
                        fieldContentCell.ToggleValidators(false);
                    }
                }
            }
        });
    }

    return actualItem;
}

AdresaFiller.sendRequestCodeListItems = function (selectBox, name, url, parentCode, selectedCode, async) {
    var values = "id=" + name + "&formId=" + GetFormIdFromMetadata() + "&pluginId=" + GetPluginIdFromMetadata() + "&lookupSource=ESD&bSortable_1=true&iSortCol_0=1";
    if (parentCode != null) {
        values += "&parentId=" + parentCode;
    }

    selectBox.addClass('working');

    $.ajax({
        type: 'GET',
        url: GetOlineLookupUri(null),
        dataType: "jsonp",
        data: values,
        success: function (data) {
            AdresaFiller.removeOptions(new Array(selectBox));
            AdresaFiller.addOptionsCodeListItems(selectBox, data.aaData, selectedCode);
        },
        async: async
    }).done(function(data) {
        selectBox.removeClass('working');
    });
}

AdresaFiller.addOptionsCodeListItems = function (selectBox, items, selectedCode) {
    //quickSort(items, 0, items.length - 1);

    selectBox.append($("<option></option>")
        .attr("value", "")
        .text(AdresaFiller.getFirstOption()));


    for (var i = 0; i < items.length; i++) {
        selectBox.append($("<option></option>")
         .attr("value", items[i][0])
         .text(items[i][1]));
    }

    if (selectedCode != null) {
        selectBox.val(selectedCode);
    }
}

AdresaFiller.getFieldValue = function(dataFromFile, field) {
    for (var i = 0; i < dataFromFile.length; i++) {
        if (dataFromFile[i].field.attr("id") == field.attr("id")) {
            return dataFromFile[i];
        }
    }

    return null;
}

AdresaFiller.isRequeired = function (element) {
    var fieldContent = element.closest(".fieldContent");
    if (fieldContent.length == 0) {
        return false;
    }

    var fieldLabel = fieldContent.siblings(".fieldLabel");
    if (fieldLabel.length == 0) {
        return false;
    }

    var isRequired = fieldLabel.html().indexOf("<em>*</em>") != -1;

    return isRequired;
}

AdresaFiller.downloadRequeired = function (elements) {
    if (elements.length == 0) {
        return false;
    }

    for (var i = elements.length -2; i >= 0; i--) {
        if (AdresaFiller.isRequeired(elements[i])) {
            return false;
        } else {
            if (elements[i].val() != "" && elements[i].val() != null) {
                return false;
            }       
        }
    }

    return true;
}

function quickSort(arr, left, right) {
    var i = left;
    var j = right;
    var tmp;
    var pivotidx = (left + right) / 2;
    var pivot = arr[pivotidx.toFixed()];
    /* partition */
    while (i <= j) {
        while (arr[i][1].localeCompare(pivot[1]) < 0)
            i++;
        while (arr[j][1].localeCompare(pivot[1]) > 0)
            j--;
        if (i <= j) {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    }

    /* recursion */
    if (left < j)
        quickSort(arr, left, j);
    if (i < right)
        quickSort(arr, i, right);
    return arr;
}

function ParseDataFromContainer(dataContainer) {
    if (dataContainer.length % 6 != 0) {
        return null;
    }

    var containerData = new Array();

    for (var i = 0; i < dataContainer.length / 6; i++) {
        var mainItem = null;
        var slaveItem = null;

        var mainItems = dataContainer[i * 6];
        var slaveItems = dataContainer[3 + i * 6];

        mainItems.each(function () {
            var mainItemActual = $(this);
            if (mainItemActual.prop("tagName").toLowerCase() == 'select') {
                mainItem = mainItemActual;
                return false;
            }
        });

        slaveItems.each(function () {
            var slaveItemActual = $(this);
            if (slaveItemActual.prop("tagName").toLowerCase() == 'select') {
                slaveItem = slaveItemActual;
                return false;
            }
        });

        if (mainItem != null && slaveItem != null) {
            var containerItem = new Array();
            containerItem.push(mainItem);
            containerItem.push(slaveItem);
            containerData.push(containerItem);
        }
    }

    return containerData;
}

function ESDDruhVozidlaKategoriaVozidla(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidDruhVozidla, clidKategoriaVozidla);
        eSDBusinessAutocomplete.Display();
    }
}

function ESDDruhVozidlaDruhKaroserie(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidDruhVozidla, clidDruhKaroserie);
        eSDBusinessAutocomplete.Display();
    }
}

function ESDKategoriaVozidlaBrzdy(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidKategoriaVozidla, clidBrzdy);
        eSDBusinessAutocomplete.Display();
    }
}

function ESDKategoriaVozidlaZvuk(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidKategoriaVozidla, clidZvuk);
        eSDBusinessAutocomplete.Display();
    }
}

function ESDKategoriaVozidlaEmisie(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidKategoriaVozidla, clidEmisie);
        eSDBusinessAutocomplete.Display();
    }
}

function ESDKategoriaVozidlaDymivost(dataContainer, url) {
    var containerData = ParseDataFromContainer(dataContainer);
    if (containerData == null) {
        return;
    }

    url = GetOlineLookupUri(url);
    for (var i = 0; i < containerData.length; i++) {
        var eSDBusinessAutocomplete = new ESDBusinessAutocomplete(containerData[i][0], containerData[i][1], url, clidKategoriaVozidla, clidDymovost);
        eSDBusinessAutocomplete.Display();
    }
}


var ESDBusinessAutocomplete = function(item1, item2, url, clidItem1, clidItem2) {

    var oldValueItem1 = item1.val();
    var oldValueItem2 = item2.val();
    var readOnlyMode = item1.attr("disabled") != undefined &&
        item2.attr("disabled") != undefined;
    var dataFormFile = new Array();

    item1.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    item2.change(function (data) {
        if ($(this).data('newValue') != undefined) {
            dataFormFile.push({ field: $(this), value: $(this).data('newValue') });
        }
    });

    if (!readOnlyMode) {
        AdresaFiller.enableOptions(new Array(item1));
        AdresaFiller.disableOptions(new Array(item2));
    }

    this.Display = function() {
        Initialize(false);
    }

    $(document).ready(function () {
        item1.bind("change", function (item1Data) {
            if ($(this).data('newValue') != undefined) {
                return;
            }

            var item1NewValue = item1.val();

            if (oldValueItem1 != item1NewValue) {

                oldValueItem1 = item1NewValue;

                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(item1));
                }

                oldValueItem2 = null;
                AdresaFiller.removeOptions(new Array(item2));
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(item2));
                }
                item2.change();

                if (item1Data.target.value == "")
                    AdresaFiller.disableOptions(new Array(item2));
                else
                    AdresaFiller.sendRequestCodeListItems(item2, clidItem2, url, $(item1Data.target).val(), oldValueItem2, true, true);
            }
            if (item1NewValue == "")
                AdresaFiller.restartCodeListItems(item1, undefined, undefined, true);
        });

        item2.bind("change", function (item2Data) {
            if ($(this).data('newValue') != undefined) {
                return;
            }

            if (item2.val() == "")
                AdresaFiller.restartCodeListItems(item2, undefined, undefined, true);
        });
    });

    function Initialize(fromFile) {
        if (fromFile) {
            var item1FileValue = AdresaFiller.getFieldValue(dataFormFile, item1);
            var item2FileValue = AdresaFiller.getFieldValue(dataFormFile, item2);
            oldValueItem1 = item1FileValue == null ? null : item1FileValue.value;
            oldValueItem2 = item2FileValue == null ? null : item2FileValue.value;
        }

        if (oldValueItem1 != "" && oldValueItem1 != null) {
            AdresaFiller.sendRequestCodeListItems(item2, clidItem2, url, oldValueItem1, oldValueItem2, false, true);
            if (!readOnlyMode) {
                AdresaFiller.enableOptions(new Array(item2));
            }
        } else {
            if (AdresaFiller.downloadRequeired(new Array(item2, item1))) {
                AdresaFiller.sendRequestCodeListItems(item2, clidItem2, url, null, oldValueItem2, false, true);
                if (!readOnlyMode) {
                    AdresaFiller.enableOptions(new Array(item2));
                }
            }
        }
    }

    $("form").on("loadedFromXmlCompleted", function (event) {
        Initialize(true);
        dataFormFile = new Array();
    });
}