if (typeof (Dynamics) == "undefined") { Dynamics = { __namespace: true }; }
if (typeof (Dynamics.Portal) == "undefined") { Dynamics.Portal = { __namespace: true }; }

Dynamics.Portal.GenericFields = new function () {
    var self = this;

    // Disabled (i campi disabled non saranno oggetti in fase di submit..usare read)
    self.Disabled = new function () {
        this.set = function (fieldName, value) {
            value ? disable(fieldName) : enable(fieldName);
        };
        this.get = function (fieldName) {
            return getEditability(fieldName);
        };

        function enable(fieldName) {
            $("#" + fieldName).attr('disabled', false);
        };
        function disable(fieldName) {
            $("#" + fieldName).attr('disabled', true);
        };
        function getEditability(fieldName) {
            return $("#" + fieldName).is(":disabled");
        };
    };

    // Readonly
    self.Readonly = new function () {
        this.set = function (fieldName, value) {
            value ? disable(fieldName) : enable(fieldName);
        };
        this.get = function (fieldName) {
            return getReadonly(fieldName);
        };
        this.cleanTextMuted = function () {
            if ($('.text-muted')[0])
                return;

            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = '.text-muted { color: transparent;}';
            document.getElementsByTagName('head')[0].appendChild(style);
        };

        function enable(fieldName) {
            //$("#" + fieldName).attr('readonly', false);
            //$("#" + fieldName).attr('disabled', false);
            $("#" + fieldName).css('cursor', '');
            $("#" + fieldName).css('pointer-events', '');
            $("#" + fieldName).css('background-color', '#fff');
        };
        function disable(fieldName) {
            //$("#" + fieldName).attr('readonly', true);
            //$("#" + fieldName).attr('disabled', true);
            $("#" + fieldName).css('cursor', 'not-allowed');
            $("#" + fieldName).css('pointer-events', 'none');
            $("#" + fieldName).css('background-color', '#eee');
        };
        function getReadonly(fieldName) {
            return $("#" + fieldName).is('[readonly]');
        };
    };

    // Visibility
    self.Visibility = new function () {
        this.set = function (fieldName, value) {
            value ? show(fieldName) : hide(fieldName);
        };
        this.get = function (fieldName) {

            return getVisible(fieldName);
        };

        this.setVisibleRow = function (fieldName, value) {
            value ? showRow(fieldName) : hideRow(fieldName);
        };
        this.getVisibleRow = function (fieldName) {

            return getVisible(fieldName);
        };

        function show(fieldName) {
            //var allTd = $('td');

            //for (var i = 0; i < allTd.length; i++) {

            //	var item = $(allTd[index]);
            //	var tryFound = $(item).find("#" + fieldName);
            //	if (tryFound.length === 1) {
            //		$(item).show();
            //		return;
            //	}
            //}
            $("#" + fieldName).closest('td').show();

        };
        function hide(fieldName) {
            //var allTd = $('td');

            //for (var i = 0; i < allTd.length; i++) {

            //	var item = $(allTd[i]);
            //	var tryFound = $(item).find("#" + fieldName);
            //	if (tryFound.length === 1) {
            //		$(item).hide();
            //		return;
            //	}
            //}

            $("#" + fieldName).closest('td').hide();
        };

        function showRow(fieldName) {
            $("#" + fieldName).closest('tr').show();
        };
        function hideRow(fieldName) {
            $("#" + fieldName).closest('tr').hide();
        };

        function getVisible(fieldName) {
            return $("#" + fieldName).is(":visible");
        };
    };
    // Required
    self.Required = new function () {
        this.set = function (fieldName, fieldLabel, value) {
            if (fieldLabel === "")
                fieldLabel = $("label[for='" + fieldName + "']").text();

            value ? addValidator(fieldName, fieldLabel) : removeValidator(fieldName, fieldLabel);
        };
        this.get = function (fieldName) {

            return getRequired(fieldName);
        };

        function addValidator(fieldName, fieldLabel) {
            if (typeof (Page_Validators) == 'undefined') return;
            // Create new validator
            $("#" + fieldName + "_label").parent().addClass("required");

            var newValidator = document.createElement('span');
            newValidator.style.display = "none";
            newValidator.id = "RequiredFieldValidator" + fieldName;
            newValidator.controltovalidate = "casetypecode";
            newValidator.errormessage = "<a href='#" + fieldName + "_label'>" + fieldLabel + " " + Leonardo.Constant.Body.Text.TXT00000496 + " </a>"; //is a mandatory field.
            newValidator.validationGroup = "";
            newValidator.initialvalue = "";
            newValidator.evaluationfunction = function () {
                var value = $("#" + fieldName).val();
                if (value == null || value === "") {
                    return false;
                } else {
                    return true;
                }
            };

            // Add the new validator to the page validators array:
            Page_Validators.push(newValidator);

            // Wire-up the click event handler of the validation summary link
            $("a[href='#" + fieldName + "_label']").on("click", function () { scrollToAndFocus(fieldName + '_label', fieldName); });

        };
        function removeValidator(fieldName) {
            if (typeof (Page_Validators) == 'undefined') return;

            $.each(Page_Validators, function (index, validator) {
                if (validator.id == "RequiredFieldValidator" + fieldName) {
                    ValidatorEnable(validator, false);
                }
            });

            $("#" + fieldName + "_label").parent().removeClass("required");
            $("#" + fieldName).removeAttr('required');

        };
        function getRequired(fieldName) {
            return $("#" + fieldName + "_label").parent().hasClass("required");
        };
    };

    // Valuing
    self.Attribute = new function () {
        this.get = function (fieldName) {
            return $("#" + fieldName).val();
        };
        this.set = function (fieldName, value) {
            $("#" + fieldName).val(value);
        };
        this.clean = function (fieldName) {
            $("#" + fieldName).val(null);
        };
        this.addOnChange = function (fieldName, callback) {
            $("#" + fieldName).change(callback);
        };
        this.fireOnChange = function (fieldName) {
            $("#" + fieldName).trigger("change");
        };
        this.setLabel = function (fieldName, newValue) {
            if (fieldName === "" || fieldName === null || fieldName === undefined)
                return;

            $("#" + fieldName + "_label").text(newValue);

        };
        this.getLabel = function (fieldName) {
            $("#" + fieldName + "_label").text();
        };
        this.encodeToHtmlText = function (fieldName) {
            var txt = this.get(fieldName);
            if (txt == null)
                return;
            txt = txt.replace(/&/g, '&amp;');
            txt = txt.replace(/"/g, "&quot;");
            txt = txt.replace(/</g, '&lt;');
            txt = txt.replace(/>/g, '&gt;');
            this.set(fieldName, txt);
        }
    };

    // Recommended
    self.Recommended = new function () {
        this.set = function (fieldName) {
            createClassCss();

            if ($("#Recommended" + fieldName)[0])
                return;

            $('#' + fieldName + '_label').after('<span id="Recommended' + fieldName + '">+</span>');
            $("#Recommended" + fieldName).addClass('recommended');
        };
        this.remove = function (fieldName) {
            $("#Recommended" + fieldName).remove();
        }
        this.removeEmptySpace = function () {
            $(".validators > span").each(function () {
                $(this).css("visibility", "");
                $(this).css("display", "none");
            });
        };

        this.checkRecommendedField = function () {
            var startMessage = Leonardo.Constant.Body.Text.TXT00000497 + "\n";
            var fieldsNotFill = "";
            var endMessage = "\nContinue ?";

            $(".recommended").each(function (index, item) {
                var fieldId = item.id.replace('Recommended', '');
                var labelField = $($($(item).prev())[0]).text();


                if ($("#" + fieldId).attr('type') === 'checkbox') {
                    var isChecked = $("#" + fieldId).is(':checked');
                    if (!isChecked)
                        fieldsNotFill += "- " + labelField + "\n";
                } else {
                    var value = $("#" + fieldId).val();
                    if (value === "")
                        fieldsNotFill += "- " + labelField + "\n";
                }
            });

            if (fieldsNotFill === "")
                return true;

            var errorMessage = startMessage + fieldsNotFill + endMessage;

            return confirm(errorMessage);
        }

        function createClassCss() {
            if ($('.recommended')[0])
                return;

            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = '.recommended { color: red; margin-left: 5px }';
            document.getElementsByTagName('head')[0].appendChild(style);
        }
    };


};

Dynamics.Portal.DateTime = new function () {
    var self = this;
    // Read Only

    self.ReadOnly = new function () {
        this.set = function (fieldName, value) {
            value ? disabledDateTime(fieldName) : enabledDateTime(fieldName);
        };
        this.get = function (fieldName) {
            return getDisabledDateTime(fieldName);
        };

        function disabledDateTime(fieldName) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control"))
                .prop('readonly', true);
        };

        function enabledDateTime(fieldName) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control"))
                .prop('readonly', false);
        };
        function getDisabledDateTime(fieldName) {
            return $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control")).is(":readonly");
        };
    };
    // Disabled
    self.Disabled = new function () {
        this.set = function (fieldName, value) {
            value ? disabledDateTime(fieldName) : enabledDateTime(fieldName);
        };
        this.get = function (fieldName) {
            return getDisabledDateTime(fieldName);
        };

        function disabledDateTime(fieldName) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control"))
                .prop('disabled', true);
        };

        function enabledDateTime(fieldName) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control"))
                .prop('disabled', false);
        };
        function getDisabledDateTime(fieldName) {
            return $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control")).is(":disabled");
        };
    };

    // Visibility
    self.Visibility = new function () {
        this.set = function (fieldName, value) {
            Dynamics.Portal.GenericFields.Visibility.set(fieldName, value);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Visibility.get(fieldName);
        }
    };

    // Required
    self.Required = new function () {
        this.set = function (fieldName, fieldLabel, value) {
            Dynamics.Portal.GenericFields.Required.set(fieldName, fieldLabel, value);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Required.get(fieldName);
        }
    };

    // Valuing
    self.Attribute = new function () {
        this.clean = function (fieldName) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker")).data("DateTimePicker").clear();
        };
        this.set = function (fieldName, value) {
            $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker")).data("DateTimePicker").date(value);
        };
        this.get = function (fieldName) {
            var value = $("#" + fieldName).val();

            if (value === "")
                return null;

            var date = new Date(value);
            date = new Date(date.setSeconds(0));
            date = new Date(date.setMinutes(0));
            date = new Date(date.setHours(0));

            return date;

        };
        this.getToday = function () {

            var today = new Date();
            today = new Date(today.setSeconds(0));
            today = new Date(today.setMinutes(0));
            today = new Date(today.setHours(0));

            return today;
        };
        this.getFromString = function (dateString) {
            if (dateString === "") return null;

            var dateStringValidate = dateString.substring(0, 10);
            dateStringValidate = dateStringValidate.replaceAll('/', '');

            var day = dateStringValidate.substring(0, 2);
            var month = dateStringValidate.substring(2, 4);
            var year = dateStringValidate.substring(4, 8);

            var stringToDate = year + '/' + month + '/' + day;

            var date = new Date(stringToDate);
            date = new Date(date.setSeconds(0));
            date = new Date(date.setMinutes(0));
            date = new Date(date.setHours(0));

            return new Date(date);
        };
        this.compare = function (date1, date2) {

            var msDateA = Date.UTC(date1.getFullYear(), date1.getMonth() + 1, date1.getDate());
            var msDateB = Date.UTC(date2.getFullYear(), date2.getMonth() + 1, date2.getDate());

            if (parseFloat(msDateA) <= parseFloat(msDateB)) return true;

            return false;
        };

        this.addOnChange = function (fieldName, callback) {
            $('input#' + fieldName)
                .parent()
                .find($(".input-append.input-group.datetimepicker"))
                .on('dp.change', callback);
        };
    };

    self.AddDirtyClassOnChange = function () {
        for (var i = 0; i < $(".input-append.input-group.datetimepicker").length; i++) {
            var callback = function () {
                $(this).addClass(" dirty");
            };

            var parent = $($(".input-append.input-group.datetimepicker")[i]).parent();
            var children = parent.children();

            var id = children[1].id;

            $('input#' + id)
                .parent()
                .find($(".input-append.input-group.datetimepicker"))
                .on('dp.change', callback);
        }
    };

};

