var disableValidatorPostfix = "_SectionIncrement_";
var disableValidatorPrefix = "DoNotValidate_";
var repeatingPostfix = "_Repeating_";
var nonCodeListValueRepresentation = "MIMO_CISELNIKA";

// Setings for RemoteLookup
var remoteLookupHeight = 350;
var remoteLookupWidth = 420;
var remoteLookupBAutoWidth = true;

//////////////// ML //////////////
var repeatingElementPostfix = "-";
/////////////////////////////////

var count = 0;
var fieldIndex = 0;
var sign = "-";
var disableValidators = "disableValidators";

function GetLookupUri() {
    try {
        if (lookupUri != undefined) {
            return lookupUri;
        }
    } catch (err) { }

    return 'http://localhost/ego.filler.ws/lookup.aspx';
}

function GetLookupHierarchicalUri() {
    try {
        if (lookupHierarchicalUri != undefined) {
            return lookupHierarchicalUri;
        }
    } catch (err) { }

    return 'http://localhost/ego.filler.ws/lookupHierarchical.aspx';
}

$.fn.InitHierarchicallyTree = function () {

    //ak su nejake hierarchicke componenty
    //id nodu udava aj jeho hodnotu a preto do id davam code a do cede id
    var hierarchicalTries = this.find(".hierarchicalTree");

    if (hierarchicalTries.length == 0) {
        return this;
    }

    //ziskanie adresy sluzby
    var url = GetLookupUri();
    var urlHierarchical = GetLookupHierarchicalUri();
    var formId = GetFormIdFromMetadata();
    var pluginId = GetPluginIdFromMetadata();

    hierarchicalTries.each(function () {
        var hierarchicalTree = $(this);
        var hierachicaltTreeInstance = new HierarchicallyTree(hierarchicalTree, url, urlHierarchical, formId, pluginId, true);
        hierachicaltTreeInstance.showTree(hierachicaltTreeInstance, true);
    });

    return this;
}

function HierarchicallyTree(hierarchicalTree, url, urlHierarchical, formId, pluginId, reindexTreeAfterPostBuild) {

    this.initializeTree = function (callback, lookupID, lookupSource, values, node, urlHierarchical) {
        var defaultValues = Array();
        if (values != null) {
            var savedValues = values.split("|");
            for (var i = 0; i < savedValues.length; i++) {
                if (savedValues[i] == "") {
                    continue;
                }

                defaultValues.push(savedValues[i]);
            }
        }

        var data = 'id=' + lookupID + '&lookupSource=' + lookupSource + '&formId=' + formId + '&pluginId=' + pluginId;
        if (remoteLanguage.length > 0) {
            data += '&language=' + remoteLanguage.html();
        }
        if (remoteNotCache.length > 0) {
            data += '&notCache=' + remoteNotCache.html();
        }

        if (values != null) {
            data += "&code=" + values;
        }

        $.ajax({
            type: 'GET',
            async: true,
            url: urlHierarchical,
            data: data,
            dataType: "jsonp",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    HierarchicallyTree.addNodeRecursive(0, data[i], node, i, defaultValues);
                }

                callback(node);
            }
        });
    };

    this.showTree = function (hierachicalTreeInstance, enabled) {
        if (remoteSourceIdentifier.length > 0 && remoteLookupCode.length > 0 && remoteSourceId.length > 0 && remoteSourceName.length > 0) {
            hierarchicalTree.chosentree({
                inputId: remoteSourceId.html(),
                inputName: remoteSourceName.html(),
                deepLoad: false,
                collapsed: false,
                selectAll: false,
                selectAllText: "Označ všetko",
                autoSelectChildren: false,
                load: function (node, callback) {
                    var nodeId = node.code == 0 ? null : node.code;
                    if (nodeId != null) {
                        HierarchicallyTree.loadChildren(node, 0, nodeId, callback, remoteLookupCode.html(), remoteSourceIdentifier.html(), url, formId, pluginId, remoteLanguage.html(), remoteNotCache.html());
                    } else {
                        var values = null;
                        if (treeValues.length > 0) {
                            values = treeValues.html();
                        }
                        hierachicalTreeInstance.initializeTree(callback, remoteLookupCode.html(), remoteSourceIdentifier.html(), values, node, urlHierarchical);
                    }
                },
                postbuild: function (node) {
                    if (reindexTreeAfterPostBuild === true) {
                        HierarchicallyTree.reindexTree(hierarchicalTree, remoteXPath, xPathRepeatingXPath, remoteSourceId.html(), remoteSourceName.html(), cssClasses, spanFieldId);

                        if (referencedField != null) {
                            HierarchicallyTree.addReferencedField(hierarchicalTree, node, referencedField, layoutRow);
                        }

                        if (!enabled) {
                            hierarchicalTree.find('input').attr('disabled', 'disabled');
                        }
                    }
                },
                treeloaded: function (node) {
                    HierarchicallyTree.reindexTree(hierarchicalTree, remoteXPath, xPathRepeatingXPath, remoteSourceId.html(), remoteSourceName.html(), cssClasses, spanFieldId);

                    if (referencedField != null) {
                        HierarchicallyTree.addReferencedFieldRecursive(hierarchicalTree, node, referencedField, layoutRow);
                        referencedField.val("");
                    }

                    IncrementElements(layoutRow, referencedField, ["id", "name"]);

                    if (!enabled) {
                        hierarchicalTree.find('input').attr('disabled', 'disabled');
                    }

                    //rozbal strom prcvy checkbox
                    var first = hierarchicalTree.find("li.treenode").first();
                    HierarchicallyTree.unpack(first);
                }
            });
        }
    };

    var cssClasses = hierarchicalTree[0].className.replace('hierarchicalTree', '');

    if (!hierarchicalTree.hasClass("chosentree")) {
        hierarchicalTree.addClass("chosentree");
    }

    var spanLookupConfiguration = hierarchicalTree.siblings(".lookupConfiguration");
    var remoteSourceIdentifier = spanLookupConfiguration.children(".remoteSourceIdentifier");
    var remoteLookupCode = spanLookupConfiguration.children(".remoteLookupCode");
    var remoteSourceId = spanLookupConfiguration.children(".lookupComponentId");
    var remoteSourceName = spanLookupConfiguration.children(".lookupComponentName");
    var xPathRepeatingXPath = spanLookupConfiguration.children(".XPathRepeatingXPath");
    var remoteXPath = spanLookupConfiguration.children(".XPathClass");
    var spanFieldId = spanLookupConfiguration.children(".fieldId");
    var treeValues = hierarchicalTree.children(".hierarchicalTreeValues");
    var remoteLanguage = spanLookupConfiguration.children(".remoteLanguage");
    var remoteNotCache = spanLookupConfiguration.children(".remoteNotCache");

    remoteXPath = remoteXPath.length > 0 ? remoteXPath : null;
    xPathRepeatingXPath = xPathRepeatingXPath.length > 0 ? xPathRepeatingXPath : null;

    var layoutRow = hierarchicalTree.closest(".layoutRow");
    var referencedField = null;

    if (spanFieldId.length > 0) {
        var fieldId = spanFieldId.html();
        var fields = layoutRow.find('[id|="' + fieldId + '"]');
        referencedField = fields.first();
        //prvy bude sluzit len na klonovanie
        referencedField.closest('.cell').ToggleValidators(true);
    }
}

HierarchicallyTree.unpack = function (node) {
    var nodes = new Array();
    nodes.push(node);

    node.siblings("li.treenode").each(function () {
        var siblingNode = $(this);
        nodes.push(siblingNode);
    });

    //nema zmysel, ked uz nema nikoho na svojej urovni
    if (nodes.length == 1) {
        return;
    }

    for (var i = 0; i < nodes.length; i++) {
        var isSelected = nodes[i].find("input:checked").length > 0;
        if (isSelected) {
            var expandElement = nodes[i].children('.treeselect-expand');
            if (expandElement.length == 0) {
                continue;
            }

            if (expandElement.hasClass("collapsed")) {
                expandElement.click();
            }
        }

        HierarchicallyTree.unpack(nodes[i].find("li.treenode").first());
    }
}

HierarchicallyTree.addNodeRecursive = function (level, lookupEntityHierarchical, node, index, defaultValues) {
    var checked = false;
    if (defaultValues.length > 0) {
        for (var i = 0; i < defaultValues.length; i++) {
            if (defaultValues[i] == lookupEntityHierarchical.LookupEntity.Code) {
                checked = true;
                break;
            }
        }
    } else {
        checked = lookupEntityHierarchical.Selected;
    }

    var newNode = {
        odd: index % 2 == 0,
        checked: checked,
        id: lookupEntityHierarchical.LookupEntity.Code,
        code: lookupEntityHierarchical.LookupEntity.ID,
        title: lookupEntityHierarchical.LookupEntity.Value,
        has_children: lookupEntityHierarchical.IsLast == null ? true : !lookupEntityHierarchical.IsLast,
        level: level,
        children: []
    };

    node.children.push(newNode);

    var lastNode = node.children[node.children.length - 1];

    if (lookupEntityHierarchical.LookupsHierarchical != null) {
        for (var i = 0; i < lookupEntityHierarchical.LookupsHierarchical.length; i++) {
            HierarchicallyTree.addNodeRecursive(level + 1, lookupEntityHierarchical.LookupsHierarchical[i], lastNode, i, defaultValues);
        }
    }
}

