var attachmentsDataArray = new Object();
var fakeValueForTemplate = "valFakeEmptyWrapper";

function GetDataXPath(acceptEmptyForm) {
    var hasMetadata = $("#mtd_formMetaData").length > 0;
    var xPaths = new Array();

    function CanDisplay(name) {
        if (name.length < disableValidatorPrefix.length) {
            return true;
        }
        return !(name.substring(0, disableValidatorPrefix.length) == disableValidatorPrefix);
    }

    function processHtml() {
        var element = $(this);
        var name = 'name';
        var layoutRow = 'layoutRow';

        if (element.is(':input')) {
            if (element.is(':file') || element.is(':button'))
                return;

            if (element.parent().hasClass(layoutRow))
                return;

            var attrXPath = element.siblings('.XPathClass');
            var attrXPathRepeatingReference = element.siblings('.XPathRepeatingReference');
            var xPathRepeatingXPath = element.siblings('.XPathRepeatingXPath');
            var attr = element.attr(name);

            if (attrXPathRepeatingReference.length > 0) {
                attrXPathRepeatingReference = attrXPathRepeatingReference.html();
            } else {
                attrXPathRepeatingReference = null;
            }

            if (xPathRepeatingXPath.length > 0) {
                xPathRepeatingXPath = xPathRepeatingXPath.html();
            } else {
                xPathRepeatingXPath = null;
            }

            if (attr !== undefined && attrXPath.length > 0 && attrXPath.html() != "") {
                var hasEmptyAttribute = !CanDisplay(attr);
                var xPathStructure = ParseXPath(attrXPath.html());
                var attrXPathValue = xPathStructure.xPath;
                var xPathConstant = xPathStructure.constant;
                var sectionConstants = xPathStructure.sectionConstants;

                var index = attr.indexOf(sign);
                if (index > -1) {
                    attr = attr.substr(0, index);
                }
                var checked = ':checked';
                var val;
                var newObj = null;

                if (element.is(':radio')) {
                    if (element.is(checked)) {
                        newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: element.val(), sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                        xPaths.push(newObj);
                    }
                } else if (element.is(':checkbox')) {
                    if (element.is(checked)) {
                        if (!hasMetadata) {
                            newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: ((element.hasClass("checkBox")) ? 1 : HtmlEncode(element.val())), sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                            xPaths.push(newObj);
                        } else {
                            newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: ((element.hasClass("checkBox") && element.hasClass("xsd_boolean")) ? 1 : HtmlEncode(element.val())), sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                            xPaths.push(newObj);
                        }
                    } else {
                        if (element.hasClass("checkBox")) {
                            if (!hasMetadata) {
                                newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: 0, sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                                xPaths.push(newObj);
                            } else {
                                if (element.hasClass("xsd_boolean")) {
                                    newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: 0, sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                                    xPaths.push(newObj);
                                }
                            }
                        }
                    }
                } else if (element.attr("multiple")) {
                    val = element.val() === null ? "" : element.val();
                    for (var i = 0, j = val.length; i < j; i++) {
                        newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: HtmlEncode(val[i]), sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                        xPaths.push(newObj);
                    }
                } else { // Je textbox, textarea, integerbox, decimalbox, date, time, datetime, combobox
                    val = element.val() === null ? "" : element.val();

                    if (element.hasClass("xsd_decimal") || element.hasClass("xsd_float") || element.hasClass("xsd_double"))
                        val = val.replace(',', '.');
                    else if (element.hasClass("xsd_date"))
                        val = xmlHelper.toXmlDate(val);
                    else if (element.hasClass("xsd_time"))
                        val = xmlHelper.toXmlTime(val);
                    else if (element.hasClass("datetime"))
                        val = xmlHelper.toXmlDateTime(val);
                    else if (element.hasClass("datetimewithseconds"))
                        val = xmlHelper.toXmlDateTimeWithSecond(val);

                    newObj = { hasEmptyAttribute: hasEmptyAttribute, element: element, xPathRepeatingReference: attrXPathRepeatingReference, xPathConstant: xPathConstant, xPath: attrXPathValue, value: HtmlEncode(val), sectionConstants: sectionConstants, xPathRepeatingXPath: xPathRepeatingXPath };
                    xPaths.push(newObj);
                }
            }
        }

        element.children().each(processHtml);
    }

    $('#main').children('div').each(processHtml);
    var data = new Array();
    var source = $("#eDocTemplate").html().trim();
    source = $('<div/>').html(source).text();
    var template = Handlebars.compile(source, { noEscape: true });
    var xml;

    if (xPaths.length == 0) {
        xml = template(data);
    }
    else {
        var rootSectionName = xPaths[0].xPath.split('/')[1];
        data[rootSectionName] = new Array();
        data[rootSectionName].push({ data: new Array() });

        for (var i = 0; i < xPaths.length; i++) {
            ProcessXPathsObjects(data, xPaths[i]);
        }
        xml = template(data[rootSectionName][0]);
    }

    var xmlnsXsi = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'";
    xml = xml.replace(xml.substring(1, xml.indexOf(">")), xml.substring(1, xml.indexOf(">")) + xmlnsXsi);

    return xml;
}

function ProcessXPathsObjects(data, object) {
    var sectionXpaths = SectionPaths(object.xPath);
    var isEmpty = object.value === "";

    var sectionName = sectionXpaths[0];

    //nastavi sa na root
    var lastNode = data[sectionName][0];

    //zisti vsetky opakovacie sekcie s poctom vyskystov
    var xPathGetSectionLevels = XPathGetSectionLevels(object);

    var actualXPath = "/" + sectionName;
    var actualEscapedXPath = "/" + sectionName;
    var actualNonEscapedXPath = "/" + sectionName;

    for (var i = 1; i < sectionXpaths.length -1; i++) {
        actualXPath += "/" + sectionXpaths[i];
        actualNonEscapedXPath += "/" + sectionXpaths[i];

        if (object.sectionConstants != undefined && object.sectionConstants[actualXPath] != undefined) {
            sectionName = XPathEscapeSectionName(sectionXpaths[i] + object.sectionConstants[actualXPath]);
            actualNonEscapedXPath += object.sectionConstants[actualXPath];
        } else {
            sectionName = XPathEscapeSectionName(sectionXpaths[i]);
        }

        actualEscapedXPath += "/" + sectionName;

        //ak tam taky prvok vobec nie je
        if (lastNode[sectionName] == undefined) {
            lastNode[sectionName] = new Array();
            lastNode[sectionName].push({ data: new Array(), isEmpty: isEmpty, hasEmptyAttribute: object.hasEmptyAttribute });
        }
        else {
            if (xPathGetSectionLevels != null) {
                //pokusi sa najst, ci existuje pocet vyskystov pre danu sekciu
                var xPathGetSectionLevel = xPathGetSectionLevels[actualNonEscapedXPath];
                if (xPathGetSectionLevel != undefined) {
                    //ak existuje pocetnost, tak sa zisti, kolko tych sekcii naozaj je a v pripade potreby zvacsi pocet
                    var sectionCount = XPathGetSectionCount(data, 1, actualEscapedXPath);
                    if (sectionCount < xPathGetSectionLevel + 1) {
                        lastNode[sectionName].push({ data: new Array(), isEmpty: isEmpty, hasEmptyAttribute: object.hasEmptyAttribute });
                    }
                }
            }

            //pozri ci sa nejedna o multiple prvky
            if (object.xPathRepeatingXPath != null) {
                //pozri sa ci je ta cesta aktualna
                if (actualNonEscapedXPath == object.xPathRepeatingXPath) {

                    var exist = false;
                    for (var j = 0; j < lastNode[sectionName][lastNode[sectionName].length - 1].data.length; j++) {
                        if (lastNode[sectionName][lastNode[sectionName].length - 1].data[j].xPath == object.xPath) {
                            exist = true;

                            break;
                        }
                    }
                    //ak sa tam taky este nenachadza, tak vlozi
                    if (exist) {
                        lastNode[sectionName].push({ data: new Array(), isEmpty: isEmpty, hasEmptyAttribute: object.hasEmptyAttribute });
                    }
                }
            }

            if (lastNode[sectionName][lastNode[sectionName].length - 1].isEmpty) {
                lastNode[sectionName][lastNode[sectionName].length - 1].isEmpty = isEmpty;
            }

            //ak nebudu mat vsetky, tak nebude povazovat za prazdne
            if (lastNode[sectionName][lastNode[sectionName].length - 1].hasEmptyAttribute) {
                lastNode[sectionName][lastNode[sectionName].length - 1].hasEmptyAttribute = object.hasEmptyAttribute;
            }
        }

        lastNode = lastNode[sectionName][lastNode[sectionName].length - 1];
    }

    //pozri este last node, ci tam nie je atribut a ten sa bude nastavovat ako nova property
    var lastName = sectionXpaths[sectionXpaths.length - 1];
    AddAttributesAsProperty(object, lastName);

    lastNode.data.push(object);
}

//pozrie sa ci elementName obsahuje atributy 
function AddAttributesAsProperty(object, elementName) {
    var foundAttributeMatch = elementName.match(/\[[@][^\]]+\]/g);
    if (foundAttributeMatch == null) {
        return;
    }

    try {
        var trimedAttributeMatch = foundAttributeMatch[0].replace(/\[/, '').replace(/\]/, '');
        var attributes = trimedAttributeMatch.split("and");
        for (var i = 0; i < attributes.length; i++) {
            var attribute = attributes[i].replace(/^\s+|\s+$/gm, '');
            var concereteAttribute = attribute.split('=');
            var concereteAttributeId = concereteAttribute[0].replace(/\@/, '');
            var concereteAttributeValue = concereteAttribute[1].replace(/\'/gi, '');

            object[concereteAttributeId] = concereteAttributeValue;
        }
    } catch (e) {

    }
}

function XPathGetSectionCount(data, actualIndex, xPathSearch) {
    var count = 0;

    var xPathParts = xPathSearch.split('/');
    var sectionParts = new Array();
    for (var i = 1; i <= actualIndex; i++) {
        sectionParts.push(xPathParts[i]);
    }

    var xPathActual = CreateAbsoluteXPathFromArray(sectionParts, actualIndex - 1);
    var sectionName = XPathEscapeSectionName(sectionParts[sectionParts.length - 1]);

    if (data[sectionName] == undefined) {
        return 0;
    }

    if (xPathActual == xPathSearch) {
        return data[sectionName].length;
    }

    for (var i = 0; i < data[sectionName].length; i++) {
        count += XPathGetSectionCount(data[sectionName][i], actualIndex + 1, xPathSearch);
    }

    return count;
}

function CreateAbsoluteXPathFromArray(xPathsParts, index) {
    var xPath = "";

    for (var i = 0; i <= index; i++) {
        xPath += "/" + xPathsParts[i];
    }

    return xPath;
}

function XPathGetSectionLevels(object) {
    //ak neobsahuje referenciu na layout row
    if (object.xPathRepeatingReference == null) {
        return null;
    }

    var sectionLevels = new Array();

    var xPathGetSectionLevel = XPathGetSectionLevel(object.xPathRepeatingReference, object.element);
    sectionLevels[xPathGetSectionLevel.xPath] = xPathGetSectionLevel.sectionIndex;
    var actual = xPathGetSectionLevel;

    while (actual != null) {
        xPathGetSectionLevel = XPathGetSectionLevel(actual.xPathRepeatingReference, actual.element);
        if (xPathGetSectionLevel == null) {
            break;
        }

        sectionLevels[xPathGetSectionLevel.xPath] = xPathGetSectionLevel.sectionIndex;
        actual = xPathGetSectionLevel;
    }

    return sectionLevels.reverse();
}

function XPathGetSectionLevel(layoutRowId, element) {
    var sectionIndex = 0;
    var xPathRepeatingReference = null;
    var xPath = null;

    var layoutRow = element.parents("[id^='layoutRow" + layoutRowId + "']");

    var layoutRowXPath = layoutRow.children("span.XPathClass");
    if (layoutRowXPath.length > 0) {
        xPath = layoutRowXPath.html();
    }

    //ak nema layoutRow XPAth tak nema zmysel riesit dalej
    if (xPath == null) {
        return null;
    }

    var attrSection = layoutRow[0].id;
    var indexSection = attrSection.indexOf(repeatingPostfix);
    if (indexSection > -1) {
        sectionIndex = parseInt(attrSection.substr(indexSection + repeatingPostfix.length, attrSection.length - 1));
    }

    var layoutRowXPathReference = layoutRow.children("span.XPathRepeatingReference");

    if (layoutRowXPathReference.length > 0) {
        xPathRepeatingReference = layoutRowXPathReference.html();
    }

    return { xPath: xPath, sectionIndex: sectionIndex, xPathRepeatingReference: xPathRepeatingReference, element: layoutRow };
}

