var add = "add";
var remove = "remove";

function GetIsAsynchronously() {
    try {
        if (isAsynchronously !== undefined) {
            return isAsynchronously;
        }
    } catch (err) {
    }

    return false;
}

function InitEgoFunctions() {
    InitValidation();

    if ($.isFunction(window.InitValidationCustomMetods))
        InitValidationCustomMetods();

    ReindexElements();
    InitPopUpDialog();
    InitPickers();
    InitSectionAccordion();
    InitDataTablePlugIn();
    InitConditionalRules();
    InitRadio();
    InitButtons();
    LocalizeErrorMessages();
    CleanRepetitionButtons();
    InitRepetitionSections($(document));
    InitDebugCode();
    ResizeTextareaField();
    LayoutTempRepetitonSection();
    InitHelp();
    InitMultiCombobox();
    InitRemoteCombobox();
    InitCombobox();
    InitRadioButonList();
    InitRemoteRadioButonList();
    InitRemoteCheckBoxList();
    // Init pageable section
    InitPageableSection();
    InitCloseBtns();
    InitHierarchicallyTree();
    InitAutocompletes();
    InitTabIndexes();
    expandLayoutRowsAndFocus();
    if ($.isFunction(window.vucInit))
        vucInit($(document));
}

$(document).ready(function () {
        if (GetIsAsynchronously()) {
            return;
        }

    InitEgoFunctions();
});

function XPathUsed() {
    return $("form").find("span.XPathClass").length > 0;
}

function InitCloseBtns(onNode) {
    if (onNode == null) onNode = $(":root");
    onNode.find("[id^='removeSectionlayoutRow']").each(function () {
        var removeBtn = $(this);
        var layoutRow = removeBtn.parent().parent();
		if (!layoutRow.hasClass("noCloseButton")) {
			var onClickFn = removeBtn.attr("onclick");
			var headerClass = "withHeader";
			var styleStr = "display: none;";
			var title = removeBtn.attr("title");
			var layoutRowId = layoutRow.attr("id").split('_');

			if (layoutRow.children("div[class^=caption]")[0] == null || layoutRow.children("div[class^=caption]").children("[class^=headercorrection]")[0] == null) {
			    headerClass = "noHeader";
			}

			if (layoutRow.parent().children("[id^=" + layoutRowId[0] + "]").length > 1)
				styleStr = "display: block;";

			//úprava keď je širší column ako rám sekcie    
			var column = layoutRow.parent().parent();
			if (column[0].offsetWidth > column.parent()[0].offsetWidth) {
				styleStr = styleStr + " margin-left:" + (column.parent()[0].offsetWidth - 15).toString() + "px;";
				if (headerClass != "withHeader")
					headerClass = "";
			}

		    var closeBtnClass = "closeButton ui-icon ui-icon-closethick " + headerClass;
			var spanStr = '<span class="' + closeBtnClass + '" onclick="' + onClickFn + '" style="' + styleStr + '" title="' + title + '"></span>';

			layoutRow.children(":first").before(spanStr);
		}
    });
}

function InitRemoteCheckBoxList() {
    $("form").InitRemoteCheckBoxList();
}

function InitAutocompletes() {
    $("form").InitAutocompletes();
}

function InitRemoteRadioButonList() {
    $("form").InitRemoteRadioButonList();
}

function InitRadioButonList() {
    $("form").InitRadioButonList();
}

function InitHierarchicallyTree() {
    $("form").InitHierarchicallyTree();
}

function InitPageableSection() {
    // Init all pageable section
    $('.section.pageableSection', 'form').pageableSection({
        validator: window.validatorObject
    });
}

function InitMultiCombobox() {
    $("form").InitMultiCombobox();
}

function DeleteMultiCombobox() {
    $("form").DeleteMultiCombobox();
}

function InitRemoteCombobox() {
    $("form").InitRemoteCombobox();
}

function InitCombobox() {
    $("form").InitCombobox();
}

function InitHelp() {
    $("form").InitHelp();
}

function InitRepetitionSections(context) {
    var selector = 'div[id^=layoutRow]';
    var removeBtns = context.find('span[id^=removeSection]');
    removeBtns.each(function () {
        var layoutRow = $(this).closest(selector);
        $(layoutRow).each(function () {
            var hasVal = false;
            $(this).find('input, select, textarea').each(function () {
                var element = $(this)[0];
                if (element.type != 'radio' && element.value != '' && element.type != 'button')
                    hasVal = true;
            });
            if (!hasVal)
                removeSectionInit(this);
        });
    });

    IncrementDecrementInnerRepeatingIds(context);
}

function removeSectionInit(sender) {
    var layoutRow = $(sender);
    var layoutRowPrevious = $(layoutRow[0].id).prev('div[id^=layoutRow]');
    var id = sender.id;
    if (id.indexOf(repeatingPostfix) == -1) {
        var removeButton = layoutRow.find('#removeSection' + id);
        var string = removeButton.attr('onclick').toString();
        var minRepetition = string.substring(string.lastIndexOf("(") + 1, string.lastIndexOf(", this"));
        var sectionsCount = countSection(removeButton, 'removeSection');

        if (sectionsCount == minRepetition)
            return null;
        var children = layoutRowPrevious.children('div[id^=repetitionCommands]');
        if (sectionsCount == minRepetition && sectionsCount > 1)
            children.children('span[id^=removeSection]').hide();

        if (sectionsCount == 1) {
            layoutRow.attr("isEmpty", "true");
            layoutRow.children('div[id^=layoutRowContent]').hide().ToggleValidators(true);
            layoutRow.ReinitializeConditionalRules();

            var repetitionCommands = layoutRow.children('div[id^=repetitionCommands]');
            repetitionCommands.children('span[id^=addSection]').show();
            layoutRow.click();
            return repetitionCommands.children('span[id^=removeSection]').hide();
        }

        children.show();
        layoutRow.remove();
        layoutRowPrevious.ReinitializeConditionalRules();

        if ((sectionsCount - 1) == minRepetition) {
            children.children('span[id^=removeSection]').hide();
        }
    }
}

function compareByTabIndex(a, b) {
    var aTabIndex = isNaN($(a).attr('tabindex')) ? Number.POSITIVE_INFINITY : Number($(a).attr('tabindex'));
    var bTabIndex = isNaN($(b).attr('tabindex')) ? Number.POSITIVE_INFINITY : Number($(b).attr('tabindex'));

    if (aTabIndex < bTabIndex)
        return -1;
    if (aTabIndex > bTabIndex)
        return 1;
    return 0;
}

function UpAllTabIndex(up) {
    var focusables = $("input[ID], select, textarea, a, area, button, object");
    var jump = 0;

    focusables.sort(compareByTabIndex);

    focusables.each(function () {
        if ($(this).attr('tabindex') != undefined) {
            var newTabIndex = Number($(this).attr('tabindex')) + jump;
            $(this).attr('tabindex', newTabIndex);
            jump += up;
        }
    });
}

function ShringTabIndexRange() {
    var focusables = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton");
    var jump = 0;

    focusables.sort(compareByTabIndex);

    for (var i = 0; i < focusables.length; i++) {
        $(focusables[i]).attr('tabIndex', i + 1);
    }
}

function InitTabIndexes() {
    if ($('.addRemoveSection, .lookupbutton, .infoIcon, .closeButton').length != $('span[tabindex]').length) {
        var previousTabIndex = 0;
        var jump = 0;
        var focusables = $("input[ID], select, textarea, a, area, button, object");
        var allFocusables = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton");

        // Pomocna uprava tabIndexov
        UpAllTabIndex(100);

        focusables.sort(compareByTabIndex);

        focusables.each(function () {
            if ($(this).attr('tabindex') != undefined) {
                if ($(this).hasClass('remoteLookup')) {
                    var newTabIndex = Number($(this).attr('tabindex')) + jump;
                    $(this).attr('tabindex', newTabIndex);
                    $(this).siblings('.lookupbutton').attr('tabindex', newTabIndex + 1);
                    jump++;
                }
                else {
                    $(this).attr('tabindex', Number($(this).attr('tabindex')) + jump);
                }
            }
        });

        jump = 0;

        allFocusables.each(function (i) {
            var tabIndex = $(this).attr('tabindex');
            if ($(this).attr('id') == 'titulItemName')
                var pom;

            if (tabIndex == undefined) {
                previousTabIndex++;
                $(this).attr('tabindex', previousTabIndex);
                jump++;
            }
            else {
                previousTabIndex = Number(tabIndex) + jump;
                $(this).attr('tabindex', previousTabIndex);
            }
        });

        // Pomocna uprava tabIndexov
        ShringTabIndexRange();
    }

    $('.addRemoveSection, .lookupbutton, .infoIcon, .ui-dialog-content, .closeButton').live('keydown', function (data) {
        if (data.which == 13 || data.which == 32) {
            var focusables = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton");
            var current = focusables.index(this);
            var next;

            if ($(this).hasClass('infoIcon')) {
                $(this).delay(100).queue(function (next) {
                    $(this).mouseover().mousedown();
                    var closeButton = $('.ui-dialog-titlebar-close:visible');
                    closeButton.focusin();
                    next();
                });
            }
            else {
                var contentLayotRow = $(this).closest('[id^=layoutRow]').find('[id^=layoutRowContentlayoutRow]');
                var isFirstHiddenSection = this.id.indexOf('addSectionlayoutRow') != -1 && !contentLayotRow.is(':visible');
                this.click();

                if (this.id.indexOf('addSectionlayoutRow') != -1) {
                    focusables = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton");
                    current = focusables.index(this);

                    if (isFirstHiddenSection)
                        current -= contentLayotRow.find("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").length;

                    while (current < focusables.length && focusables.eq(current + 1).length && (!focusables.eq(current).is(':visible') || focusables.eq(current).is('span'))) {
                        current++;
                    }

                    next = focusables.eq(current).length ? focusables.eq(current) : focusables.eq(0);
                    next.focus();
                }
                else if (this.id.indexOf('removeSectionlayoutRow') != -1 || $(this).hasClass('closeButton')) {
                    while (current > 0 && focusables.eq(current - 1).length && (!focusables.eq(current).is(':visible') || focusables.eq(current).is('span'))) {
                        current--;
                    }

                    next = focusables.eq(current).length ? focusables.eq(current) : focusables.eq(0);
                    next.focus();
                }
            }
        }
    });
}