Dynamics.Portal.Lookup = new function () {
    var self = this;

    // Disabled
    self.Disabled = new function () {
        this.set = function (fieldName, value) {
            value ? disableLookup(fieldName) : enableLookup(fieldName);
        };
        this.get = function (fieldName) {
            return Dynamics.Portal.GenericFields.Disabled.get(fieldName);
        };

        function enableLookup(fieldName) {
            $("#" + fieldName).attr('disabled', false);
            $("#" + fieldName + "_name").attr('disabled', false);
            $("#" + fieldName + "_name").attr('readonly', true);

            $("#" + fieldName + "_entityname").next().show();

            $("input#" + fieldName + "_name").css("width", "100%");
        };

        function disableLookup(fieldName) {
            var width = $("#" + fieldName + "_name").width() + $("#" + fieldName + "_entityname").next().width();

            $("#" + fieldName).attr('disabled', true);
            $("#" + fieldName + "_name").attr('disabled', true);
            $("#" + fieldName + "_name").attr('readonly', true);
            $("#" + fieldName + "_name").removeAttr('readonly');
            $("#" + fieldName + "_entityname").next().hide();

            //$("#" + fieldName + "_name").width(width);
            $("#" + fieldName + "_name").parent().parent().css("width", "100%");
            $("#" + fieldName + "_name").parent().css("width", "100%");
        };
    };

    // Visibility
    self.Visibility = new function () {
        this.set = function (fieldName, value) {
            Dynamics.Portal.GenericFields.Visibility.set(fieldName, value);
        };
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Visibility.get(fieldName);
        };
    };

    // Readonly
    self.Readonly = new function () {
        this.set = function (fieldName, value) {
            value ? disableLookup(fieldName) : enableLookup(fieldName);
        };
        this.get = function (fieldName) {
            return Dynamics.Portal.GenericFields.Disabled.get(fieldName);
        };

        function enableLookup(fieldName) {
            $("#" + fieldName).attr('readonly', false);
            $("#" + fieldName + "_name").attr('readonly', false);
            $("#" + fieldName + "_name").attr('readonly', true);

            $("#" + fieldName + "_entityname").next().show();

            $("input#" + fieldName + "_name").css("width", "100%");
            $("#" + fieldName + "_name").parent().css('cursor', 'auto');
            $("#" + fieldName + "_name").parent().css('pointer-events', 'auto');
        };

        function disableLookup(fieldName) {
            var width = $("#" + fieldName + "_name").width() + $("#" + fieldName + "_entityname").next().width();

            $("#" + fieldName).attr('readonly', true);
            $("#" + fieldName + "_name").attr('readonly', true);
            $("#" + fieldName + "_name").attr('readonly', true);
            $("#" + fieldName + "_entityname").next().hide();

            //$("#" + fieldName + "_name").width(width);
            $("#" + fieldName + "_name").parent().parent().css("width", "100%");
            $("#" + fieldName + "_name").parent().css("width", "100%");
            $("#" + fieldName + "_name").parent().css('cursor', 'not-allowed');
            $("#" + fieldName + "_name").parent().css('pointer-events', 'none');
        };
    };

    // Required
    self.Required = new function () {
        this.set = function (fieldName, fieldLabel, value) {
            Dynamics.Portal.GenericFields.Required.set(fieldName, fieldLabel, value);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Required.get(fieldName);
        }
    };

    // Valuing
    self.Attribute = new function () {
        this.set = function (fieldName, id, value, entityname) {
            $("#" + fieldName + "_name").attr("value", value);
            $("#" + fieldName).attr("value", id);
            $("#" + fieldName + "_entityname").attr("value", entityname);
        };
        this.get = function (fieldName) {
            var obj = {};

            var name = $("#" + fieldName + "_name").val();
            var id = $("#" + fieldName).val();
            var entityName = $("#" + fieldName + "_entityname").val();

            if (name === "" || id === "" || entityName === "")
                return null;

            obj.value = name;
            obj.id = id;
            obj.entityname = entityName;

            return obj;
        };
        this.clean = function (fieldName) {
            var value = Dynamics.Portal.Lookup.Attribute.get(fieldName);
            if (value === null)
                return;

            $("#" + fieldName).parent().find('.btn.btn-default.clearlookupfield').trigger('click');
        };
        this.addOnChange = function (fieldName, callback) {
            Dynamics.Portal.GenericFields.Attribute.addOnChange(fieldName, callback);
        }
        this.fireOnChange = function (fieldName) {
            Dynamics.Portal.GenericFields.Attribute.fireOnChange(fieldName);
        }

    };

    // add open
    self.OpenLookup = new function () {
        this.add = function (lookuptextId, lookupguidId, webpageName, openWindowLocation) {
            $(document).ready(function () {

                $("#" + lookuptextId).click(function () {
                    var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
                    var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

                    var width = window.innerWidth
                        ? window.innerWidth
                        : document.documentElement.clientWidth
                            ? document.documentElement.clientWidth
                            : screen.width;
                    var height = window.innerHeight
                        ? window.innerHeight
                        : document.documentElement.clientHeight
                            ? document.documentElement.clientHeight
                            : screen.height;

                    var w = 600;
                    var h = 600;

                    var left = ((width / 2) - (w / 2)) + dualScreenLeft;
                    var top = ((height / 2) - (h / 2)) + dualScreenTop;

                    var recordID = $("#" + lookupguidId).val();

                    var portalHostName = window.location.host;

                    var portalURL = "https://" + portalHostName;

                    var url = portalURL + "/" + webpageName + "/?id=" + recordID;

                    if (openWindowLocation)
                        window.open(url, 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
                    else
                        window.open(url, 'popup', 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
                });

                $("#" + lookupguidId).change(function () {

                    $("#" + lookuptextId).css("color", "blue");
                    $("#" + lookuptextId).css("cursor", "pointer");

                });

                var getLookupValue = $("#" + lookuptextId).val();

                if (getLookupValue) {

                    $("#" + lookuptextId).css("color", "blue");
                    $("#" + lookuptextId).css("cursor", "pointer");
                }

            });
        };

    };
};

Dynamics.Portal.CheckBox = new function () {
    var self = this;

    // Disabled
    self.Disabled = new function () {
        this.set = function (fieldName, value) {
            Dynamics.Portal.GenericFields.Disabled.set(fieldName, value);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Disabled.get(fieldName);
        }
    };

    // Required
    self.Required = new function () {
        this.set = function (fieldName, fieldLabel, value) {
            value ? addValidatorCheckBox(fieldName, fieldLabel) : removeValidator(fieldName, fieldLabel);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Required.get(fieldName);
        }

        function addValidatorCheckBox(fieldName, fieldLabel) {
            if (typeof (Page_Validators) == 'undefined') return;
            // Create new validator
            $("#" + fieldName + "_label").parent().addClass("required");

            var newValidator = document.createElement('span');
            newValidator.style.display = "none";
            newValidator.id = "RequiredFieldValidator" + fieldName;
            newValidator.controltovalidate = "casetypecode";
            newValidator.errormessage = "<a href='#" + fieldName + "_label'>" + fieldLabel + " is a required field.</a>";
            newValidator.validationGroup = "";
            newValidator.initialvalue = "";
            newValidator.evaluationfunction = function () {
                return !$("#" + fieldName).is(":checked");
            };

            // Add the new validator to the page validators array:
            Page_Validators.push(newValidator);

            // Wire-up the click event handler of the validation summary link
            $("a[href='#" + fieldName + "_label']").on("click", function () { scrollToAndFocus(fieldName + '_label', fieldName); });

        }

    };

    // Visibility
    self.Visibility = new function () {
        this.set = function (fieldName, value) {
            Dynamics.Portal.GenericFields.Visibility.set(fieldName, value);
        }
        this.get = function (fieldName) {
            Dynamics.Portal.GenericFields.Visibility.get(fieldName);
        }
    };

    // Valuing
    self.Attribute = new function () {
        this.get = function (fieldName) {
            return $("#" + fieldName).is(":checked");
        };
        this.set = function (fieldName, value) {
            //$("#" + fieldName).attr("checked", value);
            $("#" + fieldName).prop("checked", value);
        };
        this.addOnChange = function (fieldName, callback) {
            Dynamics.Portal.GenericFields.Attribute.addOnChange(fieldName, callback);
        };
        this.fireOnChange = function (fieldName) {
            Dynamics.Portal.GenericFields.Attribute.fireOnChange(fieldName);
        }

    };
};

Dynamics.Portal.Regex = new function () {
    var self = this;

    self.Validate = function (value, regex) {

        var result = regex.exec(value);
        return result && result[0] === value;
    };
};

Dynamics.Portal.Fetch = new function () {
    var self = this;

    self.checkIfExists = function (url, async) {
        var value = true;
        var asyncValue = async === "" ? false : true;

        var request = $.ajax({
            type: "GET",
            url: url,
            dataType: 'json',
            async: asyncValue
        });

        request.done(function (result) {
            if (result.value.length === 0)
                value = false;
        });

        return value;
    };

    self.execute = function (url, callback, async) {
        var asyncValue = async === "" ? false : true;

        var request = $.ajax({
            type: "GET",
            url: url,
            dataType: 'json',
            async: asyncValue
        });

        request.done(function (result) {
            callback(result);
        });
    };

    self.executeWithReturn = function (url, async) {
        var asyncValue = async === "" ? false : true;

        var request = $.ajax({
            type: "GET",
            url: url,
            dataType: 'json',
            async: asyncValue
        });

        var value = null;

        request.done(function (result) {
            value = result;
        });

        return value;
    };

};

Dynamics.Portal.Scheda = new function () {
    var self = this;
    var collapseButton = { transform: 'rotate(270deg)', marginLeft: '5px' };
    var expandButton = { transform: 'rotate(315deg)', marginLeft: '5px' };

    self.image =
        "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAHJJREFUOI3tz8ENgCAQBdFJNNRjidiNdVgBZdgDB71gYlbEXeRgjJNw5Gcf/L26AYjAanwx/c02Vgz60pUOCIaxkP40oRepMg29SJXd0VVU2RXdRJXl6L52DM70Kqpsp6uonWJwAXpgBqZHpx1yNKB+tA2h2lWD8t5Y8AAAAABJRU5ErkJggg==";

    self.openClose = function (item) {

        var id = $(item).attr('id');
        var idDecoded = atob(id);
        var isVisible = $("div[data-name='" + idDecoded + "']").is(':visible');

        if (isVisible) {
            $('div[data-name=' + idDecoded + ']').hide();
            $(item).removeClass('expandButton');
            $(item).css(collapseButton);
        } else {
            $('div[data-name=' + idDecoded + ']').show();
            $(item).css(expandButton);
            $(item).removeClass('collapseButton');
        }
    }

    self.addCollapseExpand = function (schedaName) {
        var scheda = $('h2:contains(' + schedaName + ')');
        var tabName = $($(scheda)[0]).next().attr('data-name');

        var id = btoa(tabName);
        id = id.replaceAll('=', '');
        var tagImg =
            "<img id='"
            + id
            + "' src='" + self.image + "' onclick='Dynamics.Portal.Scheda.openClose(this)'></img>";

        $($(scheda)).append(tagImg);
        $("#" + id).css(expandButton);
    };

    self.addAllCollapseExpand = function () {

        var allScheda = $("h2.tab-title");

        for (var i = 0; i < allScheda.length; i++) {
            var tab = $($($("h2.tab-title")[i])[0]).next();//.attr('data-name');
            var tabName = $($($("h2.tab-title")[i])[0]).next().attr('data-name');
            var id = btoa(tabName);
            id = id.replaceAll('=', '');
            console.log(tabName + " ID: " + id);
            $('h2.tab-title').parent().css('border-bottom', 'none');
            $($("h2.tab-title")[i]).addClass('panel-title paneltitlewrap cardshadowed__btn');
            $($("h2.tab-title")[i]).attr("data-toggle", "collapse");
            $($("h2.tab-title")[i]).attr("href", "#" + id);
            $($("h2.tab-title")[i]).append('<span class="cardshadowed__arrow"><img src=' + window.location.origin + '/' + $('html').attr('data-lang') + '/angle-down.svg /></span>');
            $($("h2.tab-title")[i]).wrap('<div class="panel-heading ' + id + '"></div>');
            /*$($("h2.tab-title")[i]).append('<a data-toggle="collapse" href="#' + id + '"><h4>' + $($("h2.tab-title")[i])[0].innerText + '<span class="glyphicon glyphicon-chevron-down"></span></h4></a>');
            $($("h2.tab-title")[i]).wrap('<div class="panel-heading ' + id + '"></div>');*/
            tab.wrap('<div id="' + id + '" class="panel-collapse collapse in ' + id + '"><div class="panel-body"></div></div>');
            $("." + id).wrapAll('<div class="panel panel-default"></div>');

            //$($("h2.tab-title")[0])[0].innerText

            //  var tagImg =
            //       "<img id='"
            //      + id
            //       + "' src='" + self.image + "' onclick='Dynamics.Portal.Scheda.openClose(this)'></img>";

            //    $($("h2.tab-title")[i]).append(tagImg);
            //    $("#" + id).css(expandButton);
        }
    };

    self.Visibility = new function () {
        this.set = function (schedaName, labelName, value) {
            value ? showScheda(schedaName, labelName) : hideScheda(schedaName, labelName);
        };

        function hideScheda(schedaName, labelName) {
            $('div[data-name=' + schedaName + ']').hide();
            $('h2:contains(' + labelName + ')').hide();
        };
        function showScheda(schedaName, labelName) {
            $('div[data-name=' + schedaName + ']').show();
            $('h2:contains(' + labelName + ')').show();
        };
    };


};

Dynamics.Portal.EntityList = new function () {
    var self = this;

    self.moveDetailsButtonToLeftOnEntityList = function () {
        $(".entitylist.entity-grid tr").each(function () {
            var child = $(this).children();
            var firstElement = child.first();
            var lastElement = child.last();

            if ($($(lastElement).has("span")).text() === "Actions" || $($(lastElement).has(".dropdown.action")).length > 0)
                lastElement.insertBefore(firstElement);

        });
    };

    self.hideLinkOnFirstColumnWithTdName = function (firstColumnsName) {
        $("td[data-attribute='" + firstColumnsName + "']").each(function () {
            $(this).find('a').removeAttr('href').css('textDecoration', 'none').css('color', '#666');
        });
    };

    self.hideLinkOnFirstColumn = function (tableName, firstColumnsName) {
        $("#" + tableName + " td[data-attribute='" + firstColumnsName + "']").each(function () {
            $(this).find('a').removeAttr('href').css('textDecoration', 'none').css('color', '#666');
        });
    };

};

Dynamics.Portal.Page = new function () {
    var self = this;

    self.addOnSave = function (buttonName, callback) {
        $("#" + buttonName).on('click',
            function () {
                callback();
            });
    };
    self.getParamsFromUrl = function (param) {
        var url = window.location.search.substring(1);
        var urlParams = url.split('&');

        for (var i = 0; i < urlParams.length; i++) {
            var sParameterName = urlParams[i].split('=');

            if (sParameterName[0] === param) {
                return sParameterName[1];
            }
        }
    };
    self.getDirty = function () {
        return document.getElementsByClassName("dirty");
    };
    self.isDirty = function () {
        var fieldsDirty = this.getDirty();
        return fieldsDirty.length > 0;
    };
    self.forceSave = function (portalModifiedByField, originalFunctionString) {
        var user = Dynamics.Portal.User.Get();
        Dynamics.Portal.User.Set(portalModifiedByField, user, Avanade.Sorgenia.Constants.entityUserDefault);

        originalFunctionString = originalFunctionString.replace('javascript:', '');
        var originalFunction = new Function(originalFunctionString);
        originalFunction();
    };

};

Dynamics.Portal.SubGrid = new function () {
    var self = this;

    self.addOnLoad = function (subgridName, callback) {
        $("#" + subgridName).on("loaded", function () {
            callback();
        });
    };

    self.moveDetailsButtonToLeftOnTableName = function (tableName) {
        $("#" + tableName + " tr").each(function () {
            var child = $(this).children();
            var firstElement = child.first();
            var lastElement = child.last();

            if ($($(lastElement).has("span")).text() === "Actions" || $($(lastElement).has(".dropdown.action")).length > 0)
                lastElement.insertBefore(firstElement);

        });
    };

    self.hideLinkOnFirstColumn = function (tableName, firstColumnsName) {
        Dynamics.Portal.EntityList.hideLinkOnFirstColumn(tableName, firstColumnsName);
    };

    self.addPlaceHolder = function (tableName, message) {
        var gridId = tableName + "SubGrid";

        if ($("#" + gridId).length !== 0)
            return;

        $("[data-name=" + tableName + "]")
            .append("<div style='width: 100%;height: 50px; border: solid; border-color: blue;'>" + message + "</div>");
    };

};

Dynamics.Portal.OptionSet = new function () {
    var self = this;

    self.Attribute = new function () {

        this.get = function (fieldName) {
            var value = $("#" + fieldName).val();
            var name = $("#" + fieldName + " option:selected").text();

            var obj = {};
            obj.value = value;
            obj.name = name;
            return obj;
        };
        this.set = function (fieldName, value) {
            $("#" + fieldName).val(value);
        };

    };
    self.removeOption = function (fieldName, value) {
        $("#" + fieldName + " option[value='" + value + "']").remove();
    };

    self.removeAllOption = function (fieldName) {
        $("#" + fieldName + " option").each(function () {
            $(this).remove();
        });
    };

    self.loadValue = function (name, list, usingDescr) {
        self.removeAllOption(name);
        $("#" + name).append($('<option value text label></option>'));

        if (list === null || list === undefined || list.length === 0)
            return;

        for (let i = 0; i < list.length; i++) {
            var item = list[i];

            if (usingDescr) {
                $("#" + name)
                    .append($("<option text=" + item.opt_text + " value=" + item.opt_value + " data-descr=" + item.description + ">"));

                //.append($(`<option text=${item.opt_text} value=${item.opt_value} data-descr=${item.opt_descr}>`));


                [].forEach.call(document.querySelectorAll('#' + name),
                    function (s) {
                        s.addEventListener('focus', focus);
                        s.addEventListener('blur', blur);
                        s.addEventListener('change', change);
                        blur.call(s);
                    });

            } else {
                $("#" + name).append($('<option>',
                    {
                        value: item.opt_value,
                        text: item.opt_text
                    }));
            }

        }

        function focus() {
            [].forEach.call(this.options, function (o) {
                var descr = o.getAttribute('data-descr');
                if (descr === undefined || descr === null || descr === "")
                    o.textContent = o.getAttribute('text')
                else
                    o.textContent = o.getAttribute('text') + ' (' + o.getAttribute('data-descr') + ')';
            });
        }
        function blur() {
            [].forEach.call(this.options, function (o) {
                o.textContent = o.getAttribute('text');
            });
        }
        function change() {
            [].forEach.call(this.options, function (o) {
                o.textContent = o.getAttribute('text');
                $(':focus').blur();
            });
        }
    };
    self.setCurrentValue = function (currentValue, list) {
        if (currentValue.value === "")
            return;

        for (let i = 0; i < list.length; i++) {
            var item = list[i];

            if (currentValue.value === item.opt_value)
                $("#" + name + " option[value=" + item.opt_value + "]").prop("selected", "selected");

        }
    };
};

Dynamics.Portal.MetadataLookup = new function () {
    var self = this;

    self.Attribute = new function () {

        this.get = function (fieldName) {
            var value = $("#" + fieldName).val();
            var name = $("#" + fieldName + " option:selected").text();

            var obj = {};
            obj.id = value;
            obj.value = name;
            return obj;
        };
        this.set = function (fieldName, id) {
            $("#" + fieldName + " option[value=" + id + "]").prop("selected", "selected");
        };

    };
    self.removeOption = function (fieldName, value) {
        $("#" + fieldName + " option[value='" + value + "']").remove();
    };

    self.removeAllOption = function (fieldName) {
        $("#" + fieldName + " option").each(function () {
            $(this).remove();
        });
    };

    self.loadValue = function (name, list, currentValue, usingDescr) {
        self.removeAllOption(name);
        $("#" + name).append($('<option value text label></option>'));

        if (list === null || list === undefined || list.length === 0) {
            $("#" + name).append($('<option>',
                {
                    value: currentValue.id,
                    text: currentValue.value
                }));
            return;
        }

        for (let i = 0; i < list.length; i++) {
            var item = list[i];

            if (usingDescr) {
                $("#" + name)
                    .append($("<option text=" + item.opt_text + " value=" + item.opt_value + " data-descr=" + item.opt_descr + ">"));

                //.append($(`<option text=${item.opt_text} value=${item.opt_value} data-descr=${item.opt_descr}>`));


                [].forEach.call(document.querySelectorAll('#' + name),
                    function (s) {
                        s.addEventListener('focus', focus);
                        s.addEventListener('blur', blur);
                        s.addEventListener('change', change);
                        blur.call(s);
                    });

            } else {
                $("#" + name).append($('<option>',
                    {
                        value: item.opt_value,
                        text: item.opt_text
                    }));
            }

        }

        function focus() {
            [].forEach.call(this.options, function (o) {
                var descr = o.getAttribute('data-descr');
                if (descr === undefined || descr === null || descr === "")
                    o.textContent = o.getAttribute('text')
                else
                    o.textContent = o.getAttribute('text') + ' (' + o.getAttribute('data-descr') + ')';
            });
        }
        function blur() {
            [].forEach.call(this.options, function (o) {
                o.textContent = o.getAttribute('text');
            });
        }
        function change() {
            [].forEach.call(this.options, function (o) {
                o.textContent = o.getAttribute('text');
                $(':focus').blur();
            });
        }
    };
    self.setCurrentValue = function (currentValue, list) {
        if (currentValue.value === "")
            return;

        for (let i = 0; i < list.length; i++) {
            var item = list[i];

            if (currentValue.value === item.opt_value)
                $("#" + name + " option[value=" + item.opt_value + "]").prop("selected", "selected");

        }
    };
};

Dynamics.Portal.Tab = new function () {
    var self = this;

    self.Visibility = new function () {
        this.set = function (tabName, labelTabName, value) {
            value ? showTab(tabName, labelTabName) : hideTab(tabName, labelTabName);
        };

        function hideTab(tabName, labelTabName) {
            $('[data-name=' + tabName + ']').closest(".panel").hide();
            $('legend:contains(' + labelTabName + ')').closest(".panel").hide();
        };
        function showTab(tabName, labelTabName) {
            $('[data-name=' + tabName + ']').closest(".panel").show();
            $('legend:contains(' + labelTabName + ')').closest(".panel").show();
        };
    };
};

Dynamics.Portal.QuickView = new function () {
    var self = this;

    self.Visibility = new function () {
        this.set = function (quickViewName, value) {
            value ? show(quickViewName) : hide(quickViewName);
        }

        function show(quickViewName) {
            $('table[data-name="' + quickViewName + '"]').show();
        };
        function hide(quickViewName) {
            $('table[data-name="' + quickViewName + '"]').hide();
        };
    };
};

Dynamics.Portal.User = new function () {
    var self = this;

    self.Set = function (fieldName, userObj, entityName) {
        // aggiungere guardia
        Dynamics.Portal.Lookup.Attribute.set(fieldName, userObj.id, userObj.name, entityName);
    };

    self.Get = function () {
        var username = $("#username").text();
        var userid = $("#userId").text();
        var lastlogin = $('#lnd_lastlogin').text().split(": ")[1];
        var userDateFormat = $('#lnd_numericdateformat').text();

        var userObj = {};
        userObj.name = username;
        userObj.id = userid;
        userObj.lastlogin = lastlogin;
        userObj.userDateFormat = userDateFormat;

        return userObj;
    };
};

Dynamics.Portal.Form = new function () {
    var self = this;
    var notificationLevelEnum = {
        error: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAFd0lEQVRYCe1ZXWwUVRQ+d2a6C9uuoW2IEYlg4k+lKA9txWiLC0UDD/CgjT74YGIiPmARo6gpNDRt4QGbEOtGw7sxKLYm0gRCaKtV1GZtlCrgkySCGEnUxrLb7u7MXM+Z3Znd+duZ3W5bCN3cs3Puud8993x3zp17dwdg6bM0A7f3DLBy0OddIMyMNTaqjLUACE0A6jpgbLXJN4crAOwStsVw0LFQS2yCdYFqwpRQQV8l9Mp2SUQ2rlZF3o7VF1DuRimmXAXOPhJAiIZGvvujmI752JIITDU3V1csS3VzDi+jsyDKXEoS78yxtJI8WP3lT1PFOiqawPTWpueYyqLAYGWxg3ng/+KM7Q6fHR/wwJmafRPgDQ0VN1YIUQZsl8lDmSvo/4PQlLyXTUyk/bj2ReB6JFIVkhIDwOFpP07LgDldKc62sTOTcS9fgheAb78vGBISQwsYPIW0La4Eh2hsqhQSTwKJZM1RzPcnCzmZnzYWiadqj3j5LphC061Nz2NOHvdyMp/tuLDbCi1sVwLxp55YxdU0bjxwx3wG6MP3P1yUHgqf+fa6E9Y1hTD4buyw2MFjCFADikyxkG4TwWZBw0zksbUA8CKKvyIIIK7f4A+LKA2LfVD1VTBNXprZ8vgaJ7AjAUXgryBYQvEuogjBzsOw7OgxkHY844mv2PGshg0eOASAfT07ZAAVMpN3ZVTzN5IzG3gkIsXFxFW03olSuGAAwf29IG3aksHh2SLZfwTkk4OZuuWbgg/s2Ycnh8yw8lfDkDzcCaAoFqRTlV+rrFl7DztxwgQWrNBpIf4o2ryDR5BYtx6k5ggYH8Yg2L4PpNZthklXpK3bIdD+phE82aWWzSDU1ZPq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i0Twt/KUHRjcdOzMRLWtwRb0NECHXfCCeQp/7PfbAbFdAeloxn4dQqndd2ErtXz2lv08nClpRgJvG8f1M9OBTANLZcfsN77eWaU9gZP5MxKQDl0N/su4atpkfViUqRlb52q23FkJyIFd4337BNN1WS+lYuKudfb6cu6AnARos4iX00AdwN+Glkj45kA4XCdv6bkS5iaACC8aJoQqTd96VM9B/67Iz+umf0M+X6YlkIy3Udlpp2474MhrBVKJdAb8V+IUn4OXPvmciKb2FViXR0zNOGKam+uCtYvveAVSg/yzh3ypJBL1zMesFYl+oh8ou6FDfsyKmCMyMgP/9Qz8Bk87LzI/x5PdAAAAAElFTkSuQmCC"
    };

    var getProperty = function (propertyName) {
        return notificationLevelEnum[propertyName];
    };

    var classCssOn = false;

    self.Notification = new function () {
        this.remove = function (notificationId, fieldName) {
            var element = $("#" + notificationId);
            if (element.length === 0)
                return;

            deleteMessage(notificationId);

            if (fieldName !== undefined)
                removeNearField(fieldName);

        };
        this.add = function (notificationId, notificationLevel, notificationMessage, fieldName, isDatetime) {
            this.remove(notificationId, fieldName);
            if (fieldName !== undefined)
                removeNearField(fieldName);

            createCssClass();

            var originalWidth = $('input#' + fieldName)
                .parent()
                .find($(".input-append.input-group.datetimepicker")).width();

            var element = "<div class='notification-container' id='" + notificationId + "' >"
                + "<div class='notification-img' >"
                + "<img src='" + getProperty(notificationLevel) + "' />"
                + "</div>"
                + "<div class='notification-message'>"
                + "<p>" + notificationMessage + " </p>"
                + "</div>"
                + "</div>";

            $(".page-heading").append(element);
            var isDate = fieldName !== undefined ? $("input#" + fieldName).attr('class').indexOf("datetime") != -1 : false;

            if (notificationLevel === "error") {
                addNearField(fieldName, notificationMessage);
                if (isDate) {
                    $('#' + notificationId).click(function () { $("input#" + fieldName).parent().find($(".input-append.input-group.datetimepicker > .form-control")).focus(); });
                }
                else {
                    $('#' + notificationId).click(function () { $('#' + fieldName).focus(); });
                }
            }

            if (isDate && fieldName !== undefined) {
                var currentWidth = $('input#' + fieldName)
                    .parent()
                    .find($(".input-append.input-group.datetimepicker")).width();

                if (currentWidth + 30 !== originalWidth)
                    $('input#' + fieldName)
                        .parent()
                        .find($(".input-append.input-group.datetimepicker")).width(originalWidth);
            }
        };
        function addNearField(fieldName, notificationMessage) {
            //self.clearError(fieldName);

            var imgTag = "<img src=" +
                getProperty("error") +
                " id='errorOn" +
                fieldName +
                "' height='30px' onclick='document.documentElement.scrollTop = 0;' "
                //+ " title='"
                //+ notificationMessage
                //+ "' + alt='"
                //+ notificationMessage + "'/>";
                + "'/>";

            $("#" + fieldName).parent().css("display", "flex");
            $("#" + fieldName).parent().append(imgTag);
        };
        function removeNearField(fieldName) {
            if ($("#errorOn" + fieldName).length === 0)
                return;

            $("#" + fieldName).parent().css("display", "initial");
            $("#errorOn" + fieldName).remove();
        }

        function createCssClass() {
            if (classCssOn)
                return;

            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = '.notification-img>img{height:24px;width:24px;margin-top:2px;margin-bottom:2px}.notification-img{margin-right:5px;padding-top:5px}.notification-message{flex-grow:1;margin-right:50px}.notification-message p{white-space: pre-line;font-family:"Segoe UI","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:15px;line-height:1.42857;color:#000;padding-top:7px}.notification-container{border:.5px solid grey;border-radius:4px;display:flex;background-color:#ffffb3;margin-bottom:5px}';
            document.getElementsByTagName('head')[0].appendChild(style);
            classCssOn = true;
        };
        function deleteMessage(notificationId) {
            $("#" + notificationId).remove();
        }
    };
    self.Navigation = new function () {
        this.openWindow = function (url, targetLocation, width, height) {
            var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
            var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

            var screenWidth = window.innerWidth
                ? window.innerWidth
                : document.documentElement.clientWidth
                    ? document.documentElement.clientWidth
                    : screen.width;
            var screenHeight = window.innerHeight
                ? window.innerHeight
                : document.documentElement.clientHeight
                    ? document.documentElement.clientHeight
                    : screen.height;

            var w = width != null ? width : screenWidth / 2;
            var h = height != null ? height : screenHeight / 2;

            var left = ((screenWidth / 2) - (w / 2)) + dualScreenLeft;
            var top = ((screenHeight / 2) - (h / 2)) + dualScreenTop;

            if (targetLocation == "_blank") {
                window.open(url, "_blank");
            } else if (targetLocation)
                window.open(url, targetLocation, 'width=' + w + ',height=' + h + ',top=' + top + ',left=' + left);
            else
                window.open(url, 'width=' + w + ',height=' + h + ',top=' + top + ',left=' + left);
        }
    };

    self.Uploader = new function () {
        this.removeSelectedFile = function () {
            $('input[type="file"]').val(null);
        };

        this.addOnChange = function (callback) {
            $('input[type="file"]').change(function (e) {
                callback(e);
            });
        };
    };
};

Dynamics.Portal.WebApi = new function () {

    var self = this;

    self.SafeAjax = function (ajaxOptions) {
        var deferredAjax = $.Deferred();

        shell.getTokenDeferred().done(function (token) {
            // add headers for AJAX
            if (!ajaxOptions.headers) {
                $.extend(ajaxOptions, {
                    headers: {
                        "__RequestVerificationToken": token
                    }
                });
            } else {
                ajaxOptions.headers["__RequestVerificationToken"] = token;
            }
            $.ajax(ajaxOptions)
                .done(function (data, textStatus, jqXHR) {
                    validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
                }).fail(deferredAjax.reject); //AJAX
        }).fail(function () {
            deferredAjax.rejectWith(this, arguments); // on token failure pass the token AJAX and args
        });



        return deferredAjax.promise();
    };

    self.RemoveVisibility = function (urlsite, entity, guid) {
        self.SafeAjax({
            type: "DELETE",
            url: "/_api/" + entity + "(" + guid + ")",
            contentType: "application/json",
            success: function (data, textStatus, xhr) {
                $("<div>Share Canceled. This page will be refresh.</div>").dialog({
                    modal: true,
                    create: function (event, ui) {
                        $(".ui-widget-header").hide();
                    },
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                            location.reload();
                        }
                    }
                });

            },
            error: function (xhr, textStatus, errorThrown) {
                console.log(xhr);
            }
        });
    }
    self.Remove = function (urlsite, entity, guid) {
        self.SafeAjax({
            type: "DELETE",
            url: "/_api/" + entity + "(" + guid + ")",
            contentType: "application/json",
            success: function (data, textStatus, xhr) {
                console.log("Record deleted");
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log(xhr);
            }
        });
    }
    self.Update = function (urlsite, entity, guid, listFields) {
        self.SafeAjax({
            type: "PATCH",
            contentType: "application/json",
            url: "/_api/" + entity + "(" + guid + ")",
            data: JSON.stringify(listFields),
            success: function (data, textStatus, xhr) {
                console.log("Record updated");
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log(xhr);
            }
        });
    }

    self.Get = function (urlsite, entity, guid, listFields) {
        self.SafeAjax({
            type: "GET",
            contentType: "application/json",
            url: "/_api/" + entity + "(" + guid + ")",
            data: JSON.stringify(listFields),
            success: function (data, textStatus, xhr) {
                console.log("Get executed");
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log(xhr);
            }
        });
    }

};