function XPathEscapeSectionName(sectionName) {
    sectionName = sectionName.replace(/ /g, "");
    sectionName = sectionName.replace(/\'/g, "");
    sectionName = sectionName.replace(/\=/g, "_");
    sectionName = sectionName.replace(/\@/g, "_");
    sectionName = sectionName.replace(/\[/g, "_");
    sectionName = sectionName.replace(/\]/g, "_");
    sectionName = sectionName.replace(/\//g, "");
    sectionName = sectionName.replace(/\(/g, "");
    sectionName = sectionName.replace(/\)/g, "");
    sectionName = sectionName.replace(/\,/g, "");
    sectionName = sectionName.replace(/\./g, "");

    return sectionName;
}

//vrati sekciu a odignoruje root node
function SectionPaths(xPath) {
    var xPathParts = xPath.split('/');
    var actualPaths = new Array();
    for (var i = 1; i < xPathParts.length; i++) {
        actualPaths.push(xPathParts[i]);
    }

    return actualPaths;
}

var xmlHelper = (function (helper) {
    var toDateRegex = /^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{1,4})$/g,
	    fromDateRegex = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})$/g,
        toTimeRegex = /^([0-9]{1,2})\:([0-9]{1,2})$/g,
        fromTimeRegex = /^([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/g,
        toDateTimeRegex = /^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{1,4}) ([0-9]{1,2})\:([0-9]{1,2})$/g,
        toDateTimeWithSecondsRegex = /^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{1,4}) ([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/g,
	    fromDateTimeRegex = /^([0-9]{1,4})\-([0-9]{1,2})\-([0-9]{1,2})T([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/g;

    helper.toXmlDate = function (value) {
        if (value) {
            toDateRegex.lastIndex = 0;
            var matches = toDateRegex.exec($.trim(value));
            if (matches && matches.length === 4) {
                value = matches[3] + '-' + matches[2] + '-' + matches[1];
            }
        }

        return value || '';
    };

    helper.fromXmlDate = function (value) {
        if (value) {
            fromDateRegex.lastIndex = 0;
            var matches = fromDateRegex.exec($.trim(value));
            if (matches && matches.length === 4) {
                value = matches[3] + '.' + matches[2] + '.' + matches[1];
            }
        }

        return value || '';
    };

    helper.toXmlTime = function (value) {
        if (value) {
            toTimeRegex.lastIndex = 0;
            var matches = toTimeRegex.exec($.trim(value));
            if (matches && matches.length === 3) {
                value = matches[1] + ':' + matches[2] + ':00';
            }
        }

        return value || '';
    };

    helper.fromXmlTime = function (value) {
        if (value) {
            fromTimeRegex.lastIndex = 0;
            var matches = fromTimeRegex.exec($.trim(value));
            if (matches && matches.length === 4) {
                value = matches[1] + ':' + matches[2];
            }
        }

        return value || '';
    };

    helper.toXmlDateTime = function (value) {
        if (value) {
            toDateTimeRegex.lastIndex = 0;
            var matches = toDateTimeRegex.exec($.trim(value));
            if (matches && matches.length === 6) {
                value = matches[3] + '-' + matches[2] + '-' + matches[1] + 'T' + matches[4] + ':' + matches[5] + ':00';
            }
        }

        return value || '';
    };

    helper.toXmlDateTimeWithSecond = function (value) {
        if (value) {
            toDateTimeWithSecondsRegex.lastIndex = 0;
            var matches = toDateTimeWithSecondsRegex.exec($.trim(value));
            if (matches && matches.length === 7) {
                value = matches[3] + '-' + matches[2] + '-' + matches[1] + 'T' + matches[4] + ':' + matches[5] + ':' + matches[6];
            }
        }

        return value || '';
    };

    helper.fromXmlDateTime = function (value) {
        if (value) {
            fromDateTimeRegex.lastIndex = 0;
            var matches = fromDateTimeRegex.exec($.trim(value));
            if (matches && matches.length === 7) {
                value = matches[3] + '.' + matches[2] + '.' + matches[1] + ' ' + matches[4] + ':' + matches[5];
            }
        }

        return value || '';
    };

    helper.fromXmlDateTimeWithSeconds = function (value) {
        if (value) {
            fromDateTimeRegex.lastIndex = 0;
            var matches = fromDateTimeRegex.exec($.trim(value));
            if (matches && matches.length === 7) {
                value = matches[3] + '.' + matches[2] + '.' + matches[1] + ' ' + matches[4] + ':' + matches[5] + ':' + matches[6];
            }
        }

        return value || '';
    };

    helper.fromXmlAnyURI = function (value) {
        if (value) {
            value = value.replace(/mailto:/gi, "");
        }

        return value || '';
    };

    return helper;
}({}));

function GetData(acceptEmptyForm) {
    if (XPathUsed()) {
        return GetDataXPath(acceptEmptyForm);
    }

    if (acceptEmptyForm == undefined) {
        acceptEmptyForm = false;
    }

    var formId = GetFormId();
    var xmlns = GetMetadataNamespace();
    var xml = '<' + formId + xmlns + '>';
    var hasMetadata = $("#mtd_formMetaData").length > 0;
    function processHtml() {
        var element = $(this);
        var isempty = 'isempty';

        if (!acceptEmptyForm && element.attr(isempty) !== undefined && element.attr(isempty) == "true")
            return;

        var name = 'name';
        var layoutRow = 'layoutRow';
        var firstInput;
        if (element.hasClass(layoutRow)) {
            firstInput = element.children("input:first");
            if (firstInput.attr(name) != 'Attachments') {
                if (element.hasClass('hiddenSection')) {
                    xml += '<' + disableValidatorPrefix + firstInput.attr(name) + '>';
                } else {
                    xml += '<' + firstInput.attr(name) + '>';
                }
            }
        }

        if (element.is(':input')) {
            if (element.is(':file') || element.is(':button') || element.attr('LookupDetailInfo') == "true")
                return;

            if (element.parent().hasClass(layoutRow))
                return;

            var attr = element.attr(name);
            if (attr !== undefined) {
                var index = attr.indexOf(sign);
                if (index > -1) {
                    attr = attr.substr(0, index);
                }
                var checked = ':checked';
                var val;
                if (element.is(':radio')) {
                    if (element.is(checked)) {
                        var cleanName = GetValueWithoutIncremental(attr);

                        xml += '<' + cleanName + '>' + element.val() + '</' + cleanName + '>';
                    }
                }
                else if (element.is(':checkbox')) {
                    if (element.is(checked)) {
                        if (!hasMetadata) {
                            xml += '<' + attr + '>' + ((element.hasClass("checkBox")) ? 1 : element.val()) + '</' + attr + '>';
                        }
                        else {
                            xml += '<' + attr + '>' + ((element.hasClass("checkBox") && element.hasClass("xsd_boolean")) ? 1 : element.val()) + '</' + attr + '>';
                        }
                    }
                    else {
                        if (element.hasClass("checkBox")) {
                            if (!hasMetadata) {
                                xml += '<' + attr + '>' + 0 + '</' + attr + '>';
                            }
                            else {
                                if (element.hasClass("xsd_boolean")) {
                                    xml += '<' + attr + '>' + 0 + '</' + attr + '>';
                                }
                            }
                        }
                    }
                }
                else if (element.attr("multiple")) {
                    val = element.val() === null ? "" : element.val();
                    for (var i = 0, j = val.length; i < j; i++) {
                        xml += '<' + attr + '>' + HtmlEncode(val[i]) + '</' + attr + '>';
                    }
                }

                else {
                    val = element.val() === null ? "" : element.val();

                    if (element.hasClass("xsd_decimal") || element.hasClass("xsd_float") || element.hasClass("xsd_double"))
                        val = val.replace(',', '.');
                    else if (element.hasClass("xsd_date"))
                        val = xmlHelper.toXmlDate(val);
                    else if (element.hasClass("xsd_time"))
                        val = xmlHelper.toXmlTime(val);
                    else if (element.hasClass("datetime"))
                        val = xmlHelper.toXmlDateTime(val);
                    else if (element.hasClass("datetimewithseconds"))
                        val = xmlHelper.toXmlDateTimeWithSecond(val);

                    xml += '<' + attr + '>' + HtmlEncode(val) + '</' + attr + '>';
                }
            }
        }

        if (acceptEmptyForm)
            element.children().each(processHtml);
        else {
            if (element.attr(isempty) === undefined || element.attr(isempty) == "false")
                element.children().each(processHtml);
        }

        if (element.hasClass(layoutRow)) {
            firstInput = element.children("input:first");
            if (firstInput.attr(name) != 'Attachments') {
                if (element.hasClass('hiddenSection')) {
                    xml += '</' + disableValidatorPrefix + firstInput.attr(name) + '>';
                } else {
                    xml += '</' + firstInput.attr(name) + '>';
                }
            }
        }
    }

    $('#main').children('div').each(processHtml);

    xml += '</' + formId + '>';

    return xml;
}

function GetMetadataNamespace() {
    var xmlns = '';
    var mtdNamespace = $('form').find("#mtd_namespace");
    if (mtdNamespace.length > 0) {
        if (mtdNamespace.html() != xmlns) {
            xmlns = " xmlns='" + mtdNamespace.html() + "'";
        }
    }
    return xmlns;
}

function GetFormIdFromMetadata() {
    var formId = '';

    var formMetadata = $("#mtd_formMetaData");
    if (formMetadata.length > 0) {
        var mtdNamespace = formMetadata.find("#mtd_namespace");
        if (mtdNamespace.length > 0) {
            formId = mtdNamespace.html();
        }
    }

    return formId;
}

function GetPluginIdFromMetadata() {
    var pluginId = '';

    var formMetadata = $("#mtd_formMetaData");
    if (formMetadata.length > 0) {
        var mtdPlugin= formMetadata.find("#mtd_pluginId");
        if (mtdPlugin.length > 0) {
            pluginId = mtdPlugin.html();
        }
    }

    return pluginId;
}

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

function ShowData() {
    var xml = GetData();
    alert(decodeURIComponent(xml));
}

function ShowDataWithAttachments() {
    var xml = GetData();
    var formId = GetFormId();
    var xmlWithAttachments = xml.replace('</' + formId + '>', '');

    var attachmentsData = '';
    for (var key in attachmentsDataArray) {
        attachmentsData = attachmentsData + attachmentsDataArray[key];
    }

    xmlWithAttachments += '<Attachments>' + attachmentsData + '</Attachments>';
    xmlWithAttachments += '</' + formId + '>';

    var parentWindow = window.opener;
    parentWindow.setFinalXml(xmlWithAttachments);
}

function SaveXml() {
    localStorage.setItem(GetFormStorageKey(), GetData());
    var message = '';

    switch (GetFormLanguage()) {
        case 'en':
            message = "Form " + "'" + GetFormStorageKey().replace('ego_', '') + "'" + " has been successfully stored in the repository";
            break;

        default: // sk a default
            message = "Formular " + "'" + GetFormStorageKey().replace('ego_', '') + "'" + " bol uspesne ulozeny do lokalneho uloziska";
    }

    alert(message);

    ShowSavedForms();
}

function ShowSavedForms() {
    var savedForms = "<span class='fieldContent'>";
    var savedFormsCount = 0;

    for (var i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i) == GetFormStorageKey()) {
            savedForms += "<span>" + localStorage.key(i).substr(4) + "</span><br/>";
            savedFormsCount++;
        }
    }
    savedForms += "</span>";

    $('#lcellSavedForms').html(savedForms);
    var element = $("#savedFormsContainer");
    if (savedFormsCount > 0) {
        element.show();
    }
    else {
        element.hide();
    }
}

function PrintForm() {
    window.print();
}

function GetFormId() {
    return $('form').attr('ID');
}

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

function IsError() {
    var errors = $('.error');

    for (i = 0; i < errors.length; i++) {
        if ($(errors[i]).is(':visible'))
            return true
    }

    return false;
}

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

function ValidateForm() {
    //////////////////// ML /////////////////////////

    errorValidateFocusOut = false;

    if ($('#' + GetFormId()).valid()) {
        /*switch (GetFormLanguage()) {
            case 'en':
                alert("Check the form was successful.");
                break;

            default: // sk a default
                alert("Kontrola formulára prebehla úspešne.");
        }*/

        return true;
    }
    else if (IsError()) {
        /*switch (GetFormLanguage()) {
            case 'en':
                alert("The form contains the validation errors.");
                break;

            default: // sk a default
                alert("Formulár obsahuje validačné chyby.");
        }*/

        return false;
    }
    else {
        /*switch (GetFormLanguage()) {
            case 'en':
                alert("Formulár obsahuje logické chyby. Naozaj chcete pokračovať?");
                break;

            default: // sk a default
                alert("The form contains a logic error. Are you sure?");
        }*/

        return true;
    }

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

    //return $('#' + GetFormId()).valid();
}

function CloseForm(fillerUri) {
    if (XPathUsed()) {
        return CloseFormXPath(fillerUri);
    }

    var xml = GetData();
    var parentWindow = window.opener;

    try {
        var formId = parentWindow.getFormId();
        var eDoc = TranslateNativeToEDoc(xml, fillerUri + "TranslateNativeToEDoc", formId);

        parentWindow.setXmlData(eDoc);

        window.close();
    } catch (err) {
        switch (GetFormLanguage()) {
            case 'en':
                alert('workdesk was closed');
                break;

            default: // sk a default
                alert('workdesk bol uzavretý');
        }
    }
}

function CloseFormXPath(fillerUri) {
    var xml = GetDataXPath();
    var parentWindow = window.opener;

    try {
        var eDoc = xml;

        parentWindow.setXmlData(eDoc);

        window.close();
    } catch (err) {
        alert('workdesk bol uzavretý');
    }
}

function CancelForm() {
    window.close();
}

function ValidateFormAndClose(fillerUri) {
    var form = $('#' + GetFormId());
    var $validator = form.validate();
    var confirmText = '';

    switch (GetFormLanguage()) {
    case 'en':
        confirmText = "The form contains errors. Are you sure you want to close?";
        break;

    default: // sk a default
        confirmText = "Formulár obsahuje chyby. Naozaj ho chcete ukončiť?";
    }

    //jquery validacia
    ValidateForm(form);

    if ($validator.numberOfInvalids() > 0) {
        if (confirm(confirmText)) {
            CloseForm(fillerUri);
        }

        return;
    }

    //xsd validacia
    var xml = GetData();
    var parentWindow = window.opener;
    var formId = parentWindow.getFormId();
    var result = CallValidateFormWithXsd(xml, fillerUri + "ValidateFormWithXsd", formId);

    var resultXML = $.parseXML(result);
    var resultXMLTraversable = $(resultXML);
    var responseCode = resultXMLTraversable.find("response > code").text();
    if (responseCode != "ok") {
        ShowValidationResult(result, "xsdValidation");
        if (!confirm(confirmText)) {
            
        }

        return;
    }

    CloseForm(fillerUri);
}

function validateFormAndNotClose(fillerUri) {
    var form = $('#' + GetFormId());
    var $validator = form.validate();

    //jquery validacia
    ValidateForm(form);

    if ($validator.numberOfInvalids() > 0) {
        return;
    }

    ValidateFormWithXsd(fillerUri);
}

function SaveAndCloseForm(fillerUri) {
    var form = $('#' + GetFormId());
    var $validator = form.validate();
    var confirmText = '';

    switch (GetFormLanguage()) {
        case 'en':
            confirmText = "The form contains errors. Are you sure you want to save?";
            break;

        default: // sk a default
            confirmText = "Formulár obsahuje chyby. Naozaj ho chcete uložiť?";
    }

    ValidateForm(form);

    if ($validator.numberOfInvalids() > 0) {
        if (confirm(confirmText)) {
            CloseForm(fillerUri);
        } else {
        }
    }
    else {
        CloseForm(fillerUri);
    }
}

function GetAttachments() {
    var files = $('input[type="file"]')[0].files;
    var attachements = "";
    for (var i = 0; i < files.length; i++) {
        attachements += files[i].name + "<br/>";
    }

    return attachements;
}

//vycisti formular a nastavi vsade defaultne hodnoty, odstrani nadbytocne opakovacie sekcie
function ClearForm(element) {
    $(element).find(':input').each(function () {
        var field = $(this);

        if (field.attr("id") == undefined) {
            return true;
        }

        if (field.parent().hasClass("layoutRow")) {
            return true;
        }

        //ak zisitim, ze je to donot validate, tak neupravovat
        if (field.attr("id").indexOf(disableValidatorPrefix) == 0) {
            return true;
        }

        var elementName = field.attr("name");
        var newValue = null;

        if (elementName != undefined) {
            newValue = DefaultDataProvider.GetDefaultValue(elementName);
        }

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

                        return true;
                    }
                }
            }

            field.attr("checked", false);

        } else if (field.is(':checkbox')) {
            if (newValue != null) {
                if (field.hasClass("checkBox")) {
                    if (field.hasClass("xsd_boolean")) {
                        if (newValue[0] == "1") {
                            if (field.attr('checked')) {
                                $(this).removeClass('error');

                                return true;
                            }
                            if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                field.attr("checked", "true");
                            }
                            field.click();
                            $(this).removeClass('error');

                            return true;
                        }
                    } else {
                        if (field.val() == newValue[0]) {
                            if (field.attr('checked')) {
                                $(this).removeClass('error');

                                return true;
                            }
                            if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                field.attr("checked", "true");
                            }
                            field.click();
                            $(this).removeClass('error');

                            return true;
                        }
                    }
                } else {
                    for (var j = 0; j < newValue.length; j++) {
                        if (field.val() == newValue[j]) {
                            if (field.attr('checked')) {
                                $(this).removeClass('error');

                                return true;
                            }
                            if (field.attr("disabled") !== undefined || field.attr("readonly") !== undefined) {
                                field.attr("checked", "true");
                            }
                            field.click();
                            $(this).removeClass('error');

                            return true;
                        }
                    }
                }
            }

            field.attr("checked", false);

        } else if (field.attr("multiple")) {
            if (newValue != null) {
                for (var index = 0; index < field[0].childNodes.length; index++) {
                    var childNode = field[0].childNodes[index];
                    childNode.selected = false;

                    for (var j = 0; j < newValue.length; j++) {
                        if (childNode.value == newValue[j]) {
                            childNode.selected = true;

                            break;
                        }
                    }
                }
            } else {
                for (var index = 0; index < field[0].childNodes.length; index++) {
                    var childNode = field[0].childNodes[index];
                    childNode.selected = false;
                }
            }
        } else if (field.is('select')) {
            newValue = newValue == null ? "" : newValue[0];
            field.val(newValue);

            field.change();
        } else if (!field.is(':button')) {
            newValue = newValue == null ? "" : newValue[0];
            field.val(newValue);
        }

        field.removeClass('error');
    });

    //zmaz vsetky zduplikovane opakujuce sekcie
    var removeLayotRows = new Array();
    $(element).find('div[id^=layoutRow]').each(function () {
        var layoutRow = $(this);
        var elementName = layoutRow.attr("id");

        if (elementName.indexOf(repeatingPostfix) == -1) {
            return true;
        }

        //ak bol uz zmazany predok, tak sa nemoze zmazat, lebo uz fyzicky neexistuje
        for (var i = 0; i < removeLayotRows.length; i++) {
            if (layoutRow.closest(removeLayotRows[i]).length > 0) {
                return true;
            }
        }

        elementName = GetValueWithoutIncremental(elementName);
        var indexSection = layoutRow.attr("id").replace(elementName + repeatingPostfix, "");
        if (indexSection == "") {
            indexSection = 1;
        } else {
            indexSection ++;
        }

        var addButton = layoutRow.last().find('#removeSection' + elementName);
        if (addButton[0] != null) {
            if (addButton.attr("onclick") != undefined) {
                var onclickValue = addButton.attr("onclick");
                if (onclickValue != undefined) {
                    var minRepetition = onclickValue.replace('removeSection', "");
                    minRepetition = minRepetition.replace("(", "");
                    minRepetition = minRepetition.replace(")", "");
                    minRepetition = minRepetition.replace(",", "");
                    minRepetition = minRepetition.replace("this", "");
                    if (parseInt(minRepetition) < indexSection) {
                        addButton.click();
                        removeLayotRows.push(layoutRow.attr("id"));
                    }
                }
            }
        }
    });

    //zmaz vsetky zobrazene chybove hlasky
    $('#errorsContainerDiv').find('.error').each(function () {
        $(this).hide();
    });
}