function InitPickers() {
    ReadOnlyPickers();
    InitDatePickerValues();
    InitDatePickerDateFormat();
    InitDatePickerAutoCorrectSKDateFormat();
    InitDateTimePicker();
    InitDateTimeWithSecondsPicker();
    InitTimePickerValues();
    InitDateRangePicker();
}

function ReindexElements() {
    var repetitionSections = new Array();
    var attributeName = "ID";
    $("div[id^=repetitionCommandslayoutRow]").each(function () {
        var layoutRow = $(this);
        var value = layoutRow.attr(attributeName);
        var indexOf = value.indexOf(repeatingPostfix);
        if (indexOf != -1) {
            value = value.substring(0, indexOf);
            layoutRow.attr(attributeName, value);
        }
        if ($.inArray(value, repetitionSections) == -1) {
            repetitionSections.push(value);
        }
    });

    for (var i = 0; i < repetitionSections.length; i++) {
        var sections = $("div[id^=" + repetitionSections[i].replace('repetitionCommands', '') + "]");
        if (sections.length > 1) {
            for (var j = 1; j < sections.length; j++) {
                var layoutRow = sections.eq(j);
                layoutRow.IncrementFieldIds();
            }
        }
    }
}

function ResizeTextareaField() {  // readOnly mode
    $("textarea[disabled]").each(function () {
        var textArea = $(this);
        textArea.attr('rows', (Math.round(textArea[0].scrollHeight / 15)));
    });
}

function CleanRepetitionButtons() {
    $('div[id^=repetitionCommandslayoutRow]').each(function () {
        var repetitionSection = $(this);
        if (repetitionSection[0].lastChild != null) {
            var parentRepetitionSection = repetitionSection.parent();
            var id = getOriginalId(parentRepetitionSection[0].id, '_');
            var addButton = repetitionSection.find('[id=addSection' + id + ']');
            if (addButton.length > 0) {
                var removeButton = repetitionSection.find('[id=removeSection' + id + ']');
                var string = addButton.attr('onclick').toString();
                var array = string.substring(string.lastIndexOf("(") + 1, string.lastIndexOf(", this")).split(',');
                var minRepetition = array[0];
                var maxRepetition = array[1];

                if (minRepetition == 0 && maxRepetition == 1) {
                    var hasVal = false;
                    parentRepetitionSection.find('input,select,textarea').each(function () {
                        var element = $(this);
                        var value = element.val();
                        if (value && element[0].type != 'radio')
                            hasVal = true;
                    });

                    if (hasVal) {
                        addButton.hide();
                        removeButton.show();
                    }

                } else {
                    var sectionsCount = countSection(addButton, 'addSection');
                    if (sectionsCount == maxRepetition) {
                        addButton.hide();
                        removeButton.show();
                    }

                    if (sectionsCount == minRepetition) {
                        addButton.show();
                        removeButton.hide();
                    }

                    if (sectionsCount > 0 && minRepetition == 0) {
                        removeButton.show();
                    }
                }
            }
        }
    });
}

function LayoutTempRepetitonSection() {
    $('div[adjustposition^=true]').each(Layout);
}

function InitDebugCode() {
    var ignoreClientErrors = $.GetUrlParam("ignoreClientErrors");
    if (ignoreClientErrors != 0)
        validatorObject.settings.ignoreClientErrors = true;
}

function InitExistingForm() {
    $("form :radio:checked").click();
}

function ReadOnlyPickers() {
    $(".datepicker[readonly='readonly'],.datepickerISO[readonly='readonly']").datepicker({ minDate: -1, maxDate: -2 });
    $(".timepicker[readonly='readonly']").timepicker({ hourMin: 0, hourMax: 0, minuteMin: 0, minuteMax: 0 });
    $(".datetimepicker[readonly='readonly']").datetimepicker({ minDate: -1, maxDate: -2, hourMin: 0, hourMax: 0, minuteMin: 0, minuteMax: 0 });
}

function InitDatePickerValues() {
    switch (GetFormLanguage()) {
        case 'en':
            // En is default
            break;

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

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

function InitTimePickerValues() {
    switch (GetFormLanguage()) {
        case 'en': // En is default
            $(".timepicker").timepicker({
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });
            break;

        default: // sk a default
            $(".timepicker").timepicker({
                timeOnlyTitle: 'Vyberte čas',
                timeText: 'Čas',
                hourText: 'Hodina',
                minuteText: 'Мinúta',
                secondText: 'Sekunda',
                currentText: 'Aktuálny',
                closeText: 'Vybrať',
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });
    };

    $('.timepicker').live('keypress', function (e) {
        var newVal = $(this).val() + (e.which !== 0 ? String.fromCharCode(e.which) : '')
        var charPattern = /^[0-9]?$|^\:?$/;

        if (e.which != 8 && !e.ctrlKey && !charPattern.test(String.fromCharCode(e.which)) && newVal.length > $(this).val().length)
            e.preventDefault();
    });
}

// Potrebne pre DateRangePicker
$.datepicker._defaults.onAfterUpdate = null;

var datepicker__updateDatepicker = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function (inst) {
    datepicker__updateDatepicker.call(this, inst);

    var onAfterUpdate = this._get(inst, 'onAfterUpdate');

    if (onAfterUpdate)
        onAfterUpdate.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]);
}
// ----