HierarchicallyTree.loadChildren = function (node, level, nodeId, callback, lookupID, lookupSource, url, formId, pluginId, remoteLanguage, remoteNotCache) {
    var data = 'id=' + lookupID + '&lookupSource=' + lookupSource + '&formId=' + formId + '&pluginId=' + pluginId;
    if (remoteLanguage!= undefined) {
        data += '&language=' + remoteLanguage.html();
    }
    if (remoteNotCache!= undefined) {
        data += '&notCache=' + remoteNotCache.html();
    }

    if (nodeId != null) {
        data += "&parentId=" + nodeId;
    }

    $.ajax({
        type: 'GET',
        async: true,
        url: url,
        data: data,
        dataType: "jsonp",
        success: function (data) {
            if (data.iTotalDisplayRecords == 0) {
                node.has_children = false;
                node.busy = false;
                delete node.children[0];
            } else {

                for (var i = 0; i < data.aaData.length; i++) {
                    node.children.push({
                        id: data.aaData[i][0],
                        title: data.aaData[i][1],
                        code: data.aaData[i][2],
                        has_children: true,
                        level: node.level + 1,
                        children: []
                    });
                }
            }

            callback(node);
        }
    });
};

HierarchicallyTree.addReferencedField = function (hierarchicalTree, node, field, layoutRow) {
    var clonedFieldContent = field.closest(".fieldContent").clone();
    clonedFieldContent.ToggleValidators(false);

    //ked sa zaskrtne, tak sa vlozi itemName, inak sa odstrani ak existuje
    node.input.bind('click', function () {
        var referField = node.input.siblings(".fieldContent");
        if (node.checked) {
            if (referField.length == 0) {
                clonedFieldContent.insertAfter(node.input);
                var clonedField = clonedFieldContent.find("input");
                clonedField.val(node.title);
                IncrementElements(layoutRow, clonedField, ["id", "name"]);
            }
        } else {
            if (referField.length > 0) {
                referField.remove();
            }
        }
    });

    //ak sa jedna o defaultne nacitanie, tak uz moze byt zaskrtnute a preto to treba pridat aj s hodnotou
    if (node.checked) {
        var referField = node.input.siblings(".fieldContent");
        if (referField.length == 0) {
            clonedFieldContent.insertAfter(node.input);
            var clonedField = clonedFieldContent.find("input");
            clonedField.val(node.title);
        }
    }
}

HierarchicallyTree.addReferencedFieldRecursive = function (hierarchicalTree, node, field, layoutRow) {
    for (var j = 0; j < node.children.length; j++) {
        HierarchicallyTree.addReferencedField(hierarchicalTree, node.children[j], field, layoutRow);
        HierarchicallyTree.addReferencedFieldRecursive(hierarchicalTree, node.children[j], field);
    }
}

HierarchicallyTree.reindexTree = function (hierarchicalTree, remoteXPath, xPathRepeatingXPath, id, name, cssClasses) {
    var checkboxes = hierarchicalTree.find(':checkbox');
    var position = 0;
    checkboxes.each(function () {
        var checkbox = $(this);
        checkbox.attr("name", id);
        checkbox.addClass(cssClasses);
        checkbox.attr("id", name + "PostfixList" + (position == 0 ? "" : position));
        position++;
    });

    if (remoteXPath != null) {
        checkboxes.each(function () {
            var checkbox = $(this);
            if (checkbox.siblings('.XPathClass').length == 0) {
                checkbox.after(remoteXPath.clone());
            }
            if (xPathRepeatingXPath != null) {
                if (checkbox.siblings('.XPathRepeatingXPath').length == 0) {
                    checkbox.after(xPathRepeatingXPath.clone());
                }
            }
        });
    }
}

$.fn.InitHelp = function () {

    var InfoDialog = function () {
        var infoIcon = $(this);
        var modal = infoIcon.find(".dialog-modal");
        modal.dialog({
            position: {
                my: "left",
                at: "right",
                of: infoIcon,
                offset: "20 20"
            },
            open: function (event, ui) {
                infoIcon.unbind('mouseout');
                infoIcon.mouseout(function () {
                    var target = $(event.target);
                    target.dialog('destroy');
                    target.appendTo(modal);
                });
                infoIcon.mousedown(function () {
                    infoIcon.unbind('mouseout');
                });
            },
            close: function (event, ui) {
                var target = $(event.target);
                target.dialog('destroy');
                target.appendTo(modal);
            }
        });
    };

    this.find(".info").mouseover(InfoDialog);

    return this;
}

$.fn.InitAutocompletes = function () {
    var autocompletes = $(".autocomplete");
    var formId = GetFormIdFromMetadata();
    var pluginId = GetPluginIdFromMetadata();

    if (autocompletes.length > 0) {
        autocompletes.each(function() {
            var autocomplete = $(this);
            var closestLayoutRow = autocomplete.closest(".layoutRow");
            var spanLookupConfiguration = autocomplete.siblings(".autocompleteConfiguration");
            var remoteSourceIdentifier = spanLookupConfiguration.children(".remoteSourceIdentifier");
            var remoteLookupCode = spanLookupConfiguration.children(".remoteLookupCode");
            var remoteLanguage = spanLookupConfiguration.children(".remoteLanguage");
            var remoteNotCache = spanLookupConfiguration.children(".remoteNotCache");
            var spanFieldId = spanLookupConfiguration.children(".fieldId");
            var referencedField = null;

            var fieldId = null;
            if (spanFieldId.length > 0) {
                fieldId = spanFieldId.html();
            }

            if (fieldId) {
                var comboBoxId = autocomplete.attr("name");
                var repetionsSectionId = "";
                var repetionsSectionIdPostfix = "";
                var idParts = comboBoxId.split('-');

                if (idParts.length > 1) {
                    repetionsSectionId = idParts[idParts.length - 1];
                    repetionsSectionIdPostfix = "-" + repetionsSectionId;
                }

                var fields = closestLayoutRow.find("#" + fieldId.replace(disableValidatorPrefix, '') + repetionsSectionIdPostfix);
                if (fields.length > 0) {
                    referencedField = fields.first();
                }
            }

            autocomplete.autocomplete({
                search: function () {
                    $(this).addClass('working');
                },
                open: function () {
                    $(this).removeClass('working');
                },
                source: function(request, response) {

                    var data = 'id=' + remoteLookupCode.html() + '&lookupSource=' + remoteSourceIdentifier.html() + '&sSearch=' + request.term + '&formId=' + formId + '&pluginId=' + pluginId;
                    if (remoteLanguage != undefined) {
                        data += '&language=' + remoteLanguage.html();
                    }
                    if (remoteNotCache != undefined) {
                        data += '&notCache=' + remoteNotCache.html();
                    }

                    $.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);
                        })
                    });
                },
                select: function (a, b) {
                    if (referencedField != null) {
                        referencedField(b.item.code);
                    }
                }
            });
        });
    }

    return this;
}

$.fn.InitMultiCombobox = function () {
    var elements = $(".multiCombobox");
    if (elements.length > 0) {
        elements.multiselect();
    }

    return this;
}

$.fn.DeleteMultiCombobox = function () {
    var elements = $(".multiCombobox");
    if (elements.length > 0) {
        elements.multiselect("destroy");
    }

    return this;
}

$.fn.DeleteAutocompletes = function () {
    var elements = $(".autocomplete");
    if (elements.length > 0) {
        elements.autocomplete("destroy");
    }

    return this;
}

function InitComboboxOnLoad(elements) {
    elements.each(function () {
        var element = $(this);
        var spanLookupConfiguration = element.siblings(".lookupConfiguration");
        var spanNonCodeListValue = spanLookupConfiguration.children(".nonCodeListValue");

        if ((element.val() != '' && element.val() != null) || spanNonCodeListValue.length > 0) {
            element.change();
        }
    });
}

$.fn.InitRemoteCombobox = function() {
    var elements = this.find(".remoteComboBox");
    elements.each(function() {
        var remoteComboBox = $(this);
        var closestLayoutRow = remoteComboBox.closest(".layoutRow");
        var fieldId = null;
        var spanLookupConfiguration = remoteComboBox.siblings(".lookupConfiguration");
        var spanFieldId = spanLookupConfiguration.children(".fieldId");
        var spanNonCodeListValue = spanLookupConfiguration.children(".nonCodeListValue");
        if (spanFieldId.length > 0) {
            fieldId = spanFieldId.html();
        }

        var referencedField = null;
        var nonCodeListElement = null;

        if (fieldId) {
            var comboBoxId = remoteComboBox.attr("name");
            var repetionsSectionId = "";
            var repetionsSectionIdPostfix = "";
            var idParts = comboBoxId.split('-');

            if (idParts.length > 1) {
                repetionsSectionId = idParts[idParts.length - 1];
                repetionsSectionIdPostfix = "-" + repetionsSectionId;
            }

            var fields = closestLayoutRow.find("#" + fieldId.replace(disableValidatorPrefix, '') + repetionsSectionIdPostfix);
            if (fields.length > 0) {
                referencedField = fields.first();
            }
        }

        if (spanNonCodeListValue.length > 0) {
            var xPathClass = remoteComboBox.siblings(".XPathClass");

            if (xPathClass.length > 0) {
                var xpath = xPathClass.html();

                if (xpath.indexOf("/Codelist") != -1) {
                    xpath = xpath.substring(0, xpath.indexOf("/Codelist"));

                    closestLayoutRow.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("/NonCodelistData") != -1) {
                                nonCodeListElement = xpathInfo.siblings("input");

                                return false;
                            }
                        }
                    });
                }
            }
        }

        //nastavenie kodu na zaklade referencovanej hodnoty
        if (!remoteComboBox.val() && referencedField && referencedField.val()) {
            remoteComboBox.find("option").each(function () {
                this.selected = $(this).text() === fields.first().val();
            });
        }

        remoteComboBox.change(function(e) {
            Combobox(remoteComboBox, closestLayoutRow, referencedField, nonCodeListElement, e.originalEvent === undefined);
        });
    });

    if (elements.length > 0) {
        InitComboboxOnLoad(elements);

        $("form").on("loadedFromXmlCompleted", function() {
            InitComboboxOnLoad(elements);
        });
    }

    return this;
}

