var customFieldHelper = {

    bindCustomField: function (customFields, formId) {
        var fields = $(formId).find("[name*='CustomFields']");
        $.each(fields, function (index, field) {
            for (var i = 0; i < customFields.length; i++) {
                var field = $(field);
                var fieldId = field.data("field");
                var customField = customFields[i].CustomField;
                if (fieldId == customField.FieldId ) {

                    if (customField.Values.length <= 0) {
                        customField.Values = [];
                    }

                    if (field.attr("type") == "checkbox" || field.attr("type") == "radio") {
                        if (customField.Values.indexOf(field[0].value) != -1) {
                            field[0].checked = true;
                        } else {
                            field[0].checked = false;
                        }
                    } else {
                        field.val(customField.Values[0]);
                    }
                } 
            }
        });
        return site.params.isUnlimited;
    },

    initCustomField: function (formId) {
        var fields = $(formId).find("[name*='CustomField.Value']");
        $.each(fields, function (index, field) {
            if (field.tagName == "INPUT" && (field.type == "checkbox" || field.type == "radio")) {
                field.checked = false;
            } else {
                $(field).val("");
            }
        });
    },
}
var dateHelper = {

    convert: function (date) {
        var date1 = null;
        if (date != "") {
            year = date.replace(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/, '$3');
            month = date.replace(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/, '$2');
            day = date.replace(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/, '$1');
            hours = date.replace(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/, '$4');
            minutes = date.replace(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/, '$5');
            date1 = new Date(year, month, day, hours, minutes, 0, 0);
        }
        return date1;
    },

    compare: function (date1, date2) {
        if (date1 instanceof Date && date2 instanceof Date) {
            return date1.getTime() <= date2.getTime();

        } else {
            return true;

        }
    },
    date: function (s) {
        if (s == null || s == undefined)
            return "";
        return new Date(parseFloat(/Date\(([^)]+)\)/.exec(s)[1]));
    },
    formatNumber: function (s) {

        if (s < 10 && s.toString().length < 2) {
            return "0" + s;
        }

        return s;
    },

    dateFormat: function (s) {
        date = dateHelper.date(s);

        return dateHelper.formatNumber(date.getDate()) + "/" + dateHelper.formatNumber((date.getMonth() + 1)) + "/" + date.getFullYear() + " " + dateHelper.formatNumber(date.getHours()) + ":" + dateHelper.formatNumber(date.getMinutes());
    }
}
var zoningHelper = {

    tip: '<img src="/Content/themes/metro/images/button_red.gif" alt="">',
    form: null,
    checkConflict: true,
    labelZones: "",
    labelSurZones: "",
    labelDefaultZones: "",

    init: function (form, zones, checkConflict, labelZones, labelSurZones, labelDefaultZones) {
        if(checkConflict != undefined) {
            zoningHelper.checkConflict = checkConflict;
        }
        zoningHelper.labelZones = labelZones;
        zoningHelper.labelSurZones = labelSurZones;
        zoningHelper.labelDefaultZones = labelDefaultZones;

        zoningHelper.form = form;
        zoningHelper.displayZonning(zones);
        $(".table-click tbody tr input[type='checkbox']").click(function () { zoningHelper.tableClick(this); });
    },

    displayZonning: function (zones) {
        zoningHelper.form.find(".zoning").html("");

        var contentZone = contentSurZone = "";
        var tables = $("<div><div class='row'></div></div>");
        if (zones.length > 0) {
            for (var i = 0; i < zones.length; i++) {
                var y = zones[i];
                if (y.SurZoning) {
                    contentSurZone += "<tr>";
                    contentSurZone += "<td onclick='$(this).parent().find(\"input\").click()'>" + y.Code + "</td>";
                    contentSurZone += "<td onclick='$(this).parent().find(\"input\").click()' class='zoneName'>" + y.Name + "</td>";
                    contentSurZone += "<td><input type='checkbox' data-code='" + y.Code + "' data-default='" + y.IsDefault + "' class='check pull-right' id='check_" + y.ZoneId + "' name='" + y.ZoneId + "' /></td>";
                    contentSurZone += "<td class='alert-container'></td>";
                    contentSurZone += "</tr>";
                } else {
                    contentZone += "<tr>";
                    contentZone += "<td onclick='$(this).parent().find(\"input\").click()'>" + y.Code + "</td>";
                    contentZone += "<td onclick='$(this).parent().find(\"input\").click()' class='zoneName'>" + y.Name + "</td>";
                    contentZone += "<td><input type='checkbox' data-code='" + y.Code + "' data-default='" + y.IsDefault + "' class='check pull-right' id='check_" + y.ZoneId + "' name='" + y.ZoneId + "' /></td>";
                    contentZone += "<td class='alert-container'></td>";
                    contentZone += "</tr>";
                }
            }
            var tableZone = "<div class='col-xs-6'><table class='table table-click table-full'><caption>" + zoningHelper.labelZones + "</caption></tr></thead>" + contentZone + "</table></div>";
            var tableSurZone = "<div class='col-xs-6'><table class='table table-full table-click orga-surzone'><caption>"+ zoningHelper.labelSurZones + "</caption>" + contentSurZone + "<tr><td colspan=4 style='padding:0px'>";
            if (zoningHelper.checkConflict) {
                tableSurZone += "<button style='margin:0px;' class='btn btn-grey btn-block' id='default-zoning' onclick='return zoningHelper.zoneDefault(this)'>"+ zoningHelper.labelDefaultZones + "</button>";
            }
            tableSurZone += "</td></tr></table></div>";
            if (contentZone != "") {
                tables.find(".row").append(tableZone);
            }

            if (contentSurZone != "") {
                tables.find(".row").append(tableSurZone)
            }

        }
        zoningHelper.form.find('.zoning').html(tables.html());
    },

    setDefault: function(zoneDefaults) {
        var form = zoningHelper.form;
        var checks = form.find("[id*='check_']");
        var selected = [];
        for (var i = 0; i < checks.length; i++) {
            var check = $(checks[i]);

            var tr = check.parents("tr").first();
            var code = check.data("code");
            var id = check.attr("name");
            tr.find(".alert-container").html("");
            if (zoneDefaults.indexOf(String(code)) != -1) {
                selected.push({ ZoneId: id });
                check.attr("data-default", "true");
                $.data(checks[i], "default", "true");
            } else {
                check.attr("data-default", "false");

                $.data(checks[i], "default", "false");
            }
        }
        zoningHelper.setValues(selected);
    },

    setValues: function (zones) {
        zoningHelper.form.find("[id*='check_']").each(function () {
            this.checked = false;
            zoningHelper.tableClick(this);
        });
        
        for (var z in zones) {
            zoningHelper.form.find("#check_" + zones[z].ZoneId).each(function () {
                this.checked = true;
                zoningHelper.tableClick(this);
            });
        }
    },
  
    tableClick: function (elem) {
        var tr = $(elem).closest("tr");
        var isDefault = $(elem).data("default");
        if (elem.checked) {
            if (isDefault == "true" || isDefault == true) {
                tr.find(".alert-container").html("");
            } else if (zoningHelper.checkConflict) {
                tr.find(".alert-container").html(zoningHelper.tip);
            }
            tr.addClass("success");
        } else {
            if (zoningHelper.checkConflict && (isDefault == "true" || isDefault == true)) {
                tr.find(".alert-container").html(zoningHelper.tip);
            } else {
                tr.find(".alert-container").html("");
            }
            tr.removeClass("success");
        }
    },

    zoneDefault: function (elem) {
        var form = $(elem).parents("form").first();
        var functionId = form.find("select[id*='FunctionId']").val();
        if (functionId == undefined) {
            jAlert("Aucune fonction n'a été trouvée : L'application est mal configurée", resources.Warning);
        } else {
            $.ajax({
                type: "POST",
                url: 'Zone/Default',
                dataType: "json",
                data: { fId: functionId },
                traditional: true,
                success: function (ret) {
                    var selected = [];
                    for (var z in ret.zones) {
                        selected.push({ ZoneId: ret.zones[z] });
                    }
                    zoningHelper.setValues(selected);
                }
            });
        }
        return false;
    },
}
var administrationValidator = {

    init: function (params) {
        $.extend(this.params, params);
        $.validator.addMethod("compareDate", administrationValidator.compareDate, resourcesMessages.CompareDate);
        $.validator.addMethod("compareEmpty", administrationValidator.compareEmpty, "Le champ est requis.");

        $.validator.addMethod("checkUniciteCodeEvent", administrationValidator.checkUniciteCodeEvent, resourcesMessages.CheckUniciteCodeEvent);
        $.validator.addMethod("canEditOrganization", administrationValidator.canEditOrganization, resourcesMessages.ErrorOrganizationEditDisabled);

        $.validator.addMethod("checkUniciteProvider", administrationValidator.checkUniciteProvider, resourcesMessages.CheckUniciteProvider);
        $.validator.addMethod("checkUniciteProviderOnAdd", administrationValidator.checkUniciteProviderOnAdd, resourcesMessages.CheckUniciteProviderOnAdd);

        $.validator.addMethod("checkUniciteUser", administrationValidator.checkUniciteUser, resourcesMessages.CheckUniciteUser);
        $.validator.addMethod("checkUniciteUserOnAdd", administrationValidator.checkUniciteUserOnAdd, resourcesMessages.CheckUniciteUserOnAdd);
        $.validator.addMethod("sameLoginInForm", administrationValidator.sameLoginInForm, resourcesMessages.CheckUniciteUserOnAdd);

        $.validator.addMethod("checkProvider", administrationValidator.checkProvider, resourcesMessages.CheckProvider);
       
        $.validator.addMethod("checkUniciteBlacklist", administrationValidator.CheckUniciteBlacklist, resourcesMessages.CheckUniciteBlacklist);
        
    },

    canEditOrganization: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Event/CanEditOrganization',
            dataType: "json",
            data: {
                eventId: form.find("input[name*='EventId']").val(),
                organizationId: form.find("select[name*='OrganizationId']").val()
            },
            traditional: true,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    checkUniciteCodeEvent: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Event/CheckUniciteCodeEvent',
            dataType: "json",
            data: {
                eventCode: form.find("input[name*='EventCode']").val(),
                eventId: form.find("input[name*='EventId']").val()
            },
            traditional: true,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        return verif;
    },

    checkProvider: function (value, element) {
        var form = $(element).parents("form").first();

        var providerId = form.find("[id*='_ProviderId']").val();
        var parentProviderId = form.find("[id*='_ParentProviderId']").val();

        if (providerId == parentProviderId) {
            return false;
        } else {
            return true;
        }
    },

    checkUniciteProvider: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Provider/CheckUnicite',
            dataType: "json",
            data: {
                providerId: form.find("[id*='_ProviderId']").val(),
                name: form.find("[id*='_Name']").val()
            },
            traditional: true,
            async: false,
            success: function (result) {
                var donnees = typeof JSON != 'undefined' ? JSON.parse(result) : eval('(' + result + ')');
                verif = donnees["bool"];
            }
        });
        return verif;
    },

    checkUniciteProviderOnAdd: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Provider/CheckUniciteOnAdd',
            dataType: "json",
            data: { name: form.find("#Provider_Name").val() },
            traditional: true,
            async: false,
            success: function (result) {
                var donnees = typeof JSON != 'undefined' ? JSON.parse(result) : eval('(' + result + ')');
                verif = donnees["bool"];
            }
        });

        return verif;
    },

    checkUniciteUser: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        var model = {
            userId: form.find("#UserId").val(),
            login: form.find("#Login").val()
        };

        $.ajax({
            type: "POST",
            url: 'User/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    checkUniciteUserOnAdd: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        var model = {
            login: $(element).val()
        };
        $.ajax({
            type: "POST",
            url: 'User/CheckUniciteOnAdd',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    sameLoginInForm: function (value, element) {
        var form = $(element).parents("form").first();
        var loginFields = form.find("[id*='Login']");
        var id = $(element).attr("id");
        var value = $(element).val();
        for(var i = 0; i < loginFields.length ; i++) {
            var jQfield = $(loginFields[i]);
            if (jQfield.val() == value && jQfield.attr("id") != id) {
                return false;
            }
        }
        return true;
    },

    CheckUniciteBlacklist: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;

        $.ajax({
            type: "POST",
            url: 'Blacklist/CheckUnicite',
            dataType: "json",
            data: form.serialize(),
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    /*************************** GENERIC ************************/

    compareDate: function (value, element) {

        //check if the start date is before end date
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Event/compareDate',
            dataType: "json",
            data: {
                startDate: form.find("input[name*='StartingDate']").val(),
                endDate: form.find("input[name*='EndingDate']").val()

            },
            traditional: true,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        return verif;

    },

    compareEmpty: function (value, element) {
        $(element).attr("title", ""); // bug fix pour afficher le message d'erreur du validateur compareEmpty

        return value != -1 && value != "";
    }
}
var categoryValidator = {

    init: function () {
        $.validator.addMethod("checkUniciteCategory", categoryValidator.checkUnicite, resourcesMessages.CheckUniciteCategory);
    },


    checkUnicite: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "GET",
            url: 'Category/CheckUnicite',
            dataType: "json",
            data: { Name: form.find("[id*='_Name']").val(), CategoryId: form.find("[id*='_CategoryId']").val() },
            traditional: true,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        return verif;
    }
}
var individualValidator = {


    init: function (params) {
        $.extend(this.params, params);

        $.validator.addMethod("checkUniciteIndividual", individualValidator.checkUniciteIndividual, resourcesMessages.CheckUniciteIndividual);
        $.validator.addMethod("checkUniciteOnAddIndividual", individualValidator.checkUniciteOnAddIndividual, resourcesMessages.CheckUniciteOnAddIndividual);

    },

    checkUniciteIndividual: function (value, element) {

        var form = $(element).parents("form").first();
        var verif = false;
        var params = form.serialize();
        $.ajax({
            type: "POST",
            url: 'Individual/CheckUnicite',
            dataType: "json",
            data: params,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    checkUniciteOnAddIndividual: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        var params = form.serialize();

        $.ajax({
            type: "POST",
            url: 'Individual/CheckUniciteOnAdd',
            dataType: "json",
            data: params,
            async: false,
            traditional: true,
            success: function (result) {
                verif = result.Success;                
            }
        });
        return verif;
    },
}
var mockupValidator = {

    init: function () {
        $.validator.addMethod("isBackgroundMockupUnique", mockupValidator.isBackgroundMockupUnique, resourcesMessages.CheckUniciteBackground);
        $.validator.addMethod("imageRequired", mockupValidator.imageRequired, resourcesMessages.ImageRequired);
    },


    isBackgroundMockupUnique: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = "";
        if (form.hasClass("addForm")) {
            model = form.serializeObject("BackgroundMockupAdd");
        } else {
            model = form.serializeObject("BackgroundMockupEdit");
        }
        $.ajax({
            type: "POST",
            url: 'Mockup/IsBackgroundMockupUnique',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        if (verif == true) {
            return true;
        } else {
            return false;
        }
    },

    imageRequired: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = "";
        if (form.hasClass("addForm")) {
            model = form.serializeObject("BackgroundMockupAdd");
        } else {
            model = form.serializeObject("BackgroundMockupEdit");
        }
    
        var imageName = form.find(".nameFile").val();
        if (model.BackgroundMockupId == "" && imageName == "") {
            return false;
        }
        return true;
    }
}
var moncompteValidator = {

    params : {
        passwordStrengthRegularExpression: "",
        minRequiredPasswordLength: null
    },

    init: function (params) {
        $.extend(this.params, params);

        $.validator.addMethod("comparePasswordComfirm", moncompteValidator.comparePasswordComfirm, resourcesMessages.ComparePasswordComfirm);
        $.validator.addMethod("checkComplexityPassword", moncompteValidator.checkComplexityPassword,resourcesMessages.CheckComplexityPassword);
        $.validator.addMethod("checkLengthPassword", moncompteValidator.checkLengthPassword, resourcesMessages.CheckLengthPassword);
        $.validator.addMethod("checkOldPassword", moncompteValidator.checkOldPassword, resourcesMessages.InvalidPassword);

    },

    comparePasswordComfirm: function (value, element) {
        var srz = $(element).parents("form").first().find("input#PasswordModel_NewPassword");
        if (value != srz.val()) {
            responce = false;
        } else {
            responce = true;
        }
        return responce;
    },

    checkOldPassword: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = {
            password: $(element).parents("form").first().find("input#PasswordModel_OldPassword").val()
        };

        $.ajax({
            type: "POST",
            url: 'MonCompte/CheckPassword',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        return verif;
    },

    checkComplexityPassword: function (value, element) {
        var srz = $(element).parents("form").first().find("input#PasswordModel_NewPassword").val();
        var myRegex = new RegExp(moncompteValidator.params.passwordStrengthRegularExpression);
        if (myRegex.test(srz)) {
            responce = true;
        } else {
            responce = false;
        }
        return responce;
    },

    checkLengthPassword: function (value, element) {
        var srz = $(element).parents("form").first().find("input#PasswordModel_NewPassword").val();
        if (moncompteValidator.params.minRequiredPasswordLength != null) {
            if (srz.length >= moncompteValidator.params.minRequiredPasswordLength) {
                responce = true;
            } else {
                responce = false;
            }
        } else {
            responce = true;
        }
        return responce;
    }
}
var organizationValidator = {

    init: function () {
        $.validator.addMethod("checkUniciteOnEdit", organizationValidator.checkUniciteOnEdit, resourcesMessages.CheckUniciteOnEdit);
        $.validator.addMethod("checkUniciteOnAdd", organizationValidator.checkUniciteOnAdd, resourcesMessages.CheckUniciteOnAdd);
        $.validator.addMethod("checkUniciteFunction", organizationValidator.checkUniciteFunction, resourcesMessages.CheckUniciteFunction);
        $.validator.addMethod("checkUniciteUnit", organizationValidator.checkUniciteUnit, resourcesMessages.CheckUniciteUnit);
        $.validator.addMethod("checkUniciteUnitOnAdd", organizationValidator.checkUniciteUnitOnAdd, resourcesMessages.CheckUniciteUnitOnAdd);
        $.validator.addMethod("checkUniciteCode", organizationValidator.checkUniciteCode, resourcesMessages.CheckUniciteCode);
    },

    /**************************** ORGANISATION ***********************/

    checkUniciteOnEdit: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        var model = {
            name: form.find("[name*='Name']").val(),
            id: form.find("[name*='OrganizationId']").val()
        };
        $.ajax({
            type: "POST",
            url: 'Organization/CheckUniciteOnEdit',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        if (verif == true) {
            return true;
        } else {
            return false;
        }
    },

    checkUniciteOnAdd: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        var model = {
            name: form.find("[name*='Name']").val()
        };
        $.ajax({
            type: "POST",
            url: 'Organization/CheckUniciteOnAdd',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        // Gestion des erreurs
        return verif;
    },

    /***************************** FUNCTION ***************************/

    checkUniciteFunction: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = {
            FunctionName: form.find("input[name='Function.FunctionName']").val(),
            OrganizationId: $("#Organization_OrganizationId").val(),
            FunctionId: form.find("input[name='Function.FunctionId']").val()
        };

        $.ajax({
            type: "POST",
            url: 'ProfileNew/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        if (verif == true) {
            return true;
        } else {
            return false;
        }
    },

    /******************************** UNIT ****************************/

    checkUniciteUnit: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();

        var model = {
            OrganizationUnitName: form.find("input[name='OrganizationUnit.OrganizationUnitName']").val(),
            OrganizationId: $("#Organization").val(),
            OrganizationUnitId: form.find("input[name='OrganizationUnit.OrganizationUnitId']").val(),
            OrganizationUnitIdParent: $("#tabs-unit-property .editOrganizationUnit #OrganizationUnit_OrganizationUnitId").val()
        };

        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    checkUniciteUnitOnAdd: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();

        var model = {
            OrganizationId: $("#Organization").val(),
            OrganizationUnitName: form.find("input[name='OrganizationUnit.OrganizationUnitName']").val(),
            OrganizationUnitId: form.find("input[name='OrganizationUnit.OrganizationUnitId']").val(),
            OrganizationUnitIdParent: $("#tabs-unit-property .editOrganizationUnit #OrganizationUnit_OrganizationUnitId").val()
        };

        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    },

    /***************************** CODE REPERE ************************/

    checkUniciteCode: function (value, element) {
        var verif = false;

        var form = $(element).parents("form").first();
        var model = {
            OrganizationId: $("#Organization").val(),
            referenceCode: form.find("input[name='ReferenceCode.ReferenceCode']").val()
        };
        $.ajax({
            type: "POST",
            url: 'ReferenceCode/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });
        return verif;
    }

}
var profileValidator = {

    init: function () {
        $.validator.addMethod("checkUniciteFunction", organizationValidator.checkUniciteFunction, resourcesMessages.CheckUniciteFunction);
    },


    checkUniciteFunction: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = {
            FunctionName: form.find("input[name*='Name']").val(),
            OrganizationId: form.find("[name*='OrganizationId']").val(),
            FunctionId: form.find("input[name*='FunctionId']").val()
        };

        $.ajax({
            type: "POST",
            url: 'Profile/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        if (verif == true) {
            return true;
        } else {
            return false;
        }
    }
}
var sportValidator = {

    init: function () {
        $.validator.addMethod("checkUniciteSport", sportValidator.checkUnicite, resourcesMessages.CheckUniciteSport);
    },


    checkUnicite: function (value, element) {
        var form = $(element).parents("form").first();
        var verif = false;
        $.ajax({
            type: "POST",
            url: 'Sport/CheckUnicite',
            dataType: "json",
            data: { Name: form.find("[id*='_Name']").val(), SportId: form.find("[id*='_SportId']").val() },
            traditional: true,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        return verif;
    }
}
var zoneValidator = {

    init: function () {
        $.validator.addMethod("verifySurZoneCode", zoneValidator.verifySurZoneCode, resourcesMessages.VerifySurZoneCode);
        $.validator.addMethod("checkUniciteZone", zoneValidator.checkUniciteZone, resourcesMessages.CheckUniciteZone);
    },



    verifySurZoneCode: function (value, element) {
        var responce = false;
        var reg = new RegExp('[ \t\r\n\v\f]');

        if (value.length < 6 && !reg.test(value)) {
            responce = true;
        } else {
            responce = false;
        }

        return responce;

    },

    checkUniciteZone: function (value, element) {
        var verif = false;
        var form = $(element).parents("form").first();
        var model = {
            Code: form.find("[id*='Code']").val(),
            OrganizationId: form.find("[id*='OrganizationId']").val(),
            ZoneId: form.find("[id*='ZoneId']").val()
        };

        $.ajax({
            type: "POST",
            url: 'ZoneNew/CheckUnicite',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                verif = result.Success;
            }
        });

        if (verif == true) {
            return true;
        } else {
            return false;
        }
    },
}
angular.module('accreditationApp', [
    'ngRoute',
    'ngResource',
    'ngSanitize',
    'ngAnimate',
    'ui.select',
    'ui.grid.selection',
    'ui.grid.pagination',
    'ui.grid.autoResize',
    'ui.grid.resizeColumns',
    'ui.grid.expandable',
    'ui.grid.pinning',
    'hierarchical-selector',
    'ui.validate',
    'ui.date',
    'ui.bootstrap',
    'pdf',
    'ngFileUpload',
    'angular-scroll-complete'
])
    .config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {

        var softwareVersion = site.params.softwareVersion;
        $routeProvider
            .when('/importAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/ImportAssignmentForm.html?ver=" + softwareVersion,
                controller: 'importAssignmentFormController'
            })
            .when('/createIndividualAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AssignmentForm.html?ver=" + softwareVersion,
                controller: 'assignmentFormController'
            })
            .when('/createGuestAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/GuestAssignmentForm.html?ver=" + softwareVersion,
                controller: 'guestAssignmentFormController'
            })
            .when('/createGuestAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/GuestAssignmentForm.html?ver=" + softwareVersion,
                controller: 'guestAssignmentFormController'
            })
            .when('/createAnonymousAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AnonymousAssignmentForm.html?ver=" + softwareVersion,
                controller: 'anonymousAssignmentFormController'
            })
            .when('/createIndividualAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AssignmentForm.html?ver=" + softwareVersion,
                controller: 'assignmentFormController'             
            })
            .when('/cloneIndividualAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AssignmentForm.html?ver=" + softwareVersion,
                controller: 'assignmentFormController'
            })
            .when('/cloneGuestAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/GuestAssignmentForm.html?ver=" + softwareVersion,
                controller: 'guestAssignmentFormController'
            })
            .when('/cloneVehicleAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/VehicleAssignmentForm.html?ver=" + softwareVersion,
                controller: 'vehicleAssignmentFormController'
            })
            .when('/createIndividualAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AssignmentForm.html?ver=" + softwareVersion,
                controller: 'assignmentFormController'
            })
            .when('/modifyIndividualAssignments/:assignmentsIds', {
                templateUrl: "/Scripts/Angular/Assignment/Views/AssignmentsForm.html?ver=" + softwareVersion,
                controller: 'assignmentsFormController',
                resolve: {
                    assignmentsIds: ['$route', function ($route) {
                        return $route.current.params.assignmentsIds;
                    }],
                }
            })
            .when('/modifyGuestAssignments/:assignmentsIds', {
                templateUrl: "/Scripts/Angular/Assignment/Views/GuestAssignmentsForm.html?ver=" + softwareVersion,
                controller: 'guestAssignmentsFormController',
                resolve: {
                    assignmentsIds: ['$route', function ($route) {
                        return $route.current.params.assignmentsIds;
                    }],
                }
            })
            .when('/modifyVehicleAssignments/:assignmentsIds', {
                templateUrl: "/Scripts/Angular/Assignment/Views/VehicleAssignmentsForm.html?ver=" + softwareVersion,
                controller: 'vehicleAssignmentsFormController',
                resolve: {
                    assignmentsIds: ['$route', function ($route) {
                        return $route.current.params.assignmentsIds;
                    }],
                }
            })

            .when('/createVehicleAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/VehicleAssignmentForm.html?ver=" + softwareVersion,
                controller: 'vehicleAssignmentFormController'
            })
            .when('/createVehicleAssignment/:assignmentId', {
                templateUrl: "/Scripts/Angular/Assignment/Views/VehicleAssignmentForm.html?ver=" + softwareVersion,
                controller: 'vehicleAssignmentFormController'
            })
            .when('/validateAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/ValidationForm.html?ver=" + softwareVersion,
                controller: 'validationFormController'
            })
            .when('/validatePass', {
                templateUrl: "/Scripts/Angular/Pass/Views/ValidationForm.html?ver=" + softwareVersion,
                controller: 'validationPassFormController'
            })
            //.when('/printAssignment', {
            //    templateUrl: "/Scripts/Angular/Assignment/Views/PrintForm.html?ver=" + softwareVersion,
            //    controller: 'printFormController'
            //})
            .when('/mailAssignment', {
                templateUrl: "/Scripts/Angular/Assignment/Views/MailForm.html?ver=" + softwareVersion,
                controller: 'mailFormController'
            })
            .when('/messageAssignment', {
                templateUrl: "/Scripts/Angular/Shared/Views/MessageForm.html?ver=" + softwareVersion,
                controller: 'messageFormController'
            })

            .when('/assignmentList/:openEventModal?', {
                templateUrl: "/Scripts/Angular/Assignment/Views/List.html?ver=" + softwareVersion,
                controller: 'assignmentListController'
            })
            .when('/assignmentList/search/:barcode', {
                templateUrl: "/Scripts/Angular/Assignment/Views/List.html?ver=" + softwareVersion,
                controller: 'assignmentListController'
            })
            .when('/createIndividual', {
                templateUrl: "/Scripts/Angular/Individual/Views/IndividualForm.html?ver=" + softwareVersion,
                controller: 'individualFormController',
                resolve: {
                    individualId: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                }
            })
            .when('/createIndividual/:individualId', {
                templateUrl: "/Scripts/Angular/Individual/Views/IndividualForm.html?ver=" + softwareVersion,
                controller: 'individualFormController',
                resolve: {
                    individualId: ['$route', function ($route) {
                        return $route.current.params.individualId;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }],
                }
            })
            .when('/individualList', {
                templateUrl: "/Scripts/Angular/Individual/Views/List.html?ver=" + softwareVersion,
                controller: 'individualListController'
            })
            .when('/importIndividual', {
                templateUrl: "/Scripts/Angular/Individual/Views/ImportIndividualForm.html?ver=" + softwareVersion,
                controller: 'importIndividualFormController'
            })
            .when('/importVehicle', {
                templateUrl: "/Scripts/Angular/Vehicle/Views/ImportVehicleForm.html?ver=" + softwareVersion,
                controller: 'importVehicleFormController'
            })
            .when('/vehicleList', {
                templateUrl: "/Scripts/Angular/Vehicle/Views/List.html?ver=" + softwareVersion,
                controller: 'vehicleListController'
            })
            .when('/createVehicle', {
                templateUrl: "/Scripts/Angular/Vehicle/Views/VehicleForm.html?ver=" + softwareVersion,
                controller: 'vehicleFormController',
                resolve: {
                    vehicleId: ['$route', function ($route) {
                        return undefined;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }]
                }
            })
            .when('/createVehicle/:vehicleId', {
                templateUrl: "/Scripts/Angular/Vehicle/Views/VehicleForm.html?ver=" + softwareVersion,
                controller: 'vehicleFormController',
                resolve: {
                    vehicleId: ['$route', function ($route) {
                        return $route.current.params.vehicleId;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }]
                }
            })
            .when('/passList', {
                templateUrl: "/Scripts/Angular/Pass/Views/List.html?ver=" + softwareVersion,
                controller: 'passListController'
            })
            .when('/createPass', {
                templateUrl: "/Scripts/Angular/Pass/Views/PassForm.html?ver=" + softwareVersion,
                controller: 'passFormController',
                resolve: {
                    passId: ['$route', function ($route) {
                        return undefined;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }]
                }
            })
            .when('/createPass/:passId', {
                templateUrl: "/Scripts/Angular/Pass/Views/PassForm.html?ver=" + softwareVersion,
                controller: 'passFormController',
                resolve: {
                    passId: ['$route', function ($route) {
                        return $route.current.params.vehicleId;
                    }],
                    $uibModalInstance: ['$route', function ($route) {
                        return undefined;
                    }],
                    provider: ['$route', function ($route) {
                        return undefined;
                    }]
                }
            })
            //path for passes
            .when('/createIndividualPass', {
                templateUrl: "/Scripts/Angular/Pass/Views/PassForm.html?ver=" + softwareVersion,
                controller: 'passFormController'
            })
            .when('/createIndividualPass/:passId', {
                templateUrl: "/Scripts/Angular/Pass/Views/PassForm.html?ver=" + softwareVersion,
                controller: 'passFormController'
            })

            .when('/createVehiclePass', {
                templateUrl: "/Scripts/Angular/Pass/Views/VehiclePassForm.html?ver=" + softwareVersion,
                controller: 'vehiclePassFormController'
            })

            .when('/createVehiclePass/:passId', {
                templateUrl: "/Scripts/Angular/Pass/Views/VehiclePassForm.html?ver=" + softwareVersion,
                controller: 'vehiclePassFormController'
            })
            .when('/createGuestPass', {
                templateUrl: "/Scripts/Angular/Pass/Views/GuestPassForm.html?ver=" + softwareVersion,
                controller: 'guestPassFormController'
            })
            .when('/createGuestPass/:passId', {
                templateUrl: "/Scripts/Angular/Pass/Views/GuestPassForm.html?ver=" + softwareVersion,
                controller: 'guestPassFormController'
            })
            .when('/printPass', {
                templateUrl: "/Scripts/Angular/Pass/Views/PrintPassForm.html?ver=" + softwareVersion,
                controller: 'printPassFormController'
            })
            .when('/importPass', {
                templateUrl: "/Scripts/Angular/Pass/Views/ImportPassForm.html?ver=" + softwareVersion,
                controller: 'importPassFormController'
            })
            .when('/Notify', {
                templateUrl: "/Scripts/Angular/Pass/Views/NotifyForm.html?ver=" + softwareVersion,
                controller: 'notifyFormController'
            })
            .otherwise({ redirectTo: '/assignmentList' });
        $httpProvider.interceptors.push('redirectInterceptor');

    }]).run(['$rootScope', function ($rootScope) {
        $rootScope.resources = resources;
        $rootScope.resourcesMessages = resourcesMessages;
        $rootScope.right = right;
        $rootScope.dateFormat = $.datepicker._defaults.dateFormat;
        $rootScope.softwareVersion = site.params.softwareVersion;
        $rootScope.isUserZoneModificationActive = site.params.isUserZoneModificationActive;
        $rootScope.displayZoneImage = site.params.displayZoneImage;
        $rootScope.isDailyAccreditationActive = site.params.isDailyAccreditationActive;
        $rootScope.multizoneVehicle = site.params.multizoneVehicle;

    }]).factory('redirectInterceptor', ['$location', function ($location) {
        var errorService = {
            response: function (response) {
                if (response.data && response.data.PermissionDenied) {
                    window.location.href = '/Home/Index';
                }
                return response;
            }
        };
        return errorService;
    }]);
    

angular.module('accreditationApp')
    .controller('contextController', ['$scope', '$filter', '$q', 'eventService', 'unitService', 'contextService', function ($scope, $filter, $q, eventService, unitService, contextService) {

        angular.extend(this, $controller('baseController', { $scope: $scope }));

        $scope.currentPage = contextService.currentPage;
        $scope.isContextualCollapsed = false;
        $scope.form = {
            eventId: null
        };
        $scope.statistics = [];
        $scope.currentEvent = contextService.event;

        $scope.events = [{ EventName: resourcesMessages.ChangeEvent, EventId: null }];
        $scope.getEvents = function (search) {
            $scope.events.splice(1, $scope.events.length);
            return eventService.getEvents({ Name: search }).success(function (events) {
                angular.forEach(events,
                    function (value, key) {
                        if (value.Selected) {
                            $scope.getEventConfiguration(value.EventId);
                            contextService.setContext(value.EventId);
                        }
                        $scope.events.push(value);
                    });
            });
        };

        $scope.collapse = function () {
            $scope.isContextualCollapsed = !$scope.isContextualCollapsed;
            if ($scope.isContextualCollapsed) {
                contextService.getAssignmentStatistics($scope.currentEvent.EventId).success(function (statistics) {
                    //location.reload();
                    $scope.statistics = statistics;
                });
            }

        };

        $scope.getEventConfiguration = function (eventId) {
            eventService.getEventConfiguration(eventId).success(function (configuration) {
                contextService.steps.splice(0, contextService.steps.length);
                contextService.profiles.splice(0, contextService.profiles.length);
                contextService.units.splice(0, contextService.units.length);
                contextService.zones.splice(0, contextService.zones.length);
                contextService.surZones.splice(0, contextService.surZones.length);
                contextService.nationalities.splice(0, contextService.nationalities.length);
                contextService.searchAssignmentTypes.splice(0, contextService.searchAssignmentTypes.length);
                contextService.createAssignmentTypes.splice(0, contextService.createAssignmentTypes.length);
                contextService.searchPassTypes.splice(0, contextService.searchPassTypes.length);
                contextService.createPassTypes.splice(0, contextService.createPassTypes.length);
                contextService.deliveryPlaces.splice(0, contextService.deliveryPlaces.length);
                contextService.mockups.splice(0, contextService.mockups.length);
                contextService.individualCustomFields.splice(0, contextService.individualCustomFields.length);
                contextService.vehicleCustomFields.splice(0, contextService.vehicleCustomFields.length);

                var ev = $filter('filter')($scope.events, { EventId: eventId })[0];
                contextService.event.EventId = ev.EventId;
                contextService.event.OrganizationId = ev.OrganizationId;
                contextService.event.EventName = ev.EventName;
                contextService.event.ImageName = ev.ImageName;
                contextService.event.LogoName = ev.LogoName;
                contextService.event.IsMailCampaignOpen = ev.IsMailCampaignOpen;
                contextService.previewmockup = configuration.previewmockup;
                contextService.event.AllowEditAssignmentsAccess = ev.AllowEditAssignmentsAccess;
                contextService.event.IsGroup = ev.IsGroup;
                contextService.event.CanSendIndividualTitleByMail = ev.EnableIndividualTitleSendingByMail;
                contextService.event.CanSendVehicleTitleByMail = ev.EnableVehicleTitleSendingByMail;
                contextService.event.CanSendAnonymousTitleByMail = ev.EnableAnonymousTitleSendingByMail;
                contextService.event.CanSendGuestTitleByMail = ev.EnableAnonymousTitleSendingByMail;
                angular.forEach(configuration.searchAssignmentTypes, function (value, key) {
                    contextService.searchAssignmentTypes.push(value);
                });
                angular.forEach(configuration.createAssignmentTypes, function (value, key) {
                    contextService.createAssignmentTypes.push(value);
                });
                angular.forEach(configuration.passTypes, function (value, key) {
                    contextService.searchPassTypes.push(value);
                });
                angular.forEach(configuration.passTypes, function (value, key) {
                    contextService.createPassTypes.push(value);
                });
                angular.forEach(configuration.steps, function (value, key) {
                    contextService.steps.push(value);
                });
                angular.forEach(configuration.profiles, function (value, key) {
                    contextService.profiles.push(value);
                });
                angular.forEach(configuration.units, function (value, key) {
                    contextService.units.push(value);
                });
                angular.forEach(configuration.nationalities, function (value, key) {
                    contextService.nationalities.push(value);
                });
                angular.forEach(configuration.vehicleTypes, function (value, key) {
                    contextService.vehicleTypes.push(value);
                });
                angular.forEach(configuration.vehicleBrands, function (value, key) {
                    contextService.vehicleBrands.push(value);
                });
                angular.forEach(configuration.deliveryPlaces, function (value, key) {
                    contextService.deliveryPlaces.push(value);
                });
                angular.forEach(configuration.individualCustomFields, function (value, key) {
                    contextService.individualCustomFields.push(value);
                });
                angular.forEach(configuration.vehicleCustomFields, function (value, key) {
                    contextService.vehicleCustomFields.push(value);
                });

                angular.forEach(configuration.accreditationInputs, function (value, key) {
                    contextService.accreditationInputs.push(value);
                });

                angular.forEach(configuration.multipleAccreditationInputs, function (value, key) {
                    contextService.multipleAccreditationInputs.push(value);
                });

                angular.forEach(configuration.mockups, function (value, key) {
                    contextService.mockups.push(value);
                });

                angular.forEach($filter('filter')(configuration.zones), function (value, key) {
                    contextService.allZones.push(value);
                });

                angular.forEach($filter('filter')(configuration.zones, { SurZoning: false, AssignmentTypeName: "Individual" }), function (value, key) {
                    contextService.zones.push(value);
                });

                angular.forEach($filter('filter')(configuration.zones, { SurZoning: true, AssignmentTypeName: "Individual" }), function (value, key) {
                    contextService.surZones.push(value);
                });
 
            });


       
        },

            $scope.changeEvent = function (event) {
                if (event.EventId !== null) {
                    $("body").Spinner("show");
                    contextService.setContext(event.EventId).success(function () {
                        location.reload();
                    });
                }
            };
    }]);


angular.module('accreditationApp')
    .service('contextService', ['$resource', '$http', '$rootScope', function ($resource, $http, $rootScope) {

        this.user = site.user;
        if (site.user != null) {
            this.provider = { id: site.user.ProviderId, text: site.user.ProviderName, nationalityId: site.user.NationalityId };
        }

        this.openEventModal = false;
        this.AskConfirmCookies = false;
        this.currentPage = {
            index: ""
        };

        this.paginationPageSizes = [50, 100, 200, 400];

        this.assignmentStatus = {
            Validated: "Validated",
            Waiting: "Waiting",
            Refused: "Refused",
            isWaitForSuperior: "isWaitForSuperior",
            isWaitForInferior: "isWaitForInferior"
        };

        this.isModifiable = function (isUpdate, assignmentStatus) {
            return isUpdate &&
                (
                    assignmentStatus === this.assignmentStatus.Waiting ||
                    assignmentStatus === this.assignmentStatus.isWaitForSuperior ||
                    assignmentStatus === this.assignmentStatus.isWaitForInferior
                );
        };

        this.isValidable = function (assignmentStatus) {
            return (assignmentStatus !== this.assignmentStatus.isWaitForSuperior) && (assignmentStatus !== this.assignmentStatus.Validated);
        };

        this.event = site.event !== null ? site.event : {};

        this.passEvent = {};
        this.units = [],

            this.steps = [],

            this.profiles = [],

            this.individualCustomFields = [],

            this.vehicleCustomFields = [],

            this.profiles = [],

            this.vehicleTypes = [],

            this.vehicleBrands = [],

            this.nationalities = [],

            this.zones = [],

            this.surZones = [],

            this.allZones = [],

            this.passZones = [],

            this.passSurZones = [],

            this.allPassZones = [],

            this.createAssignmentTypes = [],

            this.searchAssignmentTypes = [],

            this.createPassTypes = [],

            this.searchPassTypes = [],

            this.deliveryPlaces = [],

            this.accreditationInputs = [],

            this.multipleAccreditationInputs = [],

            this.defaultPassOrganizationId = null,

            this.mockups = [],

            this.passMockups = [],

            this.previewmockup = null,

            this.getAssignmentStatistics = function (eventId) {
                return $http.post('/Assignment/GetAssignmentStatistics', { eventId: eventId });
            },

            this.getContext = function () {
                return $http.post('/Parameter/GetContextEvent');
            },

            this.setContext = function (eventId) {
                return $http.post('/Parameter/SetContextEvent', { eventId: eventId });
            },

            this.getAcceptCookies = function () {
                return $http.get('/PrivatePolicy/GetByCode?code=Cookies');
            },
            this.getRights = function () {
                var rights = {
                    CanGrantStepAccess: false,
                    CanGrantEventAccess: false
                };

                $http.get('/Parameter/CanGrantStepAccess').success(function (ret) {
                    rights.CanGrantStepAccess = ret;
                });
                $http.get('/Parameter/CanGrantEventAccess').success(function (ret) {
                    rights.CanGrantEventAccess = ret;
                });
                return rights;
            }

        this.getSmsStatus = function () {
            return $http.post('/Assignment/GetSmsStatusEnum');
        }
    }
    ]);


angular.module('accreditationApp')
    .controller('baseController', ['$scope', '$rootScope', '$filter', '$location', '$q', 'contextService', 'assignmentService', function ($scope, $rootScope, $filter, $location, $q, contextService, assignmentService) {

        /// Props
        $scope.useMultiSite = site.params.useMultiSite;
        $scope.quotasActivated = site.params.quotasActivated;
        $scope.useCarboneOffset = site.params.useCarboneOffset;
        $scope.categories = [];
        $rootScope.IsPrinting = false;
        $scope.Creator= '',
        $scope.Updater= ''
        ///  End Props

        var noResultItem = { id: '1', CategoryId: 0, HasPicture: false, IsLoading: true, Message: $rootScope.resources.NoResult };

        $scope.hasPermission = function (r) {
            return site.hasPermission(r);
        };
        $scope.hasPermissions = function (r) {
            var index;
            for (index = 0; index < r.length; ++index) {
                if (!this.hasPermission(r[index])) return false;
            }
            return true;
        };

        $scope.getCategories = function (eventId, providerId) {
            return $scope.getCategoriesByEventAndProviderIds(eventId, [providerId]);
        };
        $scope.getCategoriesByEventAndProviderIds = function (eventId, providerIds) {
            $scope.categories = [];
            assignmentService
                .getCategoriesByEventAndProviderIds(eventId, providerIds)
                .success(function (data) {
                    angular.forEach(data, function (value) {
                        $scope.categories.push(value);
                    });
                    if (data.length === 0) {
                        $scope.categories.push(noResultItem);
                    }
                });
        };
        $scope.getCategoriesByEvent = function (eventId) {
            $scope.categories = [];
            assignmentService
                .getCategoriesByEvent(eventId)
                .success(function (data) {
                    angular.forEach(data, function (value) {
                        $scope.categories.push(value);
                    });
                    if (data.length === 0) {
                        $scope.categories.push(noResultItem);
                    }
                });
        };
        $scope.useCategories = function () {
            return contextService.event.IsGroup && $scope.useMultiSite;
        };

        $scope.getAlreadyPrintedRows = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var names = [];

            angular.forEach(objs, function (value, key) {
                if (value.PrintCount > 0) {
                    names.push(value.Name + " - " + value.Provider);
                }
            });
            return names;
        };

        $scope.CanSendSelectedAssignmentByMail = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var result = true;
            angular.forEach(objs, function (value, key) {
                if (!$scope.currentEvent.CanSendIndividualTitleByMail) {
                    if (value.AssignmentTypeName === "Individual") {
                        result = false;
                        return;
                    }
                }

                if (!$scope.currentEvent.CanSendGuestTitleByMail) {
                    if (value.AssignmentTypeName === "Guest") {
                        result = false;
                        return;
                    }
                }

                if (!$scope.currentEvent.CanSendVehicleTitleByMail) {
                    if (value.AssignmentTypeName === "Vehicle") {
                        result = false;
                        return;
                    }
                }

                if (!$scope.currentEvent.CanSendAnonymousTitleByMail) {
                    if (value.AssignmentTypeName === "Anonymous") {
                        result = false;
                        return;
                    }
                }
            });
            return result;
        };


        $scope.CanSendSelectedPassByMail = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var result = true;
            angular.forEach(objs, function (value, key) {
                if (!$scope.passEvent.CanSendIndividualTitleByMail) {
                    if (value.AssignmentTypeName === "Individual") {
                        result = false;
                        return;
                    }
                }
                if (!$scope.passEvent.CanSendGuestTitleByMail) {
                    if (value.AssignmentTypeName === "Guest") {
                        result = false;
                        return;
                    }
                }

                if (!$scope.passEvent.CanSendVehicleTitleByMail) {
                    if (value.AssignmentTypeName === "Vehicle") {
                        result = false;
                        return;
                    }
                }

                if (!$scope.passEvent.CanSendAnonymousTitleByMail) {
                    if (value.AssignmentTypeName === "Anonymous") {
                        result = false;
                        return;
                    }
                }
            });
            return result;
        };
        $scope.getNowDateFormatedDDMMYYYY = function () {
            return moment().format($scope.resourcesMessages.FormatDateDDMMYYYY);
        };

        $scope.getNowHourFormatedDHHmm = function () {
            return moment(moment(), $scope.resourcesMessages.FormatHourHHmm);
        };
    }]);
angular.module('accreditationApp')
    .directive('validDate', ['$http', function ($http) {
        var toId;
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attr, ctrl) {
                //when the scope changes, check the email.
                scope.$watch(attr.ngModel, function (value) {
                    // if there was a previous attempt, stop it.
                    if (toId) clearTimeout(toId);

                    // start a new attempt with a delay to keep it from
                    // getting too "chatty".
                    toId = setTimeout(function () {

                        $http.post('/Individual/IsValidDate', { date: value }).success(function (data) {
                            //set the validity of the field
                            ctrl.$setValidity('validDate', data.isValid);
                        });
                    }, 200);
                })
            }
        }
    }]);
angular.module('accreditationApp')
    .controller('accessControlErrorsController', ['$scope', '$uibModalInstance', 'errors', '$controller', function ($scope, $uibModalInstance, errors, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.errors = errors;

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }]);


angular.module('accreditationApp')
    .controller('addReadingFormController', ['$scope', '$uibModalInstance', 'assignmentService', 'assignmentIds', '$controller',
        function ($scope, $modalInstance, assignmentService, assignmentIds, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            $scope.form = {
                ReadingDate: null,
                ReadingTime: null,
                AssignmentIds: assignmentIds,
                ReadingChoice: null
            };

            $scope.form.ReadingChoice = "entered";
            $scope.form.ReadingDate = $scope.getNowDateFormatedDDMMYYYY();
            $scope.form.ReadingTime = $scope.getNowHourFormatedDHHmm();
            $scope.anyError = false;
            $scope.errorMessage = '';
            $scope.checkAlreadyReadingEntry = false;
            $scope.assignmentsIdsToModify = [];

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };


            $scope.validate = function (checkAlreadyReadingEntry) {
                $scope.checkAlreadyReadingEntry = checkAlreadyReadingEntry;
                $scope.anyError = false;
                if (checkAlreadyReadingEntry) {
                    assignmentService.getAssignmentsWithAlreadyReadingEntry($scope.form.AssignmentIds, $scope.form.ReadingChoice).success(function (ret) {
                        if (ret.Success) {
                            $scope.assignmentsIdsToModify = ret.data;
                            if ($scope.assignmentsIdsToModify.length > 0) {
                                $scope.errorMessage = $scope.resourcesMessages.UpdateReadingsOkWithError;
                                angular.forEach(ret.data,
                                    function (value, key) {
                                        $scope.errorMessage += value + ' ; ';
                                    });

                                var assignmentIdsOK = $scope.form.AssignmentIds.filter(function (val) {
                                    return $scope.assignmentsIdsToModify.indexOf(val) === -1;
                                });

                                if (assignmentIdsOK.length > 0) {
                                    $scope.addEntry(assignmentIdsOK);
                                }

                                $scope.anyError = true;


                            } else {
                                $scope.checkAlreadyReadingEntry = false;
                                $scope.addEntry($scope.form.AssignmentIds);//if no assignmentsWithAlreadyReadingEntry we add entry for all
                            }

                        } else {
                            $scope.errorMessage = $scope.resourcesMessages.ErrorOccured;
                        }

                    });
                } else {
                    $scope.addEntry($scope.assignmentsIdsToModify);
                }
            };

            $scope.addEntry = function (assignmentIds) {
                var time = moment($scope.form.ReadingTime).format('HH:mm');
                var actionDate = moment($scope.form.ReadingDate + " " + time, "DD/MM/YYYY HH:mm").format();
                if ($scope.form.ReadingChoice == 'entered') {
                    $scope.enterAssignments(assignmentIds, actionDate);
                } else {
                    $scope.exitAssignments(assignmentIds, actionDate);
                }
            };

            $scope.enterAssignments = function (assignmentIds, actionDate) {
                assignmentService.enterAssignments(assignmentIds, actionDate).success(function (data) {
                    $scope.manageEntryResult(data);
                });
            };

            $scope.exitAssignments = function (assignmentIds, actionDate) {
                assignmentService.exitAssignments(assignmentIds, actionDate).success(function (data) {
                    $scope.manageEntryResult(data);
                });
            };

            $scope.manageEntryResult = function (result) {
                if (result.Success) {
                    if ($scope.checkAlreadyReadingEntry) {
                        //add entry OK but assignments with Entry => we just show error message
                        $scope.anyError = true;
                    } else {
                        $modalInstance.close(result);
                    }
                } else {
                    $scope.errorMessage = $scope.resourcesMessages.ErrorOccured;
                    $scope.anyError = true;
                }

            };
        }]);


angular.module('accreditationApp')
    .controller('anonymousAssignmentFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'individualService', '$controller', function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, individualService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "assignmentList";

        $scope.$watch("maxNumberAccreditation", updatemaxNumberAccreditationError); // watcher to get notified when data change !
        $scope.maxNumberAccreditation = 100; // default value for Max number Accreditation

        assignmentService.getNumberAccreditationMaxParameter().success(function (data) {
            if (data !== undefined && data !== null) {
                $scope.maxNumberAccreditation = data;
            }
        });


        $scope.assignment = {
            EventId: contextService.event.EventId,
            CreationUnitId: null,
            AssignmentTypeId: 4,
            ProfileId: null,
            ProviderId: null,
            NumberOfAssignment: null,
            ProviderName: null,
            PopulationCode: "",
            ReferenceCodeId: null,
            IndividualFunction: "",
            ValidityStartDate: "",
            ValidityEndDate: "",
            HasAccessToAllEvent: $scope.isDailyAccreditationActive ? false : null,
            Area: "",
            Row: "",
            Seat: "",
            Comment: "",
            CustomFields: [],
            AssignmentLines: [],
            ZoneIds: [],
            StepIds: [],
            IsDaily: !contextService.event.IsGroup,
            AccessStartTime: "",
            AccessEndTime: "",
            AccessStartDate: "",
            AccessEndDate: "",
            AccessDetailsModel: {},
            Categories: [],
            CategoriesIds: []
        };
        assignmentService.getWordingStyleParameter().success(function (data) {
            $scope.wordingStyle = data;
        });
        $scope.individualIdsInError = [];
        $scope.individualsInError = false;
        $scope.isUpdate = $routeParams.assignmentId ? true : false;
        $scope.assignmentTypes = contextService.createAssignmentTypes;
        $scope.event = contextService.event;
        $scope.providers = [];
        $scope.deliveryPlaces = contextService.deliveryPlaces;
        $scope.zones = [];
        $scope.surZones = contextService.surZones;
        $scope.profiles = [];
        $scope.referenceCodes = [];
        $scope.organizationUnitId = [];
        $scope.units = [];
        $scope.steps = contextService.steps;
        $scope.user = contextService.user;
        $scope.isDailyList = [{ value: null, label: "" }, { value: true, label: $scope.resources.Unlimited }, { value: false, label: $scope.resources.Daily }];
        $scope.valuesRequired = true;

        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        $scope.groupByUnit = function (item) {
            return item.ParentName;
        };
        assignmentService.getRgpd().success(function (data) {
            $scope.rgpd = data.data;
        });

        /**************** Getters ******************/

        $scope.getUserUnitsTree = function (providerId) {

            if ($scope.units.indexOf(loadingItem) === -1) {
                $scope.units = [];
                $scope.units.push(loadingItem);
            }

            if ($scope.useCategories()) {
                $scope.getCategories($scope.assignment.EventId, providerId);
            }

            assignmentService.getUnitsTreeByProviderId($scope.assignment.EventId, providerId).success(function (data) {
                $scope.units = [];
                angular.forEach(data,
                    function (value) {
                        $scope.units.push(value);
                    });
                if ($scope.units.length === 0) {
                    $scope.units.push(noResultItem);
                }
            });
        };


        $scope.getProviders = function (q) {
            $scope.providers = [];
            $scope.providers.push(loadingItem);
            return providerService.getProviders(1, q, $scope.event.OrganizationId)
                .then(function (data) {
                    $scope.providers = [];
                    angular.forEach(data.data.items, function (value, key) {
                        $scope.providers.push(value);
                    });
                    if ($scope.providers.length === 0) {
                        $scope.providers.push(noResultItem);
                    }
                });
        };

        $scope.selectAllZones = function () {
            var untoggleAll = ($scope.zones.length + $scope.surZones.length) === $scope.assignment.ZoneIds.length;
            if (untoggleAll) {
                angular.forEach($scope.zones,
                    function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                angular.forEach($scope.surZones,
                    function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                $scope.allZonesSelected = false;
            } else {
                angular.forEach($scope.zones,
                    function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.assignment.ZoneIds.push(zone.ZoneId);
                        }
                    });
                angular.forEach($scope.surZones,
                    function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.assignment.ZoneIds.push(zone.ZoneId);
                        }
                    });
                $scope.allZonesSelected = true;
            }
        };

        $scope.selectZone = function (zoneId) {
            var index = $scope.assignment.ZoneIds.indexOf(zoneId);
            if (index < 0) {
                $scope.assignment.ZoneIds.push(zoneId);
            } else {
                $scope.assignment.ZoneIds.splice(index, 1);
            }
        };

        $scope.getZonesByProfileId = function (profile) {
            assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {
                angular.forEach(zones,
                    function (value) {
                        $scope.assignment.ZoneIds.push(value.ZoneId);
                    });
            });
        };

        /**************** Actions ******************/

        $scope.affecter = function (form) {
            $scope.loading = true;
            form.$submitted = true;

            var length = $scope.assignment.StepIds.length;
            var verifSteps = $scope.assignment.IsDaily === true || $scope.assignment.HasAccessToAllEvent === true || (length > 0 && length <= 5);

            if (form.$valid && verifSteps) {
                // creer une affectation
                $(".form-assignment").Spinner("show");
                assignmentService.manageAssignmentAccess($scope.assignment);
                assignmentService.addAnonymousAssignment($scope.assignment).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $location.path('/assignmentList/');
                    } else {
                        $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                        $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                        if (data.ExceptionOccured)
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        else
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                    }
                    $(".form-assignment").Spinner("hide");
                    $scope.loading = false;
                });
            } else {
                $scope.loading = false;
            }
        };

        $scope.getUnitConfiguration = function (creationUnitId) {
            $scope.profiles.push(loadingItem);
            assignmentService.GetUnitConfiguration(creationUnitId, "IndividualAssignment").success(function (data) {
                $scope.profiles = data.profiles;
                if (!$scope.isUpdate) {
                    $scope.assignment.CustomFields = data.customFields;
                }
                // réinit zones par unit
                $scope.zones = [];
                contextService.zones.forEach(function (value, index) {
                    if (data.zoneIds.indexOf(value.ZoneId) >= 0)
                        $scope.zones.push(value);
                });
            });
        };

        //si en mode création
        if (!$scope.isUpdate) {
            $scope.$watch("event", function (event) {
                if (event !== null) {
                    $scope.assignment.EventId = event.EventId;
                }
            }, true);
        }


        $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
            if (assignmentTypeId !== 4) {
                $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
            }
        });


        if ($scope.isUpdate) {
            jQuery(".form-assignment").Spinner("show");
            assignmentService.getAssignment($routeParams.assignmentId).success(function (data) {
                $scope.assignment = data;

                if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                    assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                } else {
                    assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                }

                $scope.getUnitConfiguration(data.CreationUnitId);
                jQuery(".form-assignment").Spinner("hide");
            });
        } else {
            if ($scope.hasPermission(right.UserLevelExclusiveRight)) {
                $scope.assignment.ProviderId = $scope.user.ProviderId;
                $scope.assignment.ProviderName = $scope.user.ProviderName;
                $scope.getUserUnitsTree($scope.assignment.ProviderId);
            }

            $scope.assignment.AccessDetailsModel.IsAbsoluteAccess = $scope.event.IsAbsoluteAccess;

            if ($scope.event.IsAbsoluteAccess) {
                assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, $scope.event.AccessStartDate, $scope.event.AccessEndDate);
            } else {

                $scope.assignment.AccessDetailsModel.MinutesNumberBeforeAccess = $scope.event.MinutesNumberBeforeAccess;
                $scope.assignment.AccessDetailsModel.MinutesNumberAfterAcces = $scope.event.MinutesNumberAfterAcces
            }
        }

        function updatemaxNumberAccreditationError(newValue) {
            if (newValue !== null && newValue !== undefined) {
                $scope.maxNumberAccreditationError = resourcesMessages.MaxAssignmentNumberError.replace('{0}', newValue);
            }
        };
    }]);


angular.module('accreditationApp')
    .controller('assignmentFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'Upload', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, Upload, sharedService, $controller) {
            $scope.culture = "fr";
            $scope.quotasActivated = site.params.quotasActivated;
            $scope.accessToAllEventCheckedForSeasonTitles = site.params.accessToAllEventCheckedForSeasonTitles;

            sharedService.getCurrentCulture().success(function (data) {

                $scope.culture = data;
                site.params.currentCulture = data;
            });

            angular.extend(this, $controller('baseController', { $scope: $scope }));
            contextService.currentPage.index = "assignmentList";

            $scope.filterSteps = function (step) {
                return step.IsActive === true;
            }
            

            $scope.assignment = {
                EventId: contextService.event.EventId,
                CreationUnitId: null,
                AssignmentTypeId: 1,
                ProfileId: null,
                ProviderId: null,
                Provider: null,
                PopulationCode: "",
                ReferenceCodeId: null,
                ValidityStartDate: "",
                ValidityEndDate: "",
                HasAccessToAllEvent: $scope.isDailyAccreditationActive ? false : null,
                Area: "",
                Row: "",
                Seat: "",
                Comment: "",
                CustomFields: [],
                Individual: {},
                IndividualId: null,
                ZoneIds: [],
                StepIds: [],
                IsDaily: !contextService.event.IsGroup,
                Individuals: [],
                IndividualIds: [],
                Categories: [],
                CategoriesIds: [],
                Status: "",
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {},
                BypassQuotas: false,
                BillingProfileId: null,
                BillingProfile: null,
                ProviderBillingActivated: false
            };
            $scope.individualIdsInError = [];
            $scope.individualsInError = false;
            $scope.individualsPage = 1;
            $scope.lastIndividualsQuery = "";
            $scope.busyLoading = false;
            $scope.categoryIsLoading = false;
            $scope.resources = resources;
            $scope.event = contextService.event;
            $scope.tempProvider = null;
            $scope.isClone = $location.path().startsWith("/clone");

            $scope.isUpdate = $routeParams.assignmentId && !$scope.isClone ? true : false;
            
            $scope.showMore = false;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.providers = [];
            $scope.deliveryPlaces = contextService.deliveryPlaces;
            $scope.zones = [];
            $scope.surZones = contextService.surZones;
            $scope.allZonesSelected = false;
            $scope.profiles = [];
            $scope.referenceCodes = [];
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.individuals = [];
            $scope.steps = contextService.steps.filter($scope.filterSteps);
            $scope.user = contextService.user;
            $scope.isDailyList = [{ value: null, label: "" }, { value: true, label: $scope.resources.Unlimited }, { value: false, label: $scope.resources.Daily }];
            $scope.uploadFiles = assignmentService.uploadFiles;
            $scope.displayZoneImage = site.params.displayZoneImage;
            $scope.valuesRequired = true;
            $scope.billingProfiles = [];

            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            };

            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            $scope.resetIndividuals = function (provider) {
                $scope.individuals = [];
                $scope.tempProvider = provider;
            };

            // because getBillingProfiles can be invoked before UseBilling parameter is initialized, 
            // we must trace the initialisation of UseBilling parameter
            // and invoke again getBillingProfiles if  UseBilling parameter is initialized after getBillingProfiles invocation
            $scope.UseBillingInitialized = false;
            $scope.BillingProfilesInitializationNeeded = null;

            assignmentService.getParameters(['IsPhotoMandatory', 'IsBirthDateMandatory', 'WordingStyle', 'IsMobilePhoneMandatory', 'IsLandlinePhoneMandatory', 'IsEmailMandatory', 'UseBilling']).success(function (params) {
                $scope.wordingStyle = params.filter(function (p) { return p.Name == 'WordingStyle'; })[0].Value;

                $scope.isPhotoMandatory = params.filter(function (p) { return p.Name == 'IsPhotoMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationPicture);
                $scope.isBirthDateMandatory = params.filter(function (p) { return p.Name == 'IsBirthDateMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationBirthDate);
                $scope.IsMobilePhoneMandatory = params.filter(function (p) { return p.Name == 'IsMobilePhoneMandatory'; })[0].Value;
                $scope.IsLandlinePhoneMandatory = params.filter(function (p) { return p.Name == 'IsLandlinePhoneMandatory'; })[0].Value;
                $scope.IsEmailMandatory = params.filter(function (p) { return p.Name == 'IsEmailMandatory'; })[0].Value;
                $scope.UseBilling = params.filter(function (p) { return p.Name == 'UseBilling'; })[0].Value;
                $scope.UseBillingInitialized = true;
                if ($scope.BillingProfilesInitializationNeeded) {
                    $scope.getBillingProfiles($scope.BillingProfilesInitializationNeeded.providerId, $scope.BillingProfilesInitializationNeeded.resetSelection);
                    $scope.BillingProfilesInitializationNeeded = null;
                }
            });

            var hideFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("hide");
            };

            var showFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("show");
            };

        /**************** Getters ******************/

            

            $scope.getBillingProfiles = function (providerId, resetSelection) {

                //if the parameter is inactive, no need to do anything
                if (!$scope.UseBilling) {

                    if (!$scope.UseBillingInitialized !== null) $scope.BillingProfilesInitializationNeeded = { providerId: providerId, resetSelection: resetSelection };
                    return;
                }

                //reset selection (has to be false when binding assignment info)
                if (resetSelection) {
                    $scope.assignment.BillingProfileId = null;
                }

                //if billing is not active for the current Provider, the list is emptied
                if (!$scope.assignment.ProviderBillingActivated) {
                    $scope.billingProfiles = [];
                    return;
                }

                if ($scope.billingProfiles.indexOf(loadingItem) == -1) {
                    $scope.billingProfiles = [];
                    $scope.billingProfiles.push(loadingItem);
                }

                providerService.getBillingProfiles(providerId, contextService.event.EventId).success(function (data) {
                    //remove loadingitem
                    $scope.billingProfiles = [];
                    if (data !== null && data !== undefined && data.length > 0) {
                        angular.forEach(data, function (value, key) {
                            $scope.billingProfiles.push(value);
                        });
                        //if selection has been reset, initialize by default to the first value
                        if (resetSelection) {
                            $scope.assignment.BillingProfileId = $scope.billingProfiles[0].BillingProfileId;
                        }
                    }
                    else {
                        //no elements retrieved
                        $scope.billingProfiles.push(noResultItem);
                    }
                })
                    .error(function (data) {
                        //backend error, no elements retrieved
                        $scope.billingProfiles.push(noResultItem);
                });
            };
            $scope.getUserUnitsTree = function (providerId) {

                if ($scope.units.indexOf(loadingItem) == -1) {
                    $scope.units = [];
                    $scope.units.push(loadingItem);
                }

                if ($scope.useCategories()) {
                    if (!$scope.isUpdate && !$scope.isClone) {
                        $scope.assignment.CategoriesIds = [];
                    }
                    $scope.getCategories($scope.assignment.EventId, providerId);
                }



                assignmentService.getUnitsTreeByProviderId($scope.assignment.EventId, providerId).success(function (data) {
                    $scope.units = [];
                    //set default unit
                    if (data.length > 0 && $scope.assignment.CreationUnitId == null) {
                        $scope.assignment.CreationUnitId = data[0].OrganizationUnitId;
                        $scope.assignment.ProfileId = null;
                        $scope.assignment.ZoneIds = [];
                        $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                    }
                    angular.forEach(data, function (value, key) {
                        $scope.units.push(value);
                    });

                    

                    if ($scope.units.length === 0) {
                        $scope.units.push(noResultItem);
                    }
                });
            };

            $scope.getProviders = function (q) {
                $scope.providers = [];
                $scope.providers.push(loadingItem);
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length == 0) {
                            $scope.providers.push(noResultItem);
                        }
                        
                    });
            };

            $scope.getIndividuals = function (q, providerId) {
                $scope.individuals = [];
                if ($scope.assignment.ProviderId != null) {
                    $scope.individuals.push(loadingItem);
                    $scope.individualsPage = 1;
                    return assignmentService.getIndividualsByProviderId(providerId == null ? $scope.assignment.ProviderId : providerId, $scope.assignment.EventId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individuals = [];
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            if ($scope.individuals.length == 0) {
                                $scope.individuals.push(noResultItem);
                            }
                            return data;
                        });
                }
            };

            $scope.getNextIndividuals = function (q) {
                if ($scope.assignment.ProviderId != null && !$scope.busyLoading) {
                    $scope.busyLoading = true;
                    if (q != $scope.lastIndividualsQuery) {
                        $scope.individualsPage = 1;
                        $scope.individuals = [];
                    }
                    return assignmentService.getIndividualsByProviderId($scope.assignment.ProviderId, $scope.assignment.EventId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            $scope.busyLoading = false;
                        });
                }
            };



            $scope.selectAllZones = function () {
                var untoggleAll = ($scope.zones.length + $scope.surZones.length) == $scope.assignment.ZoneIds.length;
                if (untoggleAll) {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    angular.forEach($scope.surZones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    $scope.allZonesSelected = false;
                } else {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.assignment.ZoneIds.push(zone.ZoneId);
                        }
                    });
                    angular.forEach($scope.surZones,
                        function (zone) {
                            var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                            if (index < 0) {
                                $scope.assignment.ZoneIds.push(zone.ZoneId);
                            }
                        });
                    $scope.allZonesSelected = true;
                }
            };

            $scope.selectZone = function (zoneId) {
                var index = $scope.assignment.ZoneIds.indexOf(zoneId);
                if (index < 0) {
                    $scope.assignment.ZoneIds.push(zoneId);
                    if ($scope.assignment.ZoneIds.length == ($scope.zones.length + $scope.surZones.length)) {
                        $scope.allZonesSelected = true;
                    }
                } else {
                    $scope.assignment.ZoneIds.splice(index, 1);
                    $scope.allZonesSelected = false;
                }
            };

            $scope.getZonesByProfileId = function (profile) {
                assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {
                    angular.forEach(zones, function (value, key) {
                        $scope.assignment.ZoneIds.push(value.ZoneId);
                    });
                });
            };

            $scope.getLastAssignmentByIndividualId = function (individualId) {
                assignmentService.getLastAssignmentByIndividualId($scope.assignment.EventId, individualId, $scope.assignment.AssignmentTypeId).success($scope.bindAssignment);
            };

            $scope.getUnitConfiguration = function (creationUnitId, noCustomField) {
                if ($scope.profiles.indexOf(loadingItem) == -1) {
                    $scope.profiles.push(loadingItem);
                }
                assignmentService.GetUnitConfiguration(creationUnitId, "IndividualAssignment").success(function (data) {
                    $scope.profiles = data.profiles;
                    if (!noCustomField) {
                        $scope.assignment.CustomFields = data.customFields;
                    }
                    //set default profile
                    if (data.profiles.length > 0 && $scope.assignment.ProfileId == null) {
                        $scope.assignment.ProfileId = data.profiles[0].ProfileId;
                        $scope.getZonesByProfileId(data.profiles[0]);
                    }

                    if ($scope.profiles.length == 0) {
                        $scope.profiles.push(noResultItem);
                    }

                    // réinit zones par unit
                    $scope.zones = [];
                    contextService.zones.forEach(function (value, index) {
                        if (data.zoneIds.indexOf(value.ZoneId)>=0)
                            $scope.zones.push(value);
                    });

                });
            };

            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required && (customField.Values.length > 0 || customField.File !== null)) || !customField.Required;
                return verif;
            };

            $scope.isValidIndividual = function (individualSelected) {
                for (var i = 0; i < individualSelected.CustomFields.length; i++) {
                    if (!$scope.validateCustomField(individualSelected.CustomFields[i])) {
                        $scope.individualIdsInError.push(individualSelected.IndividualId);
                        $scope.individualsInError = true;
                        return false;
                    }
                }

                if ($scope.isBirthDateMandatory && (individualSelected.BirthDate == null || individualSelected.BirthDate == "")) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
                if ($scope.isPhotoMandatory && individualSelected.HasImage == false) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
                if ($scope.IsMobilePhoneMandatory && (individualSelected.MobilePhoneNumber == null || individualSelected.MobilePhoneNumber == "")) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
                if ($scope.IsLandlinePhoneMandatory && (individualSelected.FixPhoneNumber == null || individualSelected.FixPhoneNumber == "")) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
                if ($scope.IsEmailMandatory && (individualSelected.Email == null || individualSelected.Email == "")) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }

                if ($scope.assignment.Individuals.indexOf(individualSelected) == -1) {
                    var testIndividual = $scope.assignment.Individuals.find(function (x) { return x.IndividualId == individualSelected.IndividualId });
                    if (testIndividual != undefined) $scope.assignment.Individuals.splice(testIndividual);
                    $scope.assignment.Individuals.push(individualSelected);
                }
                var index = $scope.individualIdsInError.indexOf(individualSelected.IndividualId);
                if (index > -1)
                    $scope.individualIdsInError.splice(index, 1);
                if ($scope.individualIdsInError.length == 0)
                    $scope.individualsInError = false;
                return true;
            };

            $scope.isSelectedIndividualValid = function (individualId) {
                var individualSelected = $filter('filter')($scope.individuals, { IndividualId: individualId })[0];
                $(".individualSelect").next().val('');
                if (individualSelected != undefined)
                    return $scope.isValidIndividual(individualSelected);
            };



            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            };

            

            $scope.finalizeAddAssignment = function () {
                
                showFormAssigmentSpinner();

                if ($scope.event.AllowEditAssignmentsAccess) {
                    assignmentService.formatAssignmentAccessStartEndDates($scope.assignment);
                    assignmentService.manageAssignmentAccess($scope.assignment);
                }

                assignmentService.addAssignment($scope.assignment).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $location.path('/assignmentList/');
                    } else {
                        $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                        $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                        if (data.ExceptionOccured)
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        else
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                    }
                    hideFormAssigmentSpinner();
                });
            };

            $scope.isModifiable = function () {
                return contextService.isModifiable($scope.isUpdate, $scope.assignment.Status, $scope.user);
            };

            $scope.isValidable = function () {
                return contextService.isValidable($scope.assignment.Status, $scope.user);
            };

            /**************** Actions ******************/

            $scope.checkQuota = function (callback) {

                // Skip quota check if quotas are not activated
                if (!$scope.quotasActivated) {
                    callback();
                    return;
                }

                // Vérification des quotas
                assignmentService.checkQuotas($scope.assignment).success(function (checkQuota) {
                    if (!checkQuota) {
                        callback();
                        return;
                    }

                    // Les quotas ont été dépassés
                    
                    console.log('checkQuota');
                    console.log(checkQuota);
                    if (!$scope.hasPermission(right.Assignment_CanBypassQuotas)) {
                        site.errorMessage(resourcesMessages.CreateAssignmentFail, checkQuota.Exception);
                        return;
                    }

                    var checkQuotaModal = $uibModal.open({
                        templateUrl: '/Scripts/Angular/Assignment/Views/_ConfirmByPassQuotas.html',
                        controller: 'BypassQuotasController',
                        resolve: {
                            bypassQuotas: $scope.assignment.BypassQuotas
                        }
                    });
                    checkQuotaModal.result.then(function (data) {
                        if (data === true) {
                            $scope.assignment.BypassQuotas = true;
                            callback();
                        }
                    });
                });
            };

            $scope.affecter = function (form) {
                $scope.loading = true;
                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily == true || $scope.assignment.HasAccessToAllEvent == true || (length > 0 && length <= 10);

                if (form.$valid && verifSteps && !$scope.individualsInError && $scope.checkCustomFields()) {

                    $scope.checkQuota(function () {
                        if ($scope.hasPermission(right.Assignment_CanViewBlackList)) {
                            assignmentService.IsBlacklisted($scope.assignment.IndividualIds).success(function (data) {
                                if (data.isBlacklisted) {
                                    var modalWarning = $uibModal.open({
                                        templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                        controller: 'BlacklistWarningController',
                                        resolve: {
                                            fromGeneralPage: false,
                                            fromAssignmentForm: true
                                        }
                                    });
                                    modalWarning.result.then(function (result) {
                                        if (result) {
                                            $scope.finalizeAddAssignment();
                                        }
                                    });
                                } else {
                                    $scope.finalizeAddAssignment();
                                }
                            });
                        } else {
                            $scope.finalizeAddAssignment();
                        }
                    });
                }

                $scope.loading = false;
            };

            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        showFormAssigmentSpinner();
                        assignmentService.cancelAssignment([$scope.assignment.AssignmentId], $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            hideFormAssigmentSpinner();
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.modify = function (form) {

                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily == true || $scope.assignment.HasAccessToAllEvent == true || (length > 0 && length <= 10);

                if (form.$valid && verifSteps && !$scope.individualsInError && $scope.checkCustomFields()) {

                    $scope.checkQuota(function () {
                        if ($scope.hasPermission(right.Assignment_CanViewBlackList)) {
                            assignmentService.IsBlacklisted($scope.assignment.IndividualIds).success(function (data) {
                                if (data.isBlacklisted) {
                                    var modalWarning = $uibModal.open({
                                        templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                        controller: 'BlacklistWarningController',
                                        resolve: {
                                            fromGeneralPage: false,
                                            fromAssignmentForm: true
                                        }
                                    });
                                    modalWarning.result.then(function (result) {
                                        if (result) {
                                            $scope.finalizeModifyAssignment();
                                        }
                                    });
                                } else {
                                    $scope.finalizeModifyAssignment();
                                }
                            });
                        }
                        else {
                            $scope.finalizeModifyAssignment();
                        }
                    });
                }

                $scope.loading = false;
            };

            $scope.getRichStatus = function () {
                assignmentService.getRichStatusForAssignment($scope.assignment.AssignmentId).success(function (data) {
                    $scope.assignment.Status = data.status;
                    hideFormAssigmentSpinner();
                });
            };

            $scope.finalizeModifyAssignment = function () {
                showFormAssigmentSpinner();
                if ($scope.event.AllowEditAssignmentsAccess) {
                    assignmentService.formatAssignmentAccessStartEndDates($scope.assignment);
                    assignmentService.manageAssignmentAccess($scope.assignment);
                }

                assignmentService.modifyAssignment($scope.assignment, $scope.assignment.Comment).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ModificationSuccess);
                        $location.path('/assignmentList/');
                    } else {
                        $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                        $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                        if (data.ExceptionOccured)
                            site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                        else
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                    }
                    hideFormAssigmentSpinner();
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };

           

            $scope.bindAssignment = function (data) {
                if (data == "") return;

                if ($scope.isUpdate || $scope.isClone) {
                    

                    var cloneData = JSON.parse(JSON.stringify(data));

                    $scope.assignment = cloneData;
               
                    if ($scope.isClone) {
                        $scope.assignment.EventId = contextService.event.EventId;
                        $scope.assignment.HasAccessToAllEvent = $scope.isDailyAccreditationActive ? false : null;
                        $scope.assignment.IsDaily = !contextService.event.IsGroup;
                        $scope.assignment.AssignmentId = 0;
                        $scope.assignment.OriginCloneAssignmentId = data.AssignmentId;
                    }

                    //set time format from datetime
                    
                    if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                        assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                    } else {
                        assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                    }

                    $scope.getUnitConfiguration(data.CreationUnitId, true);
                    $scope.getRichStatus();
                    angular.forEach($scope.assignment.Individuals, function (val, key) {
                        $scope.isValidIndividual(val);
                    });
                    if ($scope.UseBilling && $scope.assignment.ProviderBillingActivated) {
                        $scope.getBillingProfiles($scope.assignment.ProviderId, false);
                    }
                    $scope.getUserUnitsTree(data.ProviderId);

                } else {
                    $scope.assignment.PopulationCode = data.PopulationCode;
                    $scope.assignment.ReferenceCodeId = data.ReferenceCodeId;
                    $scope.assignment.Comment = data.Comment;
                    $scope.assignment.CustomFields = data.CustomFields;
                }
                
            };

            //si en mode création
            if (!$scope.isUpdate) {
                $scope.$watch("event", function (event) {
                    if (event != null) {
                        $scope.assignment.EventId = event.EventId;
                    }
                }, true);
            }


            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId != undefined && assignmentTypeId != 1) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

            $scope.$watchCollection("assignment.IndividualIds", function (newIds, oldIds) {
                var deleted = oldIds.filter(function (item) {
                    return newIds.indexOf(item) == -1;
                });
                angular.forEach(deleted, function (value, key) {
                    var index = $scope.individualIdsInError.indexOf(value);
                    if (index != -1) {
                        $scope.individualIdsInError.splice(index, 1);
                        if ($scope.individualIdsInError.length == 0) {
                            $scope.individualsInError = false;
                        }
                    }
                });
            });



            /**************** Modal individual ******************/

            $scope.modalIndividual = function (individualId) {
                $scope.modalIndividualId = individualId;

                var modalInstance = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Individual/Views/IndividualForm.html?ver=' + $scope.softwareVersion,
                    controller: 'individualFormController',
                    size: "lg",
                    backdrop: 'static',
                    resolve: {
                        individualId: function () {
                            return $scope.modalIndividualId;
                        },
                        provider: function () {
                            return $scope.tempProvider;
                        }
                    }
                });

                modalInstance.result.then(function (newIndividual) {
                    $scope.updateIndividualInfos(newIndividual);
                });
            };

            $scope.updateIndividualInfos = function (newIndividual) {
                //we have to retrieve the whole updated list, which takes time
                showFormAssigmentSpinner();
                //search by id
                var idList = [...$scope.assignment.IndividualIds];
                idList.push(newIndividual.IndividualId);
                $scope.getIndividuals("[BYID]" + idList, newIndividual.ProviderId)
                    .then(function (data) {
                        var individual = $scope.individuals.filter(function (ob) { return ob.IndividualId == newIndividual.IndividualId })[0];
                        //check if new individual is missing any info (this updates the individualIdsInError array)
                        $scope.isValidIndividual(individual);

                        if (!$scope.assignment.IndividualIds.includes(individual.IndividualId)) {
                            $scope.assignment.IndividualIds.push(individual.IndividualId);
                        }
                        //temporarily empty both arrays (individualIdsInError is used to paint in red those missing key info)
                        var temp = $scope.assignment.IndividualIds;
                        $scope.assignment.IndividualIds = [];
                        var tempError = $scope.individualIdsInError;
                        $scope.individualIdsInError = [];
                        setTimeout(function () {
                            //restore arrays, hide spinner
                            $scope.assignment.IndividualIds = temp;
                            $scope.individualIdsInError = tempError;

                            hideFormAssigmentSpinner();
                        }, 10);

                    });
            };

            

            if ($scope.isUpdate || $scope.isClone) {
                showFormAssigmentSpinner();
                assignmentService.getAssignment($routeParams.assignmentId).success($scope.bindAssignment);
                hideFormAssigmentSpinner();
            } else {
                if ($scope.hasPermission(right.UserLevelExclusiveRight)) {
                    $scope.assignment.ProviderId = $scope.user.ProviderId;
                    $scope.assignment.ProviderName = $scope.user.ProviderName;
                    $scope.assignment.ProviderBillingActivated = $scope.user.ProviderBillingActivated;
                    $scope.getBillingProfiles($scope.assignment.ProviderId, true);
                    $scope.getUserUnitsTree($scope.assignment.ProviderId);
                }

                $scope.assignment.AccessDetailsModel.IsAbsoluteAccess = $scope.event.IsAbsoluteAccess;

                if ($scope.event.IsAbsoluteAccess) {
                    assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, $scope.event.AccessStartDate, $scope.event.AccessEndDate);
                } else {
                    $scope.assignment.AccessDetailsModel.MinutesNumberBeforeAccess = $scope.event.MinutesNumberBeforeAccess;
                    $scope.assignment.AccessDetailsModel.MinutesNumberAfterAcces = $scope.event.MinutesNumberAfterAcces;
                }

                $scope.assignment.HasAccessToAllEvent = contextService.event.IsGroup && $scope.accessToAllEventCheckedForSeasonTitles;
            }

        }]);

angular.module('accreditationApp')
    .controller('assignmentListController', ['$rootScope', '$scope', '$route', '$routeParams', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'assignmentService', 'providerService', 'individualService', 'vehicleService', 'passService', '$controller'
        , function ($rootScope, $scope, $route, $routeParams, $timeout, $filter, $location, $q, $uibModal, contextService, assignmentService, providerService, individualService, vehicleService, passService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "assignmentList";
        $rootScope.rootTabulation = "assignmentList";
        
        individualService.resetPageState();
        vehicleService.resetPageState();
        passService.resetPageState();

        if ($routeParams.openEventModal === "open") {
            contextService.openEventModal = true;
        }

        if ($routeParams.openEventModal === "passwordsucceed") {
            site.successMessage($scope.resourcesMessages.PasswordUpdatedSuccessfully);
        }

        $scope.barcode = null;
        if ($routeParams.barcode != null) {
            $scope.barcode = $routeParams.barcode;
        }

        if (!$.cookie("AcceptCookies")) {
            contextService.AskConfirmCookies = true;
        }

        $scope.assignmentDisplayExtraMenu = false;

        if ($scope.hasPermission(right.Assignment_Export) ||
            $scope.hasPermission(right.Assignment_SendAccreditations) ||
            $scope.hasPermission(right.Assignment_Import) ||
            $scope.hasPermission(right.Assignment_Delete) ||
            $scope.hasPermission(right.Assignment_AddReading)) {
            $scope.assignmentDisplayExtraMenu = true;
        }

        $scope.assignmentView = null;
        $scope.doubleList = "";
        $scope.profiles = contextService.profiles;
        $scope.billingProfiles = [];
        $scope.assignmentTypes = contextService.searchAssignmentTypes;
        $scope.createAssignmentTypes = contextService.createAssignmentTypes;
        $scope.DeliveryPlaceList = contextService.deliveryPlaces;
        //filter based on rights
        $scope.steps = contextService.steps;
        $scope.hasPictureList = [{ value: false, label: $scope.resources.NoPicture }, { value: true, label: $scope.resources.WithPhoto }];
        $scope.HasDefaultZoningList = [{ value: false, label: $scope.resources.OnlyNonDefaultZones }, { value: true, label: $scope.resources.OnlyDefaultZones }];
        $scope.printStatusList = [{ value: 0, label: $scope.resources.NotPrinted }, { value: 1, label: $scope.resources.Printed }, { value: 2, label: $scope.resources.ToReprint }];
        $scope.accessStatusList = [];
        $scope.isDailyList = [{ value: false, label: $scope.resources.Unlimited }, { value: true, label: $scope.resources.Daily }];

        $("title").html(resources.Assignment);
        assignmentService.getMailStatus().success(function (data) {
            $scope.mailStatus = data;
        });
        assignmentService.getAccessStatus().success(function (data) {
            $scope.accessStatusList = data;
        });

        contextService.getSmsStatus().success(function (data) {
            $scope.smsStatusList = data;
        });

        assignmentService.getParameters(['WordingStyle', 'ShowMailjet', 'FormActivated', 'UseBilling']).success(function (params) {
            $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;

            $scope.showMailjet = params.filter(function (p) { return p.Name === 'ShowMailjet'; })[0].Value;

            //added ?. optional chaining to return undefined if the list is empty or null
            var mailStatusColorColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "MailStatusColor"; })?.[0];
            if (mailStatusColorColumn !== undefined && mailStatusColorColumn !== null) {
                mailStatusColorColumn.visible = $scope.hasPermission(right.DisplayListFieldsFullView) && $scope.showMailjet;
            }

            var formActivatedParam = params.filter(function (p) { return p.Name === 'FormActivated'; });
            $scope.formActivated = formActivatedParam.length > 0 && formActivatedParam[0].Value;

            //added ?. optional chaining to return undefined if the list is empty or null
            var formColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "SmsStatus"; })?.[0];
            if (formColumn !== undefined && formColumn !== null) {
                formColumn.visible = $scope.hasPermission(right.AssignmentList_SeeNotification) && $scope.formActivated;
            }

            $scope.UseBilling = params.filter(function (p) { return p.Name == 'UseBilling'; })[0].Value;
        });
        assignmentService.isFunctionPresent().success(function (data) {
            //added ?. optional chaining to return undefined if the list is empty or null
            var individualFunctionColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "IndividualFunction"; })?.[0];
            if (individualFunctionColumn !== undefined && individualFunctionColumn !== null) {
                individualFunctionColumn.visible = data;
            }
        });
        assignmentService.isReliabilityFieldPresent().success(function (data) {
            //added ?. optional chaining to return undefined if the list is empty or null
            var reliabilityFieldColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "Reliability"; })?.[0];
            if (reliabilityFieldColumn !== undefined && reliabilityFieldColumn !== null) {
                reliabilityFieldColumn.visible = data;
            }
        });

        if (contextService.event.OrganizationId > 0) {
            assignmentService.getSearchCustomFields(contextService.event.OrganizationId).success(function (data) {
                $scope.search.IndividualCustomFields = data.IndividualFields;
                $scope.search.AssignmentCustomFields = data.AssignmentFields;
            });
        }
        if (contextService.event.OrganizationId === undefined)
            site.errorMessage($scope.resourcesMessages.NoRightGivenForEvents, null);

        $scope.currentEvent = contextService.event;
        $scope.pageState = assignmentService.pageState;
        $scope.providers = assignmentService.pageState.providers;
        $scope.units = assignmentService.pageState.units;
        $scope.creators = assignmentService.pageState.creators;
        $scope.editors = assignmentService.pageState.editors;
        $scope.populations = assignmentService.pageState.populations;
        $scope.zones = contextService.allZones;
        $scope.viewAssignmentId = 0;
        $scope.user = contextService.user;
        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
        $scope.indPagination = {
            search: "",
            page: 1,
            isRequestMoreItems: true
        }
        $scope.proPagination = {};
        angular.copy($scope.indPagination, $scope.proPagination);

        $scope.search = assignmentService.pageState.search;

        if (!$scope.hasPermission(right.CanAccessToAllAssignments)) {
            $scope.search.ProviderId = $scope.user.ProviderId;
        }

        $scope.customFieldsToExport = [0, 1, 2];

        $scope.paginationOptions = {
            pageNumber: 1,
            pageSize: contextService.paginationPageSizes[0],
            totalItems: 0,
            sort: 'Provider',
            sortOrder: 'asc'
        };

        $scope.sortValue = "";
        $scope.sortType = "";

        $scope.$watch("search.ProviderId", function (providerId) {
            if (providerId === null || providerId === undefined || providerId == 0) {
                $scope.billingProfiles = [];
                $scope.billingProfiles.push(noResultItem);
            }
            else {
                providerService.getBillingProfiles(providerId, contextService.event.EventId)
                    .success(function (data) {
                        //remove loadingitem
                        $scope.billingProfiles = [];
                        if (data !== null && data !== undefined && data.length > 0) {
                            angular.forEach(data, function (value, key) {
                                $scope.billingProfiles.push(value);
                            });
                        }
                        else {
                            //no elements retrieved
                            $scope.billingProfiles.push(noResultItem);
                        }
                    })
                    .error(function (data) {
                        //backend error, no elements retrieved
                        $scope.billingProfiles.push(noResultItem);
                    });
            }
        });

        $scope.unitFirstCgange = true;
        $scope.unitSelectionChanged = function (items) {
            if ($scope.unitFirstCgange === false) {
                $scope.search.UnitIds = [];
            }
            $scope.unitFirstCgange = false;
            angular.forEach(items,
                function (value, key) {
                    $scope.search.UnitIds.push(value.id);
                });
        };

        $scope.getPage = function (sForm) {
            $scope.loading = true;

            if ($scope.barcode !== null) {
                $scope.search.Barcode = $scope.barcode;
            }

            assignmentService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $scope.search.Status = data.statusList;
                if ($scope.barcode !== null) {
                    $scope.gridApi.grid.modifyRows($scope.gridOptions.data);
                    $scope.expandRow($scope.gridOptions.data[0]);
                }
                $scope.loading = false;
            });
        };

        $scope.resetSearchFilters = function () {
            assignmentService.resetPageState();
            $scope.search = assignmentService.pageState.search;
        };

        $scope.getPageAfterPrinting = function (sForm) {
            $("#jqcontainer").Spinner("show");
            assignmentService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $("#jqcontainer").Spinner("hide");
                $scope.loading = false;
            });
        };

        $scope.selectRow = function (row) {
            $scope.gridApi.selection.selectRow(row.entity);
        };

        $scope.selectAllRow = function () {
            $scope.gridApi.selection.selectAllRows();
        };

        $scope.expandRow = function (row) {
            $("#pdf").remove();
            var rows = $scope.gridApi.expandable.getExpandedRows();
            for (var rowKey in rows) {
                $scope.gridApi.expandable.collapseRow(rows[rowKey]);
            }
            if (row !== rows[rowKey]) {
                $scope.gridApi.expandable.expandRow(row);
                $scope.resize(483);
            } else {
                $scope.resize(0);
            }
        };

        $scope.formatDate = function (date) {
            return site.formatDate(date);
        };
        $scope.dateIsValid = function (date) {
            return site.dateIsValid(date);
        };

        $scope.isNullOrUndefined = function (value) {
            return (!value) && (value === null);
        };

        $scope.canModify = function () {
            return $scope.hasPermission(right.Assignment_Modify)
                || $scope.hasPermission(right.Assignment_ModifyVehicle)
                || $scope.hasPermission(right.Assignment_ModifyGuest);
        };

        $scope.reactivate = function (assignmentId, eventId) {
            // todo : show spinner
            assignmentService.reactivate(assignmentId, eventId).success(function (data) {
                if (data.Success) {
                    site.successMessage(resourcesMessages.ReactivationSuccess);
                    $scope.getPage();
                } else {

                    if (data.ExceptionOccured)
                        site.errorMessage(resourcesMessages.ReactivationFail, data.Exception);
                    else
                        site.errorMessage(resourcesMessages.ReactivationFail, null);
                }
                // todo : hide spinner
            }).error(function () {
                site.errorMessage($scope.resourcesMessages.ReactivationFail, null);
                // todo : hide spinner
            });
        };

        $scope.viewSrc = '/Scripts/Angular/Assignment/Views/AssignmentView.html?ver=' + $scope.softwareVersion;

        var isStep = !$scope.currentEvent.IsGroup;

        var showAssignOnEventButon = !$scope.currentEvent.IsGroup && $scope.hasPermission(right.AssignOnStep);
        var canSeeHistory = $scope.hasPermission(right.Assignment_Historique);

        $scope.gridOptions = {
            paginationPageSizes: contextService.paginationPageSizes,
            paginationPageSize: contextService.paginationPageSizes[0],
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,
            rowTemplate: "",
            enableExpandableRowHeader: false,
            expandableRowTemplate: "<div ng-include='grid.appScope.viewSrc'></div>",
            expandableRowHeight: 483,
            expandableRowScope: {
                subGridVariable: 'subGridScopeVariable'
            },
            rowHeight: 50,
            columnDefs: [
                { field: 'AssignmentId', displayName: "AssignmentId", visible: false, enableSorting: false, enableColumnMenu: false },
                {
                    field: 'Status', width: 50, enableColumnMenu: false, displayName: "",
                    cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\" popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'assignmentStatusPopoverTemplate.html\'" popover-trigger="mouseenter">' +
                        '<div ng-class=\"{\'blacklist\': row.entity.IsBlacklisted && ' + $scope.hasPermission(right.Assignment_CanViewBlackList) + '}\" class="blacklist-assignment">' +
                        '<span class="ext-circle {{row.entity.Status}}"><span class="badge circle {{row.entity.Status}} {{row.entity.Presence}}" title="{{row.entity.Status}}-{{row.entity.Presence}}">&nbsp;</span><span></div>' +
                        '</div>'
                },
                {
                    field: 'AssignmentTypeName', width: 50, displayName: "", enableSorting: true, enableColumnMenu: false, cellTemplate:
                        '<div class=\"ui-grid-cell-contents ng-binding ng-scope\" ng-click="grid.appScope.expandRow(row.entity)">' +
                        '<div ng-if="row.entity.AssignmentTypeName == \'Individual\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><img  ng-if="row.entity.HasImage && ' + $scope.hasPermission(right.Assignment_CanSeeIndividualPicture) + '" class="img-grid hasQtip qtipImg" ng-src="/Content/images/individual/{{row.entity.ImageName}}?width=35&height=35&mode=crop" alt="" ><i ng-if="!row.entity.HasImage || ' + $scope.hasPermission(right.Assignment_CanSeeIndividualPicture) + ' === false" class="fa fa-user"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.AssignmentTypeName == \'Vehicle\'">' +
                        '<div class="thumbnail thumbnail-default pointer" ng-if="row.entity.VehicleTypeName == \'Automobile\'"><i class="fa fa-car"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'HeavyVehicle\'"><i class="fa fa-bus"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'Motorcycle\'"><i class="fa fa-motorcycle"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.AssignmentTypeName == \'Guest\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><i class="fa fa-user-plus"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.AssignmentTypeName == \'Anonymous\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><img  ng-if="row.entity.HasImage" class="img-grid hasQtip qtipImg" ng-src="/Content/images/assignment/{{row.entity.ImageName}}?width=35&height=35&mode=crop" alt="" ><i ng-if="!row.entity.HasImage" class="fa fa-user"></i></div>' +
                        '</div>' +
                        '</div>'
                },
                {
                    field: 'Name', minWidth: 80, displayName: $scope.resources.Name, enableColumnMenu: false,
                    cellTemplate:
                        '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="individual-cell pointer" ng-click="grid.appScope.expandRow(row.entity)">' +
                        '<button ng-show="' + $scope.hasPermission(right.Assignment_CanSeeDoubles) + ' && row.entity.HasDouble" class="btn btn-unstyled text-danger"  ng-mouseover="grid.appScope.getDoubles(row.entity.AssignmentId)"  popover-popup-delay="300" popover-trigger="mouseenter" uib-popover-template="\'popoverDoubleTemplate.html\'" popover-append-to-body="true" popover-title="{{grid.appScope.resources.DoubleDetected}}">' +
                        '<span class="fa fa-warning"></span>' +
                        '</button>&nbsp;&nbsp;' +
                        '<button ng-show="row.entity.AssignmentTypeName == \'Vehicle\' && row.entity.HasRequiredMinimumPassenger === false" class="btn btn-unstyled text-danger" popover-popup-delay="300" popover-trigger="mouseenter" uib-popover-template="\'popoverMinimumPassengerTemplate.html\'" popover-append-to-body="true" popover-title="{{grid.appScope.resources.Carpool}}">' +
                        '<span class="fa fa-warning"></span>' +
                        '</button>&nbsp;&nbsp;' +
                        '<span  class="individual-lastname">{{row.entity.LastName}} </span><span class="individual-firstname">{{row.entity.FirstName}}</span>' +
                        '<strong ng-show="row.entity.AssignmentTypeName == \'Vehicle\' && row.entity.BarCode != \'\' && grid.appScope.wordingStyle == \'NoStadium\'"> - n° {{row.entity.BarCode}}</strong></div></div>'
                },
                { field: 'Provider', minWidth: 50, enableColumnMenu: false, visible: $scope.hasPermission(right.DisplayListFieldsFullView), displayName: $scope.resources.Provider },
                {
                    field: 'ProfileName', minWidth: 140, enableColumnMenu: false, displayName: $scope.resources.Profile,
                    cellTemplate:
                        '<div ng-show="' + !$scope.hasPermission(right.Billing_CanViewBillingProfile) + ' || !grid.appScope.UseBilling || row.entity.BillingProfile == null || row.entity.BillingProfile.Label.length==0" class=\"ui-grid-cell-contents\">{{row.entity.ProfileName}}</div>' +
                        '<div ng-show="' + $scope.hasPermission(right.Billing_CanViewBillingProfile) + ' && grid.appScope.UseBilling && row.entity.BillingProfile.Label.length>0" class="ui-grid-cell-contents profile-container">' +
                        '<div>{{row.entity.ProfileName }}</div >' +
                        '<div class="billing-profile">{{row.entity.BillingProfile.Label}}</div>' + // BillingProfile
                        '</div>'
                },
                { field: 'IndividualFunction', enableColumnMenu: false, visible: $scope.hasPermission(right.DisplayListFieldsFullView), displayName: $scope.resources.Function },
                { field: 'Zoning', width: 250, enableColumnMenu: false, displayName: $scope.resources.Zones, cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="individual-cell" ng-include="\'zoningLine.html\'"></div></div>' },

                { field: 'CreationDate', visible: false, enableColumnMenu: false, displayName: $scope.resources.CreationDate, cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scopse"><span>{{grid.appScope.dateFormatter(row.entity.CreationDate)}}</span></div>' },
                { field: 'CreationUnitName', visible: false, enableColumnMenu: false, displayName: $scope.resources.Unit },
                { field: 'DeliveryPlaceName', width: 80, visible: false, enableColumnMenu: false, displayName: $scope.resources.DeliveryPlace },
                {
                    field: 'PrintStatus', width: 80, visible: $scope.hasPermission(right.DisplayListFieldsFullView), enableColumnMenu: false, displayName: $scope.resources.Status, cellTemplate:
                        '<div class="ui-grid-cell-contents text-center"  style=\"position: absolute;\">'
                        + '<a popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'printPopoverTemplate.html\'" popover-trigger="mouseenter" >' +
                        '<i ng-class="{\'text-success\': row.entity.PrintStatus == 1, \'text-danger\': row.entity.PrintStatus == 2}" class="fa fa-{{row.entity.SharingMode}} fa-lg"></i></a>'
                        + '<a ng-show="row.entity.ShowAccessControlState &&  row.entity.RetrieveAssignmentsAccessControlState" popover-append-to-body="true" popover-enable={{row.entity.ShowAccessControlStatePopOver}} popover-popup-delay="200" uib-popover-template="\'accessControlPopoverTemplate.html\'" popover-trigger="mouseenter" class="btn btn-{{row.entity.AccessControlClass}} btn-circle accessControlIcon" >' +
                        '<i class="fa fa-{{row.entity.AccessControlIcon}}"></i></a></div> '
                },
                {
                    field: 'Reliability', width: 90, enableColumnMenu: false, visible: false, displayName: $scope.resources.Reliability,
                    cellTemplate:
                        '<div class="ui-grid-cell-contents text-center">{{row.entity.Reliability}}</div>'
                },
                {
                    field: 'SmsStatus', width: 120, visible: $scope.hasPermission(right.AssignmentList_SeeNotification) && $scope.formActivated, enableColumnMenu: false, displayName: $scope.resources.Form,
                    cellTemplate:
                        '<div class="ui-grid-cell-contents text-center"  style=\"position: absolute;\">'
                        + '<a popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'smsStatusPopoverTemplate.html\'" popover-trigger="mouseenter" >'
                        + '<i  class="fa fa-{{row.entity.NotifyIcon}} fa-lg text-{{row.entity.NotifyClass}}"></i>'
                        + '</a>'
                        + '</div>'
                },
                {
                    field: 'MailStatusColor', width: 60, enableColumnMenu: false, displayName: $scope.resources.Email, cellTemplate:
                        '<div class=\"ui-grid-cell-contents text-center ng-binding ng-scope\"><div class="square" popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'mailStatusPopoverTemplate.html\'" popover-trigger="mouseenter" style="background-color: {{row.entity.MailStatusColor}}">&nbsp;</div></div>'
                },
                {
                    field: 'Actions', width: 80, enableColumnMenu: false, displayName: "", pinnedRight: false, cellTemplate:
                        '<div class="ui-grid-cell-contents ng-binding ng-scope">' +
                        '<div ng-if="' + $scope.hasPermission(right.Assignment_Modify) + '|| row.entity.Status != \'Validated\'">' +
                        // bouton edit
                        '<a ' +
                        'ng-if="(' + $scope.currentEvent.IsGroup + ' || row.entity.IsDaily) && row.entity.AssignmentTypeName != \'Anonymous\'" ' +
                        'class="btn btn-primary btn-circle" ' +
                        'ng-href="#/create{{row.entity.AssignmentTypeName}}Assignment/{{row.entity.AssignmentId}}" ' +
                        'title="{{grid.appScope.resources.Modify}}" >' +
                        '<i class="fa fa-pencil"></i>' +
                        '</a>' +

                        // bouton clone
                        '<a ' +
                        'ng-if="' + showAssignOnEventButon + ' && row.entity.Clonable" ' +
                        'class="btn btn-primary btn-circle"' +
                        'ng-href="#/clone{{row.entity.AssignmentTypeName}}Assignment/{{row.entity.AssignmentId}}" ' +
                        '>' +
                        '<i class="fa fa-clone"></i>' +
                        '</a>' +

                        // bouton reactivate
                        '<a ' +
                        'ng-if="' + showAssignOnEventButon + ' && row.entity.Reactivable" ' +
                        'class="btn btn-primary btn-circle"' +
                        'ng-click="grid.appScope.reactivate(row.entity.AssignmentId, ' + $scope.currentEvent.EventId + ')" ' +
                        '>' +
                        '<i class="fa fa-level-up"></i>' +
                        '</a>' +
                        // bouton History
                        '<button ' +
                        'ng-if="' + canSeeHistory + '"' +
                        'ng-hide="row.entity.AssignmentTypeName == \'Anonymous\'"' +
                        'class="btn btn-primary btn-circle" ' +
                        'ng-click="grid.appScope.showActionsHistory(row.entity.AssignmentId)" ' +
                        'title="{{grid.appScope.resources.History}}"' +
                        '>' +
                        '<i class="fa fa-history"></i>' +
                        '</button>' +
                        '</div>' +
                        '</div>'
                }
            ],
            expendAssignment: function () {
            },
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                    if (sortColumns.length !== 0) {
                        $scope.paginationOptions.sort = sortColumns[0].name;
                        $scope.paginationOptions.sortOrder = sortColumns[0].sort.direction;
                        $scope.sortType = '';
                        $scope.sortValue = '';
                    }
                    $scope.getPage();
                });
                $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    $scope.paginationOptions.pageNumber = newPage;
                    $scope.paginationOptions.pageSize = pageSize;
                    $scope.getPage();
                });

                $scope.gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
                    $scope.viewAssignmentId = row.entity.AssignmentId;
                    if (row.entity.AssignmentTypeName === 'Individual') {
                        $scope.viewSrc = '/Scripts/Angular/Assignment/Views/AssignmentView.html?ver=' + $scope.softwareVersion;
                    }
                    else if (row.entity.AssignmentTypeName === 'Vehicle') {
                        $scope.viewSrc = '/Scripts/Angular/Assignment/Views/VehicleAssignmentView.html?ver=' + $scope.softwareVersion;
                    }
                    else if (row.entity.AssignmentTypeName === 'Guest' || row.entity.AssignmentTypeName === 'Anonymous') {
                        $scope.viewSrc = '/Scripts/Angular/Assignment/Views/GuestAssignmentView.html?ver=' + $scope.softwareVersion;
                    }
                });

            }
        };

        $scope.getZonesByIds = function (ids) {
            var zones = [];
            angular.forEach(contextService.zones, function (value) {
                if (ids.indexOf(value.ZoneId)) {
                    zones.push(value);
                }
            });
            return zones;
        };

        $scope.dateFormatter = function (date) {
            return site.dateFormatter(date);
        };

        $scope.context = contextService.context;

        $scope.canViewBlackList = function () {
            return $scope.hasPermission(right.Assignment_CanViewBlackList);
        };

        /*************************************
        **************** Getter *************
        ***********************************/


        $scope.getProviders = function (q) {
            if ($scope.providers.length === 0 || q !== "") {
                $scope.providers.splice(0, $scope.providers.length);
                $scope.providers.push(loadingItem);
                return providerService.getProviders($scope.proPagination.page, q, $scope.currentEvent.OrganizationId)
                    .then(function (data) {
                        $scope.providers.splice(0, $scope.providers.length);
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length === 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            }
        };

        $scope.getUsers = function (q, control) {
            if (q.length >= 3) {
                var toUpdate = $scope.creators;
                if (control === 'creator') toUpdate = $scope.creators;
                if (control === 'editor') toUpdate = $scope.editors;
                assignmentService.getUsersByProviderId(search.providerId, q).success(function (data) {
                    toUpdate.splice(0, toUpdate.length);

                    angular.forEach(data.items, function (value, key) {
                        toUpdate.push(value);
                    });
                    if (toUpdate.length === 0) {
                        toUpdate.push(noResultItem);
                    }
                });
            }
        };

        $scope.getUserUnitsTree = function () {
            $scope.units.splice(0, $scope.units.length);
            if ($scope.search.EventId > 0) {
                assignmentService.getUserUnitsTree($scope.search.EventId).success(function (data) {
                    $scope.units.splice(0, $scope.units.length);
                    angular.forEach(data, function (value, key) {

                        if ($scope.search.UnitIds.indexOf(value.id)) {
                            value.selected = true;
                        }

                        $scope.units.push(value);
                    });
                });
            }
        };

        $scope.getUserUnitsTree();

        $scope.getPopulations = function () {
            $scope.populations.splice(0, $scope.populations.length);
            assignmentService.getPopulations().success(function (data) {
                angular.forEach(data.items, function (value, key) {
                    $scope.populations.push(value);
                });
            });
        };

        $scope.getGridIdsForValidation = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                if ($scope.hasPermission(right.Assignment_Valid)) {
                    if (value.Status === 'Waiting' || value.Status === 'isWaitForInferior') {
                        ids.push(value.AssignmentId);
                    }
                } else {
                    ids.push(value.AssignmentId);
                }
            });
            return ids;
        };

        $scope.getGridIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.AssignmentId);
            });
            return ids;
        };

        $scope.getAllReadyNotifiedIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                debugger

                ids.push(value.AssignmentId);
            });
            return ids;
        };

        $scope.getNonDeletableRows = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var names = [];
            angular.forEach(objs, function (value, key) {
                if (value.CanBeDeleted === false) {
                    names.push(value.Name + " - " + value.Provider);
                }
            });
            return names;
        };

        $scope.isNotValidAssignmentSelected = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var result = false;
            angular.forEach(objs, function (value, key) {
                if (value.Status !== "Validated") {
                    result = true;
                }
            });
            return result;
        };

        $scope.getGridPersonIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.IndividualId);
            });
            return ids;
        };

        $scope.checkSelectedAssignmentStatus = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ret = true;

            angular.forEach(objs, function (value, key) {
                if (value.Status !== "Validated")
                    ret = false;
            });
            return ret;
        };

        $scope.hasVehicleAssignmentWithoutRequiredMinimumPassenger = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ret = false;

            angular.forEach(objs, function (value, key) {
                if (value.AssignmentTypeName === "Vehicle" && !value.HasRequiredMinimumPassenger) {
                    ret = true;
                }
            });

            return ret;
        };

        $scope.showValidationForm = function () {
            var modalValidation = $uibModal.open({
                templateUrl: '/Scripts/Angular/Assignment/Views/ValidationForm.html',
                controller: 'validationFormController',
                resolve: {
                    assignmentIds: function () {
                        return $scope.getGridIdsForValidation();
                    },
                    hasVehicleAssignmentWithoutRequiredMinimumPassenger: function () {
                        return $scope.hasVehicleAssignmentWithoutRequiredMinimumPassenger();
                    }
                }
            });
            modalValidation.result.then(function (data) {
                if (data.Success) {
                    $scope.getPage();
                    site.successMessage(resources.ValidationSuccess);
                } else {
                    site.errorMessage($scope.resourcesMessages.AssignmentValidationError, data.Exception);
                }
            });
        };

        /*************************************
       **************** Action *************
       ***********************************/
        $scope.valid = function () {
            var ids = $scope.getGridIdsForValidation();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            if (!$scope.checkPermanente()) return;

            if ($scope.hasPermission(right.Assignment_CanViewBlackList)) {
                assignmentService.IsBlacklisted($scope.getGridPersonIds()).success(function (data) {
                    if (data.isBlacklisted) {
                        var modalWarning = $uibModal.open({
                            templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                            controller: 'BlacklistWarningController',
                            resolve: {
                                fromGeneralPage: true,
                                fromAssignmentForm: false
                            }
                        });
                        modalWarning.result.then(function (result) {
                            if (result) {
                                $scope.showValidationForm();
                            }
                        });
                    } else {
                        $scope.showValidationForm();
                    }
                });
            }
            else {
                $scope.showValidationForm();
            }

        };

        $scope.cancel = function () {
            var ids = $scope.getGridIds();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            if (!$scope.checkPermanente()) return;

            var strSpace = "";
            for (var i = 0; i < 30; i++) { strSpace += "&nbsp;" }
            jPrompt(resources.Comment + strSpace, "", resources.Refuse, function (message) {
                if (message !== null) {
                    assignmentService.cancelAssignment(ids, message).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $scope.getPage();
                        }
                    });
                    $scope.$apply();
                }
            });

        };

        $scope.delete = function () {

            var ids = $scope.getGridIds();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            if (!$scope.checkPermanente()) return;

            $("#jqcontainer").Spinner("show");

            var names = $scope.getNonDeletableRows();
            if (names.length > 0) {
                $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/DeleteError.html',
                    controller: 'deleteErrorController',
                    resolve: {
                        names: function () {
                            return names;
                        },
                        type: function () {
                            return 'Assignment';
                        }
                    }
                });
            } else {
                assignmentService.deleteAssignment(ids).success(function (data) {
                    if (data.Success === true) {
                        site.successMessage(resourcesMessages.SuppressionSuccess);
                        $scope.getPageAfterPrinting();
                    } else {
                        if (data.ExceptionOccured === true) {
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        } else {
                            site.errorMessage(resourcesMessages.DeleteAssignmentErrors, data.Exception);
                        }
                    }
                });
            }
            $("#jqcontainer").Spinner("hide");

        };

        $scope.addReading = function () {
            $("#jqcontainer").Spinner("show");
            var ids = $scope.getGridIds();
            if (ids.length > 0) {
                var modalAddReading = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Assignment/Views/AddReadingForm.html',
                    controller: 'addReadingFormController',
                    resolve: {
                        assignmentIds: function () {
                            return $scope.getGridIds();
                        }
                    }
                });

                modalAddReading.result.then(function (data) {
                    if (data.Success) {
                        $scope.getPage();
                        site.successMessage(resourcesMessages.AddedReadings);
                    } else {
                        site.errorMessage($scope.resourcesMessages.AssignmentValidationError, data.Exception);
                    }
                });

            } else {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            }

            $("#jqcontainer").Spinner("hide");

        };

        $scope.NotifytAll = function () {
            var ids = $scope.getGridIds();
            if (ids.length == 0) {
                jAlert(resourcesMessages.SelectValidAssignment, resources.Warning);
                return;
            }

            var modalPrint = $uibModal.open({
                templateUrl: '/Scripts/Angular/Shared/Views/NotifyForm.html',
                controller: 'notifyFormController',
                resolve: {
                    eventId: function () {
                        return $scope.currentEvent.EventId;
                    },
                    assignmentIds: function () {
                        return $scope.getGridIds();
                    }
                }
            });
            modalPrint.result.then(function (data) {
                if (data.Success) {
                    if (data.data !== null) {
                        site.successMessage(data.data);
                    } else {
                        if (ids.length > 1)
                            site.successMessage($scope.resourcesMessages.NotifySucceesMultiple);
                        else
                            site.successMessage($scope.resourcesMessages.NotifySuccees);
                    }
                    $scope.getPageAfterPrinting();
                } else {

                    if (ids.length > 1)
                        site.errorMessage($scope.resourcesMessages.NotifyErrorMultiple, data.Exception);
                    else
                        site.errorMessage($scope.resourcesMessages.NotifyError, data.Exception);

                }
            });

        };

        $scope.print = function () {

            if ($rootScope.IsPrinting) {
                jAlert(resourcesMessages.IsPrinting, resources.Warning);
                return;
            }

            var ids = $scope.getGridIds();
            if (ids === "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            if ($scope.isNotValidAssignmentSelected()) {
                jAlert(resourcesMessages.SelectOnlyValidAssignment, resources.Warning);
                return;
            }

            if (!$scope.checkPermanente()) return;

            var alreadyPrintedRows = $scope.getAlreadyPrintedRows();
            var canSend = $scope.hasPermission(right.Assignment_SendMail) ? $scope.CanSendSelectedAssignmentByMail() : false;
            var canReprint = alreadyPrintedRows.length === 0 || (alreadyPrintedRows.length > 0 &&
                $scope.hasPermission(right.Assignment_CanReprint));
            if (canReprint) {
                var modalPrint = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Assignment/Views/PrintForm.html',
                    controller: 'printFormController',
                    resolve: {
                        assignmentIds: function () {
                            return $scope.getGridIds();
                        },
                        alreadyPrinted: function () {
                            return alreadyPrintedRows.length > 0;
                        },
                        canSendTitleByMail: function () {
                            return canSend;
                        }
                    }
                });
                modalPrint.result.then(function (data) {
                    if (data.Success) {
                        if (data.data !== null) {
                            site.successMessage(data.data);
                        } else {
                            site.successMessage($scope.resourcesMessages.PrintSuccess);
                        }
                        $scope.getPageAfterPrinting();
                    } else {
                        site.errorMessage($scope.resourcesMessages.PrintFailed, data.Exception);
                    }
                });
            } else {
                $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/ReprintError.html',
                    controller: 'reprintErrorController',
                    resolve: {
                        names: function () {
                            return alreadyPrintedRows;
                        },
                        type: function () {
                            return 'Assignment';
                        }
                    }
                });
            }
        };

        $scope.sendEmail = function () {
            var check = $scope.checkSelectedAssignmentStatus();
            if (!check) {
                jAlert(resourcesMessages.OnlyValidatedAssignments, resources.Warning);
                return;
            }

            if (!$scope.currentEvent.IsMailCampaignOpen) {
                jAlert(resourcesMessages.MailSentAfterCampaignOpen, resources.Warning);
                return;
            }
            var ids = $scope.getGridIds();
            if (ids == "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            var modalPrint = $uibModal.open({
                templateUrl: '/Scripts/Angular/Assignment/Views/MailForm.html',
                controller: 'mailFormController',
                resolve: {
                    assignmentIds: function () {
                        return $scope.getGridIds();
                    }
                }
            });
            modalPrint.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                } else {
                    site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                }
            });

        };

        $scope.sendCustomMail = function () {

            var ids = $scope.getGridIds();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            var modalSendCustomMail = $uibModal.open({
                templateUrl: '/Scripts/Angular/Shared/Views/SendCustomMailForm.html',
                controller: 'sendCustomMailController',
                resolve: {
                    ids: function () {
                        return $scope.getGridIds();
                    },
                    type: function () {
                        return "assignment";
                    }
                }
            });

            modalSendCustomMail.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                } else {
                    site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                }
            });

        };

        $scope.sendMessage = function () {
            var ids = $scope.getGridIds();
            if (ids === "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            var modalPrint = $uibModal.open({
                templateUrl: '/Scripts/Angular/Shared/Views/MessageForm.html',
                controller: 'messageFormController',
                resolve: {
                    ids: function () {
                        return $scope.getGridIds();
                    },
                    type: function () {
                        return "assignments";
                    }
                }
            });
            modalPrint.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                } else {
                    site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                }
            });

        };

        $scope.exportCsv = function ($event) {

            if ($rootScope.isExporting) {
                jAlert(resourcesMessages.IsExporting, resources.Warning);
                return;
            }

            var modal = $uibModal.open({
                templateUrl: '/Scripts/Angular/Shared/Views/exportForm.html',
                controller: 'exportWarningController',
                resolve: {
                    exportType: function () {
                        return "assignment";
                    }
                }
            });

            modal.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.ExportSuccess);
                    $scope.getPage();
                } else {
                    site.errorMessage($scope.resourcesMessages.ExportFailed, null);
                }
            });

        };

        $scope.sendAccessControl = function (sendType) {

            var ids = $scope.getGridIds();
            if (ids === "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                return;
            }

            var modalAccess = $uibModal.open({
                templateUrl: '/Scripts/Angular/Assignment/Views/SendAccessControlForm.html',
                controller: 'sendAccessControlFormController',
                resolve: {
                    assignmentIds: function () {
                        return $scope.getGridIds();
                    }
                }
            });
            modalAccess.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SentToAccessControlSuccess);
                    $scope.getPage();
                } else {
                    site.errorMessage($scope.resourcesMessages.SentToAccessControlError);
                }
            });

        };

        var timer;
        $scope.doubles = [];
        $scope.doublesFromAssignmentId = 0;
        $scope.getDoubles = function (assignmentId) {
            timer = $timeout(function () {
                if ($scope.doublesFromAssignmentId !== assignmentId) {
                    $scope.doublesFromAssignmentId = assignmentId;
                    $(".popover-content").Spinner("show");
                    assignmentService.GetDoubles(assignmentId).success(function (doubles) {
                        $scope.doubles = doubles;
                        $(".popover-content").Spinner("hide");
                    })
                }
            }, 500);
        };

        $scope.hideDoubles = function () {
            $timeout.cancel(timer);
        };

        $scope.showActionsHistory = function (assignmentId) {

            assignmentService.getReprintingReason(assignmentId).success(function (data) {
                $scope.reprintingReason = data;
            });

            assignmentService.getActionsHistory(assignmentId).success(function (data) {
                $scope.actions = data;
                $(".widget-side").show("slide", { "direction": "left" });
            });
        };

        $scope.changeSortValue = function () {
            if ($scope.sortValue !== '') {
                if ($scope.sortType === '')
                    $scope.sortType = 'asc';
                $scope.paginationOptions.sort = $scope.sortValue;
                $scope.paginationOptions.sortOrder = $scope.sortType;
                $scope.removeSortFromGrid();
            } else {
                $scope.paginationOptions.sort = 'Provider';
                $scope.paginationOptions.sortOrder = 'asc';
                $scope.sortType = '';
            }
            $scope.getPage();
        };

        $scope.changeSortType = function () {
            if ($scope.sortType === '') {
                $scope.paginationOptions.sort = 'Provider';
                $scope.paginationOptions.sortOrder = 'asc';
                $scope.sortValue = '';

                $scope.getPage();
            } else if ($scope.sortValue !== '') {
                $scope.paginationOptions.sort = $scope.sortValue;
                $scope.paginationOptions.sortOrder = $scope.sortType;

                $scope.removeSortFromGrid();
                $scope.getPage();
            }
        };

        $scope.removeSortFromGrid = function () {
            for (var i = 0; i < $scope.gridApi.grid.columns.length; i++) {
                var col = $scope.gridApi.grid.columns[i];
                col.sort.direction = '';
            }
        };

        $scope.checkPermanente = function () {
            if ($scope.currentEvent.IsGroup) return true;

            var selectedAssignments = $scope.gridApi.selection.getSelectedRows();

            var anyPermanente = selectedAssignments.some(function (a) {
                return !a.IsDaily;
            });

            if (anyPermanente) {
                site.errorMessage($scope.wordingStyle == 'NoStadium' ? resourcesMessages.CannotModifyNonDailyAssignementOnStep : resourcesMessages.CannotModifyNonDailyAssignementOnStep_stadium, null);
                return false;
            }

            return true;
        };

        $scope.modify = function () {
            var selectedAssignments = $scope.gridApi.selection.getSelectedRows();
            var assignmentsType = selectedAssignments.reduce(function (res, a1) {
                var matches = res.filter(function (a2) {
                    return a1.AssignmentTypeId === a2.AssignmentTypeId;
                });
                if (matches.length === 0)
                    res.push(a1);
                return res;
            }, []);

            if (assignmentsType.length > 1) {
                site.errorMessage(resourcesMessages.CannotModifyMultiDifferentAssignmentTypes, null);
                return;
            }

            if (!$scope.checkPermanente()) return;

            var ids = [];
            angular.forEach(selectedAssignments, function (value) {
                ids.push(value.AssignmentId);
            });
            var redirectToCreateOne = "";
            if (ids.length > 0) {
                if (ids.length === 1) {
                    redirectToCreateOne = '#/create' + selectedAssignments[0].AssignmentTypeName + 'Assignment/' + ids;
                } else {
                    redirectToCreateOne = '#/modify' + selectedAssignments[0].AssignmentTypeName + 'Assignments/' + ids;
                }
                window.location.href = redirectToCreateOne;
            }

        };


        /*************************************
        **************** Watch *************
        ***********************************/
        assignmentService.getDefaultAssignmentType(contextService.event.EventId)
            .success(function (data) {
                //sanitize returned data (compare by value and not by value-type)
                if (data == undefined || data == "" || data == 0)
                    data = null;
                else
                    data = parseInt(data);
                assignmentService.pageStateModel.search.AssignmentTypeId = data;
                assignmentService.pageState.search.AssignmentTypeId = data;
                $scope.search = assignmentService.pageState.search;
                $scope.getPage();
            });

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.resize = function (plus) {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height + plus);
                $scope.gridApi.grid.handleWindowResize();
            }
        };

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.compareFilterDates = function () {
            $scope.errorWarningFilterDate = false;
            var startDate = $scope.search.FilterStartDate;
            var endDate = $scope.search.FilterEndDate;

            if (startDate.length > 0 && endDate.length > 0
                && moment(startDate, "DD/MM/YYYY").isValid() && moment(endDate, "DD/MM/YYYY").isValid()) {
                $scope.errorWarningFilterDate = moment(startDate, "DD/MM/YYYY") > moment(endDate, "DD/MM/YYYY");
            }
        }

    }]);

angular.module('accreditationApp')
    .controller('assignmentsFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'Upload', 'sharedService', 'assignmentsIds', '$timeout', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, Upload, sharedService, assignmentsIds, $timeout, $controller) {

            angular.extend(this, $controller('baseController', { $scope: $scope }));

            contextService.currentPage.index = "assignmentList";
            $scope.assignment = {
                EventId: contextService.event.EventId,
                ProvidersIds: [],
                CreationUnitsIds: [],
                AssignmentIds: [],
                CreationUnitId: null,
                AssignmentTypeId: 1,
                ProfileId: null,
                Provider: null,
                HasAccessToAllEvent: "",
                Comment: "",
                CustomFields: [],
                ZoneIds: [],
                ZoneIdsToAdd: [],
                ZoneIdsToDelete: [],
                EventIdsToDelete: [],
                CategoryIdsToAdd: [],
                EventsIdsToAdd: [],
                CategoryIdsToDelete: [],
                StepIds: [],
                IsDaily: !contextService.event.IsGroup,
                Individuals: [],
                IndividualIds: [],
                Categories: [],
                CategoriesIds: [],
                EventsIds: [],
                DeleteDeliveryPlace: false,
                DeleteComment: false,
                CustomFieldsIdsToDelete: [],
                Status: [],
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {}
            };

            $scope.individualIdsInError = [];
            $scope.individualsInError = false;
            $scope.individualsPage = 1;
            $scope.lastIndividualsQuery = "";
            $scope.busyLoading = false;
            $scope.resources = resources;
            $scope.event = contextService.event;
            $scope.tempProvider = null;
            $scope.showMore = false;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.providers = [];
            $scope.deliveryPlaces = contextService.deliveryPlaces;
            $scope.zones = [];
            $scope.events = [];
            $scope.surZones = [];
            $scope.allZonesSelected = false;
            $scope.allCategoriesSelected = false;
            $scope.profiles = [];
            $scope.referenceCodes = [];
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.individuals = [];
            $scope.steps = contextService.steps;
            $scope.user = contextService.user;
            $scope.isDailyList = [{ value: null, label: "   " }, { value: true, label: $scope.resources.Unlimited }, { value: false, label: $scope.resources.Daily }];
            $scope.uploadFiles = assignmentService.uploadFiles;
            $scope.displayZoneImage = site.params.displayZoneImage;
            $scope.assignmentsId = [];
            $scope.disableUnits = false;
            $scope.disableProfiles = false;
            $scope.disableDeliveryPlace = false;
            $scope.isMultipleUpdate = true;
            $scope.customFieldsToDelete = [];
            $scope.allZonesToAddSelected = false;
            $scope.allZonesToDeleteSelected = false;
            $scope.allCategoriesToAddSelected = false;
            $scope.allCategoriesToDeleteSelected = false;
            $scope.allEventsToAddSelected = false;
            $scope.allEventsToDeleteSelected = false;
            $scope.valuesRequired = false;

            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

            /**************** Functions ******************/

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            };

            $scope.resetIndividuals = function (provider) {
                $scope.individuals = [];
                $scope.tempProvider = provider;
            };

            $scope.getUserUnitsTree = function (providersIds) {
                if ($scope.units.indexOf(loadingItem) === -1) {
                    $scope.units = [];
                    $scope.units.push(loadingItem);
                }


                if ($scope.useCategories()) {
                    $scope.getCategoriesByEventAndProviderIds($scope.assignment.EventId, providersIds);
                }

                assignmentService.getUnitsTreeByProvidersId($scope.assignment.EventId, providersIds).success(function (data) {
                    $scope.units = [];

                    angular.forEach(data, function (value, key) {
                        $scope.units.push(value);
                    });
                    if ($scope.units.length === 0) {
                        $scope.disableUnits = true;
                    }
                });
            };

            $scope.getProviders = function (q) {
                $scope.providers = [];
                $scope.providers.push(loadingItem);
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length === 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            };

            $scope.getIndividuals = function (q, providerId) {
                $scope.individuals = [];
                if ($scope.assignment.ProvidersIds !== null) {
                    $scope.individuals.push(loadingItem);
                    $scope.individualsPage = 1;
                    return assignmentService.getIndividualsByProviderId(providerId, $scope.assignment.EventId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individuals = [];
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            if ($scope.individuals.length === 0) {
                                $scope.individuals.push(noResultItem);
                            }
                        });
                }
            };

            $scope.getNextIndividuals = function (q) {
                if ($scope.assignment.ProvidersIds !== null && !$scope.busyLoading) {
                    $scope.busyLoading = true;
                    if (q !== $scope.lastIndividualsQuery) {
                        $scope.individualsPage = 1;
                        $scope.individuals = [];
                    }
                    return assignmentService.getIndividualsByProviderId($scope.assignment.ProviderId, $scope.assignment.EventId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            $scope.busyLoading = false;
                        });
                }
            };

            $scope.selectAllZones = function (event, status) {

                $(".zones input[data-status=" + status + "]").each(function () {
                    var checkbox = $(this);
                    var toCheck = event.target.checked;
                    if (checkbox.prop('checked') !== toCheck) {

                        $timeout(function () {
                            checkbox.click();
                        });
                    }
                });

            };

            $scope.selectAllCategories = function (event, status) {

                $(".categories input[data-status=" + status + "]").each(function () {
                    var checkbox = $(this);
                    var toCheck = event.target.checked;
                    if (checkbox.prop('checked') !== toCheck) {

                        $timeout(function () {
                            checkbox.click();
                        });
                    }
                });

            };

            $scope.selectAllEvents = function (event, status) {
                $(".events input[data-status=" + status + "]").each(function () {
                    var checkbox = $(this);
                    var toCheck = event.target.checked;
                    if (checkbox.prop('checked') !== toCheck) {
                        $timeout(function () {
                            checkbox.click();
                        });
                    }
                });
            };
            $scope.selectZone = function (zoneId, status) {
                if (status === 0) {
                    $scope.updateArray(zoneId, $scope.assignment.ZoneIdsToDelete, $scope.assignment.ZoneIdsToAdd);
                    $(".zones input[data-status=1][name='ZoneIdsToAdd[]'][value='" + zoneId + "']").prop('checked', false);
                    $scope.allZonesToAddSelected = false;
                    if ($scope.assignment.ZoneIdsToDelete.length === ($scope.zones.length + $scope.surZones.length)) {
                        $scope.allZonesToDeleteSelected = true;
                    } else {
                        $scope.allZonesToDeleteSelected = false;
                    }
                } else if (status === 1) {
                    $scope.updateArray(zoneId, $scope.assignment.ZoneIdsToAdd, $scope.assignment.ZoneIdsToDelete);
                    $(".zones input[data-status=0][name='ZoneIdsToDelete[]'][value='" + zoneId + "']").prop('checked', false);
                    $scope.allZonesToDeleteSelected = false;
                    if ($scope.assignment.ZoneIdsToAdd.length === ($scope.zones.length + $scope.surZones.length)) {
                        $scope.allZonesToAddSelected = true;
                    } else {
                        $scope.allZonesToAddSelected = false;
                    }
                }
            };

            $scope.selectEvent = function (eventId, status) {
                if (status === 0) {
                    $scope.updateArray(eventId, $scope.assignment.EventsIdsToDelete, $scope.assignment.EventsIdsToAdd);
                    $(".events input[data-status=1][name='EventsIdsToAdd[]'][value='" + eventId + "']").prop('checked', false);
                    $scope.allEventsToAddSelected = false;
                    if ($scope.assignment.EventsIdsToDelete.length === $scope.events.length) {
                        $scope.allEventsToDeleteSelected = true;
                    } else {
                        $scope.allEventsToDeleteSelected = false;
                    }
                } else if (status === 1) {
                    $scope.updateArray(eventId, $scope.assignment.EventsIdsToAdd, $scope.assignment.EventsIdsToDelete);
                    $(".events input[data-status=0][name='EventsIdsToDelete[]'][value='" + eventId + "']").prop('checked', false);
                    $scope.allEventsToDeleteSelected = false;
                    if ($scope.assignment.EventsIdsToAdd.length === $scope.events.length) {
                        $scope.allEventsToAddSelected = true;
                    } else {
                        $scope.allEventsToAddSelected = false;
                    }
                }
            };

            $scope.selectCategory = function (categoryId, status) {
                if (status === 0) {
                    $scope.updateArray(categoryId, $scope.assignment.CategoryIdsToDelete, $scope.assignment.CategoryIdsToAdd);
                    $(".categories input[data-status=1][name='CategoryIdsToAdd[]'][value='" + categoryId + "']").prop('checked', false);
                    $scope.allCategoriesToAddSelected = false;
                    if ($scope.assignment.CategoryIdsToDelete.length === $scope.categories.length) {
                        $scope.allCategoriesToDeleteSelected = true;
                    } else {
                        $scope.allCategoriesToDeleteSelected = false;
                    }
                } else if (status === 1) {
                    $scope.updateArray(categoryId, $scope.assignment.CategoryIdsToAdd, $scope.assignment.CategoryIdsToDelete);
                    $(".categories input[data-status=0][name='CategoryIdsToDelete[]'][value='" + categoryId + "']").prop('checked', false);
                    $scope.allCategoriesToDeleteSelected = false;
                    if ($scope.assignment.CategoryIdsToAdd.length === $scope.categories.length) {
                        $scope.allCategoriesToAddSelected = true;
                    } else {
                        $scope.allCategoriesToAddSelected = false;
                    }
                }
            };

            $scope.updateArray = function (itemId, arrayToPush, arrayToSplice) {
                var index = arrayToPush.indexOf(itemId);
                if (index < 0) {
                    arrayToPush.push(itemId);
                    var indexToSplice = arrayToSplice.indexOf(itemId);
                    if (indexToSplice > -1) {
                        arrayToSplice.splice(indexToSplice, 1);
                    }
                } else {
                    arrayToPush.splice(index, 1);
                }
            };

            $scope.getZonesByProfileId = function (profile) {
                assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {

                    // On va rajouter les zones du profil
                    $("input[data-status=1]").each(function () {
                        var checkbox = $(this);
                        var checkboxZoneId = checkbox.val();
                        //checkboxZoneId is a string, while z.ZoneId is a number, so comparison will be made by value (==) and NOT value-type (===)
                        if ($.grep(zones, function (z) { return z.ZoneId == checkboxZoneId; })[0]) {
                            if (checkbox.prop('checked') !== true) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        } else {
                            if (checkbox.prop('checked') !== false) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        }
                    });

                    // On va supprimer toutes les autres zones
                    $("input[data-status=0]").each(function () {
                        var checkbox = $(this);
                        var checkboxZoneId = checkbox.val();
                        //checkboxZoneId is a string, while z.ZoneId is a number, so comparison will be made by value (==) and NOT value-type (===)
                        if (!$.grep(zones, function (z) { return z.ZoneId == checkboxZoneId; })[0]) {
                            if (checkbox.prop('checked') !== true) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        }
                    });
                });
            };

            $scope.getLastAssignmentByIndividualId = function (individualId) {
                assignmentService.getLastAssignmentByIndividualId($scope.assignment.EventId, individualId, $scope.assignment.AssignmentTypeId).success($scope.bindAssignment);
            };

            $scope.getUnitConfiguration = function (CreationUnitsIds, noCustomField) {
                $scope.profiles.push(loadingItem);
                assignmentService.GetUnitsConfiguration(CreationUnitsIds, "IndividualAssignment").success(function (data) {
                    $scope.profiles = data.profiles;
                    if (!noCustomField) {
                        $scope.assignment.CustomFields = data.customFields;
                    }

                    if ($scope.profiles.length === 0) {
                        $scope.disableProfiles = true;
                    }

                    // réinit zones par unit
                    $scope.zones = [];
                    $scope.surZones = [];
                    contextService.zones.forEach(function (value, index) {
                        if (data.zoneIds.indexOf(value.ZoneId) >= 0)
                            $scope.zones.push(value);
                    });
                    // réinit surzones par unit
                    contextService.surZones.forEach(function (value, index) {
                        if (data.zoneIds.indexOf(value.ZoneId) >= 0)
                            $scope.surZones.push(value);
                    });
                });
            };

            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required === true && (customField.Values.length > 0 || customField.File !== null)) || customField.Required === false;
                return verif;
            };

            $scope.isValidIndividual = function (individualSelected) {
                for (var i = 0; i < individualSelected.CustomFields.length; i++) {
                    if (!$scope.validateCustomField(individualSelected.CustomFields[i])) {
                        $scope.individualIdsInError.push(individualSelected.IndividualId);
                        $scope.individualsInError = true;
                        return false;
                    }
                }

                if ($scope.isBirthDateMandatory && (individualSelected.BirthDate === null || individualSelected.BirthDate === "")) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }

                if ($scope.isPhotoMandatory && individualSelected.HasImage === false) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
                if ($scope.assignment.Individuals.indexOf(individualSelected) === -1) {
                    var testIndividual = $scope.assignment.Individuals.find(function (x) { return x.IndividualId === individualSelected.IndividualId });
                    if (testIndividual !== undefined) {
                        var index = $scope.assignment.Individuals.indexOf(testIndividual);
                        $scope.assignment.Individuals.splice(index, 1, testIndividual);//replace old individual with new one
                    }
                }
                index = $scope.individualIdsInError.indexOf(individualSelected.IndividualId);
                if (index > -1)
                    $scope.individualIdsInError.splice(index, 1);
                if ($scope.individualIdsInError.length === 0)
                    $scope.individualsInError = false;
                return true;
            };

            $scope.isSelectedIndividualValid = function (individualId) {
                var individualSelected = $filter('filter')($scope.individuals, { IndividualId: individualId })[0];
                $(".individualSelect").next().val('');
                if (individualSelected !== undefined)
                    return $scope.isValidIndividual(individualSelected);
            };

            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            };

            $scope.finalizeAddAssignment = function () {
                $(".form-assignment").Spinner("show");

                var startDate = $scope.assignment.AccessStartDate;
                var endDate = $scope.assignment.AccessEndDate;

                assignmentService.manageAssignmentsAccess($scope.assignment);
                assignmentService.updateAndValidateAssignments($scope.assignment).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $location.path('/assignmentList/');
                    } else {
                        $scope.assignment.AccessStartDate = startDate;
                        $scope.assignment.AccessEndDate = endDate;
                        if (data.ExceptionOccured)
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        else
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                    }
                    $(".form-assignment").Spinner("hide");
                });
            };

            $scope.finalizeModifyAssignment = function () {
                $(".form-assignment").Spinner("show");

                var startDate = $scope.assignment.AccessStartDate;
                var endDate = $scope.assignment.AccessEndDate;

                assignmentService.manageAssignmentsAccess($scope.assignment);
                assignmentService.updateAssignments($scope.assignment)
                    .success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ModificationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = startDate;
                            $scope.assignment.AccessEndDate = endDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(data.Exception.filter(function (element) { return element.Status = "EventUpdate"; }).length > 0 ?
                                    resourcesMessages.SomeAccreditationsCannotBeChanged :
                                    resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        $(".form-assignment").Spinner("hide");
                    });
            };


            $scope.affecter = function (form) {
                $scope.loading = true
                //manage customs fields to remove
                $scope.assignment.CustomFieldsIdsToDelete = [];
                for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                    if ($scope.customFieldsToDelete[i])
                        $scope.assignment.CustomFieldsIdsToDelete.push(i);
                }
                if (form.$valid && !$scope.individualsInError) {
                    if ($scope.hasPermission(right.Assignment_CanViewBlackList)) {
                        assignmentService.IsBlacklisted($scope.assignment.IndividualIds).success(function (data) {
                            if (data.isBlacklisted) {
                                var modalWarning = $uibModal.open({
                                    templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                    controller: 'BlacklistWarningController',
                                    resolve: {
                                        fromGeneralPage: false,
                                        fromAssignmentForm: true
                                    }
                                });
                                modalWarning.result.then(function (result) {
                                    if (result) {
                                        $scope.finalizeAddAssignment();
                                    }
                                });
                            } else {
                                $scope.finalizeAddAssignment();
                            }
                        });
                    }
                    else {
                        $scope.finalizeAddAssignment();
                    }
                }

                $scope.loading = false;
            };

            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        $(".form-assignment").Spinner("show");
                        assignmentService.cancelAssignment($scope.assignment.AssignmentIds, $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            $(".form-assignment").Spinner("hide");
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };

            $scope.bindAssignment = function (data) {

                if (data !== "") {
                    $scope.assignment = data;
                    $scope.assignment.HasAccessToAllEvent = null;
                    //set time format from datetime
                    if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                        assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                    } else {
                        assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                    }

                    $scope.events = [];
                    angular.forEach($scope.event.Steps, function (val, key) {
                        $scope.events.push({ EventId: val.EventId, Name: val.EventName, ImageName: val.LogoName, Code: val.EventCode});
                    });
                    $scope.getUnitConfiguration(data.CreationUnitsIds, true);
                    $scope.getUserUnitsTree($scope.assignment.ProvidersIds);
                    $scope.getRichStatus();
                    angular.forEach($scope.assignment.Individuals, function (val, key) {
                        $scope.isValidIndividual(val);
                    });

                    jQuery(".form-assignment").Spinner("hide");
                }
            };

            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId !== undefined && assignmentTypeId !== 1) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

            $scope.$watchCollection("assignment.IndividualIds", function (newIds, oldIds) {
                var deleted = oldIds.filter(function (item) {
                    return newIds.indexOf(item) === -1;
                });
                angular.forEach(deleted, function (value, key) {
                    var index = $scope.individualIdsInError.indexOf(value);
                    if (index !== -1) {
                        $scope.individualIdsInError.splice(index, 1);
                        if ($scope.individualIdsInError.length === 0) {
                            $scope.individualsInError = false;
                        }
                    }
                });
            });

            $scope.isModifiable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isModifiable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            $scope.isValidable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isValidable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            $scope.getRichStatus = function () {
                $scope.assignment.Status = [];
                angular.forEach($scope.assignment.AssignmentIds, function (id) {
                    assignmentService.getRichStatusForAssignment(id).success(function (data) {
                        $scope.assignment.Status.push(data.status);
                        jQuery(".form-assignment").Spinner("hide");
                    });
                });
            };

            $scope.modify = function (form) {
                //manage customs fields to remove
                $scope.assignment.CustomFieldsIdsToDelete = [];
                for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                    if ($scope.customFieldsToDelete[i])
                        $scope.assignment.CustomFieldsIdsToDelete.push(i);
                }

                if (form.$valid && !$scope.individualsInError) {

                    if ($scope.hasPermission(right.Assignment_CanViewBlackList)) {
                        assignmentService.IsBlacklisted($scope.assignment.IndividualIds).success(function (data) {
                            if (data.isBlacklisted) {
                                var modalWarning = $uibModal.open({
                                    templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                    controller: 'BlacklistWarningController',
                                    resolve: {
                                        fromGeneralPage: false,
                                        fromAssignmentForm: true
                                    }
                                });
                                modalWarning.result.then(function (result) {
                                    if (result) {
                                        $scope.finalizeModifyAssignment();
                                    }
                                });
                            } else {
                                $scope.finalizeModifyAssignment();
                            }
                        });
                    }
                    else {
                        $scope.finalizeModifyAssignment();
                    }
                }
                $scope.loading = false;
            };


            /**************** Modal individual ******************/

            $scope.modalIndividual = function (individualId) {
                $scope.modalIndividualId = individualId;
                var modalInstance = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Individual/Views/IndividualForm.html?ver=' + $scope.softwareVersion,
                    controller: 'individualFormController',
                    size: "lg",
                    backdrop: 'static',
                    resolve: {
                        individualId: function () {
                            return $scope.modalIndividualId;
                        },
                        provider: function () {
                            return $scope.tempProvider;
                        }
                    }
                });

                modalInstance.result.then(function (newIndividual) {
                    $scope.getIndividuals(newIndividual.LastName + ' ' + newIndividual.FirstName, newIndividual.ProviderId)
                        .then(function (data) {
                            var individual = $scope.individuals.filter(function (ob) { return ob.IndividualId === newIndividual.IndividualId })[0];
                            $scope.isValidIndividual(individual);
                            if (!$scope.assignment.IndividualIds.includes(individual.IndividualId)) {
                                $scope.assignment.IndividualIds.push(individual.IndividualId);
                            }
                        });
                });
            };


            /**************** Init ******************/

            assignmentService.getParameters(['IsPhotoMandatory', 'IsBirthDateMandatory', 'WordingStyle']).success(function (params) {
                $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;
                $scope.isPhotoMandatory = params.filter(function (p) { return p.Name === 'IsPhotoMandatory'; })[0].Value;
                $scope.isBirthDateMandatory = params.filter(function (p) { return p.Name === 'IsBirthDateMandatory'; })[0].Value;
            });

            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            $scope.assignmentsId = assignmentsIds.split(',').map(Number);
            if ($scope.assignmentsId.length > 0) {
                jQuery(".form-assignment").Spinner("show");
                assignmentService.getAssignments($scope.assignmentsId).success($scope.bindAssignment);
            }
        }]);

angular.module('accreditationApp')
    .controller('assignmentViewController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            $scope.assignmentId = $scope.$parent.grid.appScope.viewAssignmentId;
            $scope.resources = resources;
            $scope.resourcesMessages = resourcesMessages;
            $scope.user = contextService.user;
            $scope.displayZoneImage = site.params.displayZoneImage;
            $scope.assignment = {};
            $scope.pdfUrl = '';
            $scope.loading = true;
            $scope.isLoad = false;
            assignmentService.getAssignment($scope.assignmentId).success(function (assignment) {
                $scope.assignment = assignment;
                if ($scope.assignment.Zones !== undefined && $scope.assignment.Zones !== null) {
                    $scope.assignment.Zones.sort(function (a, b) {
                        return (a.Code).localeCompare(b.Code);
                    });
                }
                var params = {
                    AssignmentIds: assignment.AssignmentId,
                    MockupGuid: contextService.previewmockup.Guid,
                    IsPreview: true
                };

                $scope.HidePrevisualisationPanel();


                $scope.loading = false;
                window.setTimeout(function () {
                    $scope.$apply(function () {
                        $scope.pdfUrl = '/Assignment/GetPdfs?' + $.param(params);
                    });
                }, 100);
            });

            $scope.enterAssignment = function () {
                assignmentService.enterAssignment($scope.assignmentId).success(function (data) {
                    if (data.Success) {
                        $scope.assignment.IsIn = true;
                        $scope.assignment.IsOut = false;
                        $scope.assignment.LastEntryDate = data.data;
                    }
                });
            };

            $scope.exitAssignment = function () {
                assignmentService.exitAssignment($scope.assignmentId).success(function (data) {
                    if (data.Success) {
                        $scope.assignment.IsIn = false;
                        $scope.assignment.IsOut = true;
                        $scope.assignment.LastExitDate = data.data;
                    }
                });
            };

            if ($scope.hasPermission(right.Assignment_CanViewPrevisualisation)) {
                $scope.loadingMockup = true;
            }
            $scope.errorMockup = false;

            $scope.onLoad = function () {
                $scope.loadingMockup = false;
            };

            $scope.onError = function (error) {
                $scope.loadingMockup = false;
                $scope.errorMockup = true;
            };

            $scope.HidePrevisualisationPanel = function () {
                // Hide Previsualisations pannels if no right
                if (!$scope.hasPermission(right.Assignment_CanViewPrevisualisation)) {
                    $(".previsualisationPanelAssignment").hide();
                }
            };
        }]);

angular.module('accreditationApp')
    .controller('BlacklistWarningController', ['$scope', '$uibModalInstance', 'fromGeneralPage', 'fromAssignmentForm', '$controller', function ($scope, $uibModalInstance, fromGeneralPage, fromAssignmentForm, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        if (fromGeneralPage)
            $scope.warning = resourcesMessages.BlacklistWarning;
        else {
            if (fromAssignmentForm)
                $scope.warning = resourcesMessages.BlacklistWarningAssignment;
            else
                $scope.warning = resourcesMessages.BlacklistWarningPass;
        }

        $scope.continue = function () {
            $uibModalInstance.close(true);
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('BypassQuotasController', ['$scope', '$uibModalInstance', '$controller', 'bypassQuotas', function ($scope, $uibModalInstance, $controller, bypassQuotas) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));

        $scope.continue = function () {
            $uibModalInstance.close(true);
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.bypass = function () {
            $uibModalInstance.close(true);
        };
    }]);


angular.module('accreditationApp')
    .controller('guestAssignmentFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'individualService', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, individualService, sharedService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            contextService.currentPage.index = "assignmentList";

            $scope.displayProfile = true;
            $scope.assignment = {
                EventId: contextService.event.EventId,
                CreationUnitId: null,
                AssignmentTypeId: 3,
                ProfileId: null,
                IndividualFirstName: "",
                IndividualLastName: "",
                IndividualFunction: "",
                ProviderId: null,
                GuestProviderName: "",
                ProviderName: null,
                PopulationCode: "",
                ReferenceCodeId: null,
                ValidityStartDate: "",
                ValidityEndDate: "",
                HasAccessToAllEvent: $scope.isDailyAccreditationActive ? false : null,
                Area: "",
                Row: "",
                Seat: "",
                Comment: "",
                CustomFields: [],
                AssignmentLines: [],
                ZoneIds: [],
                StepIds: [],
                IsDaily: !contextService.event.IsGroup,
                Status: "",
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {},
                Categories: [],
                CategoriesIds: []
            };

            assignmentService.getWordingStyleParameter().success(function (data) {
                $scope.wordingStyle = data;
            });
            $scope.isUpdate = $routeParams.assignmentId ? true : false;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.event = contextService.event;
            $scope.providers = [];
            $scope.deliveryPlaces = contextService.deliveryPlaces;
            $scope.zones = [];
            $scope.surZones = contextService.surZones;
            $scope.profiles = [];
            $scope.referenceCodes = [];
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.steps = contextService.steps;
            $scope.user = contextService.user;
            $scope.individualIdsInError = [];
            $scope.individualsInError = false;
            $scope.isDailyList = [{ value: null, label: "" }, { value: true, label: $scope.resources.Unlimited }, { value: false, label: $scope.resources.Daily }];
            $scope.valuesRequired = true;

            assignmentService.getWordingStyleParameter().success(function (data) {
                $scope.wordingStyle = data;
            });


            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            };

            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            var hideFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("hide");
            };

            var showFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("show");
            };

            /**************** Getters ******************/


            $scope.getUserUnitsTree = function (providerId) {

                if ($scope.units.indexOf(loadingItem) === -1) {
                    $scope.units = [];
                    $scope.units.push(loadingItem);
                }

                if ($scope.useCategories()) {
                    $scope.assignment.CategoriesIds = [];
                    $scope.getCategories($scope.assignment.EventId, providerId);
                }

                assignmentService.getUnitsTreeByProviderId($scope.assignment.EventId, providerId).success(function (data) {
                    $scope.units = [];
                    //set default unit
                    if (data.length > 0 && $scope.assignment.CreationUnitId === null) {
                        $scope.assignment.CreationUnitId = data[0].OrganizationUnitId;
                        $scope.assignment.ProfileId = null;
                        $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                    }
                    angular.forEach(data, function (value, key) {
                        $scope.units.push(value);
                    });
                });
            }

            $scope.getProviders = function (q) {
                if ($scope.providers.indexOf(loadingItem) === -1) {
                    $scope.providers = [];
                    $scope.providers.push(loadingItem);
                }
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                    });
            };

            $scope.selectAllZones = function () {
                var untoggleAll = ($scope.zones.length + $scope.surZones.length) === $scope.assignment.ZoneIds.length;
                if (untoggleAll) {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    angular.forEach($scope.surZones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    $scope.allZonesSelected = false;
                } else {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.assignment.ZoneIds.push(zone.ZoneId);
                        }
                    });
                    angular.forEach($scope.surZones,
                        function (zone) {
                            var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                            if (index < 0) {
                                $scope.assignment.ZoneIds.push(zone.ZoneId);
                            }
                        });
                    $scope.allZonesSelected = true;
                }
            }

            $scope.selectZone = function (zoneId) {
                var index = $scope.assignment.ZoneIds.indexOf(zoneId);
                if (index < 0) {
                    $scope.assignment.ZoneIds.push(zoneId);
                } else {
                    $scope.assignment.ZoneIds.splice(index, index + 1);
                }
            }

            $scope.getZonesByProfileId = function (profile) {
                assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {
                    angular.forEach(zones, function (value, key) {
                        $scope.assignment.ZoneIds.push(value.ZoneId);
                    });
                });
            }

            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required === true && (customField.Values.length > 0 || customField.File !== null)) || customField.Required === false;
                return verif;
            }

            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            }

            $scope.isModifiable = function () {
                return contextService.isModifiable($scope.isUpdate, $scope.assignment.Status, $scope.user);
            }

            $scope.isValidable = function () {
                return contextService.isValidable($scope.assignment.Status, $scope.user);
            }

            /**************** Actions ******************/

            $scope.affecter = function (form) {
                $scope.loading = true;
                form.$submitted = true;
                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily === true || $scope.assignment.HasAccessToAllEvent === true || (length > 0 && length <= 5);

                if (form.$valid && verifSteps && $scope.checkCustomFields()) {
                    // creer une affectation
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentAccess($scope.assignment);
                    assignmentService.addGuestAssignment($scope.assignment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                        $scope.loading = false;
                    });
                } else {
                    $scope.loading = false;
                }
            };

            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        showFormAssigmentSpinner();
                        assignmentService.cancelAssignment([$scope.assignment.AssignmentId], $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            hideFormAssigmentSpinner();
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.getUnitConfiguration = function (creationUnitId) {
                $scope.profiles.push(loadingItem);
                assignmentService.GetUnitConfiguration(creationUnitId, "GuestAssignment").success(function (data) {
                    $scope.profiles = data.profiles;
                    if (!$scope.isUpdate) {
                        $scope.assignment.CustomFields = data.customFields;
                    }

                    // réinit zones par unit
                    $scope.zones = [];
                    contextService.zones.forEach(function (value, index) {
                        if (data.zoneIds.indexOf(value.ZoneId) >= 0)
                            $scope.zones.push(value);
                    });
                });
            };

            $scope.modify = function (form) {
                $scope.loading = true;

                form.$submitted = true;
                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily === true || $scope.assignment.HasAccessToAllEvent === true || (length > 0 && length <= 5);

                if (form.$valid && verifSteps && $scope.checkCustomFields()) {

                    // creer une affectation
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentAccess($scope.assignment);
                    assignmentService.modifyGuestAssignment($scope.assignment, $scope.assignment.Comment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ModificationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                        $scope.loading = false;
                    });
                } else {
                    $scope.loading = false;
                }
            };
           
            $scope.getRichStatus = function () {
                assignmentService.getRichStatusForAssignment($scope.assignment.AssignmentId).success(function (data) {
                    $scope.assignment.Status = data.status;
                    hideFormAssigmentSpinner();
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };

            //si en mode création
            if (!$scope.isUpdate) {
                $scope.$watch("event", function (event) {
                    if (event !== null) {
                        $scope.assignment.EventId = event.EventId;
                    }
                }, true);
            }

            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId !== undefined && assignmentTypeId !== 3) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

            if ($scope.isUpdate) {
                showFormAssigmentSpinner();
                assignmentService.getAssignment($routeParams.assignmentId).success(function (data) {
                    $scope.assignment = data;

                    //set time format from datetime
                    if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                        assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                    } else {
                        assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                    }

                    $scope.getRichStatus();
                    $scope.getUnitConfiguration(data.CreationUnitId);
                    $scope.getUserUnitsTree($scope.assignment.ProviderId);

                });
            } else {
                if ($scope.hasPermission(right.UserLevelExclusiveRight)) {
                    $scope.assignment.ProviderId = $scope.user.ProviderId;
                    $scope.assignment.ProviderName = $scope.user.ProviderName;
                    $scope.getUserUnitsTree($scope.assignment.ProviderId);
                }

                $scope.assignment.AccessDetailsModel.IsAbsoluteAccess = $scope.event.IsAbsoluteAccess;

                if ($scope.event.IsAbsoluteAccess) {
                    assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, $scope.event.AccessStartDate, $scope.event.AccessEndDate);
                } else {

                    $scope.assignment.AccessDetailsModel.MinutesNumberBeforeAccess = $scope.event.MinutesNumberBeforeAccess;
                    $scope.assignment.AccessDetailsModel.MinutesNumberAfterAcces = $scope.event.MinutesNumberAfterAccess;
                }
            }
        }]);


angular.module('accreditationApp')
    .controller('guestAssignmentsFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'individualService', 'sharedService', 'assignmentsIds', '$timeout', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, individualService, sharedService, assignmentsIds, $timeout, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            contextService.currentPage.index = "assignmentList";

            //parameter to control displaying profile select in _ProfileForm ( not displayed for guest assignements)
            $scope.displayProfile = true;
            $scope.assignment = {
                EventId: contextService.event.EventId,
                CreationUnitId: null,
                AssignmentIds: [],
                ProvidersIds: [],
                AssignmentTypeId: 3,
                ProfileId: null,
                IndividualFunction: "",
                ProviderId: null,
                GuestProviderName: "",
                ProviderName: null,
                PopulationCode: "",
                ReferenceCodeId: null,
                ValidityStartDate: "",
                ValidityEndDate: "",
                HasAccessToAllEvent: $scope.isDailyAccreditationActive ? false : null,
                Area: "",
                Row: "",
                Seat: "",
                Comment: "",
                CustomFields: [],
                AssignmentLines: [],
                ZoneIds: [],
                ZoneIdsToAdd: [],
                ZoneIdsToDelete: [],
                StepIds: [],
                IsDaily: !contextService.event.IsGroup,
                Status: [],
                GuestsNames: [],
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {},
                Categories: [],
                CategoriesIds: []
            }

            assignmentService.getWordingStyleParameter().success(function (data) {
                $scope.wordingStyle = data;
            });
            $scope.useMultiSite = site.params.useMultiSite;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.event = contextService.event;
            $scope.providers = [];
            $scope.deliveryPlaces = contextService.deliveryPlaces;
            $scope.zones = [];
            $scope.surZones = contextService.surZones;
            $scope.profiles = [];
            $scope.referenceCodes = [];
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.steps = contextService.steps;
            $scope.user = contextService.user;
            $scope.isDailyList = [{ value: null, label: "" }, { value: true, label: $scope.resources.Unlimited }, { value: false, label: $scope.resources.Daily }];
            $scope.assignmentsId = [];
            $scope.disableProfiles = false;
            $scope.disableUnits = false;
            $scope.disableDeliveryPlace = false;
            $scope.isMultipleUpdate = true;
            $scope.customFieldsToDelete = [];
            $scope.allZonesToAddSelected = false;
            $scope.allZonesToDeleteSelected = false;
            $scope.allZonesSelected = false;
            $scope.valuesRequired = false;

            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            }

            var hideFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("hide");
            };

            var showFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("show");
            };

            /**************** Getters ******************/

            $scope.getUserUnitsTree = function (providersIds) {
                if ($scope.units.indexOf(loadingItem) === -1) {
                    $scope.units = [];
                    $scope.units.push(loadingItem);
                }

                if ($scope.useCategories()) {
                    $scope.$scope.getCategoriesByEvent($scope.assignment.EventId);
                }

                if (contextService.event.IsGroup && $scope.useMultiSite) {
                    assignmentService
                        .getCategorieByProviderId(providerId)
                        .success(function (data) {
                                angular.forEach(data, function (value) {
                                    $scope.categories.push(value);
                                });
                            }
                        );
                }

                assignmentService.getUnitsTreeByProvidersId($scope.assignment.EventId, providersIds).success(function (data) {
                    $scope.units = [];
                    angular.forEach(data, function (value, key) {
                        $scope.units.push(value);
                    });
                    if ($scope.units.length == 0) {
                        $scope.disableUnits = true;
                    }
                });
            }

            $scope.getProviders = function (q) {
                $scope.providers = [];
                $scope.providers.push(loadingItem);
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length == 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            };

            $scope.selectAllZones = function (event, status) {

                $("input[data-status=" + status + "]").each(function () {
                    var checkbox = $(this);
                    var toCheck = event.target.checked;
                    if (checkbox.prop('checked') != toCheck) {

                        $timeout(function () {
                            checkbox.click();
                        });
                    }
                });

            }

            //$scope.selectZone = function (zoneId) {
            //    var index = $scope.assignment.ZoneIds.indexOf(zoneId);
            //    if (index < 0) {
            //        $scope.assignment.ZoneIds.push(zoneId);
            //    } else {
            //        $scope.assignment.ZoneIds.splice(index, index + 1);
            //    }
            //}

            $scope.updateArrayZone = function (zoneId, arrayZoneToPush, arrayZoneToSplice) {
                var index = arrayZoneToPush.indexOf(zoneId);
                if (index < 0) {
                    arrayZoneToPush.push(zoneId);
                    var indexToSplice = arrayZoneToSplice.indexOf(zoneId);
                    if (indexToSplice > -1) {
                        arrayZoneToSplice.splice(indexToSplice, 1);
                    }
                } else {
                    arrayZoneToPush.splice(index, 1);
                }
            }

            $scope.selectZone = function (zoneId, status) {
                if (status == 0) {
                    $scope.updateArrayZone(zoneId, $scope.assignment.ZoneIdsToDelete, $scope.assignment.ZoneIdsToAdd);
                    $("input[data-status=1][name='ZoneIdsToAdd[]'][value='" + zoneId + "']").prop('checked', false);
                    $scope.allZonesToAddSelected = false;
                    if ($scope.assignment.ZoneIdsToDelete.length === ($scope.zones.length + $scope.surZones.length)) {
                        $scope.allZonesToDeleteSelected = true;
                    } else {
                        $scope.allZonesToDeleteSelected = false;
                    }
                } else if (status == 1) {
                    $scope.updateArrayZone(zoneId, $scope.assignment.ZoneIdsToAdd, $scope.assignment.ZoneIdsToDelete);
                    $("input[data-status=0][name='ZoneIdsToDelete[]'][value='" + zoneId + "']").prop('checked', false);
                    $scope.allZonesToDeleteSelected = false;
                    if ($scope.assignment.ZoneIdsToAdd.length === ($scope.zones.length + $scope.surZones.length)) {
                        $scope.allZonesToAddSelected = true;
                    } else {
                        $scope.allZonesToAddSelected = false;
                    }
                }
            }

            $scope.getZonesByProfileId = function (profile) {
                assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {

                    // On va rajouter les zones du profil
                    $("input[data-status=1]").each(function () {
                        var checkbox = $(this);
                        var checkboxZoneId = checkbox.val();
                        if ($.grep(zones, function (z) { return z.ZoneId == checkboxZoneId; })[0]) {
                            if (checkbox.prop('checked') != true) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        } else {
                            if (checkbox.prop('checked') != false) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        }
                    });

                    // On va supprimer toutes les autres zones
                    $("input[data-status=0]").each(function () {
                        var checkbox = $(this);
                        var checkboxZoneId = checkbox.val();
                        if (!$.grep(zones, function (z) { return z.ZoneId == checkboxZoneId; })[0]) {
                            if (checkbox.prop('checked') != true) {
                                $timeout(function () {
                                    checkbox.click();
                                });
                            }
                        }
                    });
                });
            }

            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) || customField.Required == false;
                return verif;
            }


            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            }

            $scope.isModifiable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isModifiable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            $scope.isValidable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isValidable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            /**************** Actions ******************/

            $scope.affecter = function (form) {
                $scope.loading = true;
                form.$submitted = true;
                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily == true || $scope.assignment.HasAccessToAllEvent == true || (length > 0 && length <= 5);

                //manage customs fields to remove
                $scope.assignment.CustomFieldsIdsToDelete = [];
                for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                    if ($scope.customFieldsToDelete[i])
                        $scope.assignment.CustomFieldsIdsToDelete.push(i);
                }

                if (form.$valid && verifSteps) {
                    // creer une affectation
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentsAccess($scope.assignment);
                    assignmentService.updateAndValidateAssignments($scope.assignment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;
                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                        $scope.loading = false;
                    });
                } else {
                    $scope.loading = false;
                }
            };

            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        showFormAssigmentSpinner();
                        assignmentService.cancelAssignment($scope.assignment.AssignmentIds, $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            hideFormAssigmentSpinner();
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.getUnitConfiguration = function (CreationUnitsIds) {
                $scope.profiles.push(loadingItem);
                assignmentService.GetUnitsConfiguration(CreationUnitsIds, "GuestAssignment").success(function (data) {
                    $scope.profiles = data.profiles;

                    if ($scope.profiles.length == 0) {
                        $scope.disableProfiles = true;
                    }

                    // réinit zones par unit
                    $scope.zones = [];
                    contextService.zones.forEach(function (value, index) {
                        if (data.zoneIds.indexOf(value.ZoneId) >= 0)
                            $scope.zones.push(value);
                    });
                });
            };

            $scope.modify = function (form) {
                $scope.loading = true;
                form.$submitted = true;
                var length = $scope.assignment.StepIds.length;
                var verifSteps = $scope.assignment.IsDaily == true || $scope.assignment.HasAccessToAllEvent == true || (length > 0 && length <= 5);

                //manage customs fields to remove
                $scope.assignment.CustomFieldsIdsToDelete = [];
                for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                    if ($scope.customFieldsToDelete[i])
                        $scope.assignment.CustomFieldsIdsToDelete.push(i);
                }

                if (form.$valid && verifSteps) {

                    // creer une affectation
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentsAccess($scope.assignment);
                    assignmentService.updateAssignments($scope.assignment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ModificationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                        $scope.loading = false;
                    });
                } else {
                    $scope.loading = false;
                }
            };
                       
            $scope.getRichStatus = function () {
                $scope.assignment.Status = [];
                angular.forEach($scope.assignment.AssignmentIds, function (id) {
                    assignmentService.getRichStatusForAssignment(id).success(function (data) {
                        $scope.assignment.Status.push(data.status);
                        hideFormAssigmentSpinner();
                    });
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };


            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId != undefined && assignmentTypeId != 3) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

              /**************** Main ******************/
            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            $scope.assignmentsId = assignmentsIds.split(',').map(Number);
            if ($scope.assignmentsId.length > 0) {

                showFormAssigmentSpinner();
                assignmentService.getAssignments($scope.assignmentsId).success(function (data) {
                    $scope.assignment = data;

                    //set time format from datetime
                    if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                        assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                    } else {
                        assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                    }

                    $scope.getRichStatus();
                    $scope.getUnitConfiguration(data.CreationUnitsIds);
                    $scope.getUserUnitsTree($scope.assignment.ProvidersIds);

                });
            }



        }]);


angular.module('accreditationApp')
    .controller('importAssignmentFormController', ['$scope', '$route', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'assignmentService', 'providerService', 'individualService', 'vehicleService', 'Upload', '$timeout', '$controller', function ($scope, $route, $timeout, $filter, $location, $q, $uibModal, contextService, assignmentService, providerService, individualService, vehicleService, Upload, $timeout, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "assignmentList";

        individualService.resetPageState();
        vehicleService.resetPageState();

        // upload later on form submit or something similar
        $scope.submit = function () {
            if ($scope.form.file.$valid && $scope.file && $scope.form.fileZip.$valid) {
                $scope.upload($scope.file, $scope.fileZip);
            }
        };
        $scope.label = null;
        $scope.uploadSuccess = null;
        $scope.applyModifToIndividual = false;
        $scope.ignoreBlacklisted = false;

        // upload on file select or drop
        $scope.upload = function (file, fileZip) {
            $(".form-import").Spinner("show");
            $scope.lineNumber = 0;
            $scope.uploadSuccess = false;

            Upload.upload({
                url: '/Assignment/Import',
                data: { file: file, FileZip: fileZip, eventId: contextService.event.EventId, BypassVerification: $scope.applyModifToIndividual || $scope.ignoreBlacklisted }
            }).then(function (resp) {
                $(".form-import").Spinner("hide");
                $(".modif-results").Spinner("hide");

                if (resp.data.Success) {
                    $scope.uploadSuccess = true;
                    $scope.lineNumber = resp.data.LineNumber;
                    $scope.isError = false;
                } else {
                    $scope.uploadSuccess = false;
                    if (resp.data.Exception) {
                        site.errorMessage(resourcesMessages.ExceptionDuringImport, null);
                    }
                    else {
                        if (resp.data.Exceptions.length > 0) {
                            $scope.gridOptions.totalItems = resp.data.Exceptions.length;
                            $scope.gridOptions.data = resp.data.Exceptions;
                        }
                    }
                    $scope.resize(0);
                }
                console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });

        };

        $scope.validateImportWithModifications = function () {
            $scope.applyModifToIndividual = true;
            $(".modif-results").Spinner("show");
            $scope.submit();
        };

        $scope.acceptBlacklisted = function () {
            $scope.ignoreBlacklisted = true;
            if ($scope.modifOptions.data.length > 0) {
                $scope.showBlacklist = false;
                $scope.showModif = true;
                $scope.ignoreBlacklisted = false;
            } else {
                $(".modif-results").Spinner("show");
                $scope.submit();
            }
        };

        $scope.gridOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'LineNb', displayName: "Ligne", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorField', displayName: "Champ", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorType', displayName: "Type d'érreur", enableColumnMenu: false },
                { field: 'ErrorMessage', displayName: "Message", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }
        };

        $scope.modifOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne mise à jour", enableSorting: false, enableColumnMenu: false },

                { field: 'FieldName', enableSorting: false, displayName: "Champ modifié", enableColumnMenu: false },
                { field: 'OldValue', enableSorting: false, displayName: "Ancienne valeur", enableColumnMenu: false },

                { field: 'NewValue', enableSorting: false, displayName: "Nouvelle valeur", enableColumnMenu: false }

            ],
            onRegisterApi: function (gridApi) {
                $scope.modifApi = gridApi;
            }
        };

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('modifApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('blacklistApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });


        $scope.resize = function (plus) {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height + plus);
                $scope.gridApi.grid.handleWindowResize();
            }
            if ($scope.modifApi) {
                if ($scope.modifOptions.totalItems > 0) {
                    $scope.modifApi.core.refresh();
                    var row_height = $scope.modifOptions.rowHeight;
                    var header_height = $scope.modifOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.modifApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.modifApi.grid.handleWindowResize();
                }
            }
            if ($scope.blacklistApi) {
                if ($scope.blacklistOptions.totalItems > 0) {
                    $scope.blacklistApi.core.refresh();
                    var row_height = $scope.blacklistOptions.rowHeight;
                    var header_height = $scope.blacklistOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.blacklistApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.blacklistApi.grid.handleWindowResize();
                }
            }
        };

        $scope.getImportTemplate = function () {
            var unitSelect = $uibModal.open({
                templateUrl: '/Scripts/Angular/Assignment/Views/UnitSelect.html',
                controller: 'unitSelectFormController',
            });

            unitSelect.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                } else {
                    site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                }
            });

        };

    }]);

angular.module('accreditationApp')
    .controller('mailFormController', ['$scope', '$uibModalInstance', 'contextService', 'assignmentService', 'assignmentIds', '$controller', function ($scope, $uibModalInstance, contextService, assignmentService, assignmentIds, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.numberAssignments = assignmentIds.length;

        $scope.send = function () {
            $(".modal-content").Spinner("show");
            assignmentService.SendEmail(assignmentIds).success(function (data) {
                $(".modal-content").Spinner("hide");
                $uibModalInstance.close(data);
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('messageFormController', ['$scope', '$uibModalInstance', 'contextService', 'assignmentService', 'assignmentIds', '$controller', function ($scope, $uibModalInstance, contextService, assignmentService, assignmentIds, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.numberAssignments = assignmentIds.length;


        $scope.form = {
            subject: null,
            message: null,
            assignmentIds: assignmentIds
        }

        $scope.validate = function(form) {
            $(".modal-content").Spinner("show");
            assignmentService.SendMessage(form).success(function(data) {
                $(".modal-content").Spinner("hide");
                $uibModalInstance.close(data);
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('printFormController', ['$rootScope', '$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', '$uibModalInstance', 'contextService', 'assignmentService', 'providerService', 'assignmentIds', 'alreadyPrinted', 'canSendTitleByMail', '$controller',
        function ($rootScope, $scope, $filter, $q, $routeParams, $uibModal, $location, $uibModalInstance, contextService, assignmentService, providerService, assignmentIds, alreadyPrinted, canSendTitleByMail, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.printForm = {
            MockupGuid: null,
            AssignmentIds: assignmentIds,
            isFirefox: false,
            ReasonId: null,
            SendTitleByMail: false
        };
        $scope.mockups = contextService.mockups;
        $scope.reasons = [];
        $scope.alreadyPrinted = alreadyPrinted;
        $scope.canSendTitleByMail = canSendTitleByMail;
        $scope.SendTitleByMailMessage = assignmentIds.length > 1 ? $scope.resources.SendAssignmentsByMail : $scope.resources.SendAssignmentByMail;
        if ($scope.mockups.length !== 0) {
            $scope.printForm.MockupGuid = $scope.mockups[0].Guid;
        }
        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
        if ($scope.mockups.length === 0) {
            $scope.mockups.push(noResultItem);
        }
        if ($scope.alreadyPrinted) {
            assignmentService.getReasons().success(function (data) {
                if (data.Success) {
                    $scope.reasons = data.data;
                } else {
                    if (data.Exception)
                        site.errorMessage($scope.resourcesMessages.PrintFailed, data.Exception);
                    else
                        site.errorMessage($scope.resourcesMessages.PrintFailed, null);
                }
            }).error(function (err) {
                site.errorMessage($scope.resourcesMessages.PrintFailed);
            });
        } else {
            $scope.printForm.ReasonId = null;
        }

        $scope.print = function (form) {
            form.$submitted = true;
            if (!form.$valid) return;

            $rootScope.IsPrinting = true;
            $(".modal-content").Spinner("show");

            if ($scope.printForm.SendTitleByMail) {
                assignmentService.SendTitleByMail(jQuery.param($scope.printForm, true))
                    .success(function (result) {
                        $(".modal-content").Spinner("hide");
                        $rootScope.IsPrinting = false;
                        $uibModalInstance.close(result);

                    })
                    .error(function () {
                        $(".modal-content").Spinner("hide");
                        $rootScope.IsPrinting = false;

                        $uibModalInstance.close({ Success: false });
                    });
            }
            else {
                assignmentService.GetPdfs(jQuery.param($scope.printForm, true))
                    .success(function (result) {
                        $rootScope.IsPrinting = false;
                        $(".modal-content").Spinner("hide");

                        if (result.Success) {
                            var url = result.data;

                            //Print
                            $.get(url).done(function () {
                                printer.print(url);
                            }).fail(function () {
                                if (!window.downloadFile.isFirefox) {
                                    site.errorMessage($scope.resourcesMessages.PrintFailed);
                                }
                            });

                            //Download
                            $.get(url).done(function () {
                                if (!window.downloadFile.isChrome) {
                                    window.open("/File/GetFileByName?name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                else {
                                    window.downloadFile(url);
                                }

                                $uibModalInstance.close({ Success: true, data: null });
                        
                            }).fail(function () {
                                site.errorMessage($scope.resourcesMessages.PrintFailed);
                            });
                        } else {
                            site.errorMessage($scope.resourcesMessages.NoAccreditationIsSelected);
                        }

                        
                    })
                    .error(function () {
                        $rootScope.IsPrinting = false;
                        $(".modal-content").Spinner("hide");
                        $uibModalInstance.close({ Success: false });
                    });
            }
        };

        $scope.cancel = function () {
            $rootScope.IsPrinting = false;
            $uibModalInstance.dismiss('cancel');
        };
    }]);


angular.module('accreditationApp')
    .controller('sendAccessControlFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', '$uibModalInstance', 'contextService', 'assignmentService', 'providerService', 'assignmentIds', '$controller', function ($scope, $filter, $q, $routeParams, $uibModal, $location, $uibModalInstance, contextService, assignmentService, providerService, assignmentIds, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.sendAccessControl = function (form) {
            form.$submitted = true;
            $(".modal-content").Spinner("show");

            assignmentService.SendAccessControl(contextService.event.EventId, assignmentIds).success(function (data) {
                $uibModalInstance.close(data);
            });
        };


        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('unitSelectFormController', ['$scope', '$uibModalInstance', 'contextService', 'assignmentService', 'messageService', '$controller', function ($scope, $uibModalInstance, contextService, assignmentService, messageService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.userUnits = [];
        assignmentService.getUserUnitsTree(contextService.event.EventId).success(function (data) {
            angular.forEach(data, function (value, key) {
                $scope.userUnits.push(value);
            });
        });
       
        $scope.form = {
            subject: null,
            message: null,
            isValid: true,
        }

        $scope.validate = function (vform) {
            if ($scope.form.isValid && ($scope.selectedUnitId != "undefined" && $scope.selectedUnitId != null && $scope.selectedUnitId != "")) {
                assignmentService.GetIndividualAssignmentTemplate($scope.selectedUnitId);
                $uibModalInstance.dismiss();
            }
        };

        $scope.cancelModal = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.unitSelectionChanged = function (items) {
            if (items != null) {
                if (items[0].children == null) {
                    $scope.selectedUnitId = items[0].id;
                    $scope.form.isValid = true;
                } else {
                    $scope.form.isValid = false;
                }
            }
        }
    }]);


angular.module('accreditationApp')
    .controller('validationFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', '$uibModalInstance', 'contextService', 'assignmentService', 'providerService', 'assignmentIds', 'hasVehicleAssignmentWithoutRequiredMinimumPassenger', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, $modalInstance, contextService, assignmentService, providerService, assignmentIds, hasVehicleAssignmentWithoutRequiredMinimumPassenger, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            $scope.form = {
                Comment: null,
                DeliveryPlaceId: null,
                AssignmentIds: assignmentIds
            };
            $scope.deliveryPlaces = contextService.deliveryPlaces;
            $scope.hasVehicleAssignmentWithoutRequiredMinimumPassenger = hasVehicleAssignmentWithoutRequiredMinimumPassenger;

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

            $scope.validate = function () {
                if ($scope.hasVehicleAssignmentWithoutRequiredMinimumPassenger) {
                    jConfirm(resourcesMessages.CarpoolMinimumPassengerValidation, resources.Warning, function (ok) {
                        if (ok) {
                            assignmentService.validAssignment($scope.form).success(function (data) {
                                $modalInstance.close(data);
                            });
                        }
                    });
                } else {
                    assignmentService.validAssignment($scope.form).success(function (data) {
                        $modalInstance.close(data);
                    });
                }
            };
        }]);


angular.module('accreditationApp')
    .controller('vehicleAssignmentFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'Upload', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, Upload, sharedService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            contextService.currentPage.index = "assignmentList";

            $scope.assignment = {
                EventId: contextService.event.EventId,
                CreationUnitId: null,
                ProviderId: null,
                AssignmentTypeId: 2,
                IndividualId: null,
                VehicleId: null,
                CustomFields: [],
                BarCode: null,
                VehicleNumberGenerationMode: null,
                KeepingOldNumber: false,
                IsDaily: !contextService.event.IsGroup,
                PassengerIds: [],
                Status: "",
                ZoneIds: [],
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {},
                SingleZoneId: null,
                Categories: [],
                CategoriesIds: [],
                HasRequiredMinimumPassenger: true,
                IsRentalVehicle: false
            };
            $scope.individualIdsInError = [];
            $scope.individualsInError = false;
            $scope.vehiclesPage = 1;
            $scope.lastVehiclesQuery = "";
            $scope.busyLoadingVehicles = false;
            $scope.busyLoadingIndividuals = true;
            $scope.individualsPage = 1;
            $scope.lastIndividualsQuery = "";
            $scope.busyLoadingPassengers = true;
            $scope.passengersPage = 1;
            $scope.lastPassengersQuery = "";
            $scope.passengerIsDriver = false;
            $scope.passengerDriverIds = [];
            $scope.tempProvider = null;
            $scope.isUpdate = $routeParams.assignmentId ? true : false;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.event = contextService.event;
            $scope.providers = [];
            $scope.selectedZone = null;
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.individuals = [];
            $scope.passengers = [];
            $scope.vehicles = [];
            $scope.isVehiculeSelectedvalid = false;
            $scope.accreditationInputs = contextService.accreditationInputs;
            $scope.user = contextService.user;
            $scope.uploadFiles = assignmentService.uploadFiles;
            $scope.zones = [];
            $scope.surZones = [];
            $scope.allZonesSelected = false;
            $scope.displayZoneImage = site.params.displayZoneImage;
            $scope.valuesRequired = true;
            $scope.eventCarpools = contextService.event.EventCarpools;
            $scope.minimumPassengerMessage = "";
            $scope.minimumPassenger = 0;

            assignmentService.getParameters(['WordingStyle']).success(function (params) {
                $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;
            });

            assignmentService.getParameters(['MultizoneVehicle']).success(function (params) {
                $scope.multizoneVehicle = params.filter(function (p) { return p.Name === 'MultizoneVehicle'; })[0].Value;
            });

            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
            $scope.size = 40;

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            };

            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            var hideFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("hide");
            };

            var showFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("show");
            };

            /**************** Getters ******************/
            $scope.resetVehicles = function (provider) {
                $scope.vehicles = [];
                $scope.tempProvider = provider;
            };

            $scope.resetIndividuals = function () {
                $scope.individuals = [];
            };

            $scope.getUserUnitsTree = function (providerId) {

                if ($scope.useCategories()) {
                    if (!$scope.isUpdate) {
                        $scope.assignment.CategoriesIds = [];
                    }
                    $scope.getCategories($scope.assignment.EventId, providerId);
                }

                if (providerId !== null) {
                    if ($scope.units.indexOf(loadingItem) === -1) {
                        $scope.units = [];
                        $scope.units.push(loadingItem);
                    }
                    assignmentService.getUnitsTreeByProviderId($scope.assignment.EventId, providerId).success(
                        function (data) {
                            $scope.units = [];

                            //set default unit
                            if (data.length > 0 && $scope.assignment.CreationUnitId == null) {
                                $scope.assignment.CreationUnitId = data[0].OrganizationUnitId;
                                $scope.assignment.ZoneIds = [];
                                $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                            }

                            angular.forEach(data,
                                function (value, key) {
                                    $scope.units.push(value);
                                });
                        });
                }
            };

            $scope.getProviders = function (q) {
                if ($scope.providers.indexOf(loadingItem) == -1) {
                    $scope.providers = [];
                    $scope.providers.push(loadingItem);
                }
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                    });
            };

            $scope.getIndividuals = function (q) {
                $scope.individuals = [];
                if ($scope.assignment.ProviderId != null) {
                    $scope.individuals.push(loadingItem);
                    $scope.individualsPage = 1;
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individuals = [];
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            if ($scope.individuals.length == 0) {
                                $scope.individuals.push(noResultItem);
                            }

                        }).catch(function () {
                            $scope.individuals = [];
                            $scope.individuals.push(noResultItem);
                            site.errorMessage(resourcesMessages.ErrorOccured);
                        });
                }
            };

            $scope.getNextIndividuals = function (q) {
                if ($scope.assignment.ProviderId != null && !$scope.busyLoadingIndividuals) {
                    $scope.busyLoadingIndividuals = true;
                    if (q !== $scope.lastIndividualsQuery) {
                        $scope.individualsPage = 1;
                        $scope.individuals = [];
                    }
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            $scope.busyLoadingIndividuals = false;
                        });
                }
            };

            $scope.getPassengers = function (q) {
                $scope.passengers = [];
                if ($scope.assignment.ProviderId != null) {
                    $scope.passengers.push(loadingItem);
                    $scope.passengersPage = 1;
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.passengersPage, q)
                        .then(function (data) {
                            $scope.passengers = [];
                            $scope.passengersPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.passengers.push(value);
                            });
                            if ($scope.passengers.length == 0) {
                                $scope.passengers.push(noResultItem);
                            }
                        });
                }
            };

            $scope.getNextPassengers = function (q) {
                if ($scope.assignment.ProviderId != null && !$scope.busyLoadingPassengers) {
                    $scope.busyLoadingPassengers = true;
                    if (q !== $scope.lastPassengersQuery) {
                        $scope.passengersPage = 1;
                        $scope.passengers = [];
                    }
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.passengersPage, q)
                        .then(function (data) {
                            $scope.passengersPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.passengers.push(value);
                            });
                            $scope.busyLoadingPassengers = false;
                        });
                }
            };

            $scope.getVehicles = function (q) {
                $scope.vehicles = [];
                if ($scope.assignment.ProviderId != null) {
                    $scope.vehicles.push(loadingItem);
                    $scope.vehiclesPage = 1;
                    return assignmentService.GetAvailableVehicleForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.vehiclesPage, q)
                        .then(function (data) {
                            $scope.vehicles = [];
                            $scope.vehiclesPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.vehicles.push(value);
                            });
                            if ($scope.vehicles.length == 0) {
                                $scope.vehicles.push(noResultItem);
                            }
                        });
                }
            };

            $scope.getNextVehicles = function (q) {
                if ($scope.assignment.ProviderId !== null && !$scope.busyLoadingVehicles) {
                    $scope.busyLoadingVehicles = true;
                    if (q !== $scope.lastVehiclesQuery) {
                        $scope.vehiclesPage = 1;
                        $scope.vehicles = [];
                    }
                    return assignmentService.GetAvailableVehicleForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.vehiclesPage, q)
                        .then(function (data) {
                            $scope.vehiclesPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.vehicles.push(value);
                            });
                            $scope.busyLoadingVehicles = false;
                        });
                }
            };

            $scope.isNullOrEmpty = function (value) {

                if (!value || value == undefined || value == "") {
                    return true;
                }
                return false;
            };

            $scope.isValidVehicule = function (vehicleSelected) {
                if (!$scope.isNullOrEmpty(vehicleSelected.VehicleTypeId)) {
                    $scope.setMinimumPassenger(vehicleSelected.VehicleTypeId);  // Pour mettre à jour même à la sélection d'un véhicule non valide
                }

                if ($scope.isNullOrEmpty(vehicleSelected.VehicleTypeName) ||
                    $scope.isNullOrEmpty(vehicleSelected.BrandName) ||
                    $scope.isNullOrEmpty(vehicleSelected.License) ||
                    $scope.isNullOrEmpty(vehicleSelected.Role) ||
                    $scope.isNullOrEmpty(vehicleSelected.ProviderName) ||
                    $scope.isNullOrEmpty(vehicleSelected.Model) ||
                    (vehicleSelected.Co2 == null && $scope.useCarboneOffset)
                ) {
                    $scope.isVehiculeSelectedvalid = false;
                    return;
                }
                $scope.isVehiculeSelectedvalid = true;
            };

            $scope.isSelectedVehiculeValid = function (vehiculeId) {
                var vehicleSelected = $filter('filter')($scope.vehicles, { VehicleId: vehiculeId })[0];
                return $scope.isValidVehicule(vehicleSelected);
            };

            $scope.isPassengerTheDriver = function (passengerId) {
                if (passengerId === $scope.assignment.IndividualId) {
                    $scope.passengerIsDriver = true;
                    $scope.passengerDriverIds.push(passengerId);
                }
            };

            $scope.isDriverAPassenger = function (driverId) {
                $scope.passengerIsDriver = false;
                $scope.passengerDriverIds = [];
                angular.forEach($scope.assignment.PassengerIds, function (value, key) {
                    $scope.isPassengerTheDriver(value);
                });
            };


            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) ||
                    customField.Required == false;
                return verif;
            };

            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            };

            $scope.getUnitConfiguration = function (creationUnitId, noCustomField) {
                assignmentService.GetUnitConfiguration(creationUnitId, "VehicleAssignment").success(function (data) {
                    $scope.zones = [];
                    angular.forEach(data.vehicleZones, function (value, key) {
                        $scope.zones.push(value);
                    });
                    //pour singlezone
                    $scope.assignment.SingleZoneId = $scope.assignment.ZoneIds[0];
                    $scope.selectedZone = $scope.findSelectedZone($scope.assignment.ZoneIds[0]);
                    if (!noCustomField) {
                        $scope.assignment.CustomFields = data.customFields;
                    }
                });
            };


            $scope.isModifiable = function () {
                return contextService.isModifiable($scope.isUpdate, $scope.assignment.Status, $scope.user);
            };

            $scope.isValidable = function () {
                return contextService.isValidable($scope.assignment.Status, $scope.user);
            };

            $scope.selectAllZones = function () {
                var untoggleAll = ($scope.zones.length + $scope.surZones.length) === $scope.assignment.ZoneIds.length;
                if (untoggleAll) {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    angular.forEach($scope.surZones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index >= 0) {
                            $scope.assignment.ZoneIds.splice(0);
                        }
                    });
                    $scope.allZonesSelected = false;
                } else {
                    angular.forEach($scope.zones, function (zone) {
                        var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.assignment.ZoneIds.push(zone.ZoneId);
                        }
                    });
                    angular.forEach($scope.surZones,
                        function (zone) {
                            var index = $scope.assignment.ZoneIds.indexOf(zone.ZoneId);
                            if (index < 0) {
                                $scope.assignment.ZoneIds.push(zone.ZoneId);
                            }
                        });
                    $scope.allZonesSelected = true;
                }
            }

            $scope.selectZone = function (zoneId) {
                if ($scope.multizoneVehicle) {
                    //multizione management
                    var index = $scope.assignment.ZoneIds.indexOf(zoneId);
                    if (index < 0) {
                        $scope.assignment.ZoneIds.push(zoneId);
                        if ($scope.assignment.ZoneIds.length === ($scope.zones.length + $scope.surZones.length)) {
                            $scope.allZonesSelected = true;
                        }
                    } else {
                        $scope.assignment.ZoneIds.splice(index, 1);
                        $scope.allZonesSelected = false;
                    }
                } else {
                    //singlezone management
                    $scope.assignment.ZoneIds = [];
                    $scope.assignment.ZoneIds.push(zoneId);
                }
            }
            $scope.getZonesByProfileId = function (profile) {
                assignmentService.getZonesByProfileId(profile.ProfileId).success(function (zones) {
                    angular.forEach(zones,
                        function (value, key) {
                            $scope.assignment.ZoneIds.push(value.ZoneId);
                        });
                });
            };

            $scope.setMinimumPassenger = function (vehicleTypeId) {
                if ($scope.eventCarpools.length === null || $scope.eventCarpools.length === 0) {
                    $scope.minimumPassenger = 0;
                    $scope.minimumPassengerMessage = "";
                    return;
                }

                for (var i = 0; i < $scope.eventCarpools.length; i++) {
                    var eventCarpool = $scope.eventCarpools[i];
                    if (eventCarpool.VehicleTypeId === vehicleTypeId) {
                        $scope.minimumPassenger = eventCarpool.MinimumPassenger;

                        if (eventCarpool.MinimumPassenger > 0) {
                            if (eventCarpool.MinimumPassenger === 1) {
                                $scope.minimumPassengerMessage = resourcesMessages.VehicleMinimumPassenger.replace('{0}', eventCarpool.MinimumPassenger);
                            } else {
                                $scope.minimumPassengerMessage = resourcesMessages.VehicleMinimumPassengers.replace('{0}', eventCarpool.MinimumPassenger);
                            }
                            $scope.minimumPassengerMessage = '(' + $scope.minimumPassengerMessage + ')';
                        } else {
                            $scope.minimumPassengerMessage = "";
                        }
                    }
                }
            };

            $scope.addOrModifyVehicleAssignment = function (form, isAdd) {
                if (isAdd) {
                    $scope.addVehicleAssignment(form);
                } else {
                    $scope.modify(form);
                }
            };

            /**************** Actions ******************/

            $scope.bindAssignment = function (data) {
                if (data !== "") {
                    if ($scope.isUpdate) {
                        $scope.assignment = data; // set all attributs
                        if ($scope.assignment.Vehicle != null) {
                            $scope.isValidVehicule($scope.assignment.Vehicle);
                        }
                        //set time format from datetime
                        if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                            assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                        } else {
                            assignmentService.setDefaultAssignmentAccessStartEndTimes($scope.assignment);
                        }
                    } else {
                        $scope.assignment.SingleZoneId = data.ZoneIds[0];
                        $scope.assignment.IndividualId = data.IndividualId;
                        $scope.assignment.Individual = data.Individual;
                        $scope.assignment.VehicleId = data.VehicleId;
                        $scope.assignment.Vehicle = data.Vehicle;
                        $scope.assignment.CustomFields = data.CustomFields;
                        $scope.assignment.BarCode = data.BarCode;
                        $scope.assignment.VehicleNumberGenerationMode = data.VehicleNumberGenerationMode;
                        $scope.assignment.KeepingOldNumber = data.KeepingOldNumber;
                    }

                    $scope.getUnitConfiguration(data.CreationUnitId, true);
                    if (data.Individual !== null) {
                        $scope.individuals.push(data.Individual);
                    }
                    if (data.Passengers !== null) {
                        angular.forEach(data.Passengers,
                            function (val, key) {
                                $scope.passengers.push(val);
                            });
                    }
                    $scope.getUserUnitsTree($scope.assignment.ProviderId);
                    $scope.oldVehicleNumber = data.BarCode;
                    if ($scope.hasPermission(right.Assignment_CanSetVehicleNumberGenerationMode) && $scope.assignment.BarCode == null) {
                        $scope.assignment.VehicleNumberGenerationMode = "AutoModeReleasingOldNumber";
                    }
                    $scope.getRichStatus();
                }
            };

            $scope.getRichStatus = function () {
                assignmentService.getRichStatusForAssignment($scope.assignment.AssignmentId).success(function (data) {
                    $scope.assignment.Status = data.status;
                    hideFormAssigmentSpinner();
                });
            };

            $scope.modify = function (form) {
                if (form.$valid && $scope.checkCustomFields() && !$scope.passengerIsDriver) {
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentAccess($scope.assignment);

                    assignmentService.modifyVehicleAssignment($scope.assignment, $scope.assignment.Comment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                    });
                }
            };

            $scope.findSelectedZone = function (zoneId) {
                var zone = null;
                $scope.zones.forEach(function (element) {
                    if (element.ZoneId === zoneId)
                        zone = element;
                });
                return zone;
            };

            $scope.addVehicleAssignment = function (form) {
                if (form.$valid && $scope.checkCustomFields() && !$scope.passengerIsDriver && ($scope.assignment.IsRentalVehicle || $scope.isVehiculeSelectedvalid)) {
                    showFormAssigmentSpinner();

                    assignmentService.manageAssignmentAccess($scope.assignment);

                    assignmentService.addVehicleAssignment($scope.assignment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {

                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                    });
                }
            };


            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        showFormAssigmentSpinner();
                        assignmentService.cancelAssignment([$scope.assignment.AssignmentId], $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            hideFormAssigmentSpinner();
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };

            if (!$scope.isUpdate) {
                $scope.$watch("event", function (event) {
                    if (event !== null) {
                        $scope.assignment.EventId = event.EventId;
                    }
                }, true);
            }

            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId !== 2) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

            $scope.$watchCollection("assignment.PassengerIds", function (newIds, oldIds) {
                var deleted = oldIds.filter(function (item) {
                    return newIds.indexOf(item) === -1;
                });
                angular.forEach(deleted, function (value, key) {
                    var index = $scope.passengerDriverIds.indexOf(value);
                    if (index !== -1) {
                        $scope.passengerDriverIds.splice(index, 1);
                        if ($scope.passengerDriverIds.length === 0) {
                            $scope.passengerIsDriver = false;
                        }
                    }
                });
            });

            $scope.validateMinimumPassenger = function (form, isAdd) {
                if ($scope.minimumPassenger > 0 && ($scope.assignment.PassengerIds === null || $scope.minimumPassenger > $scope.assignment.PassengerIds.length)) {
                    $scope.assignment.HasRequiredMinimumPassenger = false;
                    jConfirm(resourcesMessages.CarpoolMinimumPassenger, resources.Warning, function (ok) {
                        if (ok) {
                            $scope.addOrModifyVehicleAssignment(form, isAdd);
                        }
                    });
                } else {
                    $scope.assignment.HasRequiredMinimumPassenger = true;
                    $scope.addOrModifyVehicleAssignment(form, isAdd);
                }
            };

            /**************** Modal individual ******************/

            $scope.modalVehicle = function (vehicleId) {
                $scope.modalIndividualId = vehicleId;
                var modalInstance = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Vehicle/Views/VehicleForm.html?ver=' + $scope.softwareVersion,
                    controller: 'vehicleFormController',
                    size: "lg",
                    resolve: {
                        vehicleId: function () {
                            return $scope.modalIndividualId;
                        },
                        provider: function () {
                            return $scope.tempProvider;
                        }
                    }
                });

                modalInstance.result.then(function (newVehicle) {
                    var vehicle = $filter('filter')($scope.vehicles, { VehicleId: newVehicle.VehicleId })[0];
                    $scope.isValidVehicule(newVehicle);

                    if (vehicle === undefined) {
                        $scope.vehicles.push(newVehicle);
                    } else {
                        angular.extend(vehicle, newVehicle);
                    }
                    $scope.assignment.VehicleId = newVehicle.VehicleId;
                    $scope.assignment.Vehicle = newVehicle;
                });
            };

            if ($scope.isUpdate) {
                showFormAssigmentSpinner();
                assignmentService.getAssignment($routeParams.assignmentId).success($scope.bindAssignment);

            } else {
                $scope.assignment.VehicleNumberGenerationMode = "AutoModeReleasingOldNumber";
                if (!($scope.hasPermission(right.Vehicle_AccessByUserUnit) || $scope.hasPermission(right.Vehicle_AccessToAllUnit))) //not admin nor superadmin
                    $scope.assignment.ProviderId = $scope.user.ProviderId;
                $scope.assignment.ProviderName = $scope.user.ProviderName;
                $scope.getUserUnitsTree($scope.user.ProviderId);
                $scope.getIndividuals();
                $scope.getVehicles();
            }

            $scope.assignment.AccessDetailsModel.IsAbsoluteAccess = $scope.event.IsAbsoluteAccess;

            if ($scope.event.IsAbsoluteAccess) {
                assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, $scope.event.AccessStartDate, $scope.event.AccessEndDate);
            } else {

                $scope.assignment.AccessDetailsModel.MinutesNumberBeforeAccess = $scope.event.MinutesNumberBeforeAccess;
                $scope.assignment.AccessDetailsModel.MinutesNumberAfterAcces = $scope.event.MinutesNumberAfterAcces;
            }
        }
    ]);


angular.module('accreditationApp')
    .controller('vehicleAssignmentsFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'providerService', 'Upload', 'sharedService', 'assignmentsIds', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, providerService, Upload, sharedService, assignmentsIds, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            contextService.currentPage.index = "assignmentList";

            $scope.assignment = {
                EventId: contextService.event.EventId,
                CreationUnitId: null,
                ProvidersIds: [],
                ProviderId: null,
                AssignmentIds: [],
                AssignmentTypeId: 2,
                IndividualId: null,
                VehicleId: null,
                CustomFields: [],
                BarCode: null,
                BarCodeList: [],
                VehicleNumberGenerationMode: null,
                KeepingOldNumber: false,
                IsDaily: !contextService.event.IsGroup,
                PassengerIds: [],
                Status: [],
                ZoneIds: [],
                Comment: null,
                DeleteComment: false,
                AccessStartTime: "",
                AccessEndTime: "",
                AccessStartDate: "",
                AccessEndDate: "",
                AccessDetailsModel: {},
                Categories: [],
                CategoriesIds: []
            }
            $scope.individualIdsInError = [];
            $scope.vehiclesPage = 1;
            $scope.lastVehiclesQuery = "";
            $scope.busyLoadingVehicles = false;
            $scope.busyLoadingIndividuals = true;
            $scope.individualsPage = 1;
            $scope.lastIndividualsQuery = "";
            $scope.busyLoadingPassengers = true;
            $scope.passengersPage = 1;
            $scope.lastPassengersQuery = "";
            $scope.passengerIsDriver = false;
            $scope.passengerDriverIds = [];
            $scope.tempProvider = null;
            $scope.assignmentTypes = contextService.createAssignmentTypes;
            $scope.event = contextService.event;
            $scope.providers = [];
            $scope.zones = [];
            $scope.selectedZone = null;
            $scope.organizationUnitId = [];
            $scope.units = [];
            $scope.individuals = [];
            $scope.passengers = [];
            $scope.vehicles = [];
            $scope.isVehiculeSelectedvalid = false;
            $scope.accreditationInputs = contextService.multipleAccreditationInputs;
            $scope.user = contextService.user;
            $scope.uploadFiles = assignmentService.uploadFiles;
            $scope.assignmentsId = [];
            $scope.disableProfiles = false;
            $scope.profiles = [];
            $scope.customFieldsToDelete = [];
            $scope.useMultiSite = site.params.useMultiSite;
            $scope.valuesRequired = false;

            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
            $scope.size = 40;
            $scope.groupByUnit = function (item) {
                return item.ParentName;
            };

            var hideFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("hide");
            };

            var showFormAssigmentSpinner = function () {
                $(".form-assignment").Spinner("show");
            };

            /**************** Getters ******************/

            $scope.resetVehicles = function (provider) {
                $scope.vehicles = [];
                $scope.tempProvider = provider;
            };

            $scope.resetIndividuals = function () {
                $scope.individuals = [];
            };

            $scope.getUserUnitsTree = function (providersIds) {
                if (providersIds !== null && providersIds.length > 0) {
                    if ($scope.units.indexOf(loadingItem) === -1) {
                        $scope.units = [];
                        $scope.units.push(loadingItem);
                    }

                    if ($scope.useCategories()) {
                        $scope.$scope.getCategoriesByEvent($scope.assignment.EventId);
                    }

                    if (contextService.event.IsGroup && $scope.useMultiSite ) {
                        assignmentService
                            .getCategorieByProviderId(providerId)
                            .success(function (data) {
                                    angular.forEach(data, function (value) {
                                        $scope.categories.push(value);
                                    });
                                }
                            );
                    }

                    assignmentService.getUnitsTreeByProvidersId($scope.assignment.EventId, providersIds).success(function (data) {
                        $scope.units = [];

                        angular.forEach(data, function (value, key) {
                            $scope.units.push(value);
                        });
                        if ($scope.units.length === 0) {
                            $scope.disableUnits = true;
                        }
                    });
                }

            }

            $scope.getProviders = function (q) {
                $scope.providers = [];
                $scope.providers.push(loadingItem);
                return providerService.getProviders(1, q, $scope.event.OrganizationId)
                    .then(function (data) {
                        $scope.providers = [];
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length === 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            };

            $scope.getIndividuals = function (q) {
                $scope.individuals = [];
                if ($scope.assignment.ProviderId !== null) {
                    $scope.individuals.push(loadingItem);
                    $scope.individualsPage = 1;
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individuals = [];
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            if ($scope.individuals.length === 0) {
                                $scope.individuals.push(noResultItem);
                            }


                        });
                }
            };

            $scope.getNextIndividuals = function (q) {
                if ($scope.assignment.ProviderId !== null && !$scope.busyLoadingIndividuals) {
                    $scope.busyLoadingIndividuals = true;
                    if (q !== $scope.lastIndividualsQuery) {
                        $scope.individualsPage = 1;
                        $scope.individuals = [];
                    }
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.individualsPage, q)
                        .then(function (data) {
                            $scope.individualsPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.individuals.push(value);
                            });
                            $scope.busyLoadingIndividuals = false;
                        });
                }
            };

            $scope.getPassengers = function (q) {
                $scope.passengers = [];
                if ($scope.assignment.ProviderId !== null) {
                    $scope.passengers.push(loadingItem);
                    $scope.passengersPage = 1;
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.passengersPage, q)
                        .then(function (data) {
                            $scope.passengers = [];
                            $scope.passengersPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.passengers.push(value);
                            });
                            if ($scope.passengers.length === 0) {
                                $scope.passengers.push(noResultItem);
                            }
                        });
                }
            };

            $scope.getNextPassengers = function (q) {
                if ($scope.assignment.ProviderId !== null && !$scope.busyLoadingPassengers) {
                    $scope.busyLoadingPassengers = true;
                    if (q !== $scope.lastPassengersQuery) {
                        $scope.passengersPage = 1;
                        $scope.passengers = [];
                    }
                    return assignmentService.GetAvailableIndividualForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.passengersPage, q)
                        .then(function (data) {
                            $scope.passengersPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.passengers.push(value);
                            });
                            $scope.busyLoadingPassengers = false;
                        });
                }
            };

            $scope.getVehicles = function (q) {
                $scope.vehicles = [];
                if ($scope.assignment.ProviderId !== null) {
                    $scope.vehicles.push(loadingItem);
                    $scope.vehiclesPage = 1;
                    return assignmentService.GetAvailableVehicleForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.vehiclesPage, q)
                        .then(function (data) {
                            $scope.vehicles = [];
                            $scope.vehiclesPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.vehicles.push(value);
                            });
                            if ($scope.vehicles.length === 0) {
                                $scope.vehicles.push(noResultItem);
                            }
                        });
                }
            };

            $scope.getNextVehicles = function (q) {
                if ($scope.assignment.ProviderId !== null && !$scope.busyLoadingVehicles) {
                    $scope.busyLoadingVehicles = true;
                    if (q !== $scope.lastVehiclesQuery) {
                        $scope.vehiclesPage = 1;
                        $scope.vehicles = [];
                    }
                    return assignmentService.GetAvailableVehicleForVehicle($scope.assignment.EventId, $scope.assignment.ProviderId, $scope.vehiclesPage, q)
                        .then(function (data) {
                            $scope.vehiclesPage++;
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.vehicles.push(value);
                            });
                            $scope.busyLoadingVehicles = false;
                        });
                }
            };

            $scope.isNullOrEmpty = function (value) {

                if (!value || value === undefined || value === "") {
                    return true;
                }
                return false;
            };

            $scope.isValidVehicule = function (vehicleSelected) {
                if ($scope.isNullOrEmpty(vehicleSelected.VehicleTypeName) ||
                    $scope.isNullOrEmpty(vehicleSelected.BrandName) ||
                    $scope.isNullOrEmpty(vehicleSelected.License) ||
                    $scope.isNullOrEmpty(vehicleSelected.Role) ||
                    $scope.isNullOrEmpty(vehicleSelected.ProviderName) ||
                    $scope.isNullOrEmpty(vehicleSelected.Model)) {
                    $scope.isVehiculeSelectedvalid = false;
                    return;
                }
                $scope.isVehiculeSelectedvalid = true;
            };

            $scope.isSelectedVehiculeValid = function (vehiculeId) {
                var vehicleSelected = $filter('filter')($scope.vehicles, { VehicleId: vehiculeId })[0];
                return $scope.isValidVehicule(vehicleSelected);
            };

            $scope.isPassengerTheDriver = function (passengerId) {
                if (passengerId === $scope.assignment.IndividualId) {
                    $scope.passengerIsDriver = true;
                    $scope.passengerDriverIds.push(passengerId);
                }
            };

            $scope.isDriverAPassenger = function (driverId) {
                $scope.passengerIsDriver = false;
                $scope.passengerDriverIds = [];
                angular.forEach($scope.assignment.PassengerIds, function (value, key) {
                    $scope.isPassengerTheDriver(value);
                });
            };

            $scope.selectZone = function (zone) {
                $scope.assignment.ZoneIds = [zone.ZoneId];
            };


            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required === true && (customField.Values.length > 0 || customField.File !== null)) || customField.Required === false;
                return verif;
            }


            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.assignment.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.assignment.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            }

            $scope.getUnitConfiguration = function (CreationUnitsIds, noCustomField) {
                $scope.profiles.push(loadingItem);
                assignmentService.GetUnitsConfiguration(CreationUnitsIds, "VehicleAssignment").success(function (data) {
                    $scope.zones = [];
                    angular.forEach(data.vehicleZones, function (value, key) {
                        $scope.zones.push(value);
                    });
                    $scope.selectedZone = $scope.findSelectedZone($scope.assignment.ZoneId);
                    if (!noCustomField) {
                        $scope.assignment.CustomFields = data.customFields;
                    }

                    if ($scope.profiles.length === 0) {
                        $scope.disableProfiles = true;
                    }
                });
            };


            $scope.isModifiable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isModifiable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            $scope.isValidable = function () {
                angular.forEach($scope.assignment.Status, function (status) {
                    if (!contextService.isValidable(true, status, $scope.user)) {
                        return false;
                    }
                });
                return true;
            }

            /**************** Actions ******************/

            $scope.bindAssignment = function (data) {
                if (data !== "") {
                    $scope.assignment = data; 

                    //set time format from datetime
                    if (data.AccessDetailsModel.AccessStartDate && data.AccessDetailsModel.AccessEndDate) {
                        assignmentService.formatAssignmentAccessStartEndDates($scope.assignment, data.AccessDetailsModel.AccessStartDate, data.AccessDetailsModel.AccessEndDate);
                    }

                    $scope.getUnitConfiguration(data.CreationUnitsIds, true);
                    if (data.Individual !== null) {
                        $scope.individuals.push(data.Individual);
                    }
                    if (data.Passengers !== null) {
                        angular.forEach(data.Passengers, function (val, key) {
                            $scope.passengers.push(val);
                        });
                    }
                    $scope.getUserUnitsTree($scope.assignment.ProvidersIds);
                    

                    $scope.getRichStatus();
                }
            }

           
            $scope.getRichStatus = function () {
                $scope.assignment.Status = [];
                angular.forEach($scope.assignment.AssignmentIds, function (id) {
                    assignmentService.getRichStatusForAssignment(id).success(function (data) {
                        $scope.assignment.Status.push(data.status);
                        hideFormAssigmentSpinner();
                    });
                });
            };

            $scope.modify = function (form) {
                if (form.$valid && !$scope.passengerIsDriver) {

                    //manage customs fields to remove
                    $scope.assignment.CustomFieldsIdsToDelete = [];
                    for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                        if ($scope.customFieldsToDelete[i])
                            $scope.assignment.CustomFieldsIdsToDelete.push(i);
                    }

                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentsAccess($scope.assignment);
                    assignmentService.modifyVehiclesAssignment($scope.assignment, $scope.assignment.Comment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                    });
                }
            };
           
            $scope.findSelectedZone = function (zoneId) {
                var zone = null;
                $scope.zones.forEach(function (element) {
                    if (element.ZoneId === zoneId)
                        zone = element;
                });
                return zone;
            }

            $scope.addVehicleAssignment = function (form) {
                if (form.$valid  && !$scope.passengerIsDriver) {
                    showFormAssigmentSpinner();
                    assignmentService.manageAssignmentsAccess($scope.assignment);

                    //manage customs fields to remove
                    $scope.assignment.CustomFieldsIdsToDelete = [];
                    for (var i = 0; i < $scope.customFieldsToDelete.length; i++) {
                        if ($scope.customFieldsToDelete[i])
                            $scope.assignment.CustomFieldsIdsToDelete.push(i);
                    }

                    assignmentService.modifyAndValidateVehiclesAssignment($scope.assignment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/assignmentList/');
                        } else {
                            $scope.assignment.AccessStartDate = $scope.assignment.AccessStartDate;
                            $scope.assignment.AccessEndDate = $scope.assignment.AccessEndDate;

                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                            else
                                site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                        hideFormAssigmentSpinner();
                    });
                }
            };

            $scope.cancel = function () {
                var ok;
                jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                    if (ok) {
                        showFormAssigmentSpinner();
                        assignmentService.cancelAssignment($scope.assignment.AssignmentIds, $scope.assignment.Comment).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/assignmentList/');
                            }
                            hideFormAssigmentSpinner();
                        });
                        $scope.$apply();
                    }
                });
            };

            $scope.showActionsHistory = function (assignmentId) {
                assignmentService.getActionsHistory(assignmentId).success(function (data) {
                    $scope.actions = data;
                    $(".widget-side").show("slide", { "direction": "left" });
                });
            };


            $scope.$watch("assignment.AssignmentTypeId", function (assignmentTypeId) {
                if (assignmentTypeId !== 2) {
                    $location.path($filter('filter')($scope.assignmentTypes, { AssignmentTypeId: assignmentTypeId })[0].Url);
                }
            });

            $scope.$watchCollection("assignment.PassengerIds", function (newIds, oldIds) {
                var deleted = oldIds.filter(function (item) {
                    return newIds.indexOf(item) === -1;
                });
                angular.forEach(deleted, function (value, key) {
                    var index = $scope.passengerDriverIds.indexOf(value);
                    if (index !== -1) {
                        $scope.passengerDriverIds.splice(index, 1);
                        if ($scope.passengerDriverIds.length === 0) {
                            $scope.passengerIsDriver = false;
                        }
                    }
                });
            });

            /**************** Modal individual ******************/

            $scope.modalVehicle = function (vehicleId) {
                $scope.modalIndividualId = vehicleId;
                var modalInstance = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Vehicle/Views/VehicleForm.html?ver=' + $scope.softwareVersion,
                    controller: 'vehicleFormController',
                    size: "lg",
                    resolve: {
                        vehicleId: function () {
                            return $scope.modalIndividualId;
                        },
                        provider: function () {
                            return $scope.tempProvider;
                        }
                    }
                });

                modalInstance.result.then(function (newVehicle) {
                    var vehicle = $filter('filter')($scope.vehicles, { VehicleId: newVehicle.VehicleId })[0];
                    $scope.isValidVehicule(newVehicle);

                    if (vehicle === undefined) {
                        $scope.vehicles.push(newVehicle);
                    } else {
                        angular.extend(vehicle, newVehicle);
                    }
                    $scope.assignment.VehicleId = newVehicle.VehicleId;
                    $scope.assignment.Vehicle = newVehicle; 
                });
            };

            /**************** Main ******************/
            assignmentService.getParameters(['WordingStyle']).success(function (params) {
                $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;
            });

            sharedService.getRgpd().success(function (data) {
                $scope.rgpd = data.data;
            });

            $scope.assignmentsId = assignmentsIds.split(',').map(Number);
            if ($scope.assignmentsId.length > 0) {
                showFormAssigmentSpinner();
                assignmentService.getAssignments($scope.assignmentsId).success($scope.bindAssignment);
            }
        }]);


angular.module('accreditationApp')
.directive('myBlockAutoresize', function () {
    return {
        scope: true,
        link: function (scope, elem, attr) {
            scope.$watch(function () {
                return elem[0].clientHeight;
            }, function (value) {
                 
                if (value != 0) {
                    scope.$evalAsync(
                        function ($scope) {
                            var height = value;
                            $scope.$parent.row.expandedRowHeight = height;
                            $scope.$parent.grid.appScope.resize(height);
                        }
                    );
                  
                }
            });
        }
    };
});
angular.module('accreditationApp')
    .service('assignmentService', ['$resource', '$http', '$location', 'Upload', 'contextService',
        function ($resource, $http, $location, Upload, contextService) {

            this.pageStateModel = {
                search: {
                    EventId: site.event != null ? site.event.EventId : {},
                    UnitIds: [],
                    ZoneIds: [],
                    AssignmentTypeId: null,
                    StepIds: [],
                    ProviderId: null,
                    IndividualName: null,
                    ProfileId: null,
                    Population: null,
                    CreatorUserId: null,
                    EditorUserId: null,
                    ValidationStartDate: null,
                    ValidityStartDate: "",
                    ValidationEndDate: "",
                    HasImage: null,
                    IsValid: true,
                    IsWaiting: true,
                    IsSuperior: true,
                    IsInferior: true,
                    IsRefused: false,
                    IsToDo: true,
                    IsDaily: contextService.event.IsGroup ? null : true,
                    PrintStatus: null,
                    AccessStatus: null,
                    HasAffiliateProviderAccreditationInclude: false,
                    MailStatusIds: [],
                    IndividualCustomFields: [],
                    AssignmentCustomFields: [],
                    OnlyBlacklisted: false,
                    OnlyAccessControlErrors: false,
                    Barcode: null,
                    smsStatus: null,
                    Status: {
                        Valid: 0,
                        Waiting: 0,
                        WaitingInferior: 0,
                        WaitingSuperior: 0,
                        Refused: 0
                    },

                    FilterStartDate: "",
                    FilterEndDate: "",
                    FilterStartTime: "",
                    FilterEndTime: "",
                    FilterTypeDate: "",
                    BillingProfileId: null
                },
                showMore: false,
                units: [],
                creators: [],
                editors: [],
                populations: [],
                providers: []
            };

            this.pageState = {};

            this.resetPageState = function () {
                angular.copy(this.pageStateModel, this.pageState);
            };

            this.addAssignment = function (assignment) {
                return $http.post('/Assignment/Add',
                    $.param(assignment),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };


            this.getActionsHistory = function (assignmentId) {
                return $http.post('/Assignment/GetActionsByAssignmentId', { assignmentId: assignmentId });
            };

            this.getReprintingReason = function (assignmentId) {
                return $http.post('/Assignment/GetReprintingReasonByAssignmentId', { assignmentId: assignmentId });
            };

            this.updateAndValidateAssignments = function (assignments) {
                return $http.post('/Assignment/ModifyAndValideAssignments',
                    $.param(assignments),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };


            this.updateAssignments = function (assignments) {
                return $http.post('/Assignment/ModifyAssignments',
                    $.param(assignments),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.addGuestAssignment = function (assignment) {
                return $http.post('/Assignment/AddGuest',
                    $.param(assignment),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.addVehicleAssignment = function (assignment) {
                return $http.post('/Assignment/AddVehicle',
                    $.param(assignment),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };


            this.getAllCustomFields = function () {
                return $http.post('/Assignment/GetAllCustomFields');
            };

            this.addAnonymousAssignment = function (assignment) {
                return $http.post('/Assignment/AddAnonymous',
                    $.param(assignment),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.validAssignment = function (form) {
                var data = {
                    model: form
                };
                return $http.post('/Assignment/Valid',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.cancelAssignment = function (ids, comment) {
                var data = {
                    comment: comment,
                    ids: ids
                };
                return $http.post('/Assignment/Cancel',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.deleteAssignment = function (ids) {
                var data = {
                    ids: ids
                };
                return $http.post('/Assignment/Delete',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.modifyAssignment = function (assignment, comment) {
                var data = {
                    comment: comment,
                    individualAssignmentModel: assignment,
                };
                return $http.post('/Assignment/Modify',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.modifyVehicleAssignment = function (assignment, comment) {
                var data = {
                    comment: comment,
                    vehiculeAssignmentModel: assignment,
                };
                return $http.post('/Assignment/ModifyVehicle',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.getLastAssignmentByIndividualId = function (eventId, individualId, assignmentTypeId) {
                var data = {
                    eventId: eventId,
                    individualId: individualId,
                    assignmentTypeId: assignmentTypeId
                }
                return $http.post('/Assignment/GetLastAssignmentByIndividualId', data);
            };

            this.getLastAssignmentByVehicleId = function (eventId, vehicleId, assignmentTypeId) {
                var data = {
                    eventId: eventId,
                    vehicleId: vehicleId,
                    assignmentTypeId: assignmentTypeId
                }
                return $http.post('/Assignment/GetLastAssignmentByVehicleId', data);
            };


            this.getZones = function (setting) {
                return $http.post('/Assignment/GetZones', setting);
            };

            this.getUserAllUnits = function (eventId) {
                return $http.post('/OrganizationUnit/GetUserAllUnits', { eventId: eventId });
            };

            this.getUserUnitsTree = function (eventId) {
                return $http.post('/OrganizationUnit/getUserUnitsTree', { eventId: eventId });
            };

            this.getUnitsTreeByProviderId = function (eventId, providerId) {
                return $http.post('/OrganizationUnit/GetUnitsTreeByProviderId',
                    { eventId: eventId, providerId: providerId });
            };
            this.getUnitsTreeByProvidersId = function (eventId, providersIds) {
                return $http.post('/OrganizationUnit/GetUnitTreeByProvidersId',
                    $.param({ eventId: eventId, providersIds: providersIds }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.GetUnitsTreeByProviderForPassManagement = function (providerId) {
                return $http.post('/OrganizationUnit/GetUnitsTreeByProviderForPassManagement', { providerId: providerId });
            };


            this.getUsersByProviderId = function (providerId, q) {
                return $http.post('/User/GetUsersByProviderId', { providerId: providerId, q: q });
            };

            this.getZonesByProfileId = function (profileId) {
                return $http.post('/ZoneNew/GetZonesByProfileId', { profileId: profileId });
            };

            this.getFormDefaultValues = function (setting) {
                return $http.post('/Assignment/GetFormDefaultValues', setting);
            };

            this.getRichStatusForAssignment = function (id) {
                return $http.post('/Assignment/GetRichStatusForAssignment', { id: id });
            };

            this.GetUnitConfiguration = function (unitId, formName) {
                return $http.post('/OrganizationUnit/GetUnitConfiguration', { unitId: unitId, formName: formName });
            };

            this.GetUnitsConfiguration = function (unitsIds, formName) {
                return $http.post('/OrganizationUnit/GetUnitsConfiguration',
                    $.param({ unitsIds: unitsIds, formName: formName }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.GetDoubles = function (assignmentId) {
                return $http.post('/Assignment/GetDoubles', { assignmentId: assignmentId });
            };

            this.SendAccessControl = function (eventId, assignmentIds) {
                return $http.post('/Assignment/SendAccreditations',
                    $.param({ eventId: eventId, assignmentIds: assignmentIds }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.uploadFiles = function (customField, files) {
                if (files && files.length) {
                    var upload = Upload.upload({ url: '/File/UploadFile', data: { file: files[0] } });
                    upload.then(function (file) {
                        if (customField.File === null) {
                            customField.File = {};
                        }
                        customField.File.Name = file.data.Name;
                        customField.File.IsNew = true;
                        customField.File.Type = file.data.Type;
                        customField.File.Url = file.data.Url;
                    });
                }
            }
            this.modifyVehiclesAssignment = function (assignment, comment) {
                var data = {
                    Assignments: assignment,
                };
                return $http.post('/Assignment/ModifyVehicles',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };
            this.modifyAndValidateVehiclesAssignment = function (assignment, comment) {
                var data = {
                    Assignments: assignment,
                };
                return $http.post('/Assignment/ModifyAndValidateVehicles',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.modifyGuestAssignment = function (assignment, comment) {
                var data = {
                    comment: comment,
                    guestAssignmentModel: assignment,
                };
                return $http.post('/Assignment/ModifyGuest',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };


            this.getIndividualsByProviderId = function (providerId, eventId, page, search) {
                return $http.post('/Assignment/GetUnAssignedIndividual',
                    { providerId: providerId, eventId: eventId, page: page, q: search });
            };

            this.GetAvailableIndividualForVehicle = function (eventId, providerId, page, search) {

                return $http.post('/Assignment/GetAvailableIndividualForVehicle',
                    $.param({ eventId: eventId, providerId: providerId, page: page, q: search }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
                );
            };

            this.GetAvailableVehicleForVehicle = function (eventId, providerId, page, search) {
                return $http.post('/Assignment/GetAvailableVehicleForVehicle',
                    $.param({ eventId: eventId, providerId: providerId, page: page, q: search }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
                );
            };

            this.dataBind = function (grid, search) {
                var options = {
                    PageIndex: grid.pageNumber,
                    PageSize: grid.pageSize,
                    SortColumn: grid.sort,
                    SortOrder: grid.sortOrder
                };

                var url = '/Assignment/DataBind'

                return $http.post(url,
                    $.param({ grid: options, Search: search }),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.getAssignment = function (assignmentId) {
                var data = {
                    assignmentId: assignmentId
                };
                return $http.post('/Assignment/GetAssignment', data);
            };

            this.reactivate = function (assignmentId, eventId) {
                var data = {
                    assignmentId: assignmentId,
                    eventId: eventId
                };
                return $http.post('/Assignment/Reactivate', data);
            };

            this.getAssignments = function (ids) {
                var data = {
                    ids: ids
                };
                return $http.post('/Assignment/GetAssignments',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.enterAssignment = function (assignmentId) {
                var data = {
                    assignmentId: assignmentId,
                    actionType: "entered"
                };
                return $http.post('/Assignment/EnterExitAssignment', data);
            };

            this.exitAssignment = function (assignmentId) {
                var data = {
                    assignmentId: assignmentId,
                    actionType: "exited"
                };
                return $http.post('/Assignment/EnterExitAssignment', data);
            };

            this.getAssignmentsWithAlreadyReadingEntry = function (assignmentsIds, actionType) {
                var data = {
                    assignmentsIds: assignmentsIds,
                    actionType: actionType
                };
                return $http.post('/Assignment/GetAssignmentsWithAlreadyReadingEntry', data);
            };

            this.enterAssignments = function (assignmentsIds, actionDate) {
                var data = {
                    assignmentsIds: assignmentsIds,
                    actionType: "entered",
                    actionDate: actionDate
                };
                return $http.post('/Assignment/EnterExitAssignments', data);
            };

            this.exitAssignments = function (assignmentsIds, actionDate) {
                var data = {
                    assignmentsIds: assignmentsIds,
                    actionType: "exited",
                    actionDate: actionDate
                };
                return $http.post('/Assignment/EnterExitAssignments', data);
            };



            this.getParameters = function (codes) {
                var data = {
                    codes: codes
                };
                return $http.post('/Parameter/GetParametersByCode',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.getMailStatus = function () {
                return $http.post('/Mail/GetMailStatus');
            };

            this.getAccessStatus = function () {
                return $http.post('/Assignment/GetAccessStatusEnum');
            };

            this.SendEmail = function (assignmentIds) {
                var data = {
                    assignmentIds: assignmentIds
                };
                return $http.post('/Mail/SendEmailToAssignments',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.getReasons = function () {
                return $http.get('/Reason/GetReasons');
            };

            this.SendMessage = function (form) {
                return $http.post('/Mail/SendMessageToAssignments',
                    $.param(form),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };



            this.getMailjetParameter = function () {
                return $http.post('/Parameter/GetMailjetParameter');
            };

            this.getWordingStyleParameter = function () {
                return $http.post('/Parameter/GetWordingParameter');
            };

            this.getNumberAccreditationMaxParameter = function () {
                return $http.get('/Parameter/GetNumberAccreditationMax');
            };

            this.IsBlacklisted = function (personIds) {
                var data = {
                    personIds: personIds
                };
                return $http.post('/Blacklist/IsBlackListed',
                    $.param(data),
                    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.isFunctionPresent = function () {
                return $http.post("/Individual/IsFunctionPresent");
            };

            this.isReliabilityFieldPresent = function () {
                return $http.post("/CustomField/IsReliabilityFieldPresent");
            };

            this.getSearchCustomFields = function (organizationId) {
                return $http.post("/Assignment/GetSearchCustomFields", { organizationId: organizationId });
            };

            this.GetPdfs = function (param) {
                return $http.post("/Assignment/GetPdfs?" + param);
            };

            this.SendTitleByMail = function (param) {
                return $http.post("/Assignment/SendTitleByMail?" + param);
            };

            this.Export = function (param) {
                return $http.post("/Assignment/Export?" + param);
            };

            this.GetIndividualAssignmentTemplate = function (unitId) {
                return window.open("/Assignment/GetImportAssignmentTemplate?unitId=" + unitId);
            };

            this.getRgpd = function () {
                return $http.get("/Rgpd/GetRgpdSentence");
            };

            this.manageAssignmentAccess = function (assignment) {
                if (assignment.AccessDetailsModel.IsAbsoluteAccess) {
                    //get date
                    this.setDate(assignment);
                }
            };
            this.manageAssignmentsAccess = function (assignment) {

                if (assignment.AccessDetailsModel.IsAbsoluteAccess) {
                    if (assignment.AccessStartDate && assignment.AccessEndDate) {
                        //get date
                        if (!assignment.AccessStartTime) {
                            assignment.AccessStartTime = moment().set({ hour: 8, minute: 0 }).format("HH:mm");
                        }

                        if (!assignment.AccessEndTime) {
                            assignment.AccessEndTime = moment().set({ hour: 20, minute: 0 }).format("HH:mm");
                        }

                        this.setDate(assignment);
                    }
                }
            };

            this.setDate = function (assignment) {

                var accessStartTime = null;
                if (typeof assignment.AccessStartTime == "object" && assignment.AccessStartTime instanceof Date) {
                    accessStartTime = moment(assignment.AccessStartTime).format("HH:mm");
                }
                else {
                    if (typeof assignment.AccessStartTime == "string" && assignment.AccessStartTime.length > 11) {
                        accessStartTime = assignment.AccessStartTime.substring(11);
                    }
                    else {
                        accessStartTime = assignment.AccessStartTime;
                    }

                }

                var accessEndTime = null;
                if (typeof assignment.AccessEndTime == "object" && assignment.AccessEndTime instanceof Date) {
                    accessEndTime = moment(assignment.AccessEndTime).format("HH:mm");
                }
                else {
                    if (typeof assignment.AccessEndTime == "string" && assignment.AccessEndTime.length > 11) {
                        accessEndTime = assignment.AccessEndTime.substring(11);
                    }
                    else {
                        accessEndTime = assignment.AccessEndTime;
                    }

                }

                var accessStartDate = assignment.AccessStartDate !== null && accessStartTime !== null ? moment(moment(assignment.AccessStartDate, 'L').format('YYYY-MM-DD') + " " + accessStartTime) : null;
                var accessEndDate = assignment.AccessEndDate !== null && accessEndTime !== null ? moment(moment(assignment.AccessEndDate, 'L').format('YYYY-MM-DD') + " " + accessEndTime) : null;

                assignment.AccessDetailsModel.AccessStartDate = accessStartDate !== null && !isNaN(accessStartDate) ? accessStartDate.format("DD/MM/YYYY HH:mm") : null;
                assignment.AccessDetailsModel.AccessEndDate = accessEndDate !== null && !isNaN(accessEndDate) ? accessEndDate.format("DD/MM/YYYY HH:mm") : null;
            };

            this.formatAssignmentAccessStartEndDates = function (assignment, strStartDate, strEndDate) {

                var StartDate = null;

                if (strStartDate) {
                    StartDate = moment(strStartDate, 'DD/MM/YYYY HH:mm');
                }
                else {
                    var accessStartTime = null;
                    if (typeof assignment.AccessStartTime == "object" && assignment.AccessStartTime instanceof Date) {
                        accessStartTime = moment(assignment.AccessStartTime).format("HH:mm");
                    }
                    else {
                        if (typeof assignment.AccessStartTime == "string" && assignment.AccessStartTime.length > 11) {
                            accessStartTime = assignment.AccessStartTime.substring(11);
                        }
                        else {
                            accessStartTime = assignment.AccessStartTime;
                        }
                    }
                    StartDate = moment(moment(assignment.AccessStartDate, 'L').format('YYYY-MM-DD') + " " + accessStartTime);
                }

                var EndDate = null;

                if (strEndDate) {
                    EndDate = moment(strEndDate, 'DD/MM/YYYY HH:mm');
                }
                else {
                    var accessEndTime = null;
                    if (typeof assignment.AccessEndTime == "object" && assignment.AccessEndTime instanceof Date) {
                        accessEndTime = moment(assignment.AccessEndTime).format("HH:mm");
                    }
                    else {
                        if (typeof assignment.AccessEndTime == "string" && assignment.AccessEndTime.length > 11) {
                            accessEndTime = assignment.AccessEndTime.substring(11);
                        }
                        else {
                            accessEndTime = assignment.AccessEndTime;
                        }

                    }
                    EndDate = moment(moment(assignment.AccessEndDate, 'L').format('YYYY-MM-DD') + " " + accessEndTime);
                }

                assignment.AccessStartDate = isNaN(StartDate) ? null : moment(StartDate).format('L');
                assignment.AccessStartTime = isNaN(StartDate) ? null : StartDate.format("YYYY-MM-DD HH:mm");
                assignment.AccessEndDate = isNaN(EndDate) ? null : moment(EndDate).format('L');
                assignment.AccessEndTime = isNaN(EndDate) ? null : EndDate.format("YYYY-MM-DD HH:mm");
            };

            this.setDefaultAssignmentAccessStartEndTimes = function (assignment) {
                assignment.AccessStartTime = moment().set({ hour: 8, minute: 0 }).format("HH:mm");
                assignment.AccessEndTime = moment().set({ hour: 20, minute: 0 }).format("HH:mm");
            };

            this.getCategorieByProviderId = function (providerId) {
                return $http.get("/Category/GetCategoriesByProviderId?providerId=" + providerId);
            };

            this.getCategoriesByEventAndProviderIds = function (eventId, providerIds) {
                return $http.post("/Category/GetCategoriesByEventAndProviderIds", { eventId: eventId, providerIds: providerIds });
            };
            this.getCategoriesByEvent = function (eventId) {
                return $http.post("/Category/GetCategoriesByEvent", { eventId: eventId });
            };
            this.checkQuotas = function (assignments) {
                return $http.post("/Assignment/CheckQuotas", $.param(assignments), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
            };

            this.getQuotasStats = function (eventId) {
                return $http.post("/Assignment/GetStatsQuotasByEvent", { eventId: eventId });
            };

            this.getDefaultAssignmentType = function (eventId) {
                return $http.post("/Assignment/GetDefaultAssignmentType", { eventId: eventId });
            };

        }]).run(['assignmentService', function (assignmentService) {
            angular.copy(assignmentService.pageStateModel, assignmentService.pageState);
        }]);
angular
    .module('accreditationApp')
    .controller('assignmentGuestController', assignmentGuestController);

assignmentGuestController
    .$inject = ['$scope', 'assignmentGuestService', 'tokenId', 'zoneIds', 'assignmentId', 'activityAreaId', 'activityAreaFunctionId', 'providerId'];

function assignmentGuestController($scope, assignmentGuestService, tokenId, zoneIds, assignmentId, activityAreaId, activityAreaFunctionId, providerId) {
    //** PROPS **//
    $scope.IsValid = false;
    $scope.formSubmitted = false;
    $scope.individual = {
        TokenId: tokenId,
        ZoneIds: zoneIds,
        ProviderId: providerId,
        activityAreaId: null,
        activityAreaFunctionId: null,
        assignmentId: 0,
        firstname: null,
        lastname: null,
        email: null,
        individualProviderName: null,
        LinkedInUrl: null,
        AcceptAdsFromPartners: false,
        AcceptDataSharedWithPartners: false,
        AcceptAdsFromMys: true,
        emailConfirmation: null,
        country: null,
        isYachtExhibited: null,
        CaptainsFirstName: null,
        CaptainsLastName: null,
        YachtName: null,
        LengthOverAll: null,
        AuthorizePersonalDataTreatment: null,
        SumDaysCount: null,
        RgpdValidation: false
    };

    $scope.Zones = [];
    $scope.animating = false;
    $scope.activityAreas = [];
    $scope.activityAreaFunctions = [];
    $scope.isLoading = false;
    $scope.activityArea = {
        selected: ""
    };
    $scope.activityAreaFunction = {
        selected: ""
    };
    $scope.step2 = false;
    $scope.showEmailConfirmationError = false;
    $scope.countries = [];
    $scope.showSelectDaysError = false;
    $scope.selectDaysErrorMessage = "";
    $scope.numberOfItemsPerLine = 4;
    $scope.GuestFormAvailableNumberOfDays = "";
    //** END PROPS **/


    //**  Events **//
    $scope.Next = function ($event) {
        var current_fs, next_fs;
        var left, opacity, scale;

        if ($scope.animating) return false;
        $scope.animating = true;

        current_fs = $("#" + $event.currentTarget.parentElement.id);
        next_fs = $("#" + $event.currentTarget.parentElement.id).next();

        if ($scope.individual.assignmentId != null && $scope.individual.assignmentId != 0 && current_fs[0].id == "fieldset_1") {
            next_fs = $("#" + next_fs[0].id).next();
        }

        $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

        next_fs.show();
        current_fs.animate({ opacity: 0 }, {
            step: function (now, mx) {
                scale = 1 - (1 - now) * 0.2;
                left = (now * 50) + "%";
                opacity = 1 - now;
                current_fs.css({
                    'transform': 'scale(' + scale + ')',
                    'position': 'absolute'
                });
                next_fs.css({ 'left': left, 'opacity': opacity });
            },
            duration: 800,
            complete: function () {
                current_fs.hide();
                $scope.animating = false;
            },
            easing: 'easeInOutBack'
        });
    };
    $scope.Previous = function ($event) {
        var current_fs, previous_fs;
        var left, opacity, scale;
        if ($scope.animating) return false;
        $scope.animating = true;

        current_fs = $("#" + $event.currentTarget.parentElement.id);
        previous_fs = $("#" + $event.currentTarget.parentElement.id).prev();

        if ($scope.individual.assignmentId != null && $scope.individual.assignmentId != 0 && current_fs[0].id == "fieldset_3") {
            previous_fs = $("#" + previous_fs[0].id).prev();
        }

        $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

        previous_fs.show();
        current_fs.animate({ opacity: 0 }, {
            step: function (now, mx) {
                scale = 0.8 + (1 - now) * 0.2;
                left = ((1 - now) * 50) + "%";
                opacity = 1 - now;
                current_fs.css({ 'left': left });
                previous_fs.css({ 'transform': 'scale(' + scale + ')', 'opacity': opacity });
            },
            duration: 800,
            complete: function () {
                current_fs.hide();
                $scope.animating = false;
            },
            easing: 'easeInOutBack'
        });
    }
    //** End Events **//


    $scope.onActivityAreaChange = function (term) {
            $scope.isLoading = true;
            $scope.activityAreas = [];
            assignmentGuestService
                .GetActivityAreas(term)
                .success(function (data) {
                    $scope.activityAreas = $scope.activityAreas.concat(data.data);
                    $scope.isLoading = false;
                });
    };
    $scope.onActivityAreaFunctionChange = function (term) {
            $scope.isLoading = true;
            $scope.activityAreaFunctions = [];
            assignmentGuestService
                .GetActivityAreaFunctions(term)
                .success(function (data) {
                    $scope.activityAreaFunctions = $scope.activityAreaFunctions.concat(data.data);
                    $scope.isLoading = false;
                });
    };
    $scope.setFunction = function (item) {
        $scope.individual.activityAreaFunctionId = item == null ? null : item.id;
    };
    $scope.setArea = function (item) {
        $scope.individual.activityAreaId = item == null ? null : item.id;
    };
    $scope.setCountry = function (item) {
        $scope.individual.country = item == null ? null : item.CountryId;
    };

    //** Method **//


    $scope.preventDblClick = function () {
        $scope.formSubmitted = true;
        $timeout(function () { /* intentionally left blank */ }, 2000);
        $scope.formSubmitted = false;
    }
    $scope.loadEvents = function () {
        assignmentGuestService.GetZones($scope.individual.ProviderId)
            .success(function (data) {
                $scope.Zones = data.data;
                $scope.numberOfItemsPerLine = $scope.Zones.length < 4 ? $scope.Zones.length : 4;
            });
    };

    $scope.getCountries = function () {
        assignmentGuestService.GetCountries().success(function (result) {
            $scope.countries = result.data;
        })
    }


    if (assignmentId != 0) {
        $scope.individual = {
            TokenId: tokenId,
            activityAreaId: activityAreaId,
            activityAreaFunctionId: activityAreaFunctionId,
            assignmentId: assignmentId,
            ProviderId: providerId
        };
        $scope.loadEvents();
    } else {
        $scope.getCountries();
    }

    $scope.checkUserInfo = function ($event) {
        if (!$("#msform").valid())
            return false;

        if ($scope.individual.email !== $scope.individual.emailConfirmation) {
            $scope.showEmailConfirmationError = true;
            return false;
        }

        assignmentGuestService
            .CheckAssignmentForIndividual($scope.individual)
            .success(function (result) {
                if ($scope.individual.assignmentId != 0 || result.data) {
                    $scope.validAdditionalForm($event, false);
                }
                else {
                    $scope.Next($event);
                    $("[name='provider]").blur();
                }
            });
    };

    $scope.validAdditionalForm = function ($event, doChecks = true) {
        if ($scope.individual.country == null) {
            $scope.form.country.$error.required = true;
            $scope.form.country.$touched = true;
            $scope.form.country.$invalid = true;
        }

        if ($scope.individual.activityAreaFunctionId == null) {
            $scope.form.activityAreaFunction.$error.required = true;
            $scope.form.activityAreaFunction.$touched = true;
            $scope.form.activityAreaFunction.$invalid = true;
        }

        if ($scope.individual.activityAreaId == null) {
            $scope.form.activityArea.$error.required = true;
            $scope.form.activityArea.$touched = true;
            $scope.form.activityArea.$invalid = true;
        }

        if (doChecks && ($scope.individual.activityAreaId == null
            || $scope.individual.activityAreaFunctionId == null
            || $scope.individual.country == null
            || $scope.individual.individualProviderName == null
            || ($scope.activityAreaFunction.selected != null && $scope.activityAreaFunction.selected.isYachtAreaFunction && $scope.individual.isYachtExhibited == null)
            || ($scope.individual.isYachtExhibited == "1" && $scope.form.LengthOverAll.$error.pattern)))
            return false;

        $scope.step2 = true;
        $scope.formSubmitted = true;
        assignmentGuestService
            .CheckIndividualInfos($scope.individual)
            .success(function (data) {
                if (data.Success) {
                    $scope.individual.assignmentId = data.data.AssignmentId != null ? data.data.AssignmentId : 0;
                    $scope.individual.ZoneIds = data.data.ZoneIds;
                    $scope.individual.AcceptAdsFromPartners = data.data.AcceptAdsFromPartners;
                    $scope.individual.AcceptDataSharedWithPartners = data.data.AcceptDataSharedWithPartners;
                    $scope.individual.AcceptAdsFromMys = data.data.AcceptAdsFromMys;
                    $scope.individual.RgpdValidation = data.data.RgpdValidation;
                    $scope.individual.SumDaysCount = data.data.SumDaysCount;
                    var s = $scope.individual.SumDaysCount == 1 ? "" : "s";
                    $scope.GuestFormAvailableNumberOfDays = resources.GuestFormAvailableNumberOfDays
                        .replace('{0}', $scope.individual.SumDaysCount)
                        .replace('{1}', s);
                    $scope.loadEvents();
                    $scope.Next($event);
                    $scope.IsValid = data.Success;
                } else {
                    site.errorMessage(resourcesMessages.InvalidInfoCorrectyourEntry, data.Exception);
                }
                $scope.formSubmitted = false;
            }).error(function (data) {
                site.errorMessage($scope.resourcesMessages.ExceptionDuringVerification, data.Exception);
                $scope.formSubmitted = false;
            });
    };

    $scope.selectEvents = function () {
        if (!$("#msform").valid())
            return false;

        $scope.showSelectDaysError = false;

        var nbSelectedDays = $("input[id^=day-]:checked").length;
        if (nbSelectedDays == 0) {
            $scope.showSelectDaysError = true;
            $scope.selectDaysErrorMessage = resourcesMessages.GuestFormNoSelectedDays;
            return false;
        }

        if (nbSelectedDays > $scope.individual.SumDaysCount) {
            $scope.showSelectDaysError = true;
            $scope.selectDaysErrorMessage = resourcesMessages.GuestFormTooMuchSelectedDays.replace('{0}', $scope.individual.SumDaysCount);
            return false;
        }

        $scope.formSubmitted = true;
        $scope.individual.ZoneIds = [];
        $("input[id^=day-]:checked").each(function () {
            $scope.individual.ZoneIds.push(parseInt($(this).attr("id").replace('day-', '')));
        })
        $scope.formSubmitted = true;
        assignmentGuestService
            .Validate($scope.individual)
            .success(function (data) {
                if (data.Success) {
                    $("#msform").hide();
                    $("#successMessage").show();
                } else {
                    site.errorMessage($scope.resourcesMessages.ValidationFail, data.Exception);
                }
                $scope.formSubmitted = false;
            }).error(function (data) {
                $scope.formSubmitted = false;
                site.errorMessage($scope.resourcesMessages.ValidationFail, data.Exception);
            });
    };
    //** End Method **//
};

angular.module('accreditationApp')
    .service('assignmentGuestService', ['$http', function ($http) {

        this.GetZones = function (providerId) {
            var data = {
                providerId: parseFloat(providerId)
            };
            return $http.post('/AssignmentGuestForm/GetZones', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.CheckIndividualInfos = function (individual) {
            return $http.post('/AssignmentGuestForm/GetModelWithIndividualVerification', $.param(individual),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.GetActivityAreas = function (term) {
            var data = {
                searchTerm: term
            };
            return $http.post('/AssignmentGuestForm/FindActivityAreas',
                $.param(data),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.GetActivityAreaFunctions = function (term) {
            var data = {
                searchTerm: term
            };
            return $http.post('/AssignmentGuestForm/FindActivityAreaFunctions',
                $.param(data),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.Validate = function (assignmentGuestFormModel) {
            return $http.post('/AssignmentGuestForm/Validate', $.param(assignmentGuestFormModel),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.GetCountries = function () {
            return $http.post('/AssignmentGuestForm/GetCountries', null, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.CheckAssignmentForIndividual = function (assignmentGuestFormModel) {
            return $http.post('/AssignmentGuestForm/CheckAssignmentForIndividual', $.param(assignmentGuestFormModel),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };
    }
    ]);

angular.module('accreditationApp')
    .controller('CustomReportCtrl', ['$scope',  'customReportService',
    function ($scope, customReportService) {

            $scope.customreport = {};

            var paginationOptions = {
                PageSize: 25,
                PageIndex: 1,
                SortColumn: "Name",
                PageNumber: 0,
                SortOrder: "asc"
            };

            $scope.gridOptions = {
                paginationPageSizes: [100],
                paginationPageSize: 100,
                useExternalPagination: true,
                enableHorizontalScrollbar: 0,
                enableVerticalScrollbar: 0,
                multiSelect: false,
                noUnselect: true,
                modifierKeysToMultiSelect: false,
                enableRowHeaderSelection: false,
                rowHeight: 40,
                enableRowSelection: true,
                enableSelectAll: true,
                selectionRowHeaderWidth: 35,
                columnDefs: [
                    { name: 'reportId', displayName: "reportId", visible: false },
                    { name: 'Name', displayName: "Nom" },
                    { name: 'Description', displayName: "Description", width: 120, },
                    {
                        name: 'Action', displayName: "", enableSorting: false, width: 60,
                        cellTemplate: "<button class='btn btn-default btn-sm' ng-click='grid.appScope.exportCustomReport(row.entity.CustomReportId);'><i class='fa fa-download bigger-110'></i></button>"
                    }

                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                        if (sortColumns.length !== 0) {
                            paginationOptions.SortOrder = sortColumns[0].sort.direction;
                            paginationOptions.SortColumn = sortColumns[0].field;
                        }
                        $scope.getReports();
                    });

                    gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                        customReportService.Context.SelectedReport = row.entity;
                    });
                }
            };


            $scope.gridOptions.multiSelect = false;

            $scope.getReports = function () {
                var settings = {
                    PageSize: $scope.gridOptions.paginationPageSize,
                    PageIndex: paginationOptions.PageIndex,
                    SortColumn: paginationOptions.SortColumn,
                    SortOrder: paginationOptions.SortOrder
                };

                customReportService.GetCustomReports(settings)
                    .success(function (params) {
                        $scope.gridOptions.totalItems = params.Total;
                        $scope.gridOptions.data = params.Data;
                    });
            };

            $scope.getReports();

            $scope.exportCustomReport = function (customReportId) {
                var myWindow = window.open(Site.params.url +
                    "/CustomReport/ExportCustomReport?customReportId=" +
                    customReportId +
                    "&eventId=" +
                    $("#ContextEventId").val() +
                    "&source=" +
                    $("#ContextSource").val(),
                    "_blank");
            };
        }]);

angular.module('accreditationApp')
    .service('customReportService', ['$http', function ($http) {

        this.Context = {
            SelectedReport: null
        };
        this.GetCustomReports = function (settings) {
            return $http.post('CustomReport/GetCustomReport/', settings);
        };
        this.ExportCustomReport = function (param) {
            return $http.post('CustomReport/ExportCustomReport/', param);
        };
    }]);
angular.module('accreditationApp')
    .controller('eventChoiceController', ['$scope', '$route', '$timeout', '$filter', '$location', '$q', '$uibModal', '$uibModalInstance', 'contextService', 'eventService', 'events', '$controller', function ($scope, $route, $timeout, $filter, $location, $q, $uibModal, $uibModalInstance, contextService, eventService, events, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.events = events;
        $scope.useMultiSite = site.params.useMultiSite;
        $scope.quotasActivated = site.params.quotasActivated;

        eventService.getWordingStyleParameter().success(function (data) {
            $scope.wordingStyle = data;
        });

        $scope.changeContext = function (event, hasRight) {
            if (hasRight) {
                if (event.EventId != null) {
                    contextService.setContext(event.EventId).success(function (ret) {
                        if (ret.Success) {
                            $(".modal-content").Spinner("show");
                            if (window.location.href.indexOf("/open") != -1) {
                                window.location.href = location.origin;
                            } else {
                                location.reload();
                            }
                        } else {
                            site.errorMessage(ret.Exception, null);
                            return false;
                        }
                    });
                }
            }
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.rights = contextService.getRights();

    }]);

angular.module('accreditationApp')
    .controller('eventHeaderController', ['$scope', '$filter', '$q', '$location', '$uibModal', 'eventService', 'unitService', 'contextService', '$controller', 'assignmentService', function ($scope, $filter, $q, $location, $uibModal, eventService, unitService, contextService, $controller, assignmentService) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.currentPage = contextService.currentPage;
        $scope.isContextualCollapsed = false;
        $scope.form = {
            eventId: null
        };

        $scope.statistics = [];
        $scope.currentEvent = contextService.event;
        $scope.events = [];
        $scope.getEvents = function (search) {
            $scope.events.splice(1, $scope.events.length);
            return eventService.getEvents({ Name: search }).success(function (events) {
                angular.forEach(events, function (value, key) {
                    $scope.events.push(value);
                });

                var selectedEv = $filter('filter')($scope.events, { Selected: true })[0];
                if (selectedEv == undefined) {
                    angular.forEach(events, function (value, key) {
                        angular.forEach(value.Steps, function (step, key) {
                            if (step.Selected) {
                                selectedEv = step;
                            }
                        });
                    });
                }
            });
        };

        $scope.getQuotasStats = function () {
            console.log("ça bloque ici");
            return assignmentService.getQuotasStats($scope.currentEvent.EventId);
        };

        $scope.collapse = function () {
            $scope.isContextualCollapsed = !$scope.isContextualCollapsed;
            if ($scope.isContextualCollapsed) {
                contextService.getAssignmentStatistics($scope.currentEvent.EventId).success(function (statistics) {
                    //location.reload();
                    $scope.statistics = statistics;
                });
            }
        };

        $scope.getEventConfiguration = function (eventId) {
            eventService.getEventConfiguration(eventId).success(function (configuration) {
                contextService.steps.splice(0, contextService.steps.length);
                contextService.profiles.splice(0, contextService.profiles.length);
                contextService.units.splice(0, contextService.units.length);
                contextService.zones.splice(0, contextService.zones.length);
                contextService.surZones.splice(0, contextService.surZones.length);
                contextService.nationalities.splice(0, contextService.nationalities.length);

                contextService.searchAssignmentTypes.splice(0, contextService.searchAssignmentTypes.length);
                contextService.createAssignmentTypes.splice(0, contextService.createAssignmentTypes.length);

                contextService.searchPassTypes.splice(0, contextService.searchPassTypes.length);
                contextService.createPassTypes.splice(0, contextService.createPassTypes.length);
                contextService.deliveryPlaces.splice(0, contextService.deliveryPlaces.length);
                contextService.mockups.splice(0, contextService.mockups.length);
                contextService.individualCustomFields.splice(0, contextService.individualCustomFields.length);
                contextService.vehicleCustomFields.splice(0, contextService.vehicleCustomFields.length);
                contextService.previewmockup = configuration.previewmockup;
                contextService.event.IsMailCampaignOpen = configuration.isMailCampaignOpen;
                contextService.event.CanSendAnonymousTitleByMail = configuration.CanSendAnonymousTitleByMail;
                contextService.event.CanSendIndividualTitleByMail = configuration.CanSendIndividualTitleByMail;
                contextService.event.CanSendVehicleTitleByMail = configuration.CanSendVehicleTitleByMail;
                contextService.event.CanSendGuestTitleByMail = configuration.CanSendGuestTitleByMail;
                contextService.passEvent.CanSendIndividualTitleByMail = configuration.CanSendIndividualPassByMail;
                contextService.passEvent.CanSendVehicleTitleByMail = configuration.CanSendVehiclePassByMail;
                contextService.passEvent.CanSendAnonymousTitleByMail = configuration.CanSendAnonymousPassByMail;
                contextService.passEvent.CanSendGuestTitleByMail = configuration.CanSendGuestPassByMail;
                contextService.event.Steps = [];
                angular.forEach(configuration.steps, function (value) {
                    contextService.event.Steps.push(value);
                });

                angular.forEach(configuration.searchAssignmentTypes, function (value, key) {
                    contextService.searchAssignmentTypes.push(value);
                });
                angular.forEach(configuration.createAssignmentTypes, function (value, key) {
                    contextService.createAssignmentTypes.push(value);
                });

                angular.forEach(configuration.searchPassTypes, function (value, key) {
                    contextService.searchPassTypes.push(value);
                });
                angular.forEach(configuration.createPassTypes, function (value, key) {
                    contextService.createPassTypes.push(value);
                });

                angular.forEach(configuration.steps, function (value, key) {
                    contextService.steps.push(value);
                });
                angular.forEach(configuration.profiles, function (value, key) {
                    contextService.profiles.push(value);
                });
                angular.forEach(configuration.units, function (value, key) {
                    contextService.units.push(value);
                });
                angular.forEach(configuration.nationalities, function (value, key) {
                    contextService.nationalities.push(value);
                });
                angular.forEach(configuration.vehicleTypes, function (value, key) {
                    contextService.vehicleTypes.push(value);
                });
                angular.forEach(configuration.vehicleBrands, function (value, key) {
                    contextService.vehicleBrands.push(value);
                });
                angular.forEach(configuration.deliveryPlaces, function (value, key) {
                    contextService.deliveryPlaces.push(value);
                });
                angular.forEach(configuration.individualCustomFields, function (value, key) {
                    contextService.individualCustomFields.push(value);
                });
                angular.forEach(configuration.vehicleCustomFields, function (value, key) {
                    contextService.vehicleCustomFields.push(value);
                });

                angular.forEach(configuration.accreditationInputs, function (value, key) {
                    contextService.accreditationInputs.push(value);
                });

                angular.forEach(configuration.multipleAccreditationInputs, function (value, key) {
                    contextService.multipleAccreditationInputs.push(value);
                });

                angular.forEach(configuration.mockups, function (value, key) {
                    contextService.mockups.push(value);
                });
               
                angular.forEach($filter('filter')(configuration.zones), function (value, key) {
                    contextService.allZones.push(value);
                });

                angular.forEach($filter('filter')(configuration.zones, { SurZoning: false, AssignmentTypeName: "Individual" }), function (value, key) {
                    contextService.zones.push(value);
                });

                angular.forEach($filter('filter')(configuration.zones, { SurZoning: true, AssignmentTypeName: "Individual" }), function (value, key) {
                    contextService.surZones.push(value);
                });

            });
        }


        
        $scope.modalChoiceEvent = function () {
            var modalInstance = $uibModal.open({
                templateUrl: '/Scripts/Angular/Event/Views/EventChoice.html?ver=' + $scope.softwareVersion,
                controller: 'eventChoiceController',
                resolve: {
                    events: function () {
                        return $scope.events;
                    }
                }
            });
        };

        $scope.modalQuotasStats = function () {
            var modalGetQuotasStats = $uibModal.open({
                templateUrl: '/Scripts/Angular/Event/Views/QuotasStats.html?v=5669dd966dsqdqs9',
                controller: 'QuotasStatsController',
                resolve: {
                    quotasStats: $scope.getQuotasStats(),
                    event: $scope.currentEvent
                }
            });
        };

        $scope.$watch(function () { return contextService.openEventModal }, function (openEventModal) {
            if (openEventModal == true) {
                $scope.modalChoiceEvent();
            }
        }, true);

        $scope.changeEvent = function (event) {
            if (event.EventId != null) {
                $("body").Spinner("show");
                contextService.setContext(event.EventId).success(function () {
                    location.reload();
                });
            }
        };

        $scope.getEvents();
        $scope.getEventConfiguration($scope.currentEvent.EventId);
        
        eventService.getWordingStyleParameter().success(function (data) {
            $scope.wordingStyle = data;
        });

        
        $scope.getEventDisabled = function () {
            var ev = $scope.currentEvent;
            if (site.user.HasFirstConnection && site.user) {
                if (ev.EventId != null && !ev.IsActive) {
                    $scope.modalChoiceEvent();
                }
            }
        };
        $scope.getEventDisabled();
         
    }]);
angular.module('accreditationApp')
    .controller('QuotasStatsController', ['$scope', '$uibModalInstance', '$controller', 'quotasStats', 'event', function ($scope, $uibModalInstance, $controller, quotasStats, event) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));

        $scope.quotasStats = quotasStats.data.data;
        $scope.eventName = event.EventName;
        $scope.continue = function () {
            $uibModalInstance.close(true);
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }]);


angular.module('accreditationApp')
.service('eventService', ['$resource', '$http', function ($resource, $http) {


    this.getEvents = function (setting) {
        return $http.post('/Event/GetEvents', setting);
    }
    
    this.getEventConfiguration = function(eventId) {
        return $http.post('/Event/GetEventConfiguration', { eventId: eventId });
    }

    this.getWordingStyleParameter = function () {
        return $http.post('/Parameter/GetWordingParameter');
    }

}]);


angular.module('accreditationApp')
    .controller('importIndividualFormController', ['$scope', '$route', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'assignmentService', 'providerService', 'individualService', 'vehicleService', 'Upload', '$timeout', '$controller', function ($scope, $route, $timeout, $filter, $location, $q, $uibModal, contextService, assignmentService, providerService, individualService, vehicleService, Upload, $timeout, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "individualList";

        individualService.resetPageState();
        vehicleService.resetPageState();


        // upload later on form submit or something similar
        $scope.submit = function () {
            if ($scope.form.file.$valid && $scope.file && $scope.form.fileZip.$valid) {
                $scope.upload($scope.file, $scope.fileZip);
            }
        };
        $scope.label = null;
        $scope.labelZip = null;
        $scope.uploadSuccess = null;
        $scope.applyModifToIndividual = false;
        $scope.ignoreBlacklisted = false;

        // upload on file select or drop
        $scope.upload = function (file, fileZip) {
            $(".form-import").Spinner("show");
            $scope.lineNumber = 0;
            $scope.uploadSuccess = false;

            Upload.upload({
                url: '/Individual/Import',
                data: { file: file, FileZip: fileZip, eventId: contextService.event.EventId, BypassVerification: $scope.applyModifToIndividual || $scope.ignoreBlacklisted }
            }).then(function (resp) {
                $(".form-import").Spinner("hide");
                $(".modif-results").Spinner("hide");

                if (resp.data.Success) {
                    $scope.uploadSuccess = true;
                    $scope.lineNumber = resp.data.LineNumber;

                } else {
                    $scope.uploadSuccess = false;

                    if (resp.data.ExceptionOccured) {
                        site.errorMessage(resourcesMessages.ExceptionDuringImport, null);
                    }
                    else {

                        if (resp.data.Exceptions.length > 0) {
                            $scope.gridOptions.totalItems = resp.data.Exceptions.length;
                            $scope.gridOptions.data = resp.data.Exceptions;
                        }
                        $scope.resize(0);
                    }
                }
                console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });
        };

        $scope.validateImportWithModifications = function () {
            $scope.applyModifToIndividual = true;
            $(".modif-results").Spinner("show");
            $scope.submit();
            $scope.applyModifToIndividual = false;
        };

        $scope.acceptBlacklisted = function () {
            $scope.ignoreBlacklisted = true;
            if ($scope.modifOptions.data != undefined && $scope.modifOptions.data.length > 0) {
                $scope.showBlacklist = false;
                $scope.showModif = true;
                $scope.ignoreBlacklisted = false;
            } else {
                $(".modif-results").Spinner("show");
                $scope.submit();
                $scope.ignoreBlacklisted = false;
            }
        };

        $scope.gridOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                // { field: 'Row', width: 60, enableColumnMenu: false, displayName: "" },
                { field: 'LineNb', displayName: "Ligne", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorField', displayName: "Champ", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorType', displayName: "Type d'érreur", enableColumnMenu: false },
                { field: 'ErrorMessage', displayName: "Message", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }
        };

        $scope.gridImages = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,
            rowHeight: 50,
            columnDefs: [
                { field: 'Row', width: 60, enableColumnMenu: false, displayName: "" },
                { field: 'Name', displayName: "Nom de l'image", enableSorting: true, enableColumnMenu: false },
                { field: 'NewName', displayName: "Nouveau nom de l'image", enableColumnMenu: false },
                { field: 'State', displayName: "Etat de l'image", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }
        };

        $scope.modifOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne mise à jour", enableSorting: false, enableColumnMenu: false },

                { field: 'FieldName', enableSorting: false, displayName: "Champ modifié", enableColumnMenu: false },
                { field: 'OldValue', enableSorting: false, displayName: "Ancienne valeur", enableColumnMenu: false },

                { field: 'NewValue', enableSorting: false, displayName: "Nouvelle valeur", enableColumnMenu: false }

            ],
            onRegisterApi: function (gridApi) {
                $scope.modifApi = gridApi;
            }
        };

        $scope.blacklistOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne concernée", enableSorting: false, enableColumnMenu: false },

                { field: 'StartDate', enableSorting: false, displayName: "Date de début", enableColumnMenu: false },
                { field: 'EndDate', enableSorting: false, displayName: "Date de fin", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.blacklistApi = gridApi;
            }
        };

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('modifApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('blacklistApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.resize = function (plus) {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height + plus);
                $scope.gridApi.grid.handleWindowResize();
            }
            if ($scope.modifApi) {
                if ($scope.modifOptions.totalItems > 0) {
                    $scope.modifApi.core.refresh();
                    var row_height = $scope.modifOptions.rowHeight;
                    var header_height = $scope.modifOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.modifApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.modifApi.grid.handleWindowResize();
                }
            }
            if ($scope.blacklistApi) {
                if ($scope.blacklistOptions.totalItems > 0) {
                    $scope.blacklistApi.core.refresh();
                    var row_height = $scope.blacklistOptions.rowHeight;
                    var header_height = $scope.blacklistOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.blacklistApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.blacklistApi.grid.handleWindowResize();
                }
            }
        }

        $scope.getImportTemplate = function () {

            individualService.GetImportIndividualTemplate();

        };


    }]);

angular.module('accreditationApp')
    .controller('individualFormController', ['$scope', '$filter', '$q', '$location', '$routeParams', '$uibModalInstance', 'contextService', 'individualService', 'providerService', 'individualId', 'provider', '$controller', '$uibModal', function ($scope, $filter, $q, $location, $routeParams, $uibModalInstance, contextService, individualService, providerService, individualId, provider, $controller, $uibModal) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.initialize = false;
        if ($uibModalInstance == null) {
            contextService.currentPage.index = "individualList";
        }

        $scope.user = contextService.user;
        $scope.providers = [];
        $scope.nationalities = contextService.nationalities;
        $scope.showMore = false;
        $scope.showBlacklist = false;

        $scope.isUpdate = individualId ? true : false;

        individualService.getParameters(['IsPhotoMandatory', 'IsBirthDateMandatory', 'ImagePersonSizeRestriction', 'IsMobilePhoneMandatory', 'IsLandlinePhoneMandatory', 'IsEmailMandatory']).success(function (params) {
            $scope.isPhotoMandatory = params.filter(function (p) { return p.Name === 'IsPhotoMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationPicture);
            $scope.isBirthDateMandatory = params.filter(function (p) { return p.Name === 'IsBirthDateMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationBirthDate);
            $scope.isMobilePhoneMandatory = params.filter(function (p) { return p.Name === 'IsMobilePhoneMandatory'; })[0].Value;
            $scope.isLandlinePhoneMandatory = params.filter(function (p) { return p.Name === 'IsLandlinePhoneMandatory'; })[0].Value;
            $scope.isEmailMandatory = params.filter(function (p) { return p.Name === 'IsEmailMandatory'; })[0].Value;
            //show asterisk as if they're mandatory even if the user has the right to leave them empty
            $scope.showPhotoAsMandatory = params.filter(function (p) { return p.Name === 'IsPhotoMandatory'; })[0].Value;
            $scope.showBirthDateAsMandatory = params.filter(function (p) { return p.Name === 'IsBirthDateMandatory'; })[0].Value;
            $scope.showMobilePhoneAsMandatory = params.filter(function (p) { return p.Name === 'IsMobilePhoneMandatory'; })[0].Value;
            $scope.showLandlinePhoneAsMandatory = params.filter(function (p) { return p.Name === 'IsLandlinePhoneMandatory'; })[0].Value;
            $scope.showEmailAsMandatory = params.filter(function (p) { return p.Name === 'IsEmailMandatory'; })[0].Value;
            var paramImagePersonSizeRestriction = params.filter(function (p) { return p.Name === 'ImagePersonSizeRestriction'; })[0];
            $scope.imagePersonWidthRestriction = paramImagePersonSizeRestriction && paramImagePersonSizeRestriction.Value ? paramImagePersonSizeRestriction.Value.split('x')[0] : null;
        });

        $scope.LastNameSetArgs = function (val, el, attrs, ngModel) {
            return $scope.individual;
        };
        $scope.isUnique = true;
        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };


        $scope.individual = {
            IndividualId: 0,
            LastName: "",
            FirstName: "",
            ProviderId: null,
            BirthDate: undefined,
            HasImage: false,
            MobilePhoneNumber: "",
            FixPhoneNumber: "",
            Base64PngPhoto: null,
            Function: null,
            NationalityId: null,
            CustomFields: [],
            BrokenImage: false,
            Creator: '',
            Updater: ''
        };

        if ($scope.isUpdate) {
            $(".form-individual").Spinner("show");
            individualService.getIndividual(individualId).success(function (data) {
                $scope.individual = data;
                var provider = { id: data.ProviderId, text: data.ProviderName, nationalityId: data.NationalityId };
                $scope.provider = provider;
                $scope.providers.push(provider);
                $(".form-individual").Spinner("hide");
            });
        } else {
            individualService.getCustomFields().success(function (data) {
                $scope.individual.CustomFields = data.CustomFields;
            });
        }

        if (provider) {
            $scope.provider = provider;
            $scope.individual.ProviderId = provider.id;

        }

        if (!($scope.hasPermission(right.Provider_AccessByUserUnit) || $scope.hasPermission(right.Provider_AccessToAllUnit))) { //not admin nor superadmin
            $scope.provider = contextService.provider;
            $scope.individual.ProviderId = contextService.provider.id;
        }

        if ($scope.provider) {
            $scope.providers.push($scope.provider);
            $scope.individual.NationalityId = $scope.provider.nationalityId
        }

        $scope.displayBlacklist = function () {
            $scope.showBlacklist = !$scope.showBlacklist;
        }

        $scope.getProviders = function (q) {
            $scope.providers = [];
            $scope.providers.push(loadingItem);
            return providerService.getProviders(1, q)
                .then(function (data) {
                    $scope.providers = [];
                    angular.forEach(data.data.items, function (value, key) {
                        $scope.providers.push(value);
                    });
                    if ($scope.providers.length === 0) {
                        $scope.providers.push(noResultItem);
                    }
                });
        };

        $scope.deletePhoto = function () {
            $scope.individual.HasImage = false;
        };

        $scope.getProvider = function (provider) {
            $scope.individual.NationalityId = provider.nationalityId;
        };

        $scope.loading = false;

        $scope.validateCustomField = function (customField) {
            var verif = (customField.Required && (customField.Values.length > 0 || customField.File !== null)) || !customField.Required;
            return verif;
        };

        $scope.checkCustomFields = function () {
            for (var i = 0; i < $scope.individual.CustomFields.length; i++) {
                if (!$scope.validateCustomField($scope.individual.CustomFields[i])) {
                    return false;
                }
            }
            return true;
        };

        $scope.EncodeHtmlCustomFields = function () {
            angular.forEach($scope.individual.CustomFields.filter((item) => { return item.Type == "HtmlMessage" }), function (value) {
                    value.Htmls[0].Name = encodeURIComponent(value.Htmls[0].Name);
                    value.Definition = encodeURIComponent(value.Definition);
            });


        }
        $scope.setIndividualFormProperties = function () {
            $scope.individual.HasImage = !($(".img-picture").attr("src") === "null" || $(".img-picture").attr("src") === undefined);
            if ($scope.individual.HasImage && $scope.individual.PhotoCropMode) {
                var base64Image = file.getCroppedImage($scope.imagePersonWidthRestriction);
                if (base64Image !== false) {
                    $scope.individual.Base64PngPhoto = base64Image;
                }
            }
        };

        $scope.verifyOptionalFields = function () {
            if (($scope.showBirthDateAsMandatory
                && ($scope.individual.BirthDate === '' || $scope.individual.BirthDate === null || $scope.individual.BirthDate === undefined)
            ) || ($scope.showPhotoAsMandatory
                && ($(".img-picture").attr("src") === "null" || $(".img-picture").attr("src") === undefined))) {
                var ok;

                jConfirm(resourcesMessages.OverrideMandatoryFields, resources.Warning, function (ok) {

                    if (ok) {
                        $scope.finalizeSubmit();
                    } else {
                        $scope.loading = false;
                    }
                    $scope.$apply();
                });
                $scope.loading = false;
            } else {
                $scope.finalizeSubmit();
            }
        };

        $scope.finalizeSubmit = function () {

            if ($scope.individual.IndividualId > 0) {
                /* Modify */
                $scope.modify();
            } else {
                /* Add */
                if ($scope.checkCustomFields()) {
                    $(".form-individual").Spinner("show");
                    $scope.setIndividualFormProperties();
                    $scope.EncodeHtmlCustomFields();
                    individualService.addIndividual($scope.individual).success(function (data) {
                        if (data.Success) {
                            if ($uibModalInstance) {
                                $uibModalInstance.close(data.data);
                            } else {
                                if (data.Message) {
                                    site.successMessage(data.Message);
                                }
                                else {
                                    site.successMessage(resources.ValidationSuccess);
                                }
                                $location.path('/individualList/');
                            }
                            $scope.loading = true;
                        } else {
                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            else {
                                if (data.Exception)
                                    site.errorMessage(resourcesMessages.ExceptionDuringCreation, data.Exception);
                                else
                                    site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            }
                            $scope.loading = false;
                        }
                        $(".form-individual").Spinner("hide");
                    });
                } else {
                    $scope.loading = false;
                }
            }
        }

        $scope.submit = function (form) {
            $scope.loading = true;
            if (form.$valid) {
                $scope.verifyOptionalFields();
            } else {
                $scope.loading = false;
            }
        };

        $scope.modify = function () {
            $scope.loading = true;
            if ($scope.checkCustomFields()) {
                $scope.EncodeHtmlCustomFields();
                // 1- check isunique
                individualService.isUnique($scope.individual).success(function (data) {
                    if (data.Success) {
                        //modification
                        $(".form-individual").Spinner("show");
                        $scope.setIndividualFormProperties();
                        individualService.modifyIndividual($scope.individual).success(function (data) {
                            if (data.Success) {
                                if ($uibModalInstance) {
                                    $uibModalInstance.close(data.data);
                                } else {
                                    if (data.Message) {
                                        site.successMessage(data.Message);
                                    }
                                    else {
                                        site.successMessage(resources.ValidationSuccess);
                                    }
                                    $location.path('/individualList/');
                                }
                                $scope.loading = true;
                            } else {
                                if (data.ExceptionOccured)
                                    site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                                else {
                                    if (data.Exception)
                                        site.errorMessage(resourcesMessages.ExceptionDuringModification, data.Exception);
                                    else
                                        site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                                }
                                $scope.loading = false;
                            }
                            $(".form-individual").Spinner("hide");
                        });
                    } else {
                        if (data.ExceptionOccured) //catch
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        else //!unique
                        {
                            var duplicateId = data.data;
                            //popin choix entre actuelle et autre (avec lien)
                            // 2a - premier : fusion
                            // 2b- deuxieme : redirection 2eme + set active
                            // 2c - annuler
                            //site.errorMessage(resourcesMessages.CheckUniciteIndividual, data.Exception);
                            $uibModal.open({
                                templateUrl: '/Scripts/Angular/Individual/Views/MergeDuplicate.html' + '?version=' + Date.now(),
                                controller: 'IndividualMergeDuplicateWarningController',
                                windowClass: 'individual-merge-duplicate-window',
                                resolve: {
                                    individual: $scope.individual,
                                    duplicateId: duplicateId
                                }
                            });

                            $scope.loading = false;
                        }
                    }
                });

            } else {
                $scope.loading = false;
            }
        };

        $scope.cancel = function () {
            if ($uibModalInstance) {
                $uibModalInstance.dismiss('cancel');
            } else {
                $location.path('/individualList/');
            }
        };

        $scope.$watch("individual.NationalityId", function (NationalityId) {
            if (NationalityId !== null && $scope.individual.FixPhoneNumber == "" && $scope.individual.MobilePhoneNumber == "" && $scope.nationalities.length !== 0) {
                $(form.MobilePhoneNumber).val("+" + $filter('filter')(contextService.nationalities, { NationalityId: NationalityId })[0].DiallingCode + "");
                $(form.FixPhoneNumber).val("+" + $filter('filter')(contextService.nationalities, { NationalityId: NationalityId })[0].DiallingCode + "");
            }
        }, true);

        $scope.$watch("initialize", function (initialize) {
            if (initialize) {
                site.initDate();
                file.init({ crop: true });
                $("#individualPicture").click(file.fileUpload);
                camera.init({ crop: true });
            }
        }, true);

        $scope.initCropper = function () {
            var img = $(".img-picture");
            var imgName = img.attr("src");
            file.initCropper();
        };

        $scope.validateCropper = function () {
            var img = $(".img-picture");
        };
    }]);
angular.module('accreditationApp')
    .controller('individualListController', ['$scope', '$rootScope', '$filter', '$location', '$q', 'contextService', 'individualService', 'providerService', 'assignmentService', 'vehicleService', 'passService', '$uibModal', '$controller'
        , function ($scope, $rootScope, $filter, $location, $q, contextService, individualService, providerService, assignmentService, vehicleService, passService, $uibModal, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "individualList";
        $rootScope.rootTabulation = "individualList";

        assignmentService.resetPageState();
        vehicleService.resetPageState();
        passService.resetPageState();

        $scope.pageClass = "in";
        $scope.user = contextService.user;
        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        $("title").html(resources.Individual);
        $scope.search = individualService.pageState.search;
        $scope.providers = individualService.pageState.providers;
        $scope.pageState = individualService.pageState;

        individualService.getSearchCustomFields().success(function (data) {
            $scope.search.CustomFields = data.IndividualFields;
            $scope.initialSearchValues = JSON.stringify($scope.search);
        });
        individualService.isFunctionPresent().success(function (data) {
            var functionNameColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "FunctionName"; })[0];
            functionNameColumn.visible = data;
        });

        $scope.indPagination = {
            search: "",
            page: 1,
            isRequestMoreItems: true
        }

        $scope.proPagination = {};
        angular.copy($scope.indPagination, $scope.proPagination);

        $scope.paginationOptions = {
            pageNumber: 1,
            pageSize: contextService.paginationPageSizes[0],
            totalItems: 0,
            sort: 'Name',
            sortOrder: 'asc'
        };


        $scope.selectRow = function (row) {
            $scope.gridApi.selection.selectRow(row.entity);
        }

        $scope.selectAllRow = function () {
            $scope.gridApi.selection.selectAllRows();
        }

        $scope.gridOptions = {
            paginationPageSizes: contextService.paginationPageSizes,
            enableSorting: true,
            multiSelect: true,
            selectionRowHeaderWidth: 60,
            enableRowSelection: true,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableSelectAll: true,
            useExternalPagination: true,
            enablePaginationControls: false,
            useExternalSorting: true,
            showGridFooter: false,
            rowHeight: 50,
            columnDefs: [
                { field: 'IndividualId', displayName: "AssignmentId", visible: false, enableSorting: false, enableColumnMenu: false },
                { field: 'ProviderId', width: 30, visible: false, enableColumnMenu: false, displayName: "" },
                {
                    field: 'Picture', width: 50, displayName: $scope.resources.Photo, enableSorting: false, enableColumnMenu: false, cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\">' +
                        '<div ng-if="!row.entity.BrokenImage && row.entity.ImageName != \'\'" class=\"thumbnail thumbnail-default\"><img  ng-if="row.entity.HasImage && !row.entity.BrokenImage" class="img-grid hasQtip qtipImg" src="/Content/images/individual/{{row.entity.ImageName}}?width=35&height=35&mode=crop" alt="" data-qtip="images/ShowIndividualPicture?id=29&amp;width=200&amp;height=200" data-hasqtip="8"><i ng-if="!row.entity.HasImage" class="fa fa-user" title="{{grid.appScope.resourcesMessages.NoImageSource}}"></i></div>' +
                        '<div ng-if="row.entity.BrokenImage && row.entity.ImageName != \'\'" class="thumbnail thumbnail-error" title="{{grid.appScope.resourcesMessages.InvalidImageSource}}"><i class="fa fa-user"></i></div>' +
                        '</div>'
                },
                {
                    field: 'Name', displayName: $scope.resources.Name, enableColumnMenu: false,
                    cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\">' +
                        '<div class="individual-cell">' +
                        '<span class="individual-lastname">{{row.entity.LastName}} </span><span class="individual-firstname">{{row.entity.FirstName}}</span><span ng-if="row.entity.IsBlacklisted && ' + $scope.hasPermission(right.Individual_CanUseBlacklist) + '" class="blacklist blacklist-individual pull-right">{{grid.appScope.resources.Blacklist}}</span>' +
                        '</div>' +
                        '</div>'
                },
                { field: 'FunctionName', enableColumnMenu: false, displayName: $scope.resources.Function },
                { field: 'ProviderName', visible: $scope.hasPermission(right.Individual_DisplayListFieldsFullView), enableColumnMenu: false, displayName: $scope.resources.Provider },
                { field: 'BirthDate', enableColumnMenu: false, visible: false, displayName: $scope.resources.BirthDate },
                { field: 'Action', width: 76, enableColumnMenu: false, displayName: "", visible : $scope.hasPermission(right.Individual_Edit), cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scopse"><a class="btn btn-circle btn-primary" href="#createIndividual/{{row.entity.IndividualId}}"><i class="fa fa-pencil"></i></a></div>' }
            ],

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {

                    if (sortColumns.length != 0) {
                        $scope.paginationOptions.sort = sortColumns[0].name;
                        $scope.paginationOptions.sortOrder = sortColumns[0].sort.direction;
                    }
                    $scope.getPage();
                });
                $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    $scope.paginationOptions.pageNumber = newPage;
                    $scope.paginationOptions.pageSize = pageSize;
                    $scope.getPage();
                });
            }
        };

        $scope.dateFormatter = function (date) {
            return site.dateFormatter(date);
        }

        /*************************************
        **************** Getter *************
        ***********************************/

        $scope.getProviders = function (q) {
            if ($scope.providers.length == 0 || q != "") {
                $scope.providers.splice(0, $scope.providers.length);
                $scope.providers.push(loadingItem);
                return providerService.getProviders($scope.proPagination.page, q)
                    .then(function (data) {
                        $scope.providers.splice(0, $scope.providers.length);
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length == 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            }
        };

        $scope.getGridIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.IndividualId);
            });
            return ids;
        }

        $scope.getPage = function (sForm) {
            $scope.loading = true;
            individualService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $scope.loading = false;
            });
        }

        $scope.resetSearchFilters = function () {
            individualService.resetPageState();
            $scope.search = individualService.pageState.search;
        }

        /*************************************
        **************** Action *************
        ***********************************/

        $scope.remove = function () {
            var ids = $scope.getGridIds();
            if (ids.length == 0) {
                jAlert(resourcesMessages.AtLeastOneIndividualSelected, resources.Warning);
            } else {
                jConfirm($scope.resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                    if (ok) {
                        individualService.deleteIndividual(ids).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, data.Exception);
                            }
                            $scope.getPage();
                        });
                        $scope.$apply();
                    }
                });
            }
        };

        $scope.download = function () {
            if ($rootScope.isExporting) {
                jAlert(resourcesMessages.IsExporting, resources.Warning);
            } else {
                var modal = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/exportForm.html',
                    controller: 'exportWarningController',
                    resolve: {
                        exportType: function () {
                            return "individual";
                        }
                    }
                });

                modal.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.ExportSuccess);
                        $scope.getPage();
                    } else {
                        site.errorMessage($scope.resourcesMessages.ExportFailed, null);
                    }
                });
            }
        };


        $scope.getPage();

        /*************************************
        **************** Watch *************
        ***********************************/

        $scope.$watch("context", function (context) {
            if (context != null && context.event != null) {
                $scope.search.EventId = context.event.EventId;
            }
        }, true);

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height);
                $scope.gridApi.grid.handleWindowResize();
            }
        });


    }]);
angular.module('accreditationApp')
    .controller('IndividualMergeDuplicateWarningController', ['$scope', '$location', '$uibModalInstance', 'duplicateId', 'individual', 'contextService', 'individualService', '$controller',  function ($scope, $location, $uibModalInstance, duplicateId, individual, contextService, individualService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));

        if (duplicateId > 0) {
            $scope.MergeSentence = resourcesMessages.IndividualMergeDuplicateWarning;
            $scope.URLToOld = "/Assignment/#/createIndividual/" + duplicateId;
        }

        $scope.continue = function () {
            $uibModalInstance.close(true);
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.merge = function () {
            individualService.mergeIndividual(individual, duplicateId).success(function (data) {
                if (data.Success) {
                    if ($uibModalInstance) {
                        $uibModalInstance.close(data.data);
                    } 
                    site.successMessage(resources.ValidationSuccess);
                    $location.path('/individualList/');
                } else {
                    if (data.ExceptionOccured)
                        site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                    else {
                        if (data.Exception)
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, data.Exception);
                        else
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                    }
                    $scope.loading = false;
                }
            });
        };

        $scope.keepOld = function () {
            individualService.enableOne(duplicateId).success(function (data) {
                $scope.cancel();
            });
        };

    }]);


angular.module('accreditationApp')
    .service('individualService', ['$resource', '$http', function ($resource, $http) {

        this.getParameters = function (codes) {
            var data = {
                codes: codes
            };
            return $http.post('/Parameter/GetParametersByCode', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        }

        this.pageStateModel = {
            search: {
                Name: null,
                ProviderName: null,
                HasImage: null,
                NoImage: null,
                ProviderIds: null,
                OnlyBlacklisted: null,
                CustomFields: []
            },
            showMore: false,
            providers: []
        }

        this.pageState = {};

        this.resetPageState = function () {
            angular.copy(this.pageStateModel, this.pageState);
        };

        this.dataBind = function (grid, search) {
            var options = {
                PageIndex: grid.pageNumber,
                PageSize: grid.pageSize,
                SortColumn: grid.sort,
                SortOrder: grid.sortOrder
            };
            return $http.post('/Individual/DataBind', $.param({ grid: options, Search: search }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };


        this.isUnique = function (individual) {
            return $http.post('/Individual/IsUnique', individual);
        };

        this.enableOne = function (individualId) {
            return $http.post('/Individual/EnableOne', { individualId: individualId });
        };

        this.addIndividual = function(individual) {
            return $http.post('/Individual/Add',
                $.param(individual),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.modifyIndividual = function (individual) {
            return $http.post('/Individual/Modify',
                $.param(individual),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.mergeIndividual = function (individual, doublonId) {
            return $http.post('/Individual/Merge', $.param({ Individual: individual, doublonId: doublonId }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.deleteIndividual = function(ids) {
            var data = {
                ids: ids
            };
            return $http.post('/Individual/Delete',
                $.param(data),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.getIndividual = function(individualId) {
            var data = {
                individualId: individualId
            };
            return $http.post('/Individual/GetIndividual',
                $.param(data),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });

        };

        this.getIndividuals = function(page, search, providerId) {
            return $http.post('/Individual/GetIndividuals', { page: page, q: search, providerId: providerId });
        };

        this.getNationalities = function(q) {
            return $http.post('/Provider/GetNationalities', { q: q, page: 1, size: 1000 });
        };

        this.getCustomFields = function() {
            return $http.post('/Individual/GetCustomFields');
        };

        this.isFunctionPresent = function () {
            return $http.post("/Individual/IsFunctionPresent");
        };

        this.getSearchCustomFields = function () {
            return $http.post("/Individual/GetSearchCustomFields");
        };

        this.GetImportIndividualTemplate = function () {
            return window.open("/Individual/GetImportIndividualTemplate");
        };

        this.Export = function (param) {
            return $http.post("/Individual/Export?" + param);
        };

    }]).run(['individualService', function (individualService) {
        angular.copy(individualService.pageStateModel, individualService.pageState);
    }]);
angular.module('accreditationApp')
    .controller('guestPassFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'passService', 'providerService', 'individualService', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, passService, providerService, individualService, sharedService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "passList";

        //parameter to control displaying profile select in _ProfileForm ( not displayed for guest assignements)
        $scope.displayProfile = true;

        var startDate = new Date();
        startDate.setHours(8);
        startDate.setMinutes(00);

        var endDate = new Date();
        endDate.setHours(20);
        endDate.setMinutes(0);

        $scope.pass = {
            CreationUnitId: null,
            PassTypeId: 3,
            ProfileId: null,
            IndividualFirstName: "",
            IndividualLastName: "",
            IndividualFunction: "",
            ProviderId: null,
            GuestProviderName: "",
            ProviderName: null,
            PopulationCode: "",
            ReferenceCodeId: null,
            ValidityStartDate: "",
            ValidityEndDate: "",
            Comment: "",
            PopulationCode: "",
            CustomFields: [],
            PassLines: [],
            ZoneIds: [],
            StepIds: [],
            DisplayValidityStartTime: moment(startDate).format('YYYY-MM-DD HH:mm'),
            DisplayValidityStartDate: null,
            DisplayValidityEndTime: moment(endDate).format('YYYY-MM-DD HH:mm'),
            DisplayValidityEndDate: null,

            Status: ""
        }

        assignmentService.getWordingStyleParameter().success(function (data) {
            $scope.wordingStyle = data;
        });
        passService.getDefaultPassOrganizationId().success(function (organizationId) {
            $scope.defaultPassOrganizationId = organizationId;
        });

        sharedService.getRgpd().success(function (data) {
            $scope.rgpd = data.data;
        });


        $scope.isUpdate = $routeParams.passId ? true : false;
        $scope.passTypes = contextService.createPassTypes;
        $scope.providers = [];
        $scope.deliveryPlaces = contextService.deliveryPlaces;
        $scope.passZones = contextService.passZones;
        $scope.passSurZones = contextService.passSurZones;
        $scope.profiles = [];
        $scope.referenceCodes = [];
        $scope.organizationUnitId = [];
        $scope.units = [];
        $scope.steps = contextService.steps;
        $scope.user = contextService.user;

        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        $scope.groupByUnit = function (item) {
            return item.ParentName;
        }
            
        var hideFormPassSpinner = function () {
            $(".form-pass").Spinner("hide");
        };

        var showFormPassSpinner = function () {
            $(".form-pass").Spinner("show");
        };
        /**************** Getters ******************/


        $scope.getUserUnitsTree = function (providerId) {
            if ($scope.units.indexOf(loadingItem) == -1) {
                $scope.units = [];
                $scope.units.push(loadingItem);
            }

            passService.GetUnitsTreeByProviderForPassManagement(providerId).success(function (data) {
                $scope.units = [];
                //set default unit
                if (data.length > 0 && $scope.pass.CreationUnitId == null) {
                    $scope.pass.CreationUnitId = data[0].OrganizationUnitId;
                    $scope.pass.ProfileId = null;
                    $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                }
                angular.forEach(data, function (value, key) {
                    $scope.units.push(value);
                });
            });
        }


        $scope.getProviders = function (q) {
            if ($scope.providers.indexOf(loadingItem) == -1) {
                $scope.providers = [];
                $scope.providers.push(loadingItem);
            }
            return providerService.getProviders(1, q, $scope.defaultPassOrganizationId)
                .then(function (data) {
                    $scope.providers = [];
                    angular.forEach(data.data.items, function (value, key) {
                        $scope.providers.push(value);
                    });
                });
        };

        $scope.selectAllZones = function () {
            var untoggleAll = ($scope.passZones.length + $scope.passSurZones.length) == $scope.pass.ZoneIds.length;
            if (untoggleAll) {
                angular.forEach($scope.passZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index >= 0) {
                        $scope.pass.ZoneIds.splice(0);
                    }
                });
                angular.forEach($scope.passSurZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index >= 0) {
                        $scope.pass.ZoneIds.splice(0);
                    }
                });
                $scope.allZonesSelected = false;
            } else {
                angular.forEach($scope.passZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index < 0) {
                        $scope.pass.ZoneIds.push(zone.ZoneId);
                    }
                });
                angular.forEach($scope.passSurZones,
                    function (zone) {
                        var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.pass.ZoneIds.push(zone.ZoneId);
                        }
                    });
                $scope.allZonesSelected = true;
            }
        }

        $scope.selectZone = function (zoneId) {
            var index = $scope.pass.ZoneIds.indexOf(zoneId);
            if (index < 0) {
                $scope.pass.ZoneIds.push(zoneId);



            } else {
                $scope.pass.ZoneIds.splice(index, 1);
                $scope.allZonesSelected = false;
            }
        }

        $scope.getZonesByProfileId = function (profile) {
            passService.getZonesByProfileId(profile.ProfileId).success(function (passZones) {
                angular.forEach(passZones, function (value, key) {
                    $scope.pass.ZoneIds.push(value.ZoneId);
                });
            });
        }

        $scope.validateCustomField = function (customField) {
            var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) || customField.Required == false;
            return verif;
        }

        $scope.checkCustomFields = function () {
            for (var i = 0; i < $scope.pass.CustomFields.length; i++) {
                if (!$scope.validateCustomField($scope.pass.CustomFields[i])) {
                    return false;
                }
            }
            return true;
        }


        $scope.isModifiable = function () {
            return contextService.isModifiable($scope.isUpdate, $scope.pass.Status, $scope.user);
        }

        $scope.isValidable = function () {
            return contextService.isValidable($scope.pass.Status, $scope.user);
        }

        /**************** Actions ******************/

        $scope.affecter = function (form) {
            $scope.loading = true;
            form.$submitted = true;

            if (form.$valid && $scope.checkCustomFields()) {
                // creer une affectation
                showFormPassSpinner();

                //add times to start and end date validity for pass

                passService.setDate($scope.pass);

                passService.addGuestPass($scope.pass).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $location.path('/passList/');
                    } else {
                        if (data.ExceptionOccured)
                        {
                            site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                        }
                        else {
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                    }
                    hideFormPassSpinner();
                    $scope.loading = false;
                });
            } else {
                $scope.loading = false;
            }
        };

        $scope.cancel = function () {
            var ok;
            jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
                if (ok) {
                    showFormPassSpinner();
                    passService.cancelPass([$scope.pass.PassId], $scope.pass.Comment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/passList/');
                        }
                        hideFormPassSpinner();
                    });
                    $scope.$apply();
                }
            });
        };


        $scope.modify = function (form) {

            form.$submitted = true;

            if (form.$valid && $scope.checkCustomFields()) {
                // creer une affectation
                showFormPassSpinner();

                passService.setDate($scope.pass);

                passService.modifyGuestPass($scope.pass).success(function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ModificationSuccess);
                        $location.path('/passList/');
                    } else {
                        if (data.ExceptionOccured) {
                            site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                        }
                        else {
                            site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                        }
                    }
                    hideFormPassSpinner();
                });
            }
        };

        $scope.getRichStatus = function () {
            passService.getRichStatusForPass($scope.pass.PassId).success(function (data) {
                $scope.pass.Status = data.status;
                hideFormPassSpinner();
            });
        };

        $scope.getUnitConfiguration = function (creationUnitId) {
            $scope.profiles.push(loadingItem);
            passService.GetUnitConfiguration(creationUnitId, "GuestPass").success(function (data) {
                $scope.profiles = data.profiles;
            });
        }


        $scope.showActionsHistory = function (passId) {
            passService.getActionsHistory(passId).success(function (data) {
                $scope.actions = data;
                $(".widget-side").show("slide", { "direction": "left" });
            });
        };



        $scope.$watch("pass.PassTypeId", function (passTypeId) {
            if (passTypeId != undefined && passTypeId != 3) {
                $location.path($filter('filter')($scope.passTypes, { PassTypeId: passTypeId })[0].Url);
            }
        });

        if ($scope.isUpdate) {
            showFormPassSpinner();
            passService.getPass($routeParams.passId).success(function (data) {

                $scope.pass = data;

                passService.formatPassValidityStartEndDates($scope.pass, data.ValidityStartDate, data.ValidityEndDate);

                $scope.getUnitConfiguration(data.CreationUnitId);
                $scope.getUserUnitsTree($scope.pass.ProviderId);
                $scope.getRichStatus();

            });
        } else {
            if ($scope.hasPermission(right.UserLevelExclusiveRight)) {
                $scope.pass.ProviderId = $scope.user.ProviderId;
                $scope.pass.ProviderName = $scope.user.ProviderName;
                $scope.getUserUnitsTree($scope.pass.ProviderId);
            }
            passService.getCustomFields("guest").success(function (data) {
                $scope.pass.CustomFields = data.PassFields;
            });
        }


    }]);


angular.module('accreditationApp')
    .controller('importPassFormController', ['$scope', '$route', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'assignmentService', 'providerService', 'individualService', 'vehicleService', 'Upload', '$timeout', '$controller', function ($scope, $route, $timeout, $filter, $location, $q, $uibModal, contextService, assignmentService, providerService, individualService, vehicleService, Upload, $timeout, $controller) {
      angular.extend(this, $controller('baseController', { $scope: $scope }));
      contextService.currentPage.index = "passList";

      individualService.resetPageState();
      vehicleService.resetPageState();

      // upload later on form submit or something similar
      $scope.submit = function () {
          if ($scope.form.file.$valid && $scope.file && $scope.form.fileZip.$valid) {
              $scope.upload($scope.file, $scope.fileZip);
          }
      };
      $scope.label = null;
      $scope.uploadSuccess = null;
      $scope.applyModifToIndividual = false;
      $scope.ignoreBlacklisted = true;

      // upload on file select or drop
        $scope.upload = function (file, fileZip) {
          $(".form-import").Spinner("show");
          $scope.lineNumber = 0;
          $scope.uploadSuccess = false;

          Upload.upload({
              url: '/Pass/Import',
              data: { file: file, FileZip: fileZip, ApplyModifToIndividual: $scope.applyModifToIndividual, IgnoreBlacklisted: $scope.ignoreBlacklisted }
          }).then(function (resp) {
              $(".form-import").Spinner("hide");
              $(".modif-results").Spinner("hide");

              if (resp.data.Success) {
                  $scope.uploadSuccess = true;
                  $scope.lineNumber = resp.data.LineNumber;

              } else {
                  $scope.uploadSuccess = false;
                  if (resp.data.ExceptionOccured) {
                      site.errorMessage(resourcesMessages.ExceptionDuringImport, null);
                  }
                  else {
                      if (resp.data.Exceptions.length > 0) {
                          $scope.gridOptions.totalItems = resp.data.Exceptions.length;
                          $scope.gridOptions.data = resp.data.Exceptions;
                      }
                  }
                  $scope.resize(0);
              }
              console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
          }, function (resp) {
              console.log('Error status: ' + resp.status);
          }, function (evt) {
              var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
              console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
          });

      };

      $scope.validateImportWithModifications = function() {
          $scope.applyModifToIndividual = true;
          $(".modif-results").Spinner("show");
          $scope.submit();
      };

      $scope.acceptBlacklisted = function () {
            $scope.ignoreBlacklisted = true;
            if ($scope.modifOptions.data.length > 0) {
                $scope.showBlacklist = false;
                $scope.showModif = true;
            } else {
                $(".modif-results").Spinner("show");
                $scope.submit();
            }
        };

      $scope.gridOptions = {
          selectionRowHeaderWidth: 60,
          enableScrollbars: 0,
          enableHorizontalScrollbar: 0,
          enableVerticalScrollbar: 0,
          enableRowSelection: true,
          enableSelectAll: true,
          useExternalPagination: true,
          useExternalSorting: true,
          showGridFooter: false,
          multiSelect: true,
          enablePaginationControls: false,

          rowHeight: 50,
          columnDefs: [
              { field: 'LineNb', displayName: "Ligne", enableSorting: true, enableColumnMenu: false },
              { field: 'ErrorField', displayName: "Champ", enableSorting: true, enableColumnMenu: false },
              { field: 'ErrorType', displayName: "Type d'érreur", enableColumnMenu: false },
              { field: 'ErrorMessage', displayName: "Message", enableColumnMenu: false }
          ],
          onRegisterApi: function (gridApi) {
              $scope.gridApi = gridApi;
          }
      };

      $scope.modifOptions = {
          selectionRowHeaderWidth: 60,
          enableScrollbars: 0,
          enableHorizontalScrollbar: 0,
          enableVerticalScrollbar: 0,
          enableRowSelection: false,
          enableSelectAll: false,
          useExternalPagination: true,
          useExternalSorting: true,
          showGridFooter: false,
          multiSelect: false,
          enablePaginationControls: false,

          rowHeight: 50,
          columnDefs: [
          { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
          { field: 'IndividualName', displayName: "Personne mise à jour", enableSorting: false, enableColumnMenu: false },

          { field: 'FieldName', enableSorting: false, displayName: "Champ modifié", enableColumnMenu: false },
          { field: 'OldValue', enableSorting: false, displayName: "Ancienne valeur", enableColumnMenu: false },

          { field: 'NewValue', enableSorting: false, displayName: "Nouvelle valeur", enableColumnMenu: false }

          ],
          onRegisterApi: function (gridApi) {
              $scope.modifApi = gridApi;
          }
      };

        $scope.blacklistOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne concernée", enableSorting: false, enableColumnMenu: false },

                { field: 'StartDate', enableSorting: false, displayName: "Date de début", enableColumnMenu: false },
                { field: 'EndDate', enableSorting: false, displayName: "Date de fin", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.blacklistApi = gridApi;
            }
        };

      $scope.$watch('gridApi.core.getVisibleRows().length', function () {
          $scope.resize(0);
      });

      $scope.$watch('modifApi.core.getVisibleRows().length', function () {
          $scope.resize(0);
      });

        $scope.$watch('blacklistApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });


      $scope.resize = function (plus) {
          if ($scope.gridApi) {
              $scope.gridApi.core.refresh();
              var row_height = $scope.gridOptions.rowHeight;
              var header_height = $scope.gridOptions.selectionRowHeaderWidth;
              var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
              $('.grid').height(height + plus);
              $scope.gridApi.grid.handleWindowResize();
          }
          if ($scope.modifApi) {
              if ($scope.modifOptions.totalItems > 0) {
                  $scope.modifApi.core.refresh();
                  var row_height = $scope.modifOptions.rowHeight;
                  var header_height = $scope.modifOptions.selectionRowHeaderWidth;
                  var height = row_height * $scope.modifApi.core.getVisibleRows().length + header_height;
                  $('.grid').height(height + plus);
                  $scope.modifApi.grid.handleWindowResize();
              }
          }
          if ($scope.blacklistApi) {
              if ($scope.blacklistOptions.totalItems > 0) {
                  $scope.blacklistApi.core.refresh();
                  var row_height = $scope.blacklistOptions.rowHeight;
                  var header_height = $scope.blacklistOptions.selectionRowHeaderWidth;
                  var height = row_height * $scope.blacklistApi.core.getVisibleRows().length + header_height;
                  $('.grid').height(height + plus);
                  $scope.blacklistApi.grid.handleWindowResize();
              }
          }
      }
      
  }]);

angular.module('accreditationApp')
    .controller('mailPassFormController', ['$scope', '$uibModalInstance', 'contextService', 'passService', 'passIds', '$controller', function ($scope, $uibModalInstance, contextService, passService, passIds, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.numberPass = passIds.length;

        $scope.send = function() {
            $(".modal-content").Spinner("show");
            passService.SendEmail(passIds).success(function(data) {
                $(".modal-content").Spinner("hide");
                $uibModalInstance.close(data);
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('passFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'passService', 'providerService', 'Upload', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, passService, providerService, Upload, sharedService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "passList";


        var startDate = new Date();
        startDate.setHours(8);
        startDate.setMinutes(00);

        var endDate = new Date();
        endDate.setHours(20);
        endDate.setMinutes(0);


        $scope.pass = {

            PassTypeId: 1,
            ProfileId: null,
            ProviderId: null,
            Provider: null,
            ValidityStartDate: "",
            ValidityEndDate: "",
            Comment: "",
            Individual: {},
            IndividualId: null,
            ZoneIds: [],
            StepIds: [],
            Individuals: [],
            IndividualIds: [],
            CustomFields: [],

            DisplayValidityStartTime: moment(startDate).format('YYYY-MM-DD HH:mm'),
            DisplayValidityStartDate: null,
            DisplayValidityEndTime: moment(endDate).format('YYYY-MM-DD HH:mm'),
            DisplayValidityEndDate: null,

            Status: ""
        };

        $scope.individualIdsInError = [];
        $scope.individualsInError = false;
        $scope.individualsPage = 1;
        $scope.lastIndividualsQuery = "";
        $scope.busyLoading = false;
        $scope.resources = resources;
        $scope.event = contextService.event;
        $scope.tempProvider = null;
        $scope.isUpdate = $routeParams.passId ? true : false;
        $scope.showMore = false;
        $scope.passTypes = contextService.createPassTypes;
        $scope.providers = [];
        $scope.deliveryPlaces = contextService.deliveryPlaces;

        $scope.passZones = contextService.passZones;
        $scope.passSurZones = contextService.passSurZones;

        $scope.allZonesSelected = false;
        $scope.profiles = [];
        $scope.referenceCodes = [];
        $scope.defaultPassOrganizationId = contextService.defaultPassOrganizationId;
        $scope.units = [];
        $scope.individuals = [];
        $scope.steps = contextService.steps;
        $scope.user = contextService.user;
        $scope.uploadFiles = assignmentService.uploadFiles;
        $scope.displayZoneImage = site.params.displayZoneImage;

        passService.getParameters(['IsPhotoMandatory', 'IsBirthDateMandatory', 'WordingStyle']).success(function (params) {
            $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;

            $scope.isPhotoMandatory = params.filter(function (p) { return p.Name === 'IsPhotoMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationPicture);
            $scope.isBirthDateMandatory = params.filter(function (p) { return p.Name === 'IsBirthDateMandatory'; })[0].Value && !$scope.hasPermission(right.Individual_CanSurpassObligationBirthDate);
        });

        sharedService.getRgpd().success(function (data) {
            $scope.rgpd = data.data;
        });


        passService.getDefaultPassOrganizationId().success(function (organizationId) {
            $scope.defaultPassOrganizationId = organizationId;
        });

        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        $scope.groupByUnit = function (item) {
            return item.ParentName;
        }

        $scope.resetIndividuals = function (provider) {
            $scope.individuals = [];
            $scope.tempProvider = provider;
        };

        var hideFormPassSpinner = function () {
            $(".form-pass").Spinner("hide");
        };

        var showFormPassSpinner = function () {
            $(".form-pass").Spinner("show");
        };
        /**************** Getters ******************/

        $scope.getUserUnitsTree = function (providerId) {

            if ($scope.units.indexOf(loadingItem) == -1) {
                $scope.units = [];
                $scope.units.push(loadingItem);
            }


            assignmentService.GetUnitsTreeByProviderForPassManagement(providerId).success(function (data) {
                $scope.units = [];
                //set default unit
                if (data.length > 0 && $scope.pass.CreationUnitId == null) {
                    $scope.pass.CreationUnitId = data[0].OrganizationUnitId;
                    $scope.pass.ProfileId = null;
                    $scope.pass.ZoneIds = [];
                    $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                }
                angular.forEach(data, function (value, key) {
                    $scope.units.push(value);
                });
                if ($scope.units.length == 0) {
                    $scope.units.push(noResultItem);
                }
            });
        }

        $scope.getProviders = function (q) {
            $scope.providers = [];
            $scope.providers.push(loadingItem);
            return providerService.getProviders(1, q, $scope.defaultPassOrganizationId)
                .then(function (data) {
                    $scope.providers = [];
                    angular.forEach(data.data.items, function (value, key) {
                        $scope.providers.push(value);
                    });
                    if ($scope.providers.length == 0) {
                        $scope.providers.push(noResultItem);
                    }
                });
        };

        $scope.getIndividuals = function (q) {
            $scope.individuals = [];
            if ($scope.pass.ProviderId != null) {
                $scope.individuals.push(loadingItem);
                $scope.individualsPage = 1;
                return passService.getIndividualsByProviderId($scope.pass, $scope.individualsPage, q)
                    .then(function (data) {
                        $scope.individuals = [];
                        $scope.individualsPage++;
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.individuals.push(value);
                        });
                        if ($scope.individuals.length == 0) {
                            $scope.individuals.push(noResultItem);
                        }
                    });
            }
        };

        $scope.getNextIndividuals = function (q) {
            if ($scope.pass.ProviderId != null && !$scope.busyLoading) {
                $scope.busyLoading = true;
                if (q !== $scope.lastIndividualsQuery) {
                    $scope.individualsPage = 1;
                    $scope.individuals = [];
                }
                return passService.getIndividualsByProviderId($scope.pass, $scope.individualsPage, q)
                    .then(function (data) {
                        $scope.individualsPage++;
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.individuals.push(value);
                        });
                        $scope.busyLoading = false;
                    });
            }
        };

        $scope.selectAllZones = function () {
            var untoggleAll = ($scope.passZones.length + $scope.passSurZones.length) == $scope.pass.ZoneIds.length;
            if (untoggleAll) {
                angular.forEach($scope.passZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index >= 0) {
                        $scope.pass.ZoneIds.splice(0);
                    }
                });
                angular.forEach($scope.passSurZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index >= 0) {
                        $scope.pass.ZoneIds.splice(0);
                    }
                });
                $scope.allZonesSelected = false;
            } else {
                angular.forEach($scope.passZones, function (zone) {
                    var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                    if (index < 0) {
                        $scope.pass.ZoneIds.push(zone.ZoneId);
                    }
                });
                angular.forEach($scope.passSurZones,
                    function (zone) {
                        var index = $scope.pass.ZoneIds.indexOf(zone.ZoneId);
                        if (index < 0) {
                            $scope.pass.ZoneIds.push(zone.ZoneId);
                        }
                    });
                $scope.allZonesSelected = true;
            }
        }

        $scope.selectZone = function (zoneId) {
            var index = $scope.pass.ZoneIds.indexOf(zoneId);
            if (index < 0) {
                $scope.pass.ZoneIds.push(zoneId);
                if ($scope.pass.ZoneIds.length === ($scope.passZones.length + $scope.surZones.length)) {
                    $scope.allZonesSelected = true;
                }
            } else {
                $scope.pass.ZoneIds.splice(index, 1);
                $scope.allZonesSelected = false;
            }
        }

        $scope.getZonesByProfileId = function (profile) {
            passService.getZonesByProfileId(profile.ProfileId).success(function (passZones) {
                angular.forEach(passZones, function (value, key) {
                    $scope.pass.ZoneIds.push(value.ZoneId);
                });
            });
        }

        $scope.getLastAssignmentByIndividualId = function (individualId) {
            assignmentService.getLastAssignmentByIndividualId($scope.pass.EventId, individualId, $scope.pass.AssignmentTypeId).success($scope.bindAssignment);
        }

        $scope.getUnitConfiguration = function (creationUnitId) {

            if ($scope.profiles.indexOf(loadingItem) == -1) {
                $scope.profiles.push(loadingItem);
            }
            assignmentService.GetUnitConfiguration(creationUnitId, "IndividualPass").success(function (data) {
                $scope.profiles = data.profiles;
                //set default profile
                if (data.profiles.length > 0 && $scope.pass.ProfileId == null) {
                    $scope.pass.ProfileId = data.profiles[0].ProfileId;
                    $scope.getZonesByProfileId(data.profiles[0]);
                }

                if ($scope.profiles.length == 0) {
                    $scope.profiles.push(noResultItem);
                }
            });
        }

        $scope.validateCustomField = function (customField) {
            var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) || customField.Required == false;
            return verif;
        }

        $scope.isValidIndividual = function (individualSelected) {

          for (var i = 0; i < individualSelected.CustomFields.length; i++) {
                if (!$scope.validateCustomField(individualSelected.CustomFields[i])) {
                    $scope.individualIdsInError.push(individualSelected.IndividualId);
                    $scope.individualsInError = true;
                    return false;
                }
            }
                

            if ($scope.isBirthDateMandatory && (individualSelected.BirthDate == null || individualSelected.BirthDate == "")) {
                $scope.individualIdsInError.push(individualSelected.IndividualId);
                $scope.individualsInError = true;
                return false;
            }

            if ($scope.isPhotoMandatory && individualSelected.HasImage == false) {
                $scope.individualIdsInError.push(individualSelected.IndividualId);
                $scope.individualsInError = true;
                return false;
            }
            if ($scope.pass.Individuals.indexOf(individualSelected) === -1)
                $scope.pass.Individuals.push(individualSelected);
            var index = $scope.individualIdsInError.indexOf(individualSelected.IndividualId);
            if (index > -1)
                $scope.individualIdsInError.splice(index, 1);
            if ($scope.individualIdsInError.length === 0)
                $scope.individualsInError = false;
            return true;
        }

        $scope.isSelectedIndividualValid = function (individualId) {
            var individualSelected = $filter('filter')($scope.individuals, { IndividualId: individualId })[0];
            $(".individualSelect").next().val('');
            if (individualSelected != undefined)
                return $scope.isValidIndividual(individualSelected);
        }

        $scope.checkCustomFields = function () {
            for (var i = 0; i < $scope.pass.CustomFields.length; i++) {
                if (!$scope.validateCustomField($scope.pass.CustomFields[i])) {
                    return false;
                }
            }
            return true;
        }

        $scope.isModifiable = function () {
            return contextService.isModifiable($scope.isUpdate, $scope.pass.Status, $scope.user);
        }

        $scope.isValidable = function () {
            return contextService.isValidable($scope.pass.Status, $scope.user);
        }

        $scope.finalizeAddPass = function () {
            showFormPassSpinner();

            //add times to start and end date validity for pass

            passService.setDate($scope.pass);

            passService.addPass($scope.pass).success(function (data) {
                if (data.Success) {
                    site.successMessage(resources.ValidationSuccess);
                    $location.path('/passList/');
                } else {
                    if (data.ExceptionOccured) {
                        site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                    }
                    else {
                        site.errorMessage(resourcesMessages.CreatePassFail, data.Exception);
                    }
                }
                hideFormPassSpinner();
            });
        };

        $scope.finalizeModifyPass = function () {
            showFormPassSpinner();

            //add times to start and end date validity for pass

           
            passService.setDate($scope.pass);

            passService.modifyIndividualPass($scope.pass).success(function (data) {
                if (data.Success) {
                    site.successMessage(resources.ModificationSuccess);
                    $location.path('/passList/');
                } else {
                   
                    if (data.ExceptionOccured) {
                        site.errorMessage(resourcesMessages.ExceptionDuringModification, null);
                    }
                    else {
                        site.errorMessage(resourcesMessages.CreatePassFail, data.Exception);
                    }
                }
                hideFormPassSpinner();
            });
        };

        /**************** Actions ******************/
        $scope.affecter = function (form) {
            $scope.loading = true;
            if (form.$valid && !$scope.individualsInError && $scope.checkCustomFields()) {
                
                if ($scope.hasPermission(right.Pass_CanViewBlackList)) {
                    passService.IsBlacklisted($scope.pass.IndividualIds).success(function (data) {
                        if (data.isBlacklisted) {
                            var modalWarning = $uibModal.open({
                                templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                controller: 'BlacklistWarningController',
                                resolve: {
                                    fromGeneralPage: false,
                                    fromAssignmentForm: false
                                }
                            });
                            modalWarning.result.then(function (result) {
                                if (result) {
                                    $scope.finalizeAddPass();
                                }
                            });
                        } else {
                            $scope.finalizeAddPass();
                        }
                    });

                }
                else {
                    $scope.finalizeAddPass();
                }
            } 
            $scope.loading = false;
        };

        $scope.cancel = function () {
            var ok;
            jConfirm($scope.resourcesMessages.CancelPassConfirm, $scope.resources.Comment, function (ok) {
                if (ok) {
                    showFormPassSpinner();
                    passService.cancelPass([$scope.pass.PassId], $scope.pass.Comment).success(function (data) {
                        if (data.Success) {
                            site.successMessage(resources.ValidationSuccess);
                            $location.path('/passList/');
                        }
                        hideFormPassSpinner();
                    });
                    $scope.$apply();
                }
            });
        };


        $scope.modify = function (form) {
            if (form.$valid && !$scope.individualsInError && $scope.checkCustomFields()) {

                if ($scope.hasPermission(right.Pass_CanViewBlackList)) {
                    passService.IsBlacklisted($scope.pass.IndividualIds).success(function (data) {
                        if (data.isBlacklisted) {
                            var modalWarning = $uibModal.open({
                                templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                controller: 'BlacklistWarningController',
                                resolve: {
                                    fromGeneralPage: false,
                                    fromAssignmentForm: false
                                }
                            });
                            modalWarning.result.then(function (result) {
                                if (result) {
                                    $scope.finalizeModifyPass();
                                }
                            });
                        } else {
                            $scope.finalizeModifyPass();
                        }
                    });
                }
                else {
                    $scope.finalizeModifyPass();
                }
            }

        };

        $scope.getRichStatus = function () {
            passService.getRichStatusForPass($scope.pass.PassId).success(function (data) {
                $scope.pass.Status = data.status;
                hideFormPassSpinner();
            });
        };




        $scope.showPassHistory = function (passId) {
            passService.getActionsHistory(passId).success(function (data) {
                $scope.actions = data;
                $(".widget-side").show("slide", { "direction": "left" });
            });
        };

        $scope.bindPass = function (data) {
            if (data != "") {
                if ($scope.isUpdate) {

                    //break datetime into two parts, date and time
                    $scope.pass = data;

                    passService.formatPassValidityStartEndDates($scope.pass, data.ValidityStartDate, data.ValidityEndDate);

                    $scope.getUnitConfiguration(data.CreationUnitId);
                    $scope.getUserUnitsTree($scope.pass.ProviderId);
                    angular.forEach($scope.pass.Individuals, function (val, key) {
                        $scope.isValidIndividual(val);
                    });

                    $scope.getRichStatus();

                    if (site.isIE()) {
                        var startDateTimeHours = moment($scope.pass.DisplayValidityStartTime).format("HH");
                        var startDateTimeMinutes = moment($scope.pass.DisplayValidityStartTime).format("mm");
                        $('[ng-model="pass.DisplayValidityStartTime"]').find(".uib-time.hours input").val(startDateTimeHours);
                        $('[ng-model="pass.DisplayValidityStartTime"]').find(".uib-time.minutes input").val(startDateTimeMinutes);

                        var endDateTimeHours = moment($scope.pass.DisplayValidityEndTime).format("HH");
                        var endDateTimeMinutes = moment($scope.pass.DisplayValidityEndTime).format("mm");
                        $('[ng-model="pass.DisplayValidityEndTime"]').find(".uib-time.hours input").val(endDateTimeHours);
                        $('[ng-model="pass.DisplayValidityEndTime"]').find(".uib-time.minutes input").val(endDateTimeMinutes);
                    }
                } else {
                    $scope.pass.PopulationCode = data.PopulationCode;
                    $scope.pass.ReferenceCodeId = data.ReferenceCodeId;
                    $scope.pass.Comment = data.Comment;
                    hideFormPassSpinner();
                }

            }
        }

        //si en mode création
        if (!$scope.isUpdate) {

        }


        $scope.$watch("pass.PassTypeId", function (passTypeId) {
            if (passTypeId != undefined && passTypeId != 1) {
                $location.path($filter('filter')($scope.passTypes, { PassTypeId: passTypeId })[0].Url);
            }
        });

        $scope.$watchCollection("pass.IndividualIds", function (newIds, oldIds) {
            var deleted = oldIds.filter(function (item) {
                return newIds.indexOf(item) === -1;
            });
            angular.forEach(deleted, function (value, key) {
                var index = $scope.individualIdsInError.indexOf(value);
                if (index !== -1) {
                    $scope.individualIdsInError.splice(index, 1);
                    if ($scope.individualIdsInError.length === 0) {
                        $scope.individualsInError = false;
                    }
                }
            });
        });


        /**************** Modal individual ******************/

        $scope.modalIndividual = function (individualId) {
            $scope.modalIndividualId = individualId;

            var modalInstance = $uibModal.open({
                templateUrl: '/Scripts/Angular/Individual/Views/IndividualForm.html?ver=' + $scope.softwareVersion,
                controller: 'individualFormController',
                size: "lg",
                backdrop: 'static',
                resolve: {
                    individualId: function () {
                        return $scope.modalIndividualId;
                    },
                    provider: function () {
                        return $scope.tempProvider;
                    }
                }
            });

            modalInstance.result.then(function (newIndividual) {
                $scope.updateIndividualInfos(newIndividual);
            });
        };

        $scope.updateIndividualInfos = function (newIndividual) {
            //we have to retrieve the whole updated list, which takes time
            showFormPassSpinner();
            //search by id
            var idList = [...$scope.pass.IndividualIds];
            idList.push(newIndividual.IndividualId);
            $scope.getIndividuals("[BYID]" + idList, newIndividual.ProviderId)
                .then(function (data) {
                    var individual = $scope.individuals.filter(function (ob) { return ob.IndividualId == newIndividual.IndividualId })[0];
                    //check if new individual is missing any info (this updates the individualIdsInError array)
                    $scope.isValidIndividual(individual);

                    if (!$scope.pass.IndividualIds.includes(individual.IndividualId)) {
                        $scope.pass.IndividualIds.push(individual.IndividualId);
                    }
                    //temporarily empty both arrays (individualIdsInError is used to paint in red those missing key info)
                    var temp = $scope.pass.IndividualIds;
                    $scope.pass.IndividualIds = [];
                    var tempError = $scope.individualIdsInError;
                    $scope.individualIdsInError = [];
                    setTimeout(function () {
                        //restore arrays, hide spinner
                        $scope.pass.IndividualIds = temp;
                        $scope.individualIdsInError = tempError;

                        hideFormPassSpinner();
                    }, 10);

                });
        };


        if ($scope.isUpdate) {
            showFormPassSpinner();
            passService.getPass($routeParams.passId).success($scope.bindPass);
        } else {
            if ($scope.hasPermission(right.UserLevelExclusiveRight)) {
                $scope.pass.ProviderId = $scope.user.ProviderId;
                $scope.pass.ProviderName = $scope.user.ProviderName;
                $scope.getUserUnitsTree($scope.pass.ProviderId);
            }
            passService.getCustomFields("individual").success(function (data) {
                $scope.pass.CustomFields = data.PassFields;
            });
        }

    }]);

angular.module('accreditationApp')
    .controller('passListController', ['$scope', '$rootScope', '$route', '$routeParams', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'passService', 'providerService', 'individualService', 'vehicleService', 'assignmentService', '$controller'
        , function ($scope, $rootScope, $route, $routeParams, $timeout, $filter, $location, $q, $uibModal, contextService, passService, providerService, individualService, vehicleService, assignmentService, $controller) {

        angular.extend(this, $controller('baseController', { $scope: $scope }));

        contextService.currentPage.index = "passList";
        $rootScope.rootTabulation = "passList";

        assignmentService.resetPageState();
        individualService.resetPageState();
        vehicleService.resetPageState();

        if ($routeParams.openEventModal == "open") {
            contextService.openEventModal = true;
        }

        $scope.passDisplayExtraMenu = false;

        if ($scope.hasPermission(right.Pass_Export) ||
            $scope.hasPermission(right.Pass_Send) ||
            $scope.hasPermission(right.Pass_Import) ||
            $scope.hasPermission(right.Pass_SendEmail) ||
            $scope.hasPermission(right.Pass_SendMessage) ||
            $scope.hasPermission(right.Pass_Delete))
            {
                $scope.passDisplayExtraMenu = true;
            }

        $("title").html(resources.Pass);
        $scope.assignmentView = null;
        $scope.doubleList = "";
        $scope.profiles = contextService.profiles;
        $scope.createPassTypes = contextService.createPassTypes;
        $scope.passTypes = contextService.searchPassTypes;
        $scope.steps = contextService.steps;
        $scope.hasPictureList = [{ value: false, label: $scope.resources.NoPicture }, { value: true, label: $scope.resources.WithPhoto }];
        $scope.printStatusList = [{ value: 0, label: $scope.resources.NotPrinted }, { value: 1, label: $scope.resources.Printed }, { value: 2, label: $scope.resources.ToReprint }];
        $scope.isDailyList = [{ value: false, label: $scope.resources.Unlimited }, { value: true, label: $scope.resources.Daily }];
        passService.getMailStatus().success(function (data) {
            $scope.mailStatus = data;
        });
        passService.getParameters(['WordingStyle', 'ShowMailjet', 'DefaultPassOrganizationid']).success(function (params) {
            $scope.wordingStyle = params.filter(function (p) { return p.Name === 'WordingStyle'; })[0].Value;

            $scope.showMailjet = params.filter(function (p) { return p.Name === 'ShowMailjet'; })[0].Value;
            var mailStatusColorColumn = $scope.gridOptions.columnDefs.filter(function (x) { return x.field === "MailStatusColor"; })[0];
            mailStatusColorColumn.visible = $scope.hasPermission(right.Pass_ShowMailjet) && $scope.showMailjet;

            contextService.defaultPassOrganizationId = params.filter(function (p) { return p.Name === 'DefaultPassOrganizationid'; })[0].Value;
            $scope.getUserUnitsTree();
        });

        passService.getPassZones().success(function (zones) {

            contextService.allPassZones = [];
            contextService.passZones = [];
            contextService.passSurZones = [];

            angular.forEach($filter('filter')(zones), function (value, key) {
                contextService.allPassZones.push(value);
            });

            angular.forEach($filter('filter')(zones, { SurZoning: false, AssignmentTypeName: "Individual" }), function (value, key) {
                contextService.passZones.push(value);
            });

            angular.forEach($filter('filter')(zones, { SurZoning: true, AssignmentTypeName: "Individual" }), function (value, key) {
                contextService.passSurZones.push(value);
            });


        });

        passService.getPassMockups().success(function (passMockups) {
            contextService.passMockups = passMockups.mockups;
            contextService.previewmockup = passMockups.previewmockup;
        });

      

        $scope.currentEvent = contextService.event;
        $scope.passEvent = contextService.passEvent;
        $scope.pageState = passService.pageState;
        $scope.providers = passService.pageState.providers;
        $scope.units = passService.pageState.units;
        $scope.users = passService.pageState.users;
        $scope.populations = passService.pageState.populations;
        $scope.zones = contextService.allZones;
        $scope.viewAssignmentId = 0;
        $scope.user = contextService.user;

        var canSeeHistory = $scope.hasPermission(right.Pass_Historique); 

        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
        $scope.indPagination = {
            search: "",
            page: 1,
            isRequestMoreItems: true
        }
        $scope.proPagination = {};
        angular.copy($scope.indPagination, $scope.proPagination);

        $scope.search = passService.pageState.search;
        if (!$scope.hasPermission(right.Pass_EditProvider)) {
            $scope.search.ProviderId = $scope.user.ProviderId;
        }

        passService.getSearchCustomFields().success(function (data) {
            $scope.search.IndividualCustomFields = data.IndividualFields;
            $scope.search.PassCustomFields = data.PassFields;
            $scope.initialSearchValues = JSON.stringify($scope.search);
        });

        $scope.customFieldsToExport = [0, 1, 2];

        $scope.paginationOptions = {
            pageNumber: 1,
            pageSize: contextService.paginationPageSizes[0],
            totalItems: 0,
            sort: 'Provider',
            sortOrder: 'asc'
        };

        $scope.sortValue = "";
        $scope.sortType = "";
        $scope.unitFirstCgange = true;
        $scope.unitSelectionChanged = function (items) {
            if ($scope.unitFirstCgange == false) {
                $scope.search.UnitIds = [];
            }
            $scope.unitFirstCgange = false;
            angular.forEach(items,
                function (value, key) {
                    $scope.search.UnitIds.push(value.id);
                });
        }

        $scope.setValidityDates = function () {
            var date = new Date();
            date.setHours(0, 0);
            //add times to start and end date validity for pass
            if ($scope.search.TempValidityStartDate !== "") {
                if ($scope.search.ValidityStartTime === "")
                    $scope.search.ValidityStartTime = date;

                $scope.search.ValidityStartDate = $scope.search.TempValidityStartDate + " " + $scope.search.ValidityStartTime.toTimeString().substr(0, 5);
            } else {
                $scope.search.ValidityStartDate = $scope.search.TempValidityStartDate;
            }
            if ($scope.search.TempValidityEndDate !== "") {
                if ($scope.search.ValidityEndTime === "")
                    $scope.search.ValidityEndTime = date;

                $scope.search.ValidityEndDate = $scope.search.TempValidityEndDate + " " + $scope.search.ValidityEndTime.toTimeString().substr(0, 5);
            } else {
                $scope.search.ValidityEndDate = $scope.search.TempValidityEndDate;
            }
        };

        $scope.getPage = function (sForm) {
            $scope.loading = true;

            $scope.setValidityDates();
            passService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $scope.search.Status = data.statusList;
                $scope.loading = false;
            });
        };

        $scope.resetSearchFilters = function () {
            passService.resetPageState();
            $scope.search = passService.pageState.search;
        };

        $scope.getPageAfterPrinting = function (sForm) {
            $("#jqcontainer").Spinner("show");

            $scope.setValidityDates();
            passService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $("#jqcontainer").Spinner("hide");
                $scope.loading = false;
            });
        };

        $scope.selectRow = function (row) {
            $scope.gridApi.selection.selectRow(row.entity);
        };

        $scope.selectAllRow = function () {
            $scope.gridApi.selection.selectAllRows();
        };

        $scope.expandRow = function (row) {
            $("#pdf").remove();
            var rows = $scope.gridApi.expandable.getExpandedRows();
            for (var rowKey in rows) {
                $scope.gridApi.expandable.collapseRow(rows[rowKey]);
            }
            if (row != rows[rowKey]) {
                $scope.gridApi.expandable.expandRow(row);
                $scope.resize(483);
            } else {
                $scope.resize(0);
            }
        };

        $scope.sendCustomMail = function () {

            var ids = $scope.getGridIds();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOnePassSelected, resources.Warning);
                return;
            }

            var modalSendCustomMail = $uibModal.open({
                templateUrl: '/Scripts/Angular/Shared/Views/SendCustomMailForm.html',
                controller: 'sendCustomMailController',
                backdrop: 'static',
                resolve: {
                    ids: function () {
                        return $scope.getGridIds();
                    },
                    type: function () {
                        return "pass";
                    }
                }
            });

            modalSendCustomMail.result.then(function (data) {
                if (data.Success) {
                    site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                } else {
                    site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                }
            });

        };


        $scope.sendMessage = function () {

            var ids = $scope.getGridIds();
            if (ids == "") {
                jAlert(resourcesMessages.AtLeastOnePassSelected, resources.Warning);
            } else {
                var modalPrint = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/MessageForm.html',
                    controller: 'messageFormController',
                    resolve: {
                        ids: function () {
                            return $scope.getGridIds();
                        },
                        type: function () {
                            return "pass";
                        },

                    }
                });
                modalPrint.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                    } else {
                        site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                    }
                });
            }
        };

        $scope.canModify = function () {
            return $scope.hasPermission(right.Pass_ModifyIndividualPass)
                || $scope.hasPermission(right.Pass_ModifyVehiclePass)
                || $scope.hasPermission(right.Pass_ModifyGuestPass);
        };

        $scope.viewSrc = '/Scripts/Angular/Pass/Views/PassView.html?ver=' + $scope.softwareVersion;
        $scope.gridOptions = {
            paginationPageSizes: contextService.paginationPageSizes,
            paginationPageSize: contextService.paginationPageSizes[0],
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,
            rowTemplate: "",

            enableExpandableRowHeader: false,
            expandableRowTemplate: "<div ng-include='grid.appScope.viewSrc'></div>",
            expandableRowHeight: 483,
            expandableRowScope: {
                subGridVariable: 'subGridScopeVariable'
            },

            rowHeight: 50,
            columnDefs: [
                { field: 'PassId', displayName: "PassId", visible: false, enableSorting: false, enableColumnMenu: false },

                {
                    field: 'Status', width: 40, enableColumnMenu: false, displayName: "",
                    cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\" popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'assignmentStatusPopoverTemplate.html\'" popover-trigger="mouseenter">' +
                        '<div ng-class=\"{\'blacklist\': row.entity.IsBlacklisted && ' + $scope.hasPermission(right.Blacklist_IsBlackListed) + '}\" class="blacklist-assignment">' +
                        '<span class="ext-circle {{row.entity.Status}}"><span  class="badge circle {{row.entity.Status}}" title="{{row.entity.Status}}">&nbsp;</span></span></div>' +
                        '</div>'
                },
                {
                    field: 'PassTypeName', width: 50, displayName: "", enableSorting: true, enableColumnMenu: false, cellTemplate:
                        '<div class=\"ui-grid-cell-contents ng-binding ng-scope\" ng-click="grid.appScope.expandRow(row.entity)">' +
                        '<div ng-if="row.entity.PassTypeName == \'Individual\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><img  ng-if="row.entity.HasImage && ' + $scope.hasPermission(right.Pass_CanSeeIndividualPicture) + '" class="img-grid hasQtip qtipImg" ng-src="/Content/images/individual/{{row.entity.ImageName}}?width=35&height=35&mode=crop" alt="" ><i ng-if="!row.entity.HasImage || ' + $scope.hasPermission(right.Pass_CanSeeIndividualPicture) + ' === false" class="fa fa-user"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.PassTypeName == \'Vehicle\'">' +
                        '<div class="thumbnail thumbnail-default pointer" ng-if="row.entity.VehicleTypeName == \'Automobile\'"><i class="fa fa-car"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'HeavyVehicle\'"><i class="fa fa-bus"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'Motorcycle\'"><i class="fa fa-motorcycle"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.PassTypeName == \'Guest\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><i class="fa fa-user-plus"></i></div>' +
                        '</div>' +
                        '<div ng-if="row.entity.PassTypeName == \'Anonymous\'">' +
                        '<div class="thumbnail thumbnail-default pointer"><img  ng-if="row.entity.HasImage" class="img-grid hasQtip qtipImg" ng-src="/Content/images/assignment/{{row.entity.ImageName}}?width=35&height=35&mode=crop" alt="" ><i ng-if="!row.entity.HasImage" class="fa fa-user"></i></div>' +
                        '</div>' +
                        '</div>'
                },
                {
                    field: 'Name', minWidth: 100, displayName: $scope.resources.Name, enableColumnMenu: false,
                    cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="individual-cell pointer" ng-click="grid.appScope.expandRow(row.entity)">' +
                        '<button ng-show="hasPermission(right.Pass_CheckDoubles) && row.entity.HasDouble" class="btn btn-unstyled text-danger"><i ng-mouseover="grid.appScope.getDoubles(row.entity.AssignmentId)" popover-popup-delay="300" popover-trigger="mouseenter" uib-popover-template="\'popoverDoubleTemplate.html\'" popover-append-to-body="true" popover-title="{{grid.appScope.resources.DoubleDetected}}" class="fa fa-warning"></i></button>&nbsp;&nbsp;' +
                        '<span  class="individual-lastname">{{row.entity.LastName}} </span><span class="individual-firstname">{{row.entity.FirstName}}</span>' +
                        '<strong ng-show="row.entity.AssignmentTypeName == \'Vehicle\' && row.entity.BarCode != \'\'"> - n° {{row.entity.BarCode}}</strong></div></div>'
                },
                { field: 'Provider', width: 100, enableColumnMenu: false, visible: $scope.hasPermission(right.DisplayListFieldsFullView), displayName: $scope.resources.Provider },
                { field: 'ProfileName', enableColumnMenu: false, displayName: $scope.resources.Profile },
                { field: 'Zoning', width: 80, enableColumnMenu: false, displayName: $scope.resources.Zones, cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="individual-cell" ng-include="\'zoningLine.html\'"></div></div>' },
                { field: 'ValidityStartDate', minWidth: 130, enableColumnMenu: false, displayName: $scope.resources.ValidityStartDate, cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scopse"><span>{{grid.appScope.formatDate(row.entity.ValidityStartDate)}}</span></div>' },
                { field: 'ValidityEndDate', minWidth: 130, enableColumnMenu: false, displayName: $scope.resources.ValidityEndDate, cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scopse">{{grid.appScope.formatDate(row.entity.ValidityEndDate)}}</span></div>' },
                { field: 'CreationDate', visible: false, enableColumnMenu: false, displayName: $scope.resources.CreationDate, cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scopse"><span>{{grid.appScope.dateFormatter(row.entity.CreationDate)}}</span></div>' },
                { field: 'CreationUnitName', visible: false, enableColumnMenu: false, displayName: $scope.resources.Unit },
               
                {
                    field: 'PrintStatus', width: 80, visible: $scope.hasPermission(right.DisplayListFieldsFullView), enableColumnMenu: false, displayName: $scope.resources.Generated, cellTemplate:
                        '<div class="ui-grid-cell-contents text-center">' +
                        '<div  popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'printPopoverTemplate.html\'" popover-trigger="mouseenter" >' +
                        '<i ng-class="{\'text-success\': row.entity.PrintStatus == 1, \'text-danger\': row.entity.PrintStatus == 2}" class="fa fa-{{row.entity.SharingMode}} fa-lg"></i>' +
                        '</div></div>'
                },
                {
                    field: 'MailStatusColor', width: 80, enableColumnMenu: false, displayName: $scope.resources.Email, cellTemplate:
                        '<div class=\"ui-grid-cell-contents text-center ng-binding ng-scope\"><div class="square" popover-append-to-body="true" popover-popup-delay="200" uib-popover-template="\'mailStatusPopoverTemplate.html\'" popover-trigger="mouseenter" style="background-color: {{row.entity.MailStatusColor}}">&nbsp;</div></div>'
                },
                {
                    field: 'Action', width: 116, enableColumnMenu: false, displayName: "", pinnedRight: false, cellTemplate:
                        '<div class="ui-grid-cell-contents ng-binding ng-scope">' +
                            '<a ' +
                                'ng-if="' + $scope.canModify() +'|| row.entity.Status != \'Validated\'" ' +
                                'ng-hide="row.entity.PassTypeName == \'Anonymous\'"'+
                                'class="btn btn-primary btn-circle" ' +
                                'ng-href="#/create{{row.entity.PassTypeName}}Pass/{{row.entity.PassId}}" title="{{grid.appScope.resources.Modify}}">' +
                                '<i class="fa fa-pencil"></i>' +
                            '</a>' +
                            '<button ' +
                            'ng-if="' + canSeeHistory + '"' +
                                'class="btn btn-primary btn-circle" ' +
                                'ng-click="grid.appScope.showActionsHistory(row.entity.PassId)" ' +
                                'title="{{grid.appScope.resources.History}}">' +
                                '<i class="fa fa-history"></i>' +
                            '</button>' +
                        '</div>'
                }
            ],

            expendAssignment: function () {

            },

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                    if (sortColumns.length != 0) {
                        $scope.paginationOptions.sort = sortColumns[0].name;
                        $scope.paginationOptions.sortOrder = sortColumns[0].sort.direction;
                        $scope.sortType = '';
                        $scope.sortValue = '';
                    }
                    $scope.getPage();
                });
                $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    $scope.paginationOptions.pageNumber = newPage;
                    $scope.paginationOptions.pageSize = pageSize;
                    $scope.getPage();
                });

                $scope.gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
                    $scope.viewPassId = row.entity.PassId;
                    if (row.entity.PassTypeName == 'Individual') {
                        $scope.viewSrc = '/Scripts/Angular/Pass/Views/PassView.html?ver=' + $scope.softwareVersion;
                    }
                    else if (row.entity.PassTypeName == 'Vehicle') {
                        $scope.viewSrc = '/Scripts/Angular/Pass/Views/VehiclePassView.html?ver=' + $scope.softwareVersion;
                    }
                    else if (row.entity.PassTypeName == 'Guest' || row.entity.AssignmentTypeName == 'Anonymous') {
                        $scope.viewSrc = '/Scripts/Angular/Pass/Views/GuestPassView.html?ver=' + $scope.softwareVersion;
                    }
                });

            }
        };


        $scope.getZonesByIds = function (ids) {
            var zones = [];
            angular.forEach(contextService.zones, function (value) {
                if (ids.indexOf(value.ZoneId)) {
                    zones.push(value);
                }
            })
            return zones;
        }

        $scope.dateFormatter = function (date) {
            return site.dateFormatter(date);
        }


        $scope.formatDate = function (date) {
            return site.formatDate(date);
        },

        $scope.dateIsValid = function (date) {
                return site.dateIsValid(date);
        },

        $scope.context = contextService.context;


        /*************************************
        **************** Getter *************
        ***********************************/


        $scope.getProviders = function (q) {
            if ($scope.providers.length == 0 || q != "") {
                $scope.providers.splice(0, $scope.providers.length);
                $scope.providers.push(loadingItem);
                return providerService.getProviders($scope.proPagination.page, q, contextService.defaultPassOrganizationId)
                    .then(function (data) {
                        $scope.providers.splice(0, $scope.providers.length);
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length == 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            }
        };

        $scope.getUsers = function (q) {
            if (q.length >= 3) {
                passService.getUsersByProviderId(search.providerId, q).success(function (data) {
                    $scope.users.splice(0, $scope.users.length);

                    angular.forEach(data.items, function (value, key) {
                        $scope.users.push(value);
                    });
                    if ($scope.users.length == 0) {
                        $scope.users.push(noResultItem);
                    }
                });
            }
        };

        $scope.getUserUnitsTree = function () {
            $scope.units.splice(0, $scope.units.length);
            passService.getUserUnitsTreeForOrganization(contextService.defaultPassOrganizationId).success(function (data) {
                $scope.units.splice(0, $scope.units.length);
                angular.forEach(data, function (value, key) {

                    if ($scope.search.UnitIds.indexOf(value.id)) {
                        value.selected = true;
                    }

                    $scope.units.push(value);
                });
            });
        };

        $scope.getPopulations = function () {
            $scope.populations.splice(0, $scope.populations.length);
            passService.getPopulations().success(function (data) {
                angular.forEach(data.items, function (value, key) {
                    $scope.populations.push(value);
                });
            });
        };


        $scope.getGridIdsForValidation = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                if ($scope.hasPermission(right.PassList_Valid)) {
                    if (value.Status === 'Waiting' || value.Status === 'isWaitForInferior') {
                        ids.push(value.PassId);
                    }
                } else {
                    ids.push(value.PassId);
                }
            });

            return ids;
        };

        $scope.getGridIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.PassId);
            });
            return ids;
        };

        $scope.getNonDeletableRows = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var names = [];
            angular.forEach(objs, function (value, key) {
                if (value.CanBeDeleted === false) {
                    names.push(value.Name + " - " + value.Provider);
                }
            });
            return names;
        };

        $scope.isNotValidPassSelected = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var result = false;
            angular.forEach(objs, function (value, key) {
                if (value.Status != "Validated") {
                    result = true;
                }
            });
            return result;
        };


        $scope.getGridPersonIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.IndividualId);
            });
            return ids;
        };

        $scope.checkSelectedPassStatus = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ret = true;

            angular.forEach(objs, function (value, key) {
                if (value.Status !== "Validated")
                    ret = false;
            });
            return ret;
        };

        $scope.showValidationForm = function () {
            var modalValidation = $uibModal.open({
                templateUrl: '/Scripts/Angular/Pass/Views/ValidationForm.html',
                controller: 'validationPassFormController',
                resolve: {
                    passIds: function () {
                        return $scope.getGridIdsForValidation();
                    }
                }
            });
            modalValidation.result.then(function (data) {
                if (data.Success) {
                    $scope.getPage();
                    site.successMessage(resources.ValidationSuccess);
                } else {
                    site.errorMessage($scope.resourcesMessages.AssignmentValidationError, data.Exception);
                }
            });
        };

        /*************************************
        **************** Action *************
        ***********************************/

        $scope.valid = function () {
            var ids = $scope.getGridIdsForValidation();
            if(ids.length == 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            } else {
                
                if ($scope.hasPermission(right.Blacklist_IsBlackListed)) {
                    passService.IsBlacklisted($scope.getGridPersonIds()).success(function (data) {
                        if (data.isBlacklisted) {
                            var modalWarning = $uibModal.open({
                                templateUrl: '/Scripts/Angular/Assignment/Views/BlacklistWarning.html',
                                controller: 'BlacklistWarningController',
                                resolve: {
                                    fromGeneralPage: true
                                }
                            });
                            modalWarning.result.then(function (result) {
                                if (result) {
                                    $scope.showValidationForm();
                                }
                            });
                        } else {
                            $scope.showValidationForm();
                        }
                    });
                }
                else {
                    $scope.showValidationForm();
                }
            }
        };

        $scope.delete = function () {
            $("#jqcontainer").Spinner("show");
            var ids = $scope.getGridIds();
            if (ids.length === 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            } else {
                var names = $scope.getNonDeletableRows();
                if (names.length > 0) {
                    $uibModal.open({
                        templateUrl: '/Scripts/Angular/Shared/Views/DeleteError.html',
                        controller: 'deleteErrorController',
                        resolve: {
                            names: function () {
                                return names;
                            },
                            type: function () {
                                return 'Pass';
                            }
                        }
                    });
                } else {
                    passService.deletePasses(ids).success(function (data) {
                        if (data.Success === true) {
                            site.successMessage(resourcesMessages.SuppressionSuccess);
                            $scope.getPageAfterPrinting();
                        } else {
                            if (data.ExceptionOccured === true) {
                                site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            } else {
                                site.errorMessage(resourcesMessages.DeletePassErrors, data.Exception);
                            }
                        }
                    });
                }
                $("#jqcontainer").Spinner("hide");
            }
        };

        $scope.cancel = function (ids) {
            var ids = $scope.getGridIds();
            if (ids.length == 0) {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            } else {
                var strSpace = "";
                for (var i = 0; i < 30; i++) { strSpace += "&nbsp;" }
                jPrompt(resources.Comment + strSpace, "", resources.Refuse, function (message) {
                    if (message != null) {
                        passService.cancelPass(ids, message).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resources.ValidationSuccess);
                                $scope.getPage();
                            }
                        });
                        $scope.$apply();
                    }
                });
            }
        };

        $scope.print = function () {
            if ($rootScope.IsPrinting) {
                jAlert(resourcesMessages.IsPrinting, resources.Warning);
            }
            else {
                var ids = $scope.getGridIds();
                if (ids == "") {
                    jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
                } else {
                    if ($scope.isNotValidPassSelected()) {
                        jAlert(resourcesMessages.SelectOnlyValidPass, resources.Warning);
                    }
                    else {
                        var canSend = $scope.hasPermission(right.Pass_SendEmail) ? $scope.CanSendSelectedPassByMail() : false;
                        var modalPrint = $uibModal.open({
                            templateUrl: '/Scripts/Angular/Pass/Views/PrintPassForm.html',
                            controller: 'printPassFormController',
                            resolve: {
                                passIds: function () {
                                    return $scope.getGridIds();
                                },
                                canSendTitleByMail: function () {
                                    return canSend; 
                                }
                            }
                        });
                        modalPrint.result.then(function (data) {
                            if (data.Success) {
                                if (data.data !== null) {
                                    site.successMessage(data.data);
                                } else {
                                    site.successMessage($scope.resourcesMessages.PrintSuccess);
                                }
                                $scope.getPageAfterPrinting();
                            } else {
                                site.errorMessage($scope.resourcesMessages.PrintFailed, data.Exception);
                            }
                        });
                       
                    }
                }
            }


        };

        $scope.sendEmail = function () {
            var check = $scope.checkSelectedPassStatus();
            if (!check) {
                jAlert(resourcesMessages.OnlyValidatedAssignments, resources.Warning);
                return;
            }

            var ids = $scope.getGridIds();
            if (ids == "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            } else {
                var modalPrint = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Pass/Views/MailPassForm.html',
                    controller: 'mailPassFormController',
                    resolve: {
                        passIds: function () {
                            return $scope.getGridIds();
                        }
                    }
                });
                modalPrint.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.SendMailConfirmation);
                    } else {
                        site.errorMessage($scope.resourcesMessages.ErrorSendMail, data.Exception);
                    }
                });
            }
        };

        $scope.exportPassCsv = function ($event) {
            if ($rootScope.isExporting) {
                jAlert(resourcesMessages.IsExporting, resources.Warning);
            } else {
                var modal = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/exportForm.html',
                    controller: 'exportWarningController',
                    resolve: {
                        exportType: function () {
                            return "pass";
                        }
                    }
                });

                modal.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.ExportSuccess);
                        $scope.getPage();
                    } else {
                        site.errorMessage($scope.resourcesMessages.ExportFailed, null);
                    }
                });
            }
        };


        $scope.sendAccessControl = function ($event) {
            var ids = $scope.getGridIds();
            if (ids == "") {
                jAlert(resourcesMessages.AtLeastOneAssignmentSelected, resources.Warning);
            } else {
                var modalAccess = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Assignment/Views/SendAccessControlForm.html',
                    controller: 'sendAccessControlFormController',
                    resolve: {
                        assignmentIds: function () {
                            return $scope.getGridIds();
                        }
                    }
                });
                modalAccess.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.SentToAccessControlSuccess);
                        $scope.getPage();
                    } else {
                        site.errorMessage($scope.resourcesMessages.SentToAccessControlError);
                    }
                });
            }
        };

        var timer;
        $scope.doubles = [];
        $scope.getDoubles = function (assignmentId) {
            timer = $timeout(function () {
                $(".popover-content").Spinner("show");
                passService.GetDoubles(assignmentId).success(function (doubles) {
                    $scope.doubles = doubles;
                    $(".popover-content").Spinner("hide");
                })
            }, 500);
        }

        $scope.hideDoubles = function () {
            $timeout.cancel(timer);
        }

        $scope.showActionsHistory = function (passId) {

            passService.getReprintingReason(passId).success(function (data) {
                $scope.reprintingReason = data;
            });

            passService.getActionsHistory(passId).success(function (data) {
                $scope.actions = data;
                $(".widget-side").show("slide", { "direction": "left" });
            });
        };

        $scope.changeSortValue = function () {
            if ($scope.sortValue != '') {
                if ($scope.sortType == '')
                    $scope.sortType = 'asc';
                $scope.paginationOptions.sort = $scope.sortValue;
                $scope.paginationOptions.sortOrder = $scope.sortType;
                $scope.removeSortFromGrid();
            } else {
                $scope.paginationOptions.sort = 'Provider';
                $scope.paginationOptions.sortOrder = 'asc';
                $scope.sortType = '';
            }
            $scope.getPage();
        }

        $scope.changeSortType = function () {
            if ($scope.sortType == '') {
                $scope.paginationOptions.sort = 'Provider';
                $scope.paginationOptions.sortOrder = 'asc';
                $scope.sortValue = '';

                $scope.getPage();
            } else if ($scope.sortValue != '') {
                $scope.paginationOptions.sort = $scope.sortValue;
                $scope.paginationOptions.sortOrder = $scope.sortType;

                $scope.removeSortFromGrid();
                $scope.getPage();
            }
        }

        $scope.removeSortFromGrid = function () {
            for (var i = 0; i < $scope.gridApi.grid.columns.length; i++) {
                var col = $scope.gridApi.grid.columns[i];
                col.sort.direction = '';
            }
        }

        /*************************************
        **************** Watch *************
        ***********************************/
        $scope.getPage();


        //$scope.$watch("context", function (context) {
        //    if (context != null && context.event != null) {
        //        $scope.search.EventId = context.event.EventId;
        //    }
        //}, true);

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.resize = function (plus) {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height + plus);
                $scope.gridApi.grid.handleWindowResize();
            }
        }

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });



    }]);

angular.module('accreditationApp')
    .controller('passViewController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'passService', 'providerService', '$controller', function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, passService, providerService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.passId = $scope.$parent.grid.appScope.viewPassId;

        $scope.resources = resources;
        $scope.resourcesMessages = resourcesMessages;
        $scope.user = contextService.user;
        $scope.displayZoneImage = site.params.displayZoneImage;

        $scope.pass = {}
        $scope.loading = true;
        $scope.isLoad = false;
        passService.getPass($scope.passId).success(function (pass) {
            $scope.pass = pass;
            $scope.loading = true;
            var params = {
                PassIds: pass.PassId,
                MockupGuid: contextService.previewmockup != null ?  contextService.previewmockup.Guid : "" ,
                IsPreview: true
            }

            $scope.HidePassPrevisualisationPanel();
            $scope.loading = false;

            window.setTimeout(function () {
                $scope.$apply(function () {
                    $scope.pdfUrl = '/Pass/GetPdfs?' + $.param(params);
                });
            }, 100);
        });

        $scope.enterPass = function () {
            passService.enterPass($scope.passId).success(function (data) {
                if (data.Success) {
                    $scope.pass.IsIn = true;
                    $scope.pass.IsOut = false;
                    $scope.pass.LastEntryDate = data.Date;
                }
            });
        };

        $scope.exitPass = function () {
            passService.exitPass($scope.passId).success(function (data) {
                if (data.Success) {
                    $scope.pass.IsIn = false;
                    $scope.pass.IsOut = true;
                    $scope.pass.LastExitDate = data.Date;
                }
            });
        };

        if ($scope.hasPermission(right.Pass_CanViewPrevisualisation)) {
            $scope.loadingMockup = true;
        }
        $scope.errorMockup = false;

        $scope.onLoad = function () {
            $scope.loadingMockup = false;
        };

        $scope.onError = function (error) {
            $scope.errorMockup = true;
        };

        $scope.HidePassPrevisualisationPanel = function () {
            // Hide pass Previsualisation if no right
            if (!$scope.hasPermission(right.Pass_CanViewPrevisualisation)) {
                $(".previsualisationPanelPass").hide();                
            }

        };
    }]);

angular.module('accreditationApp')
    .controller('printPassFormController', ['$rootScope', '$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', '$uibModalInstance', 'contextService', 'passService', 'providerService', 'passIds', '$controller', 'canSendTitleByMail', function ($rootScope, $scope, $filter, $q, $routeParams, $uibModal, $location, $uibModalInstance, contextService, passService, providerService, passIds, $controller, canSendTitleByMail) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.printForm = {
            MockupGuid: null,
            PassIds: passIds,
            isFirefox: false,
            ReasonId: null,
            SendTitleByMail: false
        }; 
        $scope.canSendTitleByMail = canSendTitleByMail;
        $scope.SendTitleByMailMessage = passIds.length > 1 ? $scope.resources.SendAssignmentsByMail : $scope.resources.SendAssignmentByMail;
        $scope.mockups = contextService.passMockups;
        $scope.reasons = [];
        if ($scope.mockups.length != 0) {
            $scope.printForm.MockupGuid = $scope.mockups[0].Guid;
        }
        var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        if ($scope.mockups.length == 0) {
            $scope.mockups.push(noResultItem);
        }
        $scope.printForm.ReasonId = 0; //set default value

        $scope.printInError = function (result) {
            site.errorMessage(result.Exception.Message);
            $rootScope.IsPrinting = false;
            $(".modal-content").Spinner("hide");
        }

        $scope.print = function (form) {
            form.$submitted = true;
            if (!form.$valid) return;

            $rootScope.IsPrinting = true;
            $(".modal-content").Spinner("show");

            if ($scope.printForm.SendTitleByMail) {
                passService.SendTitleByMail(jQuery.param($scope.printForm, true))
                    .success(function (result) {
                        $uibModalInstance.close(result);
                        $rootScope.IsPrinting = false;
                        $(".modal-content").Spinner("hide");
                    })
                    .error($scope.printInError(result));
            }
            else {
                passService.GetPdfs(jQuery.param($scope.printForm, true))
                    .success(function (result) {
                            
                        if (result.Success) {
                            var url = result.data;

                            //Print
                            $.get(url).done(function () {
                                printer.print(url);
                            }).fail(function () {
                                if (!window.downloadFile.isFirefox) {
                                    site.errorMessage($scope.resourcesMessages.PrintFailed);
                                }
                            });

                            //Download
                            $.get(url).done(function () {
                                if (!window.downloadFile.isChrome) {
                                    window.open("/File/GetFileByName?name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                else {
                                    window.downloadFile(url);
                                }
                            }).fail(function () {
                                site.errorMessage($scope.resourcesMessages.PrintFailed);
                            });

                            $uibModalInstance.close();
                        }
                        else {
                            site.errorMessage($scope.resourcesMessages.PrintFailed);
                        }
                            
                        $rootScope.IsPrinting = false;
                        $(".modal-content").Spinner("hide");
                    })
                    .error($scope.printInError(result));
            }
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }]);


angular.module('accreditationApp')
    .controller('validationPassFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', '$uibModalInstance', 'contextService', 'passService', 'providerService', 'passIds', '$controller', function ($scope, $filter, $q, $routeParams, $uibModal, $location, $modalInstance, contextService, passService, providerService, passIds, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.form = {
          Comment: null,
          DeliveryPlaceId: null,
          PassIds: passIds
      }
      $scope.deliveryPlaces = contextService.deliveryPlaces;

      $scope.cancel = function () {
          $modalInstance.dismiss('cancel');
      };

      $scope.validate = function () {
          passService.validPass($scope.form).success(function (data) {
            $modalInstance.close(data);
          });
      }
  }]);


angular.module('accreditationApp')
    .controller('vehiclePassFormController', ['$scope', '$filter', '$q', '$routeParams', '$uibModal', '$location', 'contextService', 'assignmentService', 'passService', 'providerService', 'Upload', 'sharedService', '$controller',
        function ($scope, $filter, $q, $routeParams, $uibModal, $location, contextService, assignmentService, passService, providerService, Upload, sharedService, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
      contextService.currentPage.index = "passList";

      var startDate = new Date();
      startDate.setHours(8);
      startDate.setMinutes(00);

      var endDate = new Date();
      endDate.setHours(20);
      endDate.setMinutes(0);

      $scope.pass = {
          CreationUnitId: null,
          ProviderId: null,
          PassTypeId: 2,
          ZoneId: null,
          IndividualId: null,
          VehicleId: null,
          CustomFields: [],
          BarCode: null,
          KeepingOldNumber: false,
          IsDaily: !contextService.event.IsGroup,
          PassengerIds: [],
          ValidityStartDate: "",
          ValidityEndDate: "",

          DisplayValidityStartTime: moment(startDate).format('YYYY-MM-DD HH:mm'),
          DisplayValidityStartDate: null,
          DisplayValidityEndTime: moment(endDate).format('YYYY-MM-DD HH:mm'),
          DisplayValidityEndDate: null,

          Status : ""
      }
      $scope.individualIdsInError = [];
      $scope.passengerIsDriver = false;

      $scope.vehiclesPage = 1;
      $scope.lastVehiclesQuery = "";
      $scope.busyLoadingVehicles = false;

      $scope.busyLoadingIndividuals = true;
      $scope.individualsPage = 1;
      $scope.lastIndividualsQuery = "";

        passService.getDefaultPassOrganizationId().success(function (organizationId) {
            $scope.defaultPassOrganizationId = organizationId;
        });
        
        sharedService.getRgpd().success(function (data) {
            $scope.rgpd = data.data;
        });


      $scope.busyLoadingPassengers = true;
      $scope.passengersPage = 1;
      $scope.lastPassengersQuery = "";

      $scope.passengerDriverIds = [];
      $scope.tempProvider = null;
      $scope.isUpdate = $routeParams.passId ? true : false;
      $scope.passTypes = contextService.createPassTypes;
      $scope.providers = [];
      $scope.zones = [];
      $scope.selectedZone = null;
      $scope.organizationUnitId = [];
      $scope.units = [];
      $scope.individuals = [];
      $scope.passengers = [];
      $scope.vehicles = [];
      $scope.isVehiculeSelectedvalid = false;
      $scope.accreditationInputs = contextService.accreditationInputs;
      $scope.user = contextService.user;
      $scope.uploadFiles = assignmentService.uploadFiles;
      $scope.defaultPassOrganizationId = contextService.defaultPassOrganizationId;

      var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
      var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };
      $scope.size = 40;



      $scope.groupByUnit = function (item) {
          return item.ParentName
      }


      var hideFormPassSpinner = function () {
          $(".form-pass").Spinner("hide");
      };

      var showFormPassSpinner = function () {
          $(".form-pass").Spinner("show");
      };
      /**************** Getters ******************/


      $scope.resetVehicles = function (provider) {
          $scope.vehicles = [];
          $scope.tempProvider = provider;
      };

      $scope.resetIndividuals = function () {
          $scope.individuals = [];
      };

      $scope.getUserUnitsTree = function (providerId) {
          if (providerId != null) {
              if ($scope.units.indexOf(loadingItem) == -1) {
                  $scope.units = [];
                  $scope.units.push(loadingItem);
              }


              assignmentService.GetUnitsTreeByProviderForPassManagement(providerId).success(function (data) {
                  $scope.units = [];
                  //set default unit
                  if (data.length > 0 && $scope.pass.CreationUnitId == null) {
                      $scope.pass.CreationUnitId = data[0].OrganizationUnitId;
                      $scope.pass.ProfileId = null;
                      $scope.pass.ZoneIds = [];
                      $scope.getUnitConfiguration(data[0].OrganizationUnitId);
                  }
                  angular.forEach(data, function (value, key) {
                      $scope.units.push(value);
                  });
                  if ($scope.units.length == 0) {
                      $scope.units.push(noResultItem);
                  }
              });

          }
      }

      $scope.getProviders = function (q) {
          if ($scope.providers.indexOf(loadingItem) == -1) {
              $scope.providers = [];
              $scope.providers.push(loadingItem);
          }
          return providerService.getProviders(1, q, $scope.defaultPassOrganizationId)
              .then(function (data) {
                  $scope.providers = [];
                  angular.forEach(data.data.items, function (value, key) {
                      $scope.providers.push(value);
                  });
              });
      };








      $scope.getIndividuals = function (q) {
          $scope.individuals = [];
          if ($scope.pass.ProviderId != null) {
              $scope.individuals.push(loadingItem);
              $scope.individualsPage = 1;
              return passService.GetAvailableIndividualForPass($scope.pass.ProviderId, $scope.individualsPage, q)
                  .then(function (data) {
                      $scope.individuals = [];
                      $scope.individualsPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.individuals.push(value);
                      });
                      if ($scope.individuals.length == 0) {
                          $scope.individuals.push(noResultItem);
                      }
                  });
          }
      };

      $scope.getNextIndividuals = function (q) {
          if ($scope.pass.ProviderId != null && !$scope.busyLoadingIndividuals) {
              $scope.busyLoadingIndividuals = true;
              if (q !== $scope.lastIndividualsQuery) {
                  $scope.individualsPage = 1;
                  $scope.individuals = [];
              }
              return passService.GetAvailableIndividualForPass($scope.pass.ProviderId, $scope.individualsPage, q)
                  .then(function (data) {
                      $scope.individualsPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.individuals.push(value);
                      });
                      $scope.busyLoadingIndividuals = false;
                  });
          }
      };







      $scope.getPassengers = function (q) {
          $scope.passengers = [];
          if ($scope.pass.ProviderId != null) {
              $scope.passengers.push(loadingItem);
              $scope.passengersPage = 1;
              return passService.GetAvailableIndividualForPass($scope.pass.ProviderId, $scope.passengersPage, q)
                  .then(function (data) {
                      $scope.passengers = [];
                      $scope.passengersPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.passengers.push(value);
                      });
                      if ($scope.passengers.length == 0) {
                          $scope.passengers.push(noResultItem);
                      }
                  });
          }
      };

      $scope.getNextPassengers = function (q) {
          if ($scope.pass.ProviderId != null && !$scope.busyLoadingPassengers) {
              $scope.busyLoadingPassengers = true;
              if (q !== $scope.lastPassengersQuery) {
                  $scope.passengersPage = 1;
                  $scope.passengers = [];
              }
              return passService.GetAvailableIndividualForPass($scope.pass.ProviderId, $scope.passengersPage, q)
                  .then(function (data) {
                      $scope.passengersPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.passengers.push(value);
                      });
                      $scope.busyLoadingPassengers = false;
                  });
          }
      };



      $scope.getVehicles = function (q) {
          $scope.vehicles = [];
          if ($scope.pass.ProviderId != null ) {
              $scope.vehicles.push(loadingItem);
              $scope.vehiclesPage = 1;
              return passService.GetAvailableVehicleForPass($scope.pass.ProviderId, $scope.vehiclesPage, q)
                  .then(function (data) {
                      $scope.vehicles = [];
                      $scope.vehiclesPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.vehicles.push(value);
                      });
                      if ($scope.vehicles.length == 0) {
                          $scope.vehicles.push(noResultItem);
                      }
                  });
          }
      };


      $scope.getNextVehicles = function (q) {
          if ($scope.pass.ProviderId != null && !$scope.busyLoadingVehicles) {
              $scope.busyLoadingVehicles = true;
              if (q !== $scope.lastVehiclesQuery) {
                  $scope.vehiclesPage = 1;
                  $scope.vehicles = [];
              }
              return passService.GetAvailableVehicleForPass($scope.pass.ProviderId, $scope.vehiclesPage, q)
                  .then(function (data) {
                      $scope.vehiclesPage++;
                      angular.forEach(data.data.items, function (value, key) {
                          $scope.vehicles.push(value);
                      });
                      $scope.busyLoadingVehicles = false;
                  });
          }
      };








        $scope.isNullOrEmpty = function(value) {

            if (!value || value == undefined || value == "") {
                return true;
            }
            return false;
        };


        $scope.isValidVehicule = function(vehicleSelected) {
            if ($scope.isNullOrEmpty(vehicleSelected.VehicleTypeName) ||
                $scope.isNullOrEmpty(vehicleSelected.BrandName) ||
                $scope.isNullOrEmpty(vehicleSelected.License) ||
                $scope.isNullOrEmpty(vehicleSelected.Role) ||
                $scope.isNullOrEmpty(vehicleSelected.ProviderName) ||
                $scope.isNullOrEmpty(vehicleSelected.Model)) {
                $scope.isVehiculeSelectedvalid = false;
                return;
            }
            $scope.isVehiculeSelectedvalid = true;
        };

        $scope.isSelectedVehiculeValid = function(vehiculeId) {
            var vehicleSelected = $filter('filter')($scope.vehicles, { VehicleId: vehiculeId })[0];
            return $scope.isValidVehicule(vehicleSelected);
        };

        $scope.isPassengerTheDriver = function(passengerId) {
            if (passengerId === $scope.pass.IndividualId) {
                $scope.passengerIsDriver = true;
                $scope.passengerDriverIds.push(passengerId);
            }
        };

        $scope.isDriverAPassenger = function(driverId) {
            $scope.passengerIsDriver = false;
            $scope.passengerDriverIds = [];
            angular.forEach($scope.pass.PassengerIds, function (value, key) {
                $scope.isPassengerTheDriver(value);
            });
        };

        $scope.selectZone = function(zone) {
            $scope.selectedZone = zone;
        };

        $scope.validateCustomField = function(customField) {
            var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) ||
                customField.Required == false;
            return verif;
        };

      $scope.checkCustomFields = function () {
          for (var i = 0; i < $scope.pass.CustomFields.length; i++) {
              if (!$scope.validateCustomField($scope.pass.CustomFields[i])) {
                  return false;
              }
          }
          return true;
      }



      $scope.isModifiable = function () {
          return contextService.isModifiable($scope.isUpdate, $scope.pass.Status, $scope.user);
      }
     
      $scope.isValidable = function () {
          return contextService.isValidable($scope.pass.Status, $scope.user);
      }

      $scope.getUnitConfiguration = function (creationUnitId, noCustomField) {
          passService.GetUnitConfiguration(creationUnitId, "VehiclePass").success(function (data) {
              $scope.zones = [];
              angular.forEach(data.vehicleZones, function (value, key) {
                  $scope.zones.push(value);
              });
              $scope.selectedZone = $scope.findSelectedZone($scope.pass.ZoneId);
          });
      };

      /**************** Actions ******************/

      $scope.bindPass = function (data) {
          if (data != "") {
              if ($scope.isUpdate) {

                  $scope.pass = data; // set all attributs

                  //break datetime into two parts, date and time
                  $scope.pass = data;

                  passService.formatPassValidityStartEndDates($scope.pass, data.ValidityStartDate, data.ValidityEndDate);

                  $scope.getRichStatus();

              } else {
                  $scope.pass.ZoneId = data.ZoneId;
                  $scope.pass.IndividualId = data.IndividualId;
                  $scope.pass.Individual = data.Individual;
                  $scope.pass.VehicleId = data.VehicleId;
                  $scope.pass.Vehicle = data.Vehicle;
                  $scope.pass.CustomFields = data.CustomFields;
                  $scope.pass.BarCode = data.BarCode;
                  $scope.pass.VehicleNumberGenerationMode = data.VehicleNumberGenerationMode;
                  $scope.pass.KeepingOldNumber = data.KeepingOldNumber;
              }

              $scope.getUnitConfiguration(data.CreationUnitId, true);
              if (data.Individual != null) {
                  $scope.individuals.push(data.Individual);
              }
              if (data.Passengers != null) {
                  angular.forEach(data.Passengers, function(val, key) {
                      $scope.passengers.push(val);
                  });
              }
              $scope.getUserUnitsTree($scope.pass.ProviderId);
              $scope.oldVehicleNumber = data.BarCode;
              //if admin or superadmin > set vehiclegenerationmode
              if (($scope.hasPermission(right.Vehicle_AccessByUserUnit) || $scope.hasPermission(right.Vehicle_AccessToAllUnit)) && $scope.pass.BarCode == null) {
                  $scope.pass.VehicleNumberGenerationMode = "AutoModeReleasingOldNumber";
              }

              if (!$scope.isUpdate) {
                  hideFormPassSpinner();
              }
          }
      }

      $scope.findSelectedZone = function (zoneId) {
          var zone = null;
          $scope.zones.forEach(function (element) {
              if (element.ZoneId == zoneId)
                  zone = element;
          });
          return zone;
      }

      $scope.affecter = function (form) {
          if (form.$valid && $scope.checkCustomFields() && !$scope.passengerIsDriver) {
              showFormPassSpinner();

              passService.setDate($scope.pass);

              passService.addVehiclePass($scope.pass).success(function (data) {
                  if (data.Success) {
                      site.successMessage(resources.ValidationSuccess);
                      $location.path('/passList/');
                  } else {
                      site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                  }
                  hideFormPassSpinner();
              });
          }
      };

      $scope.cancel = function () {
          var ok;
          jConfirm($scope.resourcesMessages.CancelAccreditationConfirm, $scope.resources.Comment, function (ok) {
              if (ok) {
                  showFormPassSpinner();
                  assignmentService.cancelAssignment([$scope.pass.AssignmentId], $scope.pass.Comment).success(function (data) {
                      if (data.Success) {
                          site.successMessage(resources.ValidationSuccess);
                          $location.path('/assignmentList/');
                      }
                      hideFormPassSpinner();
                  });
                  $scope.$apply();
              }
          });
      };

      $scope.modify = function (form) {
      
          if (form.$valid && $scope.checkCustomFields() && !$scope.passengerIsDriver) {
              showFormPassSpinner();

              passService.setDate($scope.pass);
              
              passService.modifyVehiclePass($scope.pass).success(function (data) {
                  if (data.Success) {
                      site.successMessage(resources.ModificationSuccess);
                      $location.path('/passList/');
                  } else {
                      site.errorMessage(resourcesMessages.CreateAssignmentFail, data.Exception);
                  }
                  hideFormPassSpinner();
              });
          }

      };

      $scope.getRichStatus = function () {
          passService.getRichStatusForPass($scope.pass.PassId).success(function (data) {
              $scope.pass.Status = data.status;
              hideFormPassSpinner();
          });
      };



      $scope.showActionsHistory = function (assignmentId) {
          assignmentService.getActionsHistory(assignmentId).success(function (data) {
              $scope.actions = data;
              $(".widget-side").show("slide", { "direction": "left" });
          });
      };

      if (!$scope.isUpdate) {
          $scope.$watch("event", function (event) {
              if (event != null) {
                  $scope.pass.EventId = event.EventId;
              }
          }, true);
      }

      $scope.$watch("pass.PassTypeId", function (passTypeId) {
          if (passTypeId != 2) {
              $location.path($filter('filter')($scope.passTypes, { PassTypeId: passTypeId })[0].Url);
          }
      });

      $scope.$watchCollection("pass.PassengerIds", function (newIds, oldIds) {
          var deleted = oldIds.filter(function (item) {
              return newIds.indexOf(item) === -1;
          });
          angular.forEach(deleted, function (value, key) {
              var index = $scope.passengerDriverIds.indexOf(value);
              if (index !== -1) {
                  $scope.passengerDriverIds.splice(index, 1);
                  if ($scope.passengerDriverIds.length === 0) {
                      $scope.passengerIsDriver = false;
                  }
              }
          });
      });

      /**************** Modal vehicle ******************/

      $scope.modalVehicle = function (vehicleId) {
          $scope.modalVehicleId = vehicleId;
          var modalInstance = $uibModal.open({
              templateUrl: '/Scripts/Angular/Vehicle/Views/VehicleForm.html?ver=' + $scope.softwareVersion,
              controller: 'vehicleFormController',
              size: "lg",
              backdrop: 'static',
              resolve: {
                  vehicleId: function () {
                      return $scope.modalVehicleId;
                  },
                  provider: function () {
                      return $scope.tempProvider;
                  }
              }
          });

          modalInstance.result.then(function (newVehicle) {
              var vehicle = $filter('filter')($scope.vehicles, { VehicleId: newVehicle.VehicleId })[0];
              $scope.isValidVehicule(newVehicle);

              if (vehicle == undefined) {
                  $scope.vehicles.push(newVehicle);
              } else {
                  angular.extend(vehicle, newVehicle);
              }
              $scope.pass.VehicleId = newVehicle.VehicleId;
              $scope.pass.Vehicle = newVehicle;
          });
      };

        /**************** Modal individual ******************/

        $scope.modalIndividual = function (type) {

            $scope.modalIndividualId = null;

            var modalInstance = $uibModal.open({
                templateUrl: '/Scripts/Angular/Individual/Views/IndividualForm.html?ver=' + $scope.softwareVersion,
                controller: 'individualFormController',
                size: "lg",
                backdrop: 'static',
                resolve: {
                    individualId: function () {
                        return $scope.modalIndividualId;
                    },
                    provider: function () {
                        return $scope.tempProvider;
                    }
                }
            });

            modalInstance.result.then(function (newIndividual) {
                if (type === 'driver') {
                    $scope.getIndividuals('')
                        .then(function (data) {
                            $scope.pass.IndividualId = newIndividual.IndividualId;
                        });
                    //update the passenger list to include the newly added person
                    $scope.getPassengers('')
                }
                if (type === 'passenger') {
                    $scope.getPassengers('')
                        .then(function (data) {
                            $scope.pass.PassengerIds.push(newIndividual.IndividualId);
                        });
                    //update the driver list to include the newly added person
                    $scope.getIndividuals('')
                }
            });
        };

      if ($scope.isUpdate) {
          showFormPassSpinner();
          passService.getPass($routeParams.passId).success($scope.bindPass);

      } else {
          $scope.pass.VehicleNumberGenerationMode = "AutoModeReleasingOldNumber";
          if (!($scope.hasPermission(right.Provider_AccessByUserUnit) || $scope.hasPermission(right.Provider_AccessToAllUnit))) {
              $scope.pass.ProviderId = $scope.user.ProviderId;
              $scope.pass.ProviderName = $scope.user.ProviderName;
              $scope.getUserUnitsTree($scope.user.ProviderId);
              $scope.getIndividuals();
              $scope.getVehicles();
          }
          passService.getCustomFields("vehicle").success(function (data) {
              $scope.pass.CustomFields = data.PassFields;
          });
      }
  }]);


angular.module('accreditationApp')
.service('passService', ['$resource', '$http', '$location', 'Upload', 'contextService', function ($resource, $http, $location, Upload, contextService) {

    this.pageStateModel = {
        search: {
            UnitIds: [],
            ZoneIds: [],
            PassTypeId: null,
            ProviderId: null,
            IndividualName: null,
            ProfileId: null,
            Population: null,
            UserId: null,
            ValidationStartDate: null,
            ValidityStartDate: "",
            TempValidityStartDate: "",
            ValidityEndDate: "",
            TempValidityEndDate: "",
            ValidityStartTime: "",
            ValidityEndTime: "",
            HasImage: null,
            IsValid: true,
            IsWaiting: true,
            IsSuperior: true,
            IsInferior: true,
            IsRefused: false,
            IsToDo: true,
            IndividualCustomFields: [],
            AssignmentCustomFields: [],
            OnlyBlacklisted: false,
            Barcode: null,
            Status: {
                Valid: 0,
                Waiting: 0,
                WaitingInferior: 0,
                WaitingSuperior: 0,
                Refused: 0
            }
        },
        showMore: false,
        units: [],
        users: [],
        providers: []
    }

    this.pageState = {};

    this.resetPageState = function () {
        angular.copy(this.pageStateModel, this.pageState);
    };

    this.addPass = function (pass) {
        return $http.post('/Pass/AddIndividualPass', $.param(pass), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.addGuestPass = function (pass) {
        return $http.post('/Pass/AddGuest', $.param(pass), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    }

    this.addVehiclePass = function (pass) {
        return $http.post('/Pass/AddVehiclePass', $.param(pass), { headers: { 'Content-Type': 'application/x-www-form-urlencoded'}});
    }


    this.getCustomFields = function (formType) {
        return $http.post('/Pass/GetPassCustomFields', { formType: formType });
    }

    this.getDefaultPassOrganizationId = function () {
        return $http.post('/Pass/GetDefaultPassOrganizationId');
    }

    this.addAnonymousAssignment = function (assignment) {
        return $http.post('/Assignment/AddAnonymous', $.param(assignment), {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }});
    }

    this.getPass = function (passId) {
        var data = {
            passId: passId
        }
        return $http.post('/Pass/GetPass', data);
    }

    this.enterPass = function (passId) {
        var data = {
            passId: passId,
            actionType: "entered"
        }
        return $http.post('/Pass/EnterExitPass', data);
    }

    this.exitPass = function (passId) {
        var data = {
            passId: passId,
            actionType: "exited"
        }
        return $http.post('/Pass/EnterExitPass', data);
    }

    this.getPassMockups = function () {

        return $http.post('/Pass/GetPassMockups');

    }
    
    this.validPass = function (form) {
        var data = {
            model: form,
        };
        return $http.post('/Pass/Valid', $.param(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    }

    this.cancelPass = function (ids, comment) {
        var data = {
            comment: comment,
            ids: ids
        };
        return $http.post('/Pass/Cancel', $.param(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    }

    this.deletePass = function (ids) {
        var data = {
            ids: ids
        };
        return $http.post('/Pass/Delete', $.param(data) , {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    }

    this.modifyIndividualPass = function (pass, comment) {
        var data = {
            comment: comment,
            individualPassModel: pass,
        };
        return $http.post('/Pass/ModifyIndividualPass', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.modifyVehiclePass = function (pass, comment) {
        var data = {
            comment: comment,
            vehiculePassModel: pass,
        };
        return $http.post('/Pass/ModifyVehiclePass', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.modifyGuestPass = function (pass, comment) {
        var data = {
            comment: comment,
            guestPassModel: pass,
        };
        return $http.post('/Pass/ModifyGuestPass', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.getActionsHistory = function (passId) {
        return $http.post('/Pass/GetActionsByPassId', { passId: passId });
    }

    this.getIndividualsByProviderId = function (pass, page, search) {
        return $http.post('/Pass/GetUnAssignedIndividual', { providerId: pass.ProviderId, page: page, q: search });
    }

    this.GetAvailableVehicleForPass = function (providerId, page, search) {
        return $http.post('/Pass/GetAvailableVehicleForPass', { providerId: providerId, page: page, q: search });
    }

    this.GetAvailableVehicleForVehicle = function (eventId, providerId, page, search) {
        return $http.post('/Assignment/GetAvailableVehicleForVehicle', { eventId: eventId, providerId: providerId, page: page, q: search });
    }

    this.GetAvailableIndividualForPass = function (providerId, page, search) {
        return $http.post('/Pass/GetAvailableIndividualForPass', { providerId: providerId, page: page, q: search });
    }

    this.dataBind = function (grid, search) {
        var options = {
            PageIndex: grid.pageNumber,
            PageSize: grid.pageSize,
            SortColumn: grid.sort,
            SortOrder: grid.sortOrder
        };

        return $http.post('/Pass/DataBind', $.param({ grid: options, Search: search }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    },

    this.getAssignment = function (assignmentId) {
        var data = {
            assignmentId: assignmentId
        }
        return $http.post('/Assignment/GetAssignment', data);
    }

    this.getLastAssignmentByIndividualId = function (eventId, individualId, assignmentTypeId) {
        var data = {
            eventId: eventId,
            individualId: individualId,
            assignmentTypeId: assignmentTypeId
        }
        return $http.post('/Assignment/GetLastAssignmentByIndividualId', data);
    }

    this.getLastAssignmentByVehicleId = function (eventId, vehicleId, assignmentTypeId) {
        var data = {
            eventId: eventId,
            vehicleId: vehicleId,
            assignmentTypeId: assignmentTypeId
        }
        return $http.post('/Assignment/GetLastAssignmentByVehicleId', data);
    }
    

    this.getPassZones = function () {
        return $http.post('/Pass/GetPassZones');
    }

    this.getUserUnits = function (setting) {
        return $http.post('/OrganizationUnit/GetUnitsSelect', setting);
    }

    this.getUserUnitsTree = function (eventId) {
        return $http.post('/OrganizationUnit/getUserUnitsTree', { eventId: eventId });
    }

    this.getUserUnitsTreeForOrganization = function (organizationId) {
        return $http.post('/OrganizationUnit/getUserUnitsTreeForOrganization', { organizationId: organizationId });
    }

    this.GetUnitsTreeByProviderForPassManagement = function (providerId) {
        return $http.post('/OrganizationUnit/GetUnitsTreeByProviderForPassManagement', { providerId: providerId });
    }

    this.getUnitsTreeByProviderId = function (eventId, providerId) {
        return $http.post('/OrganizationUnit/GetUnitsTreeByProviderId', { eventId: eventId, providerId : providerId});
    }

    this.getUsersByProviderId = function (providerId, q) {
        return $http.post('/User/GetUsersByProviderId', { providerId: providerId, q: q });
    }

    this.getFunctionByUnitId = function (unitId) {
        return $http.post('/Function/getFunctionByUnitId', { unitId: unitId });
    }

    this.getZonesByProfileId = function (profileId) {
        return $http.post('/ZoneNew/GetZonesByProfileId', { profileId: profileId });
    }

    this.getFormDefaultValues = function (setting) {
        return $http.post('/Assignment/GetFormDefaultValues', setting);
    }

    this.getRichStatusForPass = function (id) {
        return $http.post('/Pass/GetRichStatusForPass', { id: id });
    }

    this.GetUnitConfiguration = function(unitId, formName){
        return $http.post('/OrganizationUnit/GetUnitConfiguration', { unitId: unitId, formName: formName });
    }

    this.GetDoubles = function (assignmentId) {
        return $http.post('/Assignment/GetDoubles', { assignmentId: assignmentId });
    }

    this.SendAccessControl = function (eventId, assignmentIds) {
        return $http.post('/Assignment/SendAccreditationsToAccessControl', $.param({ eventId: eventId, assignmentIds: assignmentIds }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.uploadFiles = function (customField, files) {
        if (files && files.length) {
            var upload = Upload.upload({ url: '/File/UploadFile', data: { file: files[0] } });
            upload.then(function (file) {
                if (customField.File == null) {
                    customField.File = {};
                }
                customField.File.Name = file.data.Name;
                customField.File.IsNew = true;
                customField.File.Type = file.data.Type;
                customField.File.Url = file.data.Url;
            });
        }
    }

    this.getParameters = function (codes) {
        var data = {
            codes: codes
        };
        return $http.post('/Parameter/GetParametersByCode', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    //check if the picture and nationality are required (depend on database parameter) 
    this.getCustomValidationWithParameter = function () {

        return $http.post('/Individual/GetValidationParameter');
    }

    this.getMailStatus = function() {
        return $http.post('/Mail/GetMailStatus');
    }

    this.SendEmail = function (passIds) {
        var data = {
            passIds: passIds
        };
        return $http.post('/Mail/SendEmailToPass', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.getMailjetParameter = function () {
        return $http.post('/Parameter/GetMailjetParameter');
    }

    this.IsBlacklisted = function (personIds) {
        var data = {
            personIds: personIds
        };
        return $http.post('/Blacklist/IsBlackListed', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    }

    this.getSearchCustomFields = function () {
        return $http.post("/Pass/GetSearchCustomFields");
    };

    this.GetPdfs = function (param) {
        return $http.post("/Pass/GetPdfs?" + param);
    };

    this.SendTitleByMail = function (param) {
        return $http.post("/Pass/SendTitleByMail?" + param);
    };

    this.Export = function (param) {
        return $http.post("/Pass/Export?" + param);
    };
    
    this.getRgpd = function() {
        return $http.get("/Rgpd/GetRgpdSentence");
    };

    
    this.deletePasses = function (passIds) {
        var data = {
            ids: passIds
        };
        return $http.post("/Pass/Delete", $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
    };

    this.getReprintingReason = function (passId) {
        return $http.post('/Pass/GetReprintingReasonByPassId', { passId: passId });
    };

    // affecter pass.ValidityStartDate et pass.ValidityEndDate (format de transport DD/MM/YYYY HH:mm)
    // en fonction des champs de saisis (format en fonction de la culture) 
    // pass.DisplayValidityStartDate, pass.DisplayValidityStartTime
    // DisplayValidityEndTime et pass.DisplayValidityEndDate
    this.setDate = function (pass) {

        var startTime = null;
        if (typeof pass.DisplayValidityStartTime == "object" && pass.DisplayValidityStartTime instanceof Date) {
            startTime = moment(pass.DisplayValidityStartTime).format("HH:mm");
        }
        else {
            if (typeof pass.DisplayValidityStartTime == "string" && pass.DisplayValidityStartTime.length > 11) {
                startTime = pass.DisplayValidityStartTime.substring(11);
            }
            else {
                startTime = pass.DisplayValidityStartTime;
            }

        }

        var endTime = null;
        if (typeof pass.DisplayValidityEndTime == "object" && pass.DisplayValidityEndTime instanceof Date) {
            endTime = moment(pass.DisplayValidityEndTime).format("HH:mm");
        }
        else {
            if (typeof pass.DisplayValidityEndTime == "string" && pass.DisplayValidityEndTime.length > 11) {
                endTime = pass.DisplayValidityEndTime.substring(11);
            }
            else {
                endTime = pass.DisplayValidityEndTime;
            }
        }

        var validityStartDate = pass.DisplayValidityStartDate !== null && startTime !== null ? moment(moment(pass.DisplayValidityStartDate,'L').format('YYYY-MM-DD') + " " + startTime) : null;
        var validityEndDate = pass.DisplayValidityEndDate !== null && endTime !== null ? moment(moment(pass.DisplayValidityEndDate, 'L').format('YYYY-MM-DD') + " " + endTime) : null;

        pass.ValidityStartDate = validityStartDate !== null && !isNaN(validityStartDate) ? validityStartDate.format("DD/MM/YYYY HH:mm") : null;
        pass.ValidityEndDate = validityEndDate !== null && !isNaN(validityEndDate) ? validityEndDate.format("DD/MM/YYYY HH:mm") : null;
    };

    // affecter les champs de saisi (format en fonction de la culture) 
    // DisplayValidityStartDate, DisplayValidityStartTime
    // DisplayValidityEndTime et DisplayValidityEndDate
    // en fonction des champs ValidityStartDate ValidityEndDate (format DD/MM/YYYY HH:mm)
    this.formatPassValidityStartEndDates = function (pass, strStartDate, strEndDate) {

        var StartDate = null;

        if (strStartDate) {
            StartDate = moment(strStartDate, 'DD/MM/YYYY HH:mm');
        }
        else {
            var startTime = null;
            if (typeof pass.ValidityStartTime == "object" && pass.ValidityStartTime instanceof Date) {
                startTime = moment(pass.ValidityStartTime).format("HH:mm");
            }
            else {
                if (typeof pass.ValidityStartTime == "string" && pass.ValidityStartTime.length > 11) {
                    startTime = pass.ValidityStartTime.substring(11);
                }
                else {
                    startTime = pass.ValidityStartTime;
                }
            }
            StartDate = moment(pass.ValidityStartDate + " " + startTime, 'DD/MM/YYYY HH:mm');
        }

        var EndDate = null;

        if (strEndDate) {
            EndDate = moment(strEndDate, 'DD/MM/YYYY HH:mm');
        }
        else {
            var endTime = null;
            if (typeof pass.ValidityEndTime == "object" && pass.ValidityEndTime instanceof Date) {
                endTime = moment(pass.ValidityEndTime).format("HH:mm");
            }
            else {
                if (typeof pass.ValidityEndTime == "string" && pass.ValidityEndTime.length > 11) {
                    endTime = pass.ValidityEndTime.substring(11);
                }
                else {
                    endTime = pass.ValidityEndTime;
                }

            }
            EndDate = moment(pass.ValidityEndDate + " " + endTime, 'DD/MM/YYYY HH:mm');
        }

        pass.DisplayValidityStartDate = isNaN(StartDate) ? null : moment(StartDate).format("L");
        pass.DisplayValidityStartTime = isNaN(StartDate) ? null : StartDate.format("YYYY-MM-DD HH:mm");
        pass.DisplayValidityEndDate = isNaN(EndDate) ? null : moment(EndDate).format("L");
        pass.DisplayValidityEndTime = isNaN(EndDate) ? null : EndDate.format("YYYY-MM-DD HH:mm");
    };

    this.getPassConfiguration = function () {
        return $http.post('/Pass/getPassConfiguration');
    };
}]).run(['passService', function (assignmentService) {
    angular.copy(assignmentService.pageStateModel, assignmentService.pageState);
}]);
angular.module('accreditationApp')
.service('providerService', ['$resource', '$http', function ($resource, $http) {

    this.getProviders = function(page, search, organizationId) {
        var orga = "";
        if (organizationId !== undefined) {
            orga = '?organizationId=' + organizationId;
        }
        return $http.post('/Provider/GetProviders' + orga, { page: page, q: search });
    };

    this.getProvider = function(providerId) {
        return $http.post('/Provider/BindProviderForm', { id: providerId });
    };

    this.getBillingProfiles = function (providerId, eventId) {
        return $http.post("/Provider/GetBillingProfilesByProviderId", { providerId: providerId, eventId: eventId });
    };
}]);
angular.module('accreditationApp')
    .controller('deleteErrorController', ['$scope', '$uibModalInstance', 'names', 'type', '$controller', function ($scope, $uibModalInstance, names, type, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.names = names;
        $scope.type = type;

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
}]);
angular.module('accreditationApp')
    .controller('exportWarningController',
        ['$rootScope', '$scope', '$route', '$routeParams', '$uibModal', '$uibModalInstance', 'contextService', 'assignmentService', 'passService', 'vehicleService', 'individualService', 'exportType', 'sharedService', '$controller',
            function ($rootScope, $scope, $route, $routeParams, $uibModal, $uibModalInstance, contextService, assignmentService, passService, vehicleService, individualService, exportType, sharedService, $controller) {
                angular.extend(this, $controller('baseController', { $scope: $scope }));
                $scope.search = null;
                $scope.ExportType = exportType;


                sharedService.getExport().success(function (data) {
                    $scope.ExportSentence = data.data;
                });

                $scope.Cancel = function () {
                    $uibModalInstance.dismiss('cancel');
                };

                $scope.Export = function () {
                    $(".modal-content").Spinner("show");
                    $rootScope.isExporting = true;

                    if ($scope.ExportType === "assignment") {
                        $scope.search = assignmentService.pageState.search;

                        assignmentService.Export(jQuery.param($scope.search, true))
                            .success(function (url) {
                                if (window.downloadFile.isChrome) {
                                    window.downloadFile(url);
                                } else {
                                    window.open("/File/GetFileByName?Name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                $rootScope.isExporting = false;
                                $(".modal-content").Spinner("hide");
                                $uibModalInstance.dismiss('cancel');
                            });

                    }

                    if ($scope.ExportType === "individual") {
                        $scope.search = individualService.pageState.search;

                        individualService.Export(jQuery.param($scope.search, true))
                            .success(function (url) {
                                if (window.downloadFile.isChrome) {
                                    window.downloadFile(url);
                                } else {
                                    window.open("/File/GetFileByName?Name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                $rootScope.isExporting = false;
                                $(".modal-content").Spinner("hide");
                                $uibModalInstance.dismiss('cancel');
                            });

                    }
                    if ($scope.ExportType === "vehicle") {
                        $scope.search = passService.pageState.search;
                        vehicleService.Export(jQuery.param($scope.search, true))
                            .success(function (url) {
                                if (window.downloadFile.isChrome) {
                                    window.downloadFile(url);
                                } else {
                                    window.open("/File/GetFileByName?Name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                $rootScope.isExporting = false;
                                $(".modal-content").Spinner("hide");
                                $uibModalInstance.dismiss('cancel');
                            });
                    }

                    if ($scope.ExportType === "pass") {
                        $scope.search = passService.pageState.search;
                        passService.Export(jQuery.param($scope.search, true))
                            .success(function (url) {
                                if (window.downloadFile.isChrome) {
                                    window.downloadFile(url);
                                } else {
                                    window.open("/File/GetFileByName?Name=" + url.substring(url.lastIndexOf('/') + 1), '_blank');
                                }
                                $rootScope.isExporting = false;
                                $(".modal-content").Spinner("hide");
                                $uibModalInstance.dismiss('cancel');
                            });
                    }

                };
            }]);


angular.module('accreditationApp')
    .controller('messageFormController', ['$scope', '$uibModalInstance', 'contextService', 'messageService', 'ids', 'type', '$controller', function ($scope, $uibModalInstance, contextService, messageService, ids, type, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.numberAssignments = ids.length;

        $scope.form = {
            subject: null,
            message: null,
            ids: ids,
            type: type
        }

        $scope.validate = function(form) {
            $(".modal-content").Spinner("show");
            messageService.SendMessage(form).success(function(data) {
                $(".modal-content").Spinner("hide");
                $uibModalInstance.close(data);
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .controller('notifyFormController', ['$scope', '$uibModalInstance', 'notifyService', 'assignmentIds', 'eventId', '$controller',
        function ($scope, $uibModalInstance, notifyService, assignmentIds, eventId, $controller) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));

            $scope.contactMethod = "BySms";

            $scope.notify = function (form) {
                $(".modal-content").Spinner("show");
                notifyService.Notify(eventId, assignmentIds, $scope.contactMethod ).success(function (data) {
                    $(".modal-content").Spinner("hide");
                    $uibModalInstance.close(data);
                });
            };

            $scope.cancel = function () {
                $uibModalInstance.dismiss('cancel');
            };
        }]);


angular.module('accreditationApp')
    .controller('reprintErrorController', ['$scope', '$uibModalInstance', 'names', 'type', '$controller', function ($scope, $uibModalInstance, names, type, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        $scope.names = names;
        $scope.type = type;

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
}]);
angular.module('accreditationApp')
    .controller('sendCustomMailController', ['$scope', '$uibModalInstance', 'sendCustomMailService', 'ids', 'type', '$controller', function ($scope, $uibModalInstance, sendCustomMailService, ids, type, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        
        $scope.params = {
            subject: null,
            body: null,
            ids: ids,
            type: type
        };

        $scope.description = sendCustomMailService.getDescription($scope.params.type);

        console.log("description=" + $scope.description);

        $scope.validate = function (form) {
            if (!form.$valid) return;

            $(".modal-content").Spinner("show");
            sendCustomMailService.SendCustomMail($scope.params)
                .success(function (data) {
                    $(".modal-content").Spinner("hide");
                    $uibModalInstance.close(data);
                })
                .error(function () {
                    $(".modal-content").Spinner("hide");
                    $uibModalInstance.close({ Success: false });
                });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    }]);


angular.module('accreditationApp')
    .service('messageService', ['$resource', '$http', '$location', 'Upload', 'contextService', function ($resource, $http, $location, Upload, contextService) {

        this.SendMessage = function (form) {

            return $http.post('/Mail/SendMessage', $.param(form), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        }

    }]);
angular.module('accreditationApp')
    .service('notifyService', ['$http', function ($http) {

        this.Notify = function (eventId, assigmentIds, contactMethod) {
            var data = {
                eventId: eventId,
                itemsIds: assigmentIds,
                contactMethod: contactMethod
            };
            
            return $http.post('/Notify/NotifyBySms', $.param(data),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        }
    }]);
angular.module('accreditationApp')
    .service('sendCustomMailService', [ '$http', function ( $http) {

        this.getDescription = function (type) {
            if (type == "assignment") {
                return resources.CustomMailAssignmentDescription;
            }

            return resources.CustomMailPassDescription;
        };

        this.SendCustomMail = function (form) {

            var params = {};
            var url = "";

            if (form.type == "assignment") {
                params = {
                    subject: form.subject,
                    body: form.body,
                    assignmentIds: form.ids
                };

                url = "/Assignment/SendCustomMail";
            }
            else {
                params = {
                    subject: form.subject,
                    body: form.body,
                    passIds: form.ids
                };

                url = "/Pass/SendCustomMail";
            }

            return $http.post(url,
                $.param(params),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

    }]);
angular.module('accreditationApp')
    .service('sharedService', ['$resource', '$http', '$location', 'Upload', 'contextService', function ($resource, $http, $location, Upload, contextService) {

        this.getExport = function () {
            return $http.get('/PrivatePolicy/GetByCode?code=Export');
        },
            this.getAcceptCookies = function () {
                return $http.get('/PrivatePolicy/GetByCode?code=Cookies');
            },

            this.getRgpd = function () {
                return $http.get('/PrivatePolicy/GetByCode?code=Rgpd');
            },

            this.getCurrentCulture = function () {
                return $http.get('/Parameter/GetCurrentCulture');
            }
    }]);
angular.module('accreditationApp')
.service('unitService', ['$resource', '$http', function ($resource, $http) {

    this.getUserUnits = function (setting) {
        return $http.post('/OrganizationUnit/GetUserUnits', setting);
    }



}]);
angular.module('accreditationApp')
    .controller('importVehicleFormController', ['$scope', '$route', '$timeout', '$filter', '$location', '$q', '$uibModal', 'contextService', 'assignmentService', 'providerService', 'individualService', 'vehicleService', 'Upload', '$timeout', '$controller', function ($scope, $route, $timeout, $filter, $location, $q, $uibModal, contextService, assignmentService, providerService, individualService, vehicleService, Upload, $timeout, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "vehicleList";

        individualService.resetPageState();
        vehicleService.resetPageState();


        // upload later on form submit or something similar
        $scope.submit = function () {
            if ($scope.form.file.$valid && $scope.file) {
                $scope.upload($scope.file);
            }
        };
        $scope.label = null;
        $scope.labelZip = null;
        $scope.uploadSuccess = null;
        $scope.applyModifToIndividual = false;
        $scope.ignoreBlacklisted = false;

        // upload on file select or drop
        $scope.upload = function (file) {
            $(".form-import").Spinner("show");
            $scope.lineNumber = 0;
            $scope.uploadSuccess = false;

            Upload.upload({
                url: '/Vehicle/Import',
                data: { file: file,eventId: contextService.event.EventId, ApplyModifToIndividual: $scope.applyModifToIndividual, IgnoreBlacklisted: $scope.ignoreBlacklisted }
            }).then(function (resp) {
                $(".form-import").Spinner("hide");
                $(".modif-results").Spinner("hide");
                
                if (resp.data.Success) {
                    $scope.uploadSuccess = true;
                    $scope.lineNumber = resp.data.LineNumber;

                } else {
                  
                    $scope.uploadSuccess = false;

                    if (resp.data.ExceptionOccured) {
                        site.errorMessage(resourcesMessages.ExceptionDuringImport, null);
                    }
                    else {
                        if (resp.data.Exceptions.length > 0) {
                            $scope.gridOptions.totalItems = resp.data.Exceptions.length;
                            $scope.gridOptions.data = resp.data.Exceptions;
                        } else {
                            if (resp.data.Modifications.length > 0) {
                                $scope.gridOptions.data.length = 0;
                                $scope.modifOptions.totalItems = resp.data.Modifications.length;
                                $scope.modifOptions.data = resp.data.Modifications;
                                $scope.showModif = true;
                            }
                            if (resp.data.Blacklists.length > 0) {
                                $scope.gridOptions.data.length = 0;
                                $scope.blacklistOptions.totalItems = resp.data.Blacklists.length;
                                $scope.blacklistOptions.data = resp.data.Blacklists;
                                $scope.showModif = false;
                                $scope.showBlacklist = true;
                            }
                        }
                        $scope.resize(0);
                    }
                }
                console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });
        };

        $scope.validateImportWithModifications = function () {
            $scope.applyModifToIndividual = true;
            $(".modif-results").Spinner("show");
            $scope.submit();
        };

        $scope.acceptBlacklisted = function () {
            $scope.ignoreBlacklisted = true;
            if ($scope.modifOptions.data.length > 0) {
                $scope.showBlacklist = false;
                $scope.showModif = true;
            } else {
                $(".modif-results").Spinner("show");
                $scope.submit();
            }
        };
 
        $scope.gridOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: true,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                // { field: 'Row', width: 60, enableColumnMenu: false, displayName: "" },
                { field: 'LineNb', displayName: "Ligne", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorField', displayName: "Champ", enableSorting: true, enableColumnMenu: false },
                { field: 'ErrorType', displayName: "Type d'érreur", enableColumnMenu: false },
                { field: 'ErrorMessage', displayName: "Message", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }
        };

        $scope.modifOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne mise à jour", enableSorting: false, enableColumnMenu: false },

                { field: 'FieldName', enableSorting: false, displayName: "Champ modifié", enableColumnMenu: false },
                { field: 'OldValue', enableSorting: false, displayName: "Ancienne valeur", enableColumnMenu: false },

                { field: 'NewValue', enableSorting: false, displayName: "Nouvelle valeur", enableColumnMenu: false }

            ],
            onRegisterApi: function (gridApi) {
                $scope.modifApi = gridApi;
            }
        };

        $scope.blacklistOptions = {
            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: false,
            enableSelectAll: false,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            multiSelect: false,
            enablePaginationControls: false,

            rowHeight: 50,
            columnDefs: [
                { field: 'Row', enableSorting: false, width: 60, enableColumnMenu: false, displayName: "Ligne" },
                { field: 'IndividualName', displayName: "Personne concernée", enableSorting: false, enableColumnMenu: false },

                { field: 'StartDate', enableSorting: false, displayName: "Date de début", enableColumnMenu: false },
                { field: 'EndDate', enableSorting: false, displayName: "Date de fin", enableColumnMenu: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.blacklistApi = gridApi;
            }
        };

        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('modifApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.$watch('blacklistApi.core.getVisibleRows().length', function () {
            $scope.resize(0);
        });

        $scope.resize = function (plus) {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height + plus);
                $scope.gridApi.grid.handleWindowResize();
            }
            if ($scope.modifApi) {
                if ($scope.modifOptions.totalItems > 0) {
                    $scope.modifApi.core.refresh();
                    var row_height = $scope.modifOptions.rowHeight;
                    var header_height = $scope.modifOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.modifApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.modifApi.grid.handleWindowResize();
                }
            }
            if ($scope.blacklistApi) {
                if ($scope.blacklistOptions.totalItems > 0) {
                    $scope.blacklistApi.core.refresh();
                    var row_height = $scope.blacklistOptions.rowHeight;
                    var header_height = $scope.blacklistOptions.selectionRowHeaderWidth;
                    var height = row_height * $scope.blacklistApi.core.getVisibleRows().length + header_height;
                    $('.grid').height(height + plus);
                    $scope.blacklistApi.grid.handleWindowResize();
                }
            }
        }
    }]);

angular.module('accreditationApp')
    .controller('searchVehicleFormController', ['$scope', '$controller', '$uibModalInstance', 'contextService','vehicleService',
        function ($scope, $controller, $uibModalInstance, contextService, vehicleService) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));

            $scope.searchMode = "";
            $scope.searchOnError = false;
            $scope.years = [];
            $scope.brands = contextService.vehicleBrands;

            $scope.VehicleProperties = {
                BrandName: null,
                Model: null,
                Motorization: null,
                Co2: null,
                Year: new Date().getFullYear(),
                License: null
            }
            $scope.Init = function () {
                for (var i = new Date().getFullYear() + 1; i >= 1899; i--) {
                    $scope.years.push(i - 1);
                }
            };
            $scope.FuelList = [];
            $scope.ModelList = []

            $scope.Init();

            $scope.gridOptions = {
                selectionRowHeaderWidth: 60,
                enableScrollbars: 1,
                enableHorizontalScrollbar: 0,
                enableVerticalScrollbar: 0,
                enableRowSelection: true,
                enableSelectAll: false,
                useExternalPagination: false,
                useExternalSorting: false,
                showGridFooter: false,
                multiSelect: false,
                enablePaginationControls: false,
                rowTemplate: "",
                enableExpandableRowHeader: false,
                expandableRowTemplate: "<div ng-include='grid.appScope.viewSrc'></div>",
                expandableRowScope: {
                    subGridVariable: 'subGridScopeVariable'
                },
                rowHeight: 50,
                columnDefs:
                    [
                        {
                            field: 'BrandName', enableColumnMenu: false, displayName: $scope.resources.VehicleBrand,
                            cellTemplate: ''
                        },
                        {
                            field: 'Model', enableColumnMenu: false, displayName: $scope.resources.VehicleModel,
                            cellTemplate: ''
                        },
                        {
                            field: 'CommercialDesignation', enableColumnMenu: false, displayName: $scope.resources.CommercialDesignation,
                            cellTemplate: ''
                        },
                        {
                            field: 'Motorization', enableColumnMenu: false, displayName: $scope.resources.VehicleMotorization,
                            cellTemplate: ''
                        },
                        {
                            field: 'Year', enableColumnMenu: false, displayName: $scope.resources.VehicleYear,
                            cellTemplate: ''
                        },
                        {
                            field: 'Co2', enableColumnMenu: false, displayName: $scope.resources.CO2,
                            cellTemplate: ''
                        }
                    ]
                , onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {

                        if (sortColumns.length != 0) {
                            $scope.sortType = '';
                            $scope.sortValue = '';
                        }
                        $scope.getPage();
                    });
                    $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                        $scope.paginationOptions.pageNumber = newPage;
                        $scope.paginationOptions.pageSize = pageSize;
                        $scope.getPage();
                    });
                }
            };

            $scope.getFuelList = function () {
                vehicleService.getFuelList().success(function (result) {
                    $scope.FuelList = result.data;
                });
            }

            $scope.getModelList = function () {
                if ($scope.VehicleProperties.BrandName != "" && $scope.VehicleProperties.BrandName != null) {
                    vehicleService.getModelList($scope.VehicleProperties.BrandName).success(function (result) {
                        $scope.ModelList = result.data;
                    });
                }

            }

            $scope.checkVehicleForCO2 = function () {
                if ($scope.VehicleProperties.BrandName === null
                    || $scope.VehicleProperties.BrandName === ""
                    || $scope.VehicleProperties.Model === null
                    || $scope.VehicleProperties.Model === ""
                    || $scope.VehicleProperties.Motorization === null
                    || $scope.VehicleProperties.Motorization === "")
                {
                    $scope.loading = false;
                    return;
                }

                $scope.callVehicleByPropertiesApi();                       
            };

            $scope.callVehicleByPropertiesApi = function () {
                vehicleService.getVehicleByProperties($scope.VehicleProperties)
                    .success(function (result) {
                        $scope.gridOptions.data = result.data;
                    });
                $scope.loading = false;
            };

            $scope.callLicencePlateApi = function () {
                $scope.searchOnError = false;
                vehicleService.GetVehicleByLicencePlate($scope.VehicleProperties.License)
                    .success(function (result) {
                        if (result.Success) {
                            $scope.gridOptions.data = result.data;
                        } 
                        $scope.loading = false;
                    })
                    .error(function () {
                        $scope.loading = false;
                        $scope.searchOnError = true;
                    });
            };

            $scope.refreshGrid = function (showCommercialDesignation) {
                $scope.gridOptions.data = null;

                for (var i = 0; i < $scope.gridOptions.columnDefs.length; i++) {
                    if ($scope.gridOptions.columnDefs[i].field === "CommercialDesignation") {
                        $scope.gridOptions.columnDefs[i].visible = showCommercialDesignation;
                    }
                    $scope.gridOptions.columnDefs[i].width = showCommercialDesignation ? "16%" : "20%";
                }

                $scope.gridApi.grid.refresh();
            }

            $scope.SearchVehicle = function () {
                $scope.gridOptions.data = [];
                $scope.loading = true;
                if ($scope.searchMode === "Immat") {
                    $scope.callLicencePlateApi();
                } else if ($scope.searchMode === "Model") {
                    $scope.checkVehicleForCO2();
                }
            };

            $scope.ShowImmatForm = function () {
                $("#plateBtn").addClass('active');
                $("#specificBtn").removeClass('active');
                $("#PlateNumberForm").show();
                $("#SpecificForm").hide();
                $scope.searchMode = "Immat";
                $scope.refreshGrid(false);
            };

            $scope.$watch("VehicleProperties.License", function (newImmat, oldImmat) {
                var oldImmatLength = oldImmat == null ? 0 : oldImmat.length;
                var immatLength = $scope.VehicleProperties.License == null ? 0 : $scope.VehicleProperties.License.length;
                if (immatLength <= 9 && immatLength > oldImmatLength && (immatLength === 2 || immatLength === 6)) {
                    $scope.VehicleProperties.License += "-";
                }
            });

            $scope.ShowSpecificForm = function () {
                $("#specificBtn").addClass('active');
                $("#plateBtn").removeClass('active');
                $("#PlateNumberForm").hide();
                $("#SpecificForm").show();
                $scope.searchMode = "Model";
                $scope.refreshGrid(true);
            };

            $scope.cancel = function () {
                $uibModalInstance.dismiss('cancel');
            };

            $scope.submit = function () {
                $uibModalInstance.close({ Item: $scope.gridApi.selection.getSelectedRows(), Repositories: $scope.searchMode === "Model" ? $scope.gridOptions.data : [] });
            };

            $scope.getFuelList();
            $scope.getModelList();
        }]);


angular.module('accreditationApp')
    .controller('vehicleFormController', ['$scope', '$filter', '$q', '$location', '$routeParams', '$uibModalInstance', 'contextService', 'vehicleService', 'providerService', 'individualService', 'vehicleId', 'provider', '$controller', '$uibModal',
        function ($scope, $filter, $q, $location, $routeParams, $uibModalInstance, contextService, vehicleService, providerService, individualService, vehicleId, provider, $controller, $uibModal) {
            angular.extend(this, $controller('baseController', { $scope: $scope }));
            if ($uibModalInstance == null) {
                contextService.currentPage.index = "vehicleForm";
            }
            
            $scope.providers = [];
            $scope.individuals = [];
            $scope.types = contextService.vehicleTypes;
            $scope.brands = contextService.vehicleBrands;
            $scope.user = contextService.user;
            $scope.vehicle = {
                VehicleId: 0,
                VehicleTypeId: null,
                VehicleBrandId: null,
                Model: null,
                License: "",
                Role: null,
                ProviderId: null,
                CustomFields: [],
                Creator: '',
                Updater: '',
                Co2: null
            }
            $scope.vehicleRepositories = [];

            if (provider) {
                $scope.provider = provider;
                $scope.vehicle.ProviderId = provider.id;
            }

            if (!($scope.hasPermission(right.Provider_AccessByUserUnit) ||
                $scope.hasPermission(right.Provider_AccessToAllUnit))) { //not admin nor superadmin
                $scope.provider = contextService.provider;
                $scope.vehicle.ProviderId = contextService.provider.id;
            }

            $scope.isUpdate = vehicleId ? true : false;

            if ($scope.isUpdate) {
                $(".form-individual").Spinner("show");
                vehicleService.getVehicle(vehicleId).success(function (success) {
                    var provider = { id: success.data.ProviderId, text: success.data.ProviderName };
                    $scope.provider = provider;
                    $scope.providers.push(provider);
                    $scope.vehicle = success.data;
                    $scope.disableModifyType = $scope.isUpdate && !success.data.CanModifyType;
                    $(".form-individual").Spinner("hide");

                }).error(function (err) {
                    site.errorMessage(resourcesMessages.ErrorOccured, null);
                });
            } else {
                vehicleService.getCustomFields().success(function (data) {
                    $scope.vehicle.CustomFields = data.CustomFields;
                });
            }

            $scope.loading = false;
            var loadingItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
            var noResultItem = { id: '1', IndividualId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

            $scope.size = 40;

            $scope.groupByUnit = function (item) {
                return item.ParentName;
            }
            /**************** Getters ******************/

            $scope.FindVehicle = function () {
                var modal = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Vehicle/Views/SearchVehicleForm.html',
                    controller: 'searchVehicleFormController',
                    windowClass: 'large-modal'
                });
                modal.result.then(function (data) {
                    if (data.Item != null && data.Item.length > 0) {
                        $scope.vehicleRepositories = data.Repositories;
                        $scope.vehicle.Model = data.Item[0].Model;
                        $scope.vehicle.BrandName = data.Item[0].BrandName;
                        $scope.vehicle.Co2 = parseInt(data.Item[0].Co2);
                        if (data.Item[0].License != null) {
                            $scope.vehicle.License = data.Item[0].License;
                        }

                        angular.forEach($scope.brands, function (vehicleBrand) {
                            if (vehicleBrand.Name.toUpperCase() === $scope.vehicle.BrandName.toUpperCase()) {
                                $scope.vehicle.VehicleBrandId = vehicleBrand.VehicleBrandId;
                            }
                        });
                    }
                });
            },

                $scope.getProviders = function (q) {
                    $scope.providers = [];
                    $scope.providers.push(loadingItem);
                    return providerService.getProviders(1, q)
                        .then(function (data) {
                            $scope.providers = [];
                            angular.forEach(data.data.items, function (value, key) {
                                $scope.providers.push(value);
                            });
                            if ($scope.providers.length == 0) {
                                $scope.providers.push(noResultItem);
                            }
                        });
                };

            $scope.validateCustomField = function (customField) {
                var verif = (customField.Required == true && (customField.Values.length > 0 || customField.File != null)) || customField.Required == false;
                return verif;
            }

            $scope.checkCustomFields = function () {
                for (var i = 0; i < $scope.vehicle.CustomFields.length; i++) {
                    if (!$scope.validateCustomField($scope.vehicle.CustomFields[i])) {
                        return false;
                    }
                }
                return true;
            }

            $scope.submit = function (form) {
                $scope.loading = true;
                form.$submitted = true;
                if (form.$valid) {
                    $(".form-vehicle").Spinner("show");

                    if (!$scope.checkCustomFields()) {
                        site.errorMessage(resourcesMessages.VehiculeRequiredFieldsMissing, null);
                        return;
                    }

                    var promises = null;
                    if ($scope.vehicle.VehicleId !== 0) {
                        promises = vehicleService.editVehicle($scope.vehicle);
                    } else {
                        promises = vehicleService.addVehicle($scope.vehicle);
                    }

                    promises.success(function (data) {
                        if (data.Success) {
                            $scope.vehicle.VehicleId = data.Data.VehicleId;
                            $scope.vehicle.BrandName = data.Data.BrandName;
                            if ($uibModalInstance) {
                                $uibModalInstance.close(data.Data);
                            } else {
                                site.successMessage(resources.ValidationSuccess);
                                $location.path('/vehicleList/');
                            }

                        } else {
                            $scope.loading = false;
                            if (data.ExceptionOccured)
                                site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                            else
                                site.errorMessage(resourcesMessages.VehiculeCreationFailed, data.Exception);
                        }
                        $(".form-vehicle").Spinner("hide");
                    });
                } else {
                    $scope.loading = false;
                }
            }

            $scope.cancel = function () {
                if ($uibModalInstance) {
                    $uibModalInstance.dismiss('cancel');
                } else {
                    $location.path('/vehicleList/');
                }
            };

            /**************** Actions ******************/

            if (!$scope.isUpdate) {
                $scope.$watch("event", function (event) {
                    if (event != null) {
                        $scope.vehicle.EventId = event.EventId;
                    }
                }, true);

            }

        }]);


angular.module('accreditationApp')
    .controller('vehicleListController', ['$scope', '$rootScope', '$route', '$filter', '$location', '$uibModal', '$q', 'contextService', 'vehicleService', 'providerService', 'assignmentService', 'individualService', 'passService', '$controller'
        , function ($scope, $rootScope, $filter, $route, $location, $uibModal, $q, contextService, vehicleService, providerService, assignmentService, individualService, passService, $controller) {
        angular.extend(this, $controller('baseController', { $scope: $scope }));
        contextService.currentPage.index = "vehicleList";
        $rootScope.rootTabulation = "vehicleList";
        $scope.pageClass = "in";

        assignmentService.resetPageState();
        individualService.resetPageState();
        passService.resetPageState();

        $scope.pageState = vehicleService.pageState;

        $scope.types = contextService.vehicleTypes;
        $scope.brands = contextService.vehicleBrands;
        $scope.context = contextService.context;
        $scope.user = contextService.user;

        $("title").html(resources.Vehicle);
        var loadingItem = { id: '1', VehicleId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.Loading };
        var noResultItem = { id: '1', VehicleId: 0, ProviderId: 0, IsLoading: true, Message: $scope.resources.NoResult };

        $scope.search = vehicleService.pageState.search;
        $scope.providers = vehicleService.pageState.providers;

        $scope.paginationOptions = {
            pageNumber: 1,
            pageSize: 25,
            totalItems: 0,
            sort: 'VehicleName',
            sortOrder: 'desc'
        };

        $scope.selectRow = function (row) {
            $scope.gridApi.selection.selectRow(row.entity);
        }

        $scope.selectAllRow = function () {
            $scope.gridApi.selection.selectAllRows();
        }

        $scope.gridOptions = {
            paginationPageSizes: contextService.paginationPageSizes,
            paginationPageSize: 50,
            enableSorting: true,

            selectionRowHeaderWidth: 60,
            enableScrollbars: 0,
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 0,
            enableRowSelection: true,
            enableSelectAll: true,
            useExternalPagination: true,
            useExternalSorting: true,
            showGridFooter: false,
            enablePaginationControls: false,
            rowHeight: 50,
            columnDefs: [
                { field: 'VehicleId', displayName: "VehicleId", visible: false, enableSorting: false, enableColumnMenu: false },
                { field: 'IndividualId', width: 30, enableColumnMenu: false, visible: false, displayName: "" },
                {
                    field: 'TypeName', enableColumnMenu: false, visible: true, width: 50, displayName: "Type", cellTemplate:
                        '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'Automobile\'"><i class="fa fa-car"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'HeavyVehicle\'"><i class="fa fa-bus"></i></div><div class="thumbnail thumbnail-default" ng-if="row.entity.VehicleTypeName == \'Motorcycle\'"><i class="fa fa-motorcycle"></i></div></div>'
                },
                {
                    field: 'VehicleName', enableColumnMenu: false, displayName: $scope.resources.Vehicle, cellTemplate:
                        '<div class=\"ui-grid-cell-contents ng-binding ng-scope\"><div class="individual-cell">' +
                        '<span>' +
                        '<span ng-show="row.entity.BrandName == \'\' && row.entity.Model == null">{{grid.appScope.resources.Unknown}}</span>' +
                        '<span ng-show="row.entity.BrandName != \'\' || row.entity.Model != null"><span class="individual-lastname">{{row.entity.BrandName}}</span> {{row.entity.Model}} <small ng-show="row.entity.License != null">({{row.entity.License}})</small></span>' +
                        '</span>' +
                        '</div></div>)'
                },
                { field: 'Role', enableColumnMenu: false, displayName: $scope.resources.Role },
                { field: 'ProviderName', enableColumnMenu: false, visible: $scope.hasPermission(right.Vehicle_DisplayListFieldsFullView), displayName: $scope.resources.Provider },
                { field: 'BrandName', enableColumnMenu: false, visible: false, displayName: $scope.resources.Brand },
                { field: 'Model', enableColumnMenu: false, visible: false, displayName: $scope.resources.Model },
                { field: 'License', enableColumnMenu: false, visible: false, displayName: $scope.resources.Licence, cellTemplate: '<div class=\"ui-grid-cell-contents ng-binding ng-scopse\"><div class="individual-cell" ng-bind-html=\"row.entity.Zoning\"></div></div>' },
                { field: 'Action', width: 76, enableColumnMenu: false, displayName: "", cellTemplate: '<div ng-if="' + $scope.hasPermission(right.Vehicle_Edit) +'"><div class="ui-grid-cell-contents ng-binding ng-scopse"><a class="btn btn-primary btn-circle" href="#createVehicle/{{row.entity.VehicleId}}"><i class="fa fa-pencil"></i></a></div></div>' }
            ],

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {

                    if (sortColumns.length != 0) {
                        $scope.paginationOptions.sort = sortColumns[0].name;
                        $scope.paginationOptions.sortOrder = sortColumns[0].sort.direction;
                    }
                    $scope.getPage();
                });
                $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    $scope.paginationOptions.pageNumber = newPage;
                    $scope.paginationOptions.pageSize = pageSize;
                    $scope.getPage();
                });
            }
        };

        $scope.dateFormatter = function (date) {
            return site.dateFormatter(date);
        }


        /*************************************
        **************** Getters *************
        ***********************************/
        $scope.getPage = function (sForm) {
            $scope.loading = true;
            vehicleService.dataBind($scope.paginationOptions, $scope.search).success(function (data) {
                $scope.gridOptions.totalItems = data.total;
                $scope.gridOptions.data = data.data;
                $scope.loading = false;
            });
        }

        $scope.resetSearchFilters = function () {
            $scope.search = {};
        };


        $scope.resetSearchFilters = function () {
            vehicleService.resetPageState();
            $scope.search = vehicleService.pageState.search;
        };

        $scope.getPage();

        $scope.getProviders = function (q) {
            if ($scope.providers.length == 0 || q != "") {
                $scope.providers.splice(0, $scope.providers.length);
                $scope.providers.push(loadingItem);
                return providerService.getProviders(1, q)
                    .then(function (data) {
                        $scope.providers.splice(0, $scope.providers.length);
                        angular.forEach(data.data.items, function (value, key) {
                            $scope.providers.push(value);
                        });
                        if ($scope.providers.length == 0) {
                            $scope.providers.push(noResultItem);
                        }
                    });
            }
        };

        $scope.getGridIds = function () {
            var objs = $scope.gridApi.selection.getSelectedRows();
            var ids = [];
            angular.forEach(objs, function (value, key) {
                ids.push(value.VehicleId);
            });
            return ids;
        }

        /*************************************
        **************** Actions *************
        ***********************************/

        $scope.remove = function () {
            var ids = $scope.getGridIds();
            if (ids.length == 0) {
                jAlert(resourcesMessages.AtLeastOneVehicleSelected, resources.Warning);
            } else {
                jConfirm($scope.resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                    if (ok) {
                        vehicleService.deleteVehicle(ids).success(function (data) {
                            if (data.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, data.Exception);
                            }
                            $scope.getPage();
                        });
                        $scope.$apply();
                    }
                });
            }
        };

        $scope.download = function () {
          //  var myWindow = window.open("/Vehicle/Export?" + jQuery.param($scope.search, true), "_blank");

            if ($rootScope.isExporting) {
                jAlert(resourcesMessages.IsExporting, resources.Warning);
            } else {
                var modal = $uibModal.open({
                    templateUrl: '/Scripts/Angular/Shared/Views/exportForm.html',
                    controller: 'exportWarningController',
                    resolve: {
                        exportType: function () {
                            return "vehicle";
                        }
                    }
                });

                modal.result.then(function (data) {
                    if (data.Success) {
                        site.successMessage($scope.resourcesMessages.ExportSuccess);
                        $scope.getPage();
                    } else {
                        site.errorMessage($scope.resourcesMessages.ExportFailed, null);
                    }
                });
            }
        };


        /*************************************
        **************** Watch *************
        ***********************************/

        $scope.$watch("showMore", function (showMore) {
        }, true);


        $scope.$watch('gridApi.core.getVisibleRows().length', function () {
            if ($scope.gridApi) {
                $scope.gridApi.core.refresh();
                var row_height = $scope.gridOptions.rowHeight;
                var header_height = $scope.gridOptions.selectionRowHeaderWidth;
                var height = row_height * $scope.gridApi.core.getVisibleRows().length + header_height;
                $('.grid').height(height);
                $scope.gridApi.grid.handleWindowResize();
            }
        });

    }]);

angular.module('accreditationApp')
    .service('vehicleService', ['$resource', '$http', function ($resource, $http) {

        this.pageStateModel = {
            search: {
                VehiculeTypeId: null,
                VehiculeBrandId: null,
                Model: null,
                License: null,
                VehicleName: null,
                ProviderId: null
            },
            showMore: false,
            providers: []
        };

        this.pageState = {};

        this.resetPageState = function () {
            angular.copy(this.pageStateModel, this.pageState);
        };

        this.dataBind = function (grid, search) {
            var options = {
                PageIndex: grid.pageNumber,
                PageSize: grid.pageSize,
                SortColumn: grid.sort,
                SortOrder: grid.sortOrder
            };

            return $http.post('/Vehicle/DataBind',
                $.param({ grid: options, Search: search }),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.addVehicle = function (vehicle) {
            var data = {
                Vehicle: vehicle
            };
            return $http.post('/Vehicle/Add', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.editVehicle = function (vehicle) {
            var data = {
                Vehicle: vehicle
            };
            return $http.post('/Vehicle/Edit', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.deleteVehicle = function (ids) {
            var data = {
                ids: ids
            };
            return $http.post('/Vehicle/Delete', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.getVehicle = function (vehicleId) {
            var data = {
                vehicleId: vehicleId
            };
            return $http.post('/Vehicle/GetVehicle', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };

        this.getCustomFields = function () {
            return $http.post('/Vehicle/GetCustomFields');
        };

        this.Export = function (param) {
            return $http.post("/Vehicle/Export?" + param);
        };

        this.getVehicleByProperties = function (vehicleProperties) {
            var data = {
                vehicleModel: vehicleProperties
            };        
            return $http.post('/Vehicle/GetVehicleByProperties', $.param(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
        };
        
        this.GetVehicleByLicencePlate = function (plateLicence) {
            return $http.post("/Vehicle/GetVehicleByLicensePlate?licenceplate=" + plateLicence);
        };

        this.getFuelList = function () {
            return $http.post("/Vehicle/GetFuelList");
        };
        this.getModelList = function (brandName) {
            return $http.post("/Vehicle/GetModelList?brandName=" + brandName);
        };

    }]).run(['vehicleService', function (vehicleService) {
        angular.copy(vehicleService.pageStateModel, vehicleService.pageState);
    }]);
accessControlGraphCrowd = {

    params: {
    },

    init: function (params) {
    },

    draw: function () {
        $("#chart-crowd svg g").remove();

        nv.addGraph(function () {
            accessControlGraphCrowd.chart = nv.models.lineChart()
                .noData("Aucune données");

            accessControlGraphCrowd.chart.xAxis
            .axisLabel('Temps')
            .tickFormat(function (d) {
                var millisec = new Date(d * 1000);
                var date1 = new Date(millisec);
                return d3.time.format('%m/%d/%Y %H:%M')(date1);
            });

            accessControlGraphCrowd.chart.yAxis
            .axisLabel('Accréditations cumulées')
            .tickFormat(d3.format(',f'));

            d3.select('#chart-crowd svg')
            .datum(accessControlGraphCrowd.data())
            .transition().duration(500).call(accessControlGraphCrowd.chart);

            nv.utils.windowResize(accessControlGraphCrowd.chart.update);

            return accessControlGraphPresence.chart;
        });
    },

    data: function () {
        var params = $("#search form").serialize();
        $("#tabs-crowd").Spinner("show");

        $.ajax({
            type: "POST",
            dataType: "json",
            data: params,
            el: "#chart",
            url: "AccessControl/DataChartCrowd",
            success: function (result) {
                d3.select("#chart-crowd svg")
                    .datum(result.data)
                    .transition().duration(1200)
                    .call(accessControlGraphCrowd.chart);
                $("#tabs-crowd").Spinner("hide");

            }
        });
    }
}
accessControlGraphPresence = {

    params: {
    },

    init: function (params) {
    },

    draw: function () {
        $("#chart-presence svg g").remove();

        nv.addGraph(function () {
            accessControlGraphPresence.chart = nv.models.multiBarChart()
            .noData("Aucune données");

            accessControlGraphPresence.chart.xAxis
            .axisLabel('Sociétés');
            //.tickFormat(d3.format(',f'));

            accessControlGraphPresence.chart.yAxis
            .axisLabel('Accréditations')
            .tickFormat(d3.format(',.1f'));

            d3.select('#chart-presence svg')
            .datum(accessControlGraphPresence.data())
            .transition().duration(500).call(accessControlGraphPresence.chart);

            nv.utils.windowResize(accessControlGraphPresence.chart.update);

            return accessControlGraphPresence.chart;
        });
    },

    data: function () {
        var params = $("#search form").serialize();
        $("#tabs-presence").Spinner("show");
        $.ajax({
            type: "POST",
            dataType: "json",
            data: params,
            el: "#chart",
            url: "AccessControl/DataChartPresence",
            success: function (result) {
                d3.select("#chart-presence svg")
                    .datum(result.data)
                    .transition().duration(1200)
                    .call(accessControlGraphPresence.chart);
                $("#tabs-presence").Spinner("hide");

            }
        });
    }
}
accessControlIndex = {

    params: {
        titleGrid: "",
        titlePresence: "",
        titleCrowd: ""
    },

    init: function (params) {
        $.extend(this.params, params);
        $(".container-main .container").css("background-color", "#eee");
        $(".container-search").css("background-color", "#fff")
        $(".container-search").css("padding", "20")

        $("#search .submit").click(accessControlIndex.switchTabs);
        $("#search .export").click(accessControlIndex.exporte);
        $("#js-btn-loadreading").click(accessControlIndex.importEventDataReporting);

        $(".buttonReload").qtip({
            content: {
                text: "Re-synchroniser l'événement avec le contrôle d'accès."
            },
            style: {
                classes: 'qtip-bootstrap '
            }
        });
        $("#tabs").tabs({
            show: { effect: "drop", duration: 300, direction: "right" },
            hide: { effect: "drop", duration: 200, direction: "right"},
            activate: function (event, ui) {
                accessControlIndex.switchTabs();
            }
        }).addClass("ui-tabs-vertical ui-helper-clearfix");


        $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
    },

    exporte: function () {
        $("#search form").submit();
    },

    showReadingsHistory: function(individualId) {
        $.ajax(
           {
               type: "POST",
               url: "AccessControl/GetReadingsHistory",
               traditional: true,
               async: true,
               data: { individualId: individualId },
               dataType: "json",
               success: function (result) {
                   var tr = '';
                   for (i = 0; i < result.readings.length; i++) {
                       y = result.readings[i];
                       tr += '<tr>';
                       tr += '<td>' + y.ReadingDate + '</td>';
                       tr += '<td>' + y.IsEntry + '</td>';
                       tr += '<td>' + y.Gate + '</td>';
                       tr += '<td>' + y.CheckPoint + '</td>';
                       tr += '<td>' + y.IsValid + '</td>';
                       tr += '<td>' + y.Status + '</td>';
                       tr += '</tr>';

                   }
                   var htmlTable = "<table><thead><tr><th>Date de lecture</th><th>E/S</th><th>Porte</th><th>Point d'acces</th><th>Validée</th><th>Status</th></tr></thead>";
                   htmlTable += tr + "</table>";
                   jAlert(htmlTable, "Historique : " + result.individualFullName);
               },
               error: function () {

               }
           });
    },

    importEventDataReporting: function () {
        var ok;
        var eventId = $("#Search_EventId").val();
        var eventName = $("#Search_EventId option:selected").html();
        jConfirm("La re-synchronisation peut prendre quelque minutes, êtes vous sur de vouloir re-synchroniser l'événement <strong>" + eventName + "</strong> ?", 'Attention', function (ok) {
            if (ok) {
                $.ajax(
                  {
                      type: "POST",
                      url: "AccessControl/ImportEventDataReporting",
                      traditional: true,
                      async: true,
                      data: { eventId: eventId },
                      dataType: "json",
                      success: function (result) {
                          if (result.success) {
                              site.successMessage("Événement '" + eventName + "' synchronisé avec le controle d'accès.");
                          }
                      },
                      beforeSend: function () {
                          $("#js-btn-loadreading .fa").addClass("fa-spin");
                      },
                      complete: function () {
                          $("#js-btn-loadreading .fa").removeClass("fa-spin");
                      },
                  });
            }
        });
        return false;
    },

    gridComplete: function () {


    },

    gridReload: function () {
        var params = $("#search form").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "AccessControl/DataBind?" + params,
            page: 1
        }).trigger("reloadGrid");
    },

    switchTabs: function () {
        var active = $("#tabs").tabs("option", "active");

        accessControlIndex.gridReload();
        accessControlGraphPresence.draw();
        accessControlGraphCrowd.draw();

    }


}
var accessLog = {

    rowTemplate: undefined,
    rowEditTemplate: undefined,

    params: {},

    init: function (params) {
        $.extend(this.params, params);
        $("#searchForm").submit(accessLog.gridReload);
        $(".export").click(accessLog.exportCsv);
    },

    exportCsv: function () {
        var data = jQuery("#searchForm").serialize();
        var myWindow = window.open("/AccessLog/Export?" + data, "_blank");
        return false;
    },
    gridReload: function () {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "AccessLog/DataBind"
                + "?" + data,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    gridComplete: function () {
        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    }


}
var blacklist = {

    params: {
        validFromDateToDate: ""
    },

    init: function (params) {
        $.extend(this.params, params);
        $("#searchForm").submit(blacklist.gridReload);

        $("#addForm").submit(blacklist.add);
        $("#editForm").submit(blacklist.edit);
        $("#actions .deleteAll").click(blacklist.del);
        $("#actions .submit").click(blacklist.preRempAdd);

        

    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });

        $.ajax({
            type: "POST",
            url: 'Blacklist/BindBlacklistEditForm',
            dataType: "json",
            el: "#LimitedEditForm",
            data: { id: id },
            traditional: true,
            success: function (result) {
                if (result.Success) {
                    $("#ItemEdit_ItemId").val(result.data.ItemId);
                    $("#ItemEdit_FirstName").val(result.data.FirstName);
                    $("#ItemEdit_LastName").val(result.data.LastName);
                    $("#ItemEdit_StartDate").val(result.data.StartDate);
                    $("#ItemEdit_EndDate").val(result.data.EndDate);
                    $("#ItemEdit_Comment").val(result.data.Comment);
                    $("label[for='ItemEdit_Creator']").text(result.data.Creator);
                    $("label[for='ItemEdit_Updater']").text(result.data.Updater);
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
        });
        return false;
    },

    preRempAdd: function () {
        site.showForm('#addForm', { container: ".main-container" });
        $("#addForm")[0].reset();
    },


    add: function () {
        var form = $(this);
        form.find("#Item_LastName").rules("add", "checkUniciteBlacklist");
        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'Blacklist/Add',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        site.successMessage(resources.ValidationSuccess);
                        jQuery("#JqGrid").trigger("reloadGrid");
                    } 
                    form.find(".cancel").trigger("click");
                }
            });
        }
        return false;
    },

    edit: function () {
        var form = $(this);
        form.find("#ItemEdit_LastName").rules("add", "checkUniciteBlacklist");

        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'Blacklist/Edit',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        site.successMessage(resources.ValidationSuccess);
                        form.find(".cancel").trigger("click");
                        jQuery("#JqGrid").trigger("reloadGrid");
                    }
                }
            });
        }
        return false;

    },


    del: function () {

        var ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (ids == "") {
            jAlert(blacklist.params.messageAtLeastOneBlacklistedSelected, resources.Warning);
        } else {

            var ok;
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s = jQuery("#treegrid").jqGrid('getGridParam');
                $.ajax(
                {
                    type: "POST",
                    url: 'Blacklist/Delete',
                    dataType: "json",
                    data: { ids: ids },
                    traditional: true,
                    el: $("#JqGrid"),
                    success: function (ret) {
                        if (ret.success) {
                            site.successMessage(resourcesMessages.SuppressionSuccess);
                            $("#JqGrid").trigger("reloadGrid");
                        }
                    }
                });
            });
        }
    },

    gridReload: function () {
        var nameMask = jQuery(this).serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Blacklist/DataBind"
                + "?" + nameMask,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var edProv = "";
            if (site.hasPermission(right.Blacklist_Edit)) {
                edProv = "<button class='btn btn-circle btn-primary' onclick='blacklist.preRempEdit(" + cl + ");'><i type='button' class='fa fa-pencil'></i></button>";
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { Act: edProv });
        }


        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    }
}
var customField = {

    rowTemplate: undefined,
    rowEditTemplate: undefined,

    params: {},

    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    $("#search #labelOrganization").html(resources.Organization_stadium);
                    //Ajout / Edition
                    $("#editForm #labelOrganization").html(resources.Organization_stadium);
                    $("#addForm #labelOrganization").html(resources.Organization_stadium);
                }
            }
        });
        $.extend(this.params, params);
        customField.rowTemplate = $("#addForm .table-itemlist").find("tbody tr").last().detach();
        customField.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();

        $("#add #idNumberWarning").hide();
        $("#actions .submit").click(customField.preRempAdd);
        $("#actions .delete").click(customField.del);

        $("#search .submit").click(customField.gridReload);

        $("#add .submit").click(customField.add);
        $("#add .cancel").click(function () {            
            site.hideForm('#addForm', { container: ".main-container" });
        });
        $("#edit .submit").click(customField.edit);
        $("#edit .cancel").click(function () {            
            site.hideForm('#editForm', { container: ".main-container" });
        });

        $("#CustomFieldModel_Type").change(customField.collapseOptionPanel);
        $("#CustomFieldModelEdit_Type").change(customField.collapseOptionPanel);

        $("#CustomFieldModelEdit_OrganizationId").change(function () {
            $("#CustomFieldModelEdit_UnitIds").html("");
            site.initAjaxSelect();
        });

        $("#CustomFieldModel_OrganizationId").change(function () {
            $("#CustomFieldModel_UnitIds").html("");
            site.initAjaxSelect();
        });

        $(".js-additemlist").click(function () {

            var elem = $(this).parents("form").first().find(".table-itemlist");
            customField.addItemList(elem);
            return false;
        });

        $('.wysiwyg-editor')
            .trumbowyg({
                btnsDef: {
                    // Create a new dropdown
                    image: {
                        dropdown: ['insertImage', 'base64'],
                        ico: 'insertImage'
                    }
                },
                // Redefine the button pane
                btns: [
                    ['viewHTML'],
                    ['formatting'],
                    ['strong', 'em', 'del'],
                    ['superscript', 'subscript'],
                    ['link'],
                    ['image'], // Our fresh created dropdown
                    ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                    ['unorderedList', 'orderedList'],
                    ['horizontalRule'],
                    ['removeformat'],
                    ['fullscreen']
                ],
                plugins: { resizimg: {} }
            });
        
    },

    preRempEdit: function (id) {

        site.showForm('#editForm', { container: ".main-container" });

        customField.clearItemList();
        $.ajax({
            type: "POST",
            url: 'CustomField/BindCustomFieldEditForm',
            dataType: "json",
            el: "#edit",
            data: { customFieldId: id },
            traditional: true,
            success: function (result) {
                var customFieldModel = result.customFieldModel;
                var units = result.units;

                $("#CustomFieldModelEdit_FieldId").val(customFieldModel.FieldId);
                $("#CustomFieldModelEdit_Name").val(customFieldModel.Name);
                $("#CustomFieldModelEdit_Type").val(customFieldModel.Type);
                $("#CustomFieldModelEdit_ObjectName").val(customFieldModel.ObjectName);
                $("#CustomFieldModelEdit_OrganizationId").val(customFieldModel.OrganizationId);
                $("#CustomFieldModelEdit_Required")[0].checked = customFieldModel.Required;

                site.initAjaxSelect();

                var form = $("#edit");


                $("#CustomFieldModelEdit_UnitIds").html("");
                for (u in units) {
                    var item = units[u]
                    $("#CustomFieldModelEdit_UnitIds").append('<option selected="selected" value="' + item.OrganizationUnitId + '">' + item.OrganizationUnitNameTranslate + '</option>');
                }

                var i = 0;
                var elem = $("#edit .table-itemlist");
                for (i in customFieldModel.CustomChoises) {
                    customField.addItemList(elem, customFieldModel.CustomChoises[i]);
                }

                $("#CustomFieldModelEdit_ObjectName").trigger('change');

                $("#CustomFieldModelEdit_Type").trigger('change');

                customField.addLabel(form, customFieldModel.Labels);

                customField.addHtml(form, customFieldModel.Htmls);
            }
        });

    },

    preRempAdd: function () {
        site.showForm('#addForm', { container: ".main-container" });

        $("#add input[id*='Name'], #add textarea, #add select").val("");

        $("#CustomFieldModel_ObjectName").change();
        $("#CustomFieldModel_Required")[0].checked = false;

        $("#CustomFieldModel_UnitIds").html("");
        site.initAjaxSelect();

        $("#CustomFieldModel_Type").trigger('change');

        customField.clearItemList();
    },

    gridReload: function () {
        var data = jQuery("#search").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "/CustomField/DataBind?" + data,
            //  postData: data,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var edProv = "";
            if (site.hasPermission(right.CustomField_Edit)) {
                edProv = "<button class='btn btn-circle btn-primary'  onclick='customField.preRempEdit(" + cl + ");'><i type='button' class='fa fa-pencil'></i></button>";
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },


    add: function () {
        //remove all events linked to the button click to prevent a double submit on double click
        $("#add .submit").off('click');
        tinymce.triggerSave();
        var form = $(this).parents("form").first();
        if (form.valid()) {
            var data = form.find("input[name!='FieldId'], textarea, select").serialize();
            $.ajax({
                type: "POST",
                url: 'CustomField/Add',
                dataType: "json",
                el: "#" + form.attr("id"),
                data: data,
                traditional: true,
                success: function (ret) {
                    customField.manageCustomFieldEditionRet(ret);
                    //restore click event and return to the field list
                    $("#add .submit").click(customField.add);
                    site.hideForm('#addForm', { container: ".main-container" });
                },
                failure: function (ret) {
                    //restore click event
                    $("#add .submit").click(customField.add);
                }
            });
        }
        else {
            //restore click event
            $("#add .submit").click(customField.add);
        }
    },

    edit: function () {
        //remove all events linked to the button click to prevent a double submit on double click
        $("#edit .submit").off('click');
        tinymce.triggerSave();
        var form = $(this).parents("form").first();
        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'CustomField/Edit',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    customField.manageCustomFieldEditionRet(ret);
                    //restore click event
                    $("#edit .submit").click(customField.edit);
                    site.hideForm('#editForm', { container: ".main-container" });
                },
                failure: function (ret) {
                    //restore click event
                    $("#edit .submit").click(customField.edit);
                }
            });
        }
        else {
            //restore click event
            $("#edit .submit").click(customField.edit);
        }
    },

    manageCustomFieldEditionRet: function (ret) {
        if (ret.Success) {
            site.successMessage(resources.ValidationSuccess);
            $("#JqGrid").trigger("reloadGrid");
        } else {
            site.errorMessage(ret.DuplicateKeyError ? (resourcesMessages.ValidationFail + ' : ' + resourcesMessages.CustomFieldError_DuplicateKeys) : resourcesMessages.ValidationFail);
            //restore click event in case of failure
            $("#add .submit").click(customField.add);
            $("#edit .submit").click(customField.edit);
        }
    },

    del: function (id) {
        var form = $(this).parents("form");
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(customField.params.messageAtLeastOneCustomfieldSelected, "Attention");
        }
        else {
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'CustomField/Delete',
                            dataType: "json",
                            data: { ids: s },
                            traditional: true,
                            el: "#jqcontainer",
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                    $("#JqGrid").trigger("reloadGrid");
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                            }
                        });
                }
            });
        }
    },

    refreshItemListIds: function (elem) {
        var i = 0;
        //on parcour toute les lignes du tableau 
        $(elem).find("tbody tr").each(function () {
            // pour chaque input et span on met a jour leur id nom etc..
            $(this).find('input, span').each(function () {
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var datamsq = $(this).attr("data-valmsg-for");
                if (id) id = id.replace(/(ses_\d+)/g, "ses_" + i);
                if (name) name = name.replace(/(ses\[\d+\])/g, "ses[" + i + "]");
                if (datamsq) datamsq = datamsq.replace(/(ses\[\d+\])/g, "ses[" + i + "]");
                $(this).attr("id", id);
                $(this).attr("name", name);
                $(this).attr("data-valmsg-for", datamsq);
            });
            i++;
        });

    },

    clearItemList: function () {
        //effacer les anciennes valeur (seulement les valeurs saisies, pas les champs cachés contenant les cultures de chaque colonne
        if (customField.rowTemplate != null) {
            customField.rowTemplate.find("input[id*='__Name']").val("");
            // customField.rowTemplate.find("input[id*='__Value']").val("");
        }

        $(".table-itemlist tbody").html("");
    },


    addLabel: function (form, labels) {
        if (labels != undefined) {
            $.each(labels, function (index, value) {
                form.find(".js-label input[id*='" + index + "__Name']").val(value.Name);
            });
        }

        return false;
    },

    addHtml: function (form, htmls) {
        if (htmls != undefined) {
            $.each(htmls, function (index, value) {
                if ($('#CustomFieldModelEdit_Htmls_' + index + '__Name') != undefined) {
                    $('#CustomFieldModelEdit_Htmls_' + index + '__Name').trumbowyg('html', value.Name == null ? "" : value.Name);
                }
            });
        }

        return false;
    },

    addItemList: function (elem, choise) {
        var table = elem;
        if (elem.parents("form").hasClass("addForm")) {
            var row = customField.rowTemplate;
        } else {
            var row = customField.rowEditTemplate;
        }
        //on récupere la derniere ligne du tableau

        var lastRow = table.find("tbody tr").last().clone(true);

        var nb = 0;

        //si il y a deja une ligne dans le tableau
        if (lastRow[0] != undefined) {
            var html = lastRow.html();
            //j'incrémente les numéro contenu dans CustomChoises_0__Name et CustomChoises[0].Name
            var newHtml = html.replace(/(CustomChoises_\d+)/g, function (match, str) {
                var number = str.replace("CustomChoises_", "");
                nb = parseInt(number, 10) + 1;
                return "CustomChoises_" + nb;
            });


            newHtml = newHtml.replace(/(CustomChoises\[\d+)/g, function (match, str) {
                var number = str.replace("CustomChoises[", "");
                nb = parseInt(number, 10) + 1;
                return "CustomChoises[" + nb;
            });

            lastRow.html(newHtml);
        } else {
            var lastRow = row.clone(true);
        }

        if (choise != undefined) {
            lastRow.find("input[id*='Value']").val(choise.Value);


            $.each(choise.Labels, function (index, value) {
                lastRow.find("input[id*='" + index + "__Culture']").val(value.Culture);

                lastRow.find("input[id*='" + index + "__Name']").val(value.Name);

            });

            // lastRow.find("input[id*='0__Name']").val(choise.Labels[0].Name);
        } else {
            lastRow.find("input[id*='Value']").val(nb + 1);
        }
        lastRow.find(".btn-delete").click(customField.deleteItemList);
        //j'injecte la ligne à la fin du tableau
        lastRow.appendTo(table);
        table.parents(".container-itemlist").animate({ scrollTop: lastRow.offset().top }, 'fast');

        return false;
    },

    deleteItemList: function () {
        var elem = $(this).parents(".table-itemlist").first();

        $(this).parents("tr").first().remove();
        customField.refreshItemListIds(elem);
        return false;
    },

    collapseOptionPanel: function () {
        var val = $(this).val();
        var form = $(this).parents("form");
        var options = form.find(".panel-options");
        var html = form.find(".js-html");

        options.hide();
        html.hide();

        if (val == 'Select' || val == 'Multiple' || val == 'Radio' || val == 'Checkbox') {
            options.show();
        } else if (val == 'HtmlMessage') {
            html.show();
        }
    },

    checkObjectValue: function (objectValue) {
        if (objectValue == 'Vehicle' || objectValue == 'Individual' || objectValue == 'IndividualPass' || objectValue == 'VehiclePass' || objectValue == 'GuestPass') {
            $("#CustomFieldModel_OrganizationId").attr("disabled", "disabled");
            $("#CustomFieldModel_UnitIds").attr("disabled", "disabled");

            $("#CustomFieldModel_OrganizationId").attr('required', false);
            $("#CustomFieldModel_UnitIds").attr('required', false);
        } else {
            $("#CustomFieldModel_OrganizationId").removeAttr("disabled");
            $("#CustomFieldModel_UnitIds").removeAttr("disabled");
            
            $("#CustomFieldModel_OrganizationId").attr('required', true);
            $("#CustomFieldModel_UnitIds").attr('required', true);
        }
    },

    checkIfIdNumber: function (type) {
        if (type === "IdNumber") {
            if ($("#addForm").is(":visible")) {
                $("#add #idNumberWarning").show();
            } else {
                $("#edit #idNumberWarning").show();
            }
        } else {
            if ($("#addForm").is(":visible")) {
                $("#add #idNumberWarning").hide();
            } else {
                $("#edit #idNumberWarning").hide();
            }
        }
    },

    getSelect2Params: function (params) {
        if ($("#addForm").is(":visible")) {
            params["organizationId"] = $("#CustomFieldModel_OrganizationId").val();
        } else {
            params["organizationId"] = $("#CustomFieldModelEdit_OrganizationId").val();
        }
        return params;

    }

}
var events = {
    params: {
        validFromDateToDate: "",
        name: "",
        openingTime: "",
        eventDate: "",
        organization: "",
        active: "",
        campaign: "",
        canSendCustomMail: false,
        imageLogoEventSizeRestriction: "",
        imageEventSizeRestriction: "",
        quotaTemplate: {
            QuotaTypesSelectList: null,
            QuotaZonesSelectList: null,
            QuotaProvidersSelectList: null,
            QuotaProfilesSelectList: null,
            QuotaUnitsSelectList: null,

            QuotaTypes: null,
            QuotaProfiles: null
        },
        quotaRowTemplate: null
    },

    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    $("title").html(resources.Events_stadium);
                    //Page générale
                    $(".title-primary").html(resources.Events_stadium);
                    $("#eventManagementTitle").html(resources.EventsManagement_stadium);
                    $(".add-limited-button").html(resources.Add + ' ' + resources.Step_stadium);
                    $(".add-unlimited-button").html(resources.Add + ' ' + resources.Season);
                    $("#treegrid").setLabel('EventDate', resources.EventDate_stadium);
                    $("#treegrid").setLabel('Name', resources.Organization_stadium);

                    //Saison/épreuve
                    $("#addUnlimitedTitle").html(resourcesMessages.AddUnlimited_stadium);
                    $("#updateUnlimitedTitle").html(resourcesMessages.UpdateUnlimited_stadium);
                    $("#UnlimitedEventAdd #unlimitedEventDate").html(resources.EventDate_stadium + " *");
                    $("#UnlimitedEventEdit #unlimitedEventDate").html(resources.EventDate_stadium + " *");
                    $("#UnlimitedEventAdd #unlimitedOrganization").html(resources.Organization_stadium + " *");
                    $("#UnlimitedEventEdit #unlimitedOrganization").html(resources.Organization_stadium + " *");
                    $("#UnlimitedEventAdd #unlimitedSteps").html(resources.Steps_stadium);
                    $("#UnlimitedEventEdit #unlimitedSteps").html(resources.Steps_stadium);

                    //Événement/étape
                    $("#LimitedEventAdd #addLimitedTitle").html(resourcesMessages.AddLimited_stadium);
                    $("#LimitedEventEdit #updateLimitedTitle").html(resourcesMessages.UpdateLimited_stadium);
                    $("#LimitedEventAdd #limitedEventDate").html(resources.LimitedEventDate_stadium + " *");
                    $("#LimitedEventEdit #limitedEventDate").html(resources.LimitedEventDate_stadium + " *");
                    $("#LimitedEventAdd #limitedOrganization").html(resources.Event_stadium + " *");
                    $("#LimitedEventEdit #limitedOrganization").html(resources.Event_stadium + " *");
                }
            }
        });


        $.extend(this.params, params);

        $("#actions .add-unlimited-button").click(events.preRempAddUnlimited);
        $("#actions .add-limited-button").click(events.preRempAddLimited);
        $("#actions .duplicate-button").click(events.preRempDuplicate);
        $(".js-additemlist-quota").click(events.addQuotaRow);

        $("#search").submit(events.gridReload);


        $("#LimitedEventEdit .submit").click(events.edit);
        $("#LimitedEventEdit .cancel").click(function () {
            site.hideForm('#LimitedEventEdit', { container: ".main-container" });
        });

        $("#UnlimitedEventEdit .submit").click(events.edit);
        $("#UnlimitedEventEdit .cancel").click(function () {
            site.hideForm('#UnlimitedEventEdit', { container: ".main-container" });
        });

        $("#DuplicateForm #DuplicateEventAccreditation_EventFromId").click(events.duplicateEstimation);
        $("#DuplicateForm #DuplicateEventAccreditation_EventToId").click(events.duplicateEstimation);

        $("#DuplicateForm .submit").click(events.duplicate);
        $("#DuplicateForm .cancel").click(function () {
            site.hideForm('#DuplicateForm', { container: ".main-container" });
        });

        $("#LimitedEventAdd .submit").click(events.add);
        $("#LimitedEventAdd .cancel").click(function () {
            site.hideForm('#LimitedEventAdd', { container: ".main-container" });
        });
        $("#UnlimitedEventAdd .submit").click(events.add);
        $("#UnlimitedEventAdd .cancel").click(function () {
            site.hideForm('#UnlimitedEventAdd', { container: ".main-container" });
        });

        $("#UnlimitedMailForm .submit").click(events.saveMailConfig);
        $("#UnlimitedMailForm .cancel").click(function () {
            site.hideForm('#UnlimitedMailForm', { container: ".main-container" });
        });

        $("#UnlimitedEventAdd_OrganizationId, #UnlimitedEventEdit_OrganizationId").change(events.onChangeOrganization);

        $("#LimitedEventEdit #LimitedEventEdit_Logo").click(file.fileUpload);
        $("#LimitedEventAdd #LimitedEventAdd_Logo").click(file.fileUpload);

        $("#UnlimitedEventEdit #UnlimitedEventEdit_Banner").click(file.fileUpload);
        $("#UnlimitedEventAdd #UnlimitedEventAdd_Banner").click(file.fileUpload);

        $("#UnlimitedEventEdit #UnlimitedEventEdit_Logo").click(file.fileUpload);
        $("#UnlimitedEventAdd #UnlimitedEventAdd_Logo").click(file.fileUpload);

        $("#LimitedEventAdd_EventParentId, #LimitedEventEdit_EventParentId").change(events.getEventDate);

        $("#UnlimitedEventAdd_OrganizationId, #UnlimitedEventEdit_OrganizationId").change(function () {
            $("#UnlimitedEventAdd_UnitIds").html("");
            $("#UnlimitedEventEdit_UnitIds").html("");
            site.initAjaxSelect();
        });

        $(".selectAllUnits").click(events.selectAllUnits);
        $(".selectAllSteps").click(events.selectAllSteps);
        $(".selectAllTypes").click(events.selectAllAssignmentTypes);

        jQuery("#treegrid").jqGrid({
            url: 'Event/DataBind/',
            datatype: "json",
            mtype: "POST",
            colNames: ["EventId", events.params.name, "Code", events.params.openingTime, "Fin de l'événement", events.params.eventDate, events.params.organization, "Catégories", "Envoie au controle", events.params.active, "OrganizationId", "CanUpdate", "CanDelete", "IsGroup", "<div class='text-center'><i class='fa fa-ellipsis-v'></i></div>"],
            colModel: [
                { name: 'EventId', index: 'EventId', width: 1, hidden: true, key: true },
                { name: 'EventName', index: 'EventName' },
                { name: 'EventCode', index: 'EventCode', hidden: true },
                { name: 'StartingDate', index: 'StartingDate', width: 150 },
                { name: 'EndingDate', index: 'EndingDate', hidden: true, align: "left" },
                { name: 'EventDate', index: 'EventDate', width: 150, align: "left" },
                { name: 'Name', index: 'Name', width: 150, align: "left" },
                { name: 'CategoryNames', index: 'CategoryNames' },
                { name: 'IsAccessControled', index: 'IsAccessControled', hidden: true },
                { name: 'IsActive', index: 'IsActive', align: "center", width: 50 },
                { name: 'OrganizationId', index: 'OrganizationId', hidden: true },
                { name: 'CanUpdate', index: 'CanUpdate', hidden: true },
                { name: 'CanDelete', index: 'CanDelete', hidden: true },
                { name: 'IsGroup', index: 'IsGroup', hidden: true },
                { name: 'act', index: 'act', width: 70 }
            ],
            autowidth: true,
            height: 'auto',
            pager: "#ptreegrid",
            treeGrid: true,
            treeGridModel: 'adjacency',
            onSortCol: function (index, columnIndex, sortOrder) {
                events.gridReload();
            },
            sortname: "EventDate",
            ExpandColumn: 'EventName',
            gridComplete: events.gridComplete,
            rowList: [10, 15, 30, 50, 100],
            rowNum: 50
        });
        $("#treegrid").jqGrid('navGrid', '#ptreegrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});


        //Init checkbox type access
        $('.checkbox_isAbsolute').change(function () {
            if (this.checked) {
                events.showAbsoluteAccess();
            }
            else {
                events.showRelativAccess();
            }
        });

        // get Images Dimension
        $.ajax({
            type: "GET",
            url: 'Parameter/GetImageEventSizeRestriction',
            dataType: "json",
            success: function (ImageEventSizeRestriction) {
                if (ImageEventSizeRestriction !== "") {
                    events.params.imageEventSizeRestriction = ImageEventSizeRestriction;
                }
            }
        });
        $.ajax({
            type: "GET",
            url: 'Parameter/GetImageLogoEventSizeRestriction',
            dataType: "json",
            success: function (ImageLogoEventSizeRestriction) {
                if (ImageLogoEventSizeRestriction !== "") {
                    events.params.imageLogoEventSizeRestriction = ImageLogoEventSizeRestriction;
                }
            }
        });



        $(".send-email-button").click(events.sendCustomMail);
        // convert image to base64 on uploading a new file
        // NB : On veut redimensionner directement l'image en la transformant en une image base64.
        //      Côté serveur, on aura plus qu'à uploader directement cette image base64 sans avoir à la redimensionner.
        //      Cela nous évitera le problème générique GDI+.
        $("input[type='file'].to-base-64").change(function () {
            var input = $(this);
            var div = $(input.parents(".img-wrapper"));
            var hidden = $(div.find("input[type='hidden'].img-base-64"));
            var image = div.find("img.img-picture")[0];

            var dimension = "";
            if (input.hasClass("for-logo")) {
                dimension = events.params.imageLogoEventSizeRestriction;
            } else if (input.hasClass("for-banner")) {
                dimension = events.params.imageEventSizeRestriction;
            }

            image.onload = function () {
                var parameterMaxWidth = dimension.split('x')[0];
                var parameterMaxHeight = dimension.split('x')[1];
                file.resizeBase64(div, image, hidden, parameterMaxWidth, parameterMaxHeight);
                file.resizeOnScreen(image, parameterMaxWidth, parameterMaxHeight);
            };
        });

        $("[id*=OrganizationId]").change(function () {
            var organizationId = $(this).val();
            events.initQuotas(organizationId);
        });
    },

    saveMailConfig: function () {
        var form = $(this).parents("form").first();

        if (form.valid()) {
            var data = form.serialize();
            data += ("&UnlimitedEventMail.IsMailCampaignOpen=" + $("#UnlimitedEventMail_IsMailCampaignOpen").is(":checked"));
            data += ("&UnlimitedEventMail.SendEmailAfterAssignmentValidation=" + $("#UnlimitedEventMail_SendEmailAfterAssignmentValidation").is(":checked"));
            data += ("&UnlimitedEventMail.SendAllEmailsNow=" + $("#UnlimitedEventMail_SendAllEmailsNow").is(":checked"));
            $.ajax({
                type: "POST",
                url: 'Event/EditMailConfiguration',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        form.find(".cancel").trigger("click");
                    } else if (!ret.sucess && ret.error !== undefined) {
                        site.errorMessage(resourcesMessages.MissingRequiredFields, null);
                    }
                    else if (ret.ExceptionOccured) {
                        site.errorMessage(resourcesMessages.ErrorOccured, null);
                    }
                }
            });
        }
    },

    getEventDate: function () {
        var form = $(this).parents("form").first();
        $.ajax({
            type: "POST",
            url: 'Event/BindEventEditForm',
            dataType: "json",
            data: { eventId: $(this).val() },
            traditional: true,
            success: function (result) {
                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, result.Exception);
                } else {
                    var ev = result.data.ev;
                    form.find("[id*='_StartingDate']").val(ev.StartingDate);
                    form.find("[id*='_EndingDate']").val(ev.EndingDate);
                    form.find("[id*='_EventDate']").val(ev.EventDate);
                }
            }
        });
    },

    preRempEditUnlimited: function (id) {
        window.id = id;
        site.showForm('#UnlimitedEventEdit', { container: ".main-container" });
        file.resetPicture("#UnlimitedEventEdit");
        $(".field-validation-error span").remove();
        $.ajax({
            type: "POST",
            url: 'Event/BindEventEditForm',
            dataType: "json",
            el: "#UnlimitedEventEdit",
            data: { eventId: id },
            traditional: true,
            success: function (result) {

                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, result.Exception);
                } else {
                    var ev = result.data.ev;
                    events.initQuotas(ev.OrganizationId,
                        function () {
                            events.manageEventQuotas(ev.Quotas, "#UnlimitedEventEdit");
                        }
                    );
                    var units = result.data.units;

                    if (!ev.IsTechEvent) {
                        $("#TechEventDiv").css("display", "none");
                    }

                    if (!ev.UseMultiSite) {
                        $("#Categories").css("display", "none");
                    }

                    var ret = jQuery("#treegrid").jqGrid('getRowData', window.id);
                    $("#UnlimitedEventEdit_EventId").val(ev.EventId);
                    $("#UnlimitedEventEdit_EventCode").val(ev.EventCode);
                    $("#UnlimitedEventEdit_EventName").val(ev.EventName);
                    $("#UnlimitedEventEdit_OrganizationId").val(ev.OrganizationId);
                    $("#UnlimitedEventEdit_EventDate").val(ev.EventDate);
                    $("#UnlimitedEventEdit_StartingDate").val(ev.StartingDate);
                    $("#UnlimitedEventEdit_EndingDate").val(ev.EndingDate);
                    $("#UnlimitedEventEdit_EntryExitCount").val(ret.EntryExitCount);
                    $('#UnlimitedEventEdit_IsActive').prop('checked', ev.IsActive);
                    $('#UnlimitedEventEdit_IsAccessControled').prop('checked', ev.IsAccessControled);
                    $('#UnlimitedEventEdit_RetrieveAssignmentsAccessControlState').prop('checked', ev.RetrieveAssignmentsAccessControlState);
                    $('#UnlimitedEventEdit_EnableIndividualTitleSendingByMail').prop('checked', ev.EnableIndividualTitleSendingByMail);
                    $('#UnlimitedEventEdit_EnableVehicleTitleSendingByMail').prop('checked', ev.EnableVehicleTitleSendingByMail);
                    $('#UnlimitedEventEdit_EnableAnonymousTitleSendingByMail').prop('checked', ev.EnableAnonymousTitleSendingByMail);
                    $('#UnlimitedEventEdit_EnableGuestTitleSendingByMail').prop('checked', ev.EnableGuestTitleSendingByMail);

                    var unlimitedEventEditHasVehicleAccreditation = $("#UnlimitedEventEdit_HasVehicleAccreditation")[0];
                    if (unlimitedEventEditHasVehicleAccreditation !== null && unlimitedEventEditHasVehicleAccreditation !== undefined) {
                        unlimitedEventEditHasVehicleAccreditation.checked = ev.HasVehicleAccreditation;
                    }
                    $('#UnlimitedEventEdit_HasGuestAccreditation').prop('checked', ev.HasGuestAccreditation);


                    if (ev.IsTechEvent) {
                        $("#UnlimitedEventEdit_TechEventPersonKey").val(ev.TechEventPersonKey);
                        $("#UnlimitedEventEdit_TechEventVehicleKey").val(ev.TechEventVehicleKey);
                        $("#UnlimitedEventEdit_TechEventGuestKey").val(ev.TechEventGuestKey);
                        $("#UnlimitedEventEdit_TechEventPersonTestKey").val(ev.TechEventPersonTestKey);
                        $("#UnlimitedEventEdit_TechEventVehicleTestKey").val(ev.TechEventVehicleTestKey);
                        $("#UnlimitedEventEdit_TechEventGuestTestKey").val(ev.TechEventGuestTestKey);
                        if ($("#UnlimitedEventEdit_EnableTechEventTest")[0] != null) {
                            $("#UnlimitedEventEdit_EnableTechEventTest")[0].checked = ev.EnableTechEventTest;
                        }
                    }

                    $("#UnlimitedEventEdit_UnitIds").html("");
                    for (u in units) {
                        var item = units[u];
                        $("#UnlimitedEventEdit_UnitIds").append('<option selected="selected" value="' + item.OrganizationUnitId + '">' + item.OrganizationUnitName + '</option>');
                    }

                    var htmlOrganizations = events.constructList(ev.Organizations);
                    $("#UnlimitedEventEdit_OrganizationId").html(htmlOrganizations).val(ev.OrganizationId);
                    if (ev.HasLogo) {
                        d = new Date();
                        file.setPicture("#UnlimitedEventEdit .logo", "/Content/images/event/" + ev.LogoName);
                    }

                    if (ev.HasImage) {
                        d = new Date();
                        file.setPicture("#UnlimitedEventEdit .banner", "/Content/images/event/" + ev.ImageName);
                    }

                    var htmlEventChildren = events.constructList(ev.EventChildren);
                    $("#UnlimitedEventEdit_EventChildrenIds").html(htmlEventChildren);
                    $("#UnlimitedEventEdit_EventChildrenIds").css("width", "100%").select2({ dropdownAutoWidth: true });
                    $("#UnlimitedEventEdit_OrganizationId").select2({ dropdownAutoWidth: true });
                    var htmlCategories = events.constructList(ev.Categories);
                    $("#UnlimitedEventEdit_CategoryIds").html(htmlCategories);
                    events.manageEventAccess(ev, "#UnlimitedEventEdit_");
                    $("#UnlimitedEventEdit_AccessTitleGenerationColumnsSortOrderId").val(ev.AccessTitleGenerationColumnsSortOrderId);
                    events.initEventCarpools(ev.EventCarpoolList, "#UnlimitedEventEdit");
                }
            }
        });

        events.bindMockups(id);

    },

    bindMockups: function (id) {
        $(".js-additemlist").off("click");
        $("#mockups").html('');
        $.ajax({
            type: "post",
            url: 'Event/RefreshMockup',
            data: { eventId: id },
            success: function (result) {
                $("#mockups").html(result);
                window.pass.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();
                $(".js-additemlist").click(function () {
                    var elem = $(this).parents("form").first().find(".table-itemlist");
                    window.pass.addItemList(elem);
                    return false;
                });

                $(".btn-delete").click(window.pass.deleteItemList);
            }
        });
    },

    preRempUnlimitedMail: function (id) {
        window.id = id;
        site.showForm('#UnlimitedMailForm', { container: ".main-container" });

        $.ajax({
            type: "POST",
            url: 'Event/BindEventMailConfigurationForm',
            dataType: "json",
            el: "#UnlimitedMailForm",
            data: { eventId: id },
            traditional: true,
            success: function (ev) {

                $("#UnlimitedEventMail_EventName").html(resourcesMessages.MailCampaignManagement + " " + ev.EventName);
                $("#UnlimitedEventMail_IsMailCampaignOpen")[0].checked = ev.IsActive;
                if (!ev.IsActive) {
                    $("#UnlimitedEventMail_SendEmailAfterAssignmentValidation").attr('disabled', 'disabled');
                    $("#UnlimitedEventMail_SendAllEmailsNow").attr('disabled', 'disabled');
                    $(".listChildrenAffected").attr('disabled', 'disabled');
                    $(".listTypesAffected").attr('disabled', 'disabled');
                    $(".listUserTemplates").attr('disabled', 'disabled');
                    $(".listAssignmentTemplates").attr('disabled', 'disabled');
                }
                $("#UnlimitedEventMail_SendEmailAfterAssignmentValidation")[0].checked = ev.SendMailAfterAssignmentValidation;
                $("#UnlimitedEventMail_SendAllEmailsNow")[0].checked = ev.SendAllEmailsNow;
                $("#UnlimitedEventMail_EventId").val(ev.EventId);
                var stepsHtml = events.constructList(ev.Steps);
                $(".listChildrenAffected").html(stepsHtml);
                $(".listChildrenAffected").css("width", "100%").select2({ dropdownAutoWidth: true });

                var assignmentTypesHtml = events.constructList(ev.MailAssignmentTypeIds);
                $(".listTypesAffected").html(assignmentTypesHtml);
                $(".listTypesAffected").css("width", "100%").select2({ dropdownAutoWidth: true });

                var userTemplates = events.constructList(ev.UserTemplateIds);
                $(".listUserTemplates").html(userTemplates);
                $(".listUserTemplates").css("width", "100%").select2({ dropdownAutoWidth: true });

                var assignmentTemplates = events.constructList(ev.AssignmentTemplateIds);
                $(".listAssignmentTemplates").html(assignmentTemplates);
                $(".listAssignmentTemplates").css("width", "100%").select2({ dropdownAutoWidth: true });

            }
        });
    },

    preRempEditLimited: function (id) {
        window.id = id;
        site.showForm('#LimitedEventEdit', { container: ".main-container" });
        file.resetPicture("#LimitedEventEdit");
        $(".field-validation-error span").remove();

        $.ajax({
            type: "POST",
            url: 'Event/BindEventEditForm',
            dataType: "json",
            el: "#LimitedEventEdit",
            data: { eventId: id },
            traditional: true,
            success: function (result) {
                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, result.Exception);
                } else {
                    var ev = result.data.ev;
                    var units = result.data.units;

                    events.initQuotas(ev.OrganizationId,
                        function () {
                            events.manageEventQuotas(ev.Quotas, "#LimitedEventEdit");
                        }
                    );

                    var ret = jQuery("#treegrid").jqGrid('getRowData', window.id);
                    if (ev.Mockups != undefined && ev.Mockups[0] != undefined) {
                        $("#LimitedEventEdit_MockupIds").val(ev.Mockups[0]);
                    }

                    if (ev.PreviewMockup != undefined && ev.PreviewMockup[0] != undefined) {
                        $("#LimitedEventEdit_PreviewMockupId").val(ev.PreviewMockup);
                    }
                    $("#LimitedEventEdit_EventId").val(ev.EventId);
                    $("#LimitedEventEdit_EventCode").val(ev.EventCode);
                    $("#LimitedEventEdit_EventName").val(ev.EventName);
                    $("#LimitedEventEdit_EventDate").val(ev.EventDate);
                    $("#LimitedEventEdit_StartingDate").val(ev.StartingDate);
                    $("#LimitedEventEdit_EndingDate").val(ev.EndingDate);
                    $("#LimitedEventEdit_EntryExitCount").val(ret.EntryExitCount);
                    $('#LimitedEventEdit_IsActive').prop('checked', ev.IsActive);
                    $('#LimitedEventEdit_IsAccessControled').prop('checked', ev.IsAccessControled);
                    $('#LimitedEventEdit_RetrieveAssignmentsAccessControlState').prop('checked', ev.RetrieveAssignmentsAccessControlState);
                    $('#LimitedEventEdit_EnableIndividualTitleSendingByMail').prop('checked', ev.EnableIndividualTitleSendingByMail);
                    $('#LimitedEventEdit_EnableVehicleTitleSendingByMail').prop('checked', ev.EnableVehicleTitleSendingByMail);
                    $('#LimitedEventEdit_EnableAnonymousTitleSendingByMail').prop('checked', ev.EnableAnonymousTitleSendingByMail);
                    $('#LimitedEventEdit_EnableGuestTitleSendingByMail').prop('checked', ev.EnableGuestTitleSendingByMail);

                    var limitedEventEditHasVehicleAccreditation = $("#LimitedEventEdit_HasVehicleAccreditation")[0];
                    if (limitedEventEditHasVehicleAccreditation !== null && limitedEventEditHasVehicleAccreditation !== undefined) {
                        limitedEventEditHasVehicleAccreditation.checked = ev.HasVehicleAccreditation;
                    }
                    $('#LimitedEventEdit_HasGuestAccreditation').prop('checked', ev.HasGuestAccreditation);

                    if (ev.HasLogo) {
                        d = new Date();
                        file.setPicture("#LimitedEventEdit .logo", "/Content/images/event/" + ev.LogoName);
                    }

                    var html = events.constructList(ev.Organizations);
                    $("#LimitedEventEdit_OrganizationId").html(html).val(ev.OrganizationId);

                    html = events.constructList(ev.EventParents);
                    $("#LimitedEventEdit_EventParentId").html(html);

                    $("#LimitedEventEdit_OrganizationId").select2({ dropdownAutoWidth: true });
                    $("#LimitedEventEdit_EventParentId").css("width", "100%").select2({ dropdownAutoWidth: true });

                    if (!result.data.ev.UseMultiSite) {
                        $(".Categories").css("display", "none");
                    }
                    else {
                        var htmlCategory = events.constructList(ev.Categories);
                        $("#LimitedEventEdit_CategoryIds").html(htmlCategory);
                        $("#LimitedEventEdit_CategoryIds").select2({ dropdownAutoWidth: true });
                    }
                    events.manageEventAccess(ev, "#LimitedEventEdit_");
                }
            }
        });
    },

    preRempAddUnlimited: function () {
        site.showForm('#UnlimitedEventAdd', { container: ".main-container" });
        $.ajax({
            type: "POST",
            url: 'Event/BindEventAddForm',
            dataType: "json",
            el: "#UnlimitedEventAdd",
            traditional: true,
            success: function (result) {
                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, result.Exception);
                } else {

                    if (!result.data.IsTechEvent) {
                        $("#TechEventDiv").css("display", "none");
                    }

                    if (!result.data.UseMultiSite) {
                        $(".Categories").css("display", "none");
                    }
                    else {
                        var htmlCategories = events.constructList(result.data.Categories);
                        $("#UnlimitedEventAdd_CategoryIds").html(htmlCategories);
                    }

                    $("#UnlimitedEventAdd_EventCode").val("");
                    $("#UnlimitedEventAdd_EventName").val("");
                    $("#UnlimitedEventAdd_EventDate").val("");
                    $("#UnlimitedEventAdd_OrganizationId").val("");
                    $("#UnlimitedEventAdd_StartingDate").val("");
                    $("#UnlimitedEventAdd_EndingDate").val("");
                    $("#UnlimitedEventAdd_IsAccessControled")[0] = false;
                    $("#UnlimitedEventAdd_IsActive")[0] = false;
                    var htmlOrganizations = events.constructList(result.data.Organizations);
                    $("#UnlimitedEventAdd_OrganizationId").html(htmlOrganizations);

                    file.resetPicture("#UnlimitedEventAdd");
                    var htmlEventChildren = events.constructList(result.data.EventChildren);
                    $("#UnlimitedEventAdd_EventChildrenIds").html(htmlEventChildren);
                    $("#UnlimitedEventAdd_OrganizationId").select2({ dropdownAutoWidth: true });
                    $("#UnlimitedEventAdd_EventChildrenIds").css("width", "100%").select2({ dropdownAutoWidth: true });
                    $("#UnlimitedEventAdd_TechEventPersonKey").val("");
                    $("#UnlimitedEventAdd_TechEventVehicleKey").val("");
                    $("#UnlimitedEventAdd_TechEventGuestKey").val("");
                    $("#UnlimitedEventAdd_TechEventPersonTestKey").val("");
                    $("#UnlimitedEventAdd_TechEventVehicleTestKey").val("");
                    $("#UnlimitedEventAdd_TechEventGuestTestKey").val("");
                    $("#UnlimitedEventAdd_EnableTechEventTest")[0] = false;
                    $('#UnlimitedEventAdd_IsActive').prop('checked', false);
                    $('#UnlimitedEventAdd_IsAccessControled').prop('checked', false);
                    $('#UnlimitedEventAdd_HasGuestAccreditation').prop('checked', false);
                    $('#UnlimitedEventAdd_HasVehicleAccreditation').prop('checked', false);
                    $('#UnlimitedEventAdd_RetrieveAssignmentsAccessControlState').prop('checked', false);
                    $('#UnlimitedEventAdd_EnableIndividualTitleSendingByMail').prop('checked', false);
                    $('#UnlimitedEventAdd_EnableVehicleTitleSendingByMail').prop('checked', false);
                    $('#UnlimitedEventAdd_EnableAnonymousTitleSendingByMail').prop('checked', false);
                    $('#UnlimitedEventAdd_EnableGuestTitleSendingByMail').prop('checked', false);

                    events.manageEventAccess(result.data, "#UnlimitedEventAdd_");

                    events.initEventCarpools(result.data.EventCarpoolList, "#UnlimitedEventAdd");
                }
            }
        });

        events.bindMockups(0);
    },

    preRempAddLimited: function () {
        site.showForm('#LimitedEventAdd', { container: ".main-container" });
        $.ajax({
            type: "POST",
            url: 'Event/BindEventAddForm',
            dataType: "json",
            el: "#LimitedEventAdd",
            traditional: true,
            success: function (result) {
                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, result.Exception);
                } else {
                    $("#LimitedEventAdd_EventCode").val("");
                    $("#LimitedEventAdd_EventName").val("");
                    $("#LimitedEventAdd_EventDate").val("");
                    $("#LimitedEventAdd_OrganizationId").val("");
                    $("#LimitedEventAdd_StartingDate").val("");
                    $("#LimitedEventAdd_EndingDate").val("");
                    $("#LimitedEventAdd_IsAccessControled")[0] = false;
                    $("#LimitedEventAdd_IsActive")[0] = false;
                    var htmlOrganizations = events.constructList(result.data.Organizations);
                    $("#LimitedEventAdd_OrganizationId").html(htmlOrganizations);
                    file.resetPicture("#LimitedEventAdd");
                    var htmlEventParents = events.constructList(result.data.EventParents);
                    $("#LimitedEventAdd_EventParentId").html(htmlEventParents);
                    $("#LimitedEventAdd_OrganizationId").select2({ dropdownAutoWidth: true });
                    $("#LimitedEventAdd_EventParentId").css("width", "100%").select2({ dropdownAutoWidth: true });
                    $('#LimitedEventAdd_IsActive').prop('checked', false);
                    $('#LimitedEventAdd_IsAccessControled').prop('checked', false);
                    $('#LimitedEventAdd_RetrieveAssignmentsAccessControlState').prop('checked', false);
                    $('#LimitedEventAdd_EnableIndividualTitleSendingByMail').prop('checked', false);
                    $('#LimitedEventAdd_EnableVehicleTitleSendingByMail').prop('checked', false);
                    $('#LimitedEventAdd_EnableAnonymousTitleSendingByMail').prop('checked', false);
                    $('#LimitedEventAdd_EnableGuestTitleSendingByMail').prop('checked', false);
                    $('#LimitedEventAdd_HasVehicleAccreditation').prop('checked', false);
                    $('#LimitedEventAdd_HasGuestAccreditation').prop('checked', false);

                    if (!result.data.UseMultiSite) {
                        $(".Categories").css("display", "none");
                    }
                    else {
                        if (result.data.Categories !== null && result.Categories !== undefined) {
                            result.data.Categories.unshift({ "id": "", "name": "", "selected": "" }); // élément vide par défaut au début
                        }
                        var htmlCategories = events.constructList(result.data.Categories);
                        $("#LimitedEventAdd_CategoryIds").html(htmlCategories);
                    }

                    events.manageEventAccess(result.data, "#LimitedEventAdd_");
                }
            }
        });
    },

    preRempDuplicate: function () {
        site.showForm('#DuplicateForm', { container: ".main-container" });
        $("#DuplicateForm .alert").hide();
        $("#DuplicateForm")[0].reset();
        $("select").select2({ dropdownAutoWidth: true });
    },

    selectAllUnits: function () {
        var form = $(this).parents("form").first();
        var organizationId = form.find("[id*=_OrganizationId]").val();
        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/GetUnits',
            dataType: "json",
            el: "#LimitedEventEdit",
            data: { organizationId: organizationId },
            traditional: true,
            success: function (result) {
                var units = result.items;
                var unitField = form.find("[id*='_UnitIds']");
                unitField.html("");
                events.appendUnits(units, form);
            }
        });
        return false;
    },

    appendUnits: function (units, form) {
        var unitField = $(form).find("[id*='_UnitIds']");
        for (u in units) {
            var item = units[u];
            if (item.children == null || item.children.length==0) {
                unitField.append('<option selected="selected" value="' + item.id + '">' + item.name + '</option>');
            } else {
                events.appendUnits(item.children, form);
            }
        }
    },


    selectAllSteps: function () {
        if (!$("#UnlimitedEventMail_IsMailCampaignOpen").is(":checked")) return false;

        var form = $(this).parents("form").first();
        var eventId = form.find("[id*=_EventId]").val();
        $.ajax({
            type: "POST",
            url: 'Event/GetEventSteps',
            dataType: "json",
            el: "#UnlimitedMailForm",
            data: { eventId: eventId },
            traditional: true,
            success: function (result) {
                var stepsfield = form.find("[id*='_EventChildrenIds']");
                stepsfield.html("");
                for (var u in result) {
                    var item = result[u];
                    stepsfield.append('<option selected="selected" value="' + item.EventId + '">' + item.EventName + '</option>');
                }
            }
        });
        return true;
    },

    selectAllAssignmentTypes: function () {
        if (!$("#UnlimitedEventMail_IsMailCampaignOpen").is(":checked")) return false;

        var form = $(this).parents("form").first();
        $.ajax({
            type: "POST",
            url: 'Assignment/GetAllAssignmentTypes',
            dataType: "json",
            el: "#UnlimitedMailForm",
            traditional: true,
            success: function (result) {
                var stepsfield = form.find("[id*='_MailAssignmentTypesIds']");
                stepsfield.html("");
                for (var u in result) {
                    var item = result[u];
                    stepsfield.append('<option selected="selected" value="' + item.Id + '">' + item.Name + '</option>');
                }
            }
        });
        return true;
    },

    openCampaign: function () {
        if ($("#UnlimitedEventMail_IsMailCampaignOpen").is(":checked")) {

            $("#UnlimitedEventMail_SendEmailAfterAssignmentValidation").removeAttr('disabled');
            $("#UnlimitedEventMail_SendAllEmailsNow").removeAttr('disabled');
            $(".listChildrenAffected").removeAttr('disabled');
            $(".listTypesAffected").removeAttr('disabled');
            $(".listUserTemplates").removeAttr('disabled');
            $(".listAssignmentTemplates").removeAttr('disabled');

        } else {
            $("#UnlimitedEventMail_SendEmailAfterAssignmentValidation").attr('disabled', 'disabled');
            $("#UnlimitedEventMail_SendAllEmailsNow").attr('disabled', 'disabled');
            $(".listChildrenAffected").attr('disabled', 'disabled');
            $(".listTypesAffected").attr('disabled', 'disabled');
            $(".listUserTemplates").attr('disabled', 'disabled');
            $(".listAssignmentTemplates").attr('disabled', 'disabled');
        }
    },


    constructList: function (list) {
        var html = "";
        for (var i = 0; list.length > i; i++) {
            var selected = "";
            if (list[i].selected != undefined && list[i].selected != false) {
                selected = "selected";
            }
            html += "<option " + selected + " value='" + list[i].id + "'>" + list[i].name + "</option>";
        }
        return html;
    },
    setIndividualFormProperties: function () {

        var hasImage = !($(".img-picture").attr("src") === "null" || $(".img-picture").attr("src") === undefined);

        if (hasImage) {
            var base64Image = file.getCroppedImage($scope.imagePersonWidthRestriction);
            if (base64Image !== false) {
                $scope.individual.Base64PngPhoto = base64Image;
            }
        }
    },

    getSetting: function (formId) {
        var data = "&" + formId + ".AccessDetailsModel.IsAbsoluteAccess=" + $('.checkbox_isAbsolute').is(":checked");
        data += "&LimitedEventEdit.AccessDetailsModel.IsAbsoluteAccesss=" + $('.checkbox_isAbsolute').is(":checked");
        data += "&" + formId + ".IsActive=" + $("#" + formId + "_IsActive").is(":checked");
        data += "&" + formId + ".IsAccessControled=" + $("#" + formId + "_IsAccessControled").is(":checked");
        data += "&" + formId + ".RetrieveAssignmentsAccessControlState=" + $("#" + formId + "_RetrieveAssignmentsAccessControlState").is(":checked");
        data += "&" + formId + ".EnableIndividualTitleSendingByMail=" + $("#" + formId + "_EnableIndividualTitleSendingByMail").is(":checked");
        data += "&" + formId + ".EnableVehicleTitleSendingByMail=" + $("#" + formId + "_EnableVehicleTitleSendingByMail").is(":checked");
        data += "&" + formId + ".EnableAnonymousTitleSendingByMail=" + $("#" + formId + "_EnableAnonymousTitleSendingByMail").is(":checked");
        data += "&" + formId + ".EnableGuestTitleSendingByMail=" + $("#" + formId + "_EnableGuestTitleSendingByMail").is(":checked");
        data += "&" + formId + ".HasVehicleAccreditation=" + $("#" + formId + "_HasVehicleAccreditation").is(":checked");
        data += "&" + formId + ".HasGuestAccreditation=" + $("#" + formId + "_HasGuestAccreditation").is(":checked");
        return data;
    },

    add: function () {
        var form = $(this).parents("form").first();

        form.find("[id*='_EventCode']").rules("add", "checkUniciteCodeEvent");
        form.find("[id*='_EndingDate']").rules("add", "compareDate");

        if (form.valid()) {
            events.serializeQuotas(form.attr("id")); //must be called before the actual form serialization, so that the element names are correctly formatted
            events.serializeEventCarpools(form.attr("id"));
            var data = form.serialize();
            data += events.getSetting(form[0].id);

            $.ajax({
                type: "POST",
                url: 'Event/Add',
                dataType: "json",
                el: "#" + form.attr("id"),
                data: data,
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        events.gridReload();
                        form.find(".cancel").trigger("click");
                    } else {
                        if (ret.Exception !== null) {
                            site.errorMessage(resourcesMessages.UpdateFailed, ret.Exception);
                        } else {
                            site.errorMessage(resourcesMessages.UpdateFailed);
                        }
                    }
                }
            });
        }
    },

    edit: function () {
        var form = $(this).parents("form").first();
        form.find("[id*='_EventCode']").rules("add", "checkUniciteCodeEvent");
        form.find("[id*='_EndingDate']").rules("add", "compareDate");

        if (form.find("[id*='_OrganizationId']")[0] !== undefined) {
            form.find("[id*='_OrganizationId']").rules("add", "canEditOrganization");
        }

        if (form.valid()) {
            events.serializeQuotas(form.attr("id"));
            events.serializeEventCarpools(form.attr("id"));
            var data = form.serialize();
            data += events.getSetting(form[0].id);

            $.ajax({
                type: "POST",
                url: 'Event/Edit',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        events.gridReload();
                        form.find(".cancel").trigger("click");
                    } else {
                        if (ret.Exception !== null) {
                            site.errorMessage(resourcesMessages.UpdateFailed, ret.Exception);
                        } else {
                            site.errorMessage(resourcesMessages.ErrorOccured);
                        }
                    }
                }
            });
        }
    },

    del: function (id) {
        jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
            var s = jQuery("#treegrid").jqGrid('getGridParam');
            if (ok && s != "") {
                $.ajax({
                    type: "POST",
                    url: 'Event/Delete',
                    dataType: "json",
                    data: { eventId: id },
                    traditional: true,
                    success: function (ret) {
                        if (ret.Success) {
                            site.successMessage(resourcesMessages.SuppressionSuccess);
                            $("#treegrid").trigger("reloadGrid");
                        } else {
                            site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                        }
                    }
                });
            }
        });
    },

    duplicate: function () {
        var form = $(this).parents("form").first();

        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'Event/DuplicateAccreditationToEvent',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        site.successMessage(resources.ValidationSuccess);
                        events.gridReload();
                        form.find(".cancel").trigger("click");
                    }
                }
            });
        }
    },

    duplicateEstimation: function () {
        var form = $(this).parents("form").first();
        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'Event/DuplicateEstimation',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id") + " .alert",
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        $("#DuplicateForm .alert").html(ret.message).show();
                    }
                }
            });
        }
    },

    gridReload: function () {
        var nameMask = jQuery("#Search_Name").val();
        jQuery("#treegrid").jqGrid('setGridParam', {
            url: "Event/DataBind"
                + "?name=" + nameMask,
            page: 1
        }).trigger("reloadGrid");
        return false;
    },

    sendCustomMail: function () {
        if (!$(".send-custom-mail-modal form").valid()) return;

        var unitId = $(".send-custom-mail-modal .unitId").val();

        var subject = $(".send-custom-mail-modal .subject").val();
        var body = $(".send-custom-mail-modal .body").val();

        $.ajax({
            type: "POST",
            url: 'Event/SendCustomMail',
            dataType: "json",
            data: { UnitId: unitId, Subject: subject, Body: body },
            traditional: true,
            success: function (ret) {
                if (ret.Success) {
                    site.successMessage(resourcesMessages.SendCustomMailSuccess);
                } else {
                    site.errorMessage(resourcesMessages.SendCustomMailError, ret.Exception);
                }
                $(".send-custom-mail-modal").modal("hide");
            },
            error: function () {
                site.errorMessage(resourcesMessages.SendCustomMailError, null);
            }
        });

    },

    openSendCustomMailModal: function (eventId) {

        $(".send-custom-mail-modal form").trigger("reset");

        $(".send-custom-mail-modal .unitId").html("");

        $.ajax({
            type: "POST",
            url: 'Event/GetUnits',
            dataType: "json",
            data: { eventId: eventId },
            success: function (result) {

                if (!result.Success) {
                    site.errorMessage(resourcesMessages.ErrorOccured, null);
                }

                $(".send-custom-mail-modal .unitId").append($('<option>', {
                    value: "",
                    text: ""
                }));

                $.each(result.data, function (i, item) {
                    $(".send-custom-mail-modal .unitId").append($('<option>', {
                        value: item.UnitId,
                        text: item.Name
                    }));
                });

                $(".send-custom-mail-modal").modal('show');
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured, null);
            }
        });
    },

    gridComplete: function () {
        var mailButton = "";
        var edEvent = "";
        $.ajax({
            type: "POST",
            url: 'Parameter/GetMailjetParameter',
            dataType: "json",
            traditional: true,
            success: function (mailjet) {
                var ids = jQuery("#treegrid").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
                    var data = $("#treegrid").jqGrid("getRowData", cl);
                    if (data.IsGroup == "False") {
                        if (site.hasPermission(right.Event_Edit)) {
                            edEvent = "<button class='btn btn-circle btn-primary' onclick='events.preRempEditLimited(" + cl + ");'><i type='button' class='fa fa-pencil' ></i></button>";
                        }
                    } else {
                        if (site.hasPermission(right.Event_Edit)) {
                            edEvent = "<button class='btn btn-circle btn-primary' onclick='events.preRempEditUnlimited(" + cl + ");'><i type='button' class='fa fa-pencil' ></i></button>";
                        }

                        if (mailjet === true)
                            mailButton = "<button class='btn btn-circle btn-primary' onclick='events.preRempUnlimitedMail(" + cl + ");'><i type='button' class='fa fa-paper-plane'></i></button>";
                    }

                    var sendMailButton = events.params.canSendCustomMail ? "<button class='btn btn-circle btn-primary' onclick='events.openSendCustomMailModal(" + cl + ");'><i type='button' class='fa fa-envelope'></i></button>" : "";

                    var active = data.IsActive;

                    var deEvent = "";

                    if (site.hasPermission(right.Event_Delete)) {
                        deEvent = "<button class='btn btn-circle btn-primary' onclick='events.del(" + cl + ");'><i type='button' class='fa fa-trash' ></i></button>";
                    }

                    if (data.IsActive === "True") {
                        active = "<i class='fa fa-check text-success'></i>";
                    } else if (data.IsActive === "False") {
                        active = "<i class='fa fa-times text-danger'></i>";
                    }
                    var rangeDate = data.StartingDate;
                    var eventDate = data.EventDate;

                    if (rangeDate.indexOf("small") === -1) {
                        rangeDate = "<small>" + data.StartingDate + "</small><br /><small>" + data.EndingDate + "</small>";
                        eventDate = "<small>" + data.EventDate + "</small>";
                    }

                    var catRes = "";
                    if (data.CategoryNames !== undefined && data.CategoryNames.length > 0) {
                        if (data.CategoryNames.indexOf('<span class="categories-in-list">') === -1) {
                            var catsArray = data.CategoryNames.split(';');
                            $.each(catsArray, function (i, c) {
                                catRes = catRes + '<span class="categories-in-list">' + c + ' </span>';
                            });
                        } else {
                            catRes = data.CategoryNames;
                        }
                    }

                    jQuery("#treegrid").jqGrid('setRowData', ids[i], { IsActive: active, StartingDate: rangeDate, EventDate: eventDate, act: edEvent + deEvent + mailButton + sendMailButton, CategoryNames: catRes });
                }
            }
        });
    },

    getSelect2Params: function (params) {
        if ($("#UnlimitedEventAdd").is(":visible")) {
            params["organizationId"] = $("#UnlimitedEventAdd_OrganizationId").val();
        } else {
            params["organizationId"] = $("#UnlimitedEventEdit_OrganizationId").val();
        }
        return params;
    },

    showAbsoluteAccess: function () {
        $('.checkbox_isAbsolute').prop('checked', true);
        $(".absoluteAccess").show();
        $(".relativAccess").hide();
    },

    showRelativAccess: function () {
        $('.checkbox_isAbsolute').prop('checked', false);
        $(".relativAccess").show();
        $(".absoluteAccess").hide();
    },

    manageEventAccess: function (ev, typeEvent) {
        $(typeEvent + "AccessDetailsModel_AllowEditAccesHours")[0].checked = ev.AllowEditAccesHours;

        if (ev.IsAbsoluteAccess) {
            $(typeEvent + "AccessDetailsModel_AccessStartDate").val(ev.AccessStartDate);
            $(typeEvent + "AccessDetailsModel_AccessEndDate").val(ev.AccessEndDate);
            events.showAbsoluteAccess();
        }
        else {
            $(typeEvent + "AccessDetailsModel_MinutesNumberBeforeAccess").val(ev.MinutesNumberBeforeAccess);
            $(typeEvent + "AccessDetailsModel_MinutesNumberAfterAcces").val(ev.MinutesNumberAfterAcces);
            events.showRelativAccess();
        }
    },

    manageEventQuotas: function (eventQuotas, typeEvent) {
        var elemQuotas = $(typeEvent + " .div-quotas .table-quotas tbody");
        $(elemQuotas).html('');

        if (eventQuotas !== undefined && eventQuotas !== null) {
            for (var i = 0; i < eventQuotas.length; i++) {
                events.addItemQuotaList(elemQuotas, events.getRowTemplate(), eventQuotas[i]);
            }
        }
    },

    /* Initialiser les lignes de quota */
    initQuotas: function (organizationId, callback) {
        $.ajax({
            type: "post",
            url: 'Quota/GetTemplate',
            data: { organizationId: organizationId },
            success: function (result) {
                events.params.quotaTemplate.QuotaTypes = result.data.QuotaTypes;
                events.params.quotaTemplate.QuotaProfiles = result.data.QuotaProfiles;
                events.params.quotaTemplate.QuotaProviders = result.data.QuotaProviders;
                events.params.quotaTemplate.QuotaZones = result.data.QuotaZones;
                events.params.quotaTemplate.QuotaUnits = result.data.QuotaUnits;
                events.params.quotaTemplate.quotaRowTemplate = events.getRowTemplate();

            }
        }).then(function () {
            if (callback !== undefined) {
                callback();
            }
        });

    },



    getRowTemplate: function () {
        var templateId = Math.random();
        return "<tr data-template>"
            + "<td class='quota-type'>" + events.createSelectListHTML(events.params.quotaTemplate.QuotaTypes, "QuotaTypes", "") + "<input type='hidden' class='quota-id'/> <input type='hidden' class='quota-event-id'/>" + "</td>"
            + "<td class='quota-select'>" + events.createSelectListHTML(events.params.quotaTemplate.QuotaProfiles, "QuotaProfiles", Math.random()) + "</td>"
            + "<td class='quota-max' align='center'>" + "<input class='form-control' type='number' name='" + templateId + "' step='1'  min='0' required/>"
            + "<span class='field-validation-valid text-danger' data-valmsg-for='" + templateId + "' data-valmsg-replace='true'></span></td>"
            + "<td class='quota-check-on-validation' align='center'>" + "  <div class='checkBox'> <input type='checkbox' id='" + templateId + "'><label for='" + templateId + "'></label> </div>" + "</td>"
            + "<td class='quota-delete' align='center'>" + "<button type='button' class='btn btn-unstyled btn-sm btn-delete-quota text-danger'><i class='fa fa-times fa-lg'></i></button>" + "</td>"
            + "</tr>";
    },

    addQuotaRow: function () {
        var tableQuotas = $(this).closest("div.div-quotas").find("table.table-quotas");
        var rowTemplate = events.getRowTemplate();
        $(rowTemplate).removeClass("hidden");
        events.addItemQuotaList(tableQuotas.find("tbody"), rowTemplate);
        return false;
    },

    addItemQuotaList: function (elem, item, quota) {
        elem.append(item);
        elem.find("select[name='QuotaTypes']").change(function () {
            var closestQuotaSelect = $(this).closest("tr").find(".quota-select");
            closestQuotaSelect.html('');
            var selectValue = $(this).val();
            switch (selectValue) {
                case "0":
                    closestQuotaSelect.append(events.createSelectListHTML(events.params.quotaTemplate.QuotaProfiles, "QuotaProfiles", Math.random()));//  events.params.quotaTemplate.QuotaProfilesSelectList);
                    break;
                case "1":
                    closestQuotaSelect.append(events.createSelectListHTML(events.params.quotaTemplate.QuotaProviders, "QuotaProviders", Math.random()));
                    break;
                case "2":
                    closestQuotaSelect.append("<input type='text' class='form-control combotree-units'/>");
                    var unitsComboTree = $(closestQuotaSelect.find("input.combotree-units"));
                    unitsComboTree.combotree({});
                    unitsComboTree.combotree('loadData', events.params.quotaTemplate.QuotaUnits);
                    break;
                case "3":
                    closestQuotaSelect.append(events.createSelectListHTML(events.params.quotaTemplate.QuotaZones, "QuotaProviders", Math.random()));
                    break;
                default:
            }
            closestQuotaSelect.find("select").css("width", "100%").select2({ dropdownAutoWidth: true });
        });

        var currentRow = elem.find("tr").last();
        currentRow.find(".quota-select").last().find("select").css("width", "100%").select2({ dropdownAutoWidth: true });

        currentRow.find(".btn-delete-quota").click(function () {
            currentRow.remove();
        });

        if (quota !== undefined && quota !== null) {
            currentRow.find(".quota-id").val(quota.QuotaId);
            currentRow.find(".quota-event-id").val(quota.EventId);
            currentRow.find(".quota-type select").val(quota.QuotaType).trigger('change');

            if (quota.QuotaType === 2) { // traitement spécial pour la sélection de famille
                currentRow.find(".quota-select input.combotree-units").combotree('setValue', quota.TargetId);
            } else {
                currentRow.find(".quota-select select").val(quota.TargetId).trigger('change');
            }
            currentRow.find(".quota-max input").val(quota.QuotaMax);
            currentRow.find(".quota-check-on-validation input").attr("checked", quota.CheckOnValidation).val(quota.CheckOnValidation);
        }
    },

    /* les objets passés ont un Id et un Name */
    createSelectListHTML: function (list, name, rawId) {
        var templateSelect = "<select class='form-control' name='" + rawId + '' + name + "'  required>";
        $.each(list, function (i, type) {
            templateSelect += "<option value='" + type.Id + "'>" + type.Name + "</option>";
        });
        templateSelect += "</select>";
        templateSelect += "<span class='field-validation-valid text-danger' data-valmsg-for='" + rawId + '' + name + "' data-valmsg-replace='true'></span>";
        return templateSelect;
    },

    bindQuotas: function (elem, quotas) {
        $(elem).html('');

        if (quotas !== undefined && quotas !== null) {
            for (var i = 0; i < quotas.length; i++) {
                events.addItemQuotaList(elem, events.getRowTemplate(), quotas[i]);
            }
        }
    },
    //adds name to the html elements, so that they're serialized correctly
    serializeQuotas: function (formId) {
        var tbody = $("#" + formId + " table.table-quotas tbody");

        var rowQuotas = tbody.find("tr");

        var formName = "QuotaList[";
        var quotaEventId_NAME = "].EventId";
        var quotaId_NAME = "].QuotaId";
        var quotaType_NAME = "].QuotaType";
        var quotaTargetId_NAME = "].TargetId";
        var quotaMax_NAME = "].QuotaMax";
        var checkOnValidation_NAME = "].CheckOnValidation";

        for (var i = 0; i < rowQuotas.length; i++) {
            var checkOnValidation_checkbox = $(rowQuotas[i]).find(".quota-check-on-validation input").is(':checked');

            $(rowQuotas[i]).find(".quota-id").attr("name", formName + i + quotaId_NAME);
            $(rowQuotas[i]).find(".quota-event-id").attr("name", formName + i + quotaEventId_NAME);
            $(rowQuotas[i]).find(".quota-type select").attr("name", formName + i + quotaType_NAME);

            if ($(rowQuotas[i]).find(".quota-type select").val() === "2") { // traitement spécial pour la sélection de famille
                $(rowQuotas[i]).find(".quota-select input.textbox-value").attr("name", formName + i + quotaTargetId_NAME);
            } else {
                $(rowQuotas[i]).find(".quota-select select").attr("name", formName + i + quotaTargetId_NAME);
            }

            $(rowQuotas[i]).find(".quota-max input").attr("name", formName + i + quotaMax_NAME);
            $(rowQuotas[i]).find(".quota-check-on-validation input").attr("name", formName + i + checkOnValidation_NAME).val();


            $(rowQuotas[i]).find(".quota-check-on-validation input").val(checkOnValidation_checkbox);
        }
    },

    initEventCarpools: function (eventCarpoolList, typeEvent) {
        var elemCarpools = $(typeEvent + " .div-carpools ul");
        elemCarpools.html('');
        for (var i = 0; i < eventCarpoolList.length; i++) {
            events.addItemEventCarpool(elemCarpools, eventCarpoolList[i]);
        }
    },

    addItemEventCarpool: function (elemCarpools, eventCarpoolItem) {
        var intFormat = "onkeypress='return (event.charCode >= 48 && event.charCode <= 57)'"
        var newItem = "<li class='list-group-item'>"
            + "<label for='" + eventCarpoolItem.VehicleTypeName + "'>" + eventCarpoolItem.VehicleTypeName + " *</label>"
            + "<input type='hidden' class='carpool-id' " + (eventCarpoolItem.EventCarpoolId !== 0 ? "value='" + eventCarpoolItem.EventCarpoolId + "'" : "") + " />"
            + "<input type='hidden' class='carpool-event-id' " + (eventCarpoolItem.EventId !== 0 ? "value='" + eventCarpoolItem.EventId + "'" : "") + " />"
            + "<input type='hidden' class='carpool-vehicletype-id' value='" + eventCarpoolItem.VehicleTypeId + "' /> "
            + "<input class='form-control carpool-minimumPassenger numberWithoutArrows' min='0' " + intFormat+"type='number' name='"+ eventCarpoolItem.VehicleTypeName + "' value='" + eventCarpoolItem.MinimumPassenger + "' required/>"
            + "<span class='field-validation-valid text-danger' data-valmsg-for='" + eventCarpoolItem.VehicleTypeName + "' data-valmsg-replace='true'/>"
            + "</li>";

        elemCarpools.append(newItem);
    },

    serializeEventCarpools: function (formId) {
        var eventCarpoolList = $("#" + formId + " .div-carpools ul").find("li");

        var formName = "eventCarpoolList[";
        var eventCarpoolEventCarpoolId_NAME = "].EventCarpoolId";
        var eventCarpoolEventId_NAME = "].EventId";
        var eventCarpoolVehicleType_NAME = "].VehicleTypeId";
        var eventCarpoolMinimumPassenger_NAME = "].MinimumPassenger";

        for (var i = 0; i < eventCarpoolList.length; i++) {
            $(eventCarpoolList[i]).find(".carpool-id").attr("name", formName + i + eventCarpoolEventCarpoolId_NAME).val();
            $(eventCarpoolList[i]).find(".carpool-event-id").attr("name", formName + i + eventCarpoolEventId_NAME).val();
            $(eventCarpoolList[i]).find(".carpool-vehicletype-id").attr("name", formName + i + eventCarpoolVehicleType_NAME).val();
            $(eventCarpoolList[i]).find(".carpool-minimumPassenger").attr("name", formName + i + eventCarpoolMinimumPassenger_NAME).val();
        }
    }
};
var parameters = {
    
    checkType: function (value, colName) {
        if (value == '')
            return [false, resourcesMessages.NoEmptyValueAccepted];
        var result = false;
        switch (parameters.currentRowDataType) {
            case 'boolean':
                result = parameters.isBoolean(value);
                break;
            case 'string':
                result = parameters.isString(value);
                break;
            case 'integer':
                result = parameters.isInteger(value);
                break;
            default:
                return [false, resourcesMessages.UnknownParameterType];
                break;
        }
        if (!result) {
            {
                var message = resourcesMessages.WrongParameterType;
                message = message.replace("{0}", value);
                message = message.replace("{1}", parameters.currentParameter);
                message = message.replace("{2}", parameters.currentRowDataType);
                return [false, message];
            }
        }
        else {
            return [true, ''];
        }
    },
    // Returns if a value is a string
    isString: function (value) {
        return typeof value === 'string' || value instanceof String;
    },
    // Returns if a value is really a number
    isInteger: function (value) {
        var n = Number(value);
        return typeof n === 'number' && isFinite(n) && /^\d+$/.test(value);
    },
    // Returns if a value is really a boolean
    isBoolean: function (value) {
        return /^true$/.test(value) || /^false$/.test(value);
    },
    currentRowDataType: null,
    currentParameter: null,
    init: function () {
        $.extend($.jgrid, {
            info_dialog: function (caption, content, c_b, modalopt) {
                // display custom dialog instead of default defined by jqgrid
                useCustomDialog = false;
                site.errorMessage(content, null);
            }
        });
        //Reemplissage du tableau jQgrid
        jQuery('#JqGrid').jqGrid({
            autowidth: true,
            datatype: 'json',
            gridview: true,
            height: '100%',
            hidegrid: false,
            pager: '#PagerJqGrid',
            mtype: 'post',
            rowList: [10, 15, 30, 50, 100, 200, 500],
            rowNum: 50,
            scrollrows: true,
            sortname: 'Category',
            sortorder: 'asc',
            url: 'Parameter/DataBind/',
            cellurl: 'Parameter/Edit/',
            cellEdit: true,
            cellsubmit: 'remote',
            viewrecords: true,
            loadError: function (xhr, status, error) { site.errorAjaxPopup(xhr, status, error) },
            colModel: [
                {
                    name: 'ParameterId',
                    hidden: true,
                    label: 'ParameterId',
                    index: 'ParameterId'
                },
                {
                    align: 'left',
                    name: 'Category',
                    label: 'Categorie',
                    width: 70,
                    index: 'Category'
                },
                {
                    align: 'left',
                    name: 'ParameterCode',
                    label: 'Code',
                    width: 70,
                    index: 'ParameterCode'
                },
                {
                    align: 'left',
                    name: 'Description',
                    label: 'Description',
                    width: 70,
                    index: 'Description'
                },
                {
                    align: 'left',
                    name: 'Type',
                    label: 'Type',
                    width: 70,
                    index: 'Type'
                },
                {
                    align: 'left',
                    name: 'Value',
                    label: 'Valeur',
                    editrules: { custom: true, custom_func: parameters.checkType },
                    editable: site.hasPermission(right.Parameter_Edit),
                    editoptions: { size: "Auto", maxlength: "255" },
                    width: 110,
                    index: 'Value'
                },],
            loadError: site.errorAjaxPopup,
            afterSaveCell: function () {
                //site.successMessage(resources.ValidationSuccess);
            },
            afterSubmitCell: function (serverresponse, rowid, cellname, value, iRow, iCol) {
                var response = serverresponse.responseJSON;
                if (response.Success) {
                    site.successMessage(resources.ValidationSuccess);
                    return [true, ""];
                }
                else {
                    return [false, response.Exception];
                }
            },
            beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
                var data = jQuery("#JqGrid").jqGrid('getRowData', rowid);
                //set current datatype before saving the value in cell, it will be later checked with method checkType
                parameters.currentRowDataType = data.Type;
                parameters.currentParameter = data.ParameterCode;
                return false;
            },
            errorCell: function (serverresponse, status) {
                site.errorAjaxPopup("", status, serverresponse.responseText);
            },
            afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                var data = jQuery("#JqGrid").jqGrid('getRowData', rowid);
                if (data.Type == "color") {
                    jQuery("#JqGrid #" + rowid + " input").each(function () {
                        $(this).spectrum({ showInput: true, showInitial: true, cancelText: "Annuler", chooseText: "Valider" });
                    });
                }
            }
        });
    },

}
var users = {
    labels: {
        confirmDeleteAll: "",
        confirmRegenPassword: "",
        labelRegenPasswordSuccess: "",
        messageOneUserSelected: "",
        showAD: ""
    },

    params: {
        groups: []
    },

    init: function (labels, groups) {
        $.extend(this.labels, labels);

        users.params.groups = groups;

        $("#search").submit(users.gridReload);

        $("#actions .submit").click(users.preRempAdd);
        $("#actions .delete").click(users.deleteAll);
        $("#actions .resetPwd").click(users.resetPwdAll);
        $(".send-email-button").click(users.sendCustomMail);

        $("#actions .open-modal-send-custom-mail").click(users.openSendCustomMailModal);

        $("#editForm .submit").click(users.edit);

        $("#addForm .submit").click(users.add);

        if ($(".select2-default.role").val() == "2") {
            $(".js-administration-panel").show();
        } else {
            $(".js-administration-panel").hide();
        }

        $(".select2-default.role").change(function () {
            var form = $(this).parents("form").first();

            var groupId = parseInt($(this).val());

            var group = $.grep(users.params.groups, function (g) { return g.GroupId == groupId; })[0];

            if (group.AdminLevel) {                
                form.find(".CanPrint")[0].checked = group.CanPrint;

                if (group.HasAccessToAllEvent) {
                    form.find(".js-event-group").hide();
                } else {
                    form.find(".js-event-group").show();
                }

                if (group.HasCustomTitleAccess) {
                    form.find(".js-valuerights-group").show();
                } else {
                    form.find(".js-valuerights-group").hide();
                }

                form.find(".js-administration-panel").show();
            } else {
                form.find(".js-administration-panel").hide();
            }

            if (group.SuperAdminLevel) {
                form.find(".js-superadministration-panel").show();
            } else {
                form.find(".js-superadministration-panel").hide();
            }
        });

        $("#addForm #Login").rules("add", "checkUniciteUserOnAdd");
        $("#editForm #Login").rules("add", "checkUniciteUser");
    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });

        var ret = jQuery("#JqGrid").jqGrid('getRowData', id);
        $('#edit #Login').attr("readonly", "readonly");
        $.ajax({
            type: "POST",
            url: 'User/BindUserForm',
            dataType: "json",
            el: "#edit",
            data: { id: id },
            traditional: true,
            success: function (ret) {
                $('#edit #Title').val(ret.Title);
                $('#edit #UserId').val(ret.UserId);
                $("#edit #LastName").val(ret.LastName);
                $("#edit #FirstName").val(ret.FirstName);
                $("#edit #Login").val(ret.Login);
                $("#edit #Email").val(ret.Email);
                $("#edit #MobilePhoneNumber").val(ret.MobilePhoneNumber);
                $("#edit #LandlinePhoneNumber").val(ret.LandlinePhoneNumber);
                $("#edit #Function").val(ret.Function);
                $("#edit #GroupId").val(ret.GroupId);
                $("#edit #ProviderId").val(ret.ProviderId);
                $('#edit #ProviderId').attr('disabled', 'disabled');
                //$("#edit #CanPrint")[0].checked = ret.CanPrint;

                $("#edit #UnitCodes").val(ret.UnitCodes);
                $("#edit #EventIds").val(ret.EventIds);
                $(".select2-default.role").change();

                $("#edit #ValueRights").val(ret.ValueRights);
                if (users.labels.showAD.toLowerCase() === "true") {

                    if (!ret.ADLogin) {
                        $("#ADLogin-container").hide();
                    }
                    else {
                        $("#ADLogin-container").show();
                        $("#edit #ADLogin").val(ret.ADLogin);
                    }


                }

                var createdby = $('.createdby');
                createdby.html("");
                if (ret.CreateBy !== null) {
                    var creator = resourcesMessages.CreateBy.replace("{0}", ret.CreateBy.LastName + " " + ret.CreateBy.FirstName + " (" + ret.CreateBy.Login + ")").replace("{1}", ret.CreationDate);
                    createdby.html(creator);
                }
                var updatedby = $('.updatedby');
                updatedby.html("");
                if (ret.LastUpdateBy !== null) {
                    var updater = resourcesMessages.LastUpdateBy.replace("{0}", ret.LastUpdateBy.LastName + " " + ret.LastUpdateBy.FirstName + " (" + ret.LastUpdateBy.Login + ")").replace("{1}", ret.LastUpdateDate);
                    updatedby.html(updater);
                }

            }
        });
    },

    preRempAdd: function () {
        site.showForm('#addForm', { container: ".main-container" });

        $("#addForm")[0].reset();
        $("#addForm #ProviderId").val($("#search_prov").val());
        $("#edit #UnitCodes").val("");
        $("#edit #EventIds").val("");
        $('#add input[name=LastName]').keyup(users.setLogin).click(users.setLogin);
        $('#add input[name=FirstName]').keyup(users.setLogin).click(users.setLogin);
        $("select:not(.no-select2)").select2({ dropdownAutoWidth: true });
        $(".select2-default.role").change();

        $('.createdby').html("");
        $('.updatedby').html("");

        $("#ADLogin-container").show();
    },

    setLogin: function () {
        $('#add #Login').val($('#add #FirstName').val().charAt(0) + $('#add #LastName').val().replace(/ /g, ""));
    },

    add: function () {
        if ($("#addForm").valid()) {
            var data = $("#addForm").serialize();
            $.ajax({
                type: "POST",
                url: 'User/Add',
                dataType: "json",
                data: data,
                el: "#addForm",
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#JqGrid").trigger("reloadGrid");
                        $("#addForm .cancel").trigger("click");
                    } else {
                        site.errorMessage(ret.Exception);
                    }

                }

            });

        }
    },

    edit: function () {

        if ($("#editForm").valid()) {
            var data = $("#editForm").serialize();
            $.ajax({
                type: "POST",
                url: 'User/Edit',
                dataType: "json",
                data: data,
                el: "#editForm",
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#JqGrid").trigger("reloadGrid");
                        $("#editForm .cancel").trigger("click");
                    }
                    else {
                        site.errorMessage(ret.Exception);
                    }
                }
            });

        }
    },

    openSendCustomMailModal: function () {
        var s = $("#JqGrid").jqGrid('getGridParam', 'selarrrow');

        if (s.length === 0) {
            jAlert(users.labels.messageOneUserSelected, "Attention");
        }
        else {
            $(".send-custom-mail-modal form").trigger("reset");
            $(".send-custom-mail-modal").modal('show');
        }

    },

    sendCustomMail: function () {
        if (!$(".send-custom-mail-modal form").valid()) return;

        var s = $("#JqGrid").jqGrid('getGridParam', 'selarrrow');

        var subject = $(".send-custom-mail-modal .subject").val();
        var body = $(".send-custom-mail-modal .body").val();

        $.ajax(
            {
                type: "POST",
                url: 'User/SendCustomMail',
                dataType: "json",
                data: { UserIds: s, Subject: subject, Body: body },
                traditional: true,
                el: "#jqcontainer",
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resourcesMessages.SendCustomMailSuccess);
                    } else {
                        site.errorMessage(resourcesMessages.SendCustomMailError, ret.Exception);
                    }
                    $(".send-custom-mail-modal").modal("hide");
                },
                error: function () {
                    site.errorMessage(resourcesMessages.SendCustomMailError, null);
                }
            });

    },

    deleteAll: function () {
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');

        if (s == "") {
            jAlert(users.labels.messageOneUserSelected, "Attention");
        }
        else {
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'User/DeleteSelected',
                            dataType: "json",
                            data: { userIds: s },
                            traditional: true,
                            el: "#jqcontainer",
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                    $("#JqGrid").trigger("reloadGrid");
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                            }
                        });
                }
            });
        }
    },

    resetPwdAll: function () {
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');

        if (s == "") {
            jAlert(users.labels.messageOneUserSelected, "Attention");
        }
        else {
            jConfirm(users.labels.confirmRegenPassword, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'User/RegeneratePasswordSelected',
                        dataType: "json",
                        data: { userIds: s },
                        el: "#jqcontainer",
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(users.labels.labelRegenPasswordSuccess);
                            } else {
                                if (ret.isAdErrorMessage) {
                                    site.errorMessage(resourcesMessages.DeleteUserAdError, ret.Exception);
                                }
                                else {
                                    site.errorMessage(resourcesMessages.NoSendMessage, ret.Exception);
                                }
                            }
                            $("#JqGrid").trigger("reloadGrid");
                        }
                    });
                }
            });

        }
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var userIdGrid = data.UserId;
            var edUser = "";

            if (site.hasPermission(right.User_Edit)) {
                edUser = "<button class='btn btn-circle btn-primary' onclick='users.preRempEdit(" + userIdGrid + ");'><i type='button' class='fa fa-pencil' ></i></button>";
            }

            var name = "<strong>" + data.LastName + "</strong> " + data.FirstName + " <div><small><em>" + data.Email + "</em></small></div>"
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { Name: name, act: edUser });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },

    gridReload: function () {
        var test = $("#search").serialize();

        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "User/DataBind?" + test,
            page: 1
        }).trigger("reloadGrid");
        return false;
    },

};
var assignmentImport = {

    params: {

    },

    init: function (params) {
        $.extend(this.params, params);
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');

        for (var i = 0; i < ids.length; i++) {
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            if (data.ResolutionListUrl != "") {
                var input = "<div class='row row-no-padding'><div class='col-sm-9'><input type='text' id='" + data.Row + "-" + data.FieldEntityType + "' name='" + data.Row + "-" + data.FieldEntityType + "' data-exception='" + data.Id + "' data-ajax='{\"url\":\"" + data.ResolutionListUrl + "\"}'/></div><div class='clo-sm-3'><a class='btn btn-success' href='/Organization?id=" + data.OptionalData + "' target='_blank'><i class='fa fa-plus'></i></a></div></div>"
                jQuery("#JqGrid").jqGrid('setRowData', ids[i], { FieldNewValue: input });
                $("#" + data.Row + "-" + data.FieldEntityType).Select2Ajax({ datas: [{ "EventId": $("#EventId").val() }] }).change(assignmentImport.ResolutionSelected);
            }
        }
        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
        { view: false, del: false, add: false, edit: false, search: false, refresh: true },
        {}, {}, {}, {}, {});
    },

    ResolutionSelected: function () {
        var id = $(this).data("exception");
        var data = jQuery("#JqGrid").jqGrid('getRowData', id);
        data.FieldNewValue = $(this).val();
        var serialize = $("#importForm").serialize();
        $.ajax({
            type: "POST",
            url: "Assignment/ImportConflictResolution?" + serialize,
            traditional: true,
            el: "#JqGrid",
            data: data,
            dataType: "json",
            success: function (ret) {
                if (ret.success) {
                    window.location.href = ret.returnUrl;
                } else {
                    jQuery("#JqGrid").trigger("reloadGrid")
                }
            }
        });
    }
}
var _billings = {

    params: {
        hasPermissionSetActive: false,
        useMultiSite: false,
        messageAtLeastOneBillingSelected: null
    },

    rowBillingProfileTemplates: {
        BillingProfileWorkforce: null,
        BillingProfileGlobal: null,
        BillingProfileForfait: null,
        BillingProfileFreelancer: null
    },

    // Initialize billing page
    init: function (params) {
        $.extend(this.params, params);

        //hasPermissionSetActive
        this.params.hasPermissionSetActive = site.hasPermission(right.Billing_SetActive);

        $("#search .submit").click(_billings.gridReload);

        // Fill Event Dropdown on Season change
        $("#search .season").change(_billings.fillEvent);

        $(".grid-header .add").click(_billings.preRempAdd);

        $("#editForm .submit").click(_billings.edit);

        $('#editForm .not-editable').attr('disabled', 'disabled');
        $('#editForm .add-only').remove();
        $('#addForm .only-editable').remove();

        $("#addForm .submit").click(_billings.add);

        $(".grid-header .delete").click(_billings.delSelectedBilling);

        $(".grid-header .define-quotas").click(function () {
            quotaBilling.init();

            site.showForm('#BillingQuotasView', { container: ".main-container" });
        });

        $(".grid-header .generate-reports").click(function () {
            $(".generate-reports-modal form").trigger("reset");
            $("#generate-reports-form .event").empty();
            $(".generate-reports-modal").modal('show');
        });

        $(".generate").click(_billings.generateReports);

        if (this.params.useMultiSite) {
            $("#generate-reports-form .season").change(_billings.fillCategory);
            $("#generate-reports-form .category").change(_billings.fillEventCategory);

            // Fill Event Dropdown on Season change
            $("#search .season").change(_billings.fillCategory);
            $("#search .category").change(_billings.fillEventCategory);
            $("#addForm .season").change(_billings.fillCategory);
            $("#addForm .category").change(_billings.fillEventCategory);

            $("#editForm .season").change(_billings.fillCategory);
            $("#editForm .category").change(_billings.fillEventCategory);
        }
        else {
            $("#generate-reports-form .season").change(_billings.fillEvent);

            // Fill Event Dropdown on Season change
            $("#search .season").change(_billings.fillEvent);
            $("#addForm .season").change(_billings.fillEvent);
            $("#editForm .season").change(_billings.fillEvent);
        }


        $("#generate-reports-form .provider").change(_billings.fillBillingType);

        $("#generate-reports-form .provider").change();

        $("#add").click(_billings.add);
        $("#delete").click(_billings.delete);
        $("#BillingQuotasView .cancel").click(function () {
            site.hideForm('#BillingQuotasView', { container: ".main-container" });
        });


        $('#AddForm_BillingTypeId').change(function () {
            _billings.changeBillingType("addForm");
        });

        $('#EditForm_BillingTypeId').change(function () {
            _billings.changeBillingType("editForm");
        });
        _billings.initRowTemplates();
    },

    bindBillingProfileTemplateAction: function (formId) {
        $("button.js-additemlist").unbind();
        $("button.js-additemlist").click(function () {
            var parent = $(this).parents("div.billing-profiles");
            if ($('#' + formId + ' [id*=BillingTypeId]').val() != 0 || $('#' + formId + ' [id*=BillingTypeId]').val() != undefined) {
                var tbody = "";
                var trToAppend = "";
                if ($('#' + formId + ' [id*=BillingTypeId]').val() == 1) {
                    
                    tbody = parent.find(".specialized-billing-profiles .billing-profile-workforce table tbody");
                    trToAppend = _billings.rowBillingProfileTemplates.BillingProfileWorkforce.clone();

                    trToAppend.find("button.btn-delete").click(function () {
                        trToAppend.remove();
                    });

                    tbody.append(trToAppend);
                    _billings.initValidators("billing-profile-workforce");
                } else if ($('#' + formId + ' [id*=BillingTypeId]').val() == 2) {
                    tbody = parent.find(".specialized-billing-profiles .billing-profile-global table tbody");
                    trToAppend = _billings.rowBillingProfileTemplates.BillingProfileGlobal.clone();

                    trToAppend.find("button.btn-delete").click(function () {
                        trToAppend.remove();
                    });

                    tbody.append(trToAppend);
                    _billings.initValidators("billing-profile-global");
                } else if ($('#' + formId + ' [id*=BillingTypeId]').val() == 3) {
                    tbody = parent.find(".specialized-billing-profiles .billing-profile-forfait table tbody");
                    trToAppend = _billings.rowBillingProfileTemplates.BillingProfileForfait.clone();

                    trToAppend.find("button.btn-delete").click(function () {
                        trToAppend.remove();
                    });

                    tbody.append(trToAppend);
                    _billings.initValidators("billing-profile-forfait");
                } else if ($('#' + formId + ' [id*=BillingTypeId]').val() == 4) {
                    tbody = parent.find(".specialized-billing-profiles .billing-profile-freelancer table tbody");
                    trToAppend = _billings.rowBillingProfileTemplates.BillingProfileFreelancer.clone();

                    trToAppend.find("button.btn-delete").click(function () {
                        trToAppend.remove();
                    });

                    tbody.append(trToAppend);
                    _billings.initValidators("billing-profile-profiles");
                }
            }
        });
    },

    initRowTemplates: function () {
        var bpwTemplate = $(".specialized-billing-profiles .billing-profile-workforce table tbody tr.row-template");
        var bpwTemplateClone = bpwTemplate.first().clone();
        bpwTemplateClone.removeClass("row-template");
        _billings.rowBillingProfileTemplates.BillingProfileWorkforce = bpwTemplateClone;

        var bpgTemplate = $(".specialized-billing-profiles .billing-profile-global table tbody tr.row-template");
        var bpgTemplateClone = bpgTemplate.first().clone();
        bpgTemplateClone.removeClass("row-template");
        _billings.rowBillingProfileTemplates.BillingProfileGlobal = bpgTemplateClone;

        var bpfoTemplate = $(".specialized-billing-profiles .billing-profile-forfait table tbody tr.row-template");
        var bpfoTemplateClone = bpfoTemplate.first().clone();
        bpfoTemplateClone.removeClass("row-template");
        _billings.rowBillingProfileTemplates.BillingProfileForfait = bpfoTemplateClone;

        var bpfrTemplate = $(".specialized-billing-profiles .billing-profile-freelancer table tbody tr.row-template");
        var bpfrTemplateClone = bpfrTemplate.first().clone();
        bpfrTemplateClone.removeClass("row-template");
        _billings.rowBillingProfileTemplates.BillingProfileFreelancer = bpfrTemplateClone;

        bpwTemplate.remove();
        bpgTemplate.remove();
        bpfoTemplate.remove();
        bpfrTemplate.remove();
    },

    //limit typing decimal places to the parameter count
    limitDecimalPlaces: function(e, count) {
        if (e.target.value.indexOf('.') == -1) { return; }
        if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
            e.target.value = e.target.value.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
        }
    },

    delSelectedBilling: function () {
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(_billings.params.messageAtLeastOneBillingSelected, resources.Warning);
            return;
        } 

        jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
            if (!ok) return;

            $.ajax({
                type: "POST",
                url: 'Billing/DeleteSelected',
                dataType: "json",
                data: { ids: s },
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resourcesMessages.SuppressionSuccess);
                    } else {
                        site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                    }
                    $("#JqGrid").trigger("reloadGrid");
                },
                error: function () {
                    site.errorMessage(resourcesMessages.SuppressionFailed);
                }
            });
            
        });
        
    },
    // fill category dropdownlist with categories of selected season
    fillCategory: function () {
        var elem = $(this);

        var formId = elem.attr("data-formId");
        var categoryId = $("#" + formId + " .category").attr("data-default");

        var eventDropDownList = $("#" + formId + " .event");

        eventDropDownList.empty();
        if (eventDropDownList.hasClass("select2-default")) eventDropDownList.trigger('change.select2');


        var categoryDropDownList = $("#" + formId + " .category");

        categoryDropDownList.empty();
        if (categoryDropDownList.hasClass("select2-default")) categoryDropDownList.trigger('change.select2');

        if (elem.val() == "") return;

        $.ajax({
            type: "POST",
            url: 'Category/GetCategoriesByEvent',
            dataType: "json",
            data: { eventId: elem.val() },
            success: function (result) {

                eventDropDownList.empty();
                categoryDropDownList.empty();

                $.each(result, function (i, item) {
                    categoryDropDownList.append($('<option>', {
                        value: item.CategoryId,
                        text: item.Name,
                        selected: categoryId == item.CategoryId
                    }));

                });

                categoryDropDownList.change();

            },
            error: function () {

                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    // fill BillingType dropdownlist with billing types of selected provider
    fillBillingType: function () {
        var elem = $(this);

        var formId = elem.attr("data-formId");

        var billingTypeDropDownList = $("#" + formId + " .billing-type");

        billingTypeDropDownList.empty();
        if (billingTypeDropDownList.hasClass("select2-default")) billingTypeDropDownList.trigger('change.select2');


        $.ajax({
            type: "POST",
            url: 'Billing/GetBillingType',
            dataType: "json",
            data: { providerId: elem.val() },
            success: function (result) {
                if (result.Success) {

                    $.each(result.data, function (i, item) {

                        billingTypeDropDownList.append($('<option>', {
                            value: item.Value,
                            text: item.Text
                        }));
                    });

                    if (billingTypeDropDownList.hasClass("select2-default")) billingTypeDropDownList.trigger('change.select2');

                }
                else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {

                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    // fill event dropdownlist with event of selected season and selected category
    fillEventCategory: function () {
        var elem = $(this);

        var formId = elem.attr("data-formId");
        var seasonId = $("#" + formId + " .season").val();
        var eventId = $("#" + formId + " .event").attr("data-default");

        var eventDropDownList = $("#" + formId + " .event");

        eventDropDownList.empty();
        if (eventDropDownList.hasClass("select2-default")) eventDropDownList.trigger('change.select2');

        if (seasonId == "") return;
        if (elem.val() == "") return;

        $.ajax({
            type: "POST",
            url: 'Event/GetEventByCategory',
            dataType: "json",
            data: { seasonId: seasonId, categoryId: elem.val() },
            success: function (result) {

                if (result.Success) {

                    eventDropDownList.empty();

                    $.each(result.data, function (i, item) {
                        
                        eventDropDownList.append($('<option>', {
                            value: item.EventId,
                            text: item.EventName,
                            selected: eventId == item.EventId
                        }));
                    });

                    if (eventDropDownList.hasClass("select2-default")) eventDropDownList.trigger('change.select2');

                }
                else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {

                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    // fill event dropdownlist with event of selected season
    fillEvent: function () {
        var elem = $(this);
        var formId = elem.attr("data-formId");

        var eventId = $("#" + formId + " .event").attr("data-default");

        var eventDropDownList = $("#" + formId + " .event");

        eventDropDownList.empty();
        if (eventDropDownList.hasClass("select2-default")) eventDropDownList.trigger('change.select2');

        if (elem.val() == "") return;

        $.ajax({
            type: "POST",
            url: 'Event/GetEventSteps',
            dataType: "json",
            data: { eventId: elem.val() },
            success: function (result) {

                eventDropDownList.empty();

                $.each(result, function (i, item) {
                    eventDropDownList.append($('<option>', {
                        value: item.EventId,
                        text: item.EventName,
                        selected: eventId == item.EventId
                    }));
                });

                if (eventDropDownList.hasClass("select2-default")) eventDropDownList.trigger('change.select2');

            },
            error: function () {

                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    fillEventForm: function () {
        var elem = $(this);
        var form = elem.parents("div[class^='billing']");
        var eventId = elem.attr("data-eventId");
        var events = $("#" + eventId);

        $.ajax({
            type: "POST",
            url: 'Event/GetEventSteps',
            dataType: "json",
            data: { eventId: elem.val() },
            success: function (result) {
                events.empty();

                $.each(result, function (i, item) {
                    events.append($('<option>', {
                        value: item.EventId,
                        text: item.EventName
                    }));
                });

            },
            error: function () {

                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    // generate reports
    generateReports: function () {
        if (!$("#generate-reports-form").valid()) return;

        var eventId = $("#generate-reports-form .event").val();
        var providerId = $("#generate-reports-form .provider").val();
        var billingType = $("#generate-reports-form .billing-type").val();
        var format = $("#generate-reports-form .format").val();

        $.ajax({
            type: "POST",
            url: 'Billing/GenerateReport',
            dataType: "json",
            data: { eventId: eventId, providerId: providerId, billingType: billingType, format: format },
            success: function (result) {

                if (result.Success) {

                    if (!window.downloadFile.isChrome) {
                        window.open("File/GetFileByName?name=" + decodeURIComponent(result.data.FileName), '_blank');
                    }
                    else {
                        window.downloadFile(decodeURIComponent(result.data.FileUrl));
                    }

                    site.successMessage(resourcesMessages.BillingReportSucceed);
                }
                else {
                    site.errorMessage(resourcesMessages.BillingReportFailed);
                }
                $(".generate-reports-modal").modal('hide');
            },
            error: function () {
                $(".generate-reports-modal").modal('hide');
                site.errorMessage(resourcesMessages.BillingReportFailed);
            }
        });
    },

    // custom format jqGrid Cell "Active
    formatActiveCell: function (cellvalue, options, rowobject) {

        var checked = cellvalue ? 'checked="checked"' : "";

        var disabled = _billings.params.hasPermissionSetActive ? "" : " disabled=\"disabled\"";

        return '<label class="switch-label" style="vertical-align: -webkit-baseline-middle;" >' +
            '<input type="checkbox" ' + checked + disabled + ' class="ace ace-switch ace-switch-6 btn-rotate" value="' + options.rowId + '" onclick="_billings.toggleActive(this)" />' +
            '<span class="lbl"></span>' +
            '</label>';
    },

    // On click on Active checkbox
    toggleActive: function (elem) {

        var checkbox = $(elem);

        $.ajax({
            type: "POST",
            url: 'Billing/SetActive',
            dataType: "json",
            data: { billingId: checkbox.val(), isActive: checkbox.is(":checked") },
            success: function (result) {
                if (!result.Success) {
                    _billings.rollbackSetActive(checkbox);
                }
            },
            error: function () {
                _billings.rollbackSetActive(checkbox);
            }
        });

    },

    // Rollback active checkbox check
    rollbackSetActive: function (checkbox) {
        if (checkbox.is(":checked")) {
            checkbox.removeAttr('checked');
        }
        else {
            checkbox.attr('checked', 'checked');
        }
        site.errorMessage(resourcesMessages.ErrorOccured, null);
    },

    // custom format jqGrid Cell "BillingType"
    formatBillingTypeCell: function (cellvalue, options, rowobject) {

        switch (cellvalue) {
            case 1:
                return resources.BillingType_OffreMainDOEuvre;
            case 2:
                return resources.BillingType_OffreGlobale;
            case 3:
                return resources.BillingType_OffreForfaitaire;
            case 4:
                return resources.BillingType_OffreVacataires;
        }
        return '';
    },

    // custom format jqGrid Cell "Action"
    formatActionCell: function (cellvalue, options, rowobject) {
        var isActive = rowobject[1];
        var isOffreMainDOEuvre = rowobject[3] == 1;
        var providerName = escape(rowobject[4]);
        var isValid = rowobject[8];

        var html = "";
        if (site.hasPermission(right.Billing_Edit)) {
            html = "<button class='btn btn-circle btn-primary' onclick='_billings.preRempEdit(" + options.rowId + ");'><i type='button' class='fa fa-pencil'></i></button>";
        }
        if (isOffreMainDOEuvre && isActive && isValid) {
            html += '<button class="btn btn-circle btn-primary" onclick="_billings.PreRempQuota(\'' + providerName + '\','  + options.rowId + '); "><i type="button" class="fa fa-percent"></i></button>';
        }
        return html;
    },
    /**Actions */
    delete: function () {
        alert("quota ");
    },

    // set quota for a billing
    PreRempQuota: function (providerName, billingId) {
        quotaBilling.initForBilling(providerName, billingId);
    },

    gridComplete: function () {
        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },

    // load grid again
    gridReload: function () {
        var data = $("#search").serialize();

        $("#JqGrid").jqGrid('setGridParam', {
            url: "Billing/Databind?" + data,
            page: 1
        }).trigger("reloadGrid");
    },


    preRempAdd: function () {
        $("#addForm")[0].reset();
        $("#addForm [id*=ProviderId]").select2("val", "");
        $("#addForm [id*=ReferentId]").select2("val", "");
        $('#addForm .billing-active').prop('checked', false);
        site.initAjaxSelect();
        site.showForm('#addForm', { container: ".main-container" });
        _billings.bindBillingProfileTemplateAction("addForm");
        _billings.clearSpecializedReportBilling();
    },

    changeBillingType: function (formId) {
        _billings.bindBillingProfileTemplateAction(formId);
        var type = $('#' + formId + ' [id*=BillingTypeId]').val();
        var form = $('#' + formId);
        var specializedBillingReport = form.find('.specialized-billing-report');
        var specializedBillingProfiles = form.find('.specialized-billing-profiles');

        var billingWorkforce = specializedBillingReport.find('.billing-workforce');
        var billingGlobal = specializedBillingReport.find('.billing-global');
        var billingForfait = specializedBillingReport.find('.billing-forfait');
        var billingFreelancer = specializedBillingReport.find('.billing-freelancer');

        var billingProfileWorkforce = specializedBillingProfiles.find('.billing-profile-workforce');
        var billingProfileGlobal = specializedBillingProfiles.find('.billing-profile-global');
        var billingProfileForfait = specializedBillingProfiles.find('.billing-profile-forfait');
        var billingProfileFreelancer = specializedBillingProfiles.find('.billing-profile-freelancer');

        billingWorkforce.hide();
        billingProfileWorkforce.hide();

        billingGlobal.hide();
        billingProfileGlobal.hide();

        billingForfait.hide();
        billingProfileForfait.hide();

        billingFreelancer.hide();
        billingProfileFreelancer.hide();

        if (type == 1) {
            billingWorkforce.show();
            billingProfileWorkforce.show();
        } else if (type == 2) {
            billingGlobal.show();
            billingProfileGlobal.show();
        } else if (type == 3) {
            billingForfait.show();
            billingProfileForfait.show();
        } else if (type == 4) {
            billingFreelancer.show();
            billingProfileFreelancer.show();
        }
    },

    add: function () {
        if (!$("#addForm").valid()) return;

        if (!_billings.anyBillingProfile("addForm")) {
            site.errorMessage(resourcesMessages.MissingBillingProfile);
            return;
        }


        _billings.serializeBillingProfile("addForm", "AddForm");
        var data = $("#addForm").serialize();
        data += "&AddForm.Active=" + $("#addForm .billing-active").is(":checked");
        $.ajax({
            type: "POST",
            url: 'Billing/Add',
            dataType: "json",
            data: data,
            traditional: true,
            el: "#addForm",
            success: function (data) {
                if (data.Success) {
                    site.successMessage(resources.ValidationSuccess);
                    _billings.gridReload();
                    $("#addForm .cancel").trigger("click");
                } else {
                    site.errorMessage(resourcesMessages.ErrorAddBilling, data.Exception);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
            }
        });
        
    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });
        _billings.clearSpecializedReportBilling();
        $.ajax({
            type: "POST",
            url: 'Billing/BindBillingForm',
            dataType: "json",
            el: "#editForm",
            data: { id: id },
            traditional: true,
            success: function (billing) {
                
                $('#EditForm_BillingId').val(billing.BillingId);
                $('#editForm .billing-active').prop('checked', billing.Active);
                $('#editForm .provider-id').each(function () { $(this).val(billing.ProviderId); });
               
                $('#EditForm_ReferentId').val(billing.ReferentId);
                $('#EditForm_Name').val(billing.Name);
                $('#EditForm_ProviderName').val(billing.ProviderName);

                $('#editForm .billing-type-id').each(function () { $(this).val(billing.BillingTypeId); });

                $('#EditForm_Definition').val(billing.Definition);
                if (billing.BillingTypeId == 1) {
                    $("#editForm .billing-workforce").show();
                    $("#editForm .billing-profile-workforce").show();

                    $('#EditForm_WorkforceValidityStartDate').val(billing.WorkforceValidityStartDate);
                    $('#EditForm_WorkforceValidityEndDate').val(billing.WorkforceValidityEndDate);
                    $('#EditForm_NightHoursStartId').val(billing.NightHoursStartId);
                    $('#EditForm_NightHoursEndId').val(billing.NightHoursEndId);
                    $.each(billing.BillingProfileWorkforceList, function (i, bpw) {
                        _billings.bindBillingProfile("editForm", bpw);
                    });
                    _billings.initValidators("billing-profile-workforce");
                } else if (billing.BillingTypeId == 2) {
                    $("#editForm .billing-global").show();
                    $("#editForm .billing-profile-global").show();

                    $('#EditForm_GlobalAmount').val(billing.GlobalAmount);

                    $('#editForm .season').val(billing.GlobalSeasonId);
                    $('#editForm .category').attr("data-default", billing.GlobalCategoryId);
                    $('#editForm .event').attr("data-default", billing.GlobalEventId);
                    
                    $("#editForm .season").change();

                    $('#editForm .category').empty();
                    $('#editForm .event').empty();

                    $.each(billing.BillingProfileGlobalList, function (i, bpg) {
                        _billings.bindBillingProfile("editForm", bpg);
                    });
                    _billings.initValidators("billing-profile-global");
                } else if (billing.BillingTypeId == 3) {
                    $("#editForm .billing-forfait").show();
                    $("#editForm .billing-profile-forfait").show();

                    $('#EditForm_ForfaitAmount').val(billing.ForfaitAmount);

                    $('#editForm .season').val(billing.ForfaitSeasonId);
                    $('#editForm .category').attr("data-default", billing.ForfaitCategoryId);
                    $('#editForm .event').attr("data-default", billing.ForfaitEventId);

                    $("#editForm .season").change();

                    $.each(billing.BillingProfileForfaitList, function (i, bpf) {
                        _billings.bindBillingProfile("editForm", bpf);
                    });
                    _billings.initValidators("billing-profile-forfait");
                } else if (billing.BillingTypeId == 4) {
                    $("#editForm .billing-freelancer").show();
                    $("#editForm .billing-profile-freelancer").show();

                    $('#EditForm_FreelancerValidityStartDate').val(billing.FreelancerValidityStartDate);
                    $('#EditForm_FreelancerValidityEndDate').val(billing.FreelancerValidityEndDate);
                    $('#EditForm_FreelancerAmount').val(billing.FreelancerAmount);
                    $.each(billing.BillingProfileFreelancerList, function (i, bpfr) {
                        _billings.bindBillingProfile("editForm", bpfr);
                    });
                    _billings.initValidators("billing-profile-freelancer");
                }

                var createdby = $("#editForm").find('.createdby');
                createdby.html("");
                if (billing.CreatedBy != null) {
                    var creator = resourcesMessages.CreateBy.replace("{0}", billing.CreatedBy.LastName + " " + billing.CreatedBy.FirstName + " (" + billing.CreatedBy.Login + ")").replace("{1}", billing.CreationDate);
                    createdby.html(creator);
                }

                var updatedby = $("#editForm").find('.updatedby');
                updatedby.html("");
                if (billing.LastUpdatedBy != null) {
                    var updater = resourcesMessages.LastUpdateBy.replace("{0}", billing.LastUpdatedBy.LastName + " " + billing.LastUpdatedBy.FirstName + " (" + billing.LastUpdatedBy.Login + ")").replace("{1}", billing.LastUpdateDate);
                    updatedby.html(updater);
                }

                _billings.bindBillingProfileTemplateAction("editForm");
            }
        });
    },

    clearSpecializedReportBilling: function () {
        $(".billing-workforce").hide();
        $(".billing-profile-workforce").hide();
        $(".billing-global").hide();
        $(".billing-profile-global").hide();
        $(".billing-forfait").hide();
        $(".billing-profile-forfait").hide();
        $(".billing-freelancer").hide();
        $(".billing-profile-freelancer").hide();

        $(".billing-profile-workforce .table-bpw tbody tr").remove();
        $(".billing-profile-global .table-bpg tbody tr").remove();
        $(".billing-profile-forfait .table-bpfo tbody tr").remove();
        $(".billing-profile-freelancer .table-bpfr tbody tr").remove();
    },

    // edit a billing
    edit: function () {
        if (!$("#editForm").valid()) return;


        if (!_billings.anyBillingProfile("editForm")) {
            site.errorMessage(resourcesMessages.MissingBillingProfile);
            return;
        }

        _billings.serializeBillingProfile("editForm", "EditForm");
        var data = $("#editForm").serialize();
        data += "&EditForm.Active=" + $("#editForm .billing-active").is(":checked");


        console.log("data:");
        console.log(data);

        $.ajax({
            type: "POST",
            url: 'Billing/Edit',
            dataType: "json",
            data: data,
            traditional: true,
            el: "#editForm",
            success: function (data) {
                if (data.Success) {
                    site.successMessage(resources.ValidationSuccess);
                    _billings.gridReload();
                    $("#editForm .cancel").trigger("click");
                } else {
                    site.errorMessage(data.message, data.Exception);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
            }
        });
        
    },

    bindBillingProfile: function (formId, bp) {
        var billingTypeId = $('#' + formId + ' [id*=BillingTypeId]').val();
        var type = "";
        var trToAppend = "";

        var tbody = ""
        if (billingTypeId == 1) {
            trToAppend = _billings.rowBillingProfileTemplates.BillingProfileWorkforce.clone();
            tbody = $("#" + formId + " .billing-profile-workforce table tbody");
            type = "";
        } else if (billingTypeId == 2) {
            trToAppend = _billings.rowBillingProfileTemplates.BillingProfileGlobal.clone();
            tbody = $("#" + formId + " .billing-profile-global table tbody");
            type = "";
        } else if (billingTypeId == 3) {
            trToAppend = _billings.rowBillingProfileTemplates.BillingProfileForfait.clone();
            tbody = $("#" + formId + " .billing-profile-forfait table tbody");
            type = "";
        } else if (billingTypeId == 4) {
            trToAppend = _billings.rowBillingProfileTemplates.BillingProfileFreelancer.clone();
            tbody = $("#" + formId + " .billing-profile-freelancer table tbody");
            type = "";
        }

        if (bp.CantBeDeletedHaAssignment) {
            trToAppend.find("button.btn-delete").switchClass('btn-delete', 'btn-delete-disabled').switchClass('text-danger', 'btn-disabled').click(function () {
                site.simpleErrorMessage(resourcesMessages.HasAssignementBillingDataAttached);
            });
            
        } else {
            trToAppend.find("button.btn-delete").click(function () {
                trToAppend.remove();
            });
        }

        trToAppend.find("[data-billing-profile-attribute='BillingProfileId']").val(bp.BillingProfileId);
        trToAppend.find("[data-billing-profile-attribute='Name']").val(bp.Name);
        trToAppend.find("[data-billing-profile-attribute='InOutType']").val(bp.InOutType);
        trToAppend.find("[data-billing-profile-attribute='ContractHours']").val(moment(bp.ContractHours).format('HH:mm'));
        trToAppend.find("[data-billing-profile-attribute='SignStartTime']").val(bp.SignStartTime);
        trToAppend.find("[data-billing-profile-attribute='OffsetStartTime']").val(moment(bp.OffsetStartTime).format('HH:mm'));
        trToAppend.find("[data-billing-profile-attribute='SignEndTime']").val(bp.SignEndTime);
        trToAppend.find("[data-billing-profile-attribute='OffsetEndTime']").val(moment(bp.OffsetEndTime).format('HH:mm'));

        if (billingTypeId == 1) { // BillingProfileWorkforce
            trToAppend.find("[data-billing-profile-attribute='NormalDayRate']").val(bp.NormalDayRate);
            trToAppend.find("[data-billing-profile-attribute='NormalNightRate']").val(bp.NormalNightRate);
            trToAppend.find("[data-billing-profile-attribute='SundayDayRate']").val(bp.SundayDayRate);
            trToAppend.find("[data-billing-profile-attribute='SundayNightRate']").val(bp.SundayNightRate);
            trToAppend.find("[data-billing-profile-attribute='HolidayDayRate']").val(bp.HolidayDayRate);
            trToAppend.find("[data-billing-profile-attribute='HolidayNightRate']").val(bp.HolidayNightRate);
        } else if (billingTypeId == 2) { // BillingProfileGlobal
            trToAppend.find("[data-billing-profile-attribute='Effective']").val(bp.Effective);
        } else if (billingTypeId == 3) { // BillingProfileForfait

        } else if (billingTypeId == 4) { // BillingProfileFreelancer
            trToAppend.find("[data-billing-profile-attribute='ForfaitRate']").val(bp.ForfaitRate);
        }

        tbody.append(trToAppend);
    },

    getBillingProfileTypeName: function (billingTypeId) {
        var billingProfileType = "";
        if (billingTypeId == 1) {
            billingProfileType = "workforce";
        } else if (billingTypeId == 2) {
            billingProfileType = "global";
        } else if (billingTypeId == 3) {
            billingProfileType = "forfait";
        } else if (billingTypeId == 4) {
            billingProfileType = "freelancer";
        }

        return billingProfileType;
    },

    anyBillingProfile: function (formId) {
        var billingTypeId = $('#' + formId + ' [id*=BillingTypeId]').val();

        var billingProfileType = _billings.getBillingProfileTypeName(billingTypeId);

        var rowsToSerialize = $('#' + formId + ' .billing-profile-' + billingProfileType + ' table tbody tr');

        console.log("rowsToSerialize.length=" + rowsToSerialize.length);

        return rowsToSerialize.length > 0;
    },

    serializeBillingProfile: function (formId, modelName) {
        var billingTypeId = $('#' + formId + ' [id*=BillingTypeId]').val();

        var billingProfileType = _billings.getBillingProfileTypeName(billingTypeId);

        var rowsToSerialize = $('#' + formId + ' .billing-profile-' + billingProfileType + ' table tbody tr');
        var formName = "";

        var bpBillingProfileId_NAME = "].BillingProfileId";
        var bpName_NAME = "].Name";
        var bpInOutType_NAME = "].InOutType";
        var bpContractHours_NAME = "].ContractHours";
        var bpSignStartTime_NAME = "].SignStartTime";
        var bpOffsetStartTime_NAME = "].OffsetStartTime";
        var bpSignEndTime_NAME = "].SignEndTime";
        var bpOffsetEndTime_NAME = "].OffsetEndTime";

        // BillingProfileWorkforce
        var bpwNormalDayRate_NAME = "].NormalDayRate";
        var bpwNormalNightRate_NAME = "].NormalNightRate";
        var bpwSundayDayRate_NAME = "].SundayDayRate";
        var bpwSundayNightRate_NAME = "].SundayNightRate";
        var bpwHolidayDayRate_NAME = "].HolidayDayRate";
        var bpwHolidayNightRate_NAME = "].HolidayNightRate";

        // BillingProfileGlobal
        var bpgEffective_NAME = "].Effective";

        // BillingProfileForfait

        // BillingProfileFreelancer
        var bpfrForfaitRate_NAME = "].ForfaitRate";

        for (var i = 0; i < rowsToSerialize.length; i++) {
            if (billingTypeId == 1) { // BillingProfileWorkforce
                formName = modelName + ".BillingProfileWorkforceList[";
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='NormalDayRate']").attr("name", formName + i + bpwNormalDayRate_NAME);
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='NormalNightRate']").attr("name", formName + i + bpwNormalNightRate_NAME);
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='SundayDayRate']").attr("name", formName + i + bpwSundayDayRate_NAME);
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='SundayNightRate']").attr("name", formName + i + bpwSundayNightRate_NAME);
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='HolidayDayRate']").attr("name", formName + i + bpwHolidayDayRate_NAME);
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='HolidayNightRate']").attr("name", formName + i + bpwHolidayNightRate_NAME);
            } else if (billingTypeId == 2) { // BillingProfileGlobal
                formName = modelName + ".BillingProfileGlobalList[";
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='Effective']").attr("name", formName + i + bpgEffective_NAME);
            } else if (billingTypeId == 3) { // BillingProfileForfait
                formName = modelName + ".BillingProfileForfaitList[";
            } else if (billingTypeId == 4) { // BillingProfileFreelancer
                formName = modelName + ".BillingProfileFreelancerList[";
                $(rowsToSerialize[i]).find("[data-billing-profile-attribute='ForfaitRate']").attr("name", formName + i + bpfrForfaitRate_NAME);
            }

            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='BillingProfileId']").attr("name", formName + i + bpBillingProfileId_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='Name']").attr("name", formName + i + bpName_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='InOutType']").attr("name", formName + i + bpInOutType_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='ContractHours']").attr("name", formName + i + bpContractHours_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='SignStartTime']").attr("name", formName + i + bpSignStartTime_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='OffsetStartTime']").attr("name", formName + i + bpOffsetStartTime_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='SignEndTime']").attr("name", formName + i + bpSignEndTime_NAME);
            $(rowsToSerialize[i]).find("[data-billing-profile-attribute='OffsetEndTime']").attr("name", formName + i + bpOffsetEndTime_NAME);

        }
    },
    initValidators: function (gridName) {
        $("#" + gridName + " tbody tr input.form-control").each(function (index, element) {
            element.name = element.name + Math.random();
            ($("#" + gridName + " tbody tr span")[index]).setAttribute("data-valmsg-for", element.name);
        });
    }
};
var quotaBilling = {

    IsDefineMode: false,
    BillingId: 0,
    ProviderName: "",

    init: function () {
        quotaBilling.loadTargetSaison();
        $("#LoadProfiles").click(quotaBilling.loadProfiles);
        $("#ReportBillingQuota").click(quotaBilling.reportQuotas);
        $("#eventSource").click(quotaBilling.showQuotaSourceColumn);
        $("#saveBtn").click(quotaBilling.save);
        $('.quota-target input').prop("disabled", false);
        quotaBilling.ProviderName = "";
        quotaBilling.Setlabels();
        IsDefineMode = true;
        quotaBilling.ClearGrid();
        quotaBilling.ClearSelect();
        quotaBilling.EvalSaveButtonState();
        quotaBilling.EvalSearchButtonState();
    },

    initForBilling: function (providerName, billingId) {
        quotaBilling.BillingId = billingId;
        quotaBilling.ProviderName = providerName;
        $("#table-billing-quotas-body tr").remove();
        quotaBilling.EvalSaveButtonState()
        site.showForm('#BillingQuotasView', { container: ".main-container" });
        quotaBilling.ClearSelect();

        $("#eventSource").prop('disabled', true);
        $("#seasonSource").prop('disabled', true);
        $("#eventTarget").prop('disabled', true);
        quotaBilling.EvalSearchButtonState();
        quotaBilling.EvalReportBillingState();
    },

    Setlabels: function () {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'NoStadium') {
                    $("#labelSaisonTarget").html(resources.SaisonTarget_noStadium);
                    $("#labelEventTarget").html(resources.EventTarget_noStadium);
                    $("#labelSaisonSource").html(resources.SaisonSource_noStadium);
                    $("#labelEventSource").html(resources.EventSource_noStadium);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        })
    },

    // Dropdown list
    loadTargetSaison: function () {
        $.ajax({
            type: "GET",
            url: "/Billing/GetSeason",
            success: function (result) {
                if (result.Success) {
                    var s = '<option value="0" selected ></option>';
                    $.each(result.data, function (i, item) {
                        s += '<option value="' + item.Id + '">' + item.Name + '</option>';
                    });


                    $("#seasonTarget").html(s);
                    var saisonId = $('#seasonTarget').val();
                    if (saisonId == null && saisonId == '0')
                        quotaBilling.loadTargetEvent();
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    loadTargetEvent: function () {

        $("#table-billing-quotas-body tr").remove();
        quotaBilling.EvalSaveButtonState();
        var saisonId = $('#seasonTarget').val();
        $.ajax({
            type: "GET",
            url: "/Billing/GetEventWithoutThis",
            data: { eventParentId: saisonId, eventId: null },
            success: function (result) {
                if (result.Success) {
                    var s = '<option value="0" selected ></option>';
                    $.each(result.data, function (i, item) {
                        s += '<option value="' + item.Id + '">' + item.Name + '</option>';
                    });

                    $("#eventTarget").html(s);
                    $("#eventTarget").prop('disabled', $("#seasonTarget").val() == "0");

                    quotaBilling.loadSourceSaison();
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    loadSourceSaison: function () {
        $("#table-billing-quotas-body tr").remove();
        quotaBilling.EvalSearchButtonState();
        $.ajax({
            type: "GET",
            url: "/Billing/GetSeason",
            success: function (result) {
                if (result.Success) {
                    var s = '<option value="0" selected ></option>';
                    $.each(result.data, function (i, item) {
                        s += '<option value="' + item.Id + '">' + item.Name + '</option>';
                    });
                    $("#seasonSource").html(s);
                    $("#seasonSource").prop('disabled', $("#eventTarget").val() == "0");
                    quotaBilling.loadSourceEvent();
                    quotaBilling.EvalSaveButtonState();
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },

    loadSourceEvent: function () {
        var saisonId = $('#seasonSource').val();
        var eventId = $('#eventTarget').val();
        $.ajax({
            type: "GET",
            url: "/Billing/GetEventWithoutThis",
            data: { eventParentId: saisonId, eventId: eventId },
            success: function (result) {
                if (result.Success) {
                    var s = '<option value="0" selected ></option>';
                    $.each(result.data, function (i, item) {
                        s += '<option value="' + item.Id + '">' + item.Name + '</option>';
                    });
                    $("#eventSource").html(s);
                    quotaBilling.EvalReportBillingState();
                    quotaBilling.EvalSearchButtonState();
                    $("#eventSource").prop('disabled', $("#seasonSource").val() == "0");
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });
    },
    // End dropdown

    // components states
    EvalQuotaSourceState: function () {
        if ($("#eventSource").val() != '0') {
            $('td:nth-child(5)').show();
            $('tr td:nth-child(5)').show();
        }
        else {
            $('td:nth-child(5)').hide();
            $('tr td:nth-child(5)').hide();
        }
    },

    EvalReportBillingState: function () {
        if ($("#eventSource").val() != '0') {
            $('#ReportBillingQuota').show();
        }
        else {
            $('#ReportBillingQuota').hide();
        }
    },

    EvalSearchButtonState: function () {
        if ($("#eventTarget").val() != '0' && $("#seasonTarget").val() != '0') {
            $('#LoadProfiles').prop('disabled', false);
            $('.quota-target input').prop("disabled", false);
        }
        else {
            $('#LoadProfiles').prop('disabled', true);
            $('#saveBtn').prop('disabled', true);
            $('.quota-target input').prop("disabled", true);
            quotaBilling.EvalSaveButtonState();
        }
    },

    EvalSaveButtonState: function () {
        if ($("#eventTarget").val() != '' && $("#seasonTarget").val() != '0' && $("#table-billing-quotas-body tr").length > 0) {
            $('#saveBtn').prop('disabled', false);
        }
        else {
            $('#saveBtn').prop('disabled', true);
        }
    },

    EvalSSelectInputState: function () {
        $('.quota-target input').prop("disabled", true);
    },
    // End components states

    ClearGrid: function () {
        if (IsDefineMode)
            $("#table-billing-quotas-body tr").remove();
    },

    ClearSelect: function () {
        $("#seasonTarget").val('0');
        $("#eventTarget").val('0');
        $("#seasonSource").val('0');
        $("#eventSource").val('0');
    },

    loadProfiles: function (e) {
        var eventSourceId = $('#eventSource').val();
        var eventTargetId = $('#eventTarget').val();
        var tableQuotas = $("#table-billing-quotas");
        $.ajax({
            type: "GET",
            url: "/Billing/LoadActiveWorkForceProfiles",
            data: { eventSourceId: eventSourceId, eventTargetId: eventTargetId, providerName: quotaBilling.ProviderName },
            success: function (result) {
                if (result.Success) {
                    $("#table-billing-quotas-body tr").remove();

                    $.each(result.data, function (i, item) {
                        var row = quotaBilling.getRowTemplate(item.ProviderName,
                            item.BillingName,
                            item.BillingProfileId,
                            item.BillingProfileName,
                            item.QuotaSourceValue,
                            item.QuotaTargetValue);
                        tableQuotas.append(row);
                    });
                    quotaBilling.EvalQuotaSourceState();
                    quotaBilling.EvalReportBillingState();
                    quotaBilling.EvalSaveButtonState();
                } else {
                    site.errorMessage(resourcesMessages.ErrorOccured);
                }
            },
            error: function () {
                site.errorMessage(resourcesMessages.ErrorOccured);
            }
        });

        e.stopImmediatePropagation();
        return false;
    },

    reportQuotas: function () {
        $('#table-billing-quotas td.quota-value').each(function (index, element) {
            $('#table-billing-quotas td.quota-target').eq(index).find("input").val($(element).find("input").val())
        })
    },

    save: function (e) {
        var eventTargetId = $('#eventTarget').val();
        var billingProfileDTOs = new Array();
        var profileIds = $("#table-billing-quotas-body .quota-profile-id :input");
        var targets = $("#table-billing-quotas-body .quota-target :input");
        var billingNames = $("#table-billing-quotas-body .quota-billingName");

        profileIds.each(function (index) {
            billingProfileDTOs[index] = {
                BillingProfileId: parseInt(profileIds[index].value),
                QuotaTargetValue: parseInt(targets[index].value),
                BillingName: billingNames[index].value,
                BillingId: 0,
                ProviderId: 0,
                ProviderName: 'Name'
            };
        });

        $.ajax({
            type: 'POST',
            url: "/Billing/SaveEventQuotas",
            data: { 'eventId': eventTargetId, 'billingProfileDTOs': billingProfileDTOs },
            success: function (data) {
                if (data.Success === true) {
                    site.successMessage(resources.ValidationSuccess);
                    site.hideForm('#BillingQuotasView', { container: ".main-container" });
                }
                else {
                    site.errorMessage(resourcesMessages.ExceptionDuringCreation, data.Exception);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
            }
        })

        e.stopImmediatePropagation();
        return false;
    },

    getRowTemplate: function (ProviderName, BillingName, BillingProfileId, BillingProfileName, QuotaSourceValue, QuotaTargetValue) {
        var templateId = Math.random();
        return "<tr data-template>"
            + "<td class='quota-profile-id'  style='display: none;'>" + "<input class='form-control' type='hidden' name='BillingProfileId" + templateId + "'  value='" + BillingProfileId + "'  required/>  </td>"
            + "<td class='quota-type'>" + ProviderName + "</td>"
            + "<td class='quota-billingName'>" + BillingName + "</td>"
            + "<td class='quota-type'>" + BillingProfileName + "</td>"
            + "<td class='quota-value'>" + "<input class='form-control' type='number' name='QuotaSourceValue" + templateId + "'  step='1' min='0'   value=" + QuotaSourceValue + "  required disabled/>  </td>"
            + "<td class='quota-target'>" + "<input class='form-control' type='number' name='QuotaTargetValue" + templateId + "'  step='1' min='0'  value=" + QuotaTargetValue + " required/> "
            + "<span class='field-validation-valid text-danger' data-valmsg-for='QuotaTargetValue" + templateId + "' data-valmsg-replace='true'></span></td>"
            + "</tr>";
    },
};
var board = {

    init: function () {

        board.chart = window.nv.models.pieChart()
               .x(function (d) { return d.label })
               .y(function (d) { return d.value })
               .labelThreshold(.05)
               .color(['#8fcf55', '#4c81eb', '#333333', '#fb3a3b', '#f9c35f'])
               .noData("Aucune données")
               .showLabels(true);
        $("#Search_EventId").change(board.searchEventChange);
        $(".actions .submit").click(board.loadChart);
        $('#Search_EventId').trigger("change");


    },

    loadChart: function () {
        $("#chart svg g").remove();
        var params = $("#search").serialize();
        $.ajax({
            type: "POST",
            dataType: "json",
            data: params,
            el: "#chart",
            url: "Board/DataChart",
            success: function (result) {
                d3.select("#chart svg")
                .datum(result.data)
                .transition().duration(1200)
                .call(board.chart);
            }
        });
        return chart;
    },

    drawChart: function () {
        window.nv.addGraph(board.loadChart);
    },

    searchEventChange: function () {
        var model = {
            eventId: $("#Search_EventId").val()
        };
        $.ajax(
            {
                type: "POST",
                url: "Assignment/BindUnitField",
                traditional: true,
                async: true,
                el: "#ouId",
                data: model,
                dataType: "json",
                success: function (result) {
                    $('#Search_UnitId').html("");
                    var tr = '';
                    for (var i = 0; i < result.roles.length; i++) {
                        var y = result.roles[i];
                        tr = tr + '<option value="' + y.OrganizationUnitId + '">' + y.Name + '</option>';
                    }
                    $('#Search_UnitId').html(tr);
                    $('.actions .submit').trigger("click");
                }
            });
    }

};
var category = {

    params: {
        messageAtLeastOneCategorySelected: "",
        imageSizeRestriction: "",
    },

    init: function (params) {
        $("#search .submit").click(category.gridReload);
        $(".grid-header .delete").click(category.deleteAll);

        $(".grid-header .submit").click(category.preRempAdd);

        $("#editForm, #addFormCategory").submit(function () { return false; });

        $("#editForm .submit").click(category.edit);

        $("#addFormCategory .submit").click(category.add);
        $("#addFormCategory .cancel").click(function () {
            site.hideForm('#addFormCategory', { container: ".main-container" });
        });

        $.extend(this.params, params);
        file.deleteActivated = true;
        file.init();

        $("#addFormCategory input[name='Category.Picture']").val(file.fileUpload);
        $("#editForm input[name='CategoryEdit.Picture']").val(file.fileUpload);

        $.ajax({
            type: "GET",
            url: 'Parameter/GetImageZoneSizeRestriction',
            dataType: "json",
            success: function (ImageZoneSizeRestriction) {
                if (ImageZoneSizeRestriction !== "") {
                    events.params.imageSizeRestriction = ImageZoneSizeRestriction;
                }
            }
        });

        $("input[type='file'].to-base-64").change(function () {
            var input = $(this);
            var id = input.attr("id");
            input = $("#" + id + ".to-base-64"); // avec juste $(this), il est impossible de trouver les autres éléments ci-dessous (alors que ça marche très bien pour les évènements), avec cette combine ici, ça fonctionne comme ça devrait...
            var div = $(input.parents(".img-wrapper"));
            var hidden = $(div.find("input[type='hidden'].img-base-64"));
            var image = div.find("img.img-picture")[0];

            var dimension = events.params.imageSizeRestriction;

            image.onloadend = function () {
                var parameterMaxWidth = dimension.split('x')[0];
                var parameterMaxHeight = dimension.split('x')[1];
                file.resizeBase64(div, image, hidden, parameterMaxWidth, parameterMaxHeight);
                file.resizeOnScreen(image, parameterMaxWidth, parameterMaxHeight);
            };

        });
    },


    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });
        $("#CategoryEdit_Name").rules("add", "checkUniciteCategory");
        file.resetPicture("#editForm");

        $.ajax({
            type: "POST",
            url: 'Category/BindCategoryForm',
            dataType: "json",
            el: "#editForm",
            data: { id: id },
            traditional: true,
            success: function (category) {
                $('#CategoryEdit_CategoryId').val(category.CategoryId);
                $('#CategoryEdit_Name').val(category.Name);
                $('#CategoryEdit_Description').val(category.Description);
                if (category.HasImage) {
                    file.setPicture("#editForm", category.CategoriesImageFolderPath + category.ImageName);
                    $('.nameFile').val(category.ImageName)
                }
            }
        });

    },

    preRempAdd: function () {
        $("#addFormCategory")[0].reset();
        site.initAjaxSelect();
        site.showForm('#addFormCategory', { container: ".main-container" });
        file.resetPicture("#addFormCategory");
    },


    add: function () {
        $("#addFormCategory #Category_Name").rules("add", "checkUniciteCategory");

        if ($("#addFormCategory").valid()) {
            var data = $("#addFormCategory").serialize();
            $.ajax({
                type: "POST",
                url: 'Category/Add',
                dataType: "json",
                data: data,
                el: "#addFormCategory",
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                    } else {
                        site.errorMessage(resourcesMessages.MessageError, ret.Exception);
                    }

                    category.gridReload();
                    $("#addFormCategory .cancel").trigger("click");

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },




    edit: function () {
        $("#editForm #CategoryEdit_Name").rules("add", "checkUniciteCategory");
        if ($("#editForm").valid()) {

            var data = $("#editForm").serialize();

            $.ajax({
                type: "POST",
                url: 'Category/Edit',
                dataType: "json",
                data: data,
                traditional: true,
                el: "#editForm",
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        category.gridReload();
                        $("#editForm .cancel").trigger("click");
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    deleteAll: function () {

        var ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) {
            jAlert(category.params.messageAtLeastOneCategorySelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'Category/DeleteSelected',
                            dataType: "json",
                            data: { categoryIds: s },
                            traditional: true,
                            el: jQuery("#JqGrid"),
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                                $("#JqGrid").trigger("reloadGrid");
                            }
                        });
                }
            });
        }
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var imageName = '';
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var cl = ids[i];

            if (data.HasPicture == "true") {
                imageName = '<img src=' + data.CategoriesImageFolderPath + data.ImageName + '?width=17&height=17 />';
            }
            var edProv = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='category.preRempEdit(" + cl + ");' ><i class='fa fa-pencil'></i></button>";
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv, ImageName: imageName });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },


    gridReload: function () {
        var nameMask = jQuery("#search_name").val();

        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Category/DataBind"
                + "?name=" + nameMask,
            page: 1
        }).trigger("reloadGrid");
    }
}
var customContent = {

    params: {
        updateUrl: 'CustomContent/Update'
    },

    init: function (params) {

        $(document).ready(function () {
            $('.wysiwyg-editor')
                .trumbowyg({
                    btnsDef: {
                        // Create a new dropdown
                        image: {
                            dropdown: ['insertImage', 'base64'],
                            ico: 'insertImage'
                        }
                    },
                    // Redefine the button pane
                    btns: [
                        ['viewHTML'],
                        ['formatting'],
                        ['strong', 'em', 'del'],
                        ['superscript', 'subscript'],
                        ['link'],
                        ['image'], // Our fresh created dropdown
                        ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                        ['unorderedList', 'orderedList'],
                        ['horizontalRule'],
                        ['removeformat'],
                        ['fullscreen']
                    ],
                    plugins: { resizimg: {} },
                    disabled: site.hasPermission(right.CustomContent_Update) === false
                });

            $(".container-title.title-collapse").click(function () {
                $(this).siblings(".form-container").toggle();
            });
        });


        $("#customContentHomeForm").find("input[data-action='update']").click(function () {
            var parentForm = $(this).closest(".custom-content-home-form");
            var code = parentForm.find("input[name='contentcode']").val();
            var language = parentForm.find("input[name='contentlanguage']").val();
            var value = encodeURIComponent(parentForm.find("textarea[name='contentvalue']").val());
            var customContentModel = {
                ContentCode: code,
                ContentValue: value,
                ContentLanguage: language
            };
            customContent.update(customContentModel);
        })
    },

    update: function (customContentModel) {
        $.ajax({
            type: "POST",
            url: customContent.params.updateUrl,
            dataType: "json",
            data: customContentModel,
            traditional: true,
            success: function (ret) {
                if (ret.success) {
                    site.successMessage(ret.message);
                } else {
                    site.errorMessage(ret.message, ret.Exception);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
            }
        });
    },
}
var customReport = {
    params: {
    },

    init: function (params) {
        customReport.gridReload();
        $("#validExport").click(customReport.validExport);
        $("#searchForm").submit(customReport.gridReload);
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var edProv = '<button class="btn btn-circle btn-primary"  onclick="customReport.export(\'' + cl + '\');"><i type="button" class="fa fa-download"></i></button>';
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },

    gridReload: function () {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "CustomReport/DataBind?" + data,
            page: 1
        }).trigger("reloadGrid");
    },

    export: function (reportId) {
        var item = jQuery("#JqGrid").getRowData(reportId);
        if (item.HasParameters === "true") {
            $.ajax({
                type: "POST",
                url: 'CustomReport/BindModalForm',
                dataType: "json",
                data: { "reportId": reportId },
                traditional: true,
                success: function (ret) {
                    var ExportForm = $("#ExportModalForm")[0];
                    ExportForm.innerHTML = "";
                    for (var i = 0; i < ret.length; i++) {
                        var name = ret[i].Name.substring(1, ret[i].Name.length);

                        var elem = "<div class='row'> <div class='col-lg-12'> <div class='input-group'> <span class='input-group-btn'><button class='btn btn-secondary' style='width: 150px'   type='button'>" + ret[i].Name + "</button></span>";
                        elem += "<input type='" + ret[i].Type + "'  date-format='dd/mm/yyyy' class='form-control'  data-order='" + ret[i].Order + "'  name='" + name + "' placeholder='Search for...' required></div></div></div>";
                        ExportForm.innerHTML += '<br/>' + elem;
                    }
                    if (ret.length > 0) { //check if return parameters are not null to show modal
                        $("#ExportModal").modal('show');
                    } else {
                        customReport.validExportWithId(reportId);
                    }
                },
                failure: function (ret) {
                }
            });
        } else {
            customReport.validExportWithId(reportId);
        }
    },

    validExportWithId: function (reportId) {
        var reportName = $("#JqGrid").getRowData(reportId).Name;
        customReport.Export(reportName, null);
    },
    validExport: function() {
        var parameters = [];

        var reportName = $("#JqGrid").getRowData($("#JqGrid").jqGrid('getGridParam', "selrow")).Name;
        var data = $("#ExportModalForm  input");

        for (var i = 0; i < data.length; i++) {
            parameters.push({
                "Name": data[i].name,
                "Value": data[i].value,
                "Type": data[i].type,
                "Order": data[i].getAttribute('data-order')
            });
        }

        customReport.Export(reportName, parameters);
    },
    Export: function (reportName, parameters) {
        $.ajax({
            type: "POST",
            url: 'CustomReport/ValidExportForm',
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ reportName: reportName, parameters: parameters }),
            traditional: true,
            success: function(ret) {
                if (ret.Success === true) {
                    $.get(ret.data).done(function() {
                        if (!window.downloadFile.isChrome) {
                            window.open(ret.data, '_blank');
                        } else {
                            window.downloadFile(ret.data);
                        }
                        $("#ExportModal").modal('hide');
                        site.successMessage(resourcesMessages.ExportSuccess);
                    });

                } else {
                    site.errorMessage(resourcesMessages.ExportFailed);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
            }
        });
    }
};
const AssignmentType =
{
    Individual: 1,
    Vehicle: 2,
    Guest: 3,
    Anonymous: 4,
}
var groups = {

    params: {
        loadOnce: false,
        nbColumnsTitleGrid: {
            AdminManagement: 2,
            IndividualManagement: 2,
            AssignmentPassLabels: 8 // count = AssignmentPassLabels + the rest
        },
        resources: {
            thisGroup: ""
        }
    },

    fa_icons: {
        greenOK: '<i class="fa fa-check green"></i>',
        redNOK: '<i class="fa fa-times red"></i>',
        star: '<i class="fa fa-star gold"></i>'
    },

    init: function (parameters) {
        this.params.resources.thisGroup = parameters.thisGroup;
        $(".grid-header .delete").click(groups.deleteAll);
        $(".grid-header .submit").click(groups.preRempAdd);
        $("#editForm, #addForm").submit(function () { return false; });

        $("#editForm .submit").click(groups.edit);
        $("#addForm .submit").click(groups.add);

        $(".toggle-features").click(function () {
            $('.tab-features tbody').toggle();
        });

        $(".change-label-stars").change(function () {
            var labelStars = $(this).parents(".wrapper-ddl").find("[data-label-stars]");
            groups.changeStars(labelStars, $(this).val());
        });

        $("#search").submit(groups.gridReload);
    },


    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });
        var taAccTitFeat = $('.tab-features-access-title');

        var tabAdminFeat = $('#editForm .tab-features-admin');

        var taAccFileFeat = $('.tab-features-access-file');

        taAccTitFeat.find("tbody tr[data-sub-type-row] input[data-module-input]").prop('checked', false);
        tabAdminFeat.find("tbody tr[data-module-row] input[data-sub-type-input]").prop('checked', false);
        taAccFileFeat.find("tbody tr[data-sub-type-row] input[data-module-input]").prop('checked', false);

        $.ajax({
            type: "POST",
            url: 'Group/BindGroupForm',
            dataType: "json",
            el: "#editForm",
            data: { id: id },
            traditional: true,
            success: function (group) {
                $('#GroupEditForm_GroupId').val(group.GroupId);
                $('#GroupEditForm_Name').val(group.Name);
                $('#GroupEditForm_ReadOnly').val(group.ReadOnly);
                $('#GroupEditForm_Description').val(group.Description);

                $('#GroupEditForm_GeneralRightsId').val(group.GeneralRightsId);
                $('#GroupEditForm_UnitsRightsId').val(group.UnitsRightsId);
                $('#GroupEditForm_IndividualsManagementRightsId').val(group.IndividualsManagementRightsId);
                $('#GroupEditForm_VehiclesManagementRightsId').val(group.VehiclesManagementRightsId);
                $('#GroupEditForm_SuperGroupIds').val(group.SuperGroupIds);

                $('#editForm .change-label-stars').trigger("change");

                if (group.AdministrationFeatures.length > 0) {
                    $.each(group.AdministrationFeatures, function (i, af) {
                        var afModule = af.Module;
                        var afSubType = af.SubType;
                        var adminFeatToSet = tabAdminFeat.find('tbody tr[data-module-row="' + afModule + '"] input[data-sub-type-input="' + afSubType + '"]');
                        adminFeatToSet.prop('checked', true);
                    });
                }

                if (group.AccessTitleFeatures.length > 0) {
                    $.each(group.AccessTitleFeatures, function (i, af) {
                        var afModule = af.Module;
                        var afSubType = af.SubType;
                        var accTitFeatToSet = taAccTitFeat.find('tbody tr[data-sub-type-row="' + afSubType + '"] input[data-module-input="' + afModule + '"]');
                        accTitFeatToSet.prop('checked', true);
                    });
                }

                if (group.AccessFileFeatures.length > 0) {
                    $.each(group.AccessFileFeatures, function (i, af) {
                        var afModule = af.Module;
                        var afSubType = af.SubType;
                        var accFileFeatToSet = taAccFileFeat.find('tbody tr[data-sub-type-row="' + afSubType + '"] input[data-module-input="' + afModule + '"]');
                        accFileFeatToSet.prop('checked', true);
                    });
                }
            }
        });
    },

    preRempAdd: function () {
        $("#addForm")[0].reset();
        site.initAjaxSelect();
        site.showForm('#addForm', { container: ".main-container" });
        var tabBody = $('.tab-features tbody');
        tabBody.hide();
        tabBody.html("");
        //this group doesn't exist yet, but it needs to be selectable in this dropdownlist
        if ($("#addForm .superGroupList option[value=-1]").length === 0) {
            var newOption = window.document.createElement('OPTION');
            newOption.text = '[' + groups.params.resources.thisGroup + ']';
            newOption.value = '-1';
            $("#addForm .superGroupList")[0].options.add(newOption, 0);
        }
    },

    add: function () {
        if ($("#addForm").valid()) {
            groups.serializeAdminFeatures("#addForm", "GroupAddForm");
            groups.serializeAccessTitleFeatures("#addForm", "GroupAddForm");
            groups.serializeAccessFileFeatures("#addForm", "GroupAddForm");
            var data = $("#addForm").serialize();

            $.ajax({
                type: "POST",
                url: 'Group/Add',
                dataType: "json",
                data: data,
                el: "#addForm",
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);

                        var newOption = window.document.createElement('OPTION');
                        newOption.text = ret.data.GroupName;
                        newOption.value = ret.data.GroupId;
                        $("#addForm .superGroupList")[0].options.add(newOption);
                        $("#editForm .superGroupList")[0].options.add(newOption);

                    } else {
                        site.errorMessage(resourcesMessages.MessageError, ret.Exception);
                    }

                    groups.gridReload();
                    $("#addForm .cancel").trigger("click");

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    edit: function () {
        if ($("#editForm").valid()) {
            groups.serializeAdminFeatures("#editForm", "GroupEditForm");
            groups.serializeAccessTitleFeatures("#editForm", "GroupEditForm");
            groups.serializeAccessFileFeatures("#editForm", "GroupEditForm");
            var data = $("#editForm").serialize();

            $.ajax({
                type: "POST",
                url: 'Group/Edit',
                dataType: "json",
                data: data,
                traditional: true,
                el: "#editForm",
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#addForm .superGroupList option[value=" + data.data.GroupId + "]")[0].text = data.data.GroupName;
                        $("#editForm .superGroupList option[value=" + data.data.GroupId + "]")[0].text = data.data.GroupName;
                        groups.gridReload();
                        $("#editForm .cancel").trigger("click");
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    delete: function (id) {
        jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
            var s;
            s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
            if (ok && s !== "") {
                $.ajax(
                    {
                        type: "POST",
                        url: 'Group/Delete',
                        dataType: "json",
                        data: { GroupId: id },
                        traditional: true,
                        el: jQuery("#JqGrid"),
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                                $("#addForm .superGroupList option[value=" + ret.data.GroupId + "]").remove();
                                $("#editForm .superGroupList option[value=" + ret.data.GroupId + "]").remove();
                            } else {
                                site.errorMessage(resourcesMessages.DisableProviderFailed, ret.Exception);
                            }
                            $("#JqGrid").trigger("reloadGrid");
                        }
                    });
            }
        });
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        var greenOK = '<i class="fa fa-check green"></i>';
        var redNOK = '<i class="fa fa-times red"></i>';
        var assignmentPassLabels = '<b>' + resources.AssignmentAbridgedLabel + '<br/>' + resources.PassAbridgedLabel + '</b>';
        for (var i = 0; i < ids.length; i++) {
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var cl = ids[i];
            var ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='groups.preRempEdit(" + cl + ");'><i class='fa fa-pencil'></i></button>"
                + "<button type='button' value='' class='btn btn-circle btn-primary' onclick='groups.delete(" + cl + ");'><i class='fa fa-trash'></i></button>";
            groups.convertToStars(data.AdminManagement);

            //// should receive bool datas, concat both rights
            var guestManagement = groups.converBoolToIcon(data["AssignmentFeatures.GuestManagement"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.GuestManagement"]);
            var generationFeature = groups.converBoolToIcon(data["AssignmentFeatures.GenerationFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.GenerationFeature"]);
            var importFeature = groups.converBoolToIcon(data["AssignmentFeatures.ImportFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.ImportFeature"]);
            var exportFeature = groups.converBoolToIcon(data["AssignmentFeatures.ExportFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.ExportFeature"]);
            var notificationFeature = groups.converBoolToIcon(data["AssignmentFeatures.NotificationFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.NotificationFeature"]);
            var sendByMailFeature = groups.converBoolToIcon(data["AssignmentFeatures.SendByMailFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.SendByMailFeature"]);
            var sendToAccessControlFeature = groups.converBoolToIcon(data["AssignmentFeatures.SendToAccessControlFeature"]) + "<br/>" + groups.converBoolToIcon(data["PassFeatures.SendToAccessControlFeature"]);

            var obj = {
                act: ed,
                AdminManagement: groups.convertToStars(data.AdminManagement),
                UnitsManagement: groups.convertToStars(data.UnitsManagement),

                IndividualManagement: groups.convertToStars(data.IndividualManagement),
                VehicleManagement: groups.convertToStars(data.VehicleManagement),

                AssignmentPassLabels: assignmentPassLabels,

                GuestManagement: guestManagement,
                GenerationFeature: generationFeature,
                ImportFeature: importFeature,
                ExportFeature: exportFeature,
                NotificationFeature: notificationFeature,
                SendByMailFeature: sendByMailFeature,
                SendToAccessControlFeature: sendToAccessControlFeature,
            };


            jQuery("#JqGrid").jqGrid('setRowData', ids[i], obj);

        }

        if (!groups.params.loadOnce) {
            jQuery("#JqGrid").jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders: [
                    { startColumnName: 'AdminManagement', numberOfColumns: groups.params.nbColumnsTitleGrid.AdminManagement, titleText: resources.General.toUpperCase() },
                    { startColumnName: 'IndividualManagement', numberOfColumns: groups.params.nbColumnsTitleGrid.IndividualManagement, titleText: resources.Management.toUpperCase() },
                    { startColumnName: 'AssignmentPassLabels', numberOfColumns: groups.params.nbColumnsTitleGrid.AssignmentPassLabels, titleText: resources.AccessTitle.toUpperCase() }
                ]
            });
            groups.params.loadOnce = true;
        }
    },

    convertToStars: function (data) {
        var stars = '';
        for (var j = 0; j < data; j++) {
            stars += groups.fa_icons.star;
        }

        return stars;
    },

    converBoolToIcon: function (data) { // not used yet
        return data == "true" ? groups.fa_icons.greenOK : groups.fa_icons.redNOK;
    },

    gridReload: function () {
        var data = jQuery("#search").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Group/DataBind?" + data,
            page: 1
        }).trigger("reloadGrid");
    },

    changeStars: function (el, val) {
        $(el).html("");
        //0 = No stars shown
        for (var i = 0; i < val; i++) {
            $(el).append(groups.fa_icons.star);
        }
    },

    serializeAdminFeatures: function (formId, typeForm) {
        var featuresList = $(formId).find(".tab-features-admin input[data-technical-name]");

        // reinit form
        $.each(featuresList, function (i, feature) {
            $(feature).removeAttr("name");
        });

        var formName = typeForm + ".AdministrationFeatures[";
        var featureModel_TechnicalName = "].TechnicalName";

        var cpt = 0;

        $.each(featuresList, function (i, feature) {
            if ($(feature).prop("checked") === true) {
                $(feature).attr("name", formName + cpt + featureModel_TechnicalName);
                var technicalName = $(feature).attr("data-technical-name");
                feature.value = technicalName;
                cpt++;
            }
        });
    },

    serializeAccessTitleFeatures: function (formId, typeForm) {
        var featuresList = $(formId).find(".tab-features-access-title input[data-technical-name]");

        // reinit form
        $.each(featuresList, function (i, feature) {
            $(feature).removeAttr("name");
        });

        var formName = typeForm + ".AccessTitleFeatures[";
        var featureModel_TechnicalName = "].TechnicalName";

        var cpt = 0;

        $.each(featuresList, function (i, feature) {
            if ($(feature).prop("checked") === true) {
                $(feature).attr("name", formName + cpt + featureModel_TechnicalName);
                var technicalName = $(feature).attr("data-technical-name");
                feature.value = technicalName;
                cpt++;
            }
        });
    },

    serializeAccessFileFeatures: function (formId, typeForm) {
        var featuresList = $(formId).find(".tab-features-access-file input[data-technical-name]");

        // reinit form
        $.each(featuresList, function (i, feature) {
            $(feature).removeAttr("name");
        });

        var formName = typeForm + ".AccessFileFeatures[";
        var featureModel_TechnicalName = "].TechnicalName";

        var cpt = 0;

        $.each(featuresList, function (i, feature) {
            if ($(feature).prop("checked") === true) {
                $(feature).attr("name", formName + cpt + featureModel_TechnicalName);
                var technicalName = $(feature).attr("data-technical-name");
                feature.value = technicalName;
                cpt++;
            }
        });
    }
}
var individualImport = {

    init: function () {
        $("#importMatricule").click(individualImport.downloadPatron);
    },

    downloadPatron: function () {
        if (HTMLElement.prototype.click) {
            $("#importMatriculeCsv")[0].click();
        } else {
            window.open($("#importMatriculeCsv").attr('href'));
        }
    }

}
var mailTemplate = {

    params: {
        editor: null,
        editorInit: null
    },

    init: function () {
        $(document).ready(function () {
            $("#editForm .submit").click(mailTemplate.edit);
            $("#editForm .testmail").click(mailTemplate.sendTestMail);
            $("#editForm .cancel").click(function () { site.hideForm('#editForm', { container: ".main-container" }); });

           

            $(".container-title.title-collapse").click(function () {
                $(this).siblings(".form-container").toggle();
            });

            $(".mailtemplate-change-translation").change(function () {
                mailTemplate.loadCurrentLanguageEditor(this);
            });
            mailTemplate.loadCurrentLanguageEditor($(".mailtemplate-change-translation"));
        });
    },

    loadCurrentLanguageEditor: function (divTranslations) {
        var translationLanguage = $(divTranslations).val();
        $(".mailtemplate-translations fieldset[data-language]").addClass("hide");
        $.each($(".mailtemplate-translations fieldset[data-language]"), function (i, fieldset) {
            if ($(fieldset).attr("data-language") === translationLanguage) {
                $(fieldset).removeClass("hide");
            }
        });
    },

    preRempAdd: function () {
    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });

        $.ajax({
            type: "POST",
            url: 'MailTemplate/BindMailTemplateForm',
            dataType: "json",
            data: { id: id },
            el: "#editForm",
            async: false,
            success: function (result) {
                $("#MailTemplateEdit_MailTemplateId").val(result.MailTemplateId);
                $("#MailTemplateEdit_MailCode").val(result.MailCode);
                MailTemplateEdit_Translations_0__IsHtmlEditor
                mailTemplate.loadTagsGrid(result.Tags);

                var initHtmlEditor = false;
                /*** translations ***/
                if (result.Translations.length > 0) {
                    $.each(result.Translations, function (i, translation) {
                        var fieldsetTranslation = $("[data-language='" + translation.MailLanguage + "']");
                        fieldsetTranslation.find("input[id$='MailDescription']").val(translation.MailDescription);
                        fieldsetTranslation.find("input[id$='MailTitle']").val(translation.MailTitle);
                        fieldsetTranslation.find("input[id$='MailObject']").val(translation.MailObject);
                        fieldsetTranslation.find("input[id$='IsHtmlEditor']").val(translation.IsHtmlEditor);

                        var translationEditor = fieldsetTranslation.find("textarea[id$='MailValue']");
                        translationEditor.val(decodeURIComponent(translation.MailValue));
                
                        if (translation.IsHtmlEditor == true) {

                            $('.wysiwyg-editor')
                                .trumbowyg({
                                    // Redefine the button pane
                                    btns: [
                                        ['viewHTML'],
                                        ['formatting'],
                                        ['strong', 'em', 'del'],
                                        ['superscript', 'subscript'],
                                        ['link'],
                                        ['image'], // Our fresh created dropdown
                                        ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                                        ['unorderedList', 'orderedList'],
                                        ['horizontalRule'],
                                        ['removeformat'],
                                        ['fullscreen']
                                    ],
                                    plugins: { resizimg: {} }
                                });

                            translationEditor.trumbowyg('html', translationEditor.trumbowyg('html'));
                        }
                        else {
                            translationEditor.trumbowyg('destroy');
                        }

                    });
                } else {
                    var fieldsetTranslation = $("[data-language");
                    fieldsetTranslation.find("input[id$='MailDescription']").val("");
                    fieldsetTranslation.find("input[id$='MailTitle']").val("");
                    fieldsetTranslation.find("input[id$='MailObject']").val("");
                    fieldsetTranslation.find("textarea[id$='MailValue']").val("");
                    $.each(fieldsetTranslation.find("textarea[id$='MailValue']"), function (i, textEditor) {
                        $(textEditor).trumbowyg('html', $(textEditor).trumbowyg('html'));
                    });
                }


            },
            error: function (xhr, ajaxOptions, thrownError) {
                site.errorMessage(resourcesMessages.BindMailTemplateForm_Error);
            }
        });
        return false;
    },

    loadTagsGrid: function (tags) {
        $("#MailTemplateEdit_MailTags").empty();

        var table = "<table class=\"table table-popover table-borderless\">";
        table += "<thead>";
            table += "<tr>";
                table += "<th>" + resources.TagToPaste + "</th>";
                table += "<th>" + resources.Description + "</th>";
            table += "</tr>";
        table += "</thead>";

            table += "<tbody>";
            $.each(tags, function (i, tag) {
                table += "<tr>";
                    table += "<td>**" + tag.TagName + "**</td>";
                    table += "<td>" + tag.TagDescription + "</td>";
                table += "<tr>";
            });

            table += "</tbody>";
        table += "</table>";
        $("#MailTemplateEdit_MailTags").append(table);
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);

            var cl = ids[i];
            var ed = "";
            var description = "<div style='white-space: normal !important;'>" + data.MailDescription + "</div>";
            var recipient = "<div style='white-space: normal !important;'>" + data.MailRecipient + "</div>";
            var trigger = "<div style='white-space: normal !important;'>" + data.MailTrigger + "</div>";

            if (site.hasPermission(right.MailTemplate_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='mailTemplate.preRempEdit(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            }

            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { MailDescription: description, MailTrigger: trigger, MailRecipient: recipient, act: ed });
        }
    },

    edit: function () {
        if ($("#editForm").valid()) {
            var form = $("#editForm").first();
            var data = form.serializeArray();

            /** Encoder chaque valeur des éditeurs de texte enrichi **/
            $.each(data, function (i, d) {
                if (d.name.indexOf('MailValue') > -1) {
                    d.value = encodeURIComponent(d.value);
                }
            });

            $.ajax({
                type: "POST",
                url: 'MailTemplate/Edit',
                dataType: "json",
                data: data,
                traditional: true,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        mailTemplate.gridReload();
                        $("#editForm .cancel").click();
                    }
                    else {
                        console.error("Erreur - MailTemplate.js edit - " + result.Exception);
                        site.errorMessage(resourcesMessages.ErrorOccured);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.error("Erreur - MailTemplate.js edit - " + thrownError);
                    site.errorMessage(resourcesMessages.ErrorOccured);
                    //$("#editForm .cancel").click();
                }
            });
        }
        else {
            console.warn("editForm is not valid");
        }
        return false;
    },

    gridReload: function () {
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "MailTemplate/DataBind",
            page: 1
        }).trigger("reloadGrid");
    },

    sendTestMail: function () {
        if ($("#editForm").valid()) {
            var form = $("#editForm").first();
            var data = form.serializeArray();

            /** Encoder chaque valeur des éditeurs de texte enrichi **/
            $.each(data, function (i, d) {
                if (d.name.indexOf('MailValue') > -1) {
                    d.value = encodeURIComponent(d.value);
                }
            });
            $.ajax({
                type: "POST",
                url: 'MailTemplate/SendTestMail',
                dataType: "json",
                data: data,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resourcesMessages.SendTestMail_Success);
                    } else {
                        site.errorMessage(resourcesMessages.SendTestMail_Error);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorMessage(resourcesMessages.SendTestMail_Error);
                }
            });
        } else {
            console.warn("editForm is not valid");
        }
        return false;
    }
};
window.mockup = {

    rowTemplate: null,
    rowEditTemplate: null,
    params: {},
    lastUnitId_addForm: null,
    lastUnitId_editForm: null,
    lastUnitId_searchForm: null,

    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    //Page générale
                    $("#labelSearch").html(resources.Organization_stadium);
                    $("#JqGrid").setLabel('OrganizationName', resources.Organization_stadium);

                    //Ajout / Edition
                    $("#addForm #labelOrganization").html(resources.Organization_stadium + ' *');
                    $("#editForm #labelOrganization").html(resources.Organization_stadium + ' *');
                }
            }
        });

        mockup.rowTemplate = $("#addForm .table-itemlist").find("tbody tr").last().detach();
        mockup.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();

        $("#editForm .submit").click(mockup.editBackgroundMockup);


        $("#addForm .submit").click(mockup.addBackgroundMockup);

        $("#actions .submit").click(mockup.preRempAddBackgroundMockup);
        $("#actions .delete").click(mockup.delSelected);

        $("#addForm input[name='BackgroundMockupAdd.Picture']").val(file.fileUpload);
        $("#editForm input[name='BackgroundMockupEdit.Picture']").val(file.fileUpload);

        $("#search").submit(mockup.gridReload);


        $(".js-additemlist").click(function () {
            var elem = $(this).parents("form").first().find(".table-itemlist");
            window.mockup.addItemList(elem);
            return false;
        });
    },

    preRempEditBackgroundMockup: function (id) {
        var ret = jQuery("#JqGrid").jqGrid('getRowData', id);
        site.showForm('#editForm', { container: ".main-container" });
        $(".table-itemlist tbody").html("");
        file.resetPicture("#editForm");

        $.ajax({
            type: "POST",
            url: "Mockup/BindBackgroundMockupForm",
            data: { id: id },
            dataType: "json",
            traditional: true,
            el: "#LimitedEditContainer",
            success: function (ret) {
                var backgroundModel = ret.background;
                var units = ret.units;
                var profiles = ret.profiles;

                $("#editForm #BackgroundMockupEdit_BackgroundMockupId").val(backgroundModel.BackgroundMockupId);
                $("#editForm #BackgroundMockupEdit_Name").val(backgroundModel.Name);
                $("#editForm #BackgroundMockupEdit_OrganizationId").val(backgroundModel.OrganizationId);
                $("#editForm #BackgroundMockupEdit_HasIndividualPicture")[0].checked = backgroundModel.HasIndividualPicture;

                if (backgroundModel.HasImage) {
                    file.setPicture("#editForm", "/Content/images/backgroundMockup/" + backgroundModel.ImageName);
                }

                var i = 0;
                var elem = $("#editForm .table-itemlist");
                for (i in backgroundModel.Rules) {
                    mockup.addItemList(elem, backgroundModel.Rules[i], units, profiles);
                }
            }
        });
    },

    preRempAddBackgroundMockup: function () {
        site.showForm('#addForm', { container: ".main-container" });
        $(".table-itemlist tbody").html("");
        $("#addForm")[0].reset();
        $("#select2-BackgroundMockupAdd_OrganizationId-container").empty();
        file.resetPicture("#addForm");

    },

    addBackgroundMockup: function () {
        var form = $("#addForm");
        form.find("[id*='_Name']").rules("add", "isBackgroundMockupUnique");
        form.find("[id*='_OrganizationId']").rules("add", "imageRequired");

        if ($("#addForm").valid()) {
            var model = form.serialize();
            $.ajax({
                type: "POST",
                url: 'Mockup/Add',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#addForm .cancel").click();
                        mockup.gridReload();
                    }
                }
            });
        }
        return false;
    },

    editBackgroundMockup: function () {
        var form = $("#editForm");
        form.find("[id*='_Name']").rules("add", "isBackgroundMockupUnique");
        form.find("[id*='_OrganizationId']").rules("add", "imageRequired");

        if (form.valid()) {
            var model = $("#editForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Mockup/Edit',
                dataType: "json",
                el: "#editForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#editForm .cancel").click();
                        mockup.gridReload();
                    }
                }
            });
        }
        return false;
    },


    delSelected: function () {
        var ok
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(ResourcesMessages.AtLeastOneBackgroundSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'Mockup/DeleteSelected',
                        dataType: "json",
                        el: "#jqcontainer",
                        data: { ids: s },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            mockup.gridReload();
                        }
                    });
                }
            });
        }
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var data = jQuery("#JqGrid").jqGrid('getRowData', cl);
            var ed = "";

            if (site.hasPermission(right.Mockup_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='mockup.preRempEditBackgroundMockup(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            }

            var imageName = '<img src="/Content/images/backgroundMockup/' + data.ImageName + '?height=50" />';

            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: ed, ImageName: imageName });
        }
    },

    gridReload: function () {
        var data = jQuery("#search").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Mockup/BackgroundDataBind?" + data,
            page: 1
        }).trigger("reloadGrid");
    },

    clearItemList: function () {
        //effacer les anciennes valeur (seulement les valeurs saisies, pas les champs cachés contenant les cultures de chaque colonne
        if (mockup.rowTemplate != null) {
            mockup.rowTemplate.find("select").val("");
        }

        $(".table-itemlist tbody").html("");
    },


    addItemList: function (elem, rule, units, profiles) {
        var table = elem;
        if (elem.parents("form").hasClass("addForm")) {
            var row = window.mockup.rowTemplate;
        } else {
            var row = window.mockup.rowEditTemplate;
        }

        var selects = table.find("tbody tr").last().find("select");
        var len = selects.length;
        for (var i = 0 ; i < len ; i++) {
            var select2 = table.find("tbody tr").last().find("select")[i];
            if (select2) {
                $(select2).select2('destroy');
            }
        }


        var lastRow = table.find("tbody tr").last().clone(true);

        var nb = 0;

        //si il y a deja une ligne dans le tableau
        if (lastRow[0] != undefined) {

            var html = lastRow.html();
            //j'incrémente les numéro contenu dans CustomChoises_0__Name et CustomChoises[0].Name
            var newHtml = html.replace(/(Rules_\d+)/g, function (match, str) {
                var number = str.replace("Rules_", "");
                nb = parseInt(number, 10) + 1;
                return "Rules_" + nb;
            });
            
            newHtml = newHtml.replace(/(Rules\[\d+)/g, function (match, str) {
                var number = str.replace("Rules[", "");
                nb = parseInt(number, 10) + 1;
                return "Rules[" + nb;
            });

            lastRow.html(newHtml);
        } else {
            var lastRow = row.clone(true);
        }

        var unitField = lastRow.find("select[id*='UnitId']");
        var profileField = lastRow.find("select[id*='ProfileId']");
        profileField.prop('disabled', true);

        if (rule != undefined) {

            //unitField.html("");
            //profileField.html("");
            profileField.prop('disabled', false);

            for (z in units) {
                var unit = units[z];
                unitField.append('<option selected="selected" value="' + unit.OrganizationUnitId + '">' + unit.OrganizationUnitName + '</option>');
            }

            for (z in profiles) {
                var profile = profiles[z];
                profileField.append('<option selected="selected" value="' + profile.ProfileId + '">' + profile.Name + '</option>');
            }


            unitField.val(rule.UnitId);
            profileField.val(rule.ProfileId);

        } else {
            unitField.val("");
            profileField.val("");
        }
        lastRow.find(".btn-delete").click(window.zone.deleteItemList);
        //j'injecte la ligne à la fin du tableau
        lastRow.appendTo(table);
        table.parents(".container-itemlist").animate({ scrollTop: lastRow.offset().top }, 'fast');

        $(".container-itemlist select").css("width", "100%").each(function () {
            var elem = $(this);

            $(this).select2(
            {
                ajax: {
                    data: function (params, page) {
                        var p = elem.data("ajax--params");
                        if (p) {
                            p = p.split(".");
                            var params = window[p[0]][p[1]](params, elem);
                        }
                        params["q"] = params.term;
                        params["page"] = params.term;

                        return params;
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                }
            });
        });

        return false;
    },

    deleteItemList: function () {
        var elem = $(this).parents(".table-itemlist").first();

        $(this).parents("tr").first().remove();
        mockup.refreshItemListIds(elem);
        return false;
    },

    enableProfileSelect: function(elem) {
        var elemId = $(elem).attr("id");
        var nb = parseInt(elemId.replace(/[^0-9\.]/g, ''), 10);
        var form = "";

        if ($("#addForm").is(":visible")) {
            form = "Add";
        } else if ($("#editForm").is(":visible")) {
            form = "Edit";
        }
        $("#BackgroundMockup" + form + "_Rules_" + nb + "__ProfileId").prop('disabled', false);
    },

    refreshItemListIds: function (elem) {
        var i = -1;
        //on parcour toute les lignes du tableau 
        $(elem).find("tr").each(function () {
            // pour chaque input et span on met a jour leur id nom etc..
            $(this).find('select, input, span').each(function () {
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var datamsq = $(this).attr("data-valmsg-for");
                if (id) id = id.replace(/(\d+)/g, i);
                if (name) name = name.replace(/(\d+)/g, i);
                if (datamsq) datamsq = datamsq.replace(/(\d+)/g, i);
                $(this).attr("id", id);
                $(this).attr("name", name);
                $(this).attr("data-valmsg-for", datamsq);
            });
            i++;
        });

    },

    getSelect2Params: function (params, elem) {
        var elemId = $(elem).attr("id");
        var nb = parseInt(elemId.replace(/[^0-9\.]/g, ''), 10);
        var form = "";

        if ($("#addForm").is(":visible")) {
            params["organizationId"] = $("#BackgroundMockupAdd_OrganizationId").val();
            form = "Add";
        } else if ($("#editForm").is(":visible")) {
            params["organizationId"] = $("#BackgroundMockupEdit_OrganizationId").val();
            form = "Edit";
        } else {
            params["organizationId"] = $("#Search_OrganizationId").val();
        }
        var unitValue = $("#BackgroundMockup" + form + "_Rules_" + nb + "__UnitId").val();
        params["unitId"] = parseInt(unitValue, 10);

        return params;
    }

}
var moncompteIndex = {

    params: {
        newPasswordMessageHover: ""
    },


    init: function (params) {
        $.extend(this.params, params);

        $("#editForm .edit").click(moncompteIndex.preRempEdit);
        $("#editForm .cancel").click(moncompteIndex.onclickCancel);
        $("#editForm .submit").click(moncompteIndex.edit);

        $("#editPasswordForm .cancel").click(moncompteIndex.onclickPasswordCancel);
        $("#editPasswordForm .submit").click(moncompteIndex.editPassword);

        $("#PasswordModel_NewPassword").qtip({
            content: {
                text: moncompteIndex.params.newPasswordMessageHover
            },
            style: {
                classes: 'qtip-bootstrap '
            }
        });
    },

    preRempEdit: function () {
        return false;
    },

    edit: function () {

        if ($("#editForm").valid()) {
            var params = {
                LastName: $("#InformationModel_LastName").val(),
                FirstName: $("#InformationModel_FirstName").val(),
                Email: $("#InformationModel_Email").val(),
                MobilePhoneNumber: $("#InformationModel_MobilePhoneNumber").val(),
                LandlinePhoneNumber: $("#InformationModel_LandlinePhoneNumber").val(),
                Title: $("#InformationModel_Title").val(),
                Function: $("#InformationModel_Function").val()
            };

            $.ajax({
                type: "POST",
                dataType: "json",
                data: params,
                url: "MonCompte/Edit",
                el: "#editForm fieldset",
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                    }
                }
            });
        }
        return false;
    },

    editPassword: function () {
        var params = {
            UserId: $("#userPasswordModel_UserId").val(),
            OldPassword: $("#OldPassword").val(),
            NewPassword: $("#NewPassword").val(),
            NewPasswordConfirmation: $("#NewPasswordConfirmation").val()
        };
       
        if ($("#editPasswordForm").valid() && $("#formValidity").val() == "true") {
            $.ajax({
                type: "POST",
                dataType: "json",
                data: params,
                el: "#editPasswordForm fieldset",
                url: "MonCompte/EditPassword",
                success: function (result) {
                    if (result.success) {
                        site.successMessage(resources.ValidationSuccess);
                    } else {
                        site.simpleErrorMessage(result.Exception[0].Message);
                    }
                }
            });
        }
        return false;
    },

    onclickCancel: function () {
        $("#editForm .field-validation-error").empty(); //supprime les messages d'erreur
    },

    onclickPasswordCancel: function () {
        $("#editPasswordForm .field-validation-error").empty(); //supprime les messages d'erreur
        $("#NewPassword").css("border", "");
        $("#NewPasswordConfirmation").css("border", "");
        $('#errors').hide();
        $('#confirmationErrors').hide();
        $("#formValidity").val(false);
    },
}
var organization = {

    wordingStyle: "",

    init: function () {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                organization.wordingStyle = wordingStyle;
                if (organization.wordingStyle === 'Stadium') {
                    //Page générale
                    $(".title-primary").html(resources.OrganizationsManagement_stadium);
                    $("#listTitle").html(resources.OrganizationList_stadium);
                    $("#updateOrganizationTitle").html(resources.UpdateOrganization_stadium);
                    $("#addOrganizationTitle").html(resources.AddOrganization_stadium);
                    $("title").html(resources.Organizations_stadium);
                }
            }
        });
        $("#addForm #OrganizationId").change(organization.preRempAdd);
        $("#addForm .submit").click(organization.add);
        $("#addForm .duplicate").click(organization.duplicate);

        $("#editForm .submit").click(organization.edit);


        $("#searchForm").submit(organization.gridReload);

        $("#actions .submit").click(organization.preRempAdd);
        $("#actions .delete").click(organization.deleteAll);

        $("#addForm .duplicate").hide();
        $("#Organization").css("width", "100%").select2({
            allowClear: true,
            dropdownAutoWidth: true
        });


        $("#OrganizationAdd_Name").rules("add", "checkUniciteOnAdd");
        $("#OrganizationEdit_Name").rules("add", "checkUniciteOnEdit");
    },


    preRempAdd: function () {
        site.showForm('#addForm', { container: ".main-container" });
        $("#addForm")[0].reset();
        $("#OrganizationAdd_CategoryIds").val(null).trigger("change"); 
    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });

        var model = {
            id: id
        };

        $.ajax({
            type: "POST",
            url: 'Organization/GetOrgaInfo',
            dataType: "json",
            data: model,
            el: "#editForm",
            async: false,
            success: function (result) {
                $("#OrganizationEdit_OrganizationId").val(result.OrganizationId);
                $("#OrganizationEdit_SportId").val(result.SportId);
                $("#OrganizationEdit_Name").val(result.Name);
                $("#OrganizationEdit_BarcodeHeader").val(result.BarcodeHeader);
                $("#OrganizationEdit_Comment").val(result.Comment);
                $("#OrganizationEdit_CategoryIds").val(result.Categories).trigger("change"); 
            }
            
        });
        return false;
    },
        
    add: function () {
        if ($("#addForm").valid()) {
            model = $("#addForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Organization/Add',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organization.gridReload();
                    }
                    else {
                        console.error("Erreur - Organization.js add - " + result.Exception);
                        site.errorMessage(resourcesMessages.ErrorOccured);
                    }
                    $("#addForm .cancel").click();
                   
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.error("Erreur - Organization.js add - " + thrownError);
                    site.errorMessage(resourcesMessages.ErrorOccured);
                    $("#addForm .cancel").click();
                    
                }
            });
        }
        else {
            console.warn("addForm is not valid");
        }
        // Gestion des erreurs
        return false;
    },

    edit: function () {
        if ($("#editForm").valid()) {
            var model = $("#editForm").serialize();

            $.ajax({
                type: "POST",
                url: 'Organization/Edit',
                dataType: "json",
                data: model,
                async: false,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organization.gridReload();
                    }
                    else {
                        console.error("Erreur - Organization.js edit - " + result.Exception);
                        site.errorMessage(resourcesMessages.ErrorOccured);
                    }
                    $("#editForm .cancel").click();
                },
                error: function (xhr, ajaxOptions, thrownError)
                {
                    console.error("Erreur - Organization.js edit - " + thrownError);
                    site.errorMessage(resourcesMessages.ErrorOccured);
                    $("#editForm .cancel").click();
                }
            });
        }
        else {
            console.warn("editForm is not valid");
        }
        return false;
    },

    deleteAll: function () {
        var ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        var suppWording;

        if (organization.wordingStyle === 'Stadium') {
            suppWording = resourcesMessages.SuppressionOrgaConfirmation;
        } else {
            suppWording = resourcesMessages.SuppressionEpreuveConfirmation;
        }
        var wording = ""

        if (ids == "") {
            jAlert(provider.params.messageAtLeastOneProviderSelected, resources.Warning);
        } else {
            var ok;
            jConfirm(suppWording, resources.Warning, function (ok) {
                if (ok) {
                    $(".inner").Spinner("show");
                    var ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                    $.ajax({
                        type: "POST",
                        url: 'Organization/DeleteSelected',
                        dataType: "json",
                        el: "#tabs-unit-property",
                        data: { ids : ids },
                        async: true,
                        success: function (ret) {
                            $(".inner").Spinner("hide");
                            if (ret.Status == "Success") {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                                organizationIndex.preRemp();
                                organization.gridReload();
                            } else if (ret.Status == "warning") {
                                site.errorMessage(resourcesMessages.SuppressionOrgaWarning, ret.Exception);
                                organization.gridReload();
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                        }
                    });
                }
            });
        }
        // Gestion des erreurs
        return false;
    },

    duplicate: function () {
        $("#addForm  #Name").rules("add", "checkUniciteOnAdd");
        if ($("#addForm").valid()) {
            model = $("#addForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Organization/Duplicate',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if(result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $(".btn-return")[0].click();
                    } else {
                        site.errorMessage(resourcesMessages.SuppressionFailed, result.Exception);
                    }
                }
            });
        }
        // Gestion des erreurs
        return false;
    },

    gridReload: function() {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Organization/DataBind"
                + "?" + data,
            page: 1
        }).trigger("reloadGrid");
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var ed = "";

            if (site.hasPermission(right.Organization_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='organization.preRempEdit(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            }

            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: ed });
        }
    }

}
var organizationAdd = {

    init: function () {
        var dateFormat = site.dateFormat;
        $("#addForm #OrganizationId").change(organizationAdd.preRemp);
        $("#addForm .submit").click(organizationAdd.Add);
        $("#addForm .duplicate").click(organizationAdd.Duplicate);

        $("#addForm .duplicate").hide();
        $("#Organization").css("width", "100%").select2({
            allowClear: true,
            dropdownAutoWidth: true
        });
    },


    preRemp: function () {
        if ($('#OrganizationId').val().length) {
            var model = {
                id: $("#OrganizationId").val()
            };
            $.ajax({
                type: "POST",
                url: 'Organization/GetOrgaInfo',
                dataType: "json",
                data: model,
                el: "#addForm",
                success: function (result) {
                    $("input[name=Name]").val(result.Name);
                    $("input[name=BarcodeHeader]").val(result.BarcodeHeader);
                    $("input[name=ValidityStartDate]").val(result.ValidityStartDate);
                    $("input[name=ValidityEndDate]").val(result.ValidityEndDate);
                    $("input[name=SportId]").val(result.SportId);
                    $("textarea[name=Comment]").val(result.Comment);
                }
            });

            $("#addForm .submit").hide();
            $("#addForm .duplicate").show();
        } else {
            $("#addForm .duplicate").hide();
            $("#addForm .submit").show();
        }
    },
        
    Add: function () {
        $("#addForm  #Name").rules("add", "checkUniciteOnAdd");
        if ($("#addForm").valid()) {
            $("#addForm #OrganizationId").val(0);
            model = $("#addForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Organization/Add',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $(".btn-return")[0].click();
                    }
                }
            });
            
        }
        // Gestion des erreurs
        return false;
    },

    Duplicate: function () {
        $("#addForm  #Name").rules("add", "checkUniciteOnAdd");
        if ($("#addForm").valid()) {
            model = $("#addForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Organization/Duplicate',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if(result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $(".btn-return")[0].click();
                    } else {
                        site.errorMessage(resourcesMessages.SuppressionFailed, result.Exception);
                    }
                }
            });
        }
        // Gestion des erreurs
        return false;
    }

}
var organizationIndex = {

    params: {
        messageAtLeastOneZoneSelected: "",
        messageAtLeastOneFunctionSelected: "",
        messageAtLeastOneOrganizationUnitSelected: "",
        messageAtLeastOneCodeRepere: "",
        labelOrganization: "",
        labelZones: "",
        labelSurZones: "",
        labelDefaultZones: ""
    },

    init: function (params) {
        treeview.DisplayBreadcrumb();
        $("#main").css("padding", "0");

        $.extend(this.params, params);

        $("#editOrgaForm .submit").click(organizationIndex.UpdateOrga);
        $("#editOrgaForm .cancel").click(organizationIndex.DeleteOrga);

        $("#editZoneForm .submit").click(organizationIndex.EditZone);
        $("#editZoneForm .cancel").click(function () { $('#editZone').hide(); $('#actions, #tabs-zone .jqcontainer').fadeIn('fast'); return false; });

        $("#addZoneForm .submit").click(organizationIndex.AddZone);
        $("#addZoneForm .cancel").click(function () { $('#addZone').hide(); $('#actions, #tabs-zone .jqcontainer').fadeIn('fast'); return false; });

        $("#actions .submit").click(organizationIndex.preRempAddZone);
        $("#actions .delete").click(organizationIndex.delSelectedZone);

        $("#editFormFunction .submit").click(organizationIndex.EditFunction);
        $("#editFormFunction .cancel").click(function () { $('#editFormFunction').hide(); $('#actionsFunction, #tabs-function .jqcontainer').fadeIn('fast'); return false; });
        
        $("#addFormReferenceCodeorganization .cancel").click(function () { $('#addFormReferenceCodeorganization').hide(); $('.actionsCode , #tabs-code .jqcontainer').fadeIn('fast'); return false; });

        $("#addFormFunction .submit").click(organizationIndex.AddFunction);
        $("#addFormFunction .cancel").click(function () { $('#addFormFunction').hide(); $('#actionsFunction, #tabs-function .jqcontainer').fadeIn('fast'); return false; })

        $("#actionsFunction .submit").click(organizationIndex.preRempAddFunction);
        $("#actionsFunction .delete").click(organizationIndex.delSelectedFunction);

        $(".actionsCode .submit").click(organizationIndex.preRempAddCode);
        $(".actionsCode .delete").click(organizationIndex.delSelectedCode);

        $("#addFormReferenceCodeorganization .submit").click(organizationIndex.referenceCodeAdd);
        $("#addFormReferenceCodeorganization .cancel").click(function () { $('#addFormReferenceCodeorganization').hide(); $('.actionsCode').fadeIn('fast'); return false; })

        $("#tabs-unit .actionsOrganizationUnit .submit").click(organizationIndex.preRempAddOrganizationUnit);
        $("#tabs-unit .actionsOrganizationUnit .delete").click(organizationIndex.delSelectedOrganizationUnit);

        $("#tabs-unit .editOrganizationUnit .submit").click(organizationIndex.organizationUnitsEditOrganizationUnit);
        $("#tabs-unit .editOrganizationUnit .cancel").click(function () { $('#tabs-unit .editOrganizationUnit').hide(); $('#tabs-unit .actionsOrganizationUnit').fadeIn('fast'); });

        $("#tabs-unit .addOrganizationUnit .submit").click(organizationIndex.organizationUnitsAddOrganizationUnit);
        $("#tabs-unit .addOrganizationUnit .cancel").click(function () { $('#tabs-unit .addOrganizationUnit').hide(); $('#tabs-unit .actionsOrganizationUnit').fadeIn('fast'); });

        //$('.select-unit').combotree({
        //    // url: 'get_data.php',
        //    // required: true
        //    url: "/OrganizationUnit/GetUnitsTreeByOrganizationId/93",
        //    onSelect: treeview.onClickOrganizationUnit
        //});

        $("#Organization").change(organizationIndex.preRemp);

        $("#addZone input[name='Zone.Picture']").val(file.fileUpload);
        $("#editZone input[name='Zone.Picture']").val(file.fileUpload);


        $(".has-popover").popover();
        
        $(".container").css("padding", 0);
        organizationIndex.preRemp();
    },

    /********************************************************************************************/
    /***************************************** ORGANIZAION **************************************/
    /********************************************************************************************/

    preRemp: function () {
        if ($('#Organization').val() != null) {
            var model = {
                id: $("#Organization").val()
            };

            $.ajax({
                type: "POST",
                url: 'Organization/GetOrgaInfo',
                dataType: "json",
                data: model,
                el: "#tabs",
                async: false,
                success: function (result) {
                    $(window).trigger('resize');

                    $("#Organization_OrganizationId").val(result.OrganizationId);
                    $("#Zone_OrganizationId").val(result.OrganizationId);
                    $("#Function_OrganizationId").val(result.OrganizationId);

                    $("#Organization_SportId").val(result.SportId);
                    $("#Organization_Name").val(result.Name);
                    $("#Organization_BarcodeHeader").val(result.BarcodeHeader);
                    $("#Organization_ValidityStartDate").val(result.ValidityStartDate);
                    $("#Organization_ValidityEndDate").val(result.ValidityEndDate);
                    $("#Organization_Comment").val(result.Comment);
                    $("#Organization_ZoneListId").val(result.ZoneListId);
                    $("#Organization_FunctionListId").val(result.FunctionListId);

                    //Gestion du titre 
                    treeview.ResetBreadcrumb();
                    treeview.AddToBreadcrumb(result.Name, 0);
                }
            });
            organizationIndex.showHideTab('tabs', true);
            organizationIndex.showHideTab('tabsOrganizationUnit', false);
            treeview.Init();

            organizationIndex.gridReload();
            organizationIndex.initZoning();
        }
        else {
            organizationIndex.showHideTab('tabs', false);
            organizationIndex.showHideTab('tabsOrganizationUnit', false);

        //    treeview.Hide();
        }
    },

    initZoning: function() {
        if ($("#Organization").val()) {

            var model = {
                id: $("#Organization").val()
            };
            var form = $("#addFormFunction");
            $.ajax({
                type: "POST",
                url: 'ZoneNew/GetZonesByOrga',
                dataType: "json",
                data: model,
                success: function (result) {
                    zoningHelper.init($("#addFormFunction"), result.Zones, false, organizationIndex.params.labelZones, organizationIndex.params.labelSurZones, organizationIndex.params.labelDefaultZones);
                    zoningHelper.init($("#editFormFunction"), result.Zones, false, organizationIndex.params.labelZones, organizationIndex.params.labelSurZones, organizationIndex.params.labelDefaultZones);
                }
            });
        }
        // Gestion des erreurs
        return false;
    },

    showHideTab: function (id, bool) {
        if (bool == false) {
            $('#' + id).css("display", "none");
        }
        else {
            $('#' + id).css("display", "block");
        }
    },

    showHideOnglet: function (anchor, bool) {
        if (bool == false) {
            $('li a[href=' + anchor + ']').css("display", "none");
            //$(anchor).css("display", "none");
        } else {
            $('li a[href=' + anchor + ']').css("display", "block");
            //$(anchor).css("display", "block");
        }
    },

    UpdateOrga: function () {
        $("#editOrgaForm input[name='Organization.Name']").rules("add", "checkUniciteOnEdit");
        if ($("#editOrgaForm").valid()) {
            var model = $("#editOrgaForm").serialize();

            $.ajax({
                type: "POST",
                url: 'Organization/Edit',
                dataType: "json",
                data: model,
                async: false,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organizationIndex.listOrga();
                        $("#Organization").val(model.OrganizationId);
                    }
                }
            });
        }
        // Gestion des erreurs
        return false;
    },

    DeleteOrga: function () {
        var ok;
        jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
            if (ok && $("#tabs-property input[name='Organization.OrganizationId']").val()) {
                var model = {
                    OrganizationId: $("#tabs-property input[name='Organization.OrganizationId']").val()
                };

                $.ajax({
                    type: "POST",
                    url: 'Organization/Delete',
                    dataType: "json",
                    el: "#tabs-unit-property",
                    data: model,
                    async: false,
                    success: function (ret) {
                        if (ret.Success) {
                            site.successMessage(resourcesMessages.SuppressionSuccess);
                            organizationIndex.listOrga();
                            organizationIndex.preRemp();
                        } else {
                            site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                        }
                    }
                });
            }
        });
        // Gestion des erreurs
        return false;
    },

    gridReload: function () {
        //zone
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Zone/DataBind/" + $('#Organization').val(),
            page: 1,
            editurl: '/Zone/JqGridOnUpdate'
        }).trigger("reloadGrid");
        //function
        jQuery("#JqGridFunction").jqGrid('setGridParam', {
            url: "Profile/DataBind/" + $('#Organization').val(),
            page: 1,
            editurl: '/Profile/JqGridOnUpdate'
        }).trigger("reloadGrid");
        
        //Code
        jQuery("#JqGridCode").jqGrid('setGridParam', {
            url: "ReferenceCode/DataBind/",
            postData: {
                idOrganization: $('#Organization').val(),
            },
            page: 1,
        }).trigger("reloadGrid");

        var ouid =  $("#tabs-unit-property .editOrganizationUnit input[name='OrganizationUnit.OrganizationUnitId']").val();
        //if (ouid.length) {
        //    jQuery("#JqGridUser").jqGrid('setGridParam', {
        //        url: "User/DataBindForOgra/" + ouid,
        //        page: 1
        //    }).trigger("reloadGrid");
        //}
        //unit
        jQuery("#JqGridOrganizationUnit").jqGrid('setGridParam', {
            mtype: "POST",
            url: "OrganizationUnit/DataBind",
            datatype: "json", // can also be xml
            postData: {
                orgaId: $('#Organization').val(),
                parentId: 0
            },
            page: 1,
            editUrl: 'OrganizationUnit/JqGridOnUpdate'
        }).trigger("reloadGrid");
        jQuery("#JqGridOrganizationUnitFromOuNode").jqGrid('setGridParam', {
            mtype: "POST",
            url: "OrganizationUnit/DataBind",
            datatype: "json", // can also be xml
            postData: {
                orgaId: $('#Organization').val(),
                parentId: $("#tabs-unit-unit .addOrganizationUnit input[name='OrganizationUnit.ParentId']").val()
            },
            page: 1
        }).trigger("reloadGrid");
    },

    /********************************************************************************************/
    /********************************************* ZONE *****************************************/
    /********************************************************************************************/

    preRempEditZone: function (id) {
        
        var ret = jQuery("#JqGrid").jqGrid('getRowData', id);
        $("#addZone, #actions, #tabs-zone .jqcontainer").hide();
        file.resetPicture("#editZone");

        $("#editZone").fadeIn("slow");

        $.ajax({
            type: "POST",
            url: "Zone/BindZoneForm",
            data: { id: id },
            dataType: "json",
            traditional: true,
            el: "#editZone",
            success: function (ret) {
                $("#editZone input[name='Zone.ZoneId']").val(ret.ZoneId);
                $("#editZone input[name='Zone.OrganizationId']").val(ret.OrganizationId);
                $("#editZone input[name='Zone.Code']").val(ret.Code);
                $("#editZone input[name='Zone.Name']").val(ret.Name);
                $("#editZone input[name='Zone.Code']").attr("readonly", "readonly");
                $("#editZone input[name='Zone.IsActive']")[0].checked = ret.IsActive;
                $("#editZone select[name='Zone.AssignmentTypeId']").val(ret.AssignmentTypeId);

                if (ret.HasImage) {
                    file.setPicture("#editZone", "/Content/images/zone/" + ret.ImageName);
                }

                if (ret.Color != undefined && ret.Color != "") {
                    $("#editZone input[name='Zone.Color']").val(ret.Color);
                    $("#editZone input[name='Zone.Color']").spectrum("set", ret.Color);
                } else {
                    $("#editZone input[name='Zone.Color']").val("#222222");
                    $("#editZone input[name='Zone.Color']").spectrum("set", "#222222");
                }
                if (ret.SurZoning) {
                    $("#editZone input[name='Zone.SurZoning']").attr("checked", "checked");
                    $("#editZone input[name='Zone.SurZoning']")[0].checked = true;
                } else {
                    $("#editZone input[name='Zone.SurZoning']").removeAttr("checked");
                }
            }
        });
    },

    preRempAddZone: function () {
        $("#editZone, #actions, #tabs-zone .jqcontainer").hide()
        $("#addZone").fadeIn("slow");
        file.resetPicture("#addZone");

        $("#addZone input[name='Zone.OrganizationId']").val($('#Organization').val());
        $("#addZone input[name='Zone.Code']").val("");
        $("#addZone input[name='Zone.Name']").val("");
        $("#addZone input[name='Zone.SurZoning']").removeAttr("checked");
        $("#addZone input[name='Zone.Color']").spectrum("set", "#222222");

    },

    delSelectedZone: function () {
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(organizationIndex.params.messageAtLeastOneZoneSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'Zone/DeleteSelected',
                        dataType: "json",
                        el: "#tabs-zone",
                        data: { ids: s },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            $("#JqGrid").trigger("reloadGrid");
                        }
                    });
                }
            });
        }
    },    

    AddZone: function () {
       $("#addZoneForm input[name='Zone.Code']").rules("add", "verifySurZoneCode");
       $("#addZoneForm input[name='Zone.Code']").rules("add", "checkUniciteZone");

        if ($("#addZoneForm").valid()) {

            var model = $('#addZoneForm textarea, #addZoneForm select, #addZoneForm input[name!="Zone.ZoneId"] ').serializeObject("Zone");
            model.SurZoning = $("#addZoneForm input[name='Zone.SurZoning']").is(":checked");
            model.IsActive = $("#addZoneForm input[name='Zone.IsActive']").is(":checked");
            model.NameFile = $("#addZoneForm .nameFile").val();

            $.ajax({
                type: "POST",
                url: 'Zone/Add',
                dataType: "json",
                el: "#tabs-zone #addZoneForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organizationIndex.preRemp();
                        $("#addZoneForm .cancel").click();
                        $("#JqGrid").trigger("reloadGrid");
                    }
                }
            });

        }
        return false;
    },

    EditZone: function () {
        $("#editZoneForm input[name='Zone.Code']").rules("add", "verifySurZoneCode");
        $("#editZoneForm input[name='Zone.Code']").rules("add", "checkUniciteZone");

        if ($("#editZoneForm").valid()) {
            var model = $('#tabs-zone #editZoneForm').serializeObject("Zone");
            model.NameFile = $("#editZoneForm .nameFile").val();

            if ($.isArray(model.SurZoning)) {
                model.SurZoning = model.SurZoning[0];
            }
            if ($.isArray(model.IsActive)) {
                model.IsActive = model.IsActive[0];
            }

            $.ajax({
                type: "POST",
                url: 'Zone/Edit',
                dataType: "json",
                el: "#tabs-zone #editZone",
                data: model,
                async: false,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#editZoneForm .cancel").click();
                        $("#JqGrid").trigger("reloadGrid");
                    }
                }
            });

            // Gestion des erreurs
            return false;
        }
    },

    DisableZone: function (elem) {
        $.ajax({
            type: "POST",
            url: 'Zone/DisableZone',
            dataType: "json",
            data: { zoneId: $(elem).val(), isActive: $(elem).is(":checked") },
            success: function (result) {
                if (result.Success) {
                }
            }
        });
    },


    /********************************************************************************************/
    /********************************************* FUNCTION *************************************/
    /********************************************************************************************/
    
    preRempEditFunction: function(id) {
        var ret = jQuery("#JqGridFunction").jqGrid('getRowData', id);
        $("#addFormFunction, #actionsFunction, #tabs-function .jqcontainer").hide();
        $("#editFormFunction").fadeIn("slow");

        $.ajax({
            type: "POST",
            url: "Profile/BindProfileForm",
            data: { id: id },
            dataType: "json",
            traditional: true,
            el: "#editFormFunction",
            success: function (ret) {
                $("#editFormFunction input[name='Profile.ProfileId']").val(ret.ProfileId);
                $("#editFormFunction input[name='Profile.OrganizationId']").val(ret.OrganizationId);
                $("#editFormFunction input[name='Profile.Name']").val(ret.Name);
                $("#editFormFunction [name='Profile.Definition']").val(ret.Definition);
                $("#editFormFunction input[name='Profile.EntryExitCount']").val(ret.EntryExitCount);
                $("#editFormFunction input[name='Profile.IsEntryExitControled']")[0].checked = ret.IsEntryExitControled;
                $("#editFormFunction input[name='Profile.IsActive']")[0].checked = ret.IsActive;

                $(".chkEdit").each(function () {
                    $(this).removeAttr('checked');
                });

                organizationIndex.initZoningOnEdit();
            }
        });

   
        return false;
    },

    preRempAddFunction: function () {
        $("#editFormFunction, #actionsFunction, #tabs-function .jqcontainer").hide();

        $("#addFormFunction").fadeIn("slow");

        $("#addFormFunction")[0].reset();

    },

    initZoningOnEdit: function(){
        var model = {
            id: $("#tabs-function #editFormFunction input[name='Profile.ProfileId']").val()
        };

        $.ajax({
            type: "POST",
            url: 'ZoneNew/GetZoning',
            dataType: "json",
            data: model,
            async: false,
            success: function (result) {
                zoningHelper.form = $("#editFormFunction");
                zoningHelper.setValues(result.zoning);
                return true;
            }
        });
        // Gestion des erreurs
        return false;
    },

    //AddFunction: function () {
    //    $("#addFormFunction input[name='Profile.Name']").rules("add", "checkUniciteFunction");
    //    if ($("#addFormFunction").valid()) {
    //        var model = {
    //            Name: $("#addFormFunction #Profile_Name").val(),
    //            Definition: $("#addFormFunction #Profile_Definition").val(),
    //            EntryExitCount: $("#addFormFunction #Profile_EntryExitCount").val(),
    //            IsEntryExitControled: $("#addFormFunction #Profile_IsEntryExitControled").is(':checked'),
    //            OrganizationId: $("#Organization").val(),
    //            IsActive: $("#addFormFunction #Profile_IsActive").is(':checked'),
    //            zoning: organizationIndex.postZoning('#addFormFunction .zoning')
    //        };

    //        $.ajax({
    //            type: "POST",
    //            url: 'Profile/Add',
    //            dataType: "json",
    //            el: "#addFormFunction",
    //            data: model,
    //            success: function (result) {
    //                if (result.Success) {
    //                    site.successMessage(resources.ValidationSuccess);
    //                    organizationIndex.preRemp();
    //                    $("#addFormFunction .cancel").click();
    //                    $("#JqGridFunction").trigger("reloadGrid");
    //                }
    //            }
    //        });
    //    }
    //    return false;
    //},

    //EditFunction: function () {
    //    var form = $("#editFormFunction");
    //    $("#editFormFunction input[name='Profile.Name']").rules("add", "checkUniciteFunction");

    //    if (form.valid()) {
    //        var model = {
    //            ProfileId: form.find("input[name='Profile.ProfileId']").val(),
    //            Name: form.find("input[name='Profile.Name']").val(),
    //            Definition: form.find("[name='Profile.Definition']").val(),
    //            entryExitCount: form.find("input[name='Profile.EntryExitCount']").val(),
    //            isEntryExitControled: form.find("input[name='Profile.IsEntryExitControled']").is(':checked'),
    //            organizationId: form.find("input[name='Profile.OrganizationId']").val(),
    //            IsActive: form.find("input[name='Profile.IsActive']").is(':checked'),
    //            zoning: organizationIndex.postZoning('#editFormFunction .zoning')
    //        };

    //        $.ajax({
    //            type: "POST",
    //            url: 'Profile/Edit',
    //            dataType: "json",
    //            data: model,
    //            el: "#editFormFunction",
    //            success: function (result) {
    //                if (result.Success) {
    //                    site.successMessage(resources.ValidationSuccess);
    //                    organizationIndex.preRemp();
    //                    $("#editFormFunction .cancel").click();
    //                    $("#JqGridFunction").trigger("reloadGrid");
    //                }
    //            }
    //        });
    //    }
    //    return false;
    //},

    //DisableFunction: function (elem) {
    //    $.ajax({
    //        type: "POST",
    //        url: 'ProfileNew/DisableProfile',
    //        dataType: "json",
    //        data: { profileId: $(elem).val(), isActive: $(elem).is(":checked") },
    //        success: function (result) {
    //            if (result.Success) {
    //            }
    //        }
    //    });
    //},

    postZoning: function (c) {
        var vals = "";
        $(c + " input[type='checkbox']:checked").each(function () {
           vals += this.id + ";";
        });
        vals += ";";
        return vals.replace(";;", "");
    },

    delSelectedFunction: function () {
        var ok
        var s = jQuery("#JqGridFunction").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(organizationIndex.params.messageAtLeastOneFunctionSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'Profile/DeleteSelected',
                        dataType: "json",
                        el: "#tabs-function",
                        data: { ids: s },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            $("#JqGridFunction").trigger("reloadGrid");
                        }
                    });
                }
            });
        }

    },



    delSelectedOrganizationUnit: function (id) {
        var s = jQuery("#JqGridOrganizationUnit").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(organizationIndex.params.messageAtLeastOneOrganizationUnitSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'OrganizationUnit/DeleteSelected',
                        dataType: "json",
                        data: { ids: s },
                        el: "#tabs-unit",
                        traditional: true,
                        async: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                                $("#JqGridOrganizationUnit").trigger("reloadGrid");
                                organizationIndex.preRemp();
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                        }
                    });
                }
            });
        }
        return false;
    },

    organizationUnitsInit: function () {
        jQuery("#JqGridOrganizationUnit").jqGrid('setGridParam', {
            url: "/OrganizationUnit/DataBind",
            mtype: 'POST',
            postData: {
                id: $('#Organisation').val(),
                profil: $('#Name').val(),
                parent: $('#Parent').val()
            },
            page: 1
        }).trigger("reloadGrid");
    },

    organizationUnitsAddOrganizationUnit: function () {
        var tab = $(this).parents("div[id^='tabs-']").first();
        var form = tab.find("form[class*='add']").first();
        // Fonction qui ajoute un OrganizationUnit
        form.find("input[name='OrganizationUnit.OrganizationUnitName']").rules("add", "checkUniciteUnitOnAdd");
        form.find("input[name='OrganizationUnit.ValidityStartDate']").rules("add", "compareDate");

        if (form.valid()) {
            
            var parentId = "";
            if (tab.attr('id') == "tabs-unit-unit") {
                parentId = form.find("input[name='OrganizationUnit.ParentId']").val();
            } 
            var model = form.serializeObject();
            model["OrganizationUnit.ParentId"] = parentId;
            model["OrganizationUnit.IsValidator"] = form.find("#OrganizationUnit_IsValidator")[0].checked;

            $.ajax({
                type: "POST",
                url: 'OrganizationUnit/Add',
                dataType: "json",
                data: model,
                el: ".addOrganizationUnit",
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organizationIndex.gridReload();
                        form.find(".cancel").click();
                        treeview.Refresh();
                    }
                }
             });
        }
        return false;
    },


    organizationUnitsVerifProfil: function (link) {
        return link.attr("data-Level");
    },

    /********************************************************************************************/
    /****************************************** CODE REPERE *************************************/
    /********************************************************************************************/

    preRempAddCode: function () {
        $(".actionsCode, #tabs-code .jqcontainer").hide();
        $("#addFormReferenceCodeorganization").fadeIn("slow");
        $("#addFormReferenceCodeorganization #ReferenceCode_ReferenceCode").val("");
    },

    referenceCodeAdd: function () {
        $("#addFormReferenceCodeorganization input[name='ReferenceCode.ReferenceCode']").rules("add", "required");
        $("#addFormReferenceCodeorganization input[name='ReferenceCode.ReferenceCode']").rules("add", "checkUniciteCode");

        if ($("#tabs-code form").valid()) {

            var model = {
                OrganizationId: $("#Organization").val(),
                referenceCode: $("#addFormReferenceCodeorganization input[name='ReferenceCode.ReferenceCode']").val()
            };           
            // Ajout si unique
            $.ajax({
                type: "POST",
                url: 'ReferenceCode/Add',
                dataType: "json",
                data: model,
                el: "#addFormReferenceCodeorganization",
                success: function (res) {
                    if (res.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#addFormReferenceCodeorganization .cancel").click();
                        jQuery("#JqGridCode").trigger("reloadGrid");
                    }
                }
            });
        }
        return false;
    },

    delSelectedCode: function () {
        var ok;
        var s = jQuery("#JqGridCode").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(organizationIndex.params.messageAtLeastOneCodeRepere, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'ReferenceCode/DeleteSelected',
                        el: "#tabs-code",
                        dataType: "json",
                        data: {
                            ids: s,
                            idOrganization: $('#Organization').val()
                        },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            $("#JqGridCode").trigger("reloadGrid");
                        }
                    });
                }
            });
        }
    },

    gridComplete: function(){
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var cl = ids[i];
            var ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='organizationIndex.preRempEditZone(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            var color = "<div style='color: " + data.Color + "'>" + data.Color + "</div>";
            var checked = '';
            if (data.IsActive == "true") {
                checked = 'checked="checked"';
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: ed, Color: color, IsActive: '<label class="switch-label"><input onclick="return organizationIndex.DisableZone(this)" ' + checked + ' class="ace ace-switch ace-switch-6 btn-rotate" type="checkbox" value="' + data.ZoneId + '"/><span class="lbl"></span></label>' });
        }
    },

    gridCompleteFunction: function (){
        var ids = jQuery("#JqGridFunction").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var data = jQuery("#JqGridFunction").jqGrid('getRowData', cl);
            var ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='organizationIndex.preRempEditFunction(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            var checked = '';
            if (data.IsActive == "true") {
                checked = 'checked="checked"';
            }
            jQuery("#JqGridFunction").jqGrid('setRowData', ids[i], { act: ed, IsActive: '<label class="switch-label"><input onclick="return organizationIndex.DisableFunction(this)" ' + checked + ' class="ace ace-switch ace-switch-6 btn-rotate" type="checkbox" value="' + data.ProfileId + '"/><span class="lbl"></span></label>' });
        }
    },

    gridCompleteUnit: function(){
        var ids = jQuery("#JqGridOrganizationUnit").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='organizationIndex.preRempEditOrganizationUnit(" + cl + ", this, \"JqGridOrganizationUnit\");'><i class='fa fa-pencil'></i></button>";
            jQuery("#JqGridOrganizationUnit").jqGrid('setRowData', ids[i], { act: ed });
        }
    },

    loadBeforeSend: function (grid) {
        //set dynamic size of grid
        var width = $('#template-breadcrumb').outerWidth() - 20;
        $(grid).jqGrid('setGridWidth', width);

        grid.p.loadBeforeSend = null; //remove event handler
        return false; // dont send load data request
    }  
    
};
var organizationUnit = {
    params: {
        messageAtLeastOneZoneSelected: "",
        messageAtLeastOneFunctionSelected: "",
        messageAtLeastOneOrganizationUnitSelected: "",
        messageAtLeastOneCodeRepere: "",
        messageAtLeastOneUserSelected: "",
        labelUnit: "",
        labelOrganization: ""
    },
   
    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    var unitOrganizationUnit = resources.Organization_stadium + ' *';
                    $("#unitOrganization").html(unitOrganizationUnit);
                    $("#editUnitOrganization").html(unitOrganizationUnit);
                    $("#labelOrganizationSearch").html(resources.Organization_stadium);
                    $("#OrganizationName").html(resources.Organization_stadium);
                }
            }
        });
        $.ajax({
            type: "POST",
            url: 'Parameter/GetunitSynchronizationParameter',
            dataType: "json",
            traditional: true,
            success: function (value) {
                if (value === false) {
                    $("#organizationSearch").css("display", "block");
                    jQuery("#treegrid").showCol("OrganizationName");
                    $("#treegrid").jqGrid("setGridWidth", $("#jqcontainer").width() - 20);
                }
            }
        });

        $.extend(this.params, params);

        $("#actions .submit").click(organizationUnit.preRempAdd);
        $(".addOrganizationUnit .submit").click(organizationUnit.addUnit);
        $(".addOrganizationUnit .cancel").click(function () {            
            site.hideForm('.addOrganizationUnit', { container: ".main-container" });
        });


        $(".editOrganizationUnit .submit").click(organizationUnit.editUnit);

        $(".cancel").click(function () {           
            site.hideForm('#tabsOrganizationUnit', { container: ".main-container" });
        });
        $("#search").submit(organizationUnit.gridReload);


        $("#treegrid .submit").click(organizationUnit.referenceCodeAdd);

        $("#OrganizationUnit_OrganizationId").change(function () {
            var form = $(this).parents("form").first();
            $('.select-unit').combotree({
                url: "/OrganizationUnit/GetUnitsTreeByOrganizationId/" + form.find("[id*='OrganizationId']").val(),
            });
        });

        jQuery("#treegrid").jqGrid({
            url: 'OrganizationUnit/DataBind?UnitSearchModel.OrganizationId=' + $("#UnitSearchModel_OrganizationId").val(),
            datatype: "json",
            treedatatype: "json",
            mtype: "POST",
            colNames: ["OrganizationUnitId", organizationUnit.params.labelUnit, organizationUnit.params.labelOrganization, "IsValidator", "OrganizationId", "<div class='text-center'><i class='fa fa-ellipsis-v'></i></div>"],
            colModel: [
                { name: 'OrganizationUnitId', index: 'OrganizationUnitId', width: 1, hidden: true, key: true },
                { name: 'Name', index: 'Name', width: 300 },
                { name: 'OrganizationName', index: 'OrganizationName', width: 300, hidden: true },
                { name: 'IsValidator', index: 'IsValidator', hidden: true },
                { name: 'OrganizationId', index: 'EndingDate', hidden: true, align: "left" },
                { name: 'act', index: 'act', width: 50 }
            ],
            autowidth: true,
            height: 'auto',
            pager: "#ptreegrid",
            treeGrid: true,
            treeGridModel: 'adjacency',
            sortname: "Name",
            ExpandColumn: 'Name',
            onSortCol: function (index, columnIndex, sortOrder) {
                organizationUnit.gridReload();
            },
            gridComplete: organizationUnit.gridCompleteUnit,
            rowList: [10, 15, 30, 50, 100],
            rowNum: 50
        });
        $("#treegrid").jqGrid('navGrid', '#ptreegrid',
        { view: false, del: false, add: false, edit: false, search: false, refresh: true },
        {}, {}, {}, {}, {});

    },


    getSelect2Params: function (params) {
        params["OrganizationUnitId"] = $("#OrganizationUnitEdit_OrganizationUnitId").val();
        return params;
    },

    preRempAdd: function () {
        site.showForm('.addOrganizationUnit', { container: ".main-container" });
        var input = $(".addOrganizationUnit").find("[id*='OrganizationId']");
        $(".addOrganizationUnit")[0].reset();
        $('.select-unit').combotree({
            url: "/OrganizationUnit/GetUnitsTreeByOrganizationId/" + input.val()
    });

    },

    addUnit: function () {
        var form = $(this).parents("form").first();
        if (form.valid()) {
            var data = form.serialize();
            $.ajax({
                type: "POST",
                url: 'OrganizationUnit/Add',
                dataType: "json",
                data: data,
                el: ".addOrganizationUnit",
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        organizationUnit.gridReload();
                        form.find(".cancel").click();
                    }
                }
            });
        }
        return false;
    },

    editUnit: function () {
        var form = $(this).parents("form").first();
        form.find("#OrganizationUnitEdit_OrganizationUnitName").rules("add", "checkUniciteUnit");

        if (form.valid()) {
            var model = form.serialize();
            $.ajax({
                type: "POST",
                url: 'OrganizationUnit/Edit',
                dataType: "json",
                data: model,
                el: ".editOrganizationUnit",
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        form.find(".cancel").click();
                        organizationUnit.gridReload();
                    }
                }
            });
        }
        return false;
    },


    confirmdelUnit: function (id) {
        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/GetOrganizationUnitById',
            dataType: "json",
            el: "#tabs-unit-unit",
            data: { ouId: id },
            traditional: true,
            async: false,
            success: function (ret) {
                if (ret.HasAssignments == true) {
                    jConfirm(resourcesMessages.SuppressionConfirmation, resources.WarningDeletingUnit, function (ok) {
                        if (ok) {
                            organizationUnit.delUnit(id);
                        }
                    });

                }
                else {
                    jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                        if (ok) {
                            organizationUnit.delUnit(id);
                        }
                    });
                }
            }
        });
    },

    delUnit: function (id) {
                $.ajax({
                    type: "POST",
                    url: 'OrganizationUnit/DeleteSelected',
                    dataType: "json",
                    el: "#tabs-unit-unit",
                    data: { ids: [id] },
                    traditional: true,
                    async: false,
                    success: function (ret) {
                        if (ret.Success) {
                            site.successMessage(resourcesMessages.SuppressionSuccess);
                        } 
                        else
                        {
                            site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                        }
                        organizationUnit.gridReload();
                    }
                });
    },

    gridCompleteFunction: function () {
        var ids = jQuery("#JqGridOrganizationUnitFunction").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var ret = jQuery("#JqGridOrganizationUnitFunction").jqGrid('getRowData', cl);
            var ed = "";

            if (site.hasPermission(right.OrganizationUnit_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='organizationUnit.preRempEditOrganizationUnitFunction(" + ret.ProfileId + ");'><i class='fa fa-pencil'></i></button>";
            }

            jQuery("#JqGridOrganizationUnitFunction").jqGrid('setRowData', ids[i], { act: ed });
        }
    },


    gridReload: function () {
        var data = $(".form-search").serialize();
        jQuery("#treegrid").jqGrid('setGridParam', {
            url: "OrganizationUnit/DataBind"
                + "?" + data,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    gridCompleteUnit: function () {
        var ids = jQuery("#treegrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var unit = jQuery("#treegrid").jqGrid('getRowData', cl);
            var data = {
                OrganizationUnitId: unit.OrganizationUnitId,
                parent: unit.parent
            };
            var ed = "";
            var del = "";

            if (site.hasPermission(right.OrganizationUnit_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='treeview.onClickOrganizationUnit(" + JSON.stringify(data) + ");'><i class='fa fa-pencil'></i></button>";
            }

            if (site.hasPermission(right.OrganizationUnit_DeleteSelected)) {
                del = "<button class='btn btn-circle btn-primary' onclick='organizationUnit.confirmdelUnit(" + cl + ");'><i type='button' class='fa fa-trash' ></i></button>";
            }

            jQuery("#treegrid").jqGrid('setRowData', ids[i], { act: ed + del });
        }
    },


}
var treeview = {
    breadcrumbs: [],
    breadcrumbTemplate: undefined,
    params: {
        collapsed: true,
        animated: "fast",
        control: "#sidetreecontrol",
        persist: "location"
    },

    Init: function (params) {
        $.extend(this.params, params);
        var model = {
            id: $("#Organization option:selected").val()
        };
    },

    onClickOrganization: function () {
        organizationIndex.showHideTab('tabs', true);
        organizationIndex.showHideTab('tabsOrganizationUnit', false);
        treeview.breadcrumbs[1] = undefined;
        treeview.DisplayBreadcrumb();
        jQuery("#JqGridOrganizationUnit").jqGrid('setGridParam', {
            mtype: "POST",
            url: "OrganizationUnit/DataBind",
            datatype: "json", // can also be xml
            postData: {
                orgaId: $('#Organization').val(),
                parentId: 0
            },
            el: "#right",
            absolute: true,
            page: 1
        }).trigger("reloadGrid");
    },

    onClickOrganizationUnit: function (data) {
        site.showForm('#tabsOrganizationUnit', { container: ".main-container" });
        var form = $(".editOrganizationUnit");
        form[0].reset();

        model = {
            ouId: data.OrganizationUnitId,
            organizationId: $("#Organization option:selected").val()
        };
        organizationIndex.showHideTab('tabs', false);
        organizationIndex.showHideTab('tabsOrganizationUnit', true);
        $(".unit-name").html("");
        $(".parent-unit-name").html("");
        $(".company-unit-name").html("");

        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/GetOrganizationUnitById',
            dataType: "json",
            data: model,
            el: "#tabsOrganizationUnit",
            absolute: true,
            success: function (result) {
                $(".unit-name").html(result.OrganizationUnitName);
                $(".parent-unit-name").html(result.ParentName);
                $('.company-unit-name').html(result.OrganizationName);

                $("#OrganizationUnitEdit_ParentId").val(data.parent);
                $("#OrganizationUnitEdit_OrganizationId").val(result.OrganizationId);
                $("#OrganizationUnitEdit_OrganizationUnitId").val(result.OrganizationUnitId);
                $("#OrganizationUnitEdit_OrganizationUnitName").val(result.OrganizationUnitName);
                $("#OrganizationUnit_OrganizationName").val(result.OrganizationName);
                $("#OrganizationUnit_ParentName").val(result.ParentName);
                $("#OrganizationUnitEdit_ValidityEndDate").val(result.ValidityEndDate);
                $("#OrganizationUnitEdit_ValidityStartDate").val(result.ValidityStartDate);
                $("#OrganizationUnitEdit_AccessControlReference").val(result.AccessControlReference);

                $("#OrganizationUnit_ValidityStartDate_Add_unit").val(result.ValidityStartDate);
                $("#OrganizationUnit_ValidityEndDate_Add_unit").val(result.ValidityEndDate);

                treeview.addLabel(form, result.Translations);

            }
        });

        return false;
    },

    addLabel: function (form, labels) {
        if (labels != undefined) {
            $.each(labels, function (index, value) {
                form.find("input[id*='" + index + "__Name']").val(value.Name);
            });
        }
        return false;
    },



};
var pass = {

    rowEditTemplate: undefined,


    init: function () {

        $("form").Spinner("show");
        pass.preCompletePassConfig();
        pass.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();
        $(".js-additemlist").off("click");
        $(".js-additemlist").click(function () {
            var elem = $(this).parents("form").first().find(".table-itemlist");
            window.pass.addItemList(elem);
            return false;
        });

        $(".btn-delete").click(window.pass.deleteItemList);

    },
    addItemList: function (elem, rule, zones) {
        var table = elem;
        var row = window.pass.rowEditTemplate;
        var lastRow = table.find("tbody tr").last().clone(true);

        var nb = 0;

        //si il y a deja une ligne dans le tableau
        if (lastRow[0] != undefined) {

            var html = lastRow.html();
            //j'incrémente les numéro contenu dans CustomChoises_0__Name et CustomChoises[0].Name
            var newHtml = html.replace(/(PrintingMockups_\d+)/g, function (match, str) {
                var number = str.replace("PrintingMockups_", "");
                nb = parseInt(number, 10) + 1;
                return "PrintingMockups_" + nb;
            });


            newHtml = newHtml.replace(/(PrintingMockups\[\d+)/g, function (match, str) {
                var number = str.replace("PrintingMockups[", "");
                nb = parseInt(number, 10) + 1;
                return "PrintingMockups[" + nb;
            });
            var order = $(lastRow).find(":input").val();
            lastRow.html(newHtml);
            lastRow.find(":input").val(parseInt(order) + 1);
            lastRow.find("option[selected]").removeAttr("selected");
        } else {
            var lastRow = row.clone(true);
        }


        lastRow.find(".btn-delete").click(window.pass.deleteItemList);
        //j'injecte la ligne à la fin du tableau
        lastRow.appendTo(table);
        table.parents(".container-itemlist").animate({ scrollTop: lastRow.offset().top }, 'fast');
        return false;
    },

    deleteItemList: function () {
        var elem = $(this).parents(".table-itemlist").first();

        $(this).parents("tr").first().remove();
        pass.refreshItemListIds(elem);
        return false;
    },

    refreshItemListIds: function (elem) {
        var i = -1;
        //on parcour toute les lignes du tableau 
        $(elem).find("tr").each(function () {
            // pour chaque input et span on met a jour leur id nom etc..
            $(this).find('select, input, span').each(function () {
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var datamsq = $(this).attr("data-valmsg-for");
                if (id) id = id.replace(/(\d+)/g, i);
                if (name) name = name.replace(/(\d+)/g, i);
                if (datamsq) datamsq = datamsq.replace(/(\d+)/g, i);
                $(this).attr("id", id);
                $(this).attr("name", name);
                $(this).attr("data-valmsg-for", datamsq);
            });
            i++;
        });

    },



    saveConfigOld: function () {
        var form = $("form").first();
        if (form.valid()) {
            var data = form.serialize();


            $.ajax({
                type: "POST",
                url: 'Pass/UpdatePassConfig',
                dataType: "json",
                data: data,
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                    }
                }
            });
        }
    },

    preCompletePassConfig: function () {

        $.ajax({
            type: "GET",
            url: 'Pass/GetPassConfiguration',
            dataType: "json",
            traditional: true,
            success: function (data) {
                $("form").Spinner("hide");
                $("#PassConfigMail_IsMailCampaignOpen")[0].checked = data.IsActive;

                if (!data.IsActive) {

                    $("#PassConfigMail_SendEmailAfterPassValidation").attr('disabled', 'disabled');
                    $("#PassConfigMail_SendAllEmailsNow").attr('disabled', 'disabled');
                    $(".listChildrenAffected").attr('disabled', 'disabled');
                    $(".listTypesAffected").attr('disabled', 'disabled');
                    $(".listUserTemplates").attr('disabled', 'disabled');
                    $(".listAssignmentTemplates").attr('disabled', 'disabled');

                  
                } else {

                    $("#PassConfigMail_SendEmailAfterPassValidation").removeAttr('disabled');
                    $("#PassConfigMail_SendAllEmailsNow").removeAttr('disabled');
                    $(".listChildrenAffected").removeAttr('disabled');
                    $(".listTypesAffected").removeAttr('disabled');
                    $(".listUserTemplates").removeAttr('disabled');
                    $(".listAssignmentTemplates").removeAttr('disabled');

                }
                $("#PassConfigMail_SendEmailAfterPassValidation")[0].checked = data.SendMailAfterPassValidation;
                $("#PassConfigMail_SendAllEmailsNow")[0].checked = data.SendAllEmailsNow;

                $('#PassConfigMail_EnableIndividualTitleSendingByMail').prop('checked', data.EnableIndividualTitleSendingByMail);
                $('#PassConfigMail_EnableVehicleTitleSendingByMail').prop('checked', data.EnableVehicleTitleSendingByMail);
                $('#PassConfigMail_EnableAnonymousTitleSendingByMail').prop('checked', data.EnableAnonymousTitleSendingByMail);
                $('#PassConfigMail_EnableGuestTitleSendingByMail').prop('checked', data.EnableGuestTitleSendingByMail);

            }
        });
    },

    saveConfig: function () {
        $("form").Spinner("show");
        var form = $("form").first();

        if (form.valid()) {
            var data = form.serialize();

            data += "&IsMailCampaignOpen=" + $("#PassConfigMail_IsMailCampaignOpen").is(":checked");
            data += "&SendEmailAfterPassValidation=" + $("#PassConfigMail_SendEmailAfterPassValidation").is(":checked");
            data += "&SendAllEmailsNow=" + $("#PassConfigMail_SendAllEmailsNow").is(":checked");
            data += "&EnableIndividualTitleSendingByMail=" + $("#PassConfigMail_EnableIndividualTitleSendingByMail").is(":checked");
            data += "&EnableGuestTitleSendingByMail=" + $("#PassConfigMail_EnableGuestTitleSendingByMail").is(":checked");
            data += "&EnableVehicleTitleSendingByMail=" + $("#PassConfigMail_EnableVehicleTitleSendingByMail").is(":checked");
            data += "&EnableAnonymousTitleSendingByMail=" + $("#PassConfigMail_EnableAnonymousTitleSendingByMail").is(":checked");
         
            $.ajax({
                type: "POST",
                url: 'Pass/UpdatePassConfig',
                dataType: "json",
                data: data,
                el: "#" + form.attr("id"),
                traditional: true,
                success: function (ret) {
                    $("form").Spinner("hide");
                    if (ret.Success) {
                        form.find(".cancel").trigger("click");
                        site.successMessage(resources.ValidationSuccess);
                    }
                    else {
                        if (ret.Exception !== null) {
                            site.errorMessage(ret.Exception);
                        } else {
                            site.errorMessage(resourcesMessages.ErrorOccured);
                        }
                    }
                }
            });
        }
        $("form").Spinner("hide");
    },


    openCampagnPass: function () {
        var isMailCampaignOpen = $("#PassConfigMail_IsMailCampaignOpen")[0].checked;
        if (!isMailCampaignOpen) {

            $("#PassConfigMail_SendEmailAfterPassValidation").attr('disabled', 'disabled');
            $("#PassConfigMail_SendAllEmailsNow").attr('disabled', 'disabled');
            $(".listChildrenAffected").attr('disabled', 'disabled');
            $(".listTypesAffected").attr('disabled', 'disabled');
            $(".listUserTemplates").attr('disabled', 'disabled');
            $(".listAssignmentTemplates").attr('disabled', 'disabled');
        } else {

            $("#PassConfigMail_SendEmailAfterPassValidation").removeAttr('disabled');
            $("#PassConfigMail_SendAllEmailsNow").removeAttr('disabled');
            $(".listChildrenAffected").removeAttr('disabled');
            $(".listTypesAffected").removeAttr('disabled');
            $(".listUserTemplates").removeAttr('disabled');
            $(".listAssignmentTemplates").removeAttr('disabled');
        }
    }
}
var profile = {
    params: {
        labelZones: "",
        labelSurZones: "",
        labelDefaultZones: ""
    },

    init: function (params) {

        $.extend(this.params, params);
        //initialization here
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    //Page générale
                    $("#labelSearch").html(resources.Organization_stadium);
                    $("#JqGrid").setLabel('OrganizationName', resources.Organization_stadium);

                    //Ajout / Edition
                    $("#editForm #labelOrganization").html(resources.Organization_stadium + ' *');
                    $("#addForm #labelOrganization").html(resources.Organization_stadium + ' *');
                }
            }
        });

        $("#editForm .submit").click(profile.EditFunction);

        $("#addForm .submit").click(profile.AddFunction);

        $("#actions .submit").click(profile.preRempAddFunction);
        $("#actions .delete").click(profile.delSelectedFunction);

        $("#searchForm").submit(profile.gridReload);

        $('.popover-item').popover();
        $("#ProfileModelAdd_OrganizationId, #ProfileModelEdit_OrganizationId").change(function () {
            $("#ProfileModelAdd_UnitIds").html("");
            $("#ProfileModelEdit_UnitIds").html("");
            site.initAjaxSelect();
            profile.initZoning(this);
        });
    },

    preRempEditFunction: function (id) {
        var ret = jQuery("#JqGrid").jqGrid('getRowData', id);
        site.showForm('#editForm', { container: ".main-container" });
        var form = $("#editForm");
        form[0].reset();
        $.ajax({
            type: "POST",
            url: "ProfileNew/BindProfileForm",
            data: { id: id },
            dataType: "json",
            traditional: true,
            el: "#editForm",
            success: function (ret) {
                var profileModel = ret.profile;
                var units = ret.units;

                profile.addLabel(form, ret.profile.Translations);

                form.find("input[name='ProfileModelEdit.ProfileId']").val(profileModel.ProfileId);
                form.find("select[name='ProfileModelEdit.OrganizationId']").val(profileModel.OrganizationId);
                form.find("input[name='ProfileModelEdit.Name']").val(profileModel.Name);
                form.find("[name='ProfileModelEdit.Definition']").val(profileModel.Definition);
                form.find("input[name='ProfileModelEdit.IsActive']")[0].checked = profileModel.IsActive;
                form.find("input[name='ProfileModelEdit.IsPrivate']")[0].checked = profileModel.IsPrivate;
                form.find("input[name='ProfileModelEdit.AccessControlReference']").val(profileModel.AccessControlReference);

                $("#ProfileModelEdit_UnitIds").html("");
                for (u in units) {
                    var item = units[u]
                    $("#ProfileModelEdit_UnitIds").append('<option selected="selected" value="' + item.OrganizationUnitId + '">' + item.OrganizationUnitName + '</option>');
                }

                profile.ManageAccessControlField("#editForm");

                zoningHelper.init($("#editForm"), ret.zones, false, profile.params.labelZones, profile.params.labelSurZones, profile.params.labelDefaultZones);
                for (z in profileModel.ZoneIds) {
                    var id = profileModel.ZoneIds[z]
                    $("#editForm #check_" + id).click();
                }
            }
        });
        return false;
    },

    ManageAccessControlField: function (element) {
        $.ajax({
            type: "POST",
            url: "ProfileNew/IsTechEvent",
            dataType: "json",
            traditional: true,
            success: function (ret) {
                if (!ret.IsTechEvent) {
                    $(".TechEventDiv").css("display", "none");
                }
            }
        });
    },

    preRempAddFunction: function () {
        profile.ManageAccessControlField("#addForm");
        site.showForm('#addForm', { container: ".main-container" });
        $("#addForm").find(".zoning").html("");
        $("#addForm")[0].reset();
    },



    AddFunction: function () {
        $("#addForm input[name='ProfileModelAdd.Name']").rules("add", "checkUniciteFunction");
        if ($("#addForm").valid()) {
            var model = $("#addForm").serialize();
            model = model + "&zoning=" + profile.postZoning('#addForm .zoning');

            $.ajax({
                type: "POST",
                url: 'ProfileNew/Add',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#addForm .cancel").click();
                        profile.gridReload();
                    }
                }
            });
        }
        return false;
    },

    EditFunction: function () {
        var form = $("#editForm");
        $("#editForm input[name='ProfileModelEdit.Name']").rules("add", "checkUniciteFunction");

        if (form.valid()) {
            var model = $("#editForm").serialize();
            model = model + "&zoning=" + profile.postZoning('#editForm .zoning');

            $.ajax({
                type: "POST",
                url: 'ProfileNew/Edit',
                dataType: "json",
                data: model,
                el: "#editForm",
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#editForm .cancel").click();
                        profile.gridReload();
                    }
                }
            });
        }
        return false;
    },

    DisableFunction: function (elem) {
        $.ajax({
            type: "POST",
            url: 'ProfileNew/DisableProfile',
            dataType: "json",
            data: { profileId: $(elem).val(), isActive: $(elem).is(":checked") },
            success: function (result) {
                if (result.Success) {

                }
            }
        });
    },

    postZoning: function (c) {
        var vals = "";
        $(c + " input[type='checkbox']:checked").each(function () {
            vals += this.id + ";";
        });
        vals += ";";
        return vals.replace(";;", "");
    },

    addLabel: function (form, labels) {
        if (labels != undefined) {
            $.each(labels, function (index, value) {
                form.find("input[id*='" + index + "__Name']").val(value.Name);
            });
        }
        return false;
    },

    initZoning: function (elem) {
        var organizationId = $(elem).val();
        if (organizationId) {
            var model = {
                id: organizationId
            };
            var form = $("#addForm");
            $.ajax({
                type: "POST",
                url: 'ZoneNew/GetZonesByOrga',
                dataType: "json",
                data: model,
                success: function (result) {
                    zoningHelper.init($("#addForm"), result.Zones, false, profile.params.labelZones, profile.params.labelSurZones, profile.params.labelDefaultZones);
                    zoningHelper.init($("#editForm"), result.Zones, false, profile.params.labelZones, profile.params.labelSurZones, profile.params.labelDefaultZones);
                }
            });
        }
        return false;
    },

    getSelect2Params: function (params) {
        if ($("#addForm").is(":visible")) {
            params["organizationId"] = $("#ProfileModelAdd_OrganizationId").val();
        } else {
            params["organizationId"] = $("#ProfileModelEdit_OrganizationId").val();
        }
        return params;

    },

    gridCompleteFunction: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var data = jQuery("#JqGrid").jqGrid('getRowData', cl);
            var ed = "";
            if (site.hasPermission(right.Profile_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='profile.preRempEditFunction(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            }

            var checked = '';
            if (data.IsActive == "true") {
                checked = 'checked="checked"';
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: ed, IsActive: '<label class="switch-label"><input onclick="return profile.DisableFunction(this)" ' + checked + ' class="ace ace-switch ace-switch-6 btn-rotate" type="checkbox" value="' + data.ProfileId + '"/><span class="lbl"></span></label>' });
        }
    },

    DisableFunction: function (elem) {
        $.ajax({
            type: "POST",
            url: 'ProfileNew/DisableProfile',
            dataType: "json",
            data: { profileId: $(elem).val(), isActive: $(elem).is(":checked") },
            success: function (result) {
                if (result.Success) {
                }
            }
        });
    },


    delSelectedFunction: function () {
        var ok
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(resourcesMessages.AtLeastOneFunctionSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'ProfileNew/DeleteSelected',
                        dataType: "json",
                        el: "#tabs-function",
                        data: { ids: s },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            profile.gridReload();
                        }
                    });
                }
            });
        }
    },

    gridReload: function () {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "ProfileNew/DataBind?" + data,
            page: 1,
            editurl: '/ProfileNew/JqGridOnUpdate'
        }).trigger("reloadGrid");
    }
}
var provider = {

    params: {
        messageAtLeastOneProviderSelected: ""
    },

    init: function (params) {
        $.extend(this.params, params);

        $("#search").submit(provider.gridReload);

        $(".grid-header .submit").click(provider.preRempAdd);
        $(".grid-header .delete").click(provider.deleteAll);

        $("#editForm, #addFormProvider").submit(function () { return false; });

        $("#validateForm .validate").click(provider.validate);
        $("#validateForm .cancel").click(function () { site.hideForm('#validateForm', { container: ".main-container" }); });
        $("#validateForm .refused").click(provider.refused);

        $("#editForm .submit").click(provider.edit);

        $("#addFormProvider .submit").click(provider.add);
        $("#addFormProvider .cancel").click(function () {
            site.hideForm('#addFormProvider', { container: ".main-container" });
        });

        $("#Provider_NationalityId").change(provider.GetNationality);

        $("#exportAll").click(provider.exportAll);

        ////Init checkbox type access
        $('#Provider_IsBillingProfil').change(function () {
            if (this.checked) {
                params.IsBillingProfil = true;
            }
            else {
                params.IsBillingProfil = false;
            }
        });

        // activate & disable param UseBilling
        var code = ['UseBilling'];
        $.ajax({
            type: "POST",
            url: 'Parameter/GetParametersByCode',
            dataType: "json",
            data: { codes: code },
            traditional: true,
            success: function (data) {

                if (data[0].Value == true) {
                    $('.UseBilling').show();
                }
                else {
                    $('.UseBilling').hide();
                }
            }
        });
      
    },

    refused: function () {
        var providerId = $("#ProviderValidate_ProviderId").val();
        var ok;
        jConfirm(resourcesMessages.RefusedProviderRegistration, 'Attention', function (ok) {
            if (ok) {
                $.ajax(
                    {
                        type: "POST",
                        url: 'Provider/DeleteSelected',
                        dataType: "json",
                        data: { provIds: providerId, approvalComment: $("#ProviderValidate_ApprovalComment").val() },
                        traditional: true,
                        el: jQuery("#JqGrid, #validateForm"),
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                                $("#validateForm .cancel").trigger("click");
                                $("#JqGrid").trigger("reloadGrid");
                            } else {
                                if (ret.data && ret.data.HasAssignmentOnPassedEvent) {
                                    jConfirm(resourcesMessages.AlreadyExistingAssignmentsOnPassedEvent, resources.Warning, function (ok) {
                                        if (ok && window.ids != "") {
                                            $.ajax(
                                                {
                                                    type: "POST",
                                                    url: 'Provider/DisableSelected',
                                                    dataType: "json",
                                                    data: { provIds: providerId, approvalComment: $("#ProviderValidate_ApprovalComment").val() },
                                                    traditional: true,
                                                    el: jQuery("#JqGrid, #validateForm"),
                                                    success: function (ret) {
                                                        if (ret.Success) {
                                                            site.successMessage(resourcesMessages.DisableProviderSuccess);
                                                            $("#validateForm .cancel").trigger("click");
                                                            $("#JqGrid").trigger("reloadGrid");
                                                        } else {
                                                            site.errorMessage(resourcesMessages.DisableProviderFailed, ret.Exception);
                                                        }
                                                    }
                                                });
                                        }
                                    });
                                } else
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                        }
                    });
            }
        });
    },

    preRempForm: function (id, formId) {
        var form = $(formId);
        site.showForm(formId, { container: ".main-container" });
        $.ajax({
            type: "POST",
            url: 'Provider/BindProviderForm',
            dataType: "json",
            el: formId,
            data: { id: id },
            traditional: true,
            success: function (ret) {
                form.find('[name*="ProviderId"]').val(ret.ProviderId);
                form.find('[name*="Name"]').val(ret.Name);
                if (ret.ParentProviderId) {
                    form.find('[name*="ParentProviderId"]').addOption({ value: ret.ParentProviderId, text: ret.ParentProvider.Name });
                }
                form.find('[name*=".ParentProviderId"]').val(ret.ParentProviderId);
                form.find('[name*=".IndustryId"]').val(ret.IndustryId);
                form.find('[name*=".SportIds"]').val(ret.SportIds);
                form.find('[name*=".UnitIds"]').val(ret.UnitIds);
                form.find('[name*=".Address"]').val(ret.Address);
                form.find('[name*=".PostalCode"]').val(ret.PostalCode);
                form.find('[name*=".City"]').val(ret.City);
                form.find('[name*=".NationalityId"]').val(ret.NationalityId);
                form.find('[name*=".PhoneNumber"]').val(ret.PhoneNumber);
                form.find('[name*=".Email"]').val(ret.Email);
                form.find('[name*=".Comment"]').val(ret.Comment);
                form.find('[name*=".ApprovalComment"]').val(ret.ApprovalComment);
                form.find('[name*=".ValueRights"]').val(ret.ValueRights);
                form.find('[name*=".CategoryIds"]').val(ret.CategoryIds);
                form.find('[name*=".IsBillingProfil"]').prop('checked', ret.IsBillingProfil);



               

                var tab = form.find('.tab-users');
                tab.html("");

                if (ret.Users.length == 0) {
                    tab.html(resourcesMessages.NoReferentContact);
                }


                for (i = 0; i < ret.Users.length; i++) {

                    var td = '<tr><td>' + ret.Users[i].LastName + ' ' + ret.Users[i].FirstName;

                    if (ret.Users[i].Function != null) {
                        td = td + ' (' + ret.Users[i].Function + ')</td><td>' + ret.Users[i].Email + '</td><td>' + ret.Users[i].MobilePhoneNumber + '</td></tr>';
                    }
                    tab.append(td);
                }


                var createdby = form.find('.createdby');
                createdby.html("");
                if (ret.CreateBy != null) {
                    var creator = resourcesMessages.CreateBy.replace("{0}", ret.CreateBy.LastName + " " + ret.CreateBy.FirstName + " (" + ret.CreateBy.Login + ")").replace("{1}", ret.CreationDate);
                    createdby.html(creator);
                }
                var updatedby = form.find('.updatedby');
                updatedby.html("");
                if (ret.LastUpdateBy != null) {
                    var updater = resourcesMessages.LastUpdateBy.replace("{0}", ret.LastUpdateBy.LastName + " " + ret.LastUpdateBy.FirstName + " (" + ret.LastUpdateBy.Login + ")").replace("{1}", ret.LastUpdateDate);
                    updatedby.html(updater);
                }

                if (ret.IsApproved) {
                    if ($(".category-ids").hasClass("hidden")) {
                        $(".category-ids").removeClass("hidden");
                    }
                } else {
                    if (!$(".category-ids").hasClass("hidden")) {
                        $(".category-ids").addClass("hidden");
                    }
                }
            }
        });
    },


    preRempAdd: function () {
        $("#addFormProvider")[0].reset();
        site.showForm('#addFormProvider', { container: ".main-container" });
        $("#add #Provider_Name").val("");
        $("#add #Provider_CanGrantEventAccess").prop('checked', true);
        $("#add #Provider_CanGrantStepAccess").prop('checked', true);
        $("#add #Provider_isBillingProfil").prop('checked',true);
        $(".select2-default").css("width", "100%").select2({ dropdownAutoWidth: true });
        site.initAjaxSelect();

        if (site.params.userName !== undefined && site.params.userName !== null) {
            if ($(".category-ids").hasClass("hidden")) {
                $(".category-ids").removeClass("hidden");
            }
        } else {
            if (!$(".category-ids").hasClass("hidden")) {
                $(".category-ids").addClass("hidden");
            }
        }
    },

    GetNationality: function () {
        var elem = $(this);
        var form = elem.parents("form").first();
        $.ajax({
            type: "POST",
            url: 'Provider/GetNationality',
            dataType: "json",
            data: { nationalityId: elem.val() },
            traditional: true,
            el: ".PhoneNumber",
            success: function (data) {
                if (form.find(".PhoneNumber").val() == "") {
                    form.find(".PhoneNumber").val("+" + data.DiallingCode);
                }
                var elems = form.find("[id *= 'MobilePhoneNumber']");
                for (var i = 0; i < elems.length; i++) {
                    jelem = $(elems[i]);
                    if (jelem.val() == "") {
                        jelem.val("+" + data.DiallingCode);
                    }
                }
            }
        });
    },

    add: function () {
        $("#addFormProvider #Provider_Name").rules("add", "checkUniciteProviderOnAdd");

        if ($("#addFormProvider").valid()) {
            var data = $("#addFormProvider").serialize();
            $.ajax({
                type: "POST",
                url: 'Provider/Add',
                dataType: "json",
                data: data,
                el: "#addFormProvider",
                traditional: true,
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                    } else {
                        site.errorMessage(resourcesMessages.NoSendMessage, data.Exception);
                    }

                    provider.gridReload();
                    $("#addFormProvider .cancel").trigger("click");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    edit: function () {
        $("#editForm #ProviderEdit_ParentProviderId").rules("add", "checkProvider");
        $("#editForm #ProviderEdit_Name").rules("add", "checkUniciteProvider");
        if ($("#editForm").valid()) {
            var data = $("#editForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Provider/Edit',
                dataType: "json",
                data: data,
                traditional: true,
                el: "#editForm",
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        provider.gridReload();
                        $("#editForm .cancel").trigger("click");
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    validate: function () {
        $("#validateForm #ProviderValidate_Name").rules("add", "checkUniciteProvider");
        if ($("#validateForm").valid()) {
            var data = $("#validateForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Provider/Validate',
                dataType: "json",
                data: data,
                traditional: true,
                el: "#validateForm",
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        provider.gridReload();
                        $("#validateForm .cancel").trigger("click");
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },

    deleteAll: function (ids) {
        if (!Array.isArray(ids))
            ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');

        if (ids == "") {
            jAlert(provider.params.messageAtLeastOneProviderSelected, resources.Warning);
        } else {
            var ok;
            window.ids = ids;
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && window.ids != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'Provider/DeleteSelected',
                            dataType: "json",
                            data: { provIds: window.ids },
                            traditional: true,
                            el: jQuery("#JqGrid, #validateForm"),
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                    $("#validateForm .cancel").trigger("click");
                                    $("#JqGrid").trigger("reloadGrid");
                                } else {
                                    if (ret.data && ret.data.HasAssignmentOnPassedEvent) {
                                        jConfirm(resourcesMessages.AlreadyExistingAssignmentsOnPassedEvent, resources.Warning, function (ok) {
                                            if (ok && window.ids != "") {
                                                $.ajax(
                                                    {
                                                        type: "POST",
                                                        url: 'Provider/DisableSelected',
                                                        dataType: "json",
                                                        data: { provIds: window.ids },
                                                        traditional: true,
                                                        el: jQuery("#JqGrid, #validateForm"),
                                                        success: function (ret) {
                                                            if (ret.Success) {
                                                                site.successMessage(resourcesMessages.DisableProviderSuccess);
                                                                $("#validateForm .cancel").trigger("click");
                                                                $("#JqGrid").trigger("reloadGrid");
                                                            } else {
                                                                site.errorMessage(resourcesMessages.DisableProviderFailed, ret.Exception);
                                                            }
                                                        }
                                                    });
                                            }
                                        });
                                    } else
                                        site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                            }
                        });
                }
            });
        }
    },

    exportAll: function () {
        var search = $("#search").serialize();
        window.open("/Provider/Export?" + search, "_blank");
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var edProv = "";
            var status = "";

            if (data.IsApproved == "true") {
                if (site.hasPermission(right.Provider_Edit)) {
                    edProv = "<button class='btn btn-circle btn-primary' onclick='provider.preRempForm(" + cl + ", \"#editForm\");'><i type='button' class='fa fa-pencil'></i></button>";
                }
                status = '<span class="badge circle Validated" title="Validée">&nbsp;</span>';
            } else {

                if (site.hasPermission(right.Provider_Validate)) {
                    edProv = "<button class='btn btn-circle btn-primary' onclick='provider.preRempForm(" + cl + ", \"#validateForm\");'><i type='button' class='fa fa-check'></i></button>";
                }
                status = '<span class="badge circle Waiting" title="A traiter">&nbsp;</span>';
            }
            var name = "<strong>" + data.Name + "</strong>";
            if (data.ParentProvider)
                name += " <small>(" + data.ParentProvider + ")</small>";

            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { Name: name, IsApproved: status, act: edProv });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});

        // var pager = $("#PagerJqGrid").detach();
        // $(pager).css("width", "500px");
        // $(".pagerContainer").append(pager);
    },

    gridReload: function () {
        var test = $("#search").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Provider/DataBind?" + test,
            page: 1
        }).trigger("reloadGrid");

        return false;
    }
}
var registration = {


    params: {
        messageAtLeastOneProviderSelected: "",
        useBilling: false
    },

    init: function (params) {
        $.extend(this.params, params);

        $("#editForm, #addFormProvider").submit(function () { return false; });

        $("#addFormProvider .submit").click(registration.add);

        $("#Provider_NationalityId").change(provider.GetNationality);

        $(".js-adduserlist").click(function () {
            var elem = $(".user-list");
            registration.addUserlist(elem);
            return false;
        });
        $('input[name*="LastName"]').keyup(registration.setLogin).click(registration.setLogin);
        $('input[name*="FirstName"]').keyup(registration.setLogin).click(registration.setLogin);

        if (params.useBilling === "True") { //the stored parameter is a string with capital T
            $('.UseBilling').show();
        }
        else {
            $('.UseBilling').hide();
        }
    },

    setLogin: function () {
        var nb = $(this)[0].id.match(/\d+/)[0]; 
        $('#Provider_Users_' + nb + '__Login').val($('#Provider_Users_' + nb + '__FirstName').val().charAt(0) + $('#Provider_Users_' + nb + '__LastName').val().replace(/ /g, ""));
    },
    
    GetNationality: function () {
        var elem = $(this);
        var form = elem.parents("form").first();
        $.ajax({
            type: "POST",
            url: 'Provider/GetNationality',
            dataType: "json",
            data: { nationalityId: elem.val() },
            traditional: true,
            el: ".PhoneNumber",
            success: function (data) {
                if (form.find(".PhoneNumber").val() == "") {
                    form.find(".PhoneNumber").val("+" + data.DiallingCode);
                }
                var elems = form.find("[id *= 'MobilePhoneNumber']");
                for (var i = 0; i < elems.length; i++) {
                    jelem = $(elems[i]);
                    if (jelem.val() == "") {
                        jelem.val("+" + data.DiallingCode);
                    }
                }
            }
        });
    },

    add: function () {
        $("#addFormProvider #Provider_Name").rules("add", "checkUniciteProviderOnAdd");
        $("#addFormProvider [name*='Login']").each(function () {
            $(this).rules("add", "checkUniciteUserOnAdd");
            $(this).rules("add", "sameLoginInForm");

        });

        if ($("#addFormProvider").valid()) {
            var data = $("#addFormProvider").serialize();
            $.ajax({
                type: "POST",
                url: 'Provider/Add',
                dataType: "json",
                data: data,
                el: "#addFormProvider",
                traditional: true,
                success: function (ret) {
                    $(".registration-confirmation").show();
                    $("#addFormProvider").hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
        return true;
    },


    addUserlist: function (elem, choise) {
        var table = elem;
        //on récupere la derniere ligne du tableau
        var lastRow = table.find(".user-form").last().clone(true);
        lastRow.find(".separator").remove();
        var nb = 0;

        //si il y a deja une ligne dans le tableau
        if (lastRow[0] != undefined) {
            var elems = lastRow.find("[name*='Provider.Users'], span");
            for (var i = 0; i < elems.length; i++) {
                var elem = $(elems[i]);
                var newName = elem.attr("name");
                var newId = elem.attr("id");
                var newClass = elem.attr("class");
                var err = elem.attr("data-valmsg-for");

                if (err) {
                    elem.attr("data-valmsg-for", err.replace(/(\d+)/g, registration.replaceNumber));
                }
                if (newName) {
                    elem.attr("name", newName.replace(/(\d+)/g, registration.replaceNumber));
                }

                if (newId) {
                    elem.attr("id", newId.replace(/(\d+)/g, registration.replaceNumber));
                }

                if (newClass) {
                    elem.attr("class", newClass.replace(/(\d+)/g, registration.replaceNumber));
                }
            }
        }
        var html = lastRow.html();
        lastRow.html("<div class='separator-table'><div class='separator'><hr /></div><a class='btn btn-link separator-link' onclick='registration.delUserlist(this)'>" + resources.Delete + "</a></div>" + html);

        lastRow.find("[name*='LastName']").keyup(registration.setLogin).click(registration.setLogin);
        lastRow.find("[name*='FirstName']").keyup(registration.setLogin).click(registration.setLogin);
        //j'injecte la ligne à la fin du tableau
        lastRow.appendTo(table);

        $("form").removeData("validator").removeData("unobtrusiveValidation");

        //Parse the form again
        $.validator.unobtrusive.parse("form");


        table.parents(".container-itemlist").animate({ scrollTop: lastRow.offset().top }, 'fast');

        return false;
    },

    delUserlist: function (element) {

        var elem = $(element).parents(".user-form").first();
        $(element).remove();
        elem.remove();
    },


    replaceNumber: function (match, number) {
        nb = parseInt(number, 10) + 1;
        return nb;
    }
}
var rgpd = {
    params: {},
    rowEditTemplate: null,

    init: function (params) {
        $.fn.editable.defaults.mode = 'inline';
        $.fn.editable.defaults.url = '/PrivatePolicy/Update';

        /* Editable */

        $("#rgpd_fr").editable({ wysihtml5: { "image": false } });
        $("#rgpd_en").editable({ wysihtml5: { "image": false } });
        $("#rgpd_es").editable({ wysihtml5: { "image": false } });

        $("#cgu_fr").editable({ wysihtml5: { "image": false } });
        $("#cgu_en").editable({ wysihtml5: { "image": false } });
        $("#cgu_es").editable({ wysihtml5: { "image": false } });

        $("#export_fr").editable({ wysihtml5: { "image": false } });
        $("#export_en").editable({ wysihtml5: { "image": false } });
        $("#export_es").editable({ wysihtml5: { "image": false } });

        $("#cookies_fr").editable({ wysihtml5: { "image": false } });
        $("#cookies_en").editable({ wysihtml5: { "image": false } });
        $("#cookies_es").editable({ wysihtml5: { "image": false } });

        /* END Editable */

        $("#rgpdEditFr").click(rgpd.rgpdEditFr);
        $("#rgpdEditEn").click(rgpd.rgpdEditEn);
        $("#rgpdEditEs").click(rgpd.rgpdEditEs);

        $("#cguEditFr").click(rgpd.cguEditFr);
        $("#cguEditEn").click(rgpd.cguEditEn);
        $("#cguEditEs").click(rgpd.cguEditEs);

        $("#exportEditFr").click(rgpd.exportEditFr);
        $("#exportEditEn").click(rgpd.exportEditEn);
        $("#exportEditEs").click(rgpd.exportEditEs);

        $("#cookiesEditFr").click(rgpd.cookiesEditFr);
        $("#cookiesEditEn").click(rgpd.cookiesEditEn);
        $("#cookiesEditEs").click(rgpd.cookiesEditEs);


        $(".js-additemlist").click(function () {
            var elem = $(this).parents("form").first().find(".table-itemlist");
            window.rgpd.addItemList(elem);
            return false;
        });

        $(".table-itemlist").find("tbody tr").find(".btn-delete").click(function () {
            var row = $(this).parent("td").parent("tr");
            window.rgpd.deleteItemList(row);
        });
        $(".table-itemlist").find("tbody tr").find(".btn-update").click(function () {
            var row = $(this).parent("td").parent("tr");
            $(row).find("button").attr("disabled", true);
            window.rgpd.saveCheckBoxRow(row);
        });
    },

    addItemList: function (elem) {
        var table = elem;
        var row = $(".table-itemlist").find("tbody tr").last().clone();
        var nb = 1;
        if (row.find("input[name='order']")[0] != undefined && !isNaN(parseInt(row.find("input[name='order']").val()))) {
            nb = parseInt(row.find("input[name='order']").val());
        }
        row.removeClass("row-template");
        row.find("input[name='order']").val(nb + 1);
        row.find("input[name='name']").val("");
        row.find("input[name='value']").val("");

        row.find(".btn-delete").click(function () {
            var row = $(this).parent("td").parent("tr");
            window.rgpd.deleteItemList(row);
        });
        row.find(".btn-update").click(function () {
            var row = $(this).parent("td").parent("tr");
            $(row).find("button").attr("disabled", true);
            window.rgpd.saveCheckBoxRow(row);
        });

        row.addClass("newItemRow");
        row.appendTo(table);

        return false;
    },

    saveCheckBoxRow: function (row) {
        var checkBoxesModelToSave = {
            Name: $(row).find("input[name='name']").val(),
            Checkboxes: []
        };
        var requiredInputError = false;
        row.find("input").removeClass("textbox-error");
        $(row).find("[data-checkbox]").each(function () {
            var checkbox = {
                Value: $(this).find("input[name='value']").val(),
                Language: $(this).find("input[name='language']").val(),
            };

            if (checkbox.Value == "") {
                requiredInputError = true;
                $(this).find("input[name='value']").addClass("textbox-error");
            }
            checkBoxesModelToSave.Checkboxes.push(checkbox);
        });
        if (requiredInputError) {
            jAlert(resourcesMessages.MissingRequiredFields, resources.Warning);
            $(row).find("button").attr("disabled", false);
        } else {
            $.ajax({
                type: "POST",
                url: 'PrivatePolicy/UpdateCheckBoxes',
                dataType: "json",
                data: $.param(checkBoxesModelToSave),
                traditional: true,
                success: function (ret) {
                    if (ret.success) {
                        row.removeClass("newItemRow");
                        row.find("input").removeClass("textbox-error");
                        if (ret.code != "") {
                            $(row).find("input[name='name']").val(ret.code)
                        }
                        site.successMessage(resources.ValidationSuccess);
                    }
                }
            }).done(function () {
                $(row).find("button").attr("disabled", false);
            });
        }
    },

    deleteItemList: function (row) {
        var checkBoxesModelToDelete = {
            Name: $(row).find("input[name='name']").val(),
        };
        
        jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
            var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
            if (ok && s != "") {
                if ($(row).hasClass("newItemRow")) {
                    $(row).remove();
                } else {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'PrivatePolicy/DeleteCheckBoxes',
                            dataType: "json",
                            data: $.param(checkBoxesModelToDelete),
                            traditional: true,
                            success: function (ret) {
                                if (ret.success) {
                                    $(row).remove();
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                            }
                        });
                }
            }
        });
        return false;
    },

    /* RGPD */
    rgpdEditFr: function (e, sender) {
        e.stopPropagation();
        e.preventDefault();
        $('#rgpd_fr').editable('toggle');
    },

    rgpdEditEn: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#rgpd_en').editable('toggle');
    },

    rgpdEditEs: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#rgpd_es').editable('toggle');
    },

    /* CGU */
    cguEditFr: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cgu_fr').editable('toggle');
    },

    cguEditEn: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cgu_en').editable('toggle');
    },

    cguEditEs: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cgu_es').editable('toggle');
    },

    /* Export */

    exportEditFr: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#export_fr').editable('toggle');
    },

    exportEditEn: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#export_en').editable('toggle');
    },

    exportEditEs: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#export_es').editable('toggle');
    },

    /* Cookies */
    cookiesEditFr: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cookies_fr').editable('toggle');
    },

    cookiesEditEn: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cookies_en').editable('toggle');
    },

    cookiesEditEs: function (e) {
        e.stopPropagation();
        e.preventDefault();
        $('#cookies_es').editable('toggle');
    },

    acceptCookies: function () {
        $.cookie("AcceptCookies", true);
        $("#AcceptCookies").remove();
    },
}
const right = {
    Assignment_Index: 1,
    Assignment_Export: 2,
    Assignment_DataBind: 3,
    Assignment_GetSearchCustomFields: 4,
    Assignment_GetRichStatusForAssignment: 5,
    Assignment_GetAssignmentStatistics: 6,
    Assignment_Valid: 7,
    Assignment_Cancel: 8,
    Assignment_Modify: 9,
    Assignment_ModifyVehicle: 10,
    Assignment_ModifyGuest: 11,
    Assignment_Delete: 12,
    Assignment_GetActionsByAssignmentId: 13,
    Assignment_GetReprintingReasonByAssignmentId: 14,
    Assignment_GetUnlimitedEvents: 15,
    Assignment_GetAssignment: 16,
    Assignment_GetLastAssignmentByIndividualId: 17,
    Assignment_GetLastAssignmentByVehicleId: 18,
    Assignment_GetZones: 19,
    Assignment_GetFormDefaultValues: 20,
    Assignment_GetUnAssignedIndividual: 21,
    Assignment_GetAvailableIndividualForVehicle: 22,
    Assignment_GetAvailableVehicleForVehicle: 23,
    Assignment_AddAnonymous: 24,
    Assignment_AddGuest: 25,
    Assignment_ModifyAndValideAssignments: 26,
    Assignment_ModifyAssignments: 27,
    Assignment_ModifyVehicles: 28,
    Assignment_ModifyAndValidateVehicles: 29,
    Assignment_Add: 30,
    Assignment_AddVehicle: 31,
    Assignment_BindUnitField: 32,
    Assignment_HasAssignmentNumberExceeded: 33,
    Assignment_GetImportTemplate: 34,
    Assignment_IncrementPrintCount: 35,
    Assignment_GetPdfs: 36,
    Assignment_GetFileByName: 37,
    Assignment_GetDoubles: 38,
    Assignment_SendAccreditations: 39,
    Assignment_Import: 40,
    Assignment_GetImportAssignmentTemplate: 41,
    Assignment_GetAllAssignmentTypes: 42,
    Assignment_EnterExitAssignment: 43,
    Assignment_GetAssignments: 44,
    Individual_IsValidDate: 45,
    Individual_IsFunctionPresent: 46,
    Individual_IsUnique: 47,
    Individual_UploadPicture: 48,
    Individual_GetIndividual: 49,
    Individual_DataBind: 50,
    Individual_GetSearchCustomFields: 51,
    Individual_Add: 52,
    Individual_Delete: 53,
    Individual_Webcam: 54,
    Individual_Import: 55,
    Individual_Export: 56,
    Individual_GetPartial: 57,
    Individual_GetIndividuals: 58,
    Individual_GetCustomFields: 59,
    Individual_GetImportIndividualTemplate: 60,
    Pass_GetPassMockups: 61,
    Pass_GetPassConfiguration: 62,
    Pass_GetPassZones: 63,
    Pass_GetActionsByPassId: 64,
    Pass_GetReprintingReasonByPassId: 65,
    Pass_Index: 66,
    Pass_GetSearchCustomFields: 67,
    Pass_GetRichStatusForPass: 68,
    Pass_GetPassCustomFields: 69,
    Pass_UpdatePassConfig: 70,
    Pass_Import: 71,
    Pass_GetImportPassTemplate: 72,
    Pass_Export: 73,
    Pass_AddVehiclePass: 74,
    Pass_GetAvailableIndividualForPass: 75,
    Pass_GetAvailableVehicleForPass: 76,
    Pass_Cancel: 77,
    Pass_ModifyIndividualPass: 78,
    Pass_ModifyVehiclePass: 79,
    Pass_ModifyGuestPass: 80,
    Pass_AddGuest: 81,
    Pass_IncrementPrintCount: 82,
    Pass_GetPdfs: 83,
    Pass_GetFileByName: 84,
    Pass_GetPass: 85,
    Pass_DataBind: 86,
    Pass_Delete: 87,
    Pass_GetDefaultPassOrganizationId: 88,
    Pass_GetUnAssignedIndividual: 89,
    Pass_Valid: 90,
    Pass_AddIndividualPass: 91,
    Pass_EnterExitPass: 92,
    User_Index: 93,
    User_GetRoles: 94,
    User_GetProviders: 95,
    User_CheckUnicite: 96,
    User_DeleteSelected: 97,
    User_RegeneratePasswordSelected: 98,
    User_DataBind: 99,
    User_BindUserForm: 100,
    User_Add: 101,
    User_Edit: 102,
    User_GetUsers: 103,
    User_GetUnitUsers: 104,
    User_GetUsersByProviderId: 105,
    User_Import: 106,
    User_GetImportUserTemplate: 107,
    Event_Index: 108,
    Event_RefreshMockup: 109,
    Event_GetEventById: 110,
    Event_CheckUniciteCodeEvent: 111,
    Event_CanEditOrganization: 112,
    Event_compareDate: 113,
    Event_DataBind: 114,
    Event_BindEventAddForm: 115,
    Event_BindEventEditForm: 116,
    Event_BindEventMailConfigurationForm: 117,
    Event_Edit: 118,
    Event_Add: 119,
    Event_DuplicateEstimation: 120,
    Event_Delete: 121,
    Event_GetEventConfiguration: 122,
    //Event_GetEventsSelect: 123,
    Event_GetEvents: 124,
    Event_GetEventSteps: 125,
    //Event_GetOrganizationIdForEvent: 126,
    Event_EditMailConfiguration: 127,
    Organization_Index: 128,
    Organization_Add: 129,
    Organization_DataBind: 130,
    Organization_GetOrganizations: 131,
    Organization_GetOrgaInfo: 132,
    Organization_CheckUniciteOnAdd: 133,
    Organization_CheckUniciteOnEdit: 134,
    Organization_Duplicate: 135,
    Organization_Delete: 136,
    Organization_DeleteSelected: 137,
    Organization_Edit: 138,
    Organization_GetContextOrganization: 139,
    PrivatePolicy_Index: 140,
    PrivatePolicy_Update: 141,
    Profile_Index: 142,
    Profile_CheckUnicite: 143,
    Profile_DataBind: 144,
    Profile_JqGridOnEdit: 145,
    Profile_Add: 146,
    Profile_Edit: 147,
    Profile_DisableProfile: 148,
    Profile_DeleteSelected: 149,
    Profile_BindProfileForm: 150,
    Profile_GetProfiles: 151,
    Profile_GetProfilesForUnit: 152,
    Provider_Index: 153,
    Provider_Registration: 154,
    Provider_CheckUnicite: 155,
    Provider_DataBind: 156,
    Provider_BindProviderForm: 157,
    Provider_Edit: 158,
    Provider_Validate: 159,
    Provider_DeleteSelected: 160,
    Provider_GetUnitProviders: 161,
    Provider_Import: 162,
    Provider_Export: 163,
    Provider_GetImportProviderTemplate: 164,
    Provider_GetNationalities: 165,
    CustomContent_Index: 166,
    CustomContent_Update: 167,
    CustomContent_GetAll: 168,
    CustomContent_GetAllHomePageCustomContent: 169,
    CustomField_Index: 170,
    CustomField_DataBind: 171,
    CustomField_BindCustomFieldEditForm: 172,
    CustomField_Add: 173,
    CustomField_UpdateImportVehicleTemplateFile: 174,
    CustomField_Edit: 175,
    CustomField_Delete: 176,
    Mockup_Index: 177,
    Mockup_Background: 178,
    Mockup_BackgroundDataBind: 179,
    Mockup_IsBackgroundMockupUnique: 180,
    Mockup_Add: 181,
    Mockup_Edit: 182,
    Mockup_DeleteSelected: 183,
    Mockup_BindBackgroundMockupForm: 184,
    Parameter_CheckUnicite: 185,
    Parameter_Edit: 186,
    Parameter_DataBind: 187,
    Sport_Index: 188,
    Sport_DataBind: 189,
    Sport_BindSportForm: 190,
    Sport_DeleteSelected: 191,
    Sport_Add: 192,
    Sport_Edit: 193,
    Sport_CheckUnicite: 194,
    Vehicle_Index: 195,
    Vehicle_DataBind: 196,
    Vehicle_Add: 197,
    Vehicle_Delete: 198,
    Vehicle_GetVehicle: 199,
    Vehicle_GetPartial: 200,
    Vehicle_IsVehicleNumberEditable: 201,
    Vehicle_GetCustomFields: 202,
    Vehicle_Import: 203,
    Vehicle_GetImportVehicleTemplate: 204,
    Vehicle_Export: 205,
    Vehicle_Edit: 206,
    VehicleNumber_Index: 207,
    VehicleNumber_DataBindVehicleNumber: 208,
    VehicleNumber_Add: 209,
    VehicleNumber_Edit: 210,
    VehicleNumber_GetRangeTypes: 211,
    VehicleNumber_BindVehicleNumberEditForm: 212,
    VehicleNumber_BindVehicleNumberAddForm: 213,
    VehicleNumber_DeleteVehicleNumber: 214,
    Zone_Index: 215,
    Zone_CheckUnicite: 216,
    Zone_DataBind: 217,
    Zone_BindZoneForm: 218,
    Zone_Add: 219,
    Zone_Edit: 220,
    Zone_DisableZone: 221,
    Zone_DeleteSelected: 222,
    Zone_GetZonesByOrga: 223,
    Zone_Default: 224,
    Zone_GetZonesAvailable: 225,
    Zone_GetZones: 226,
    Zone_GetZonesByEvent: 227,
    Zone_GetUnusedZones: 228,
    Zone_GetZoning: 229,
    Zone_GetZonesByProfileId: 230,
    File_UploadPicture: 231,
    File_UploadFile: 232,
    File_GetCapturedImage: 233,
    AccessLog_Index: 234,
    AccessLog_DataBind: 235,
    AccessLog_Export: 236,
    Blacklist_Index: 237,
    Blacklist_DataBind: 238,
    Blacklist_BindBlacklistEditForm: 239,
    Blacklist_Add: 240,
    Blacklist_Edit: 241,
    Blacklist_Delete: 242,
    Blacklist_CheckUnicite: 243,
    Blacklist_IsBlackListed: 244,
    CustomReport_DataBind: 245,
    CustomReport_BindModalForm: 246,
    CustomReport_ValidExportForm: 247,
    CustomReport_Index: 248,
    MonCompte_Index: 249,
    MonCompte_Edit: 250,
    MonCompte_EditPassword: 251,
    MonCompte_CheckPassword: 252,
    OrganizationUnit_Index: 253,
    OrganizationUnit_DataBind: 254,
    OrganizationUnit_GetOrganizationUnitById: 255,
    OrganizationUnit_CheckUnicite: 256,
    OrganizationUnit_DeleteSelected: 257,
    OrganizationUnit_Add: 258,
    OrganizationUnit_Edit: 259,
    OrganizationUnit_GetUnits: 260,
    OrganizationUnit_GetUnitsWithoutTreeByOrganization: 261,
    OrganizationUnit_GetUnitsTreeByOrganizationId: 262,
    OrganizationUnit_GetUserAllUnits: 263,
    OrganizationUnit_GetUserUnitsTree: 264,
    OrganizationUnit_GetUserUnitsGroupTrees: 265,
    OrganizationUnit_GetUserUnitsTreeForOrganization: 266,
    OrganizationUnit_GetUnitsTreeByProviderId: 267,
    OrganizationUnit_GetUnitsTreeByProviderForPassManagement: 268,
    OrganizationUnit_GetUnitConfiguration: 269,
    OrganizationUnit_GetFilteredUnitByEvent: 270,
    OrganizationUnit_GetUnitTreeByProvidersId: 271,
    OrganizationUnit_GetUnitsConfiguration: 272,
    Category_Index: 273,
    Category_DataBind: 274,
    Category_BindCategoryForm: 275,
    Category_DeleteSelected: 276,
    Category_Add: 277,
    Category_Edit: 278,
    Category_CheckUnicite: 279,
    Category_GetCategoriesByProviderId: 280,
    Category_GetCategoriesByEventAndProviderId: 281,
    Reason_GetReasons: 282,
    Parameter_Index: 283,
    Mail_CallBack: 284,
    Mail_SendEmail: 285,
    Mail_SendMessageEmailJob: 286,
    Mail_SendAssignmentEmailJob: 287,
    Mail_SendPassEmailJob: 288,
    Mail_GetMailStatus: 289,
    Mail_SendEmailToAssignments: 290,
    Mail_SendMessage: 291,
    Mail_SendEmailToPass: 292,
    Pass_Send: 293,
    Pass_SendEmail: 294,
    Pass_SendMessage: 295,
    Pass_EditProvider: 296,
    Pass_ShowActionsHistory: 297,
    //Pass_DeliveryPlace: 298,
    Pass_ZoningEdit: 299,
    Pass_ShowMailjet: 300,
    Pass_CheckDoubles: 301,
    //Assignment_AccessControlState: 302,
    Assignment_DeliveryPlaces: 303,
    Assignment_CanSeeUserInformation: 304,
    Assignment_CanEditZoning: 305,
    Assignment_CanReprint: 306,
    Pass_CanReprint: 307,
    Assignment_CanSearchAssignment: 308,
    Assignment_CanSeeIndividualPicture: 309,
    Assignment_CanSeeAffiliatedProvider: 310,
    Assignment_CanFilterBlacklist: 311,
    Assignment_CanSeeMailStatus: 312,
    Assignment_CanViewContact: 313,
    Assignment_CanViewPrevisualisation: 314,
    Assignment_CanModifyValidated: 315,
    User_CanSetParameters: 316,
    Assignment_CanPrintManyTime: 317,
    Assignment_CanChangeProvider: 318,
    Assignment_CanSetVehicleNumberGenerationMode: 319,
    Pass_CanSeeUserInformation: 320,
    //Pass_GetRichStatusForAssignment: 321,
    //Pass_CanEditZoning: 322,
    Pass_CanSearchAssignment: 323,
    Pass_CanSeeIndividualPicture: 324,
    Pass_CanSeeAffiliatedProviderAccreditation: 325,
    Pass_CanFilterBlacklist: 326,
    Pass_CanSeeMailStatus: 327,
    Pass_CanViewContact: 328,
    Pass_CanViewPrevisualisation: 329,
    Pass_CanModifyValidated: 330,
    Pass_CanPrintManyTime: 331,
    Assignment_CanSetZoning: 332,
    Vehicle_CanFilterByProvider: 333,
    Individual_CanFilterByProvider: 334,
    Individual_CanUseBlacklist: 335,
    Pass_CanFilterByProvider: 336,
    Pass_CanFilterByPicture: 337,
    Pass_CanFilterByUser: 338,
    Pass_Historique: 339,
    UserLevelExclusiveRight: 340,
    SuperAdminLevelExclusiveRight: 341,
    AdminLevelExclusiveRight: 342,
    Profile_CanSeePrivate: 343,
    Assignment_ExportCSVFullView: 344,
    Pass_ExportCSVFullView: 345,
    //HasRightsAllOrganization: 346,
    HasAccessToAllEvents: 347, //User & SuperAdmin
    CanDeleteUnits: 348,
    HasAccessToAccreditationGuest: 349,
    NotifyOnExport: 350, //TODO: VERIFY GROUPFEATURERIGHT
    Pass_CanSetZoning: 351,
    DisplayListFieldsFullView: 352,
    CanAccessToAllAssignments: 353,
    Assignment_CanSeeDoubles: 354,
    Assignment_CanFinalize: 355,
    Pass_CanFinalize: 356,
    AssignmentList_Modify: 357,
    AssignmentList_Valid: 358,
    AssignmentList_Cancel: 359,
    AssignmentList_GetPdfs: 360,
    MailTemplate_Index: 361,
    MailTemplate_DataBind: 362,
    MailTemplate_BindMailTemplateForm: 363,
    MailTemplate_Edit: 364,
    MailTemplate_SendTestMail: 365,
    AssignmentList_Delete: 366,
    Assignment_SendMail: 367,
    Individual_CanExportAll: 368,
    Event_CanGetAll: 369,
    Individual_CanSurpassObligationPicture: 370,
    Individual_CanSurpassObligationBirthDate: 371,
    AssignOnStep: 372,
    CanSendCustomMail: 373,
    Assignment_AddReading: 374,
    Assignment_CanBypassQuotas: 375,
    Assignment_GetStatsQuotasByEvent: 376,
    Quota_GetTemplate: 377,
    AssignmentList_Notify: 378,
    AssignmentList_SeeNotification: 379,
    PassList_Notify: 380,
    PassList_SeeNotification: 381,
    Billing_Index: 382,
    Billing_DefineQuota: 383,
    Billing_Databind: 384,
    Billing_SetActive: 385,
    Billing_GetBillingType: 386,
    Billing_GenerateReport: 387,
    Event_GetEventByCategory: 388,
    Billing_CanViewBillingProfile: 389,
    Provider_GetBillingProfiles: 390,
    Billing_CanSetBillingProfile: 391,
    Billing_DeleteSelected: 392,
    Billing_LoadActiveWorkForceProfiles: 393,
    Billing_LoadBillingProfiles: 394,
    Billing_SaveEventQuotas: 395,
    Billing_BindBillingForm: 396,
    Billing_Edit: 397,
    Billing_Add: 398,
    Group_Index: 399,
    Group_DataBind: 400,
    Group_Add: 401,
    Group_Edit: 402,
    Group_DeleteSelected: 403,
    Group_BindGroupForm: 404,
    RestrictByUserUnitsProvider: 405,
    CanGrantAccessAlways: 406,
    CanGrantAccessByUser: 407,
    CanGrantAccessByProvider: 408,
    RestrictByUserProvider: 409,
    PassList_GetPdfs: 410,
    AccreditationWCF_GetNotPrintedAccreditations: 411,
    AccreditationWCF_CheckNotPrintedAccreditations: 412,
    AccreditationWCF_MarkAccreditationsPrinted: 413,
    AccreditationWCF_GetNumberAccreditationOnMockup: 414,
    AccreditationWCF_GetAccreditationPdf: 415,
    AccreditationWCF_MarkAccreditationSendToAccessControl: 416,
    AccreditationWCF_GetAccreditations: 417,
    Vehicle_AccessByUserUnit: 418,
    Vehicle_AccessByProviderUnit: 419,
    Vehicle_RestrictByUserProvider: 420,
    Vehicle_RestrictByUserUnitsProvider: 421,
    Vehicle_AccessToAllUnit: 422,
    Vehicle_DisplayListFieldsFullView: 423,
    Individual_AccessByUserUnit: 424,
    Individual_DisplayListFieldsFullView: 425,
    Individual_AccessByProviderUnit: 426,
    Individual_AccessToAllUnit: 427,
    Individual_RestrictByUserProvider: 428,
    Unit_AccessByUserUnit: 429,
    Unit_RestrictByUserUnitsProvider: 430,
    Unit_AccessByProviderUnit: 431,
    Unit_RestrictByUserProvider: 432,
    Unit_AccessToAllUnit: 433,
    Provider_AccessToAllUnit: 434,
    Provider_AccessByUserUnit: 435,
    Provider_AccessByProviderUnit: 436,
    Event_AccessByUserUnit: 437,
    Event_AccessByProviderUnit: 438,
    User_AccessToAllUnit: 439,
    User_AccessByUserUnit: 440,
    User_AccessByProviderUnit: 441,
    Billing_AccessToAllUnit: 442,
    Billing_AccessByUserUnit: 443,
    Billing_AccessByProviderUnit: 444,
    Assignment_AccessToAllUnit: 445,
    Assignment_AccessByUserUnit: 446,
    Assignment_AccessByProviderUnit: 447,
    WebApi_Notify: 448,
    Assignment_Historique: 449,
    Assignment_AccessControlHistory: 450,
    Assignment_CanViewBlackList: 451,
    Pass_CanViewBlackList: 452,
    Event_GetUnits: 453,
    PassAdmin_Edit: 454,
    Provider_Add: 455,
    Assignment_NewAssignmentButton: 456,
    Assignment_CanSeeIndividual: 457,
    Assignment_CanSeeVehicle: 458,
    Assignment_CanSeeGuest: 459,
    Assignment_CanSeeAnonymous: 460,
    Assignment_CanCreateIndividual: 461,
    Assignment_CanCreateVehicle: 462,
    Assignment_CanCreateGuest: 463,
    Assignment_CanCreateAnonymous: 464,
    Pass_NewPassButton: 465,
    Pass_CanSeeIndividual: 466,
    Pass_CanSeeVehicle: 467,
    Pass_CanSeeGuest: 468,
    Pass_CanCreateIndividual: 469,
    Pass_CanCreateVehicle: 470,
    Pass_CanCreateGuest: 471,
    Individual_CanAccessModule: 472,
    Vehicle_CanAccessModule: 473,
    Assignment_CanAccessModule: 474,
    Pass_CanAccessModule: 475,
    Individual_Edit: 476,
    HasCustomTitleAccess: 477,
    PassList_Valid: 478,
    WebApi_AssignmentOnDemandToken: 479,
    Assignment_ViewContactInformations: 480,
    Pass_ViewContactInformations: 481,
    Assignment_GetDefaultAssignmentType: 482
};
var sport = {

    init: function () {

        $("#search .submit").click(sport.gridReload);
        $(".grid-header .delete").click(sport.deleteAll);

        $(".grid-header .submit").click(sport.preRempAdd);

        $("#editForm, #addFormSport").submit(function () { return false; });

        $("#editForm .submit").click(sport.edit);

        $("#addFormSport .submit").click(sport.add);
        $("#addFormSport .cancel").click(function () {            
            site.hideForm('#addFormSport', { container: ".main-container" });
        });
    },


    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });
        $("#SportEdit_Name").rules("add", "checkUniciteSport");

        $.ajax({
            type: "POST",
            url: 'Sport/BindSportForm',
            dataType: "json",
            el: "#editForm",
            data: { id: id },
            traditional: true,
            success: function (ret) {
                
                if (ret.UserId) {
                    $('#SportEdit_UserId').addOption({ value: ret.UserId, text: ret.User.FirstName + " " + ret.User.LastName });
                }
                $('#SportEdit_SportId').val(ret.SportId);
                $('#SportEdit_Name').val(ret.Name);
                $('#SportEdit_Comment').val(ret.Comment);
                $('#SportEdit_UserId').val(ret.UserId);

                sport.addLabel($("#editForm"), ret.SportNameTranslations);



            }
        });

    },

    preRempAdd: function () {
        $("#addFormSport")[0].reset();
        site.initAjaxSelect();
        site.showForm('#addFormSport', { container: ".main-container" });
    },


    add: function () {
        $("#addFormSport #Sport_Name").rules("add", "checkUniciteSport");

        if ($("#addFormSport").valid()) {
            var data = $("#addFormSport").serialize();
            $.ajax({
                type: "POST",
                url: 'Sport/Add',
                dataType: "json",
                data: data,
                el: "#addFormSport",
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resources.ValidationSuccess);
                    } else {
                        site.errorMessage(resourcesMessages.ErrorAddUnivers, ret.Exception);
                    }

                    sport.gridReload();
                    $("#addFormSport .cancel").trigger("click");

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }
    },




    edit: function () {
        $("#editForm #SportEdit_Name").rules("add", "checkUniciteSport");
        if ($("#editForm").valid()) {
            var data = $("#editForm").serialize();
            $.ajax({
                type: "POST",
                url: 'Sport/Edit',
                dataType: "json",
                data: data,
                traditional: true,
                el: "#editForm",
                success: function (data) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        sport.gridReload();
                        $("#editForm .cancel").trigger("click");
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    site.errorAjaxPopup(xhr, xhr.status, thrownError.error);
                }
            });
        }

    },

    deleteAll: function () {

        var ids = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (ids == "") {
            jAlert(resourcesMessages.AtLeastOneSportSelected, resources.Warning);
        } else {
            var ok;
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'Sport/DeleteSelected',
                            dataType: "json",
                            data: { sportIds: s },
                            traditional: true,
                            el: jQuery("#JqGrid"),
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                                $("#JqGrid").trigger("reloadGrid");
                            }
                        });
                }
            });
        }
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var edProv = "";

            if (site.hasPermission(right.Sport_Edit)) {
                edProv = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='sport.preRempEdit(" + cl + ");' ><i class='fa fa-pencil'></i></button>";
            }

            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv });
        }


        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },


    gridReload: function () {
        var nameMask = jQuery("#search_name").val();

        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "Sport/DataBind"
                + "?name=" + nameMask,
            page: 1
        }).trigger("reloadGrid");
    },

    addLabel: function (form, labels) {
        if (labels != undefined) {
            $.each(labels, function (index, value) {
                form.find("input[id*='" + index + "__Name']").val(value.Name);
            });
        }
        return false;
    }
}
var translation = {
    params: {},
    colModel: [],
    init: function (params) {

        $(".add-translation").click(translation.add);

        $.extend(this.params, params);
        var l = params.supportedLanguages.length;

        translation.colModel = [
            {
                align: 'left',
                name: 'Key',
                label: 'Valeur Fr (Clé)',
                editable: true,
                index: 'Key',
                editrules:{edithidden:true, required:true}
            },
            {
                align: 'left',
                name: 'OldKey',
                label: 'Valeur',
                editable: true,
                editoptions: { size: "Auto", maxlength: "255" },
                index: 'OldKey',
                hidden: true
            }
            
        ];

        for (var i = 0; i < l; i++) {
            var lang = params.supportedLanguages[i];
            if (lang.TwoLetterISOLanguageName != "fr") {
                translation.colModel.push(
                  {
                      align: 'left',
                      name: 'lang_' + lang.TwoLetterISOLanguageName,
                      label: 'Valeur ' + lang.TwoLetterISOLanguageName,
                      editable: true,
                      formatter: translation.langFmatter,
                      editoptions: { size: "Auto", maxlength: "255" },
                      editrules: { required: false },
                      width: 110,
                      index: 'lang_' + lang.TwoLetterISOLanguageName
                  }
                );
            }

        }

        translation.colModel.push({
            align: 'left',
            name: 'act',
            label: '&nbsp;',
            editable: false,
            editoptions: { size: "Auto", maxlength: "255" },
            width: 30,
            index: 'act',
        });

        var lastSel = 0;

        //Reemplissage du tableau jQgrid
        jQuery('#JqGrid').jqGrid({
            autowidth: true,
            datatype: 'json',
            gridview: true,
            height: '100%',
            hidegrid: false,
            pager: '#PagerJqGrid',
            mtype: 'post',
            rowList: [10, 15, 30, 50, 100, 200, 500],
            rowNum: 50,
            scrollrows: true,
            sortname: 'Key',
            sortorder: 'asc',
            url: 'Translation/DataBind',
            cellurl: 'Translation/Edit/',
            editurl: "Translation/Edit/",
            gridComplete: translation.gridComplete,
            viewrecords: true,
            loadError: function (xhr, status, error) { site.errorAjaxPopup(xhr, status, error) },
            colModel: translation.colModel,
            loadError: site.errorAjaxPopup,
            formatter: 'actions',
            ajaxRowOptions: {
                success: function (data, textStatus) {
                    if (data.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#JqGrid").trigger("reloadGrid");
                    } else {
                        site.errorMessage(resourcesMessages.AddZoneFail, data.Exception);
                    }
                }
            },
            onSelectRow: function (id) {
                if (id && id !== lastSel) {
                    jQuery('#JqGrid').restoreRow(lastSel);
                    lastSel = id;
                }
                jQuery('#JqGrid').editRow(id, true);
             //   jQuery("#JqGrid").jqGrid('setRowData', id, { act: "" });
            }
        });
    },

    add: function() {
        var obj = { OldKey: "", Key: "", 2: [] };
        var l = translation.params.supportedLanguages.length;
        for (var i = 0; i < l; i++) {
            var lang = translation.params.supportedLanguages[i];

            if (lang.TwoLetterISOLanguageName != "fr") {
                obj[2].push({
                    key: "",
                    Culture: lang.TwoLetterISOLanguageName,
                    Value: ""
                });
            }
        }
        jQuery("#JqGrid").jqGrid('addRowData', 0, obj, "first");
    },

    remove : function(idRow) {
        var data = jQuery("#JqGrid").jqGrid('getRowData', idRow);

        $.ajax({
            type: "POST",
            url: 'Translation/Delete',
            dataType: "json",
            data: data,
            traditional: true,
            success: function (ret) {
                if (ret.Success) {
                    site.successMessage(resourcesMessages.SuppressionSuccess);
                    $("#JqGrid").trigger("reloadGrid");
                } else {
                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                }
            }
        });
        return false;
    },

    langFmatter: function(cellvalue, options, rowObject)
    {
        var column = translation.colModel[options.pos];

        var langs = rowObject[2];

        if (langs != undefined) {
            var len = langs.length;
            for (var i = 0; i < len; i++) {
                var lang = langs[i];
                if ("lang_" + lang.Culture == column.name) {
                    return lang.Value;
                }
            }
        }

        // do something here
        return cellvalue;
    },


    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];

            var edProv = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='translation.remove(\"" + cl + "\");' ><i class='fa fa-trash'></i></button>";
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv });
        }
    },
}
var vehicleNumber = {
    rowTemplate: undefined,
    rowEditTemplate: undefined,

    params: {
        messageAtLeastOneZoneSelected: "",
        labelName: "",
        labelUnit: "",
        labelEvent: "",
        labelType: "",
        labelStartRange: "",
        labelEndRange: "",
        labelAvailableVehicleNumbers: "",
        labelExtensions: "",
        labelSecondStartRange: "",
        labelSecondEndRange: ""
    },

    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    $("#labelSearch").html(resources.Event_stadium);
                    $("#JqGrid").setLabel('EventName', resources.Event_stadium);
                }
            }
        });

        vehicleNumber.rowTemplate = $("#addForm .table-itemlist").find("tbody tr").last().detach();
        vehicleNumber.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();

        $("#searchForm").submit(vehicleNumber.gridReload);
        $.extend(this.params, params);

        $("#Search_EventId").change(function () {
            if ($("#Search_EventId").val() !== "") {
                vehicleNumber.isEventNumberEditable();
                vehicleNumber.gridReload();
                if ($("#addButton").length > 0) {
                    $("#addButton")[0].disabled = false;
                }
            } else {
                if ($("#addButton").length > 0) {
                    $("#addButton")[0].disabled = true;
                }
            }
        });

        $("#actions .submit").click(vehicleNumber.preRempAdd);
        $("#actions .default").click(vehicleNumber.release);
        $("#actions .delete").click(vehicleNumber.del);
        $("#add .submit").click(vehicleNumber.add);
        $("#add .cancel").click(function () {           
            site.hideForm('#addForm', { container: ".main-container" });
        });
        $("#edit .submit").click(vehicleNumber.edit);
        $("#edit .cancel").click(function () {            
            site.hideForm('#editForm', { container: ".main-container" });
        });
        if ($("#addButton").length > 0) {
            $("#addButton")[0].disabled = true;
        }
        if ($("#deleteButton").length > 0) {
            $("#deleteButton")[0].disabled = true;
        }
        $(".selectAllUnits").click(vehicleNumber.selectAllUnits);
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var cl = ids[i];
            var edProv = '';
            if (site.hasPermission(right.VehicleNumber_Edit)) {
                edProv = '<button class="btn btn-circle btn-primary"  onclick="vehicleNumber.preRempEdit(\'' + cl + '\');"><i type="button" class="fa fa-pencil"></i></button>';
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: edProv });
        }

        $("#JqGrid").jqGrid('navGrid', '#PagerJqGrid',
            { view: false, del: false, add: false, edit: false, search: false, refresh: true },
            {}, {}, {}, {}, {});
    },

    isEventNumberEditable: function () {
        $.ajax({
            type: "POST",
            url: "Vehicle/IsVehicleNumberEditable",
            data: { eventId: $("#Search_EventId").val() },
            dataType: "json",
            traditional: true,
            // el: "#editForm",
            success: function (ret) {
                var MinVehicleNumber = jQuery("#JqGrid").jqGrid('getColProp', 'MinVehicleNumber');
                var MaxVehicleNumber = jQuery("#JqGrid").jqGrid('getColProp', 'MaxVehicleNumber');
                var RangeTypeName = jQuery("#JqGrid").jqGrid('getColProp', 'RangeTypeName');

                if (ret.Success) {
                    MinVehicleNumber.editable = true;
                    MaxVehicleNumber.editable = true;
                    RangeTypeName.editable = true;

                    $(".js-event-disabled").hide();
                } else {

                    MinVehicleNumber.editable = false;
                    MaxVehicleNumber.editable = false;
                    RangeTypeName.editable = false;
                    $(".js-event-disabled").show();
                }
                //always call editRow after changing editable property
                jQuery('#JqGrid').jqGrid('editRow', 0, {});

            }
        });
    },

    gridReload: function () {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "/VehicleNumber/DataBindVehicleNumber?" + data,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    loadBeforeSend: function (grid) {
        //set dynamic size of grid
        var width = $('.inner').outerWidth() - 20;
        $(grid).jqGrid('setGridWidth', width);

        grid.p.loadBeforeSend = null; //remove event handler
        return false; // dont send load data request
    },

    del: function (id) {
        var form = $(this).parents("form");
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(vehicleNumber.params.messageAtLeastOneZoneSelected, "Attention");
        }
        else {
            jConfirm(resourcesMessages.SuppressionConfirmation, 'Attention', function (ok) {
                var s;
                s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
                if (ok && s != "") {
                    $.ajax(
                        {
                            type: "POST",
                            url: 'VehicleNumber/DeleteVehicleNumber',
                            dataType: "json",
                            data: { id: s },
                            traditional: true,
                            el: "#jqcontainer",
                            success: function (ret) {
                                if (ret.Success) {
                                    site.successMessage(resourcesMessages.SuppressionSuccess);
                                    $("#JqGrid").trigger("reloadGrid");
                                } else {
                                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                                }
                            }
                        });
                }
            });
        }
    },

    preRempAdd: function () {
        site.showForm('#addForm', { container: ".main-container" });
        $.ajax({
            type: "POST",
            url: 'VehicleNumber/BindVehicleNumberAddForm',
            dataType: "json",
            el: "#addForm",
            traditional: true,
            data: { eventId: $("#Search_EventId").val() },
            success: function (result) {
                var vehicleNumber = result.vehicleNumberModel;

                $("#add input[id*='Name'], #add textarea, #add select").val("");
                $("#RangeVehicleNumberModelAdd_EventId").val(vehicleNumber.EventId);
                $("#RangeVehicleNumberModelAdd_EventId").selectedIndex = vehicleNumber.EventId;
                $("#RangeVehicleNumberModelAdd_MinVehicleNumber").val("0");
                $("#RangeVehicleNumberModelAdd_MaxVehicleNumber").val("0");
                $("#RangeVehicleNumberModelAdd_MinVehicleNumberSecondary").val("0");
                $("#RangeVehicleNumberModelAdd_MaxVehicleNumberSecondary").val("0");
                $("#RangeVehicleNumberModelAdd_ZoneId").html("");
                for (u in vehicleNumber.Zones) {
                    let item = vehicleNumber.Zones[u];
                    $("#RangeVehicleNumberModelAdd_ZoneId").append('<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>');
                }
                $("#RangeVehicleNumberModelAdd_ZoneId").selectedIndex = vehicleNumber.ZoneId;

                $("#RangeVehicleNumberModelAdd_RangeTypeId").prop("disabled", false);
            }
        });

        site.initAjaxSelect();
        vehicleNumber.clearItemList();
    },

    preRempEdit: function (id) {
        site.showForm('#editForm', { container: ".main-container" });
        vehicleNumber.clearItemList();

        var form = $("#editForm");
        form[0].reset();

        $.ajax({
            type: "POST",
            url: 'VehicleNumber/BindVehicleNumberEditForm',
            dataType: "json",
            el: "#edit",
            data: { vehicleNumberId: id },
            traditional: true,
            success: function (result) {
                var vehicleNumber = result.vehicleNumberModel;
                $("#RangeVehicleNumberModelEdit_Id").val(vehicleNumber.Id);
                $("#RangeVehicleNumberModelEdit_EventId").val(vehicleNumber.EventId);
                $("#RangeVehicleNumberModelEdit_Units").val(vehicleNumber.UnitIds);
                $("#RangeVehicleNumberModelEdit_RangeTypeId").val(vehicleNumber.RangeTypeId);
                $("#RangeVehicleNumberModelEdit_MinVehicleNumber").val(vehicleNumber.MinVehicleNumber);
                $("#RangeVehicleNumberModelEdit_MaxVehicleNumber").val(vehicleNumber.MaxVehicleNumber);
                $("#RangeVehicleNumberModelEdit_MinVehicleNumberSecondary").val(vehicleNumber.MinVehicleNumberSecondary);
                $("#RangeVehicleNumberModelEdit_MaxVehicleNumberSecondary").val(vehicleNumber.MaxVehicleNumberSecondary);
                $("#RangeVehicleNumberModelEdit_OldSelectedUnitIds").val(vehicleNumber.OldSelectedUnitIds);
                $("#RangeVehicleNumberModelEdit_RangeTypeName").prop("disabled", true);

                site.initAjaxSelect();
                $("#RangeVehicleNumberModelEdit_ZoneId").html("");
                for (u in vehicleNumber.Zones) {
                    let item = vehicleNumber.Zones[u];
                    $("#RangeVehicleNumberModelEdit_ZoneId").append('<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>');
                }
                $("#RangeVehicleNumberModelEdit_ZoneId").val(vehicleNumber.ZoneId);
                $("#RangeVehicleNumberModelEdit_ZoneId").selectedIndex = vehicleNumber.ZoneId;
                $("#RangeVehicleNumberModelEdit_ZoneId").prop("disabled", true);

                $("#RangeVehicleNumberModelEdit_OldSelectedUnitIds").html("");
                for (u in vehicleNumber.OldSelectedUnitIds) {
                    let item = vehicleNumber.OldSelectedUnitIds[u];
                    $("#RangeVehicleNumberModelEdit_OldSelectedUnitIds").append('<option selected="selected" value="' + item + '"></option>');
                }

                $("#RangeVehicleNumberModelEdit_Units").html("");
                for (u in vehicleNumber.Units) {
                    let item = vehicleNumber.Units[u];
                    $("#RangeVehicleNumberModelEdit_Units").append('<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>');
                }
            }
        });
    },

    add: function () {
        $("#add .submit").off('click');
        var form = $(this).parents("form").first();
        if (form.valid()) {
            if (!vehicleNumber.checkSelectedUnits()) {
                $("#add .submit").click(vehicleNumber.add);
                return false;
            }
            if (!vehicleNumber.checkParkingLots()) {
                $("#add .submit").click(vehicleNumber.add);
                return false;
            }
            var data = site.serializeAll(form);
            data.forEach(function (e) { if (e.name === "RangeVehicleNumberModelAdd.Units") { e.name = "RangeVehicleNumberModelAdd.SelectedUnitIds"; } });
            $.ajax({
                type: "POST",
                url: 'VehicleNumber/Add',
                dataType: "json",
                el: "#" + form.attr("id"),
                data: data,
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resourcesMessages.RVNCreationSuccess);
                        site.hideForm('#addForm', { container: ".main-container" });
                        $("#JqGrid").trigger("reloadGrid");
                    } else {
                        site.errorMessage(resourcesMessages.RVNCreationFailure, ret.Exception);
                    }
                    $("#add .submit").click(vehicleNumber.add);
                },
                failure: function (ret) {
                    $("#add .submit").click(vehicleNumber.add);
                }
            });
        } else {
            $("#add .submit").click(vehicleNumber.add);
        }
    },

    edit: function () {
        $("#edit .submit").off('click');
        var form = $(this).parents("form").first();
        if (form.valid()) {
            if (!vehicleNumber.checkSelectedUnits()) {
                $("#edit .submit").click(vehicleNumber.edit);
                return false;
            }
            if (!vehicleNumber.checkParkingLots()) {
                $("#edit .submit").click(vehicleNumber.edit);
                return false;
            }
            var data = site.serializeAll(form);
            data.forEach(function (e) { if (e.name === "RangeVehicleNumberModelEdit.Units") { e.name = "RangeVehicleNumberModelEdit.SelectedUnitIds"; } });
            $.ajax({
                type: "POST",
                url: 'VehicleNumber/Edit',
                dataType: "json",
                el: "#" + form.attr("id"),
                data: data,
                traditional: true,
                success: function (ret) {
                    if (ret.Success) {
                        site.successMessage(resourcesMessages.RVNUpdateSuccess);
                        site.hideForm('#editForm', { container: ".main-container" });
                        $("#JqGrid").trigger("reloadGrid");
                    } else {
                        site.errorMessage(resourcesMessages.RVNUpdateFailed, ret.Exception);
                    }
                    $("#edit .submit").click(vehicleNumber.edit);
                },
                failure: function (ret) {
                    $("#edit .submit").click(vehicleNumber.edit);
                }
            });
        } else {
            $("#edit .submit").click(vehicleNumber.edit);
        }
    },

    clearItemList: function () {
        //effacer les anciennes valeur (seulement les valeurs saisies, pas les champs cachés contenant les cultures de chaque colonne
        if (vehicleNumber.rowTemplate !== null) {
            vehicleNumber.rowTemplate.find("input[id*='__Name']").val("");
            // customField.rowTemplate.find("input[id*='__Value']").val("");
        }
        $(".table-itemlist tbody").html("");
    },

    getSelect2Params: function (params) {
        if ($("#addForm").is(":visible")) {
            params["EventId"] = $("#RangeVehicleNumberModelAdd_EventId").val();
        } else {
            params["EventId"] = $("#RangeVehicleNumberModelEdit_EventId").val();
        }
        return params;
    },

    checkSelectedUnits: function () {
        var units = null;
        if ($("#addForm").is(":visible")) {
              units = $("#RangeVehicleNumberModelAdd_Units").val();
        } else {
            units = $("#RangeVehicleNumberModelEdit_Units").val();
        }
        
        if (units === null) {
            site.errorMessage(resourcesMessages.AtLeastOneOrganizationUnitSelected);
            return false;
        }
        else return true;
    },
    checkParkingLots: function () {
        var min1 = 0;
        var min2 = 0;
        var max1 = 0;
        var max2 = 0;
        //add or edit?
        if ($("#addForm").is(":visible")) {
            min1 = parseInt($("#RangeVehicleNumberModelAdd_MinVehicleNumber").val());
            min2 = parseInt($("#RangeVehicleNumberModelAdd_MinVehicleNumberSecondary").val());
            max1 = parseInt($("#RangeVehicleNumberModelAdd_MaxVehicleNumber").val());
            max2 = parseInt($("#RangeVehicleNumberModelAdd_MaxVehicleNumberSecondary").val());
        }
        else {
            min1 = parseInt($("#RangeVehicleNumberModelEdit_MinVehicleNumber").val());
            min2 = parseInt($("#RangeVehicleNumberModelEdit_MinVehicleNumberSecondary").val());
            max1 = parseInt($("#RangeVehicleNumberModelEdit_MaxVehicleNumber").val());
            max2 = parseInt($("#RangeVehicleNumberModelEdit_MaxVehicleNumberSecondary").val());
        }
        //
        //individual checks
        //
        //in general, the starting number of a tranche cannot be more than the ending number
        if (min1 > max1) {
            //show error message
            site.errorMessage(resourcesMessages.RVNFirstRangeError);
            return false;
        }
        if (min2 > max2) {
            //show error message
            site.errorMessage(resourcesMessages.RVNSecondRangeError);
            return false;
        }
        //if secondary is empty -> ok
        if (min2 === 0 && max2 === 0) return true;

        //
        //combined checks
        //
        //check non-intersection between the tranches
        if (!((max1 < min2) || (max2 < min1))) {
            //show error message
            site.errorMessage(resourcesMessages.RVNRangesIntersectError);
            return false;
        }
        return true;
    },

    toogleActionButtons: function (Id) {
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "" || s.length > 1) {
            if ($("#deleteButton").length > 0) {
                $("#deleteButton")[0].disabled = true;
            }
        }
        else {
            if ($("#deleteButton").length > 0) {
                $("#deleteButton")[0].disabled = false;
            }
        }
    },

    selectAllUnits: function () {
        var form = $(this).parents("form").first();
        var eventId = form.find("[id*=_EventId]").val();
        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/GetFilteredUnitByEvent',
            dataType: "json",
            el: "#LimitedEditForm",
            data: { eventId: eventId },
            traditional: true,
            success: function (result) {
                var unitField = null;
                if ($("#addForm").is(":visible")) {
                    unitField = $("#RangeVehicleNumberModelAdd_Units");
                } else {
                    unitField = $("#RangeVehicleNumberModelEdit_Units");
                }

                var units = result.items;
                unitField.val(null);
                vehicleNumber.addUnits(units, unitField);
                unitField.trigger("change");
            }
        });
        return false;
    },

    addUnits: function (units, unitField) {
        for (u in units) {
            var item = units[u];
            if (item.children === null) {
                unitField.append("<option selected='selected' value='" + item.id + "'>" + item.name + "</option>");
            }
            else {
                vehicleNumber.addUnits(item.children, unitField);
            }
        }
    },

    release: function () {
        var id = jQuery("#JqGrid").jqGrid("getGridParam", 'selrow');
        $.ajax({
            type: "POST",
            url: 'VehicleNumber/ReleaseVehicleNumber',
            dataType: "json",
            data: { id: id },
            traditional: true,
            success: function (ret) {
                if (ret.Success) {
                    site.successMessage(resourcesMessages.SuppressionSuccess);
                    site.hideForm('#addForm', { container: ".main-container" });
                    $("#JqGrid").trigger("reloadGrid");
                } else {
                    site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                }
            },
            failure: function (ret) {
            }
        });
    }
};
jQuery.extend(jQuery.validator.messages, {
    min : resources.RVNHigherOrEqualAtOne,
});
var zone = {
    params: {
        messageAtLeastOneZoneSelected: "",
        imageSizeRestriction: "",
    },
    rowTemplate: undefined,
    rowEditTemplate: undefined,
    multizone: undefined,
    isStadium: false,
    init: function (params) {
        $.ajax({
            type: "POST",
            url: 'Parameter/GetWordingParameter',
            dataType: "json",
            traditional: true,
            success: function (wordingStyle) {
                if (wordingStyle === 'Stadium') {
                    //Page générale
                    $("#labelSearch").html(resources.Organization_stadium);
                    $("#JqGrid").setLabel('OrganizationName', resources.Organization_stadium);

                    //Ajout / Edition
                    $("#editForm #labelOrganization").html(resources.Organization_stadium + ' *');
                    $("#addForm #labelOrganization").html(resources.Organization_stadium + ' *');
                    zone.isStadium = true;
                }
            }
        });

        $.ajax({
            type: "GET",
            url: 'Parameter/GetUseVehicule',
            dataType: "json",
            traditional: true,
            success: function (data) {
                if (data === false) {
                    //remove vehicule option

                    var addAssignmentVehiculeOption = $("#addForm #ZoneAdd_AssignmentTypeId option[value=" + AssignmentType.Vehicle + "]");
                    var editAssignmentVehiculeOption = $("#editForm #ZoneEdit_AssignmentTypeId option[value=" + AssignmentType.Vehicle + "]")

                    if (addAssignmentVehiculeOption !== null && addAssignmentVehiculeOption !== undefined) {
                        addAssignmentVehiculeOption.remove();
                    }

                    if (editAssignmentVehiculeOption !== null && editAssignmentVehiculeOption !== undefined) {
                        editAssignmentVehiculeOption.remove();
                    }
                }
            }
        });
        $.extend(this.params, params);

        zone.rowTemplate = $("#addForm .table-itemlist").find("tbody tr").last().detach();
        zone.rowEditTemplate = $("#editForm .table-itemlist").find("tbody tr").last().detach();

        $(".js-additemlist").click(function () {
            var elem = $(this).parents("form").first().find(".table-itemlist");
            window.zone.addItemList(elem);
            return false;
        });

        file.deleteActivated = true;
        file.init();
        $("#actions .submit").click(zone.preRempAddZone);
        $("#actions .delete").click(zone.delSelectedZone);

        $("#editForm .submit").click(zone.EditZone);

        $("#searchForm").submit(zone.gridReload);

        $("#ZoneEdit_OrganizationId, #ZoneAdd_OrganizationId").change(function () {
            $("#ZoneEdit_UnitIds").html("");
            $("#ZoneAdd_UnitIds").html("");
            site.initAjaxSelect();
        });

        $("#addForm .submit").click(zone.AddZone);

        $("#addForm input[name='ZoneAdd.Picture']").val(file.fileUpload);
        $("#editForm input[name='ZoneEdit.Picture']").val(file.fileUpload);

        $("#ZoneEdit_AssignmentTypeId, #ZoneAdd_AssignmentTypeId").change(zone.toggleUnits);

        $("#addForm input[name='ZoneAdd.Code']").rules("add", "verifySurZoneCode");
        $("#addForm input[name='ZoneAdd.Code']").rules("add", "checkUniciteZone");

        $("#editForm input[name='ZoneEdit.Code']").rules("add", "verifySurZoneCode");
        $("#editForm input[name='ZoneEdit.Code']").rules("add", "checkUniciteZone");
        $(".selectAllUnits").click(zone.selectAllUnits);


        $.ajax({
            type: "GET",
            url: 'Parameter/GetImageZoneSizeRestriction',
            dataType: "json",
            success: function (ImageZoneSizeRestriction) {
                if (ImageZoneSizeRestriction !== "") {
                    events.params.imageSizeRestriction = ImageZoneSizeRestriction;
                }
            }
        });

        $("input[type='file'].to-base-64").change(function () {
            var input = $(this);
            var id = input.attr("id");
            input = $("#" + id + ".to-base-64"); // avec juste $(this), il est impossible de trouver les autres éléments ci-dessous (alors que ça marche très bien pour les évènements), avec cette combine ici, ça fonctionne comme ça devrait...
            var div = $(input.parents(".img-wrapper"));
            var hidden = $(div.find("input[type='hidden'].img-base-64"));
            var image = div.find("img.img-picture")[0];

            var dimension = events.params.imageSizeRestriction;

            image.onloadend = function () {
                var parameterMaxWidth = dimension.split('x')[0];
                var parameterMaxHeight = dimension.split('x')[1];
                file.resizeBase64(div, image, hidden, parameterMaxWidth, parameterMaxHeight);
            };
        });
    },


    addItemList: function (elem, rule, zones) {
        var table = elem;
        if (elem.parents("form").hasClass("addForm")) {
            var row = window.zone.rowTemplate;
        } else {
            var row = window.zone.rowEditTemplate;
        }

        table.find("tbody tr").last().find("select").each(function () {
            if ($(this)) {
                $($(this)).select2('destroy');
            }
        });

        var lastRow = table.find("tbody tr").last().clone(true);

        var nb = 0;

        //si il y a deja une ligne dans le tableau
        if (lastRow[0] != undefined) {

            var html = lastRow.html();
            //j'incrémente les numéro contenu dans CustomChoises_0__Name et CustomChoises[0].Name
            var newHtml = html.replace(/(ZoneRules_\d+)/g, function (match, str) {
                var number = str.replace("ZoneRules_", "");
                nb = parseInt(number, 10) + 1;
                return "ZoneRules_" + nb;
            });


            newHtml = newHtml.replace(/(ZoneRules\[\d+)/g, function (match, str) {
                var number = str.replace("ZoneRules[", "");
                nb = parseInt(number, 10) + 1;
                return "ZoneRules[" + nb;
            });

            lastRow.html(newHtml);
        } else {
            var lastRow = row.clone(true);
        }

        if (rule != undefined) {
            lastRow.find("input[id*='Priority']").val(rule.Priority);

            var zonezField = lastRow.find("select[id*='ZoneIds']");
            zonezField.html("");
            for (z in rule.ZoneIds) {
                var id = rule.ZoneIds[z];
                var zone = zones.filter(function (elem) { return elem.ZoneId == id })[0];
                zonezField.append('<option selected="selected" value="' + zone.ZoneId + '">' + zone.Name + '</option>');
            }
            var zoneToDisplay = lastRow.find("select[id*='ZoneToDisplay']");
            zoneToDisplay.html("");
            var display = zones.filter(function (elem) { return elem.ZoneId == rule.ZoneToDisplayId })[0];
            zoneToDisplay.append('<option selected="selected" value="' + display.ZoneId + '">' + display.Name + '</option>');
        } else {
            lastRow.find("input[id*='Priority']").val(nb + 1);
            lastRow.find("select[id*='ZoneIds']").val("");
            lastRow.find("select[id*='ZoneToDisplay']").val("");
        }
        lastRow.find(".btn-delete").click(window.zone.deleteItemList);
        //j'injecte la ligne à la fin du tableau
        lastRow.appendTo(table);
        table.parents(".container-itemlist").animate({ scrollTop: lastRow.offset().top }, 'fast');

        $(".container-itemlist select").css("width", "100%").each(function () {
            var elem = $(this);

            $(this).select2(
                {
                    ajax: {
                        data: function (params, page) {
                            var p = elem.data("ajax--params");
                            if (p) {
                                p = p.split(".");
                                var params = window[p[0]][p[1]](params);
                            }
                            params["q"] = params.term;
                            params["page"] = params.term;

                            return params;
                        },
                        processResults: function (data, page) {
                            return {
                                results: data.items
                            };
                        },
                        cache: true
                    }
                });
        });

        return false;
    },

    deleteItemList: function () {
        var elem = $(this).parents(".table-itemlist").first();

        $(this).parents("tr").first().remove();
        zone.refreshItemListIds(elem);
        return false;
    },

    refreshItemListIds: function (elem) {
        var i = -1;
        //on parcour toute les lignes du tableau 
        $(elem).find("tr").each(function () {
            // pour chaque input et span on met a jour leur id nom etc..
            $(this).find('select, input, span').each(function () {
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var datamsq = $(this).attr("data-valmsg-for");
                if (id) id = id.replace(/(\d+)/g, i);
                if (name) name = name.replace(/(\d+)/g, i);
                if (datamsq) datamsq = datamsq.replace(/(\d+)/g, i);
                $(this).attr("id", id);
                $(this).attr("name", name);
                $(this).attr("data-valmsg-for", datamsq);
            });
            i++;
        });

    },


    /********************************************************************************************/
    /********************************************* ZONE *****************************************/
    /********************************************************************************************/

    toggleUnits: function () {
        var form = $(this).parents("form").first();
        var elem = form.find(".row-units");
        var onZone = form.find(".row-on-zone");
        zone.showUnitsAndSurZone($(this).val(), elem, onZone);
        $("#ZoneEdit_OrganizationId, #ZoneAdd_OrganizationId").change();
    },
    showUnitsAndSurZone: function (assignmentType, unitElement, surZoningElement) {
        // check with ==, not ===, since the calls can either have "2" as a string or 2 as an integer
        // object type matching is not recommended
        if (assignmentType == 2) { // if vehicle
            if (zone.isStadium) { unitElement.show(); } else { unitElement.hide(); }//hide unit zone if no stadium
            surZoningElement.hide();
        } else {
            unitElement.show();
            surZoningElement.show();
        }
    },

    preRempEditZone: function (id) {
        var ret = jQuery("#JqGrid").jqGrid('getRowData', id);
        site.showForm('#editForm', { container: ".main-container" });

        file.resetPicture("#editForm");
        $(".table-itemlist tbody").html("");

        $.ajax({
            type: "POST",
            url: "ZoneNew/BindZoneForm",
            data: { id: id },
            dataType: "json",
            traditional: true,
            el: "#editForm",
            success: function (r) {
                var ret = r.data;
                var zoneModel = ret.zone;
                var zones = ret.zones;
                var multizone = ret.multizone;
                zone.multizone = multizone;
                $("#editForm")[0].reset();

                var units = ret.units;
                var unitsId = units.map(function (x) {
                    return x.OrganizationUnitId;
                });

                $("#editForm input[name='ZoneEdit.ZoneId']").val(zoneModel.ZoneId);
                $("#editForm select[name='ZoneEdit.OrganizationId']").val(zoneModel.OrganizationId).change();

                $("#editForm input[name='ZoneEdit.Code']").val(zoneModel.Code);
                $("#editForm input[name='ZoneEdit.Name']").val(zoneModel.Name);
                $("#editForm input[name='ZoneEdit.IsActive']")[0].checked = zoneModel.IsActive;
                $("#editForm select[name='ZoneEdit.AssignmentTypeId']").val(zoneModel.AssignmentTypeId);
                $("#editForm select[name='ZoneEdit.UnitIds']").val(unitsId).trigger('change');

                zone.addLabel($("#editForm"), zoneModel.CommentTranslations);

                if (zoneModel.HasImage) {
                    file.setPicture("#editForm", "/Content/images/Zone/" + zoneModel.ImageName);
                }

                for (u in units) {
                    var item = units[u];
                    $("#ZoneEdit_UnitIds").append('<option selected="selected" value="' + item.OrganizationUnitId + '">' + item.OrganizationUnitName + '</option>');
                }

                if (zoneModel.Color != undefined && zoneModel.Color != "") {
                    $("#editForm input[name='ZoneEdit.Color']").val(zoneModel.Color);
                    $("#editForm input[name='ZoneEdit.Color']").spectrum("set", zoneModel.Color);
                } else {
                    $("#editForm input[name='ZoneEdit.Color']").val("#222222");
                    $("#editForm input[name='ZoneEdit.Color']").spectrum("set", "#222222");
                }
                if (zoneModel.SurZoning) {
                    $("#editForm input[name='ZoneEdit.SurZoning']").attr("checked", "checked");
                    $("#editForm input[name='ZoneEdit.SurZoning']")[0].checked = true;
                } else {
                    $("#editForm input[name='ZoneEdit.SurZoning']").removeAttr("checked");
                }

                var elem = $(".row-units");
                var onZone = $(".row-on-zone");
                zone.showUnitsAndSurZone(zoneModel.AssignmentTypeId, elem, onZone);

                var i = 0;
                var elem = $("#edit .table-itemlist");
                for (i in zoneModel.ZoneRules) {
                    zone.addItemList(elem, zoneModel.ZoneRules[i], zones);
                }


            }
        });
    },

    addLabel: function (form, labels) {
        if (labels != undefined) {
            $.each(labels, function (index, value) {
                form.find("input[id*='" + index + "__Name']").val(value.Name);
            });
        }
        return false;
    },

    preRempAddZone: function () {
        $.ajax({
            type: "POST",
            url: "Parameter/GetMultizoneVehicleParameter",
            data: null,
            dataType: "json",
            traditional: true,
            el: "#addForm",
            success: function (ret) {
                zone.multizone = ret;
            }
        });
        site.showForm('#addForm', { container: ".main-container" });
        file.resetPicture("#addForm");
        $("#addForm")[0].reset();
        $("#addForm input[name='ZoneAdd.Color']").spectrum("set", "#222222");
        $(".row-units").hide();
        $(".table-itemlist tbody").html("");
    },

    delSelectedZone: function () {
        var ok;
        var s = jQuery("#JqGrid").jqGrid('getGridParam', 'selarrrow');
        if (s == "") {
            jAlert(zone.params.messageAtLeastOneZoneSelected, resources.Warning);
        } else {
            jConfirm(resourcesMessages.SuppressionConfirmation, resources.Warning, function (ok) {
                if (ok && s != "") {
                    $.ajax({
                        type: "POST",
                        url: 'ZoneNew/DeleteSelected',
                        dataType: "json",
                        //el: "#tabs-zone",
                        data: { ids: s },
                        traditional: true,
                        success: function (ret) {
                            if (ret.Success) {
                                site.successMessage(resourcesMessages.SuppressionSuccess);
                            } else {
                                site.errorMessage(resourcesMessages.SuppressionFailed, ret.Exception);
                            }
                            $("#JqGrid").trigger("reloadGrid");
                        }
                    });
                }
            });
        }
    },

    AddZone: function () {
        if ($("#addForm").valid()) {
            var model = $('#addForm textarea, #addForm select, #addForm input[name!="ZoneAdd.ZoneId"] ').serializeObject("ZoneAdd");
            model.SurZoning = $("#addForm input[name='ZoneAdd.SurZoning']").is(":checked");
            model.IsActive = $("#addForm input[name='ZoneAdd.IsActive']").is(":checked");
            model.NameFile = $("#addForm .nameFile").val();

            $.ajax({
                type: "POST",
                url: 'ZoneNew/Add',
                dataType: "json",
                el: "#addForm",
                data: model,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#addForm .cancel").click();
                        $("#JqGrid").trigger("reloadGrid");
                    }
                    else {
                        site.errorMessage(resourcesMessages.ExceptionDuringCreation, null);
                    }
                }
            });

        }
        return false;
    },

    EditZone: function () {
        if ($("#editForm").valid()) {
            var model = $('#editForm').serializeObject("ZoneEdit");
            model.NameFile = $("#editForm .nameFile").val();

            if ($.isArray(model.SurZoning)) {
                model.SurZoning = model.SurZoning[0];
            }
            if ($.isArray(model.IsActive)) {
                model.IsActive = model.IsActive[0];
            }

            $.ajax({
                type: "POST",
                url: 'ZoneNew/Edit',
                dataType: "json",
                el: "#editForm",
                data: model,
                async: false,
                success: function (result) {
                    if (result.Success) {
                        site.successMessage(resources.ValidationSuccess);
                        $("#editForm .cancel").click();
                        $("#JqGrid").trigger("reloadGrid");
                    }
                }
            });

            // Gestion des erreurs
            return false;
        }
    },

    DisableZone: function (elem) {
        $.ajax({
            type: "POST",
            url: 'ZoneNew/DisableZone',
            dataType: "json",
            data: { zoneId: $(elem).val(), isActive: $(elem).is(":checked") },
            success: function (result) {
                if (result.Success) {
                }
            }
        });
    },

    gridComplete: function () {
        var ids = jQuery("#JqGrid").jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var data = jQuery("#JqGrid").jqGrid('getRowData', ids[i]);
            var cl = ids[i];
            var ed = "";
            var color = "<div style='color: " + data.Color + "'>" + data.Color + "</div>";
            var checked = '';
            var imageName = '';
            var assignmentTypeName = '<i class="fa fa-user text-muted"></i>';
            if (site.hasPermission(right.Zone_Edit)) {
                ed = "<button type='button' value='' class='btn btn-circle btn-primary' onclick='zone.preRempEditZone(" + cl + ");'><i class='fa fa-pencil'></i></button>";
            }
            if (data.IsActive == "true") {
                checked = 'checked="checked"';
            }
            if (data.HasPicture == "true") {
                imageName = '<img src="/Content/images/Zone/' + data.ImageName + '?width=17&height=17" />';
            }
            if (data.AssignmentTypeName == "Vehicle") {
                assignmentTypeName = '<i class="fa fa-car text-muted"></i>';
            }
            jQuery("#JqGrid").jqGrid('setRowData', ids[i], { act: ed, AssignmentTypeName: assignmentTypeName, ImageName: imageName, Color: color, IsActive: '<label class="switch-label"><input onclick="return zone.DisableZone(this)" ' + checked + ' class="ace ace-switch ace-switch-6 btn-rotate" type="checkbox" value="' + data.ZoneId + '"/><span class="lbl"></span></label>' });
        }
    },

    getSelect2Params: function (params) {
        if ($("#addForm").is(":visible")) {
            params["organizationId"] = $("#ZoneAdd_OrganizationId").val();
        } else {
            params["organizationId"] = $("#ZoneEdit_OrganizationId").val();
        }
        return params;
    },

    gridReload: function () {
        var data = jQuery("#searchForm").serialize();
        jQuery("#JqGrid").jqGrid('setGridParam', {
            url: "/ZoneNew/DataBind?" + data,
            //  postData: data,
            page: 1
        }).trigger("reloadGrid");

        return false;
    },

    selectAllUnits: function () {
        var form = $(this).parents("form").first();
        var organizationId = form.find("[id*=_OrganizationId]").val();
        $.ajax({
            type: "POST",
            url: 'OrganizationUnit/GetUnits',
            dataType: "json",
            el: "#LimitedEditForm",
            data: { organizationId: organizationId },
            traditional: true,
            success: function (result) {
                var units = result.items;
                var unitField = form.find("[id*='_UnitIds']");
                unitField.html("");
                events.appendUnits(units, form);
            }
        });
        return false;
    }
};

window.zone = zone;
var file = {

    params: {
        crop: false
    },

    scope: null,

    cropper: null,

    deleteActivated: false,

    init: function (params) {
        file.scope = angular.element($(".nameFile")).scope();
        $.extend(this.params, params);
        $(".button-file").show();

        $(".button-file").click(function () {
            if (window.isIe8) {
                $(this).parents(".inner-file").find("span").css("display", "block");
                $(this).parents(".inner-file").find(".button-file").css("visibility", "hidden");
            } else {
                $(this).parents(".inner-file").find("input[type='file']").click();
            }
            return false;
        });

        $(".button-webcam").click(function () {
            var form = $(this).parents(".inner-file");
            form.find(".id-sumbnail").val(form[0].id);
            return false;
        });

        //decomment and try
        file.hideDeleteButton();
        $(".button-delete-picture, .button-delete-file").click(function () {
            if (file.scope.individual) {
                file.scope.$apply(function () {
                    if (file.scope.individual)
                        file.scope.individual.ImageName = "";
                    file.scope.individual.BrokenImage = true;
                    file.scope.individual.PhotoCropMode = false;
                });
            }
            var form = $(this).parents(".inner-file");
            form.find(".img-picture").attr("src", "null");
            form.find(".nameFile").val(null);
            form.find(".nameFile").trigger('input');
            file.resetPicture(".inner-file");
            if (file.cropper) file.cropper('destroy');
            file.hideDeleteButton();
            return false;
        });

        $('.img-picture').on('show', function () {
            file.showDeleteButton();
        });

        $('.img-picture').on('hide', function () {
            file.hideDeleteButton();
        });

        $(".button-rotate-left").click(function () {
            var form = $(this).parents(".inner-file");
            var imgToCrop = form.find("img.img-picture");
            if (file.scope.individual.PhotoCropMode) {
                if (!file.cropper) file.initCropper();
                file.cropper.rotate(-90);
            }

            return false;
        });

        $(".button-rotate-right").click(function () {
            var form = $(this).parents(".inner-file");
            var imgToCrop = form.find("img.img-picture");
            if (file.scope.individual.PhotoCropMode) {
                if (!file.cropper) file.initCropper();
                file.cropper.rotate(90);
            }

            return false;
        });

    },

    showDeleteButton: function () {
        if (this.deleteActivated) $(".button-delete-file").show();
        else file.hideDeleteButton();
    },

    hideDeleteButton: function () {
        $(".button-delete-file").hide();
    },

    getCroppedImage: function (maxWidth) {
        if (file.cropper !== null) {
            var getCroppedCanvas = file.cropper.getCroppedCanvas(maxWidth ? { maxWidth: maxWidth } : {});

            if (getCroppedCanvas != null) {
                var base64Image = getCroppedCanvas.toDataURL("image/png");
                return base64Image.replace('data:image/png;base64,', '');
            }
        }
        return false;
    },

    fileUpload: function () {

        var form = $(this).parents(".inner-file").first();
        if (window.isIe8) {
            form.find(".sumbnail").Spinner("show");
        }

        $(this).fileupload({
            dataType: 'json',
            url: "File/UploadPicture/",
            done: function (e, data) {
                var img = form.find(".sumbnail").html();
                if (data.result.Success) {
                    if (file.scope.individual) {
                        file.scope.individual.PhotoRotation = 0;
                        file.scope.individual.PhotoCropMode = true;
                        file.scope.$apply(function () {
                            if (file.scope.individual !== undefined) {
                                file.scope.individual.BrokenImage = false;
                                file.scope.individual.PhotoToDelete = false;
                            }
                        });
                    }

                    $.each(data.files, function (index, fileTemp) {
                        form.find(".nameFile").val(fileTemp.name);
                        form.find(".nameFile").trigger('input');
                        file.applyPictureChange(fileTemp.name);
                        form.find(".progress").hide();
                        form.find(".sumbnail img").attr("src", site.params.url + "/Content/temp/" + site.params.userName + "/" + fileTemp.name).show();
                        form.find(".sumbnail").show();
                        form.find(".img-picture").show().trigger('show');

                        if (file.params.crop) {
                            if (file.cropper) file.cropper.destroy();
                            
                            file.cropper = new Cropper(
                                form.find(".sumbnail img").get()[0],
                                {
                                    aspectRatio: 9 / 10,
                                    zoomable: false,
                                    checkOrientation: false,
                                    crop: function (e) {
                                        var xFile = Math.round(e.x, 0);
                                        var yFile = Math.round(e.y, 0);

                                        if (xFile < 0) {
                                            xFile = 0;
                                        }
                                        if (yFile < 0) {
                                            yFile = 0;
                                        }
                                    }
                                }
                            );
                        }
                    });
                } else {
                    form.find(".progress").hide();
                    form.find(".sumbnail").html(img).show();
                    form.find(".field-validation-error").html(data.result.Exception);
                }
            },
            progressall: function (e, data) {
                form.find(".progress").show();

                var progress = parseInt(data.loaded / data.total * 100, 10);
                form.find(".progress .bar").css(
                    'width',
                    progress + '%'
                );
            },
            add: function (e, data) {

                if (data.autoUpload || (data.autoUpload !== false &&
                    ($(this).data('blueimp-fileupload') ||
                        $(this).data('fileupload')).options.autoUpload)) {

                    data.submit();
                    data.context = form.find(".sumbnail").hide();
                }
            },
            submit: function (e, data) {
                var $this = $(this);
                $this.fileupload('send', data);
                return false;
            },
            fail: function (e, data) {
                var img = form.find(".sumbnail").html();
                form.find(".progress").hide();
                form.find(".sumbnail").html(img).show();
                form.find(".field-validation-error").html("Fichier trop volumineux.");
            },
            always: function (jqXHRorResult, textStatus, jqXHRorError) {
                $("#editForm input.file, #addForm input.file").hide();
                if (window.isIe8) {
                    form.find(".sumbnail").Spinner("destroy");
                }
            }
        });
    },

    setPicture: function (formId, urlPicture) {
        $(formId).find(".img-picture").attr("src", urlPicture).show().trigger('show');
        $(formId).find(".nameFile").trigger('input');
        $(formId).find(".fa-picture-o").hide();
    },

    resetPicture: function (formId) {
        $(formId).find(".fa-picture-o").show();
        $(formId).find(".img-picture").hide().trigger('hide');
        $(formId).find(".nameFile").val(null);
        $(formId).find(".nameFile").trigger('input');
        file.applyPictureChange(null);
    },

    applyPictureChange: function (pictureName) {
        var scope = angular.element($(".nameFile")).scope();
        file.scope.$apply(function () {
            if (file.scope.individual)
                file.scope.individual.NameFile = pictureName;
        });

    },

    initCropper: function (form) {

        this.cropper = new Cropper(
            $(".inner-file").find(".sumbnail img").get()[0],
            {
                aspectRatio: 9 / 10,
                zoomable: false,
                checkOrientation: false,
                crop: function (e) {
                    var xFile = Math.round(e.x, 0);
                    var yFile = Math.round(e.y, 0);

                    if (xFile < 0) {
                        xFile = 0;
                    }
                    if (yFile < 0) {
                        yFile = 0;
                    }
                }
            }
        );
        if (file.scope.individual) {
            file.scope.individual.PhotoCropMode = true;
        }
    },


    // paramètres :
    //      div     : bloc qui encapsule le champ d'upload d'image [.img-wrapper]
    //      image   : élément image qui affiche à l'écran un aperçu de ce qui a été uploadé [se trouve sous div]
    //      hidden  : champ caché qui va contenir l'image base64 sous forme de chaîne de caractères et qui sera envoyé au serveur [se trouve sous div]
    //      parameterMaxWidth, parameterMaxHeight : tailles en paramètres
    //              Voir UnlimitedEventModel.cshtml pour un exemple de structure
    resizeBase64: function (div, image, hidden, parameterMaxWidth, parameterMaxHeight) {
        // Il faut systématiquement supprimer le canvas, car quand on le réutilise, il "compresse" la nouvelle image pour l'ajouter à l'image précédente aussi compressée (si elle a déjà été définie)
        // Ce qui affiche 2 images ensemble, comprimées dans le même canvas qui garde la même dimension maximale
        div.find("canvas").remove();
        var canvas = document.createElement("canvas");
        canvas.className = "hidden";
        div.append(canvas);


        if (image !== undefined || image !== null) {
            var ctx = canvas.getContext("2d");
            if (image.naturalWidth >= parameterMaxWidth && image.naturalHeight >= parameterMaxHeight) {
                canvas.width = parameterMaxWidth;

                if (image.naturalWidth <= parameterMaxWidth) {
                    canvas.width = image.naturalWidth;
                }

                canvas.height = (image.naturalHeight * parameterMaxWidth) / image.naturalWidth;

                if (canvas.height > parameterMaxHeight) {
                    canvas.width = image.naturalWidth * parameterMaxHeight / image.naturalHeight;
                    canvas.height = parameterMaxHeight;
                }

                var ratio = parameterMaxWidth / image.naturalWidth;

                if (image.naturalHeight > image.naturalWidth) {
                    ratio = parameterMaxHeight / image.naturalHeight;
                }

                ctx.scale(ratio, ratio);
            } else { // l'image a des dimensions strictement inférieures aux limites, en largeur ET en longueur, si on le spécifie pas, le canvas va prendre une dimension par défaut pour le canvas, 150x200
                canvas.width = image.naturalWidth;
                canvas.height = image.naturalHeight;
            }

            ctx.drawImage(image, 0, 0);
            var dataurl = canvas.toDataURL("image/png");
            hidden.val(dataurl);
        }
    },

    resizeOnScreen: function (image, parameterMaxWidth, parameterMaxHeight) {

        // On montre directement le résultat final à l'écran, en redimensionnant à l'écran l'image
        if (image.naturalWidth >= parameterMaxWidth && image.naturalHeight >= parameterMaxHeight) { // On vérifie si l'image uploadée n'est pas plus petite que les dimensions max
            var ratio = parameterMaxWidth / image.naturalWidth;
            if (image.naturalHeight > image.naturalWidth) {
                ratio = parameterMaxHeight / image.naturalHeight;
            }

            if (image.naturalWidth > image.naturalHeight) {
                $(image).width(parameterMaxWidth);
                $(image).height(image.naturalHeight * ratio);
            } else if (image.naturalWidth < image.naturalHeight) {
                $(image).height(parameterMaxHeight);
                $(image).width(image.naturalWidth * ratio);
            } else if (image.naturalWidth === image.naturalHeight) {
                $(image).width(parameterMaxWidth);
                $(image).height(parameterMaxHeight);
            }
        } else { // sinon on réinitialise les dimension de l'image (pour qu'elle ne soit pas déformée à cause d'un redimensionnement précédent)
            $(image).width("");
            $(image).height("");
        }
    },
}
var printer = {

    print: function (url) {
        if (url !== "") {
            var printFrame = document.getElementById('printFrame');
            var oldEmbed = document.getElementById("printEmbed");

            if (oldEmbed != null) {
                document.body.removeChild(oldEmbed);
            }

            if (window.downloadFile.isChrome) {
                printFrame.setAttribute('src', url);
                setTimeout(function () {
                    window.document.getElementById('printFrame').contentWindow.document.execCommand('print', false, null);
                    return true;
                }, 5000);
            }

            if (window.downloadFile.isIe) {
                var printEmbed = document.createElement("embed");
                printEmbed.setAttribute("width", "0%");
                printEmbed.setAttribute("height", "0%");
                printEmbed.setAttribute("id", "printEmbed");
                printEmbed.setAttribute("src", url);
                printEmbed.setAttribute("type", "application/pdf");

                document.body.appendChild(printEmbed);
                setTimeout(function () {
                    printEmbed.print();
                    return true;
                }, 3000);
            }
        }
    }
}

var camera = {

    params: {
        crop: false
    },
    width: 320, // 320
    height: 240, //240
    modal: undefined,
    container: null,
    file: null,
    buttonTake: null,
    buttonSave: null,
    buttonCancel: null,
    camera: null,
    data: null,

    init: function (params) {
        $.extend(this.params, params);

        $(".button-webcam").show();
        camera.initDialog();

        camera.container = $(".picture-container");

        camera.buttonTake = camera.modal.find(".take-picture");
        camera.buttonSave = camera.modal.find(".submit");
        camera.buttonCancel = camera.modal.find(".btn-danger");
        camera.camera = camera.container.find(".camera");
        
        camera.buttonSave.click(camera.savePicture);
        camera.buttonTake.click(camera.takePicture);
        camera.buttonCancel.click(camera.closeDialogPicture);
        $(".button-webcam").click(camera.openDialogPicture);
        $("#screenshot").hide();

        if ((navigator.mediaDevices && navigator.mediaDevices.getUserMedia) == false) {
            alert('Webcam access is not supported by your browser');
        }
    },

    initDialog: function () {
        // initialisation de la popup
        var data = {
            title: "Prendre une photo",
            css: "modal-webcam",
            buttons: [{ type: "primary", css: "take-picture", label: "Prendre une photo", icon: { type: "camera" } },
            { type: "success", css: "submit", label: "Enregistrer", icon: { type: "check" } }
            ]
        };

        var template = $("#modal-template").clone().html();
        var html = Mustache.to_html(template, data);
        var con = $("<div>").html(html);
        $('body').append(con);
        camera.modal = con.find(".modal");
        camera.container = $(".picture-container");
        camera.container.detach();
        camera.modal.find(".modal-body").append(camera.container);
    },

    closeDialogPicture: function () {

        const video = document.querySelector('video');
        const mediaStream = video.srcObject;
        const tracks = mediaStream.getTracks();
        tracks.forEach(track => track.stop())
        camera.modal.modal('hide');

    },

    openDialogPicture: function () {
        camera.modal.modal('show');
        const constraints = {
            video: true
        };
        // start webcam video capture
        navigator.mediaDevices.getUserMedia(constraints)
            .then((stream) => { document.querySelector('video').srcObject = stream })

            .catch(camera.takePictureFailureCallback);
    },

    savePicture: function () {
        var scope = angular.element($(".nameFile")).scope();
        scope.$apply(function () {
            if (scope.individual) {
                scope.individual.BrokenImage = false;
                scope.individual.PhotoToDelete = false;

            }
        });
        
        if (camera.params.crop) {
            file.initCropper();
        }
        file.scope.individual.PhotoCropMode = true;
        camera.closeDialogPicture();
 },


    takePicture: function () {

        $("#screenshot").show();
        // do not use jquery selector
        const canvas = document.querySelector('#canvas');
        const video = document.querySelector('video');
        const photo = document.querySelector('#screenshot')
        const mainPhoto = document.querySelector('#savedPicture')
        
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
        mainPhoto.setAttribute('src', data);

    },

    takePictureFailureCallback: function () {
        alert("Unable to start webcam");
    }
};