function InitDateRangePicker() {
    $(function () {
        var cur = new Array();
        var prv = new Array();
        var list = $('.daterangepickerdiv');
        var count = list.length;
        var numberOfMonthsVals = new Array();

        for (var i = 0; i < count; i++) {
            var dRPInput;

            if (list[i]) {
                var searchDiv = list[i].parentNode;
                dRPInput = $(searchDiv).find("input[ID]");
            }

            if (dRPInput[0].value != '') {
                var v = dRPInput[0].value;
                var d;

                try {
                    if (v.indexOf(' - ') != -1) {
                        d = v.split(' - ');
                        prv.push($.datepicker.parseDate('dd.mm.yy', d[0]).getTime());
                        cur.push($.datepicker.parseDate('dd.mm.yy', d[1]).getTime());
                    } else if (v.length > 0) {
                        var time = $.datepicker.parseDate('dd.mm.yy', v).getTime();
                        prv.push(time);
                        cur.push(time);
                    }
                } catch (e) {
                    cur.push(-1);
                    prv.push(-1);
                }
            }
            else {
                cur.push(-1);
                prv.push(-1);
            }

            numberOfMonthsVals.push(1);
        }

        function arrayObjectIndexOf(myArray, searchObject) {
            for (var i = 0; i < myArray.length; i++) {
                if (myArray[i] === searchObject)
                    return i;
            }
            return -1;
        }

        switch (GetFormLanguage()) {
            case 'en': // En is default
                $('.daterangepickerdiv')
                  .datepicker({
                      weekHeader: 'Ty',
                      dateFormat: 'dd.mm.yy',
                      firstDay: 1,
                      isRTL: false,
                      showMonthAfterYear: false,
                      yearSuffix: '',
                      changeMonth: true,
                      changeYear: true,
                      yearRange: "-100:+100",
                      showButtonPanel: true,

                      beforeShowDay: function (date) {
                          var index = arrayObjectIndexOf(list, this);

                          return [true, ((date.getTime() >= Math.min(prv[index], cur[index]) && date.getTime() <= Math.max(prv[index], cur[index])) ? 'date-range-selected' : '')];
                      },

                      onSelect: function (dateText, inst) {
                          var d1, d2;
                          var dRPInput;
                          var index = arrayObjectIndexOf(list, this);

                          if (this) {
                              var searchDiv = this.parentNode;
                              dRPInput = $(searchDiv).find("input[ID]");
                          }

                          if (dRPInput) {
                              prv[index] = cur[index];
                              cur[index] = (new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)).getTime();

                              if (prv[index] == -1 || prv[index] == cur) {
                                  prv[index] = cur[index];
                                  $(dRPInput).val(dateText);
                              }
                              else {
                                  d1 = $.datepicker.formatDate('dd.mm.yy', new Date(Math.min(prv[index], cur[index])), {});
                                  d2 = $.datepicker.formatDate('dd.mm.yy', new Date(Math.max(prv[index], cur[index])), {});
                                  $(dRPInput).val(d1 + ' - ' + d2);
                              }
                          }
                      },

                      onChangeMonthYear: function (year, month, inst) {
                          // Reset date on month or year change
                          /*var index = arrayObjectIndexOf(list, this);
                              
                          cur[index] = prv[index] = -1;*/
                      },

                      onAfterUpdate: function () {
                          var thisDRPDir = this;

                          $('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Select</button>')
                                 .appendTo($('.ui-datepicker-buttonpane'))
                                 .on('click', function () {
                                     var dRPInput;

                                     if (thisDRPDir) {
                                         var searchDiv = thisDRPDir.parentNode;
                                         dRPInput = $(searchDiv).find("input[ID]");
                                     }

                                     if (dRPInput[0].value == '') {
                                         var index = arrayObjectIndexOf(list, thisDRPDir);

                                         cur[index] = prv[index] = -1;
                                     }

                                     $(thisDRPDir).hide();
                                     dRPInput.focusout();
                                 });

                          $('<button type="button" class="ui-state-default ui-corner-all" data-event="click">Clear</button>')
                                 .appendTo($('.ui-datepicker-buttonpane'))
                                 .on('click', function () {
                                     var index = arrayObjectIndexOf(list, thisDRPDir);
                                     var dRPInput;

                                     if (thisDRPDir) {
                                         var searchDiv = thisDRPDir.parentNode;
                                         dRPInput = $(searchDiv).find("input[ID]");
                                     }

                                     if (dRPInput) {
                                         dRPInput[0].value = '';
                                         cur[index] = prv[index] = -1;
                                         $(thisDRPDir).datepicker("refresh");
                                     }
                                 });

                          $('<button type="button" class="ui-state-default ui-corner-all" data-event="click">></button>')
                              .appendTo($('.ui-datepicker-buttonpane'))
                              .on('click', function () {
                                  var index = arrayObjectIndexOf(list, thisDRPDir);

                                  if (numberOfMonthsVals[index] < 6) {
                                      numberOfMonthsVals[index] = numberOfMonthsVals[index] + 1;
                                  }
                                  var object = $(thisDRPDir);
                                  if (numberOfMonthsVals[index] < 5)
                                      object.datepicker("option", "numberOfMonths", [1, numberOfMonthsVals[index]]);
                                  else
                                      object.datepicker("option", "numberOfMonths", [numberOfMonthsVals[index] - 3, 4]);
                              });

                          $('<button type="button" class="ui-state-default ui-corner-all" data-event="click"><</button>')
                                 .appendTo($('.ui-datepicker-buttonpane'))
                                 .on('click', function () {
                                     var index = arrayObjectIndexOf(list, thisDRPDir);

                                     if (numberOfMonthsVals[index] > 1) {
                                         numberOfMonthsVals[index] = numberOfMonthsVals[index] - 1;
                                     }
                                     var object = $(thisDRPDir);
                                     if (numberOfMonthsVals[index] < 5)
                                         object.datepicker("option", "numberOfMonths", [1, numberOfMonthsVals[index]]);
                                     else
                                         object.datepicker("option", "numberOfMonths", [numberOfMonthsVals[index] - 3, 4]);
                                 });

                          $(document).on('click', function (e) {
                              var dRPInput;

                              if (thisDRPDir) {
                                  var searchDiv = thisDRPDir.parentNode;
                                  dRPInput = $(searchDiv).find("input[ID]");
                              }

                              function isDescendantOrUiDP(parent, child) {
                                  var node = child.parentNode;

                                  while (node != null) {
                                      try {
                                          if (node == parent || node.className.indexOf('ui-datepicker') != -1) {
                                              return true;
                                          }
                                      }
                                      catch (e) {
                                          return false;
                                      }
                                      node = node.parentNode;
                                  }
                                  return false;
                              }

                              if (e.target.id != dRPInput[0].id && !isDescendantOrUiDP(thisDRPDir, e.target)) {
                                  if (dRPInput[0].value == '') {
                                      var index = arrayObjectIndexOf(list, thisDRPDir);

                                      cur[index] = prv[index] = -1;
                                  }

                                  $(thisDRPDir).hide();
                                  dRPInput.focusout();
                              }
                          });
                          $(this).css({ position: 'absolute', zIndex: 1 });
                      }
                  }).hide();

                break;

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

                                  beforeShowDay: function (date) {
                                      var index = arrayObjectIndexOf(list, this);

                                      return [true, ((date.getTime() >= Math.min(prv[index], cur[index]) && date.getTime() <= Math.max(prv[index], cur[index])) ? 'date-range-selected' : '')];
                                  },

                                  onSelect: function (dateText, inst) {
                                      var d1, d2;
                                      var dRPInput;
                                      var index = arrayObjectIndexOf(list, this);

                                      if (this) {
                                          var searchDiv = this.parentNode;
                                          dRPInput = $(searchDiv).find("input[ID]");
                                      }

                                      if (dRPInput) {
                                          prv[index] = cur[index];
                                          cur[index] = (new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)).getTime();

                                          if (prv[index] == -1 || prv[index] == cur) {
                                              prv[index] = cur[index];
                                              $(dRPInput).val(dateText);
                                          }
                                          else {
                                              d1 = $.datepicker.formatDate('dd.mm.yy', new Date(Math.min(prv[index], cur[index])), {});
                                              d2 = $.datepicker.formatDate('dd.mm.yy', new Date(Math.max(prv[index], cur[index])), {});
                                              $(dRPInput).val(d1 + ' - ' + d2);
                                          }
                                      }
                                  },

                                  onChangeMonthYear: function (year, month, inst) {
                                      // Reset date on month or year change
                                      /*var index = arrayObjectIndexOf(list, this);
                                          
                                      cur[index] = prv[index] = -1;*/
                                  },

                                  onAfterUpdate: function () {
                                      var thisDRPDir = this;

                                      $('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Vybrať</button>')
                                             .appendTo($('.ui-datepicker-buttonpane'))
                                             .on('click', function () {
                                                 var dRPInput;

                                                 if (thisDRPDir) {
                                                     var searchDiv = thisDRPDir.parentNode;
                                                     dRPInput = $(searchDiv).find("input[ID]");
                                                 }

                                                 if (dRPInput[0].value == '') {
                                                     var index = arrayObjectIndexOf(list, thisDRPDir);

                                                     cur[index] = prv[index] = -1;
                                                 }

                                                 $(thisDRPDir).hide();
                                                 dRPInput.focusout();
                                             });

                                      $('<button type="button" class="ui-state-default ui-corner-all" data-event="click">Vymaž</button>')
                                             .appendTo($('.ui-datepicker-buttonpane'))
                                             .on('click', function () {
                                                 var index = arrayObjectIndexOf(list, thisDRPDir);
                                                 var dRPInput;

                                                 if (thisDRPDir) {
                                                     var searchDiv = thisDRPDir.parentNode;
                                                     dRPInput = $(searchDiv).find("input[ID]");
                                                 }

                                                 if (dRPInput) {
                                                     dRPInput[0].value = '';
                                                     cur[index] = prv[index] = -1;
                                                     $(thisDRPDir).datepicker("refresh");
                                                 }
                                             });

                                      $('<button type="button" class="ui-state-default ui-corner-all" data-event="click">></button>')
                                          .appendTo($('.ui-datepicker-buttonpane'))
                                          .on('click', function () {
                                              var index = arrayObjectIndexOf(list, thisDRPDir);

                                              if (numberOfMonthsVals[index] < 6) {
                                                  numberOfMonthsVals[index] = numberOfMonthsVals[index] + 1;
                                              }
                                              var object = $(thisDRPDir);
                                              if (numberOfMonthsVals[index] < 5)
                                                  object.datepicker("option", "numberOfMonths", [1, numberOfMonthsVals[index]]);
                                              else
                                                  object.datepicker("option", "numberOfMonths", [numberOfMonthsVals[index] - 3, 4]);
                                          });

                                      $('<button type="button" class="ui-state-default ui-corner-all" data-event="click"><</button>')
                                             .appendTo($('.ui-datepicker-buttonpane'))
                                             .on('click', function () {
                                                 var index = arrayObjectIndexOf(list, thisDRPDir);

                                                 if (numberOfMonthsVals[index] > 1) {
                                                     numberOfMonthsVals[index] = numberOfMonthsVals[index] - 1;
                                                 }
                                                 var object = $(thisDRPDir);
                                                 if (numberOfMonthsVals[index] < 5)
                                                     object.datepicker("option", "numberOfMonths", [1, numberOfMonthsVals[index]]);
                                                 else
                                                     object.datepicker("option", "numberOfMonths", [numberOfMonthsVals[index] - 3, 4]);
                                             });

                                      $(document).on('click', function (e) {
                                          var dRPInput;

                                          if (thisDRPDir) {
                                              var searchDiv = thisDRPDir.parentNode;
                                              dRPInput = $(searchDiv).find("input[ID]");
                                          }

                                          function isDescendantOrUiDP(parent, child) {
                                              var node = child.parentNode;

                                              while (node != null) {
                                                  try {
                                                      if (node == parent || node.className.indexOf('ui-datepicker') != -1) {
                                                          return true;
                                                      }
                                                  }
                                                  catch (e) {
                                                      return false;
                                                  }
                                                  node = node.parentNode;
                                              }
                                              return false;
                                          }

                                          if (e.target.id != dRPInput[0].id && !isDescendantOrUiDP(thisDRPDir, e.target)) {
                                              if (dRPInput[0].value == '') {
                                                  var index = arrayObjectIndexOf(list, thisDRPDir);

                                                  cur[index] = prv[index] = -1;
                                              }

                                              $(thisDRPDir).hide();
                                              dRPInput.focusout();
                                          }
                                      });
                                      $(this).css({ position: 'absolute', zIndex: 1 });
                                  }
                              }).hide();
        }

        $('.daterangepicker').on('focus', function () {
            var v = this.value;
            var d;
            var index = arrayObjectIndexOf(list, this);

            try {
                if (v.indexOf(' - ') != -1) {
                    d = v.split(' - ');

                    prv[index] = $.datepicker.parseDate('dd.mm.yy', d[0]).getTime();
                    cur[index] = $.datepicker.parseDate('dd.mm.yy', d[1]).getTime();
                }
                else if (v.length > 0) {
                    prv[index] = cur[index] = $.datepicker.parseDate('dd.mm.yy', v).getTime();
                }
            } catch (e) {
                cur[index] = prv[index] = -1;
            }

            var dRPDiv;

            if (this) {
                var searchDiv = this.parentNode;
                dRPDiv = $(searchDiv).find(".daterangepickerdiv");
            }

            if (cur[index] > -1)
                $(dRPDiv).datepicker('setDate', new Date(cur[index]));

            $(dRPDiv).datepicker('refresh').show();
        });
    });
}