$.fn.InitCombobox = function () {
    var elements = this.find(".comboBox");
    elements.each(function () {
        var comboBox = $(this);
        var closestLayoutRow = comboBox.closest(".layoutRow");
        var fieldId = null;
        var spanLookupConfiguration = comboBox.siblings(".lookupConfiguration");
        var spanFieldId = spanLookupConfiguration.children(".fieldId");
        var spanNonCodeListValue = spanLookupConfiguration.children(".nonCodeListValue");
        if (spanFieldId.length > 0) {
            fieldId = spanFieldId.html();
        }

        var referencedField = null;
        var nonCodeListElement = null;

        if (fieldId) {
            var comboBoxId = comboBox.attr("name");
            var repetionsSectionId = "";
            var repetionsSectionIdPostfix = "";
            var idParts = comboBoxId.split('-');

            if (idParts.length > 1) {
                repetionsSectionId = idParts[idParts.length - 1];
                repetionsSectionIdPostfix = "-" + repetionsSectionId;
            }

            var fields = closestLayoutRow.find("#" + fieldId.replace(disableValidatorPrefix, '') + repetionsSectionIdPostfix);
            if (fields.length > 0) {
                referencedField = fields.first();
            }
        }

        if (spanNonCodeListValue.length > 0) {
            var xPathClass = comboBox.siblings(".XPathClass");

            if (xPathClass.length > 0) {
                var xpath = xPathClass.html();

                if (xpath.indexOf("/Codelist") != -1) {
                    xpath = xpath.substring(0, xpath.indexOf("/Codelist"));

                    closestLayoutRow.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("/NonCodelistData") != -1) {
                                nonCodeListElement = xpathInfo.siblings("input");

                                return false;
                            }
                        }
                    });
                }
            }
        }

        //nastavenie kodu na zaklade referencovanej hodnoty
        if (!comboBox.val() && referencedField && referencedField.val()) {
            comboBox.find("option").each(function () {
                this.selected = $(this).text() === fields.first().val();
            });
        }

        comboBox.change(function (e) {
            Combobox(comboBox, closestLayoutRow, referencedField, nonCodeListElement, e.originalEvent === undefined);
        });
    });

    if (elements.length > 0) {
        InitComboboxOnLoad(elements);

        $("form").on("loadedFromXmlCompleted", function () {
            InitComboboxOnLoad(elements);
        });
    }

    return this;
}

function Combobox(comboBox, layoutRow, referencedField, nonCodeListElement, isLoadEvent) {
    isLoadEvent = (typeof isLoadEvent === 'undefined') ? true : isLoadEvent;

    if (referencedField != null) {
        referencedField.val(comboBox.find("option:selected").text());

        if (nonCodeListElement != null) {
            var nonCodeListElementCell = nonCodeListElement.closest('[id^=layoutCell]');
            var comboBoxCell = comboBox.closest('[id^=layoutCell]');
            var fieldsCell = referencedField.closest('[id^=layoutCell]');

            if (comboBox.val() === nonCodeListValueRepresentation) {
                referencedField.val('');

                comboBoxCell.ToggleValidators(true);
                fieldsCell.ToggleValidators(true);

                nonCodeListElementCell.removeClass('hiddenSection');
                nonCodeListElementCell.ToggleValidators(false);
            } else if (isLoadEvent && comboBox.val() === '' && nonCodeListElement.val() !== '') {
                comboBox.val(nonCodeListValueRepresentation);

                comboBoxCell.ToggleValidators(true);
                fieldsCell.ToggleValidators(true);

                nonCodeListElementCell.removeClass('hiddenSection');
                nonCodeListElementCell.ToggleValidators(false);
            } else {
                comboBoxCell.ToggleValidators(false);
                fieldsCell.ToggleValidators(false);

                nonCodeListElementCell.addClass('hiddenSection');
                nonCodeListElementCell.ToggleValidators(true);
            }
        }
    }
}

$.fn.InitRadioButonList = function () {
    var elements = this.find(".radioButtonList");

    elements.each(function () {
        var element = $(this);
        var layoutRow = element.closest(".layoutRow");
        var referencedField = null;

        var radioButtonLists = element.find("input");
        radioButtonLists.each(function() {
            var radioButtonList = $(this);

            if (referencedField == null) {
                var fieldId = null;
                var spanLookupConfiguration = radioButtonList.parent().siblings(".lookupConfiguration");
                var spanFieldId = spanLookupConfiguration.children(".fieldId");
                if (spanFieldId.length > 0) {
                    fieldId = spanFieldId.html();
                }

                if (fieldId) {
                    var comboBoxId = radioButtonList.attr("name");
                    var repetionsSectionId = "";
                    var repetionsSectionIdPostfix = "";
                    var idParts = comboBoxId.split('-');

                    if (idParts.length > 1) {
                        repetionsSectionId = idParts[idParts.length - 1];
                        repetionsSectionIdPostfix = "-" + repetionsSectionId;
                    }

                    var fields = layoutRow.find("#" + fieldId.replace(disableValidatorPrefix, '') + repetionsSectionIdPostfix);
                    if (fields.length > 0) {
                        referencedField = fields.first();
                    }
                }
            }

            if (referencedField != null) {
                radioButtonList.click(function() {
                    referencedField.val(radioButtonList.siblings("label").html());
                });
            }

            if (radioButtonList.is(":checked")) {
                radioButtonList.click();
            }
        });
    });

    return this;
}

$.fn.InitRemoteRadioButonList = function() {
    var elements = this.find("div.remoteRadioButtonList");

    elements.each(function () {
        var element = $(this);
        var layoutRow = element.closest(".layoutRow");
        var referencedField = null;

        var remoteRadioButtonLists = element.find("input.remoteRadioButtonList");
        remoteRadioButtonLists.each(function () {
            var remoteRadioButtonList = $(this);

            if (referencedField == null) {
                var fieldId = null;
                var spanLookupConfiguration = remoteRadioButtonList.parent().siblings(".lookupConfiguration");
                var spanFieldId = spanLookupConfiguration.children(".fieldId");
                if (spanFieldId.length > 0) {
                    fieldId = spanFieldId.html();
                }

                if (fieldId) {
                    var comboBoxId = remoteRadioButtonList.attr("name");
                    var repetionsSectionId = "";
                    var repetionsSectionIdPostfix = "";
                    var idParts = comboBoxId.split('-');

                    if (idParts.length > 1) {
                        repetionsSectionId = idParts[idParts.length - 1];
                        repetionsSectionIdPostfix = "-" + repetionsSectionId;
                    }

                    var fields = layoutRow.find("#" + fieldId.replace(disableValidatorPrefix, '') + repetionsSectionIdPostfix);
                    if (fields.length > 0) {
                        referencedField = fields.first();
                    }
                }
            }

            if (referencedField != null) {
                remoteRadioButtonList.click(function () {
                    referencedField.val(remoteRadioButtonList.siblings("label").html());
                });
            }

            if (remoteRadioButtonList.is(":checked")) {
                remoteRadioButtonList.click();
            }
        });

    });

    return this;
}

$.fn.InitRemoteCheckBoxList = function () {
    var remoteRadioButtonLists = this.find("div.remoteCheckBoxList");
    if (remoteRadioButtonLists.length > 0) {
        remoteRadioButtonLists.each(function () {
            var remoteRadioButtonList = $(this);
            var elements = remoteRadioButtonList.find("input.remoteCheckBoxList");

            elements.each(function () {
                var element = $(this);

                element.click(function () {
                    CheckBoxList(element, true);
                });

                //ak su skopirovane, tak sa prenasali aj skryte naklonovane elementy
                CheckBoxList(element, false);
            });
        });
    }

    return this;
}

function CheckBoxList(checkboxListItem, onClick) {
    var checkboxListItemId = checkboxListItem.attr("name");
    if (checkboxListItemId != undefined) {
        var idParts = checkboxListItemId.split('-');
        if (idParts.length > 1) {
            checkboxListItemId = idParts[0];
        }

        var layoutRow = checkboxListItem.closest(".layoutRow");

        var spanLookupConfiguration = checkboxListItem.parent().siblings(".lookupConfiguration");
        if (spanLookupConfiguration.length > 0) {
            var spanLookupComponentId = spanLookupConfiguration.children(".lookupComponentId");
            var spanFieldId = spanLookupConfiguration.children(".fieldId");

            if (spanFieldId.length > 0 && spanLookupComponentId.length > 0 && spanLookupComponentId.html() == checkboxListItemId) {

                var fieldId = spanFieldId.html();
                var fields = layoutRow.find('[id|="' + fieldId + '"]');
                var referencedField = null;

                //zmazu sa vsetky pomocne skryte polia, do ktorych sa vklada samotna hodnota itemName
                fields.each(function () {
                    var itemName = $(this);
                    if (itemName.parent('.fieldContent').length > 0 && itemName.parent('.fieldContent').siblings(':checkbox').length == 0) {
                        referencedField = itemName;
                        itemName.val("");
                        var itemNameCell = itemName.closest('.cell');
                        itemNameCell.addClass('hiddenSection');
                        itemNameCell.ToggleValidators(true);
                    }
                });

                if (referencedField == null) {
                    return;
                }

                //ak je oznacene ze existuje, tak sa mu prida naklonovany field
                var clonedFieldContent = referencedField.closest(".fieldContent").clone();
                clonedFieldContent.removeClass('hiddenSection');
                clonedFieldContent.ToggleValidators(false);

                //ked sa zaskrtne, tak sa vlozi itemName, inak sa odstrani ak existuje
                var referField = checkboxListItem.siblings(".fieldContent");
                var reindex = false;

                if (checkboxListItem.is(":checked")) {
                    if (referField.length == 0) {
                        clonedFieldContent.insertAfter(checkboxListItem);
                        var clonedField = clonedFieldContent.find("input");
                        clonedField.val(checkboxListItem.siblings("label").html());
                        reindex = true;
                    }
                } else {
                    if (referField.length > 0) {
                        referField.remove();
                        reindex = true;
                    }
                }

                if (onClick && reindex) {
                    checkboxListItem.closest('.cell').IncrementFieldIds();
                }
            }
        }
    }
}