function GetFormStorageKey() {
    var formId = GetFormId();
    return 'ego_' + formId;
}

function HandleFileSelect(evt) {
    var files = evt.target.files;

    for (var i = 0, f; f = files[i]; i++) {
        var reader = new FileReader();

        reader.onload = (function (theFile) {
            return function (e) {
                attachmentsDataArray[evt.target.id] = '<Attachment><Name>' + theFile.name + '</Name><Type>' + theFile.type
                    + '</Type><Size>' + theFile.size + '</Size>' + '<Content>' + e.target.result + '</Content></Attachment>';
            };
        })(files[0]);

        reader.readAsDataURL(files[0]);
    }
}

function WrapXmlData(xml) {
    return "<FormDataXml><XmlData>" + xml + "</XmlData></FormDataXml>";
}

function TranslateNativeToEDoc(xml, url, formId) {
    var formDataXml = WrapXmlData(xml);
    var formData = '{"FormId": "' + formId + '", "FormDataXml": "' + formDataXml + '"}';

    var contentType = "application/json";

    var eDoc = "";
    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        contentType: contentType,
        success: function (result) {
            eDoc = result;
        },
        error: function (result) {
            alert(result);
        },
        async: false
    });

    return eDoc.Content;
}

function ValidateFormWithXsd(fillerUri) {
    var xml = GetData();
    var parentWindow = window.opener;

    try {
        var formId = parentWindow.getFormId();
        var valRes = CallValidateFormWithXsd(xml, fillerUri + "ValidateFormWithXsd", formId);

        ShowValidationResult(valRes, "xsdValidation");

    } catch (err) {
        alert(err);
    }
}

function GetResultFromValidateFormWithXsd() {
    var fillerUri = GetFillerUri();
    var xml = GetData();
    var parentWindow = window.opener;

    try {
        var formId = parentWindow.getFormId();
        var result = CallValidateFormWithXsd(xml, fillerUri + "ValidateFormWithXsd", formId);

        var resultXML = $.parseXML(result),
        resultXMLTraversable = $(resultXML);

        var responseCode = resultXMLTraversable.find("response > code").text();
        var responseErrors = resultXMLTraversable.find("response > errors > error");
        var responseXsltErrors = resultXMLTraversable.find("response > errors > xsltError");
        var validationResult = '';

        if (responseCode != 'ok' || responseErrors.length != 0 || responseXsltErrors.length != 0) {
            responseErrors.each(function () {
                validationResult += this.innerHTML + '\r\n\r\n';
            });

            responseXsltErrors.each(function () {
                validationResult += this.innerHTML + '\r\n\r\n';
            });

            return validationResult;
        }
        else
            return '';
    }
    catch (err) {
        return err;
    }
}

function ValidateFormWithServer(fillerUri) {
    var xml = GetData();
    var parentWindow = window.opener;

    try {
        var formId = parentWindow.getFormId();
        var valRes = CallValidateFormWithServer(xml, fillerUri + "ValidateForm", formId);

        ShowValidationResult(valRes, "serverValidation");

    } catch (err) {
        alert(err);
    }
}

function ShowValidationResultXsdOK(statusDialog, validationType) {
    switch (GetFormLanguage()) {
        case 'en': {
            statusDialog.setMessage(validationType === "xsdValidation" ? "The form is valid against XSD schema." : "The form is valid.");
            statusDialog.setOptions({ "buttons": { "Ok": function () { statusDialog.hideDialog(); } } });
        }
            break;

        default: { // sk a default
            statusDialog.setMessage(validationType === "xsdValidation" ? "Formulár je validný voči XSD schéme." : "Formulár je validný.");
            statusDialog.setOptions({ "buttons": { "Ok": function () { statusDialog.hideDialog(); } } });
        }

    }
}