function LocalizeErrorMessages() {
    switch (GetFormLanguage()) {
        case 'en':
            // En is default
            break;

        default: // sk a default
            jQuery.extend(jQuery.validator.messages, {
                date: "Zadajte platný dátum.",
                dateISO: "Zadajte platný dátum (ISO)."
            });
    }
}

function InitDatePickerDateFormat() {
    $(".datepicker").datepicker({
        dateFormat: 'dd.mm.yy',
        onSelect: function (dateText, inst) {
            $(this).focusout();
        }
    });
    $(".datepickerISO").datepicker({
        dateFormat: 'yy-mm-dd',
        onSelect: function (dateText, inst) {
            $(this).focusout();
        }
    });
}

function InitDatePickerAutoCorrectSKDateFormat() {
    $(".datepicker").live('change', function () {
        var date = this.value.split('.');

        if (date.length == 3) {
            var day = ('0' + (date[0])).slice(-2);
            var month = ('0' + (date[1])).slice(-2);
            var year = date[2];

            this.value = day + '.' + month + '.' + year;
        }
    });
}

function InitDateTimePicker() {
    switch (GetFormLanguage()) {
        case 'en': // En is default
            $(".datetimepicker").datetimepicker({
                dateFormat: 'dd.mm.yy',
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });
            break;

        default: // sk a default
            $(".datetimepicker").datetimepicker({
                dateFormat: 'dd.mm.yy',
                timeOnlyTitle: 'Vyber dátum',
                timeText: 'Čas',
                hourText: 'Hodina',
                minuteText: 'Мinúta',
                secondText: 'Sekunda',
                currentText: 'Aktuálny',
                closeText: 'Vybrať',
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });

            $(".datetimepicker").each(function () {
                if (this.value != '') {
                    var re = /^\d{1,2}\.\d{1,2}\.\d{4}\s\d{1,2}:\d{1,2}:\d{1,2}$/;

                    if (re.test(this.value))
                        this.value = this.value.substr(0, this.value.length - 3);
                }
            });
    }
}

function InitDateTimeWithSecondsPicker() {
    switch (GetFormLanguage()) {
        case 'en': // En is default
            $(".datetimewithsecondspicker").datetimepicker({
                dateFormat: 'dd.mm.yy',
                showSecond: true,
                timeFormat: 'HH:mm:ss',
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });
            break;

        default: // sk a default
            $(".datetimewithsecondspicker").datetimepicker({
                dateFormat: 'dd.mm.yy',
                showSecond: true,
                timeFormat: 'HH:mm:ss',
                timeOnlyTitle: 'Vyber dátum',
                timeText: 'Čas',
                hourText: 'Hodina',
                minuteText: 'Мinúta',
                secondText: 'Sekunda',
                currentText: 'Aktuálny',
                closeText: 'Vybrať',
                onClose: function (dateText, inst) {
                    $(this).focusout();
                }
            });

            $(".datetimewithsecondspicker").each(function () {
                if (this.value != '') {
                    var re = /^\d{1,2}\.\d{1,2}\.\d{4}\s\d{1,2}:\d{1,2}$/;               
                    
                    if (re.test(this.value))
                        this.value = this.value + ':00'
                }
            });
    }
}

function InitSectionAccordion() {
    $("form").InitSectionAccordion();
}

function InitRadio() {
    $("input[type='radio'][checked]").each(function() {
        var radio = $(this);
        if (radio.attr("disabled") !== undefined || radio.attr("readonly") !== undefined) {
            radio.attr("checked", "true");
        }

        radio.click();
    });
}

function InitButtons() {
    $(".button").button();
    $("#cancelForm").click(TryRedirectToReturnUrl);
}

function InitPopUpDialog() {
    $("form").InitPopUpDialog();
}

var oTable;

function fnGetSelected(oTableLocal) {
    var aReturn = new Array();
    var aTrs = oTableLocal.fnGetNodes();

    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).hasClass('row_selected')) {
            aReturn.push(aTrs[i]);
        }
    }
    return aReturn;
}

function InitDataTablePlugIn() {
    $.fn.dataTableExt.oApi.fnFilterOnReturn = function (oSettings) {
        var that = this;

        this.each(function (i) {
            $.fn.dataTableExt.iApiIndex = i;
            var anControl = $('input', that.fnSettings().aanFeatures.f);
            anControl.unbind('keyup').bind('keypress', function (e) {
                if (e.which == 13) {
                    $.fn.dataTableExt.iApiIndex = i;
                    that.fnFilter(anControl.val());
                }
            });
            return this;
        });
        return this;
    };
}

function initRepetitionSection(minRepetition, maxRepetition, sender) {
    var targetLayoutRow = $('div[id^=' + sender + ']');
    if (minRepetition == 1) {
        var repetitiveCommands = targetLayoutRow.children('div[id^=repetitionCommands]');
        repetitiveCommands.children('span[id^=removeSection]').hide();
    }
    if (minRepetition > 1) {
        for (var i = 0; i < minRepetition; i++) {
            var addButton = targetLayoutRow.last().find('#addSection' + sender);
            addSection(minRepetition, maxRepetition, addButton);
        }
    }
    else if (minRepetition == 0 && ((projectType == "NEV" && targetLayoutRow.attr("isempty") != "false") || projectType != "NEV")) {
        if (targetLayoutRow.length == 1) {
            var removeButton = targetLayoutRow.find('#removeSection' + sender);
            removeSection(minRepetition, removeButton);
        }
    }
}

function parseId(sender, replaceText) {
    var id = sender.id;
    if (id == null) {
        id = sender[0].id;
    }
    return id.replace(replaceText, '');
}

function countSection(sender, replaceText) {
    if ($(sender).hasClass("closeButton") == true) {
        var layoutRow = $(sender).closest('div[id^=layoutRow]');
        var layoutRowId = layoutRow.attr("ID").split('_')[0];
        return layoutRow.parent().children().filter('div[id^=' + layoutRowId + ']').length;
    } else {
        return $(sender).parent().parent().parent().children().filter('div[id^=' + parseId(sender, replaceText) + ']').length;
    }
}

function RemoveDateRangePicker() {
    var dRPickerDivs = $(document).find(".daterangepickerdiv");
    var count = dRPickerDivs.length;
    // Odstranenie vsetkych potomkov vsetkym daterangepickerdivom
    for (var i = 0; i < count; i++) {
        if (dRPickerDivs[i]) {
            while (dRPickerDivs[i].firstChild && dRPickerDivs[i].children.length > 0) {
                dRPickerDivs[i].removeChild(dRPickerDivs[i].firstChild);
            }
        }
    }
    // Samotne odstranenie classy
    dRPickerDivs.removeClass("hasDatepicker");
}

function ReinitTabIndexIncrement(layoutRow) {
    var allLayoutRowElements = $(layoutRow).find("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").sort(compareByTabIndex);
    var allPreviousLayoutRowElements = $(layoutRow).prev("[id^='" + $(layoutRow).attr('id') + "']").find("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").sort(compareByTabIndex);

    if (allLayoutRowElements[0] && allLayoutRowElements[0].tabIndex && allPreviousLayoutRowElements[0] && allPreviousLayoutRowElements[0].tabIndex) {
        var allElements = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").sort(compareByTabIndex);

        if (allElements) {
            var incrementRange = allLayoutRowElements[allLayoutRowElements.length - 1].tabIndex - allLayoutRowElements[0].tabIndex + 1;
            var incrementSubRepeatingRange = allPreviousLayoutRowElements[allPreviousLayoutRowElements.length - 1].tabIndex - allLayoutRowElements[allLayoutRowElements.length - 1].tabIndex;

            $(allElements).each(function () {
                if (this.tabIndex > allPreviousLayoutRowElements[allPreviousLayoutRowElements.length - 1].tabIndex)
                    this.tabIndex = this.tabIndex + incrementRange;
            });

            $(allLayoutRowElements).each(function () {
                this.tabIndex = this.tabIndex + incrementSubRepeatingRange + incrementRange;
            });
        }
    }
}

function ReinitTabIndexDecrement(layoutRow) {
    var allLayoutRowElements = $(layoutRow).find("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").sort(compareByTabIndex);

    if (allLayoutRowElements[0] && allLayoutRowElements[0].tabIndex) {
        var allElements = $("input[ID], select, textarea, a, area, button, object, .addRemoveSection, .lookupbutton, .infoIcon, .closeButton").sort(compareByTabIndex);

        if (allElements) {
            var incrementRange = allLayoutRowElements[allLayoutRowElements.length - 1].tabIndex - allLayoutRowElements[0].tabIndex + 1;

            $(allElements).each(function () {
                if (this.tabIndex > allLayoutRowElements[allLayoutRowElements.length - 1].tabIndex)
                    this.tabIndex = this.tabIndex - incrementRange;
            });
        }
    }
}