$.fn.InitSectionAccordion = function () {
    var allCaption = this.find(".caption");
    var isInfoIconClicked = false;

    var showText = "Rozbaliť";
    var hideText = "Zbaliť";

    switch (GetFormLanguage()) {
        case 'en':
            showText = "Unpack";
            hideText = "Pack";
            break;
    }

    allCaption.attr("title", hideText);

    allCaption.find('.info').click(function (e) {
        e.preventDefault;
        isInfoIconClicked = true;
    });

    allCaption.click(function () {
        if (!isInfoIconClicked) {
            var caption = $(this);
            var layoutRowContent = caption.next(".columns");
            var isEmpty = layoutRowContent.parent().attr('isEmpty');
            var arrowSpan = caption.children("span.ui-icon");

            arrowSpan.toggleClass("ui-icon-carat-1-n").toggleClass("ui-icon-carat-1-s");
            if (arrowSpan.hasClass("ui-icon-carat-1-n")) {
                arrowSpan.attr("title", hideText);
            } else {
                arrowSpan.attr("title", showText);
            }
            //layoutRowContent.slideToggle(0);
            if (arrowSpan.hasClass("ui-icon-carat-1-n")) {
                if (isEmpty != 'true')
                    layoutRowContent.show();
            } else if (arrowSpan.hasClass("ui-icon-carat-1-s")) {
                if (isEmpty != 'true')
                    layoutRowContent.hide();
            }
        }
        else {
            isInfoIconClicked = false;
        }
    });

    return this;
};

// Skok na pozadovany element s pripadnym rozbalenim zbalenych sekcii interakciou chybovej hlasky
function expandLayoutRowsAndFocus() {
    $('.error[for], .warning[for]').live("focus click", function (e) {
        e.preventDefault();

        var closestLayotRow = $("[id='" + this.htmlFor + "']").closest('.layoutRow');
        var firstCaption;

        if (closestLayotRow[0]) {
            firstCaption = $(closestLayotRow[0]).find('.caption').first();

            if (firstCaption.children("span.ui-icon").hasClass("ui-icon-carat-1-s"))
                firstCaption.click();
        }

        while (closestLayotRow[0]) {
            if (closestLayotRow[0].parentElement) {
                closestLayotRow = $(closestLayotRow[0].parentElement).closest('.layoutRow');

                if (closestLayotRow[0]) {
                    firstCaption = $(closestLayotRow[0]).find('.caption').first();

                    if (firstCaption.children("span.ui-icon").hasClass("ui-icon-carat-1-s"))
                        firstCaption.click();
                }
            }
        }

        $("[id='" + this.htmlFor + "']").focus();
    });
}

$.fn.RemoveDatePickerClass = function () {
    this.find(".datepicker, .datepickerISO, .timepicker, .datetimepicker, .datetimewithsecondspicker").removeClass("hasDatepicker");

    return this;
};

$.fn.InitDatePicker = function () {
    this.find(".datepicker").datepicker();

    return this;
};

$.fn.InitDateTimeControl = function () {
    this.find(".datetimepicker").datetimepicker();

    return this;
};

$.fn.InitPopUpDialog = function () {
    RemoteLookupNew(this);

    return this;
}

function GetFormLanguage() {
    return $('meta[name=language]').attr("content");
}


function RemoteLookupAfterLoadItems(table) {
    return true;
}