function ShowValidationResult(result, validationType) {
    var valid = true;
    var resultXML = $.parseXML(result),
        resultXMLTraversable = $(resultXML);
    var responseCode = resultXMLTraversable.find("response > code").text();
    var responseErrors = resultXMLTraversable.find("response > errors > error");
    var responseXsltErrors = resultXMLTraversable.find("response > errors > xsltError");
    var localErrors = new Array();
    var ok = "ok";
    validatorObject.resetForm();

    if (responseCode == ok && responseErrors.length == 0 && responseXsltErrors.length == 0) {
        validatorObject.resetForm();
        statusDialog.hideProgress();
        ShowValidationResultXsdOK(statusDialog, validationType);
        statusDialog.showDialog();
    }

    var valMsg = new Object;
    responseErrors.each(function (index, item) {
        if (!AddValidationMessage(index, item, valMsg)) {
            localErrors.push($(item).text());
        }
    });

    if (responseCode != ok || responseErrors.length != 0) {
        valid = false;
        validatorObject.settings.onfocusout = false;
        validatorObject.showErrors(valMsg);
        validatorObject.focusInvalid();
    }

    if (responseCode != ok || responseXsltErrors.length != 0 || localErrors.length != 0) {
        valid = false;
        var xsltErrorDiv = $("#xsltErrorContainer");

        if (!xsltErrorDiv.length) {
            $('#errorsContainerDiv').after('<div id="xsltErrorContainer"></div>');
            xsltErrorDiv = $("#xsltErrorContainer");
        }
        else {
            xsltErrorDiv.empty();
        }

        responseXsltErrors.each(function (index, item) {
            var input = $(item);
            xsltErrorDiv.append('<li>' + input.text() + '</li>');
        });

        for (var i = 0; i < localErrors.length; i++) {
            xsltErrorDiv.append('<li>' + localErrors[i] + '</li>');
        }
    }
    else {
        var xsltErrorDiv = $('#xsltErrorContainer');
        if (xsltErrorDiv.length) {
            xsltErrorDiv.remove();
        }
    }
    return valid;
}

function CallValidateFormWithXsd(xml, url, formId) {
    var formDataXml = WrapXmlData(xml);
    var formData = '{"FormId": "' + formId + '", "FormDataXml": "' + formDataXml + '"}';

    var contentType = "application/json";

    var response = "";
    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        contentType: contentType,
        success: function (result) {
            response = result;
        },
        error: function (result) {
            alert(result);
        },
        async: false
    });

    return response.Details;
}

function CallValidateFormWithServer(xml, url, formId) {
    var formDataXml = WrapXmlData(xml);
    var formData = '{"FormId": "' + formId + '", "FormDataXml": "' + formDataXml + '"}';

    var contentType = "application/json";

    var response = "";
    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        contentType: contentType,
        success: function (result) {
            response = result;
        },
        error: function (result) {
            alert(result);
        },
        async: false
    });

    return response.Content;
}

function GetConfigurationValue(key, url, callbackName) {
    var parentWindow = window.opener;
    try {
        var formId = parentWindow.getFormId();
        var values = "ConfigurationKey=" + key + "&FormId=" + formId;
        var contentType = "application/json";

        $.ajax({
            url: url,
            dataType: "jsonp",
            contentType: contentType,
            data: values,
            jsonpCallback: callbackName,
            jsonp: 'callback'
        });
    } catch (err) {
        switch (GetFormLanguage()) {
            case 'en':
                alert('workdesk was closed');
                break;

            default: // sk a default
                alert('workdesk bol uzavretý');
        }
    }
}

function HtmlEncode(value) {
    if (value == null) {
        return value;
    }

    if (/*@cc_on!@*/false || !!document.documentMode) {
        if (document.documentMode && document.documentMode == 8)
            value = value.replace(/(\r\n|\r|\n)/g, '________BREAK________');
    }

    value = $('<div/>').text(value).html();

    if (/*@cc_on!@*/false || !!document.documentMode) {
        if (document.documentMode && document.documentMode == 8)
            value = value.replace(/________BREAK________/g, '\n');
    }

    value = value.replace(/&nbsp;/g, "&#160;");

    var coding = Array();

    coding['92'] = '#92';
    coding['10'] = '#10';
    coding['34'] = 'quot';
    var finalText = "";

    for (var i = 0; i < value.length ; i++) {
        var char = value.charCodeAt(i);
        var characters = value.charAt(i);

        for (var key in coding) {
            if (key == char) {
                characters = '&' + coding[char] + ';';
                break;
            }
        }

        finalText += characters;
    }

    return finalText;
}

function DisableForm() { $('form :input').attr('disabled', 'disabled'); }

function EnableForm() {
    $('form :input').each(function () {
        var input = $(this);
        if (input.attr('isReadonly') == undefined) {
            input.removeAttr('disabled');
        }
    });
}

function SaveXmlAs() {
    try {
        var xml = GetData();
        var fileName = GetFormId() + ".xml";
        this.SaveToFile(xml, 'text/xml', fileName);
    }
    catch (exc) {
        alert(exc);
    }
}

function SaveToFile(content, type, filename) {
    if (window.Blob === 'undefined' || !window.Blob) {
        switch (GetFormLanguage()) {
            case 'en':
                throw "Save this browser is not supported, use a newer browser version";

            default: // sk a default
                throw "Ukladanie v tomto prehliadači nie je podporované, použite novšiu verziu prehliadača";
        }
    }

    try {
        var blob = new Blob([content], { type: type });
        $.saveAs(blob, filename);
    }
    catch (exc) {
        switch (GetFormLanguage()) {
            case 'en':
                throw "Error saving the file to disk";

            default: // sk a default
                throw "Chyba pri ukladaní súboru na disk";
        }
    }
}

function LoadFile(callback) {
    if (!window.FileReader) {
        switch (GetFormLanguage()) {
            case 'en':
                throw "This functionality is not supported in this browser, use a newer browser version"

            default: // sk a default
                throw "Táto funkcionalita nie je podporovaná v tomto prehliadači, použite novšiu verziu prehliadača"
        }
    }
    var content = $("#form-buttons-load-dialog");
    var exist = true;

    if (content.length == 0) {
        exist = false;
        var file = $('<input type="file" id="form-buttons-input-file"/>');
        var submit = '';

        switch (GetFormLanguage()) {
            case 'en': {
                submit = $('<input type="button" name="form-buttons-load-dialog-confirm" class="button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-onl" value="Load file" id="form-buttons-load-dialog-confirm" disabled = "disabled" />');
                content = $('<div id="form-buttons-load-dialog" />').attr('title', "Select the xml file").append(file).append(submit);
            }
                break;

            default: { // sk a default
                submit = $('<input type="button" name="form-buttons-load-dialog-confirm" class="button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-onl" value="Nahrať súbor" id="form-buttons-load-dialog-confirm" disabled = "disabled" />');
                content = $('<div id="form-buttons-load-dialog" />').attr('title', "Vyberte xml súbor").append(file).append(submit);
            }

        }

        submit.bind('click', function (e) {
            var dialog = $('#form-buttons-load-dialog');
            var input = $('input:file', dialog)[0];
            var currentFile = input.files[0];

            if (currentFile) {
                if (!currentFile.name.match(/^.*\.xml$/i)) {
                    switch (GetFormLanguage()) {
                        case 'en':
                            alert('Incorrect file format.');
                            break;

                        default: // sk a default
                            alert('Nesprávny formát súboru.');
                    }

                    return;
                }

                if (!currentFile.size > 15 * 1024 * 1024) {
                    switch (GetFormLanguage()) {
                        case 'en':
                            alert('The file must not be greater than 15MB.');
                            break;

                        default: // sk a default
                            alert('Súbor nesmie byť väčší ako 15MB.');
                    }

                    return;
                }
            }

            LoadFormFromXmlFile(currentFile, callback);
        });

        file.bind('change', function (e) {
            if ($(e.target).val()) {
                $('#form-buttons-load-dialog-confirm').removeAttr('disabled');
            } else {
                $('#form-buttons-load-dialog-confirm').attr('disabled', 'disabled');
            }
        });

        $('#' + GetFormId()).append(content);
    }
    else {
        $("#form-buttons-input-file").val('');
    }

    content.dialog({
        autoOpen: false,
        modal: true,
        width: 500
    });

    if (!exist) {
        $('#form-buttons-load-dialog').closest(".ui-dialog").addClass("load-dialog");
    }

    content.dialog('open');
}

function LoadFormFromXmlFile(file, callback) {
    var reader = new FileReader();
    var readerHelp = new FileReader();
    reader.onload = function (e) {
        try {
            callback(e.target.result);

            switch (GetFormLanguage()) {
                case 'en':
                    alert('Filling the form was successful');
                    break;

                default: // sk a default
                    alert('Naplnenie formulára bolo úspešné');
            }
        }
        catch (exc) {
            switch (GetFormLanguage()) {
                case 'en':
                    alert('Filling the form has been unsuccessful');
                    break;

                default: // sk a default
                    alert('Naplnenie formulára bolo neúspešné');
            }
        }
    };

    reader.onerror = function () {
        switch (GetFormLanguage()) {
            case 'en':
                alert('Could not read file.');
                break;

            default: // sk a default
                alert('Nepodarilo sa prečítať súbor.');
        }
    };

    readerHelp.onload = function (e) {
        if (e.target.result.search("encoding=\"ISO-8859-2\"") > 0 || e.target.result.search("encoding=\"iso-8859-2\"") > 0 || e.target.result.search("encoding=\"Iso-8859-2\"") > 0) {
            reader.readAsText(file, 'ISO-8859-2');
        }
        else if (e.target.result.search("encoding=\"WINDOWS-1250\"") > 0 || e.target.result.search("encoding=\"Windows-1250\"") > 0 || e.target.result.search("encoding=\"windows-1250\"") > 0) {
            reader.readAsText(file, 'Windows-1250');
        }
        else {
            reader.readAsText(file);
        }
    };

    readerHelp.onerror = function () {
        switch (GetFormLanguage()) {
            case 'en':
                alert('Could not read file.');
                break;

            default: // sk a default
                alert('Nepodarilo sa prečítať súbor.');
        }
    };

    readerHelp.readAsText(file);
}

function LoadFromFile() {
    if (XPathUsed()) {
        LoadFile(LoadFromFileXPathCallback);
        return;
    }

    LoadFile(LoadFromFileCallback);
}

function LoadFromFileCallback(fileContent) {
    var xmlDoc = $.parseXML(fileContent);
    var indexes = Array();
    var nodeWithContains = new Array();
    var emptyNativeTemplate = GetEmptyNativeTemplate();
    var emptyNativeTemplateDoc = $.parseXML(emptyNativeTemplate);
    AddMissingElements(xmlDoc.childNodes[0], emptyNativeTemplateDoc.childNodes[0], nodeWithContains);
    LoadXml(xmlDoc.childNodes[0], indexes);

    var context = $(document);
    var selector = 'div[id^=layoutRow]';
    var removeBtns = context.find('span[id^=removeSection]');
    removeBtns.each(function () {
        var removeButton = $(this);
        var layoutRow = $(this).closest(selector);
        var string = removeButton.attr('onclick').toString();
        var minRepetition = string.substring(string.lastIndexOf("(") + 1, string.lastIndexOf(", this"));

        if (minRepetition == 0) {
            if (DefaultDataProvider.SectionIsEmpty(layoutRow)) {
                removeButton.click();
            }
        }
    });

    IncrementDecrementInnerRepeatingIds(context);

    $("form").trigger("loadedFromXmlCompleted");
}

function LoadFromFileXPathCallback(fileContent) {
    var xmlDoc = $.parseXML(fileContent);
    var indexes = Array();
    LoadXPathXml(xmlDoc.childNodes[0], indexes);

    var context = $(document);
    var selector = 'div[id^=layoutRow]';
    var removeBtns = context.find('span[id^=removeSection]');
    removeBtns.each(function () {
        var removeButton = $(this);
        var layoutRow = $(this).closest(selector);
        var string = removeButton.attr('onclick').toString();
        var minRepetition = string.substring(string.lastIndexOf("(") + 1, string.lastIndexOf(", this"));

        if (minRepetition == 0) {
            if (DefaultDataProvider.SectionIsEmpty(layoutRow)) {
                removeButton.click();
            }
        }
    });

    IncrementDecrementInnerRepeatingIds(context);
    $("form").trigger("loadedFromXmlCompleted");
}

function AncestorsAndSelf(element) {
    var parts = new Array();
    var actual = element;

    while (actual != null && actual.parentNode != null) {
        parts.push(actual);
        actual = actual.parentNode;
    }

    return parts.reverse();
}