function addSection(minRepetition, maxRepetition, sender) {
    DeleteMultiCombobox();
    // Potrebne odstranit daterangepicker este pred clone
    RemoveDateRangePicker();
    var layoutRow = $(sender).closest('div[id^=layoutRow]');
    var firstLayoutRow = GetRepeatingSections(layoutRow).first();
    var layoutRowCopy = firstLayoutRow.clone();

    if (firstLayoutRow.attr("isempty") == "true") {
        layoutRowCopy.removeAttr("isempty");
        layoutRowCopy.children("#layoutRowContent" + firstLayoutRow.attr("id")).show();
    }

    if (typeof vucAddSection == 'function') { // we are loaded in VUC configuration (function in p_vuc.js)
		vucAddSection(layoutRowCopy);
	}
    var sectionsCount = countSection(sender, 'addSection');
    var isSectionListEmpty = layoutRow.attr('isEmpty');
    var sectionCountForX = countSection(sender, "");

    if (sectionsCount == 1 && isSectionListEmpty == 'true')
        sectionsCount = 0;

    if (sectionsCount >= maxRepetition)
        return alert('Dosiahli ste maximálny počet opakovania zvolenej sekcie.');

    if (sectionsCount == 0) {
        layoutRow.attr("isEmpty", "false");
        layoutRow.children('div[id^=layoutRowContent]').show().ToggleValidators(false); //bug by "style" atribute
        layoutRow.children('div[id^=repetitionCommands]').children('span[id^=removeSection]').show(); //IE bug by "Odobrať" button 
        layoutRow.find('input[type="radio"]:checked').each(function () {
            $(this).click();
        });
        $(layoutRow).children('div[id^=repetitionNumberinglayoutRow]').show();
        layoutRow.IncrementFieldIds();
    }
    else {
        layoutRowCopy.ClearFormElements()
            .ResetRepetitionSection()
            .InitSectionAccordion()
            .RemoveDatePickerClass()
            .DeleteAutocompletes()
            .InitRemoteCombobox()
            .InitCombobox()
            .InitRadioButonList()
            .InitRemoteRadioButonList()
            .InitRemoteCheckBoxList()
            .InitPopUpDialog()
            .InitHelp()
            .InitHierarchicallyTree();
        layoutRowCopy.ToggleValidators(false);
        layoutRowCopy.IncrementLayoutrowCopyFieldIds();
        layoutRow.after(layoutRowCopy);
        layoutRowCopy.IncrementFieldIds();
        layoutRowCopy.InitAutocompletes();
        ReinitTabIndexIncrement(layoutRowCopy);
    }

    InitPickers();
    InitMultiCombobox();
    IncrementDecrementSectionId(layoutRowCopy, minRepetition);
    InitRepetitionNumbering(layoutRowCopy);
    ChangeRepetitionNumbering(layoutRow);

    //Ak pridavana sekcia je poslena mozna (maxrepetition) skryjem je button Pridaj
    var repetitiveCommands = layoutRowCopy.children('div[id^=repetitionCommands]');
    var addButton = repetitiveCommands.children('span[id^=addSection]');
    var removeButton = repetitiveCommands.children('span[id^=removeSection]');
    if ((sectionsCount + 1) == maxRepetition) {
        if (minRepetition == 0 && maxRepetition == 1) {
            layoutRow.children('div[id^=repetitionCommands]').children('span[id^=addSection]').hide();
        } else {
            addButton.hide();
        }
    }

    if (sectionsCount > 0) {
        //Na pridanej sekcii zobrazim button Odober

        removeButton.show();
        //Na predchadzajucej sekcii skryjem command bar
        layoutRow.children('div[id^=repetitionCommands]').hide();
    }

    if ((sectionsCount + 1) == minRepetition)
        removeButton.hide();

    InitRepetitionSections(layoutRowCopy);
    layoutRowCopy.ReinitializeConditionalRules().ReinitRadioDefaultCheck();
    HideShowX(layoutRow, sectionCountForX + minRepetition, -1);
    InitXInCopySection(layoutRowCopy);
    DefaultDataProvider.SetDefaultValues(layoutRowCopy);
}

function removeSection(minRepetition, sender) {
    var layoutRow = $(sender).closest('div[id^=layoutRow]');
    var sectionsCount = countSection(sender, 'removeSection');
    var sectionCountForX = countSection(sender, "");
    var layoutRowIdClean = GetValueWithoutIncremental(layoutRow.attr("id"));
    var layoutRowsLocalGroup = layoutRow.siblings("div[id^='" + layoutRowIdClean + "']");
    var layoutRowPrevious = layoutRowsLocalGroup.last();

    if (sectionsCount == minRepetition)
        return alert('Sekciu nie je možné odobrať.');

    var children = layoutRowPrevious.children('div[id^=repetitionCommands]');
    if (sectionsCount == minRepetition && sectionsCount > 1)
        children.children('span[id^=removeSection]').hide();

    if (sectionsCount == 1) {
        layoutRow.attr("isEmpty", "true");
        layoutRow.children('div[id^=layoutRowContent]').hide().ToggleValidators(true);
        layoutRow.children('div[id^=repetitionNumberinglayoutRow]').hide();

        var repetitionCommands = layoutRow.children('div[id^=repetitionCommands]');
        repetitionCommands.children('span[id^=addSection]').show();
        return repetitionCommands.children('span[id^=removeSection]').hide();
    }

    ReinitTabIndexDecrement(layoutRow);
    children.show();

    if ($(sender).hasClass("closeButton") || (sectionsCount - 1) == 1) {
        if (!$(sender).hasClass("closeButton")) { sectionCountForX = sectionsCount - 1; }
        HideShowX(layoutRow, sectionCountForX - 1, minRepetition);
    }

    if ($(sender).hasClass("closeButton")) {
        HideAndShowRemoveBtns(layoutRow.siblings("div[id^='" + layoutRowIdClean + "']"), sectionCountForX - 1, minRepetition);
    }

    layoutRow.remove();

    if ((sectionsCount - 1) == minRepetition) {
        children.children('span[id^=removeSection]').hide();
    }
    children.children('span[id^=addSection]').show();
    
    if (layoutRowPrevious[0]) {
        // Musi byt pred reindexaciou sekcii
        RemoveRepSecClass(layoutRowPrevious);
        $(layoutRowPrevious).IncrementFieldIds();
        IncrementDecrementSectionId(layoutRowPrevious, minRepetition);
        IncrementDecrementInnerRepeatingIds(layoutRowPrevious);
        ChangeRepetitionNumbering(layoutRowPrevious);
    }

    var layoutRowAll = $("[id^='" + layoutRowIdClean + "']"); // vyber opakovacky

    $(layoutRowAll).each(function () {
        $(this).RemoveDatePickerClass();// resetne datepicker sekcie ktoru mazeme 
    });

    InitPickers(); // opetovna inicializacia 
}

function RemoveRepSecClass(sender) {
    var layoutRowIdClean = GetValueWithoutIncremental($(sender).attr("id"));
    var lr = $(document).find("div[id^='" + layoutRowIdClean + "']:first");

    lr.removeClass("repeatingSection");

    lr.find(".repeatingSection").each(function () {
        $(this).removeClass("repeatingSection");
    });
}

function HideShowX(sender, sectionCount, minRepetition) {
    var layoutRowIdClean = sender.attr("id").split('_')[0];
    var layoutRows = sender.parent().children("div[id^='" + layoutRowIdClean + "']");
    var layoutRowsCount = layoutRows.length;

    if ((layoutRowsCount - 1) == 1 && minRepetition != -1) {
        var lr = $(sender).children('div[id^=layoutRow]');
        layoutRows.children('.closeButton').hide();
    } else if (layoutRowsCount > 1)
        layoutRows.each(function () {
            $(this).children('.closeButton').show();
        });
}

function HideAndShowRemoveBtns(layoutRows, sectionCount, minRepetition) {
    if (minRepetition != -1) {
        var count = 0;
        layoutRows.each(function () {
            if (count != layoutRows.length - 1)
                $(this).children('div[id^=repetitionCommands]').hide();
            else {
                if ((layoutRows.length) == minRepetition) {
                    $(this).children('div[id^=repetitionCommands]').children('span[id^=removeSection]').hide();
                } else {
                    $(this).children('div[id^=repetitionCommands]').show();
                    $(this).children('div[id^=repetitionCommands]').children('span[id^=addSection]').show();
                }
            }
            count++;
        });
    }
}

function InitXInCopySection(sender) {
    var subSection = $(sender).children("[id^='layoutRowContentlayoutRow']");
    subSection.find('.closeButton').each(function () {
        $(this).hide();
    });
}

$.fn.NewGuid = function () {
    function p8(s) {
        var p = (Math.random().toString(16) + "000000000").substr(2, 8);
        return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
    }
    return p8() + p8(true) + p8(true) + p8();
};

function SwitchSections(switchesToSections, context, isCheckBoxList) {
    if (typeof context === "object")
        throw "kontext nemôže byť objekt";

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

    for (var singleSwitch in switchesToSections) {
        for (var i = 0; i < switchesToSections[singleSwitch].length; i++) {
            if (switchesToSections[singleSwitch][i] != '' && switchesToSections[singleSwitch][i].indexOf('^=') == -1)
                switchesToSections[singleSwitch][i] = '[id^=' + switchesToSections[singleSwitch][i].replace('#', '') + ']';
        }
    }

    if (context[0] === "undefined")
        throw "neznámy kontext";

    if (isCheckBoxList == true)
        context.HideSwitchSections(switchesToSections);

    context.SwitchSections(switchesToSections, isCheckBoxList);
}

function FindValueInXml(elementName, xmlDoc) {
    var $xml = $(xmlDoc);
    var $xmlValue = $xml.find(elementName);
    return $xmlValue.text();
}