function RemoteLookupNew(layoutRow) {

    var elements = layoutRow.find(".remoteLookup");
    elements.each(function () {
        var remoteLookup = $(this);

        var lookupDetailInfo = remoteLookup.siblings('.LookupDetailInfo');
        var lookupInfo = remoteLookup.parent().siblings(".fieldInfo");
        var lookupFieldValue = null;
        lookupDetailInfo.val("");

        //Nacitanie hodnot z konfiguracnej sekcie
        var spanLookupConfiguration = remoteLookup.siblings(".lookupConfiguration");
        var spanLookupComponentId = spanLookupConfiguration.children(".lookupComponentId");
        var spanFieldId = spanLookupConfiguration.children(".fieldId");
        var remoteSourceIdentifier = spanLookupConfiguration.children(".remoteSourceIdentifier");
        var remoteLookupCode = spanLookupConfiguration.children(".remoteLookupCode");
        var remoteLanguage = spanLookupConfiguration.children(".remoteLanguage");
        var remoteNotCache = spanLookupConfiguration.children(".remoteNotCache");

        var nonCodeListElement = null;
        var closestLayoutRow = remoteLookup.closest(".layoutRow");

        var xPathClass = remoteLookup.siblings(".XPathClass");
        if (xPathClass.length > 0) {
            var xpath = xPathClass.html();
            if (xpath.indexOf("/Codelist") != -1) {
                xpath = xpath.substring(0, xpath.indexOf("/Codelist"));

                closestLayoutRow.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("/NonCodelistData") != -1) {
                            nonCodeListElement = xpathInfo.siblings("input");

                            return false;
                        }
                    }
                });
            }
        }

        if (spanFieldId.length > 0) {
            var isCtrl = false;
            var isCtrlV = false;
            var isCtrlX = false;
            var isCtrlA = false;

            lookupFieldValue = closestLayoutRow.find('[id|="' + spanFieldId.html() + '"]');

            remoteLookup.keydown(function (data) {
                if (data.ctrlKey)
                    isCtrl = true;
                else
                    isCtrl = false;

                if (data.ctrlKey && data.which == 86)
                    isCtrlV = true;
                else
                    isCtrlV = false;

                if (data.ctrlKey && data.which == 88)
                    isCtrlX = true;
                else
                    isCtrlX = false;

                if (data.ctrlKey && data.which == 65)
                    isCtrlA = true;
                else
                    isCtrlA = false;
            });

            remoteLookup.keyup(function (data) {
                if (remoteLookup.val() !== "" && (!isCtrl || isCtrlV || isCtrlX) && !isCtrlA) {
                    //zobrazi sa noncodelist
                    if (nonCodeListElement != null) {
                        lookupFieldValue.val("");
                        var remoteLookupCell = remoteLookup.closest('.cell');
                        remoteLookupCell.addClass('hiddenSection');
                        remoteLookupCell.ToggleValidators(true);
                        var remoteLookupValue = remoteLookup.val();
                        remoteLookup.val("");

                        if (lookupFieldValue != null) {
                            var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                            lookupFieldValueCell.addClass('hiddenSection');
                            lookupFieldValueCell.ToggleValidators(true);
                        }

                        var nonCodeListElementCell = nonCodeListElement.closest('.cell');
                        nonCodeListElementCell.removeClass('hiddenSection');
                        nonCodeListElementCell.ToggleValidators(false);
                        nonCodeListElement.focus();
                        nonCodeListElement.val(remoteLookupValue);
                    }
                }
                else if (remoteLookup.val() === "") {
                    lookupFieldValue.val('');
                    lookupDetailInfo.val('');
                }
            });
        }

        if (nonCodeListElement != null) {
            if (nonCodeListElement.val() !== "") {
                var remoteLookupCell = remoteLookup.closest('.cell');
                remoteLookupCell.addClass('hiddenSection');
                remoteLookupCell.ToggleValidators(true);

                if (lookupFieldValue != null) {
                    var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                    lookupFieldValueCell.addClass('hiddenSection');
                    lookupFieldValueCell.ToggleValidators(true);
                }
            } else {
                var nonCodeListElementCell = nonCodeListElement.closest('.cell');
                nonCodeListElementCell.addClass('hiddenSection');
                nonCodeListElementCell.ToggleValidators(true);
            }

            nonCodeListElement.keyup(function () {
                if (nonCodeListElement.val() === "") {
                    var remoteLookupCell = remoteLookup.closest('.cell');
                    remoteLookupCell.removeClass('hiddenSection');
                    remoteLookupCell.ToggleValidators(false);

                    if (lookupFieldValue != null) {
                        var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                        lookupFieldValueCell.removeClass('hiddenSection');
                        lookupFieldValueCell.ToggleValidators(false);
                    }

                    var nonCodeListElementCell = nonCodeListElement.closest('.cell');
                    nonCodeListElementCell.addClass('hiddenSection');
                    nonCodeListElementCell.ToggleValidators(true);

                    remoteLookup.focus();
                }
            });

            $("form").on("loadedFromXmlCompleted", function () {
                if (nonCodeListElement.val() !== "") {
                    if (remoteLookup != null) {
                        var remoteLookupCell = remoteLookup.closest('.cell');
                        remoteLookupCell.addClass('hiddenSection');
                        remoteLookupCell.ToggleValidators(true);
                    }

                    if (lookupFieldValue != null) {
                        var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                        lookupFieldValueCell.addClass('hiddenSection');
                        lookupFieldValueCell.ToggleValidators(true);
                    }

                    if (nonCodeListElement != null) {
                        var nonCodeListElementCell = nonCodeListElement.closest('.cell');
                        nonCodeListElementCell.removeClass('hiddenSection');
                        nonCodeListElementCell.ToggleValidators(false);
                    }
                } else {
                    if (remoteLookup != null) {
                        var remoteLookupCell = remoteLookup.closest('.cell');
                        remoteLookupCell.removeClass('hiddenSection');
                        remoteLookupCell.ToggleValidators(false);
                    }

                    if (lookupFieldValue != null) {
                        var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                        lookupFieldValueCell.removeClass('hiddenSection');
                        lookupFieldValueCell.ToggleValidators(false);
                    }

                    if (nonCodeListElement != null) {
                        var nonCodeListElementCell = nonCodeListElement.closest('.cell');
                        nonCodeListElementCell.addClass('hiddenSection');
                        nonCodeListElementCell.ToggleValidators(true);
                    }
                }
            });

        }

        //najdenie lookup Formu
        var lookupForms = $(".LookupForm");
        var lookupForm = null;
        lookupForms.each(function () {
            var lookupFormLocal = $(this);
            var spanLookupFormConfiguration = lookupFormLocal.children(".lookupConfiguration");
            var spanLookupFormComponentId = spanLookupFormConfiguration.children(".lookupComponentId");
            if (spanLookupFormComponentId.html() == spanLookupComponentId.html()) {
                lookupForm = lookupFormLocal;
                return false;
            }
        });

        //najdenie lookup detailu
        var lookupDetails = $(".LookupDetail");
        var lookupDetail = null;
        var lookupTable = null;
        lookupDetails.each(function () {
            var lookupDetailLocal = $(this);
            var spanLookupDetailConfiguration = lookupDetailLocal.children(".lookupConfiguration");
            var spanLookupDetailComponentId = spanLookupDetailConfiguration.children(".lookupComponentId");
            if (spanLookupDetailComponentId.html() == spanLookupComponentId.html()) {
                lookupDetail = lookupDetailLocal;
                return false;
            }
        });

        //nastavnie lookup table
        if (lookupForm != null) {
            lookupTable = lookupForm.find('.LookupTable');
        }

        if (lookupDetail != null && lookupDetail.length > 0) {
            lookupDetail.dialog({
                autoOpen: false,
                modal: true
            });
        }

        remoteLookup.siblings(".lookupbutton").click(function() {
            lookupForm.dialog({
                autoOpen: false,
                height: remoteLookupHeight,
                width: remoteLookupWidth,
                modal: true,
                open: function(args, callback) {
                    OpenLookup(lookupForm, lookupTable, remoteSourceIdentifier.html(), remoteLookupCode.html(), remoteLanguage.html(), remoteNotCache.html());
                }
            });
            lookupForm.closest(".ui-dialog").addClass("lookup-dialog");

            //prida do html styl na vertikalne poziciovanie dialogoveho okna (zatial len pre UPVS)
            if (projectType == "UPVS") {            
                var topPosition = $(this).offset().top - 150;
                var dialogClassName = "dialog" + lookupForm.attr("id");
                $(document.head).append('<style type="text/css">.' + dialogClassName + '{top: ' + topPosition + 'px !important;}</style>');
                lookupForm.closest(".ui-dialog").addClass(dialogClassName);
            }

            lookupForm.dialog("open");
        });

        switch (GetFormLanguage()) {
            case 'en':
                remoteLookup.siblings(".lookupbutton").click(function () {
                    lookupForm.dialog({
                        buttons: {
                            "OK": function (args, callback) {
                                SubmitLookup(lookupForm, remoteLookup, lookupDetailInfo, lookupFieldValue, nonCodeListElement);
                            },
                            "Cancel": function () {
                                $(this).dialog("close");
                            }
                        }
                    });
                });
                break;

            default: // sk a default
                remoteLookup.siblings(".lookupbutton").click(function () {
                    lookupForm.dialog({
                        buttons: {
                            "OK": function (args, callback) {
                                SubmitLookup(lookupForm, remoteLookup, lookupDetailInfo, lookupFieldValue, nonCodeListElement);
                            },
                            "Zrušiť": function () {
                                $(this).dialog("close");
                            }
                        }
                    });
                });
        }

        if (lookupInfo.length > 0) {
            lookupInfo.mouseover(function () {
                var infoIcon = lookupInfo.children("span");
                var targetWidth = remoteLookup.width();
                var infoText = lookupDetailInfo.val();
                lookupDetail.children('.LookupDetailInfoText').text(infoText);

                lookupDetail.dialog({
                    autoOpen: true,
                    modal: false,
                    position: { my: "left bottom-3", at: "left top", of: remoteLookup },
                    width: targetWidth,
                    open: function (event, ui) {
                        infoIcon.unbind('mouseout');
                        infoIcon.mouseout(function () {
                            var target = $(event.target);
                            target.dialog('close');
                            target.appendTo(lookupDetail);
                        });
                        infoIcon.mousedown(function () {
                            infoIcon.unbind('mouseout');
                        });
                    },
                    close: function (event, ui) {
                        var target = $(event.target);
                        target.dialog('close');
                        target.appendTo(lookupDetail);
                    }
                });
            });
        }

    });

    function SubmitLookup(lookupForm, field, lookupDetailInfo, lookupFieldValue, nonCodeListElement) {
        var anSelected = fnGetSelected(oTable);
        var turned = "turned";

        var aData = oTable.fnGetData(anSelected[0]);
        var data = anSelected.length > 0 ? aData : aData[0];

        if (data != undefined && data.length > 0) {
            if (field.hasClass(turned)) {
                field.val(data[1]);
                lookupDetailInfo.val(data[0]);
                if (lookupFieldValue != null)
                    lookupFieldValue.val(data[0]);
            } else {
                field.val(data[0]);
                lookupDetailInfo.val(data[1]);
                if (lookupFieldValue != null)
                    lookupFieldValue.val(data[1]);
            }
        }

        if (nonCodeListElement != null) {
            var remoteLookupCell = field.closest('.cell');
            remoteLookupCell.removeClass('hiddenSection');
            remoteLookupCell.ToggleValidators(false);

            if (lookupFieldValue != null) {
                var lookupFieldValueCell = lookupFieldValue.closest('.cell');
                lookupFieldValueCell.removeClass('hiddenSection');
                lookupFieldValueCell.ToggleValidators(false);
            }

            var nonCodeListElementCell = nonCodeListElement.closest('.cell');
            nonCodeListElementCell.ToggleValidators(true);
            nonCodeListElementCell.addClass('hiddenSection');
        }

        field.focus();
        field.change();
        lookupForm.dialog("close");
    }

    function OpenLookup(lookupForm, lookupTable, lookupSource, lookupId, remoteLanguage, remoteNotCache) {
        var formId = GetFormIdFromMetadata();
        var pluginId = GetPluginIdFromMetadata();

        var data = GetLookupUri() + '?id=' + lookupId + '&lookupSource=' + lookupSource + '&formId=' + formId + '&pluginId=' + pluginId;
        if (remoteLanguage != undefined) {
            data += '&language=' + remoteLanguage;
        }

        if (remoteNotCache != undefined) {
            data += '&notCache=' + remoteNotCache;
        }

        data += '&callback=?';

        switch (GetFormLanguage()) {
            case 'en':
                oTable = lookupTable.dataTable({
                    "bAutoWidth": remoteLookupBAutoWidth,
                    "bFilter": true,
                    "bServerSide": true,
                    "bJQueryUI": true,
                    "bProcessing": true,
                    "bLengthChange": false,
                    "iDisplayLength": 10,
                    "bPaginate": true,
                    "bInfo": false,
                    "bRetrieve": true,
                    "fnDrawCallback": function (oSettings) {
                        RemoteLookupAfterLoadItems(oTable);
                    },
                    "sAjaxSource": data,
                    "aoColumns": [{ "sName": "Code" }, { "sName": "Value" }],
                    "oLanguage": {
                        "sEmptyTable": "No data available in table",
                        "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
                        "sInfoEmpty": "Showing 0 to 0 of 0 entries",
                        "sInfoFiltered": "(filtered from _MAX_ total entries)",
                        "sInfoPostFix": "",
                        "sInfoThousands": ",",
                        "sLengthMenu": "Show _MENU_ entries",
                        "sLoadingRecords": "Loading...",
                        "sProcessing": "Processing...",
                        "sSearch": "Search:",
                        "sZeroRecords": "No matching records found",
                        "oPaginate": {
                            "sFirst": "First",
                            "sLast": "Last",
                            "sNext": "Next",
                            "sPrevious": "Previous"
                        },
                        "oAria": {
                            "sSortAscending": ": activate to sort column ascending",
                            "sSortDescending": ": activate to sort column descending"
                        }
                    }
                });
                break;

            default: // sk a default
                oTable = lookupTable.dataTable({
                    "bAutoWidth": remoteLookupBAutoWidth,
                    "bFilter": true,
                    "bServerSide": true,
                    "bJQueryUI": true,
                    "bProcessing": true,
                    "bLengthChange": false,
                    "iDisplayLength": 10,
                    "bPaginate": true,
                    "bInfo": false,
                    "bRetrieve": true,
                    "fnDrawCallback": function (oSettings) {
                        RemoteLookupAfterLoadItems(oTable);
                    },
                    "sAjaxSource": data,
                    "aoColumns": [{ "sName": "Kod" }, { "sName": "Hodnota" }],
                    "oLanguage": {
                        "sEmptyTable": "Nie sú k dispozícii žiadne dáta",
                        "sInfo": "Záznamy _START_ až _END_ z celkom _TOTAL_",
                        "sInfoEmpty": "Záznamy 0 až 0 z celkom 0 ",
                        "sInfoFiltered": "(vyfiltrované spomedzi _MAX_ záznamov)",
                        "sInfoPostFix": "",
                        "sInfoThousands": ",",
                        "sLengthMenu": "Zobraz _MENU_ záznamov",
                        "sLoadingRecords": "Načítavam...",
                        "sProcessing": "Spracúvam...",
                        "sSearch": "Hľadať:",
                        "sZeroRecords": "Nenašli sa žiadne vyhovujúce záznamy",
                        "oPaginate": {
                            "sFirst": "Prvá",
                            "sLast": "Posledná",
                            "sNext": "Nasledujúca",
                            "sPrevious": "Predchádzajúca"
                        },
                        "oAria": {
                            "sSortAscending": ": aktivujte na zoradenie stĺpca vzostupne",
                            "sSortDescending": ": aktivujte na zoradenie stĺpca zostupne"
                        }
                    }
                });
        }

        oTable.fnFilterOnReturn();

        var filterButton = lookupForm.find(".FilterButton");
        var lookupTableTbody = lookupTable.find("tbody");
        filterButton.unbind("click");
        lookupTableTbody.unbind("click");

        lookupForm.find(".dataTables_filter").hide();
        filterButton.click(function () {
            oTable.fnFilter($(this).prev().val());
        });

        lookupTableTbody.click(function (event) {
            $(oTable.fnSettings().aoData).each(function () {
                $(this.nTr).removeClass('row_selected');
            });
            $(event.target.parentNode).addClass('row_selected');
        });
    }
}