function GetXpath(elements) {
    var xpath = "";
    for (var i = 0; i < elements.length; i++) {
        // odstranenie pripadneho prefixu v tvare "xx:" na sekciach a poliach v pripade ze je zmeneny namespace <xx:SEction xmlns:p1="...
        var xPathClean = "";
        var pomElement = elements[i].nodeName;
        if (pomElement.indexOf(':') != -1) {
            xPathClean = pomElement.split(":");
            pomElement = xPathClean[1]; 
        }
        xpath += "/" + pomElement;

        if (elements[i].parentNode != null && elements[i].attributes != null) {
            //rootu sa preskakuju namespaces
            if (elements[i].attributes.length == 0 || i == 0) {
                continue;
            }

            xpath += "[";

            for (var j = 0; j < elements[i].attributes.length; j++) {
                xpath += "@" + elements[i].attributes[j].nodeName + "='" + elements[i].attributes[j].value + "'";
                if (j != elements[i].attributes.length - 1) {
                    xpath += " and ";
                }
            }

            xpath += "]";
        }
    }

    return xpath;
}

function ParseXPath(xPath) {
    if (xPath == undefined) {
        return null;
    }

    var xPathStructure = { xPath: xPath, constant: null, fullXpath: xPath, sectionConstants: new Array() };
    //xPath - xpath bez konstant
    //constant - konstanta na poli
    //fullXPath - plna cesta
    //sectionConstants - konstanty na sekciach s polu s cestami k nim bez konstant

    var constantFromXPath = xPath.match(/\[[^@][^\]]*\]/gi);
    if (constantFromXPath != null && constantFromXPath.length > 0) {
        for (var i = 0; i < constantFromXPath.length; i++) {
            var xPathPom = xPathStructure.xPath;
            var constant = constantFromXPath[i];
            var index = xPathStructure.xPath.indexOf(constant);
            xPathStructure.xPath = xPathStructure.xPath.replace(constant, "");

            //ak je naozaj na liste
            if (index + constant.length == xPathPom.length) {
                xPathStructure.constant = constant;
            } else {
                xPathStructure.sectionConstants[xPathStructure.xPath.substring(0, index)] = constant;
            }
        }
    }

    return xPathStructure;
}

function CreateEmptyTemplateFromXPath(nodeWithContains) {
    var xPaths = new Array();
    var absoluteXPaths = new Array();

    function XPathAllreadyExist(absoluteXPath) {
        for (var i = 0; i < absoluteXPaths.length; i++) {
            if (absoluteXPaths[i] == absoluteXPath) {
                return true;
            }
        }

        return false;
    }

    function processHtml() {
        var element = $(this);
        var name = 'name';
        var layoutRow = 'layoutRow';

        if (element.is(':input')) {
            if (element.is(':file') || element.is(':button') || element.attr('LookupDetailInfo') == "true")
                return;

            if (element.parent().hasClass(layoutRow))
                return;

            var attrXPath = element.siblings('.XPathClass');
            var attrXPathRepeatingReference = element.siblings('.XPathRepeatingReference');
            var attr = element.attr(name);
            var xPathRepeatingReferenceLayoutRowId = null;
            if (attrXPathRepeatingReference.length > 0) {
                xPathRepeatingReferenceLayoutRowId = attrXPathRepeatingReference.html();
            }

            if (attr !== undefined && attrXPath.length > 0 && attrXPath.html() != "") {
                var absoluteXPath = attrXPath.html();
                var xPathStructure = ParseXPath(absoluteXPath);
                if (!XPathAllreadyExist(xPathStructure.fullXpath)) {
                    var fakeValue = fakeValueForTemplate;
                    if (xPathStructure.fullXpath.match(/\[contains\(([^\,]+),'([^']+)'\)\]/g) && !xPathStructure.fullXpath.match(/\[not\(contains\(([^\,]+),'([^']+)'\)\)\]/g)) {
                        var containsMatch = xPathStructure.fullXpath.match(/\[contains\(([^\,]+),'([^']+)'\)\]/g);
                        var matches = containsMatch[0].match(/([^\,]+),'([^']+)'/g);
                        var matchesValues = matches[0].replace("[contains(", "");
                        matchesValues = matchesValues.split(',');
                        var containsValue = matchesValues[1].replace(/\'/g, "");

                        //fake hodnota, hodnota v contains, cesta s contains, xpath pre contains element bez xpathov
                        fakeValue = fakeValue + "|" + containsValue + "|" + matchesValues[0];
                    }

                    var newObj = { hasEmptyAttribute: false, element: element, xPathRepeatingReference: xPathRepeatingReferenceLayoutRowId, xPathConstant: xPathStructure.constant, xPath: xPathStructure.xPath, value: fakeValue, sectionConstants: xPathStructure.sectionConstants };
                    xPaths.push(newObj);
                    absoluteXPaths.push(xPathStructure.fullXpath);
                }
            }
        }

        element.children().each(processHtml);
    }

    $('#main').children('div').each(processHtml);
    var data = new Array();
    var source = $("#eDocTemplate").html().trim();
    source = $('<div/>').html(source).text();
    var template = Handlebars.compile(source, { noEscape: true });
    var xml;

    if (xPaths.length == 0) {
        return null;
    } else {
        var rootSectionName = xPaths[0].xPath.split('/')[1];
        data[rootSectionName] = new Array();
        data[rootSectionName].push({ data: new Array() });

        for (var i = 0; i < xPaths.length; i++) {
            ProcessXPathsObjects(data, xPaths[i]);
        }
        xml = template(data[rootSectionName][0]);
    }

    var xmlnsXsi = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'";
    xml = xml.replace(xml.substring(1, xml.indexOf(">")), xml.substring(1, xml.indexOf(">")) + xmlnsXsi);

    var xmlDoc = $.parseXML(xml);
    EmptyXmlNodeRecursive(xmlDoc.childNodes[0], nodeWithContains);

    return xmlDoc.childNodes[0];
}

//najde nod v zadanom roote na zaklade xpathu
function FindNode(root, xPath) {

    var ancestorsAndSelfParent = AncestorsAndSelf(root);
    var xPathParent = GetXpath(ancestorsAndSelfParent);
    if (xPath == xPathParent) {
        return root;
    }

    for (var i = 0; i < root.childNodes.length; i++) {
        var foundNode = FindNode(root.childNodes[i], xPath);
        if (foundNode != null) {
            return foundNode;
        }
    }

    return null;
}

