/*  
 *  ©2009-2018, Tecknodreams Software Consulting Pvt. Ltd.
 */
/* Manually minify using js es6 minify online */
/* Global variable */
var arMISAccessMap = new Map();
var reportList = "";
var ARProjectList = "";
var arMISReportsMap = new Map();
var filterDivList = [];
var editLength="";
var filterMap = new Map();
var existingFilter = new Map();

/* show introduction and summary starts */
$(document).on("click", "#arEnableIntrSummary", function (e) {
    if ($('#arEnableIntrSummary').is(':checked')) {
        $('#intrSummaDiv').css("display", "");
    } else {
        $('#intrSummaDiv').css("display", "none");
    }
});

$(document).on("mouseup","#arMISAccessRole + .ms-parent .ms-choice",function(){
    if(isarMISAccessRoleRefreshed==false){
        $("#arMISAccessRole").multipleSelect("refresh");
        $("#arMISAccessRole").multipleSelect("open");
        isarMISAccessRoleRefreshed=true;
    }
});

/* show introduction and summary ends */
// OLD method getReportListBasedOnProject
function getMISAddOrEditView(projectId, isEditView, editData) {
    var authDetail=getAuthData(arTenantName);
    $("#reportListDiv").css("display", "");
    $("#misSelectedProjectId").val(projectId);
    var siteId = $('#siteId').val();
    var module = $('#arModule').val();
    reportList = "";
    var finalData = "";
    clearMISPageElements();
    if (!isEditView) {
        $('#arMIS_' + module).prop('selected', true);
        $('#arMIS_moduleList').multipleSelect('refresh');
    } else {
        //Setting module data on edit call
        setMISModuleListOnEdit(editData.module);
    }
    //Ajax call to get the report category list.
    $("#progressMsg").css("display", "block");
    $.ajax({
        url: "//" + arIpAddress + "/default-publish/publish/misview?platform=false&id=" + projectId + "&inbuilt=false&userid=" + $('#arUserId').val() + "&module=" + module + "&siteId=" + siteId + "&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
        type: "GET",
        contentType: 'application/json',
        dataType: 'json',
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        crossDomain: true,
        success: function (data, textStatus, jqXHR) {
            $("#progressMsg").css("display", "none");
            finalData = data;

            populateMISARPojectList(isEditView, projectId, editData);
            populateMISARSiteList(isEditView, siteId, editData);

            if (!isEditView) {
                arGetReportsBasedOnProjectList(isEditView, "");
            } else {
                arGetReportsBasedOnProjectList(isEditView, editData);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
//            console.log(' getMISAddOrEditView : error : textStatus' + textStatus);
            $("#progressMsg").css("display", "none");
            redirectToReportTypeView('MIS');
            setMISPublishErrorMessage("Failed to load the data, please contact Administrator");
        },
        complete: function (jqXHR, textStatus) {
//            console.log(' getMISAddOrEditView : complete : textStatus' + textStatus);
            $("#progressMsg").css("display", "none");
            // renderMISRoles(finalData.accessRoles,finalData.rolesUserList);
            // renderMISUsers(finalData.userList,finalData.rolesUserList);
//            renderOverrideTimePeriodView();
            reportList = finalData;
            var buttonView = $('<input type="button" id="arReportSaveBtn" onclick="arMISSave();" value="Save" class="btn apply updateBtn"><a href="javascript:void(0)" class="btn cancel" onclick="arMISCancel();">Cancel</a>');
            $('#arMISSubmitDiv').empty();
            $('#arMISSubmitDiv').append(buttonView);
            if(editLength==0 && editLength!=null){
                if (isEditView) {
                    editData="";
                   $("#misUserMsg.errMsg").remove();
                   $("#arMISEditGrid").before('<div class="errMsg statusIco" id="misUserMsg"><i class="ico statusIco"></i><p>Selected Custom Report(s) may have moved to Inbuilt Reports or you may not have access to it</p></div>');
                   showEditView(finalData, editData);
              }
            }
            else{
                if (isEditView) {
                    showEditView(finalData, editData);
                }
             }
        }
    });
}

function setMISModuleListOnEdit(moduleList) {
    var moduleArr = moduleList.split(",");
    for (var j = 0; j < moduleArr.length; j++) {
        var reports = $('#arMIS_moduleList').find('option');
        $.each(reports, function (i, option) {
            if (option.value == moduleArr[j]) {
                var doc = document.getElementById(option.id);
                doc.selected = true;
            }
        });
    }
    $('#arMIS_moduleList').multipleSelect('refresh');
}

function formReportListView(data, divId, ulDefaultId, ulSelectId) {
    $('#' + divId).empty();
    var arProjectMap = new Map();
    $('#ar_projectList').find("option:selected").each(function () {
        arProjectMap.set($(this).val(), $(this).text());
    });
    var arModuleMap = new Map();
    $('#arMIS_moduleList').find("option:selected").each(function () {
        arModuleMap.set($(this).val(), $(this).text());
    });
    var ulView = $('<ul class="sortCust connected list" id=\'' + ulDefaultId + '\' name=\'' + ulDefaultId + '\' >'); //arDefaultReports
    $.each(data, function (i, item) {
      //  if (item.viewPermission == 1 && item.template != 'RPT Stored Procedure') {
        //if (item.viewPermission == 1 && item.template != 'RPT Stored Procedure') // removing  item.template != 'RPT Stored Procedure' this condition to support stored procedure
   if(item.viewPermission == 1){
            var displayText = arModuleMap.get(item.module) + "-->" + arProjectMap.get(item.projectId) + "-->" + item.reportName;
            var liView = $('<li>', {text: displayText, 'data-value': JSON.stringify(item), id: ulDefaultId + '_' + item.reportLabel, title: displayText});
            liView.appendTo(ulView);
        }
    });
    $('#' + divId).append('<div class="searchCustFld"><input type="text" placeholder="Search for Reports" class="custSearch" id=' + divId + '_Search><a href="javascript:void(0)" class="searchCust"></a></div>');
    $('#' + divId).append(ulView);
    var byId = function (id) {
        return document.getElementById(id);
    }
    Sortable.create(byId(ulDefaultId), {
        group: "words",
        animation: 150
    });
    // adding on change method to only selected report s block and avoiding override time period block
    if (ulSelectId == 'arSelectedReports') {
        $('#arMISFiltersDiv').empty();
        Sortable.create(byId(ulSelectId), {
            group: "words",
            animation: 150,
            onAdd: function (/**Event*/evt) {
                arPopulateMISFilters('add');
            },
            onRemove: function (/**Event*/evt) {
                arPopulateMISFilters('remove'); /*commented by Dheeraj on May 28th'20  */
                //arPopulateMISFiltersForRemovingReport('remove'); 
				/* code added by Dheeraj for DREC15497 for 7th point */


            }
        });
    } else {
        Sortable.create(byId(ulSelectId), {
            group: "words",
            animation: 150
        });
    }
    $('.sortCust').perfectScrollbar();
    
}

function formReportListViewForEdit(data, editData, divId, ulDefaultId, ulSelectId) {
    var reportList = data;
    var savedReportList = [], nonSelectedReportList = [], selectedReportList = [];
    var editReportStrArray = "";
    if (divId != 'arIncludeDefaultReportsDiv') {
        editReportStrArray = (editData.selectedMisReportList).split("|");
    } else {
        editReportStrArray = (editData.includedReports).split("|");
    }

    for (var i = 0; i < editReportStrArray.length; i++)
        savedReportList.push(+editReportStrArray[i]);

    reportList.filter(function (val) {
        if (savedReportList.indexOf(val.id) == -1) {
            nonSelectedReportList.push(val);
        } else {
            selectedReportList.push(val);
        }
    });
    $('#' + divId).empty();
      
    $('#' + divId).append('<div class="searchCustFld"><input type="text" placeholder="Search for Reports" class="custSearch" id=' + divId + '_Search><a href="javascript:void(0)" class="searchCust"></a></div>');
   
    var ulView = $('<ul class="sortCust connected list" id=\'' + ulDefaultId + '\' name=\'' + ulDefaultId + '\' >'); //arDefaultReports
    $('#' + divId).append(ulView);
    if (nonSelectedReportList.length > 0) {
        var arProjectMap = new Map();
        $('#ar_projectList').find("option:selected").each(function () {
            arProjectMap.set($(this).val(), $(this).text());
        });
        var arModuleMap = new Map();
        $('#arMIS_moduleList').find("option:selected").each(function () {
            arModuleMap.set($(this).val(), $(this).text());
        });
        ulView = $('#' + ulDefaultId);
        $.each(nonSelectedReportList, function (i, item) {
            if (item.viewPermission == 1) {
                var displayText = arModuleMap.get(item.module) + "-->" + arProjectMap.get(item.projectId) + "-->" + item.reportName;
                var liView = $('<li>', {text: displayText, 'data-value': JSON.stringify(item), id: ulDefaultId + '_' + item.reportLabel, title: displayText});
                liView.appendTo(ulView);
            }
        });
        $('#' + divId).append(ulView);
    }
    if (selectedReportList.length > 0) {
        $('#' + ulSelectId).empty();
        var arProjectMap = new Map();
        $('#ar_projectList').find("option:selected").each(function () {
            arProjectMap.set($(this).val(), $(this).text());
        })
        $.each(selectedReportList, function (i, item) {
            if (item.viewPermission == 1) {
                var displayText = arProjectMap.get(item.projectId) + "-->" + item.reportName;
                var liView = $('<li>', {text: displayText, 'data-value': JSON.stringify(item), id: ulDefaultId + '_' + item.reportLabel, title: displayText});
                $('#' + ulSelectId).append(liView);
            }
        });
    }
    var byId = function (id) {
        return document.getElementById(id);
    }
    Sortable.create(byId(ulDefaultId), {
        group: "words",
        animation: 150
    });
    /*Sortable.create(byId(ulSelectId), {
     group: "words",
     animation: 150
     });*/
    if (ulSelectId == 'arSelectedReports') {
//        $('#arMISFiltersDiv').empty();
        Sortable.create(byId(ulSelectId), {
            group: "words",
            animation: 150,
            onAdd: function (/**Event*/evt) {
                arPopulateMISFilters('add');
            },
            onRemove: function (/**Event*/evt) {
                arPopulateMISFilters('remove');
            }
        });
    } else {
        Sortable.create(byId(ulSelectId), {
            group: "words",
            animation: 150
        });
    }
    $('.sortCust').perfectScrollbar();
    arMisRenderEditFilters(editData);// update filter block for edit reports
    return selectedReportList.length;
}
$(document).on("mouseover", ".sortCust", function () {
    $(this).perfectScrollbar('update');
});


$(document).on("click", "#arMISOverrideTimePeriod", function (e) {
    if ($('#arMISOverrideTimePeriod').is(':checked')) {
        $('#arMISAdvanceSettingDiv').css("display", "");
        arGetReportsForOverrideTimePeriod(arMISReportData);
    } else {
        $('#arMISAdvanceSettingDiv').css("display", "none");
    }
});

function renderMISRoles(rolesList,roleUserMap) {
    var moduleList = $('#arMIS_moduleList').multipleSelect('getSelects');
    $('#arMISAccessRole').empty();
    var $optionChoose = $("<option></opion>");
    $optionChoose.val("-1");
    $optionChoose.text("--Choose--");
    if(moduleList.toString() === 'CMDB' || moduleList.toString() === 'ITSM'){
        $.each(rolesList, function (i, item) {
            if(moduleList.toString() === 'CMDB'){
                var option = $('<option>', {id: 'cmdbroles_' + item.assetRoleId, text: item.roleName, value: 'CMDB_'+item.assetRoleId});
            }else{
                var option = $("<option>", {text: item.roleDisplayName, value: 'ITSM_'+item.projectRoleID, id: "itsmroles_" + item.projectRoleID});
            }
            $("#arMISAccessRole").append(option);
        });
    }else{
        $.each(roleUserMap, function (optgroup, roleusers) {
            $.each(roleusers.accessRoles, function (i, item) {
                if(optgroup === 'CMDB Roles'){
                    var option = $('<option>', {id: 'cmdbroles_' + item.assetRoleId, text:"CMDB -- " + item.roleName, value: 'CMDB_'+item.assetRoleId});
                }else{
                    var option = $("<option>", {text:"ITSM -- " + item.roleDisplayName, value: 'ITSM_'+item.projectRoleID, id: "itsmroles_" + item.projectRoleID});
                }
                $("#arMISAccessRole").append(option);
            });
        });
    }
    $("#arMISAccessRole").multipleSelect('refresh');
    $("#arMISAccessRole").multipleSelect('uncheckAll');

}

function renderMISUsers(userList,roleUserMap) {
    var moduleList = $('#arMIS_moduleList').multipleSelect('getSelects');
    $('#arMISAccessUser').empty();
    var $optionChoose = $("<option></opion>");
    $optionChoose.val("-1");
    $optionChoose.text("--Choose--");
    if(moduleList === 'CMDB' || moduleList === 'ITSM'){
        $.each(userList, function (i, user) {
            var option = $("<option>", {text: user[1], value: user[0], id: "users_" + user[0]});
            $("#arMISAccessUser").append(option);
        });
    }else{
        $.each(roleUserMap, function (optgroup, roleusers) {
            $.each(roleusers.userList, function (i, user) {
                var option = $('<option>', {id: 'users_' + user[0], text: user[1], value: user[0]});
                $("#arMISAccessUser").append(option);
            });
        });
    }
    $("#arMISAccessUser").multipleSelect('refresh');
    $("#arMISAccessUser").multipleSelect('uncheckAll');
}

function arMISPermissionCheckBoxValidation(checkFlag) {
    if (checkFlag === 'single') {
        if ($('#arMISAccessView').is(':checked') && $('#arMISAccessEdit').is(':checked') && $('#arMISAccessDelete').is(':checked')) {
            $('#arMISAccessView').prop('checked', false);
            $('#arMISAccessEdit').prop('checked', false);
            $('#arMISAccessDelete').prop('checked', false);
            $('#arMISAccessAll').prop('checked', true);
        }
        if ($('#arMISAccessEdit').is(':checked') || $('#arMISAccessDelete').is(':checked')) {
            $('#arMISAccessView').prop('checked', true);
        }
        if ($('#arMISAccessAll').is(':checked') && ($('#arMISAccessView').is(':checked') ||
                $('#arMISAccessEdit').is(':checked') || $('#arMISAccessDelete').is(':checked'))) {
            $('#arMISAccessAll').prop('checked', false);
        }
    }
    if (checkFlag === 'all' && $('#arMISAccessAll').is(':checked')) {
        $('#arMISAccessView').prop('checked', false);
        $('#arMISAccessEdit').prop('checked', false);
        $('#arMISAccessDelete').prop('checked', false);
    }
}

function arMISClearUserRoles() {
    $("#arMISAccessRole").multipleSelect("uncheckAll");
    $("#arMISAccessRole").multipleSelect("refresh");
    $("#arMISAccessUser").multipleSelect("uncheckAll");
    $("#arMISAccessUser").multipleSelect("refresh");
    $('#arMISAccessView').prop('checked', true);
    $('#arMISAccessEdit').prop('checked', false);
    $('#arMISAccessDelete').prop('checked', false);
    $('#arMISAccessAll').prop('checked', false);
}

function arMISAddAccessPermissions() {
    var rolesId = "", usersId = "", userNames = "", roleNames = "", accessPermissions = [];
    rolesId = $('#arMISAccessRole').multipleSelect('getSelects');
    usersId = $('#arMISAccessUser').multipleSelect('getSelects');

    /* validation */
    if (rolesId.length == 0 && usersId.length == 0) {
        var errMsg = "please select roles or users";
        $("#arMISAccessRole").closest('.formElem').addClass('errField');
        $('#arMISAccessRole').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#arMISAccessRole').multipleSelect("focus");
        $("#arMISAccessUser").closest('.formElem').addClass('errField');
        $('#arMISAccessUser').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#arMISAccessUser').multipleSelect("focus");
        return;
    }
    if (rolesId !== null && rolesId.length !== 0) {
        if (validateARMISPermissions("#arMISAccessRole", "roles_")) {
            $("#accessmis_permission_confirm").show();
            return;
        } else {
            arMISAccessAddToMap("#arMISAccessRole", "roles_", 1);
        }

    }
    if (usersId !== null && usersId.length !== 0) {
        if (validateARMISPermissions("#arMISAccessUser", "users_")) {
            $("#accessmis_permission_confirm").show();
            return ;
        } else {
            arMISAccessAddToMap("#arMISAccessUser", "users_", 1);
        }

    }
    arMISClearUserRoles();
}
function validateARMISPermissions(elementId,appId){
    var selectedValues = $(elementId).multipleSelect('getSelects');//get selected values from multi select box
    var i = 0;
    var flag =false;
    var value;
    var text;
    $.each(selectedValues, function (i, val) {
        if(appId.includes('roles')){
            appId = ((val.split("_")[0]) === 'CMDB') ? "cmdbroles_":"itsmroles_";
            value = val;
            val = val.split("_")[1];
            var tempText = $('#' + appId + val).text().split(" -- ")[1];
            text = tempText === undefined? $('#' + appId + val).text() : tempText;
        }else{
            text = $('#' + appId + val).text();
            value = $('#' + appId + val).val();
        }
        var id = value + '_' + text.split(' ').join('_') + '_ul';
        if (arMISAccessMap.has(id)) {
            flag =true;
            return true;
        }
    });
    return flag;
}
function arMISAddPermissionActionType(acctionType){
    var rolesId = "", usersId = "";
    rolesId = $('#arMISAccessRole').multipleSelect('getSelects');
    usersId = $('#arMISAccessUser').multipleSelect('getSelects');

    /* validation */
    if (rolesId.length === 0 && usersId.length === 0) {
        var errMsg = "please select roles or users";
        $("#arMISAccessRole").closest('.formElem').addClass('errField');
        $('#arMISAccessRole').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#arMISAccessRole').multipleSelect("focus");
        $("#arMISAccessUser").closest('.formElem').addClass('errField');
        $('#arMISAccessUser').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#arMISAccessUser').multipleSelect("focus");
        return;
    }
    if (rolesId !== null && rolesId.length !== 0) {
        arMISAccessAddToMap("#arMISAccessRole", "roles_", acctionType);
    }
    if (usersId !== null && usersId.length !== 0) {
        arMISAccessAddToMap("#arMISAccessUser", "users_", acctionType);
    }
    arMISClearUserRoles();
}
function arMISAccessAddToMap(elementId, appId,actionType) {

    var permissionsArray = [];
    if ($('#arMISAccessView').is(':checked')) {
        permissionsArray.push($('#arMISAccessView').val());
    }
    if ($('#arMISAccessEdit').is(':checked')) {
         if (!(permissionsArray.indexOf($('#arMISAccessView').val()) >= 0)) {
            permissionsArray.push($('#arMISAccessView').val());
        }
        permissionsArray.push($('#arMISAccessEdit').val());
    }
    if ($('#arMISAccessDelete').is(':checked')) {
        if (!(permissionsArray.indexOf($('#arMISAccessView').val()) >= 0)) {
            permissionsArray.push($('#arMISAccessView').val());
        }
        permissionsArray.push($('#arMISAccessDelete').val());
    }
    if ($('#arMISAccessAll').is(':checked')) {
        permissionsArray.length = 0;
        permissionsArray.push($('#arMISAccessAll').val());
    }
    if (permissionsArray.length === 0) {
        return;
    }
    var accessPermissions = permissionsArray.join();
    var selectedValues = $(elementId).multipleSelect('getSelects');
    var text;
    $.each(selectedValues, function (i, val) {
        var value;
        if(appId.includes('roles')){
            appId = ((val.split("_")[0]) === 'CMDB') ? "cmdbroles_":"itsmroles_";
            value = val;
            val = val.split("_")[1];
            var tempText = $('#' + appId + val).text().split(" -- ")[1];
            text = tempText === undefined? $('#' + appId + val).text() : tempText;
        }else{
            value = $('#' + appId + val).val();
            text = $('#' + appId + val).text();
        }
        var accessType = "";
        if (elementId == '#arMISAccessRole') {
            accessType = 'role';
        } else {
            accessType = 'user';
        }
        
        var id = value + '_' + text.split(' ').join('_') + '_ul';
        if (arMISAccessMap.has(id)) {
            if (actionType === 1) {
                var accessObj = arMISAccessMap.get(id);
                accessObj.permissions = ""; // code added by Dheeraj //May14'20 for update issue no 4. in defect.
                // var accessPermis = (accessObj.permissions).split(","); commented by Dheeraj Mishra
                var accessPermis = [];
               // var previousPermis = (accessObj.permissions).split(",");
                accessPermis.length = 0;
                $.each(permissionsArray, function (i, permission) {
                    if (permission.toLowerCase() === 'all') {
                        accessPermis.length = 0;
                        accessPermis.push(permission);
                    } else {
                        if (accessPermis.indexOf('all') >= 0) {
                            accessPermis.length = 0;
                        }
                        if ((accessPermis.indexOf(permission) >= 0)) {
                        } else {
                            accessPermis.push(permission);
                        }
                    }
                });
                accessObj.permissions = accessPermis.join();
                arMISAccessMap.set(id, accessObj);
                arSetMISPermissionsDiv();
            }         
        } else {
            var accessObj = {};
            accessObj.accessType = accessType;
            accessObj.permissions = accessPermissions;
            if (accessType == 'role') {
                accessObj.roleId = value;
                accessObj.accessorName = text;
                accessObj.userId = '';
            } else {
                accessObj.roleId = '';
                accessObj.accessorName = text;
                accessObj.userId = value;
            }
            arMISAccessMap.set(id, accessObj);
            arSetMISPermissionsDiv();
        }
    });    
}

function arSetMISPermissionsDiv() {
    $('#arMISUserRolesDiv').empty();
    $("#accessmis_permission_confirm").hide();
//    arMISAccessMap.forEach((value, key, entry) => {
    arMISAccessMap.forEach(function (value, key, map) {
        var ulView = "";
        if (value.accessType == 'role') {
            ulView = $('<ul class="lstView" id="' + key + '">' +
                    '<li class="custFld"><span>' + value.accessorName + '</span></li><li class="criteriaFld"><span>--</span></li>' +
                    '<li class="valFld"><span>' + value.permissions + '</span></li>' +
                    '<a href="javascript:void(0)" class="delCust"><img src="assets/images/err_temp.png" alt=""></a>' +
                    '<div class="alertMsg" style="display: none;"><p>Are you sure, want to delete ?</p>' +
                    '<a href="javascript:void(0)" class="yesBtn" id="yesBtn" onclick="arRemoveMISAccessPermissions(\'' + key + '\')">Yes</a>' +
                    '<a href="javascript:void(0)" class="noBtn" id="noBtn" style="float: left;">No</a></div></ul>');
        } else {
            var permissionAccessNameUserId = key.trim().split('_')[0];
            var tempOnBehalfUserName = value.accessorName;
            if(permissionAccessNameUserId !== '0'){
                tempOnBehalfUserName = getUserNameWithOnBehalfColumns(permissionAccessNameUserId);
            }
            ulView = $('<ul class="lstView" id="' + key + '">' +
                    '<li class="custFld"><span>--</span></li><li class="criteriaFld"><span>' + tempOnBehalfUserName + '</span></li>' +
                    '<li class="valFld"><span>' + value.permissions + '</span></li>' +
                    '<a href="javascript:void(0)" class="delCust"><img src="assets/images/err_temp.png" alt=""></a>' +
                    '<div class="alertMsg" style="display: none;"><p>Are you sure, want to delete ?</p>' +
                    '<a href="javascript:void(0)" class="yesBtn" id="yesBtn" onclick="arRemoveMISAccessPermissions(\'' + key + '\')">Yes</a>' +
                    '<a href="javascript:void(0)" class="noBtn" id="noBtn" style="float: left;">No</a></div></ul>');
        }
        $('#arMISUserRolesDiv').append(ulView);
    });
}

function arRemoveMISAccessPermissions(ulId) {
    arMISAccessMap.delete(ulId);
    arSetMISPermissionsDiv();
}

function formMISSaveUpdateJsonObject(selectedReportIds, includedReportIdsForOverrideTimePeriod, upadteOrSave) {
    //code added by Dheeraj on May 13th'20 for changing creted by column changed.
    var arCreatedBy = "";
    arCreatedBy = $("#arMISEditGrid").find('.slick-cell.l2.r2').text();
    if (typeof arCreatedBy == 'undefined' || !arCreatedBy || arCreatedBy.length === 0 || arCreatedBy === "" || !/[^\s]/.test(arCreatedBy) || /^\s*$/.test(arCreatedBy) || arCreatedBy.replace(/\s/g, "") === "") {
        arCreatedBy = $('#arUserName').val();
    }


    var enabledIntroSummary = "", timePeriodText = "", timePeriodVal = "", enableOverrideTimePeriod = "";
    ($('#arEnableIntrSummary').is(':checked')) ? enabledIntroSummary = 1 : enabledIntroSummary = 0;
    ($('#arMISOverrideTimePeriod').is(':checked')) ? enableOverrideTimePeriod = 1 : enableOverrideTimePeriod = 0;
    /* forming user and roles array */


    var accessPermissions = {};//save logged in user and provide full acess
    if (upadteOrSave) {
        // code added by Dheeraj Mishea on May 14'20 for						 
        accessPermissions.accessType = 'user';

        accessPermissions.permissions = 'all';

        accessPermissions.roleId = '';
        accessPermissions.accessorName = $('#arUserName').val();
        accessPermissions.userId = $('#arUserId').val();
        var mapKey = accessPermissions.userId + '_' + (accessPermissions.accessorName).split(' ').join('_') + '_ul';
        arMISAccessMap.set(mapKey, accessPermissions);
    }
    var misReportPermissionsList = [];
//    for (var entry of arMISAccessMap.values()) {
    arMISAccessMap.forEach(function (entry, key, map) {
        misReportPermissionsList.push(entry);
    });
    var projects = $('#ar_projectList').multipleSelect('getSelects');
    projects = "|" + projects.join("|") + "|";

    var module = $('#arMIS_moduleList').multipleSelect('getSelects');
    module = module.join(",");
    var sites = $('#arMIS_siteList').multipleSelect('getSelects');
    if (sites.length <= 0) {
        sites = "|" + $("#siteId").val() + "|";
    } else {
        sites = "|" + sites.join("|") + "|";
    }
    /* forming user and roles array */
    /* get time period */
    if ($('#arMisTimePeriod').multipleSelect('getSelects').toString() != 'custom') {
        timePeriodVal = "between '" + $('#arMISFromTime').val() + "' and '" + $('#arMISToTime').val() + "'";
        timePeriodText = $('#arMisTimePeriod').multipleSelect('getSelects', 'text').toString();
    } else {
        timePeriodVal = "between '" + $('#arMISFromTime').val() + "' and '" + $('#arMISToTime').val() + "'";
        timePeriodText = $('#arMisTimePeriod').multipleSelect('getSelects').toString();
    }
    /* get time period */
    /* form the object */
    var formObject = {
        "reportName": $('#arMISTitle').val(),
        "description": $('#arMISDesc').val(),
        "inbuilt": "false",
        "module": module,
        "projectId": projects,
        "siteId": sites,
        "firstPageTitle": $('#arFirstPageTitle').val(),
        "editIntroAndSummary": enabledIntroSummary,
        "introduction": $('#arIntroduction').val(),
        "summary": $('#arSummary').val(),
        "createdBy": $('#arUserId').val(),
        /* "createdUser": $('#arUserName').val(), commented by Dheeraj for addind code to changed by created By and code added by Dheeraj for DREC15717 */
        "createdUser": arCreatedBy,

        "updatedBy": $('#arUserName').val(),
        "overrideTimePeriod": false, //enableOverrideTimePeriod
        "misTimeFilter": {"text": timePeriodText, "value": timePeriodVal},
        "selectedMisReportList": selectedReportIds,
        "includedReports": includedReportIdsForOverrideTimePeriod,
        "reportPermissionList": misReportPermissionsList,
        "misCustomReport": arGetUserSelectedFilters()
    };
    return formObject;
}


function arMISSave() {
    var authDetail=getAuthData(arTenantName);
    var module = $('#arMIS_moduleList').multipleSelect('getSelects');
    var site = $("#arMIS_siteList").multipleSelect("getSelects");
    var selectedReportList = [], inculdeReportsListForOverrideTimePeriod = [],
            selectedReportIds = "", includedReportIdsForOverrideTimePeriod = "";
    $('#arSelectedReports').children('li').each(function () {
        selectedReportList.push($(this).attr('id').replace("arDefaultReports_", ""));
        if (selectedReportIds == '') {
            selectedReportIds = $(this).data('value').id;
        } else {
            selectedReportIds += "|" + $(this).data('value').id;
        }
    });
    $('#arIncludeSelectedReports').children('li').each(function () {
        inculdeReportsListForOverrideTimePeriod.push($(this).attr('id').replace("arIncludeDefaultReports_", ""));
        if (includedReportIdsForOverrideTimePeriod == '') {
            includedReportIdsForOverrideTimePeriod = $(this).data('value').id;
        } else {
            includedReportIdsForOverrideTimePeriod += "|" + $(this).data('value').id;
        }
    });
    var isValidated = arMISFormValidation(selectedReportList, inculdeReportsListForOverrideTimePeriod, module, site);
    if (isValidated) {
        var formObject = formMISSaveUpdateJsonObject(selectedReportIds, includedReportIdsForOverrideTimePeriod,true);
        //  Ajax call to submit MIS data.
        $("#progressMsg").css("display", "block");
        $.ajax({
            url: "//" + arIpAddress + "/default-publish/publish/mis?platform=false&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
            type: "POST",
            contentType: 'application/json',
            crossDomain: true,
            data: JSON.stringify(formObject),
            headers:{
                'x-auth-key':authDetail[0],
                'x-auth-token':authDetail[1]
            },
            jsonp: true,
            success: function (data, textStatus, jqXHR) {
                arOnMISCreateModuleRedireation();
                arMISAccessMap.clear();
                setMISPublishSuccessMessage(data);
                arMISPublishSuccess('MIS');
            },
            error: function (errorMessage) {
                setMISPublishErrorMessage(errorMessage.responseText);
                console.log(' arMISSave : error : textStatus' + errorMessage.responseText);
            },
            complete: function (jqXHR, textStatus) {
                console.log(' arMISSave : complete : textStatus' + textStatus);
                $("#progressMsg").css("display", "none");
            }
        });
    }
}

/*
 * setting listing page module text and hidden variable value to last published module type.
 * @returns {undefined}
 */
function arOnMISCreateModuleRedireation() {
    var module = $('#arMIS_moduleList').multipleSelect('getSelects');
    var selectedModule = module[0];
    $('#arModule').val(selectedModule);// setting it for listing tab selection.
    arChangeModuleOnReportSubmit(selectedModule);
}

function arMISFormValidation(selectedReportList, inculdeReportsListForOverrideTimePeriod, module, site) {
    /* title validation */

    var commonReportsList = [], isValid = true;
    if ($('#arMISTitle').val() == '') {
        isValid = false;
        displayErrorMessage("#arMISTitle", "Please provide title");
        return false;
    } else if (arCheckSpecialChars($("#arMISTitle").val())) { // this function is ArCustomAddView.js
        isValid = false;
        displayErrorMessage('#arMISTitle', "Report name should not contain any special charecter.!");
        return false;
    } else if ($("#arMISTitle").val().length > 175) {
        isValid = false;
        displayErrorMessage('#arMISTitle', "Report name should not be more than 175 characters");
        return false;
    } else if (module.length <= 0) { //#arMIS_siteList
        isValid = false;
        displayErrorMessage('#arMIS_moduleList', "Please provide module");
        return false;
 //   } else if (module.length > 0 && module.indexOf("CMDB") != -1 && site.length <= 0) {
//        if( site.length <= 0 ){
        //isValid = false;
 

       // displayErrorMessage('#arMIS_siteList', "Please provide site");
 //       return false;
//        }
    } else if (selectedReportList.length == 0) {
        isValid = false;
        displayErrorMessage("#arDefaultReportsDiv", "Choose atleast one report");
        return false;
    } else if ($('#arMISOverrideTimePeriod').is(':checked')) {
        if ($('#arMisTimePeriod').multipleSelect('getSelects').toString() == '' ||
                $('#arMisTimePeriod').multipleSelect('getSelects').toString() == '-1') {
            isValid = false;
            displayErrorMessage("#arMisTimePeriod", "Please provide time period");
            return false;
        } else if ($('#arMisTimePeriod').multipleSelect('getSelects').toString() == 'custom') {
            if ($('#arMISFromTime').val() == '') {
                isValid = false;
                displayErrorMessage("#arMISFromTime", "Please provide From time");
                return false;
            } else if ($('#arMISToTime').val() == '') {
                isValid = false;
                displayErrorMessage("#arMISToTime", "Please provide To time");
                return false;
            } else {
                isValid = validateTimeFields($('#arMISFromTime').val(), $('#arMISToTime').val(), "arMISFromTime", "arMISToTime");
                if (isValid == false)
                    return false;
            }
        }
        if (inculdeReportsListForOverrideTimePeriod.length == 0) {
            isValid = false;
            displayErrorMessage("#arIncludeDefaultReportsDiv", "Choose atleast one report");
            return false;
        } else if (inculdeReportsListForOverrideTimePeriod.length > 0) {
            $.map(inculdeReportsListForOverrideTimePeriod, function (val, i) {
                if ($.inArray(val, selectedReportList) > -1) {
                    commonReportsList.push(val);
                } else {
                    isValid = false;
                    displayErrorMessage('#arIncludeDefaultReportsDiv', "Reports mismatch, Please choose the reports which have been choosen in Reports block");
                    return false;
                }
            });
        }
    } else if (!arOnSubmitFilterValidation()) {
        isValid = false;
        return false;
    }
    return isValid;
}

function displayErrorMessage(elementID, errMsg) {
    $(elementID).closest('.frm-field, .formElem').addClass('errField');
    $(".fldErr").remove();
    //$(elementID).focus();
    $(elementID).parents(".errField").focus();
    $(elementID).after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
    if ($('.errField').closest('.innerDetails')) {
        $('.errField').closest('.innerDetails').parent().children('.expForm').addClass("expand");
        $('.errField').closest('.innerDetails').closest('.filteredBlk').children(".expForm").children(".ico").removeClass("plusIco").addClass("closeIco");
        $('.errField').closest('.innerDetails').slideDown();
    }
    return;
}

function  setMISPublishSuccessMessage(message) {
    $('#arMISAddResult').append('<div class="sucessMsg"><i class="ico statusIco"></i><p>' + message + '</p></div>');
    $('#arMISAddResult').focus();
    $('body, html').animate({
        scrollTop: 0
    });
    setTimeout(function () {
        $('#arMISAddResult .sucessMsg').fadeOut('fast');

    }, 5000);
}

function setMISPublishErrorMessage(message) {
    $('#arMISAddResult').empty();
    $('#arMISAddResult').append('<div class="errMsg statusIco"></i><p>' + message + '</p></div>');
    $('#arMISAddResult').focus();
    $('body, html').animate({
        scrollTop: 0
    });
    setTimeout(function () {
        $('#arMISAddResult .errMsg').fadeOut('fast');
    }, 5000);
}

function clearMISPageElements() {
    $('#arMISTitle').val('');
    $('#arMISDesc').val('');
    $('#arEnableIntrSummary').prop("checked", false);
    $('#intrSummaDiv').css('display', 'none');
    $('#arFirstPageTitle').val('');
    $('#arIntroduction').val('');
    $('#arSummary').val('');
    $('#arSelectedReports').empty();
    $('#arMISFiltersDiv').empty();

    arMISAccessMap.clear();
    $('#arMISUserRolesDiv').empty();
    $('#arMISOverrideTimePeriod').prop("checked", false);
    $('#arMISAdvanceSettingDiv').css("display", "none");
    $('#arMisTimePeriod').multipleSelect("uncheckAll");
    $('#arMisTimePeriod').multipleSelect("refresh");
    $('#arIncludeSelectedReports').empty();

    $('#arMIS_moduleList').multipleSelect('uncheckAll');
    $('#arMIS_moduleList').multipleSelect('refresh');
    $("#arMISSiteDiv").css("display", "none");
    $('#arMIS_siteList').empty();

    $('#arMisTimePeriod').multipleSelect("refresh");
    $('#arMISFromTime').val('');
    $('#arMISToTime').val('');
    $('#arIncludeSelectedReports').empty();
//    $('#arMISFilters').css('display', 'none');

    $('#arMISAddViewDiv .filter-block .filteredBlk .expForm').removeClass("expand");
    $('#arMISAddViewDiv .filter-block .filteredBlk .expForm .ico').removeClass("closeIco").addClass("plusIco");
    $('#arMISAddViewDiv .innerDetails').slideUp();
    misReportList = "";

}

function renderOverrideTimePeriodView() {
    var authDetail=getAuthData(arTenantName);
    $("#arMisTimePeriod").empty();
    var query = "select Query,Templete from time_table  where Type=0";
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        url: "//" + arIpAddress + "/default-publish/doc/getfiltervalue?tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
        data: query,
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        crossDomain: true,
        async: false,
        jsonp: true,
        success: function (data) {
            $.each(data, function (i, item) {
                var option = $("<option>", {text: item.text, value: item.value, id: (item.text).split(' ').join('_')});
                $("#arMisTimePeriod").append(option);
            });
            var custom = $("<option>", {text: 'custom', value: 'custom', id: 'custom'});
            $("#arMisTimePeriod").append(custom);
            $("#arMisTimePeriod").multipleSelect('refresh');
            $("#arMisTimePeriod").multipleSelect('uncheckAll');
        },
        error: function (e) {
            $("#progressMsg").css("display", "none");
        },
        complete: function () {
            $("#progressMsg").css("display", "none");
        }
    });
}