function jsonLookupCallback(json, fieldId) {
    var options = '';

    $.each(json, function (key, val) {
        options += '<option value="' + val.optionValue + '">' + val.optionDisplay + '</option>';
    });

    $("select#" + fieldId + "SelectLookup").html(options);
}

function IsHybrid(elementId) {
    var element = $("#" + elementId);
    var closestLayoutRow = element.closest(".layoutRow");
    var xPathClass = element.siblings(".XPathClass");
    var isElementHybrid = false;

    if (xPathClass.length > 0) {
        var xpath = xPathClass.html();

        if (xpath.indexOf("/Codelist") != -1) {
            xpath = xpath.substring(0, xpath.indexOf("/Codelist"));

            closestLayoutRow.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("/NonCodelistData") != -1) {
                        nonCodeListElement = xpathInfo.siblings("input");
                        isElementHybrid = true;;

                        return false;
                    }
                }
            });
        }
    }

    return isElementHybrid;
}

$.fn.ClearFormElements = function () {
    this.find(':input').each(function () {
        var element = $(this);
        switch (this.type) {
            case 'password':
            case 'text':
            case 'textarea':
            case 'select-multiple':
                element.val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
                break;
        }

        var errorClass = "error";
        if (element.hasClass(errorClass)) {
            element.removeClass(errorClass);
        }
    });

    this.find('textarea').each(function () {
        $(this).html("");
    });
    this.find('select').each(function () {
        $(this).val("");
    });

    return this;
};

$.fn.ReinitRadioDefaultCheck = function () {
    this.find(':input').each(function () {
        switch (this.type) {
            case 'radio':
                var input = $(this);
                var defaultVal = input.attr('default');
                if (defaultVal == 'true') {
                    this.checked = true;
                    input.click();
                }
        }
    });

    return this;
};

$.fn.ResetRepetitionSection = function () {
    this.toggleClass('hiddenSection', false);
    this.find('.layoutRow.repeatingSection').remove();
    this.find('.layoutRow.hiddenSection').toggleClass("hiddenSection");
    // Potrebne pre defaultne zobrazenie remote lookupov pri hybridnych(noncodelist) ciselnikoch
    this.find('.remoteLookup').closest("[id^=layoutCell]").toggleClass('hiddenSection', false);
    this.find('div[id^=repetitionCommands]').show();
    this.find('span[id^=addSectionlayoutRow]').css('display', 'inline-block');

    var repeatingLayoutRowsGroup = this.find('.layoutRow[id*=_Repeating_]');
    var repeatingLayoutRowsID = [];
    var thisLayoutRow = $(this);
    // Potrebne pre schovanie buttonu pridat pri sekciach od N do M pre N > 1 a N <= M
    repeatingLayoutRowsGroup.each(function () {
        var cleanLayoutRowID = cleanSectionID($(this).attr('id'));

        if ($.inArray(cleanLayoutRowID, repeatingLayoutRowsID) == -1)
            repeatingLayoutRowsID.push(cleanLayoutRowID);
    });

    if (repeatingLayoutRowsID.length > 0) {
        $(repeatingLayoutRowsID).each(function () {
            var repeatingLayoutRows = thisLayoutRow.find('[id^=' + this + ']');

            repeatingLayoutRows.splice(-1, 1);
            repeatingLayoutRows.find('span[id^=addSectionlayoutRow]').hide();
        });
    }

    this.find('span[id^=removeSectionlayoutRow]').hide();

    return this;
};

function cleanSectionID(layoutRowID) {
    var regEx = new RegExp(repeatingPostfix + "\\d+$");
    return layoutRowID.replace(regEx, '');
}

function GetRepeatingSections(repeatSection) {
    var sections;
    var filterSection = [];

    if ($(repeatSection).hasClass("closeButton") == true) {
        var layoutRow = $(repeatSection).closest('div[id^=layoutRow]');
        var layoutRowId = layoutRow.attr("ID").split('_')[0];

        sections = $('div[id^=' + layoutRowId + ']');

        sections.each(function () {
            if (cleanSectionID($(this).attr('ID')) == layoutRowId)
                filterSection.push($(this));
        });
    } else {
        var cleanId = cleanSectionID(parseId(repeatSection, 'addSection'));
        sections = $('div[id^=' + cleanId + ']');

        sections.each(function () {
            if (cleanSectionID($(this).attr('ID')) == cleanId)
                filterSection.push($(this));
        });
    }

    return $($.map(filterSection, function (el) { return $.makeArray(el) }));
}

function GetSingleGroupRepeatingSections(layoutRow) {
    var cleanId = cleanSectionID(layoutRow.attr('ID'));
    var parentRepeatSection;
    var parentSection = layoutRow.parent().closest('div[id^=layoutRow]');
    var parentCloseButton = parentSection.children('.closeButton');

    while (parentSection[0] && !parentCloseButton[0]) {
        parentCloseButton = parentSection.children('.closeButton');

        if (!parentCloseButton[0])
            parentSection = parentSection.parent().closest('div[id^=layoutRow]');
    }

    parentRepeatSection = parentSection;

    if (!parentRepeatSection[0])
        return GetRepeatingSections(layoutRow);
    else
        return parentRepeatSection.find('div[id^=' + cleanId + ']');
}

function ChangeRepetitionNumbering(layoutRow) {
    repeatLayoutRows = GetSingleGroupRepeatingSections(layoutRow);

    for (i = 0; i < repeatLayoutRows.length; i++) {
        $(repeatLayoutRows[i]).children('div[id^=repetitionNumberinglayoutRow]').find('.currentRepeatPage').text(i + 1);
        $(repeatLayoutRows[i]).children('div[id^=repetitionNumberinglayoutRow]').find('.totalRepeatPage').text(repeatLayoutRows.length);
    }
}

function InitRepetitionNumbering(layoutRow) {
    $(layoutRow).find('.currentRepeatPage, .totalRepeatPage').text(1);
}

function isRepeatingSection(layoutRow) {
    layoutRow = $(layoutRow);

    if (layoutRow.hasClass('layoutRow') && layoutRow.find('[id=repetitionCommands' + layoutRow.attr('id') + ']').length > 0)
        return true;

    return false;
}

function IncrementDecrementSectionId(layoutRowCopy, minRepetition) {
    minRepetition = minRepetition || 1;
    var repeatSection = layoutRowCopy[0];
    if (repeatSection == undefined) { repeatSection = layoutRowCopy; }
    var sections = GetRepeatingSections(repeatSection);

    if (sections.first()[0]) {
        $(sections.first()[0]).attr("ID", cleanSectionID($(sections.first()[0]).attr("ID")));
    }

    var i = 0;

    sections.slice(1).each(function () {
        var section = $(this);
        i++

        if (isRepeatingSection(this) && i > minRepetition - 1)
            section.addClass("repeatingSection");

        section.attr("ID", GetIncrementalValue(section.attr("ID"), i));
    });
};

function IncrementDecrementInnerRepeatingIds(layoutRowCopy) {
    $(layoutRowCopy).find('div[id]').each(function () {
        var thisDiv = $(this);
        var minRepetition = 1;

        if (isRepeatingSection(thisDiv)) {
            var layoutRowsGroup = thisDiv.find('[id^=addSection' + cleanSectionID(thisDiv.attr('id')) + ']');
            var addButton = layoutRowsGroup.last();

            if (addButton[0] != null) {
                var onclickValue = addButton.attr("onclick");

                if (onclickValue != undefined) {
                    var firstSubstring = onclickValue.toString().split('addSection(');

                    if (firstSubstring[1]) {
                        minRepetition = firstSubstring[1].split(',')[0];
                    }
                }
            }
        }

        IncrementDecrementSectionId(thisDiv, minRepetition);
    });
}

$.fn.IncrementFieldIds = function () {
    var layoutRow = this;
    layoutRow.find('[ID].datepicker, [ID]:input, [ID].daterangepickerdiv').each(function () {
        IncrementElements(layoutRow, $(this), ["id", "name"]);
    });

    return layoutRow;
};