function WriteProtection(element) {
    if (element.which != 8 && element.which != 9 && element.which != 37 && element.which != 39 && element.which != 46 && !element.ctrlKey)
        element.preventDefault();
}

function MaxLengthRestriction(element, maxLength, data) {
    var newVal = $(element).val() + (data.charCode !== 0 ? String.fromCharCode(data.charCode) : '');
	
    if (data.which != 8 && data.which != 0 && (document.activeElement.selectionStart) == (document.activeElement.selectionEnd) && newVal.length > maxLength)
	    data.preventDefault();
}

function MaxLengthOnPateRestriction(element, maxLength) {
    var newVal = $(element).val().substr(0, maxLength);

    $(element).val(newVal).focusout();
}

// WCF  Validation Service       

function AddValidationMessage(index, item, valMsg) {
    var input = $(item);
    var key = input.attr("key");
    var order = (input.attr("order") == null || input.attr("order") == undefined) ? 0 : input.attr("order");

    //ak sa jedna o xpathy
    if (XPathUsed()) {
        var nativeKey = null;
        $(':input').each(function () {
            var element = $(this);
            switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                case 'checkbox':
                case 'radio':
                    var xPathClass = element.siblings('.XPathClass');
                    if (xPathClass.length > 0) {
                        if (xPathClass[0].innerHTML == key) {
                            nativeKey = element.attr("name");
                            return false;
                        }
                    }
            }
        });

        key = nativeKey;
    }

    if (key != null) {
        var postfix = order == 0 ? "" : "-" + order;
        var keyName = key + postfix;
        if ($("#" + keyName).length == 0) {
            return false;
        }

        if (valMsg[keyName] == undefined)
            valMsg[keyName] = input.text() + '</br>';
    else
            valMsg[keyName] += input.text() + '</br>';

        return true;
    }

    //ak je false, znamena, ze sa nedal najst ziaden input a treba to evidovat ako xslt error
    return false;
}

function TryRedirectToReturnUrl() {
    var returnUrl = $.GetUrlParam("ReturnUrl");

    if (returnUrl != 0)
        self.location.href = unescape(returnUrl);
}

function Layout() {
    var templateSection = $(this);
    var tempSecParent = templateSection.closest("[id^='layoutCell']");

    templateSection.css({ 'margin': '0px', 'padding': '0px', 'border': '0px', 'background': 'none' });
    tempSecParent.css({ 'margin': '-3px 0px' });
}

///////////////////////////////////////// ML /////////////////////////////////////////
///////////////////////////// Funkcia Hodnota pre ML /////////////////////////////////

function HodnotaTypPola(element, nazov) {
    var value = 0;

    var elements;

    if (!element) {
        elements = $('#' + nazov);
        if (!elements || elements.length == 0)
            elements = $("[name='" + nazov + "']");
        element = elements[0];
    }

    if (element.type == 'select-one') {
        value = document.getElementById(nazov).selectedIndex;
    }
    else if (element.type == 'radio') {
        //je radiobutton		
        //je radiobuttonlist
        //kod je univerzalny, zafunguje aj aj
        value = 0;
        for (i = 0; i < elements.length; i++) {
            if (elements[i].checked) {
                value = i + 1; //vrat index oznaceneho pola od 1 - n
                break;
            }
        }
    }
    else if (element.type == 'checkbox') {
        //je checkbox
        if (element.checked) {
            value = 1;
        }
        else {
            value = 0;
        }
    }
    else {
        value = element.value;
    }

    return value;
}

function hodnota(element, nazov, opak_typ, sid, layoutNazov, dataType) { // sid je indexovany od 0..
    var tstr;

    ////////////////////////////////////////////////////////////////////////// zaciatok opakovana
    if (opak_typ == 'o') {
        if (element == null) {
            if (sid == 0 || sid == -1)
                tstr = HodnotaTypPola(null, nazov);  //document.getElementById(nazov).value;
            else
                tstr = HodnotaTypPola(null, GetElementIncrementalValue(nazov, sid)); //document.getElementById(GetIncrementalValue(nazov, sid)).value;
        } else {
            tstr = HodnotaTypPola(element, nazov);
        }
    } else
        ////////////////////////////////////////////////////////////////////////// koniec opakovana
        ////////////////////////////////////////////////////////////////////////// zaciatok strankovana
        if (opak_typ == 's' || opak_typ == 'p') {
            var section = $('#' + layoutNazov).pageableSection();
            if (section && section.currentPage != sid + 1) {
                var temp = section.getValueFor(nazov, sid + 1);
                if (typeof temp === 'boolean') {
                    tstr = temp ? 1 : 0;
                } else {
                    tstr = temp;
                }
            } else {
                tstr = HodnotaTypPola(element, nazov);
            }
        } else
            ////////////////////////////////////////////////////////////////////////// koniec strankovana
            ////////////////////////////////////////////////////////////////////////// zaciatok normalna
            if (opak_typ == 'n') {
                tstr = HodnotaTypPola(element, nazov);
            }
    ////////////////////////////////////////////////////////////////////////// koniec opakovania
    if (tstr == null && dataType == 'x')
        return '';
    if (tstr != null && dataType == 'x')
        return tstr.toString();
    if (tstr == null || tstr === undefined || tstr == '')
        return 0;
    //tstr = 0;

    //ak je datovy typ string, vrat dlzku retazca
    if (dataType == 's') {
        /*
        if (tstr == 0) {
        return 0;
        }
        */
        if (tstr.length) {
            return tstr.length;
        }
    }
    return parseFloat(tstr);
}

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


/////////////////// Strankovacie sekcie //////////////////////