function AddMissingElements(sourceRootNode, destinationRootNode, nodeWithContains) {

    //zisti, ktore casti stromu maju contains
    function GetContainsInformation(node, nodeWithContains) {
        if (node.nodeName != "#text") {
            for (var k = 0; k < nodeWithContains.length; k++) {
                if (nodeWithContains[k].node == node) {
                    return { containsValue: nodeWithContains[k].containsValue, containsElementXpath: nodeWithContains[k].containsElementXpath };
                }
            }

            for (var i = 0; i < node.childNodes.length; i++) {
                var pom = GetContainsInformation(node.childNodes[i], nodeWithContains);
                if (pom != null) {
                    return pom;
                }
            }
        }

        return null;
    }

    function GetMultipleElements(destinationRootNode) {
        var multipleNames = new Array();

        //najdem viac nasbne vyskyty na danej urovni
        for (var i = 0; i < destinationRootNode.childNodes.length; i++) {
            var ancestorsAndSelf = AncestorsAndSelf(destinationRootNode.childNodes[i]);
            var xPathSource = GetXpath(ancestorsAndSelf);

            if (multipleNames[xPathSource] == undefined) {
                multipleNames[xPathSource] = new Array();
            }

            multipleNames[xPathSource].push(destinationRootNode.childNodes[i]);
        }

        //vyberiem len tie, ktore sa viac krat opakuju
        var multiple = new Array();
        for (var multipleName in multipleNames) {
            if (multipleNames[multipleName].length > 1) {
                for (var k = 0; k < multipleNames[multipleName].length; k++) {
                    multiple.push(multipleNames[multipleName][k]);
                }
            }
        }

        return multiple;
    }

    //zisti, contains elementy
    function GetElementWithContains(destinationRootNode, nodeWithContains) {

        var multiple = GetMultipleElements(destinationRootNode);
        var elementWithContains = new Array();

        //najde s contains a vlozi ich
        for (var i = 0; i < multiple.length; i++) {
            var containsInformation = GetContainsInformation(multiple[i], nodeWithContains);
            if (containsInformation != null) {
                elementWithContains.push({ node: multiple[i], containsValue: containsInformation.containsValue, containsElementXpath: containsInformation.containsElementXpath });
            }
        }

        return elementWithContains;
    }

    function FindAllNodes(childrenNodes, xpath, containsValue, templateContainsXPath) {
        var foundNodes = new Array();

        for (var j = 0; j < childrenNodes.length; j++) {
            if (childrenNodes[j].nodeName == "#text") {
                continue;
            }

            var ancestorsAndSelf = AncestorsAndSelf(childrenNodes[j]);
            var xPathSource = GetXpath(ancestorsAndSelf);

            if (xpath == xPathSource) {
                //ak je predchadzajuci destination to iste, tak nesmie vlozit ale bude sa klonovat
                if (containsValue != null) {
                    var foundElement = FindNode(childrenNodes[j], templateContainsXPath);
                    if (foundElement == null) {
                        continue;
                    }

                    var fieldNode = GetFieldNode(foundElement);

                    if (fieldNode == null || fieldNode.nodeValue.indexOf(containsValue) == -1) {
                        continue;
                    }
                }

                foundNodes.push(childrenNodes[j]);
            }
        }

        return foundNodes;
    }

    var finalArray = new Array();
    var finalExistingDestination = new Array();

    var elementWithConstains = GetElementWithContains(destinationRootNode, nodeWithContains);
    var multipleElements = GetMultipleElements(destinationRootNode);

    var actualChildrenNodes = new Array();

    for (var i = 0; i < sourceRootNode.childNodes.length; i++) {
        actualChildrenNodes.push(sourceRootNode.childNodes[i]);
    }

    var indexis = new Array();

    for (var i = 0; i < destinationRootNode.childNodes.length; i++) {
        if (destinationRootNode.childNodes[i].nodeName == "#text") {
            continue;
        }

        var isMultiple = false;
        for (var h = 0; h < multipleElements.length; h++) {
            if (multipleElements[h] == destinationRootNode.childNodes[i]) {
                isMultiple = true;

                break;
            }
        }

        var ancestorsAndSelfDestination = AncestorsAndSelf(destinationRootNode.childNodes[i]);
        var xPathDestination = GetXpath(ancestorsAndSelfDestination);

        if (indexis[xPathDestination] == undefined) {
            indexis[xPathDestination] = 0;
        }

        indexis[xPathDestination]++;

        var templateContainsValue = null;
        var templateContainsXPath = null;

        //ak je templatovy element oznaceny, ze bude mat aj contains
        for (var k = 0; k < elementWithConstains.length; k++) {
            if (elementWithConstains[k].node == destinationRootNode.childNodes[i]) {
                templateContainsValue = elementWithConstains[k].containsValue;

                //ak je len na konci xpathu
                var xpathInContainsConditions = elementWithConstains[k].containsElementXpath;
                var connector = "/";
                if (xpathInContainsConditions == '.') {
                    xpathInContainsConditions = "";
                    connector = "";
                }

                templateContainsXPath = xPathDestination + connector + xpathInContainsConditions;
                
                break;
            }
        }      

        //najde vsetky elementy, ktore prisluchaju template
        var foundBusiness = FindAllNodes(actualChildrenNodes, xPathDestination, templateContainsValue, templateContainsXPath);

        //ak sa jedna o variantu, ze je element odliseny pomocou konstanty, nie contains, tak sa zoberie podla indexu
        if (isMultiple && templateContainsXPath == null) {
            if (indexis[xPathDestination] <= foundBusiness.length) {
                var tempFoundBusiness = new Array();
                if (foundBusiness[indexis[xPathDestination] - 1].textContent.indexOf(destinationRootNode.childNodes[i].textContent) == 0) {
                    tempFoundBusiness.push(foundBusiness[indexis[xPathDestination] - 1]);
                }

                foundBusiness = tempFoundBusiness;
            }
        }

        var usedNodes = new Array();

        //zisti, ktore nody sa pouzili
        for (var h = 0; h < foundBusiness.length; h++) {
            for (var k = 0; k < actualChildrenNodes.length; k++) {
                if (foundBusiness[h] == actualChildrenNodes[k]) {
                    usedNodes.push(actualChildrenNodes[k]);
                }
            }
        }

        //zmaze nody, ktore uz boli pouzite
        if (usedNodes.length > 0) {
            var clonedActualChildrenNodes = actualChildrenNodes;
            actualChildrenNodes = new Array();
            for (var l = 0; l < clonedActualChildrenNodes.length; l++) {
                var found = false;

                for (var m = 0; m < usedNodes.length; m++) {
                    if (usedNodes[m] == clonedActualChildrenNodes[l]) {
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    actualChildrenNodes.push(clonedActualChildrenNodes[l]);
                }
            }
        }

        if (foundBusiness.length > 0) {
            for (var k = 0; k < foundBusiness.length; k++) {
                finalArray.push(foundBusiness[k]);
                finalExistingDestination.push(destinationRootNode.childNodes[i]);
            }
        } else {
            finalArray.push(destinationRootNode.childNodes[i].cloneNode(true));
            finalExistingDestination.push(destinationRootNode.childNodes[i]);
        }
    }

    //este treba do final array poslat aj ostatne neprejdene elementy
    if (finalArray.length == 0) {
        return;
    }

    //zmaz cele pole
    while (sourceRootNode.childNodes.length > 0) {
        sourceRootNode.removeChild(sourceRootNode.childNodes[0]);
    }

    //nahraj childy nanovo
    for (var i = 0; i < finalArray.length; i++) {
        sourceRootNode.appendChild(finalArray[i]);
    }

    for (var i = 0; i < finalArray.length; i++) {
        AddMissingElements(finalArray[i], finalExistingDestination[i], nodeWithContains);
    }
}

//z template nodu odstrani vsetky predvyplnene hodnoty
function EmptyXmlNodeRecursive(node, nodeWithContains) {
    if (node.nodeName == "#text" && node.nodeValue.indexOf(fakeValueForTemplate) >= 0) {
        //teoreticky moze byt mailto
        var containsValue = node.nodeValue.replace(fakeValueForTemplate, "");
        containsValue = containsValue.replace("http://", "");
        containsValue = containsValue.replace("mailto:", "");

        //ak bolo vyplnene contains tak sa prenasaju aj dalsie informacie
        if (containsValue.length > 0) {
            var containsValueParts = containsValue.split("|");
            nodeWithContains.push({ node: node.parentNode, containsValue: containsValueParts[1], containsElementXpath: containsValueParts[2] });
        }

        node.nodeValue = "";
    } else {
        for (var i = 0; i < node.childNodes.length; i++) {
            EmptyXmlNodeRecursive(node.childNodes[i], nodeWithContains);
        }
    }
}

function LoadXPathXml(rootNode, indexes) {
    //nacita sa prazdna xml templeta (ako sk.xml)
    var nodeWithContains = new Array();
    var emptyTemplateRoot = CreateEmptyTemplateFromXPath(nodeWithContains);

    //doplnia sa elementy, ktore chybaju na zaklade sk.xml
    AddMissingElements(rootNode, emptyTemplateRoot, nodeWithContains);

    var indexesLayoutRows = new Array();
    //nacita sa xml do formulara
    LoadXPathXmlInternal(rootNode, indexes, indexesLayoutRows);
}

function LoadXPathXmlInternal(rootNode, indexes, indexesLayoutRows) {

    function GetChildNode(node, foundNodeName, value, onlyContains) {
        if (node.nodeName == foundNodeName) {
            var child = node.childNodes[0];
            if (child == null) {
                return null;
            }

            if (child.nodeName == "#text") {
                if (onlyContains == null) {
                    if (child.nodeValue == value) {
                        return node;
                    }
                } else if (onlyContains) {
                    if (child.nodeValue.indexOf(value) != -1) {
                        return node;
                    }
                } else {
                    if (child.nodeValue.indexOf(value) == -1) {
                        return node;
                    }
                }
            }
        } else {
            for (var i = 0; i < node.childNodes.length; i++) {
                var pom = GetChildNode(node.childNodes[i], foundNodeName, value, onlyContains);
                if (pom != null) {
                    return pom;
                }
            }
        }

        return null;
    }

    function GetParentNode(node, foundNodeName) {
        if (node.nodeName == foundNodeName) {
            return node;
        }

        return GetParentNode(node.parentNode, foundNodeName);
    }

    function GetFullXPathFieldInfo(xPath, node) {
        var xPathStructure = { xPath: xPath, fullXpath: xPath, lastField: null, xPathRepeatingReference: null };

        $('form :input').each(function () {
            var field = $(this);
            if (field.parent().hasClass("layoutRow"))
                return true;

            var parsedXPath = ParseXPath(field.siblings("span.XPathClass").html());
            if (parsedXPath == null || xPathStructure.xPath != parsedXPath.xPath) {
                return true;
            }

            var xPathRepeatingReference = field.siblings("span.XPathRepeatingReference");
            if (xPathRepeatingReference.length > 0) {
                xPathStructure.xPathRepeatingReference = xPathRepeatingReference;
            }

            if (parsedXPath.constant == null && associativeArrayLength(parsedXPath.sectionConstants) == 0) {
                xPathStructure.lastField = field;

                return false;
            }

            var constants = parsedXPath.sectionConstants;
            if (parsedXPath.constant != null) {
                constants[parsedXPath.xPath] = parsedXPath.constant;
            }

            //pocet najdenych konstant
            var foundConstants = 0;
            //pocet konstant, kedze sa jedna o asociativne pole
            var constantsCount = 0;

            for (var constantInfo in constants) {
                constantsCount++;

                //ziskam si parenta
                var constantBegins = constantInfo.split("/");
                var parentNode = GetParentNode(node, constantBegins[constantBegins.length - 1]);

                //ziskaj nazov elementu a hodnotu konstanty
                var constant = constants[constantInfo].replace(/\[/g, "");
                constant = constant.replace(/\]/g, "");

                if (constant.match(/contains\(([^\,]+),'([^']+)'\)/g)) {
                    foundConstants++;

                    continue;
                }

                var constantDefinition = constant.split("=");
                var constantNames = constantDefinition[0].split("/");
                var nodeName = constantNames[constantNames.length - 1];

                var namesValues = new Array();
                var onlyContains = null;

                if (nodeName.match(/ConstantLookup\('([^']+)','([^']+)','([^']+)'\)/g)) {
                    var matches = nodeName.match(/'([^']*)'/gi);
                    var codeList = matches[0].replace(/\'/g, "");
                    var itemCode = matches[1].replace(/\'/g, "");
                    var itemName = matches[2].replace(/\'/g, "");

                    namesValues["CodelistCode"] = codeList;
                    namesValues["ItemCode"] = itemCode;
                    namesValues["ItemName"] = itemName;                   
                } else {
                    var constantValues = constantDefinition[1].split("'");
                    var constantValue = constantValues[1];
                    namesValues[nodeName] = constantValue;
                }

                for (var nameValue in namesValues) {
                    if (GetChildNode(parentNode, nameValue, namesValues[nameValue], onlyContains) == null) {
                        return true;
                    }
                }

                foundConstants++;
            }

            if (foundConstants == constantsCount) {
                xPathStructure.lastField = field;
                xPathStructure.fullXpath = TrimContainsConstant(parsedXPath.fullXpath);

                return false;
            }
        });

        return xPathStructure;
    }

    function TrimContainsConstant(xpath) {
        xpath = xpath.replace(/\[not\(contains\(([^\,]+),'([^']+)'\)\)\]/g, "");
        xpath = xpath.replace(/\[contains\(([^\,]+),'([^']+)'\)\]/g, "");

        return xpath;
    }

    function FindInput(absoluteXPath, position) {
        var foundField = { field: null, sibblings: null };

        var foundFieldsCount = 0;
        var wasContains = false;

        var allInputs = $('form :input');

        allInputs.each(function () {
            var field = $(this);
            if (field.parent().hasClass("layoutRow"))
                return true;

            if (!field.attr("name"))
                return true;

            var xpathInfo = (field.siblings("span.XPathClass"));

            if (xpathInfo.length == 0) {
                return true;
            }

            var xpath = xpathInfo.html();

            var trimedXpath = TrimContainsConstant(xpath);

            if (absoluteXPath != trimedXpath) {
                return true;
            }

            wasContains = xpath.length != trimedXpath.length;

            //boli orezane contains
            if (wasContains) {
                if (position > foundFieldsCount) {
                    foundFieldsCount++;

                    return true;
                } 
            } else {
                if (position > 0) {
                    var index = field.attr("name").indexOf(sign);
                    var attr = "";
                    if (index > -1) {
                        attr = field.attr("name").substr(index + 1, field.attr("name").length - index);
                    }

                    if (attr != position) {
                        return true;
                    }
                }
            }

            foundField.field = field;

            //ak nie su viacnasobne prvky
            if ((!foundField.field.is(':checkbox') || foundField.field.hasClass("checkBox")) && !foundField.field.is(':radio')) {
                return false;
            }

            //ak sa jednao checkboxlist, radioButtonList tak moze byt hodnot viac
            if (foundField.sibblings == null) {
                foundField.sibblings = new Array();
            }
            foundField.sibblings.push(field);
        });

        //musi este najst ostatne sibligs ak sa jedna o contains
        if (foundField.field != null && wasContains && ((foundField.field.is(':checkbox') && !foundField.field.hasClass("checkBox")) || foundField.field.is(':radio'))) {
            allInputs.each(function() {
                var field = $(this);
                if (field.attr("name") != foundField.field.attr("name")) {
                    return true;
                }

                for (var i = 0; i < foundField.sibblings.length; i++) {
                    if (foundField.sibblings[i].attr("id") == field.attr("id")) {
                        return true;
                    }
                }

                foundField.sibblings.push(field);
            });
        }

        return foundField;
    }

    function GetFullXPathLayoutRowInfo(xPath, node) {
        var xPathStructure = { xPath: xPath, fullXpath: xPath, layoutRows: new Array() };

        $("form div.layoutRow").each(function () {
            var layoutRow = $(this);

            var parsedXPath = ParseXPath(layoutRow.children("span.XPathClass").html());
            if (parsedXPath == null || xPathStructure.xPath != parsedXPath.xPath) {
                return true;
            }

            if (parsedXPath.constant == null && associativeArrayLength(parsedXPath.sectionConstants) == 0) {
                xPathStructure.layoutRows.push(layoutRow);

                return true;
            }

            var constants = parsedXPath.sectionConstants;
            if (parsedXPath.constant != null) {
                constants[parsedXPath.xPath] = parsedXPath.constant;
            }

            //pocet najdenych konstant
            var foundConstants = 0;
            //pocet konstant, kedze sa jedna o asociativne pole
            var constantsCount = 0;

            for (var constantInfo in constants) {
                constantsCount++;

                //ziskam si parenta
                var constantBegins = constantInfo.split("/");
                var parentNode = GetParentNode(node, constantBegins[constantBegins.length - 1]);

                //ziskaj nazov elementu a hodnotu konstanty
                var constant = constants[constantInfo].replace(/\[/g, "");
                constant = constant.replace(/\]/g, "");

                if (constant.match(/contains\(([^\,]+),'([^']+)'\)/g)) {
                    foundConstants++;

                    continue;
                }

                var constantDefinition = constant.split("=");
                var constantNames = constantDefinition[0].split("/");
                var nodeName = constantNames[constantNames.length - 1];

                var namesValues = new Array();
                var onlyContains = null;

                if (nodeName.match(/ConstantLookup\('([^']+)','([^']+)','([^']+)'\)/g)) {
                    var matches = nodeName.match(/'([^']*)'/gi);
                    var codeList = matches[0].replace(/\'/g, "");
                    var itemCode = matches[1].replace(/\'/g, "");
                    var itemName = matches[2].replace(/\'/g, "");

                    namesValues["CodelistCode"] = codeList;
                    namesValues["ItemCode"] = itemCode;
                    namesValues["ItemName"] = itemName;
                } else {
                    var constantValues = constantDefinition[1].split("'");
                    var constantValue = constantValues[1];
                    namesValues[nodeName] = constantValue;
                }

                for (var nameValue in namesValues) {
                    if (GetChildNode(parentNode, nameValue, namesValues[nameValue], onlyContains) == null) {
                        return true;
                    }
                }

                foundConstants++;
            }

            if (foundConstants == constantsCount) {
                xPathStructure.fullXpath = TrimContainsConstant(parsedXPath.fullXpath);
                xPathStructure.layoutRows.push(layoutRow);
            }
        });

        return xPathStructure;
    }

    function IsEmpty(node) {
        if (node.nodeName == "#text") {
            if (node.nodeValue != null || node.nodeValue !== "") {
                return false;
            }
        } else {
            for (var i = 0; i < node.childNodes.length; i++) {
                var result = IsEmpty(node.childNodes[i]);
                if (!result) {
                    return result;
                }
            }
        }

        return true;
    }

    //bud vrato prvy element, ktory nema uz potomka, alebo codelist strukturu
    function IsFinalElement(node) {

        if (node.childNodes.length == 0 || GetFieldNode(node) != null) {
            return true;
        }

        if (node.childNodes.length > 0) {
            for (var k = 0; k < node.childNodes.length; k++) {
                if (node.childNodes[k].nodeName == "Codelist") {
                    return true;
                }
            }
        }

        return false;
    }

    function ProcessFinalElement(indexes, node, repeatingXPath) {
        var fieldNode = GetFieldNode(node);
        if (fieldNode != null) {
            var ancestorsAndSelf = AncestorsAndSelf(node);
            var xPath = GetXpath(ancestorsAndSelf);
            var xPathFieldInfo = GetFullXPathFieldInfo(xPath, node);

            if (xPathFieldInfo.lastField != null) {
                xPath = xPathFieldInfo.fullXpath;

                var fieldInfo = FindInput(xPath, indexes[repeatingXPath]);
                node = fieldNode;

                if (fieldInfo.field == null) {
                    return;
                }

                if (fieldInfo.field.is(':checkbox')) {
                    if (fieldInfo.field.hasClass("checkBox")) {
                        if (fieldInfo.field.hasClass("xsd_boolean")) {
                            if (node.nodeValue == "1") {
                                var fieldCheckbox = fieldInfo.field;
                                if (!fieldCheckbox.attr('checked')) {
                                    if (fieldCheckbox.attr("disabled") !== undefined || fieldCheckbox.attr("readonly") !== undefined) {
                                        fieldCheckbox.attr("checked", "true");
                                    }

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

                            field.click();
                            break;
                        }
                    }
                } else if (fieldInfo.field.attr("multiple")) {
                    for (var index = 0; index < fieldInfo.field[0].childNodes.length; index++) {
                        var childNode = fieldInfo.field[0].childNodes[index];
                        if (childNode.value == node.nodeValue) {
                            childNode.selected = true;
                            break;
                        }
                    }
                } else if (fieldInfo.field.is('select')) {
                    var val = node.nodeValue;
                    if (val != "") {
                        fieldInfo.field.val(val);

                        //kvoli online ciselnikom
                        fieldInfo.field.data('newValue', val);
                        fieldInfo.field.change();
                        fieldInfo.field.removeData('newValue');
                    }
                } else {
                    var val = node.nodeValue;
                    if (val != "") {
                        if (fieldInfo.field.hasClass("xsd_decimal") || fieldInfo.field.hasClass("xsd_float") || fieldInfo.field.hasClass("xsd_double"))
                            val = val.replace('.', ',');
                        else if (fieldInfo.field.hasClass("xsd_date"))
                            val = xmlHelper.fromXmlDate(val);
                        else if (fieldInfo.field.hasClass("xsd_time"))
                            val = xmlHelper.fromXmlTime(val);
                        else if (fieldInfo.field.hasClass("datetime"))
                            val = xmlHelper.fromXmlDateTime(val);
                        else if (fieldInfo.field.hasClass("datetimewithseconds"))
                            val = xmlHelper.fromXmlDateTimeWithSeconds(val);
                        else if (fieldInfo.field.hasClass("xsd_anyURI"))
                            val = xmlHelper.fromXmlAnyURI(val);
                    }

                    fieldInfo.field.val(val);
                }
            }
        }
    }

    //equalsNodeNames - Hovori, ci sa ma zvacsovat voci ostatnym 
    function ProcessFinalElements(indexes, rootNode, repeatingXPath, duplicateNode, xpathsInElements) {
        //ked pride na prvy z elementov, tak zisti o aky prvok sa jedna
        if (node.childNodes.length == 0 ||GetFieldNode(rootNode) != null) {
            var ancestorsAndSelf = AncestorsAndSelf(rootNode);
            var xPath = GetXpath(ancestorsAndSelf);
            var xPathFieldInfo = GetFullXPathFieldInfo(xPath, rootNode);
            xPath = xPathFieldInfo.fullXpath;
            var allowEquals = false;

            if (xPathFieldInfo.lastField == null) {
                repeatingXPath = xPath;
            } else {
                if (!xPathFieldInfo.lastField.hasClass("remoteCheckBoxList")
                    && !xPathFieldInfo.lastField.hasClass("radioButtonList")
                    && !xPathFieldInfo.lastField.hasClass("checkBoxList")
                    && !xPathFieldInfo.lastField.hasClass("hierarchicalTree")
                    && !xPathFieldInfo.lastField.hasClass("listBox")
                    && !xPathFieldInfo.lastField.hasClass("remoteRadioButtonList")
                    && !xPathFieldInfo.lastField.hasClass("multiCombobox")) {
                    repeatingXPath = xPath;
                } else {
                    if (duplicateNode) {
                        allowEquals = true;
                    } else {
                        if (xPathFieldInfo.lastField.hasClass("remoteCheckBoxList") ||
                            xPathFieldInfo.lastField.hasClass("listBox") ||
                            xPathFieldInfo.lastField.hasClass("multiCombobox") ||
                            xPathFieldInfo.lastField.hasClass("hierarchicalTree")) {
                            for (var i = 0; i < xpathsInElements.length; i++) {
                                if (xpathsInElements[i] == xPath) {
                                    allowEquals = true;

                                    break;
                                }
                            }
                        }
                    }
                }
            }

            var xpathRepeatingInfo = null;
            if (xPathFieldInfo.xPathRepeatingReference != null) {
                xpathRepeatingInfo = XPathGetSectionLevel(xPathFieldInfo.xPathRepeatingReference.html(), xPathFieldInfo.lastField);
            }

            //ak nie je ziadny, alebo sa nejedna o viacnasobne elementy, tak daj original xpath

            if (indexes[repeatingXPath] === undefined) {
                indexes[repeatingXPath] = 0;
                xpathsInElements.push(xPath);
            } else {
                if (!allowEquals) {
                    if (!duplicateNode) {
                        indexes[repeatingXPath]++;
                        xpathsInElements.push(xPath);
                    } else {
                        //alebo sa mzoe stat, ze je sekcia zaobalena
                        if (xpathRepeatingInfo != null) {
                            indexes[repeatingXPath]++;
                            xpathsInElements.push(xPath);
                        }
                    }
                }
            }

            ProcessFinalElement(indexes, rootNode, repeatingXPath);
            return;
        }

        for (var i = 0; i < rootNode.childNodes.length; i++) {
            ProcessFinalElements(indexes, rootNode.childNodes[i], repeatingXPath, duplicateNode, xpathsInElements);
        }
    }

    function ProcessFinalLayoutRow(xPath, node, indexesLayotRows) {
        var xPathLayoutRowInfo = GetFullXPathLayoutRowInfo(xPath, node);
        xPath = xPathLayoutRowInfo.fullXpath;

        if (indexesLayotRows[xPath] === undefined) {
            indexesLayotRows[xPath] = 0;
        } else {
            indexesLayotRows[xPath]++;
        }

        var foundSection = xPathLayoutRowInfo.layoutRows[indexesLayotRows[xPath]];

        if ((((foundSection == undefined || (!IsEmpty(node) && foundSection.attr("isempty") == "true")))) && xPathLayoutRowInfo.layoutRows.length > 0) {
            var foundSectionId = xPathLayoutRowInfo.layoutRows[0].attr("id");
            var layoutRowIDWithoutIncremental = GetValueWithoutIncremental(foundSectionId);
            var addButton = $('div[id^=' + foundSectionId + ']').last().find('#addSection' + layoutRowIDWithoutIncremental);
            if (addButton[0] != null) {
                addButton.click();
            }
        }
    }

    var lastFinalElement = null;

    for (var i = 0; i < rootNode.childNodes.length; i++) {
        var node = rootNode.childNodes[i];
        var ancestorsAndSelf = AncestorsAndSelf(node);
        var xPath = GetXpath(ancestorsAndSelf);

        var xPathLastFinalElement = null;
        if (lastFinalElement != null) {
            var ancestorsAndSelfLastFinalElement = AncestorsAndSelf(lastFinalElement);
            xPathLastFinalElement = GetXpath(ancestorsAndSelfLastFinalElement);
        }

        ProcessFinalLayoutRow(xPath, node, indexesLayoutRows);

        if (IsFinalElement(node)) {
            var xpathsInElements = new Array();
            ProcessFinalElements(indexes, node, xPath, lastFinalElement != null && xPathLastFinalElement == xPath, xpathsInElements);
            lastFinalElement = node;

            continue;
        }

        LoadXPathXmlInternal(node, indexes, indexesLayoutRows);
    }
}

function GetFieldNode(node) {
    if (node == null) {
        return null;
    }

    if (node.childNodes.length > 0) {
        for (var k = 0; k < node.childNodes.length; k++) {
            if (node.childNodes[k].nodeName == "#text") {
                return node.childNodes[k];
            }
        }
    }

    return null;
}

function LoadXml(rootNode, indexes) {
    function IsEmpty(node) {
        if (node.nodeName == "#text") {
            if (node.nodeValue != null || node.nodeValue !== "") {
                return false;
            }
        }
        else {
            for (var i = 0; i < node.childNodes.length; i++) {
                var result = IsEmpty(node.childNodes[i]);
                if (!result) {
                    return result;
                }
            }
        }

        return true;
    }

    var lastNode = null;

    for (var i = 0; i < rootNode.childNodes.length; i++) {

        var node = rootNode.childNodes[i];

        var nodeName = node.nodeName;
        nodeName = nodeName.replace("DoNotValidate_", "");

        var fieldNode = GetFieldNode(node);
        var lastFieldNode = GetFieldNode(lastNode);

        if (indexes[nodeName] === undefined) {
            indexes[nodeName] = 0;
        }
        else {
            //ak su oba fieldnody a maju rovnaky name, tak sa nebude zvysovat, lebo sa bude jednat o multi prvok
            if (fieldNode == null || lastFieldNode == null || fieldNode.parentNode.nodeName != lastFieldNode.parentNode.nodeName) {
                indexes[nodeName]++;
            }
        }

        lastNode = node;

        if (fieldNode == null) {

            var allLayoutRows = $('div[id^=layoutRow]');
            var repeatingIndex = indexes[nodeName];
            var repeatingPostfixText = repeatingIndex;
            if (repeatingIndex == 0) {
                repeatingPostfixText = '';
            }
            else {
                repeatingPostfixText = repeatingPostfix + repeatingIndex;
            }

            var foundSection = null;
            var layoutRowID = null;

            allLayoutRows.each(function () {
                var layoutRow = $(this);
                if (layoutRow.find('[name=' + nodeName + ']').length > 0) {
                    var layoutRowPostfix = layoutRow.attr('id').replace(GetValueWithoutIncremental(layoutRow.attr('id')), "");
                    layoutRowID = layoutRow.attr('id');
                    if (layoutRowPostfix == repeatingPostfixText) {
                        foundSection = layoutRow;
                    }
                }
            });

            if ((foundSection == null || (!IsEmpty(node) && foundSection.attr("isempty") == "true")) && layoutRowID != null) {
                var layoutRowIDWithoutIncremental = GetValueWithoutIncremental(layoutRowID);
                var addButton = $('div[id^=' + layoutRowID + ']').last().find('#addSection' + layoutRowIDWithoutIncremental);
                if (addButton[0] != null) {
                    addButton.click();
                }
            }

            LoadXml(node, indexes);
        }
        else {
            node = fieldNode;
            var repeatingIndex = indexes[nodeName];
            var repeatingPostfixText = repeatingIndex;
            if (repeatingIndex == 0) {
                repeatingPostfixText = '';
            }
            else {
                repeatingPostfixText = repeatingElementPostfix + repeatingIndex;
            }

            var field = $("[name=" + nodeName + repeatingPostfixText + "]");

            if (field.length > 0) {
                if (field.is(':checkbox')) {
                    if (field.hasClass("checkBox")) {
                        if (field.hasClass("xsd_boolean")) {
                            if (node.nodeValue == "1") {
                                var fieldCheckbox = $(field);
                                if (!fieldCheckbox.attr('checked')) {
                                    if (fieldCheckbox.attr("disabled") !== undefined || fieldCheckbox.attr("readonly") !== undefined) {
                                        fieldCheckbox.attr("checked", "true");
                                    }
                                    field.click();
                                }
                            }
                        }
                        else {
                            if (field.val() == node.nodeValue) {
                                var fieldCheckbox = $(field);
                                if (!fieldCheckbox.attr('checked')) {
                                    if (fieldCheckbox.attr("disabled") !== undefined || fieldCheckbox.attr("readonly") !== undefined) {
                                        fieldCheckbox.attr("checked", "true");
                                    }
                                    field.click();
                                }
                            }
                        }
                    }
                    else {
                        for (var index = 0; index < field.length; index++) {
                            var childNode = field[index];
                            if (childNode.value == node.nodeValue) {
                                var fieldCheckbox = $(childNode);
                                if (!fieldCheckbox.attr('checked')) {
                                    if (fieldCheckbox.attr("disabled") !== undefined || fieldCheckbox.attr("readonly") !== undefined) {
                                        fieldCheckbox.attr("checked", "true");
                                    }
                                    childNode.click();
                                }
                            }
                        }
                    }
                }
                else if (field.is(':radio')) {
                    for (var index = 0; index < field.length; index++) {
                        var childNode = field[index];
                        if (childNode.value == node.nodeValue) {
                            var radio = $(childNode);
                            if (radio.attr("disabled") !== undefined || radio.attr("readonly") !== undefined) {
                                radio.attr("checked", "true");
                            }

                            childNode.click();
                            break;
                        }
                    }
                }
                else if (field.attr("multiple")) {
                    for (var index = 0; index < field[0].childNodes.length; index++) {
                        var childNode = field[0].childNodes[index];
                        if (childNode.value == node.nodeValue) {
                            childNode.selected = true;
                            break;
                        }
                    }
                } else {
                    var val = node.nodeValue;
                    if (val != "") {
                        if (field.hasClass("xsd_decimal") || field.hasClass("xsd_float") || field.hasClass("xsd_double"))
                            val = val.replace('.', ',');
                        else if (field.hasClass("xsd_date"))
                            val = xmlHelper.fromXmlDate(val);
                        else if (field.hasClass("xsd_time"))
                            val = xmlHelper.fromXmlTime(val);
                        else if (field.hasClass("datetime"))
                            val = xmlHelper.fromXmlDateTime(val);
                        else if (field.hasClass("datetimewithseconds"))
                            val = xmlHelper.fromXmlDateTimeWithSeconds(val);
                        else if (field.hasClass("xsd_anyURI"))
                            val = xmlHelper.fromXmlAnyURI(val);
                    }

                    field.val(val);
                }
            }
        }
    }
}

function associativeArrayLength(array) {
    var length = 0;
    for (var object in array) {
        length++;
    }
    return length;
}

function GetEmptyNativeTemplate() {

    var formId = GetFormId();
    var xmlns = GetMetadataNamespace();
    var xml = '<' + formId + xmlns + '>';
    var usedXmlNames = new Array();

    function processHtml() {
        var element = $(this);
        var name = 'name';
        var layoutRow = 'layoutRow';
        var firstInput;
        if (element.hasClass(layoutRow)) {
            firstInput = element.children("input:first");
            if (firstInput.attr(name) != 'Attachments') {
                xml += '<' + firstInput.attr(name) + '>';
            }
        }

        if (element.is(':input')) {
            if (element.is(':file') || element.is(':button') || element.attr('LookupDetailInfo') == "true")
                return;

            if (element.parent().hasClass(layoutRow))
                return;

            var attr = element.attr(name);
            if (attr != undefined) {
                var index = attr.indexOf(sign);
                if (index == -1) {
                    if (usedXmlNames[attr] == undefined) {
                        attr = attr.replace(disableValidatorPrefix, "");
                        xml += '<' + attr + '>' + '</' + attr + '>';
                        usedXmlNames[attr] = "";
                    }
                }
            }
        }

        element.children().each(processHtml);

        if (element.hasClass(layoutRow)) {
            firstInput = element.children("input:first");
            if (firstInput.attr(name) != 'Attachments') {
                xml += '</' + firstInput.attr(name) + '>';
            }
        }
    }

    $('#main').children('div').each(processHtml);

    xml += '</' + formId + '>';

    return xml;
}

function FillLookup(element, lookupDetailInfo, lookupFieldValue) {
    var lookupItems = null;
    var lookupUri = GetLookupUri();

    $.ajax({
        type: "GET",
        url: GetLookupUri(),
        async: false
    }).done(function (data) {
        if (data != null) {
            lookupItems = $.parseJSON(data.replace("(", "").replace(");", ""));
        }
    });

    if (lookupItems != null && lookupItems.aaData != null) {
        var randIndex = Math.floor(Math.random() * lookupItems.aaData.length);
        var randLookupItem = lookupItems.aaData[randIndex];

        element.val(randLookupItem[1]);
        lookupDetailInfo.val(randLookupItem[1]);
        lookupFieldValue.val(randLookupItem[0]);
    }
}

function FillSpecificInput(element, rules, data) {
    var rule;
    var finalValue = "";
    var rIndex = Math.floor((Math.random() * data.length));

    for (rule in rules) {
        if (rules.hasOwnProperty(rule)) {
            if (rule == "date") {
                var dateValue = new Date();
                finalValue = $.datepicker.formatDate('dd.mm.yy', new Date());
                break;
            }
            if (rule.indexOf("RegEx") != -1) {
                finalValue = "";
                if (element.attr("id").toLowerCase().indexOf("email") != -1
                  || element.siblings("span.XPathClass").html().indexOf("InternetAddress[contains(Address,'@')]/Address") != -1) {
                    finalValue = data[rIndex] + "@" + data[rIndex] + ".com";
                    break;
                } else
                    if (element.attr("title").toLowerCase().indexOf("webovú adresu") != -1
                      || element.siblings("span.XPathClass").html().indexOf("InternetAddress[not(contains(Address,'@'))]/Address") != -1) {
                        finalValue = data[rIndex] + ".com";
                        break;
                    } else
                        if (element.attr("title").toLowerCase().indexOf("číslo telefónu") != -1
                          || element.siblings("span.XPathClass").html().indexOf("TelephoneAddress/Number/FormattedNumber") != -1) {
                            finalValue = "+421";
                            for (var i = 0; i <= 8; i++) {
                                var randNumber = Math.floor((Math.random() * 10));
                                finalValue += randNumber;
                            }
                            break;
                        } else
                            if (element.attr("title").toLowerCase().indexOf("ičo") != -1) {
                                for (var i = 0; i <= 7; i++) {
                                    var randNumber = Math.floor((Math.random() * 10));
                                    finalValue += randNumber;
                                }
                                break;
                            } else
                                if (element.attr("title").toLowerCase().indexOf("dič") != -1
                                   || element.attr("title").toLowerCase().indexOf("rodné číslo") != -1) {
                                    for (var i = 0; i <= 9; i++) {
                                        var randNumber = Math.floor((Math.random() * 10));
                                        finalValue += randNumber;
                                    }
                                    break;
                                } else
                                    if (element.attr("title").toLowerCase().indexOf("poštové smerovacie číslo") != -1
                                      || element.siblings("span.XPathClass").html().indexOf("DeliveryAddress/PostalCode") != -1) {
                                        for (var i = 0; i <= 4; i++) {
                                            var randNumber = Math.floor((Math.random() * 10));
                                            finalValue += randNumber;
                                        }
                                        break;
                                    } else
                                        if (element.attr("title").toLowerCase().indexOf("ič dph") != -1) {
                                            finalValue = "SK";
                                            for (var i = 0; i <= 9; i++) {
                                                var randNumber = Math.floor((Math.random() * 10));
                                                finalValue += randNumber;
                                            }
                                            break;
                                        } else
                                            if (element.hasClass("xsd_decimal")) {
                                                var randNumber = Math.floor((Math.random() * 100) + 1);
                                                finalValue += randNumber;
                                            } else {
                                                //finalValue = "regex"; 
                                            }
                break;
            }
            if (rule == "minlength") {
                var randomValue = data[rIndex];
                var minLength = parseInt(rules.minlength);

                while (randomValue.length < minLength) {
                    randomValue += Math.floor((Math.random() * 10));
                }
                finalValue = randomValue;
            }
            if (rule == "maxlength") {
                var randomValue = data[rIndex];
                var maxLength = parseInt(rules.maxlength);

                if (randomValue.length <= maxLength) {
                    finalValue = randomValue;
                } else {
                    finalValue = randomValue.substring(0, maxLength);
                }
            }
            if (element.attr("title").toLowerCase().indexOf("poštové smerovacie číslo") != -1
              || element.siblings("span.XPathClass").html().indexOf("DeliveryAddress/PostalCode") != -1) {
                finalValue = "";
                for (var i = 0; i <= 4; i++) {
                    var randNumber = Math.floor((Math.random() * 10));
                    finalValue += randNumber;
                }
            }
        }
    }

    element.val(finalValue).change();
}

function FillForm() {
    // random click tlačidla Pridať         

    var elements = $("input:radio, input:checkbox, select, input:text, textarea");
    var data = ["lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "ut", "aliquam", "purus", "sit", "amet", "luctus", "venenatis", "lectus", "magna", "fringilla", "urna", "porttitor", "rhoncus", "dolor", "purus", "non", "enim", "praesent", "elementum", "facilisis", "leo", "vel", "fringilla", "est", "ullamcorper", "eget", "nulla", "facilisi", "etiam", "dignissim", "diam", "quis", "enim", "lobortis", "scelerisque", "fermentum", "dui", "faucibus", "in", "ornare", "quam", "viverra", "orci", "sagittis", "eu", "volutpat", "odio", "facilisis", "mauris", "sit", "amet", "massa", "vitae", "tortor", "condimentum", "lacinia", "quis", "vel", "eros", "donec", "ac", "odio", "tempor", "orci", "dapibus", "ultrices", "in", "iaculis", "nunc", "sed", "augue", "lacus", "viverra", "vitae", "congue", "eu", "consequat", "ac", "felis", "donec", "et", "odio", "pellentesque", "diam", "volutpat", "commodo", "sed", "egestas", "egestas", "fringilla", "phasellus", "faucibus", "scelerisque", "eleifend", "donec", "pretium", "vulputate", "sapien", "nec", "sagittis", "aliquam", "malesuada", "bibendum", "arcu", "vitae", "elementum"];
    var dataLength = data.length;

    elements.each(function () {
        var element = $(this);
        if (element.is(":visible") && !element.is(":disabled") && element.attr("readonly") != "readonly") {
            switch (this.type) {
                case 'radio': {
                    var elemName = element.attr("name");
                    var allRb = $("[name='" + elemName + "']");
                    if (!allRb.is(":checked")) {
                        var randIndex = Math.floor(Math.random() * allRb.length);
                        allRb.eq(randIndex).click();
                    }
                }
                    break;
                case 'checkbox': {
                    var randCheck = Math.floor(Math.random() * 2);
                    if (element.hasClass("xsd_required")) {
                        randCheck = 1;
                    }
                    if (randCheck && !element.is(":checked")) {
                        element.click();
                    }
                }
                    break;
                case 'select-one': {
                    if (element.is(":blank")) {
                        var options = element.find("option");
                        var randIndex = Math.floor((Math.random() * (options.length - 1)) + 1);
                        var selectedOption = options.eq(randIndex).val();
                        element.val(selectedOption).change();
                    }
                }
                    break;
                case 'text': {
                    if (element.is(":blank")) {
                        if (element.hasClass("remoteLookup")) {
                            var lookupDetailInfo = element.siblings(".LookupDetailInfo");
                            var fieldValueId = element.attr("id") + "ItemName";
                            var lookupFieldValue = $("[id='" + fieldValueId + "']");

                            FillLookup(element, lookupDetailInfo, lookupFieldValue);
                        } else {
                            FillSpecificInput(element, element.rules(), data);
                        }
                    }
                }
                    break;
                case 'textarea': {
                    if (element.is(":blank")) {
                        var randLength = Math.floor((Math.random() * dataLength - 1) + 1);
                        var genString = "";

                        for (var i = 0; i <= randLength; i++) {
                            var randIndex = Math.floor((Math.random() * dataLength - 1));
                            if (i == 0) {
                                genString = data[randIndex];
                            } else {
                                genString += " " + data[randIndex];
                            }
                        }

                        element.val(genString).change();
                    }
                }
                    break;
                default:
                    break;
            }
        }
    });
}