$.fn.IncrementLayoutrowCopyFieldIds = function () {
    var layoutRow = this;
    layoutRow.find('[ID].datepicker, [ID]:input, [ID].daterangepickerdiv').each(function () {
        this.id = this.id + '-0'
        this.name = this.name + '-0'
    });

    return layoutRow;
};

function IncrementElements(layoutRow, copyElement, attributes) {
    var attributeName = attributes[0];
    var oldId = copyElement.attr(attributeName);
    oldId = getOriginalId(oldId, sign);
    var selector = "[" + attributeName + "|='" + oldId + "']";
    var elements = $("#main").find(selector);

    if (elements.length > 0) {
        var suffix = "";

        switch (copyElement[0].type) {
            case 'checkbox':
            case 'radio':
                var countRadios = layoutRow.find(selector).length;
                var countGroups = elements.length / countRadios;
                for (var i = 0; i < countGroups; i++) {
                    var start = i * countRadios;
                    elements.slice(start, start + countRadios).each(function () {
                        var element = $(this);
                        if (i > 0) {
                            suffix = sign + i;
                        }

                        SetAttributeFor(element, oldId, suffix);
                        for (a = 0; a < attributes.length; a++) {
                            SetAttribute(element, attributes[a], suffix);
                        }
                    });
                }
                break;
            default:
                i = 0;
                var firtsElement = elements.first();
                SetAttributeFor(firtsElement, oldId, suffix);
                for (var a = 0; a < attributes.length; a++) {
                    SetAttribute(firtsElement, attributes[a], suffix);
                }

                elements.slice(1).each(function () {
                    var element = $(this);
                    suffix = sign + ++i;
                    SetAttributeFor(element, oldId, suffix);
                    for (a = 0; a < attributes.length; a++) {
                        SetAttribute(element, attributes[a], suffix);
                    }
                });
        }

        var lastElement = elements.slice(elements.length - 1);
        if (lastElement != copyElement) {
            CopyValidationRules(oldId, lastElement);
        }
        CopyValidationRules(oldId, copyElement);
    }
}

function SetAttribute(input, attributeName, suffix) {
    var value = input.attr(attributeName);
    if (value != null) {
        value = getOriginalId(value, sign);

        input.attr(attributeName, value + suffix);
    }
}

function getOriginalId(value, sign) {
    var index = value.indexOf(sign);
    if (index > -1) {
        value = value.substring(0, index);
    }

    return value;
}

function SetAttributeFor(element, oldId, suffix) {
    var attributeName = "for";
    var selectorFor = "[" + attributeName + "|='" + oldId + "']";
    var label = element.closest('.cell').find(selectorFor);
    if (label != undefined) {
        SetAttribute(label, attributeName, suffix);
    }
}

function CopyValidationRules(oldId, copyElement) {
    if (copyElement.attr("name")) {
        var element = $('#' + oldId);
        var attributeName = "name";
        var elementName = element.attr(attributeName);
        if (elementName != null) {
            var backUpElementName = element[0].name;
            var backUpCopyElement = copyElement[0].name;
            element[0].name = element[0].name.replace(disableValidatorPrefix, '');
            copyElement[0].name = copyElement[0].name.replace(disableValidatorPrefix, '');
            var rules = element.rules();

            if (element[0] != copyElement[0])
                element[0].name = backUpElementName;

            element = element[0];
            var newRules = {};
            var newMessages = {};
            var settings = $.data(element.form, 'validator').settings;
            for (var method in rules) {
                var name = method.replace(elementName, copyElement.attr(attributeName));
                var validationObject = settings.messages[element.name.replace(disableValidatorPrefix, '')];
                if (validationObject != null) {
                    newRules[name] = rules[method];
                    var messages = validationObject[method];
                    newMessages[name] = messages;
                    $.validator.addMethod(name, $.validator.methods[method]);
                }
            }
            newRules.messages = newMessages;
            copyElement.rules('add', newRules);
            copyElement[0].name = backUpCopyElement;
        }
    }
}

function GetIncrementalValue(value, sectionIncrement) {
    var regEx = new RegExp(repeatingPostfix + "\\d+$");
    var cleanVal = value.replace(regEx, '');
    ////// ML vrati povodnu ////
    //if (sectionIncrement == '')
    //    return cleanVal;
    ////////////////////////////
    return cleanVal + repeatingPostfix + sectionIncrement;
}

function ReindexAddressInput(value) {
    var index = value.indexOf(sign);
    if (index > 0) {
        value = value.substring(0, index);
    }

    var count = 0;
    var selector = value;
    var element = $('#' + selector);

    while (element[0] != undefined) {
        count = count + 1;
        selector = value + sign + count;
        element = $('#' + selector);
    }

    return selector;
}

function GetValueWithoutIncremental(value) {
    var regEx = new RegExp(repeatingPostfix + "\\d+$");
    return value.replace(regEx, '');
}

function IncrementItemDelegate(context, sectionIncrement) {
    var attributeName = "name";
    context.attr(attributeName, GetIncrementalValue(context.attr(attributeName), sectionIncrement));
}

$.fn.ToggleValidators = function (toggle) {
    var attributeName;

    if (toggle == false) {
        attributeName = "name";

        this.find('[ID]:input').each(function () {
            var input = $(this);

            if (input.attr(attributeName) && input.attr(attributeName).indexOf(disableValidatorPrefix) != -1 && input.closest("[id^='layoutRow'][isempty='true'], div.hiddenSection").length == 0) {
                input.attr(attributeName, input.attr(attributeName).replace(disableValidatorPrefix, ''));
            }
        });

        DefaultDataProvider.SetDefaultValues(this, true);
    } else {
        attributeName = "name";

        this.find('[ID]:input').each(function () {
            var input = $(this);

            if (input.attr(attributeName) && input.attr(attributeName).indexOf(disableValidatorPrefix) == -1) {
                input.attr(attributeName, disableValidatorPrefix + input.attr(attributeName));
            }
        });
    }

    return this;
};

$.fn.ToggleValidatorsStyle = function (toggle) {
    var disablevalidators = disableValidators;
    this.find('[ID]:input').each(function () {
        var input = $(this);
        if (toggle == false) {
            input.removeClass(disablevalidators);
        } else {
            input.addClass(disablevalidators);
        }
        input.focusout();
    });

    return this;
};

$.fn.HideSwitchSections = function (switchesToSections) {
    for (var oneSwitch in switchesToSections) {
        var trigger = $(oneSwitch);
        for (var i = 0; i < trigger.length; i++) {
            var currentTrigger = $(trigger[i]);
            if (!currentTrigger.is(":checked")) {
                var sectionsCollection = switchesToSections[oneSwitch];
                var context = GetContext(currentTrigger, sectionsCollection);
                for (section in sectionsCollection) {
                    var section = context.find(sectionsCollection[section]).eq(0);
                    var hiddensection = "hiddenSection";
                    if (section.hasClass('cell')) {
                        var sectionChild = section.children().first();
                        sectionChild.toggleClass(hiddensection, true);
                        sectionChild.ToggleValidators(true);
                    }
                    section.toggleClass(hiddensection, true);
                    section.ToggleValidators(true);
                }
            }
        }
    }

    return this;
};

$.fn.SwitchSections = function (switchesToSections, isCheckBoxList) {
    var context = $(this);
    var isShowAll;
    var hasVal;

    $('form').find(context.selector).each(function () {
        var actualContext = $(this);
        hasVal = false;
        for (var singleSwitch in switchesToSections) {
            isShowAll = false;
            var target = switchesToSections[singleSwitch];
            var trigger = actualContext.find(singleSwitch);
            for (var section in target) {
                if (isShowAll)
                    return;

                actualContext.find(target[section]).find('input, select, textarea').each(function () {
                    var element = $(this)[0];
                    if (element.type != 'radio' && element.value != '')
                        hasVal = true;
                });
                isShowAll = trigger.is('[readonly]') && !hasVal;
            }
        }

        if (!isShowAll) {
            for (singleSwitch in switchesToSections) {
                trigger = actualContext.find(singleSwitch);
                if (trigger.length == 0)
                    return this;

                trigger.click(function () {
                    if (isCheckBoxList == true)
                        switchCheckboxClicked(switchesToSections, this);
                    else
                        switchRadioClicked(switchesToSections, this);
                });
            }
        }
    });

    return this;
};

$.fn.ReinitializeConditionalRules = function () {
    var context = $(this);

    InitConditionalRules(context);

    return this;
};

function GetContext(currentclick, target) {
    return recur($(currentclick), target[0]);
}

function findParent(element) {
    var patt = new RegExp("^layoutRow[0-9]+$");
    var patt2 = new RegExp("^layoutRow[0-9]+_Repeating_[0-9]+$");
    var id = element[0].id;
    if (patt.test(id) || patt2.test(id) || id == "main") {
        return element;
    } else {
        return findParent(element.parent());
    }
}

function recur(element, target) {
    var f;
    var children = element[0].children;

    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (child.id == "main") {
            return $("form");
        }
        if (child.children.length > 0) {
            var a = $(child).find(target);
            if (a.length > 0) {
                f = findParent(a.parent());
            }
        }
    }

    if (f == null) {
        return recur(element.parent(), target);
    } else {
        return f;
    }
}

function customFunctionAfterSwitchSection(switchesToSections, currentclick) {
    // Override this function in custom p_PROJECT.js file
}