(function ($, undefined) {
    'use strict';

    function PageableSection() {

        if (!(this instanceof PageableSection)) {
            return new PageableSection();
        }

        this.section = null;
        this.pager = null;
        this.currentPageLabel = null;
        this.totalPagesLabel = null;
        this.prevPageButton = null;
        this.nextPageButton = null;
        this.addPageButton = null;
        this.removePageButton = null;

        this.currentPage = 1;
        this.totalPages = 1;

        this.pages = [];
        this.defaultValues = {};

        this.options = {
            namespace: '.pageable-section',
            validator: null,
            sectionName: '',
            xmlNodeName: '',
            min: 1,
            max: 5
        };
    }

    $.extend(PageableSection.prototype, {
        init: function (target, userOptions) {
            $.extend(true, this.options, userOptions);

            var self = this,
			    options = self.options,
			    namespace = options.namespace;

            // section
            this.section = $(target);

            if (!options.sectionName) {
                options.sectionName = this.section[0].id;
            }

            if (!options.xmlNodeName) {
                options.xmlNodeName = $('input:hidden', this.section)[0].name;
            }

            // min, max
            var min = this.section.data('section-min') * 1,
			    max = this.section.data('section-max') * 1;

            if (!isNaN(min)) {
                options.min = min;
            }
            if (!isNaN(max)) {
                options.max = max;
            }

            // pager
            this.pager = $('.sectionPager', this.section);
            this.currentPageLabel = $('.currentPage', this.pager);
            this.totalPagesLabel = $('.totalPage', this.pager);
            this.prevPageButton = $('.prevPageButton', this.pager);
            this.nextPageButton = $('.nextPageButton', this.pager);
            this.addPageButton = $('.addPageButton', this.pager);
            this.gotoPageButton = $('.gotoPageButton', this.pager);
            this.removePageButton = $('.removePageButton', this.pager);

            this.prevPageButton
				.unbind(namespace)
				.bind('click' + namespace, $.proxy(function (e) {
				    e.preventDefault();
				    this.previousPage();
				}, this));

            this.nextPageButton
				.unbind(namespace)
				.bind('click' + namespace, $.proxy(function (e) {
				    e.preventDefault();
				    this.nextPage();
				}, this));

            this.addPageButton
				.unbind(namespace)
				.bind('click' + namespace, $.proxy(function (e) {
				    e.preventDefault();
				    this.addPage();
				}, this));

            this.removePageButton
				.unbind(namespace)
				.bind('click' + namespace, $.proxy(function (e) {
				    e.preventDefault();
				    this.removePage();
				}, this));

            this.gotoPageButton
				.unbind(namespace)
				.bind('click' + namespace, $.proxy(function (e) {
				    e.preventDefault();
				    var currentInput = $(e.currentTarget).next();
				    if (isNaN(parseInt(currentInput.val()))) {
				        var strana = this.currentPage;
				        currentInput.val("");
				    } else {
				        var strana = parseInt(currentInput.val());
				        currentInput.val("");
				    }
				    this.goToPage(strana);
				}, this));

            this.currentPageLabel.text(this.currentPage);
            this.totalPagesLabel.text(this.totalPages);

            this.updateButtons();
            this.saveCurrentPage();
            this.saveDefaultValues();
        },

        previousPage: function () {
            if (this.currentPage <= 1) {
                return;
            }

            if (this.currentPage <= this.totalPages)
                this.saveCurrentPage();
            this.currentPage--;
            this.currentPageLabel.text(this.currentPage);

            this.resetLayout();

            this.loadCurrentPage();
        },

        nextPage: function () {
            if (this.currentPage >= this.totalPages) {
                return;
            }

            this.saveCurrentPage();

            this.currentPage++;
            this.currentPageLabel.text(this.currentPage);

            this.resetLayout();
            this.loadCurrentPage();
        },

        addPage: function () {
            if (this.totalPages >= this.options.max) {
                return;
            }

            this.totalPages++;
            this.totalPagesLabel.text(this.totalPages);
            this.updateButtons();

            this.saveCurrentPage();
            this.currentPage = this.totalPages;
            this.currentPageLabel.text(this.currentPage);

            this.resetLayout();
            this.saveCurrentPage();
        },

        removePage: function () {
            if (this.totalPages <= this.options.min) {
                return;
            }

            this.totalPages--;
            this.totalPagesLabel.text(this.totalPages);
            this.updateButtons();

            this.removeCurrentPage();
            this.resetLayout();
            if (this.currentPage > this.totalPages) {
                this.previousPage();
            } else {
                this.loadCurrentPage();
            }
        },

        updateButtons: function () {
            this.addPageButton.toggle(this.totalPages < this.options.max);
            this.removePageButton.toggle(this.totalPages > this.options.min);
        },

        resetLayout: function () {
            $(':text, :password, :file, select, textarea', this.section).each($.proxy(function (_, input) {
                if (input.id) {
                    $(input).val(this.defaultValues[input.id] || '');
                } else {
                    $(input).val('');
                }
            }, this));

            $(':radio, :checkbox', this.section).each($.proxy(function (_, input) {
                if (input.id) {
                    input.checked = this.defaultValues[input.id] || false;
                } else {
                    input.checked = false;
                }
            }, this));

            var validator = this.options.validator;
            if (validator && validator.settings) {
                var error = validator.settings.errorClass,
				    warning = validator.settings.warningClass;

                $('.' + error + ', .' + warning, this.section).removeClass(error + ' ' + warning);
            }
        },

        saveDefaultValues: function () {
            var inputs = $(':text, :password, :file, select, textarea', this.section);

            var defaults = {};
            $.each(inputs, function (_, input) {
                if (input.id) {
                    defaults[input.id] = input.value;
                }
            });

            var checkable = $(':radio, :checkbox', this.section);
            $.each(checkable, function (_, input) {
                if (input.id) {
                    defaults[input.id] = input.checked;
                }
            });

            this.defaultValues = defaults;
        },

        saveCurrentPage: function () {
            var radioButtonLists = [];

            var getErrorType = $.proxy(function ($element) {
                var validator = this.options.validator;
                if (validator && validator.settings) {
                    if ($element.hasClass(validator.settings.errorClass)) {
                        return 'e';
                    } else if ($element.hasClass(validator.settings.warningClass)) {
                        return 'w';
                    }
                }
            }, this);

            var values = $.map($(':input', this.section), $.proxy(function (input) {
                if (input.id) {
                    var $input = $(input),
					    result = { key: input.id, value: $input.val() };
                    if ($input.is(':radio')) {
                        var list = $input.closest('.radioButtonList');
                        if (list.length) {
                            var radioButtonListName = input.name;
                            if ($.inArray(radioButtonListName, radioButtonLists) >= 0) {
                                return;
                            }

                            var inputs = list.find(':radio');
                            var checked = inputs.filter(':checked');
                            var value = checked.val();
                            radioButtonLists.push(radioButtonListName);
                            result.value = value || '';
                            result.key = radioButtonListName;
                            result.rb = {
                                list: list,
                                name: radioButtonListName,
                                checked: checked
                            };

                            var errorTypes = [];
                            $.each(inputs, $.proxy(function (_, radio) {
                                var et = getErrorType($(radio));
                                if (et) {
                                    errorTypes.push(et);
                                }
                            }, this));

                            result.rb.errorTypes = errorTypes;
                        } else {
                            result.value = $input.is(':checked');
                        }
                    } else if ($input.is(':checkbox')) {
                        result.value = input.checked;
                    }

                    var errorType = getErrorType($input);
                    if (errorType) {
                        result.errorType = errorType;
                    }

                    return result;
                }
            }, this));

            if (this.pages.length) {
                var current = this.pages[this.currentPage - 1];
                if (current) {
                    current.values = values;
                    return;
                }
            }

            this.pages.splice(this.currentPage - 1, 0, { values: values });
        },

        removeCurrentPage: function () {
            if (this.pages.length && this.pages.length >= this.currentPage) {
                this.pages.splice(this.currentPage - 1, 1);
            }

            if (this.options.validator) {
                this.options.validator.removeAllSectionErrors(this.getSectionName(), this.currentPage);
            }
        },

        _loadRadioButtonList: function (value) {
            var list = value.rb.list;
            list.find(':radio').each(function (_, radio) {
                radio.checked = radio.value === value.value;
            });
        },

        loadCurrentPage: function () {
            if (this.pages.length && this.pages.length >= this.currentPage) {
                var current = this.pages[this.currentPage - 1];
                if (current && current.values) {
                    for (var j = 0; j < current.values.length; j++) {
                        var value = current.values[j],
						    rb = value.rb;

                        if (rb) {
                            this._loadRadioButtonList(value);
                            continue;
                        }

                        var $input = $('#' + value.key, this.section);
                        if (!$input || $input.length === 0) { //radio v strankovacich sekciach
                            if (value.value !== '0') {
                                $input = $('input[name="' + value.key + '"]', this.section);
                                $input[value.value - 1].checked = true;
                            }
                        }
                        else {
                            if ($input.is(':radio') || $input.is(':checkbox')) {
                                $input[0].checked = (value.value === true || value.value == '1');
                                continue;
                            }
                            $input.val(value.value);

                            if (value.errorType) {
                                var validator = this.options.validator;
                                if (validator && validator.settings) {
                                    if (value.errorType === 'e') {
                                        $input.addClass(validator.settings.errorClass);
                                    } else if (value.errorType === 'w') {
                                        $input.addClass(validator.settings.warningClass);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },

        goToPage: function (page) {
            if (page > this.totalPages) {
                page = this.totalPages;
            }

            if (page < 1) {
                page = 1;
            }

            this.saveCurrentPage();
            this.currentPage = page;
            this.currentPageLabel.text(this.currentPage);
            this.resetLayout();
            this.loadCurrentPage();
        },

        getSectionName: function () {
            return this.options.sectionName || '';
        },

        getSectionXmlNodeName: function () {
            return this.options.xmlNodeName || '';
        },

        getCurrentPage: function () {
            return this.currentPage;
        },

        focusin: function (elementId) {
            if (elementId) {
                $('#' + elementId, this.section).focus();
            }
        },

        getValueFor: function (elementId, page) {
            if (this.totalPages > 0 && page === this.currentPage) {
                this.saveCurrentPage();
            }

            if (this.pages.length) {
                page = page || 1;
                if (page > this.pages.length) {
                    return '';
                }

                var pageValues = this.pages[page - 1];

                for (var i = 0; i < pageValues.values.length; i++) {
                    var value = pageValues.values[i];
                    if (value.key === elementId) {
                        return value.value || '';
                    }
                }
            }

            return '';
        },

        getValuesFor: function (elementId) {
            var result = [];

            if (this.totalPages > 0) {
                this.saveCurrentPage();
            }

            for (var i = 0; i < this.pages.length; i++) {
                var pageValues = this.pages[i];

                for (var j = 0; j < pageValues.values.length; j++) {
                    var value = pageValues.values[j];
                    if (value.key === elementId) {
                        result.push(value.value || '');
                    }
                }
            }

            return result;
        },

        validatePage: function (page) {
            if (this.totalPages < page) {
                return;
            }

            var pageValues = this.pages[page - 1].values;

            var validator = this.options.validator;
            if (!validator) {
                return;
            }

            validator.sectionScope = {
                name: this.getSectionName(),
                page: page,
                values: pageValues
            };

            for (var i = 0; i < pageValues.length; i++) {
                var pageValue = pageValues[i];
                var elem = $('#' + pageValue.key, this.section)
                if (!elem || elem.length === 0) {
                    elem = $('input[name="' + pageValue.key + '"]', this.section)[0];
                }
                validator.check(elem);
            }

            delete validator.sectionScope;
        },

        validate: function () {
            if (this.totalPages > 0) {
                this.saveCurrentPage();
            }

            for (var i = 1; i <= this.totalPages; i++) {
                this.validatePage(i);
            }
        },

        validateElementOnPage: function (elementId, page, ruleName) {
            if (this.totalPages < page) {
                return;
            }

            if (this.totalPages > 0) {
                this.saveCurrentPage();
            }

            var pageValues = this.pages[page - 1].values;
            var validator = this.options.validator;
            if (!validator) {
                return;
            }

            validator.sectionScope = {
                name: this.getSectionName(),
                page: page,
                values: pageValues,
                ruleName: ruleName
            };

            validator.element($('#' + elementId, this.section));
            delete validator.sectionScope;
        },

        resetSection: function () {
            this.pages = [];

            this.totalPages = 1;
            this.totalPagesLabel.text(this.totalPages);

            this.currentPage = 1;
            this.currentPageLabel.text(this.currentPage);

            this.updateButtons();

            this.resetLayout();
        },

        structure: null,

        buildUpStructure: function () {
            var section = this.section;
            var rows = $('.layoutRow', section)
				.filter(function (_, row) {
				    return $(row).attr('isempty') !== 'true';
				}).map(function (_, row) {
				    var $row = $(row);
				    return { id: row.id, node: $row.children('input:hidden').attr('name'), parent: $row.parent().closest('.layoutRow')[0], element: row };
				});

            var sectionElement = section[0];

            this.structure = {
                id: sectionElement.id,
                node: section.children('input:hidden').attr('name'),
                parent: null,
                element: sectionElement
            };

            var buildRowsRecursive = function (parent) {
                parent.children = $.grep(rows, function (row) {
                    return row.parent === parent.element;
                });

                if (parent.children && parent.children.length) {
                    $.each(parent.children, function (_, child) {
                        buildRowsRecursive(child);
                    });
                }
            };

            if (rows.length) {
                buildRowsRecursive(this.structure);
            }

            var elements = $(':input:not(:hidden)', section).map(function (_, element) {
                var $element = $(element);
                return { id: element.id, name: element.name, element: element, parent: $element.closest('.layoutRow')[0] };
            });

            var buildElementsRecursive = function (parent) {
                parent.elements = $.grep(elements, function (element) {
                    return element.parent === parent.element;
                });

                if (parent.children && parent.children.length) {
                    $.each(parent.children, function (_, child) {
                        buildElementsRecursive(child);
                    });
                }
            };

            if (elements.length) {
                buildElementsRecursive(this.structure);
            }
        },

        writeXml: function (sb, page) {
            if (!this.structure) {
                this.buildUpStructure();
            }

            if (!sb) {
                sb = new $.StringBuilder();
            }

            var writeRecursive = function (parent) {

                sb.append('<' + parent.node + '>');

                var index = 0;
                var lastRadio = '$$$';
                var lastRadioEmpty = true;
                $.each(parent.elements, function (_, element) {
                    index++;
                    var pair = $.grep(page.values, function (value) {
                        return value.key === element.id;
                    })[0];
                    element = element.element;
                    if ($(element).is(':radio')) {
                        if (lastRadio != element.name) {
                            if (lastRadioEmpty && lastRadio != '$$$') {
                                sb.append('<' + lastRadio + '>' + 0 + '</' + lastRadio + '>');
                            }
                            lastRadio = element.name;
                            lastRadioEmpty = true;
                        }
                        if (pair && pair.value === true) {
                            sb.append('<' + element.name + '>' + index + '</' + element.name + '>');
                            lastRadioEmpty = false;
                        }
                    } else if ($(element).is(':checkbox')) {
                        sb.append('<' + pair.key + '>' + (pair.value !== undefined && (pair.value === true || pair.value == '1') ? 1 : 0) + '</' + pair.key + '>');
                    } else {
                        if (pair) {
                            if (pair.value && pair.value.length > 0) {
                                if ($(element).attr('isempty') == undefined || $(element).attr('isempty') == "false") {
                                    if ($(element).attr("class") && $(element).attr("class").indexOf("date") != -1) {
                                        var value = pair.value;
                                        if ($(element).is('[class*=date]')) {
                                            value = xmlHelper.toXmlDate(value);
                                        }
                                        sb.append('<' + pair.key + '>' + value + '</' + pair.key + '>');
                                    } else {
                                        sb.append('<' + pair.key + '>' + pair.value + '</' + pair.key + '>');
                                    }
                                }
                            } else {
                                //sb.append('<' + pair.key + ' />');
                            }
                        } else {
                            //sb.append('<' + element + ' />');
                        }
                    }
                });
                if (lastRadioEmpty && lastRadio != '$$$') {
                    sb.append('<' + lastRadio + '>' + 0 + '</' + lastRadio + '>');
                }

                if (parent.children) {
                    $.each(parent.children, function (_, child) {
                        writeRecursive(child);
                    });
                }

                sb.append('</' + parent.node + '>');

            };

            writeRecursive(this.structure);
        },

        loadXml: function (xmlNode, nodeName) {
            if (!xmlNode || !xmlNode.childNodes) {
                return;
            }

            this.resetSection();

            if (!this.structure) {
                this.buildUpStructure();
            }

            var loadXmlRecursive = function (structureNode, sectionNode, values) {
                if (!sectionNode || !sectionNode.childNodes) {
                    return;
                }
                for (var j = 0; j < sectionNode.childNodes.length; j++) {
                    var sectionChildNode = sectionNode.childNodes[j];

                    var possibleSections = $.grep(structureNode.children, function (child) {
                        return child.node === sectionChildNode.nodeName;
                    });

                    if (possibleSections.length) {
                        loadXmlRecursive(possibleSections[0], sectionChildNode, values);
                    }

                    var possibleElements = $.grep(structureNode.elements, function (element) {
                        if ($(element.element).is(':radio')) {
                            return element.name === sectionChildNode.nodeName;
                        }
                        else {
                            return element.id === sectionChildNode.nodeName;
                        }
                    });

                    if (possibleElements.length) {
                        var value = sectionChildNode.firstChild.nodeValue;
                        var element = possibleElements[0];
                        if ($(element.element).is('[class*=date]')) {
                            value = xmlHelper.fromXmlDate(value);
                        }
                        if ($(element.element).is(':checkbox'/*, :radio'*/)) {
                            value = value === '1';
                        }
                        values.push({ key: sectionChildNode.nodeName, value: value });
                    }
                }
            };

            for (var i = 0; i < xmlNode.childNodes.length; i++) {
                var childNode = xmlNode.childNodes[i];

                if (childNode.nodeName !== nodeName) {
                    continue;
                }

                var values = [];
                loadXmlRecursive(this.structure, childNode, values);
                this.pages.push({ values: values });
            }

            this.totalPages = this.pages.length || 1;
            this.totalPagesLabel.text(this.totalPages);

            this.loadCurrentPage();
        }
    });

    $.fn.pageableSection = function (options) {
        var self = this;

        if (!options) {
            return self.data('pageable-section');
        } else {
            return $.each(self, function (_, element) {
                var section = new PageableSection();
                section.init(element, options);

                $(element).data('pageable-section', section);
            });
        }
    };
})(jQuery);

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


//////////////////////// Funkcie pre ML //////////////////////////

function zaokruhli_dole(cislo, poc_desatin) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.floor(poma + 0.00000001) / pomb;
    return vrat.toFixed(poc_desatin);
}

function zaokruhli_dolemj(poc_desatin, cislo) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.floor(poma + 0.00000001) / pomb;
    return vrat.toFixed(poc_desatin);
}

function zaokruhli_hore(cislo, poc_desatin) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.ceil(poma) / pomb;
    return vrat.toFixed(poc_desatin);
}

function zaokruhli_horemj(poc_desatin, cislo) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.ceil(poma) / pomb;
    return vrat.toFixed(poc_desatin);
}


function zaokruhli_mate(cislo, poc_desatin) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.round(poma) / pomb;
    return vrat.toFixed(poc_desatin);
}

function zaokruhli_matmj(poc_desatin, cislo) {
    vrat = cislo;
    pomb = Math.pow(10, poc_desatin);
    poma = cislo * pomb;
    vrat = Math.round(poma) / pomb;
    return vrat.toFixed(poc_desatin);
}

function cislo_znamienko(cislo) {
    vrat = cislo;
    if (cislo > 0) { vrat = '+' + vrat; }
    return vrat;
}

function sum_opak(element) {
    var sum = '';

    $("[id^='" + element + "']").each(function () {
        if (!isNaN(this.value))
            sum = Number(sum) + Number(this.value);
    });

    return sum;
}

function count_opak(element) {
    return $("[id^='" + element + "']").length;
}

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


////////////////// pre JS testing - presunie sa do vlastneho suboru //////////////////////////

function CheckIfAllFieldsHaveXpaths() {
    var errorFieldsId = '';

    $('[ID]:input').not('.button').each(function () {
        if ($(this).siblings('.XPathClass').length == 0) {
            errorFieldsId += ', ' + $(this).attr('id');
        }
    });

    $('textarea').each(function () {
        if ($(this).siblings('.XPathClass').length == 0) {
            errorFieldsId += ', ' + $(this).attr('id');
        }
    });

    $('select').each(function () {
        if ($(this).siblings('.XPathClass').length == 0) {
            errorFieldsId += ', ' + $(this).attr('id');
        }
    });

    if (errorFieldsId == '')
        return "Result: OK - All fields have xpaths";
    else
        return "Result: FAIL - This fields haven't xpath:" + errorFieldsId.substr(1);
}

function CheckIfAllRepeatingLayoutRowsHaveXpaths() {
    var errorLayoutRowsId = '';

    $("[id^='repetitionCommandslayoutRow']").each(function () {
        if ($(this).siblings('.XPathClass').length == 0) {
            errorLayoutRowsId += ', ' + $(this).attr('id').substr(18);
        }
    });

    if (errorLayoutRowsId == '')
        return "Result: OK - All repeating layoutrows have xpaths";
    else
        return "Result: FAIL - This repeating layoutrows haven't xpath:" + errorLayoutRowsId.substr(1);
}

function CheckIfAllFieldsHaveSameRootXpath() {
    var errorXptahFieldsId = '';
    var allXpaths = $('.XPathClass');
    var firstXpath = allXpaths.first();

    if (firstXpath.length != 0) {
        var root = firstXpath[0].innerHTML.substr(1).split('/')[0];

        allXpaths.each(function () {
            if (this.innerHTML.substr(1).split('/')[0] !== root) {
                var elementId = $(this).siblings('[id]').first().attr('id');

                if (elementId.indexOf('layoutRowContentlayoutRow') == -1)
                    errorXptahFieldsId += ', ' + elementId;
                else
                    errorXptahFieldsId += ', ' + elementId.substr(17);
            }
        });

        if (errorXptahFieldsId == '')
            return "Result: OK - All fields have same root xpath";
        else
            return "Result: FAIL - This fields haven't same root xpath:" + errorXptahFieldsId.substr(1);
    }
    else
        return 'Result: FAIL - xpaths is not present';
}

function CheckXpathsOnFields() {
    var result = 'Check if all fields have xpaths \r\n' + CheckIfAllFieldsHaveXpaths();
    result += '\r\n\nCheck if all repeating layoutrows have xpaths \r\n' + CheckIfAllRepeatingLayoutRowsHaveXpaths();
    result += '\r\n\nCheck if all xpaths have same root \r\n' + CheckIfAllFieldsHaveSameRootXpath();

    return result;
}

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