/* EDIT view starts */
function showEditView(viewData, editMetaData) {
    $('#arMISTitle').val(editMetaData.reportName);
    $('#arMISDesc').val(editMetaData.description);
    $('#arFirstPageTitle').val(editMetaData.firstPageTitle);
    //checkBox.
    if (editMetaData.editIntroAndSummary) {
        $('#arEnableIntrSummary').prop("checked", true);
        $('#intrSummaDiv').css('display', '');
        $('#arIntroduction').val(editMetaData.introduction);
        $('#arSummary').val(editMetaData.summary);
    } else {
        $('#arEnableIntrSummary').prop("checked", false);
        $('#intrSummaDiv').css('display', 'none');
    }
    // add role and user data to map arMISAccessMap
    setEditRoleUserView(editMetaData.reportPermissionList);
    // form override report list for edit
    if (editMetaData.overrideTimePeriod) {
        $('#arMISOverrideTimePeriod').prop("checked", true);
        $('#arMISAdvanceSettingDiv').css("display", "");
        if (editMetaData.misTimeFilter.text == 'Publish custom') {
            var id = (editMetaData.misTimeFilter.text).split(' ').join("_");
            $('#' + id).attr('selected', true);
            var value = editMetaData.misTimeFilter.value;
            var fromToTime = value.substring(8, value.length).split("and");
            $('#arMISFromTime').val(fromToTime[0].trim().replace(/'/g, ""));
            $('#arMISToTime').val(fromToTime[1].trim().replace(/'/g, ""));

        } else
        if (editMetaData.misTimeFilter.text != 'custom') {
            var id = (editMetaData.misTimeFilter.text).split(' ').join("_");
            $('#' + id).attr('selected', true);
        } else if (editMetaData.misTimeFilter.text == 'custom') {
            $('#custom').attr('selected', true);
            var value = editMetaData.misTimeFilter.value;
            var fromToTime = value.substring(8, value.length).split("and");
            $('#arMISFromTime').val(fromToTime[0].trim().replace(/'/g, ""));
            $('#arMISToTime').val(fromToTime[1].trim().replace(/'/g, ""));
            $('#arMISFromTime').removeAttr("disabled");
            $('#arMISToTime').removeAttr("disabled");
        }
        $('#arMisTimePeriod').multipleSelect('refresh');
        arGetReportsBasedOnProjectList(true, editMetaData);
    } else {
        $('#arMISAdvanceSettingDiv').css("display", "none");
        $('#arMISOverrideTimePeriod').prop("checked", false);
    }
//    arMisRenderEditFilters(editMetaData);
    // Change button.    
    var buttonView = $('<input type="button" id="arReportSaveBtn" onclick="arMISUpdate(\'' + editMetaData.id + '\');" value="Update" class="btn apply updateBtn"><a href="javascript:void(0)" class="btn cancel" onclick="arMISCancel();">Cancel</a>');
    $('#arMISSubmitDiv').empty();
    $('#arMISSubmitDiv').append(buttonView);
}

function arMisRenderEditFilters(editMetaData) {
    filterMap.clear();
    existingFilter.clear();
    arPopulateMISFilters();//first populate all filters.
    var customReports = editMetaData.misCustomReport;
    $.each(customReports, function (i, report) {
        var reportLabel = arReplaceSpacewithUscr(report.reportLabel);
        var filters = report.filters;

        $.each(filters, function (i, filter) {
            var optIds = [];
            var filterElementId = arCustomFieldIdCreator(reportLabel, filter);
            var filterVals = filter.filterValues;
            $.each(filterVals, function (i, val) {

                if (val.text == 'Custom') {
                    var value = {value: "custom", text: "Custom"};
                    var optId = arMisFilterValueIdCreator(value, filter);
                    optIds.push(optId);
                    arSetTimeFilterValues(val.value, filterElementId, filterElementId);
                } else if (val.text == 'Publish custom') {

                    var value = val.value;
                    var fromToTime = value.substring(8, value.length).split("and");
                    $('#filterFrom' + filterElementId).val(fromToTime[0].trim().replace(/'/g, ""));
                    $('#filterTo' + filterElementId).val(fromToTime[1].trim().replace(/'/g, ""));
                    $('#filterFrom' + filterElementId).attr("disabled", true);
                    $('#filterTo' + filterElementId).attr("disabled", true);
                    var optId = arMisFilterValueIdCreator(val, filter);
                    optIds.push(optId);
                } else {
                    var optId = arMisFilterValueIdCreator(val, filter);
                    optIds.push(optId);
                }
            });
           
              $.each(optIds, function (index, value) {
                    $('#filter' + filterElementId+' option[value='+value+']').attr("selected","selected");
              });
            $('#filter' + filterElementId).val(optIds);
            $('#filter' + filterElementId).multipleSelect("refresh");
            $('#filter' + filterElementId).val(optIds);
        });
    });
}

function arSetTimeFilterValues(selectedVal, fromDiv, toDiv) {
    selectedVal = (selectedVal).split(' ');
    for (var i = 0; i < selectedVal.length; i++) {
        var fromTime = (selectedVal[1] + " " + selectedVal[2]).replaceAll(/'/, "");
        var toTime = (selectedVal[4] + " " + selectedVal[5]).replaceAll(/'/, "");
        $('#filterFrom' + fromDiv).val(fromTime);
        $('#filterTo' + toDiv).val(toTime);
        $('#filterFrom' + fromDiv).removeAttr("disabled");
        $('#filterTo' + toDiv).removeAttr("disabled");
    }
}

function setEditRoleUserView(permissionList) {
    $.each(permissionList, function (i, item) {
        var mapKey = "";
        (item.accessType == 'user') ? mapKey = item.userId + '_' + (item.accessorName).split(' ').join('_') + '_ul' : mapKey = item.roleId + '_' + (item.accessorName).split(' ').join('_') + '_ul'
        arMISAccessMap.set(mapKey, item);
    });
    arSetMISPermissionsDiv();
}

function arMISUpdate(docId) {
     $("#misUserMsg.errMsg").remove();
    var authDetail=getAuthData(arTenantName);
    if ($('#arEnableIntrSummary').prop("checked") != true) {
        $('#arIntroduction').val('');
        $('#arSummary').val('');

    }
    var module = $('#arMIS_moduleList').multipleSelect('getSelects');
    var site = $("#arMIS_siteList").multipleSelect("getSelects");

    var selectedReportList = [], inculdeReportsListForOverrideTimePeriod = [],
            selectedReportIds = "", includedReportIdsForOverrideTimePeriod = "";
    $('#arSelectedReports').children('li').each(function () {
        selectedReportList.push($(this).attr('id').replace("arDefaultReports_", ""));
        if (selectedReportIds == '') {
            selectedReportIds = $(this).data('value').id;
        } else {
            selectedReportIds += "|" + $(this).data('value').id;
        }
    });
    if ($('#arMISOverrideTimePeriod').prop("checked") == true)
    {
        $('#arIncludeSelectedReports').children('li').each(function () {
            inculdeReportsListForOverrideTimePeriod.push($(this).attr('id').replace("arIncludeDefaultReports_", ""));
            if (includedReportIdsForOverrideTimePeriod == '') {
                includedReportIdsForOverrideTimePeriod = $(this).data('value').id;
            } else {
                includedReportIdsForOverrideTimePeriod += "|" + $(this).data('value').id;
            }
        });
    }
    var isValidated = arMISFormValidation(selectedReportList, inculdeReportsListForOverrideTimePeriod, module, site);

    if (isValidated) {
        var formObject = formMISSaveUpdateJsonObject(selectedReportIds, includedReportIdsForOverrideTimePeriod,false);
        formObject.id = docId;
        //  Ajax call to submit MIS data.
        $.ajax({
            url: "//" + arIpAddress + "/default-publish/publish/updatemis?platform=false&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
            type: "POST",
            contentType: 'application/json',
            crossDomain: true,
            data: JSON.stringify(formObject),
            headers:{
                'x-auth-key':authDetail[0],
                'x-auth-token':authDetail[1]
            },
            jsonp: true,
            success: function (data, textStatus, jqXHR) {
                arMISAccessMap.clear();
                setMISPublishSuccessMessage(data);
            },
            error: function (errorMessage) {
                setMISPublishErrorMessage(errorMessage.responseText);
                console.log(' arMISUpdate : error : textStatus' + errorMessage.responseText);
            },
            complete: function (jqXHR, textStatus) {
                console.log(' arMISUpdate : complete : textStatus' + textStatus);
                arMISPublishSuccess('MIS');
            }
        });
    }

}
/* EDIT view ends */

function showMISCustomFromTo() {
    var selectedTimePeriod = $('#arMisTimePeriod').multipleSelect('getSelects').toString();
    $('#arMISFromTime').val('');
    $('#arMISToTime').val('');
    if (selectedTimePeriod === 'custom') {
        $('#arMISFromTime').removeAttr("disabled");
        $('#arMISToTime').removeAttr("disabled");
    } else {
        $('#arMISFromTime').attr("disabled", "disabled");
        $('#arMISToTime').attr("disabled", "disabled");
    }
}

/*Poppulate project starts*/
function populateMISARPojectList(isEditView, projectId, editData) {
    var authDetail=getAuthData(arTenantName);
    $.ajax({
        url: "//" + arIpAddress + "/default-repository/sdproject?userId=" + $('#arUserId').val() + "&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
        type: "GET",
        contentType: 'application/json',
        dataType: 'json',
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        crossDomain: true,
        async: false,
        success: function (data, textStatus, jqXHR) {
            populatePojectsListForMIS(data, projectId);
            if (isEditView == false) {
                setMISInitProjectList(projectId, isEditView);
            } else {
                setMISProjectListForEditView(isEditView, editData);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $("#progressMsg").css("display", "none");
        },
        complete: function (jqXHR, textStatus) {
            $("#progressMsg").css("display", "none");
        }
    });
}

function populatePojectsListForMIS(projectsList) {
    $('#ar_projectList').empty();
    var select = document.getElementById("ar_projectList");
    $.each(projectsList, function (i, option) {
        var $option = $("<option>", {text: option.projectName, value: option.projectID, id: option.projectID + "_" + option.projectName, name: option.projectName});
        $option.appendTo(select);
    });
    $('#ar_projectList').multipleSelect('refresh');
    $("#ar_projectList").multipleSelect("uncheckAll");
}
/*Poppulate project ends*/

//populate projects on add view
function setMISInitProjectList(projectId, isEditView) {
    var reports = $('#ar_projectList').find('option');
    $.each(reports, function (i, option) {
        if (option.value == projectId) {
            var doc = document.getElementById(option.id);
            doc.selected = true;



        }
    });
    $('#ar_projectList').multipleSelect('refresh');
}

//populate projects-->for edit view
function setMISProjectListForEditView(isEditView, editData) {
    var editProjectArray = editData.projectId.split(/\|/);
    for (var j = 0; j < editProjectArray.length; j++) {
        var reports = $('#ar_projectList').find('option');
        $.each(reports, function (i, option) {
            if (option.value == editProjectArray[j]) {
                var doc = document.getElementById(option.id);
                doc.selected = true;
            }
        });
    }
    $('#ar_projectList').multipleSelect('refresh');
}

function validateModuleProjectAndSiteList(moduleList, siteList, projectList) {
    var isValid = true;
    if (moduleList.length <= 0) {
        isValid = false;
        $("#arMISSiteDiv").css("display", "none");
        $("#arMIS_siteList").multipleSelect("uncheckAll");
        displayErrorMessage("#arMIS_moduleList", "Please provide module");
		$('#arDefaultReports').empty();
    } else if (moduleList.length > 0) {
        if (moduleList.indexOf("CMDB") != -1) {
            $("#arMISSiteDiv").css("display", "");
            //if (siteList.length == 0) {
          //      isValid = false;
          //      displayErrorMessage("#arMIS_siteList", "Please provide site");
          //  }
        } else {
            $("#arMISSiteDiv").css("display", "none");
           // $("#arMIS_siteList").multipleSelect("uncheckAll"); // commented By Dheeraj Mishra for selecting  SiteId by Default
        }
    } else if (projectList.length <= 0) {
        isValid = false;
        displayErrorMessage("#ar_projectList", "Please provide project");
    }
    return isValid;
}

var arMISReportData = "";
function arGetReportsBasedOnProjectList(editMode, editData) {
    var authDetail=getAuthData(arTenantName);
    arMISReportData = "";
//    $("#progressMsg").css("display", "block");    
    var moduleList = "", siteList = "", projectList = "";
    moduleList = $('#arMIS_moduleList').multipleSelect('getSelects');
    siteList = $("#arMIS_siteList").multipleSelect("getSelects");
    projectList = $('#ar_projectList').multipleSelect('getSelects');
    getRolesUserList(moduleList.toString(),'mis');
    var doAjaxCall = validateModuleProjectAndSiteList(moduleList, siteList, projectList);

    if (doAjaxCall) {
        if (siteList.length <= 0) {
            siteList = $("#siteId").val();
        }
        var URL = "//" + arIpAddress + "/default-publish/publish/reports?id=" + projectList + "&inbuilt=false&userId=" + $('#arUserId').val() + "&module=" + moduleList + "&siteId=" + siteList + "&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1];
        clearDivElements();
        $("#progressMsg").css("display", "block");
        $.ajax({
            url: URL,
            type: "GET",
            async: false,
            contentType: 'application/json',
            headers:{
                'x-auth-key':authDetail[0],
                'x-auth-token':authDetail[1]
            },
            dataType: 'json',
            crossDomain: true,
            success: function (data, textStatus, jqXHR) {
                arMISReportData = data;
                $("#progressMsg").css("display", "none");
                if (editMode == false) {
                    formReportListView(data, 'arDefaultReportsDiv', 'arDefaultReports', 'arSelectedReports', false);
                    if ($('#arMISOverrideTimePeriod').is(':checked')) {
                        formReportListView(data, 'arIncludeDefaultReportsDiv', 'arIncludeDefaultReports', 'arIncludeSelectedReports', false);
                    }
                } else {
                    var size=formReportListViewForEdit(data, editData, 'arDefaultReportsDiv', 'arDefaultReports', 'arSelectedReports');
                 
                    if(size==0){
                       editLength=0;
                    }
                    else{
                        editLength=null;
                    }
                    if ($('#arMISOverrideTimePeriod').is(':checked')) {
                        formReportListViewForEdit(data, editData, 'arIncludeDefaultReportsDiv', 'arIncludeDefaultReports', 'arIncludeSelectedReports');
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $("#progressMsg").css("display", "none");
            },
            complete: function (jqXHR, textStatus) {
                $("#progressMsg").css("display", "none");
            }
        });
    }
}
function clearDivElements() {
    $('#arSelectedReports').empty();
    $('#arIncludeSelectedReports').empty();
    $('#arDefaultReports').empty();
    $('#arIncludeDefaultReportsDiv').empty();
}
function Expand(expandid, elementid, errmsg) {
    $(expandid).closest('.frm-field, .formElem').addClass('expandField');
    $(".fldErr").remove();
    $(elementid).after('<p class="fldErr"><span class="topCurve"></span>' + errmsg + '</p>');
    if ($('.expandField').closest('.innerDetails')) {
        $('.expandField').closest('.innerDetails').parent().children('.expForm').addClass("expand");
        $('.expandField').closest('.innerDetails').closest('.filteredBlk').children(".expForm").children(".ico").removeClass("plusIco").addClass("closeIco");
        $('.expandField').closest('.innerDetails').slideDown();
    }
    return;
}
function arGetReportsForOverrideTimePeriod(arMISReportData) {
    formReportListView(arMISReportData, 'arIncludeDefaultReportsDiv', 'arIncludeDefaultReports', 'arIncludeSelectedReports');
}
$(document).on("keyup", '#arDefaultReportsDiv_Search', function (e) {
    var KeyUpVal = $(e.target)[0].value;
    arFieldSearchMIS(KeyUpVal, "#arDefaultReportsDiv");
});
$(document).on("keyup", '#arIncludeDefaultReportsDiv_Search', function (e) {
    var KeyUpVal = $(e.target)[0].value;
    arFieldSearchMIS(KeyUpVal, "#arIncludeDefaultReportsDiv");
});
function arFieldSearchMIS(search, elemantId)
{
    $(elemantId).find('ul li').each(function () {
        var val = $(this).data('value').reportName;
        if ((val.toLowerCase()).indexOf(search.toLowerCase()) >= 0)
            $(this).addClass("found");
        if ($(this).hasClass("found") === true)
        {
            $(this).show();
            $(this).removeClass("found");
        } else
        {
            $(this).hide();
            // $(this).append("li"). text("Not Found");
        }
        $(".incustFlds").scrollTop(0);
    });
}

function onSelectionOfModule() {
    var module = $("#arMIS_moduleList").multipleSelect("getSelects");
    var selectedSiteIds = [];
    if (module.indexOf("CMDB") != -1) {
        $("#arMISSiteDiv").css("display", "");
        selectedSiteIds = $("#arMIS_siteList").multipleSelect("getSelects");
        //return;
    } else {
        $("#arMISSiteDiv").css("display", "none");
    }
    if (module.lenght != 0) {
        if (module.indexOf("CMDB") == -1) {
            arGetReportsBasedOnProjectList(false, "");
        } else if (module.indexOf("CMDB") != -1 && selectedSiteIds.lenght != 0) {
            arGetReportsBasedOnProjectList(false, "");
        }
    }
}

function populateMISARSiteList(isEditView, siteId, editData) {
    /*$("#progressMsg").css("display", "block");
     $.ajax({
     url: "//" + arIpAddress + "/default-repository/site?status=1&tenant_id=" + arTenantName,
     type: "GET",
     contentType: 'application/json',
     dataType: 'json',
     crossDomain: true,
     async: false,
     success: function (data, textStatus, jqXHR) {
     $('#arMIS_siteList').empty();
     var siteSelect = $("#arMIS_siteList");
     $.each(data, function (i, option) {
     var $option = $("<option>", {text: option.siteName, value: option.siteId, id: option.siteId + "_" + option.siteName, name: option.siteName});
     $option.appendTo(siteSelect);
     });
     $("#arMIS_siteList").multipleSelect("uncheckAll");
     $('#arMIS_siteList').multipleSelect('refresh');
     if (isEditView) {
     
     checkMultiSelectionSiteId(editData);
     }
     },
     error: function (jqXHR, textStatus, errorThrown) {
     $("#progressMsg").css("display", "none");
     },
     complete: function (jqXHR, textStatus) {
     $("#progressMsg").css("display", "none");
     }
     });*/
}

function checkMultiSelectionSiteId(editData) {
    var siteIdArray = editData.siteId.split(/\|/);
    for (var j = 0; j < siteIdArray.length; j++) {
        var options = $('#arMIS_siteList').find('option');
        $.each(options, function (i, option) {
            if (option.value == siteIdArray[j]) {
                var doc = document.getElementById(option.id);
                doc.selected = true;
            }
        });
    }
    $('#arMIS_siteList').multipleSelect('refresh');
}
function getFiltersForMIS() {
    var childElementsLength = $('#arSelectedReports').children('li').length;
//    console.log('total zizize :: ' + childElementsLength);
    if (childElementsLength > 0) {
        $('#arMISFilters').css('display', '');
        $('#arSelectedReports').children('li').each(function () {
            var reportId = $(this).data('value').id;
            var template = $(this).data('value').template;
            var projectId = $(this).data('value').projectId;
            var reportName = $(this).data('value').reportName;
            var assetModuleId = $(this).data('value').assetModuleId;
            formAndRenderDynamicFilters(reportId, template, 'arMISFiltersDiv', '', '', projectId, reportName,assetModuleId);
        });
    } else {
        $('#arMISFiltersDiv').empty();
        $('#arMISFilters').css('display', 'none');
    }
}
 
function formDynamicFiltersForMis(docId) {
    authDetail=getAuthData(arTenantName);
    var filters = null;
    $("#progressMsg").css("display", "block");
    $.ajax({
        url: '//' + arIpAddress + '/default-publish/publish/filters?reportId=' + docId + "&tenant_id=" + arTenantName + "&authKey="+authDetail[0]+ "&authToken="+authDetail[1]+"&userId=" +$('#arUserId').val(),
        type: 'GET',
        crossDomain: true,
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        contentType: 'application/json',
        async: false,
        success: function (data, textStatus, jqXHR) {
            $("#progressMsg").css("display", "none");
            filters = data;
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(" formDynamicFiltersForMis :: ERROR : " + textStatus);
            $("#progressMsg").css("display", "none");
            setReportCreateError("Failed to load Report, please contact Administrator.!");
        }
    });
    
    return filters;
}
 
// code added by  Dheeraj  mishra on May 28th'20 for derc may 28th'20 for derc 7th point.
function arPopulateMISFiltersForRemovingReport() {
    var filterDiv = "arMISFiltersDiv";
    var map1 = new Map();
    var map2 = new Map();
    $('#' + filterDiv).children('div').children('div').children().each(function () {
        var parentObj = $.extend(true, {}, $(this).data('value'));// clone //$(this).data('value');
        var reportLabel1 = arReplaceSpacewithUscr(parentObj.reportLabel);
        if (reportLabel1 !== null) {
            map1.set(reportLabel1, reportLabel1);
        }
    });
    $('#arSelectedReports').children('li').each(function () {
        deleteDiv = $.extend(true, {}, $(this).data('value'));
        var repLable = arReplaceSpacewithUscr(deleteDiv.reportLabel);
        if (repLable !== null) {
            map2.set(repLable, repLable);
        }
    });
    map1.forEach(function (entry2, key1, map1) {


        if (!map2.get(entry2)) {

            $("#" + entry2).remove();
        }
    });
}

 function arPopulateMISFilters(variable) {
    var filterDiv = "arMISFiltersDiv";
      // var filterDiv = "arMISFiltersDiv";
 /* code added by dheeraj May 28th'20 for DREC15497 7th point*/
    /*var reportsMap1 = new Map();
    $('#' + filterDiv).children('div').children('div').children().each(function () {
        var parentObj = $.extend(true, {}, $(this).data('value'));// clone //$(this).data('value');
        var reportLabel1 = arReplaceSpacewithUscr(parentObj.reportLabel);
        if (reportLabel1 != null) {
            reportsMap1.set(reportLabel1, reportLabel1);
        }
    });*/

    // $("#arMISFiltersDiv").empty();   /*commented By Dheeraj May 28th'20 for DREC15497 7th point */								
     //$("#arMISFiltersDiv").empty();
    if(variable === "add" || variable === undefined){
    $('#arSelectedReports').children('li').each(function () {
        var report = $.extend(true, {}, $(this).data('value'));// clone
        if(!filterMap.has(report.reportName)){
        if (report !== null) {
            var data = formDynamicFiltersForMis(report.id);
            var reportName = report.reportName;
            var reportLabel = arReplaceSpacewithUscr(report.reportLabel);

            if (data.length <= 0)
                reportName = reportName + " ( Filter(s) not found...! )";
            var parentDiv = $('<div id="' + reportLabel + '" style="width: 100%;float: right;"><label class="arChartLabel">' + reportName + '</label></div>');
            $('#' + filterDiv).append(parentDiv);
            if (data != null && data.length > 0) {
                $.each(data, function (i, item) {
                    var filterElementId = arCustomFieldIdCreator(reportLabel, item);
                    var isMandatory = (item.mandatory === "mandatory") ? "<span><font color='red'>*</font></span>" : "";
                    if (item.visibilityType == "visible" && item.htmlType == "timeScale") {
                        var optionData = item.filterValues;
                        var newDiv = $('<div id="arTimeDiv" style="width: 100%;float: right;"></div>');
                        item.filterValues = "";
						for(var outerFilterIndex = 0; outerFilterIndex < data.length; outerFilterIndex++) {
                            var tempFilterValues = data[outerFilterIndex].filterValues;
                            for(var innerFilterValueIndex = 0; innerFilterValueIndex < tempFilterValues.length; innerFilterValueIndex++) {
                                tempFilterValues[innerFilterValueIndex].value = tempFilterValues[innerFilterValueIndex].value.replaceAll("'", "");
                            }
                            data[outerFilterIndex].filterValues = tempFilterValues;
                        }
                       var divView = $("<div></div>")
								.addClass("formElem")
								.attr("data-value", JSON.stringify(report));

							var label = $("<label></label>")
								.attr("for", "filter" + filterElementId)
								.attr("title", item.columnDisplayName)
								.html(item.columnDisplayName + isMandatory);

							divView.append(label);
                        var selectView = $("<select id='filter" + filterElementId + "' name='filter" + filterElementId + "' class='demo' onChange=\"arMisDisableCustomCalender('filter" + filterElementId + "','filterFrom" + filterElementId + "','filterTo" + filterElementId + "');\" data-value='" + JSON.stringify(item) + "'></select>");
                        $("<option />", {value: "-1", text: "-- choose --"}).appendTo(selectView);
                        $.each(optionData, function (index, value) {
                            var optId = arMisFilterValueIdCreator(value, item);
                            $("<option />", {id: optId, value: optId, text: value.text, 'data-value': value.value}).appendTo(selectView);
                        });
                        var value = {value: "custom", text: "Custom"};
                        var optId = arMisFilterValueIdCreator(value, item);
                        $("<option />", {id: optId, value: optId, text: value.text, 'data-value': value.value}).appendTo(selectView);
                        selectView.appendTo(divView);
                        var scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').multipleSelect({ filter:true, single:true});</script>");
                        scriptData.appendTo(divView);
                        var fromDivView = $("<div class='formElem'><label>From</label><input type='text' id='filterFrom" + filterElementId + "' name='filterFrom" + filterElementId + "' size='20' value='' disabled='disabled' /></div>");
                        var formScriptData = $("<script type='text/javascript'>$('#filterFrom" + filterElementId + "').datetimepicker({step: 15, format: 'Y-m-d H:i',defaultTime:'00:00'});</script>");
                        formScriptData.appendTo(fromDivView);
                        var toDivView = $("<div class='formElem'><label>To</label><input type='text' id='filterTo" + filterElementId + "' name='filterTo" + filterElementId + "' size='20' value='' disabled='disabled' /></div>");
                        var toScriptData = $("<script type='text/javascript'>$('#filterTo" + filterElementId + "').datetimepicker({step: 15, format: 'Y-m-d H:i',defaultTime:'23:59'});</script>");
                        toScriptData.appendTo(toDivView);
                        newDiv.append(divView).append(fromDivView).append(toDivView);
                        $(parentDiv).append(newDiv);
                        if ("filter" + filterDiv + "-101" == ('filter' + filterElementId)) {
                            $('#arTimeDiv').css("display", "none");
                        }
                    } else if (item.visibilityType == "visible" && item.htmlType == "simple") {
                        var optionData = item.filterValues;
                        var newDiv1 = $('<div id="arSimpleDiv" style="width: 33.33%;float: left;"></div>')
                        item.filterValues = "";
						for(var outerFilterIndex = 0; outerFilterIndex < data.length; outerFilterIndex++) {
                            var tempFilterValues = data[outerFilterIndex].filterValues;
                            for(var innerFilterValueIndex = 0; innerFilterValueIndex < tempFilterValues.length; innerFilterValueIndex++) {
                                tempFilterValues[innerFilterValueIndex].value = tempFilterValues[innerFilterValueIndex].value.replaceAll("'", "");
                            }
                            data[outerFilterIndex].filterValues = tempFilterValues;
                        }
                        var columnValue = item.columnDisplayName;
                        if(item.columnDisplayNameWithFieldId!==null && item.columnDisplayNameWithFieldId!==""){
                            columnValue = item.columnDisplayNameWithFieldId;
                        }
                        var divView = $("<div class='formElem' data-value='" + JSON.stringify(report) + "'><label for='filter" + filterElementId + "' title='" + columnValue + "'>" + columnValue + isMandatory + "</label></div>");
                        var selectView = "";
                        if (item.columnName === 'arListBy') {
                            selectView = $("<select id='filter" + filterElementId + "' name='filter" + filterElementId + "' class='demo' data-value='" + JSON.stringify(item) + "' onChange=\"showOnlyCustom(this.value,'" + filterDiv + "');\"></select>");
                        } else {
                            selectView = $("<select id='filter" + filterElementId + "' name='filter" + filterElementId + "' class='demo' data-value='" + JSON.stringify(item) + "' multiple='multiple'></select>");
                        }
                        //  var selectView = $("<select id='filter" + filterElementId + "' name='filter" + filterElementId + "' class='demo' data-value='" + JSON.stringify(item) + "' multiple='multiple'></select>");
                        $("<option />", {value: "-1", text: "-- choose --"}).appendTo(selectView);
                        $.each(optionData, function (index, value) {
                            var optId = arMisFilterValueIdCreator(value, item);
                            $("<option />", {id: optId, value: optId, text: value.text, 'data-value': value.value}).appendTo(selectView);




 

                        });
                        selectView.appendTo(divView);
//                        var scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').multipleSelect({filter: true,single:true,selectAll: false});</script>");
//                        scriptData.appendTo(divView);
                        if (item.filterType == "dynamic") {
                            scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').addClass('dynamic');$('#filter" + filterElementId + "').multipleSelect({filter: true,single:true,selectAll: true,onOpen: function () {arMisFilterValuesonOpen('filter" + filterElementId + "');},onClick:function(){var selectedVal=$('#filter" + filterElementId + "').multipleSelect('getSelects');var selectedIds=[];$.each(selectedVal, function(index, value) {selectedIds[index]=$('#filter" + filterElementId + " option[data-value='+value+']').attr('id');$('#filter" + filterElementId + " option[data-value='+value+']').attr('selected','selected');});$('#filter" + filterElementId + " ').val(selectedIds)}});</script>");
                            scriptData.appendTo(divView);
                            var hiddenSearchEl = $("<input type='hidden' id='filter" + filterElementId + "_st' name='filter" + filterElementId + "_st' value=''/>");
                            hiddenSearchEl.appendTo(divView);
                        } else {
                            var scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').multipleSelect({filter: true,single:true,selectAll: false,onClick:function(){var selectedVal=$('#filter" + filterElementId + "').multipleSelect('getSelects');var selectedIds=[];$.each(selectedVal, function(index, value) {selectedIds[index]=$('#filter" + filterElementId + " option[data-value='+value+']').attr('id');$('#filter" + filterElementId + " option[data-value='+value+']').attr('selected','selected');});$('#filter" + filterElementId + " ').val(selectedIds)}});</script>");
                            scriptData.appendTo(divView);
                        }
                        newDiv1.append(divView).append(fromDivView).append(toDivView);
                        $(parentDiv).append(newDiv1);
                    } else if (item.visibilityType == "visible" && item.htmlType.indexOf("multi") != -1) {
                        var optionData = item.filterValues;
                        var newDiv2 = $('<div id="arMultiDiv" style="width: 33.33%;float: left;"></div>')
                        item.filterValues = "";
						for(var outerFilterIndex = 0; outerFilterIndex < data.length; outerFilterIndex++) {
                            var tempFilterValues = data[outerFilterIndex].filterValues;
                            for(var innerFilterValueIndex = 0; innerFilterValueIndex < tempFilterValues.length; innerFilterValueIndex++) {
                                tempFilterValues[innerFilterValueIndex].value = tempFilterValues[innerFilterValueIndex].value.replaceAll("'", "");
                            }
                            data[outerFilterIndex].filterValues = tempFilterValues;
                        }
                        var divView = $("<div class='formElem' data-value='" + JSON.stringify(report) + "'><label for='filter" + filterElementId + "' title='" + item.columnDisplayName + "'>" + item.columnDisplayName + isMandatory + "</label></div>");
                        var selectView = $("<select id='filter" + filterElementId + "' name='filter" + filterElementId + "' class='demo'  multiple='multiple' size='4' data-value='" + JSON.stringify(item) + "'></select>");
                        $.each(optionData, function (index, value) {
                            var optId = arMisFilterValueIdCreator(value, item);
                            $("<option />", {id: optId, value: optId, text: value.text, 'data-value': value.value}).appendTo(selectView);
                        });
                        selectView.appendTo(divView);
//                        var scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').multipleSelect({filter: true,multiple:true,selectAll: true});</script>");
//                        scriptData.appendTo(divView);
                        if (item.filterType == "dynamic") {
                            scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').addClass('dynamic');$('#filter" + filterElementId + "').multipleSelect({filter: true,selectAll: true,onOpen: function () {arMisFilterValuesonOpen('filter" + filterElementId + "');},onClick:function(){debugger;var selectedVal=$('#filter" + filterElementId + "').multipleSelect('getSelects');var selectedIds=[];$.each(selectedVal, function(index, value) {selectedIds[index]=$('#filter" + filterElementId + " option[data-value='+value+']').attr('id');$('#filter" + filterElementId + " option[data-value='+value+']').attr('selected','selected');});$('#filter" + filterElementId + " ').val(selectedIds)}});</script>");
                            scriptData.appendTo(divView);
                            var hiddenSearchEl = $("<input type='hidden' id='filter" + filterElementId + "_st' name='filter" + filterElementId + "_st' value=''/>");
                            hiddenSearchEl.appendTo(divView);
                        } else {
                            var scriptData = $("<script type='text/javascript'>$('#filter" + filterElementId + "').multipleSelect({filter: true,selectAll: true,onClick:function(){debugger;var selectedVal=$('#filter" + filterElementId + "').multipleSelect('getSelects');var selectedIds=[];$.each(selectedVal, function(index, value) {selectedIds[index]=$('#filter" + filterElementId + " option[data-value='+value+']').attr('id');$('#filter" + filterElementId + " option[data-value='+value+']').attr('selected','selected');});$('#filter" + filterElementId + " ').val(selectedIds)}});"+
							"$('#filter" + filterElementId + "').on('change', function() {" +
								"if ($('#filter" + filterElementId + " + .ms-parent .ms-select-all').hasClass('selected') == false) {" +
								"$('#filter" + filterElementId + " option').prop('selected',true);" +
								"}" +
							  "});"
							+"</script>");
                            scriptData.appendTo(divView);

 

                        }
                        newDiv2.append(divView).append(fromDivView).append(toDivView);
                        $(parentDiv).append(newDiv2);
                    }
                });
            }
            }
            filterMap.set(report.reportName);
            existingFilter.set(reportLabel);
        }
        });
    }
    else{
        //var newFilter = new Map(existingFilter);
		var newFilter = new Map();
        existingFilter.forEach(function(value, key) {
              newFilter.set(key,value);
        });
        console.log(newFilter);
        filterMap.clear();
        existingFilter.clear();
        $('#arSelectedReports').children('li').each(function () {
        var report = $.extend(true, {}, $(this).data('value'));// clone
           filterMap.set(report.reportName);
           existingFilter.set(arReplaceSpacewithUscr(report.reportLabel));
        });
        //newFilter.forEach( (value, key, map) => {
           // if(!(existingFilter.has(`${key}`))){
                //$("#arMISFiltersDiv").children('#' + `${key}`).remove();
            //}
        //});
		newFilter.forEach(function(value, key) {
            if(!(existingFilter.has(key))){
                $("#arMISFiltersDiv").children('#' + key).remove();
            }
        });
    }
}

$(document).on("click","#AddMISReport",function(){
    $("#arMISFiltersDiv").empty();
    filterMap.clear();
    existingFilter.clear();
});
function arMisDisableCustomCalender(elementId, fromDiv, toDiv) {

debugger;
	var getSelected =$("#" + elementId).multipleSelect("getSelects");
	getSelected=getSelected.toString();
	$("#" + elementId+" option").removeAttr("selected");
	$("#" + elementId + " option[data-value=\""+ getSelected +"\"]").attr("selected", "selected");
    var selTimeScale = $("#" + $("#" + elementId).find("option[selected]").val()).data('value');
	var id = $("#" + elementId).find("option[selected]").val();
    if(id === "-1" || selTimeScale != "custom"){
        $("#" + fromDiv).attr("disabled", true);
        $("#" + toDiv).attr("disabled", true);
        document.getElementById(fromDiv).value = '';
        document.getElementById(toDiv).value = '';
    }
    if (selTimeScale == "custom") {
        $("#" + fromDiv).removeAttr("disabled");
        $("#" + toDiv).removeAttr("disabled");
        document.getElementById(fromDiv).value = '';
        document.getElementById(toDiv).value = '';
    } else {
        $("#" + fromDiv).attr("disabled", true);
        $("#" + toDiv).attr("disabled", true);
        var selectedText = $('#' + elementId).multipleSelect("getSelects", "text").toString();
        if (selectedText === 'Publish custom') {
            var selectedVal = selTimeScale.toString().replaceAll("between", '');
            selectedVal = selectedVal.replaceAll("and", '');
            selectedVal = $.trim(selectedVal);

            selectedVal = (selectedVal).split(' ');
            for (var i = 0; i < selectedVal.length; i++) {
                var fromTime = (selectedVal[0] + " " + selectedVal[1]).replaceAll(/'/, "");
                var toTime = (selectedVal[3] + " " + selectedVal[4]).replaceAll(/'/, "");
                $('#' + fromDiv).val(fromTime);
                $('#' + toDiv).val(toTime);
            }
        }
    }
}

function arReplaceSpacewithUscr(replaceString) {
    if (replaceString != null && replaceString != undefined) {
        return replaceString.split(' ').join('_');
    }
    return replaceString;
}

function arMISFilterIdCreator(prefix, fieldObj) {
    var columnDisplayName = fieldObj.columnDisplayName.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var tableName = fieldObj.tableName.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var fieldGroupType = fieldObj.fieldGroupType.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var optionId = (prefix + "-" + tableName + fieldObj.fieldId + fieldGroupType + columnDisplayName).split(' ').join('_');
    return optionId;
}

function arMisFilterValueIdCreator(filterVal, filterObj) {
    var prefix = "mff";
    var columnDisplayName = filterObj.columnDisplayName.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var val = filterVal.value.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var text = filterVal.text.replace(/[&\/\\#,+@!--()$~%.'":*?<>{}]/g, '');
    var optId = (prefix + "-" + columnDisplayName + val + text).split(' ').join('_');
    return optId;
}

function arGetUserSelectedFilters() {

    var reportsMap = new Map();
    var reportsList = [];
    var filterDiv = 'arMISFiltersDiv';
    $('#' + filterDiv).children('div').children('div').children().each(function () {
        var parentObj = $.extend(true, {}, $(this).data('value'));// clone //$(this).data('value');
        var reportLabel = arReplaceSpacewithUscr(parentObj.reportLabel);
        var selLength = $(this).children('select').length;
        var selBoxElement = $(this).children('select');//clone select box element
        if (selLength > 0) {
            var dataValue = $.extend(true, {}, $(selBoxElement).data('value')), selectId = $(selBoxElement).attr('id');
            var filtervalueArray = [];
            var isSelected = false;
            var filterElementId = arCustomFieldIdCreator(reportLabel, dataValue);
            // find all all values from select boxe
            $.each($('#' + selectId).find(':selected'), function () {
                var val = $('#' + $(this).val()).data('value');
                if (val == 'custom') {
                    var timeScaleValue = "";
                    timeScaleValue = "Between '" + $('#filterFrom' + filterElementId).val() + "' and '" + $('#filterTo' + filterElementId).val() + "'";
                    filtervalueArray.push({"value": "" + timeScaleValue + "", "text": "" + $(this).text() + ""});
                    isSelected = true;
                } else if ($(this).val() != -1) {
                    filtervalueArray.push({"value": "" + $("#" + $(this).val()).data('value') + "", "text": "" + $(this).text() + ""});
                    isSelected = true;
                }
            });

            if (isSelected) {
                dataValue.filterValues = filtervalueArray;
                dataValue.columnId = 0;
                var reportLabel = parentObj.reportLabel;
                //add filter to ralted report.
                if (reportsMap.has(reportLabel)) {
                    var existingFilters = reportsMap.get(reportLabel);
					if(existingFilters.filters){
                    (existingFilters.filters).push(dataValue);
					}
                    reportsMap.set(reportLabel, existingFilters);
                } else {
                    if (parentObj.filters) {
                        (parentObj.filters).length = 0;
                        (parentObj.filters).push(dataValue);
                    }
                    if (parentObj.filters === null){
                        parentObj.filters = [];
                        (parentObj.filters).length = 0;
                        (parentObj.filters).push(dataValue);
                    }
                    reportsMap.set(reportLabel, parentObj);
                }
            }
        }
    });
    // get list of Reports to added to list
    reportsMap.forEach(function (entry, key, map) {
        reportsList.push(entry);
    });
    return reportsList;
}

function arOnSubmitFilterValidation() {
    var isValid = true;
    var filterDiv = 'arMISFiltersDiv';
    $('#' + filterDiv).children('div').children('div').children().each(function () {
        var selBoxElement = $(this).children('select');//clone select box element
        var selLength = $(this).children('select').length;
        if (isValid && selLength > 0) {
            var dataValue = $.extend(true, {}, $(selBoxElement).data('value')), selectId = $(selBoxElement).attr('id');
            isValid = arValidateMisFilters(selectId, dataValue, filterDiv);
        }
    });
    return isValid;
}

function arGetAllListedSelectedBoxIdsMis(filterDiv) {
    var selBoxIds = [];
//    var filterDiv = "arFiltersDiv";
    $('#' + filterDiv).children('div').children('div').children().children('select').each(function () {
//        var selBoxElement = $(this).children('select');//clone select box element
        var dataValue = $(this).data('value');
        var htmlType = dataValue.htmlType;
        var filterType = dataValue.filterType;
        if (htmlType != 'timeScale' && filterType != 'static') {
            selBoxIds.push($(this).attr('id'));
        }
    });
    return selBoxIds;
}

function arGetFilterValuesonSearchMIS(selectId, searchTxt, initSearch) {
    var authDetail=getAuthData(arTenantName);
    var filterObj = $("#" + selectId).data('value');
    //var datval=$(this).parent().data('value');
    var columnId = filterObj.columnId;
    var doc = $('#' + selectId).parent().data('value');
    var docId = doc.id;
//    console.log('filter search call..!');
    $("#progressMsg").css("display", "block");
    $.ajax({
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        url: "//" + arIpAddress + "/default-publish/publish/getfiltervaluebydocid?docId=" + docId + "&columnId=" + columnId + "&template=" + filterObj.template+ "&columnDisplayName=" + filterObj.columnDisplayName + "&userId=" +$('#arUserId').val() + "&searchText=" + searchTxt + "&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
//            data: filerQuery,
        crossDomain: true,
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        jsonp: true,
        success: function (data) {
            $("#progressMsg").css("display", "none");
            arUserSearchPopulateFilterValuesMIS(doc, filterObj, data, initSearch);
            $('#' + selectId + "_st").attr('value', searchTxt);
            $('#' + selectId).next().find('.ms-search input').val(searchTxt);
        },
        error: function (e) {
            $("#progressMsg").css("display", "none");
        }
    });
}

function arUserSearchPopulateFilterValuesMIS(report, item, optionData, initSearch) {
//    console.log('populating mis page filter values.!');
//    var filterDiv = "arFiltersDiv";
    var reportLabel = arReplaceSpacewithUscr(report.reportLabel);
    var filterElementId = arCustomFieldIdCreator(reportLabel, item);
    var selectView = $("#filter" + filterElementId);
    var prevFilterValues = [];
    var selectionType = item.htmlType;//single or multi
    var isChooseSelected = false;
    var chooseObj = {value: "-1", text: "-- choose --"};
    if (!initSearch) {
        //  prevFilterValues = $(selectView).val();
        var prevObjs = [];
        $.each(selectView.find('option[selected]'), function (e, val) {
            if ($(val).text() == chooseObj.text) {
                var id = {value: "-1", text: $(val).text()};
                prevObjs.push(id);
                isChooseSelected = true;
                prevFilterValues.push($(val).attr('value'));
            } else {
                var id = {value: $(val).attr('data-value'), text: $(val).text()};//create a object of previous selected filtervalueObj
                prevObjs.push(id);
                prevFilterValues.push($(val).attr('id'));
            }
        });
        optionData = arRemoveDuplicatesFilterValuesOnSearch(optionData, prevObjs);
    }
    $(selectView).empty();
    if (selectionType == "simple" && !isChooseSelected) {
        $("<option />", {value: chooseObj.value, text: chooseObj.text}).appendTo(selectView);
    }
    $.each(optionData, function (index, value) {
        var optId = arMisFilterValueIdCreator(value, item);
        $("<option />", {id: optId, value: optId, text: value.text, 'data-value': value.value}).appendTo(selectView);
    });
    arRefreshAndUncheckAllMultiSelect("#"+selectView[0].id);
    if (!initSearch) {
        if (prevFilterValues != null){
            $(selectView).multipleSelect('setSelects', prevFilterValues);
              $.each(prevFilterValues, function (index, value) {
                    $('#'+selectView[0].id+' option[value="'+value+'"]').attr("selected","selected");
              });
            $('#'+selectView[0].id).val(prevFilterValues);
            $('#'+selectView[0].id).multipleSelect("refresh");
            $('#'+selectView[0].id).val(prevFilterValues);
        }
    }
}

function arValidateMisFilters(selectId, dataValue, filterDiv) {
    var isValid = true, isMandatory = dataValue.mandatory, displayName = dataValue.columnDisplayName;
    var htmlType = dataValue.htmlType, columnId = dataValue.columnId;
    var columnName = dataValue.columnName;
    if (isMandatory === 'mandatory' && htmlType === "multi-value" && ($('#' + selectId).multipleSelect("getSelects").length == 0 || $('#' + selectId).multipleSelect("getSelects").toString() === '-1')) {
        $('#' + selectId).parent(".formElem").addClass("errField");
        isValid = false;
        arSelectFormElemVal('#' + selectId, "Please provide value for " + displayName);
    } else if (isMandatory === 'mandatory' && htmlType === "simple" &&
            ($('#' + selectId).multipleSelect("getSelects").length == 0 || $('#' + selectId).multipleSelect("getSelects").toString() === '-1')) {
        $('#' + selectId).parent(".formElem").addClass("errField");
        isValid = false;
        arSelectFormElemVal('#' + selectId, "Please provide value for " + displayName);
    } else if (htmlType === "timeScale") {
        if (isMandatory === 'mandatory' && ($('#' + selectId).multipleSelect("getSelects").length == 0
                || $('#' + selectId).multipleSelect("getSelects").toString() === '-1')) {
            $('#' + selectId).parent(".formElem").addClass("errField");
            isValid = false;
            arSelectFormElemVal('#' + selectId, "Please provide value for " + displayName);
        } else if ((isMandatory === 'mandatory' || isMandatory === 'optional')) {
            var selArray = $('#' + selectId).multipleSelect("getSelects", "text").toString();
            if (selArray.length > 0) {
                var safeValue = selArray[0].replace(/[\s()]/g, '\\$&');
                var dataVal = $('#' + safeValue).data('value');
				if(dataVal == undefined){
                    dataVal = "";
                }
                if (dataVal.toString() === 'custom') {
                    var selObject = $('#' + selectId).parent().data('value');
                    var reportLabel = selObject.reportLabel;
                    var filterElementId = arCustomFieldIdCreator(reportLabel, dataValue);
                    var fromId = 'filterFrom' + filterElementId, toId = 'filterTo' + filterElementId;
                    var fromTime = $('#' + fromId).val();
                    var toTime = $('#' + toId).val();
                    if (fromTime === '') {
                        $('#' + fromId).parent(".formElem").addClass("errField");
                        var errorMsg = $("<p class='fldErr'><span class='topCurve'></span>Please provide value for From time</p>");
                        //errorMsg.appendTo(errorTag);
                        isValid = false;
                        $('#' + fromId).after(errorMsg);
						//$('#' + fromId).focus();
                        if ($('.errField').closest('.innerDetails')) {
                            $('.errField').closest('.innerDetails').parent().children('.expForm').addClass("expand");
                            $('.errField').closest('.innerDetails').closest('.filteredBlk').children(".expForm").children(".ico").removeClass("plusIco").addClass("closeIco");
                            $('.errField').closest('.innerDetails').slideDown();
                            $('#' + fromId).parents(".errField").focus();
                        }else{
                            $('#' + fromId).parents(".errField").focus();
                        }
                    } else if (toTime === '') {
                        $('#' + toId).parent(".formElem").addClass("errField");
                        var errorMsg = $("<p class='fldErr'><span class='topCurve'></span>Please provide value for TO time</p>");
                        isValid = false;
                        $('#' + toId).after(errorMsg);
                        //$('#' + toId).focus();
						if ($('.errField').closest('.innerDetails')) {
                            $('.errField').closest('.innerDetails').parent().children('.expForm').addClass("expand");
                            $('.errField').closest('.innerDetails').closest('.filteredBlk').children(".expForm").children(".ico").removeClass("plusIco").addClass("closeIco");
                            $('.errField').closest('.innerDetails').slideDown();
                            $('#' + toId).parents(".errField").focus();
                        }else{
                            $('#' + toId).parents(".errField").focus();
                        }
                    } else {
                        isValid = validateTimeFields(fromTime, toTime, fromId, toId);
                    }
                }
            }
        }
    }
    return isValid;
}

$(document).on("click","#arMultiDiv .dynamic + .ms-parent .ms-choice",function(){
   var selectId = $(this).closest(":has(select)").find('select').attr("id");
   arGetFilterValuesonSearchMIS(selectId,"",false);
});

$(document).on("click","#arSimpleDiv .dynamic + .ms-parent .ms-choice",function(){
    var selectId = $(this).closest(":has(select)").find('select').attr("id");
   arGetFilterValuesonSearchMIS(selectId,"",false);
});
function arMisFilterValuesonOpen(filterId) {
//    console.log("mis on open is called for : "+filterId);
    var searchText = $('#' + filterId + "_st").val();
    var selectList = $("#" + filterId);
    var preSelectedArr = [];
    var defaultChooseText = $('#arDefaultChooseText').attr('value');
    $.each(selectList.find('option[selected]'), function (e, val) {
        var id = {value: $(val).attr('data-value'), text: $(val).text()};//create a object of previous selected filtervalueObj
        preSelectedArr.push(id);
    });

    if (preSelectedArr.length != 0) {
        var LastObj = preSelectedArr[preSelectedArr.length - 1];
        var lText = LastObj.text;
        console.log("appending search value.!" + LastObj.text + " and search text is :" + searchText);
        if (searchText == "") {
            if (defaultChooseText == lText) {
                $("#" + filterId).next().find('.ms-search input').val(searchText);
            } else {
                //$("#" + filterId).next().find('.ms-search input').val(LastObj.text);
            }
        } else {
            $("#" + filterId).next().find('.ms-search input').val(searchText);
        }
    } else {
       $("#" + filterId).next().find('.ms-search input').val(searchText);
    }
}
 $(document).on('keyup','#arMISAccessUser +.ms-parent .ms-search input',function(){debugger;
    var searchTxt=$(this).val();setTimeout(function(){
    var checkExist=setInterval(function(){
        if($('#arMISAccessUser +.ms-parent .ms-search input').is(":visible")){
        $('#arMISAccessUser +.ms-parent .ms-search input').val(searchTxt);
        clearInterval(checkExist);
        }
    },500);},500);
 });
                                                                                  