function switchRadioClicked(switchesToSections, currentclick) {
    for (var oneSwitch in switchesToSections) {
        var target = switchesToSections[oneSwitch];
        var context = GetContext(currentclick, target);
        oneSwitch = context.find(oneSwitch);

        for (var section in target) {
            section = context.find(target[section]);
            var sectionChild;
            var hiddensection = "hiddenSection";
            var cell = 'cell';
            if (oneSwitch[0] == currentclick) {
                if (section.hasClass(cell)) {
                    sectionChild = section.children().first();
                    sectionChild.toggleClass(hiddensection, false);
                    sectionChild.ToggleValidators(false);
                }
                section.toggleClass(hiddensection, false);
                section.ToggleValidators(false);
            } else {
                if (section.hasClass(cell)) {
                    sectionChild = section.children().first();
                    sectionChild.toggleClass(hiddensection, true);
                    sectionChild.ToggleValidators(true);
                }
                section.toggleClass(hiddensection, true);
                section.ToggleValidators(true);
            }
        }
    }

    customFunctionAfterSwitchSection(switchesToSections, currentclick);
}

function switchCheckboxClicked(switchesToSections, currentclick) {
    var isCheckboxSelected = $(currentclick).is(':checked');
    var sectionsCollection = null;

    for (var sectionsKey in switchesToSections) {
        var target = switchesToSections[sectionsKey];
        var context = GetContext(currentclick, target);
        var oneSwitch = context.find(sectionsKey);
        if (oneSwitch[0] == currentclick) {
            sectionsCollection = target;
            break;
        }
    }

    if (sectionsCollection == null)
        return;

    for (var section in sectionsCollection) {
        section = context.find(sectionsCollection[section]).eq(0);
        var sectionChild;
        var hiddensection = "hiddenSection";
        var cell = 'cell';
        if (isCheckboxSelected) {
            if (section.hasClass(cell)) {
                sectionChild = section.children().first();
                sectionChild.toggleClass(hiddensection, false);
                sectionChild.ToggleValidators(false);
            }
            section.toggleClass(hiddensection, false);
            section.ToggleValidators(false);
        }
        else {
            if (section.hasClass(cell)) {
                sectionChild = section.children().first();
                sectionChild.toggleClass(hiddensection, true);
                sectionChild.ToggleValidators(true);
            }
            section.toggleClass(hiddensection, true);
            section.ToggleValidators(true);
        }
    }

    customFunctionAfterSwitchSection(switchesToSections, currentclick);
}

$.GetUrlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);

    if (results == null)
        return 0;

    return results[1] || 0;
}

// Funkcia trim pre IE 8 a nizsie
$(function () {
    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }
});

/////////////////////////////// ML /////////////////////////////////////

function GetOnlyIncrementValue(value) {    //////////////////////////////////////////////////////////////////////////  rozsirenie

    var regEx = new RegExp(repeatingElementPostfix + "(\\d+)$");
    var cleanVal = regEx.exec(value);
    if (cleanVal == null)
        return '';
    else
        return parseInt(cleanVal[1]);
}

function getPagedSectionName(element) {  //////////////////////////////////////////////////////////////////////////  rozsirenie
    var lsecpg = $(element).closest('div.pageableSection');
    if (lsecpg != null)
        return lsecpg.attr('id');
    else
        return null;
}

function GetElementIncrementalValue(value, sectionIncrement) {
    var regEx = new RegExp(repeatingElementPostfix + "\\d+$");
    var cleanVal = value.replace(regEx, '');
    //// ML vrati povodnu ////
    if (sectionIncrement == '')
        return cleanVal;

    return cleanVal + repeatingElementPostfix + sectionIncrement;
}

///////////////////////////////////////////////////////////////////////

var DefaultDataProvider = {
    defaultData: new Array(),

    Add: function (elementName, defaultValue) {
        if (DefaultDataProvider.defaultData[elementName] == undefined) {
            DefaultDataProvider.defaultData[elementName] = new Array();
        }

        DefaultDataProvider.defaultData[elementName].push(defaultValue);
    },

    GetDefaultValue: function (elementName) {
        if (elementName == null) {
            return null;
        }

        var idParts = elementName.split('-');
        if (idParts.length > 1) {
            elementName = idParts[0];
        }

        elementName = elementName.replace(disableValidatorPrefix, "");

        if (DefaultDataProvider.defaultData[elementName] == undefined) {
            return null;
        }

        return DefaultDataProvider.defaultData[elementName];
    },

    SectionIsEmpty: function (section) {
        var inputValues = section.find('[ID]:input');
        var isEmpty = true;

        inputValues.each(function () {
            var field = $(this);

            if (field.is('[type = text]') || field.is('select')) {
                if (field.val() == "" || field.val() == null) {
                    return true;
                }
            }

            var name = field.attr("name");
            var idParts = name.split('-');
            if (idParts.length > 1) {
                name = idParts[0];
            }

            name = name.replace(disableValidatorPrefix, "");

            var foundValues = DefaultDataProvider.GetDefaultValue(name);

            if (foundValues == null && (field.is('[type = text]') || field.is('select'))) {
                isEmpty = false;

                return false;
            }

            //TODO
            if (field.is(':radio')) {
                if (field.is(':checked'))
                    return false;
            }
            else if (field.is(':checkbox')) {

            }
            else if (field.attr("multiple")) {

            }
            else if (field.is('select')) {
                //ak je remotecombobox a zaroven sa odkazuje na nejake pole, tak nastavi hodnotu cez text
                if (field.hasClass("remoteComboBox")) {
                    var spanLookupConfiguration = field.siblings("span.lookupConfiguration");
                    var spanFieldId = spanLookupConfiguration.children("span.fieldId");
                    if (spanLookupConfiguration.length > 0 && spanFieldId.length > 0 && spanFieldId.html() != "") {
                        for (var i = field[0].options.length - 1; i >= 0; i--) {
                            if (foundValues && field[0].options[i].text == foundValues[0]) {
                                if (field[0].options[i].value != field.val()) {
                                    isEmpty = false;

                                    return false;
                                }
                                break;
                            }
                        }
                    }
                } else {
                    if (foundValues && foundValues[0] != field.val()) {
                        isEmpty = false;

                        return false;
                    }
                }
            } else {
                if (foundValues && foundValues[0] != field.val()) {
                    isEmpty = false;

                    return false;
                }
            }
        });

        return isEmpty;
    },

    SetDefaultValues: function (destination, normalizeSpace) {
        //najskor sa pozrem, ci su vsetky viditelne hodnoty
        var inputValues = destination.find('[ID]:input');
        var addDefaultValues = true;

        if (normalizeSpace === true) {
            inputValues.each(function () {
                var inputValue = $(this);
                if (inputValue.is(':radio') || inputValue.is(':checkbox')) {
                    if (inputValue.is(":checked")) {
                        addDefaultValues = false;

                        return false;
                    }
                } else if (inputValue.attr("multiple")) {
                    for (var index = 0; index < inputValue[0].childNodes.length; index++) {
                        var childNode = inputValue[0].childNodes[index];
                        if (childNode.selected && $(childNode).val() != '' && $(childNode).val() != null) {
                            addDefaultValues = false;

                            return false;
                        }
                    }
                } else if (inputValue.val() != '' && inputValue.val() != null) {
                    addDefaultValues = false;

                    return false;
                }
            });

            if (!addDefaultValues) {
                return;
            }
        }

        inputValues.each(function () {
            var field = $(this);
            var name = field.attr("name");
            var idParts = name.split('-');
            if (idParts.length > 1) {
                name = idParts[0];
            }

            name = name.replace(disableValidatorPrefix, "");

            var foundValues = DefaultDataProvider.defaultData[name];
            if (foundValues === undefined) {
                return true;
            }

            if (field.is(':radio')) {
                for (var index = 0; index < foundValues.length; index++) {
                    if (field.val() == foundValues[index]) {
                        if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                            field.attr("checked", "true");
                        }

                        field.click();

                        break;
                    }
                }
            } else if (field.is(':checkbox')) {
                if (field.hasClass("checkBox")) {
                    if (field.hasClass("xsd_boolean")) {
                        if (foundValues[0] == "1") {
                            if (!field.attr('checked')) {
                                if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                    field.attr("checked", "true");
                                }
                                field.click();
                            }
                        }
                    } else {
                        if (field.val() == foundValues[0]) {
                            if (!field.attr('checked')) {
                                if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                    field.attr("checked", "true");
                                }
                                field.click();
                            }
                        }
                    }
                } else {
                    for (var j = 0; j < foundValues.length; j++) {
                        if (field.val() == foundValues[j]) {
                            if (!field.attr('checked')) {
                                if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                    field.attr("checked", "true");
                                }
                                field.click();
                            }
                        }
                    }
                }
            } else if (field.attr("multiple")) {
                for (var index = 0; index < field[0].childNodes.length; index++) {
                    var childNode = field[0].childNodes[index];
                    for (var j = 0; j < foundValues.length; j++) {
                        if (childNode.value == foundValues[j]) {
                            childNode.selected = true;

                            break;
                        }
                    }
                }
            } else if (field.is('select')) {
                //ak je remotecombobox a zaroven sa odkazuje na nejake pole, tak nastavi hodnotu cez text
                if (field.hasClass("remoteComboBox")) {
                    var spanLookupConfiguration = field.siblings("span.lookupConfiguration");
                    var spanFieldId = spanLookupConfiguration.children("span.fieldId");
                    if (spanLookupConfiguration.length > 0 && spanFieldId.length > 0 && spanFieldId.html() != "") {
                        for (var i = field[0].options.length - 1; i >= 0; i--) {
                            if (field[0].options[i].text == foundValues[0]) {
                                field.val(field[0].options[i].value);
                                break;
                            }
                        }
                    } else {
                        field.val(foundValues[0]);
                    }
                } else {
                    field.val(foundValues[0]);
                }

                field.change();
            } else {
                field.val(foundValues[0]);
            }
        });
    }
}