/*  
 *  ©2009-2018, Tecknodreams Software Consulting Pvt. Ltd.
 */
 
/*$(document).on("click",function(e){
    if(!$(e.target).is(".ms-parent,.ms-parent *")){
        $("div#arScheduleFiltersDiv select").multipleSelect("refresh");
    }
});*/
$(document).on("click","#arScheduleFiltersDiv .ms-parent",function(){
    $("#arScheduleFiltersDiv .ms-search input").val("");
});

var ARScheduleRecord = {};
function showComponents(id) {
    if (id !== undefined) {
        document.getElementById(id).style.display = 'block';
    }
}

function hide_Component(id) {
    if (id !== undefined) {
        document.getElementById(id).style.display = 'none';
    }
}
function getComponentValue(id) {
    var data = $(id).val();
    return data;
}
/*Hide FromTime when immediately is checked*/
function disTime() {
    if (document.getElementById('immCheck').checked == true) {
        document.getElementById('AR_FromTime').value = "";
        document.getElementById('AR_FromTime').disabled = true;
    } else {
        document.getElementById('AR_FromTime').value = "";
        document.getElementById('AR_FromTime').disabled = false;
    }
}
/*TO CLEAR PAGE ELEMENTS*/
function clearWeekDaysElemnets() {
    var selectedCheckbox = getSelectedBox();
    for (var i = 0; i < selectedCheckbox.length; i++) {
        document.getElementById(selectedCheckbox[i]).checked = false;
    }
}
function  getSelectedBox() {
    var selchbox = [];
    var inpfields = document.getElementsByName('one');
    var nr_inpfields = inpfields.length;
    for (var i = 0; i < nr_inpfields; i++) {
        if (inpfields[i].type == 'checkbox' && inpfields[i].checked == true) {
            selchbox.push(inpfields[i].value);
            check = true;
        }
    }
    return selchbox;
}
function validateRadioChecked(name) {
    var rate_value;
    var rates = document.getElementsByName(name);
    for (var i = 0; i < rates.length; i++) {
        if (rates[i].checked == true) {
            rate_value = rates[i].value;
        }
    }
    return rate_value;
}
function getEndDateTime(id) {
    var dateTime = document.getElementById(id).value;
    if (dateTime == "" || dateTime == undefined) {
        dateTime = null;
    }
    return dateTime;

}
function getHours() {
    var h = document.getElementById('idc').value;
    if (h < 23) {
        return h;
    }
}
function getSelectValue(id) {
    var selectedText = $(id).multipleSelect("getSelects", "text");
    return selectedText.join();
}
function currentDateTime() {
    now = new Date();
    year = "" + now.getFullYear();
    month = "" + (now.getMonth() + 1);
    if (month.length == 1) {
        month = "0" + month;
    }
    day = "" + now.getDate();
    if (day.length == 1) {
        day = "0" + day;
    }
    hour = "" + now.getHours();
    if (hour.length == 1) {
        hour = "0" + hour;
    }
    minute = "" + (now.getMinutes() + 1);
    if (minute.length == 1) {
        minute = "0" + minute;
    }
    return year + "-" + month + "-" + day + " " + hour + ":" + minute;
}
/*format user input values to required string*/
function stringRoleFormatter(stringForm) {
    var resultForm = '';
    if (stringForm != null && stringForm != undefined) {
        for (var i = 0; i < stringForm.length; i++) {
            resultForm = resultForm + stringForm[i];
            if (i < stringForm.length - 1) {
                resultForm = resultForm + ',';
            }
        }
    }
    return resultForm;
}

function getRepeatValue() {
    var result = "";
    var hours;
    var timerRadio = validateRadioChecked('repeat');
    if (timerRadio == "Hourly") {
        hours = getHours();
        result = timerRadio + "|" + hours;
    } else if (timerRadio == "Weekly") {
        var selectedCheckbox = getSelectedBox();
//        if (selectedCheckbox.length <= 0) {
//            $("#div1").closest('.frm-field').addClass('errField');
//            $(".fldErr").remove();
//            errMsg = getARDisplayMessage("selectWeekdays");
//            $('#div1').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
//            $('#div1').focus();
//            return false;
//        }
        result = timerRadio + "|" + selectedCheckbox;
    } else {
        result = timerRadio;
    }
    return result;
}
function arCheckMailId(mailids)
{

    var arr = new Array(
            '.com', '.net', '.org', '.biz', '.coop', '.info', '.museum', '.name', '.pro',
            '.edu', '.gov', '.int', '.mil', '.ac', '.ad', '.ae', '.af', '.ag', '.ai', '.al',
            '.am', '.an', '.ao', '.aq', '.ar', '.as', '.at', '.au', '.aw', '.az', '.ba', '.bb',
            '.bd', '.be', '.bf', '.bg', '.bh', '.bi', '.bj', '.bm', '.bn', '.bo', '.br', '.bs',
            '.bt', '.bv', '.bw', '.by', '.bz', '.ca', '.cc', '.cd', '.cf', '.cg', '.ch', '.ci',
            '.ck', '.cl', '.cm', '.cn', '.co', '.cr', '.cu', '.cv', '.cx', '.cy', '.cz', '.de',
            '.dj', '.dk', '.dm', '.do', '.dz', '.ec', '.ee', '.eg', '.eh', '.er', '.es', '.et',
            '.fi', '.fj', '.fk', '.fm', '.fo', '.fr', '.ga', '.gd', '.ge', '.gf', '.gg', '.gh',
            '.gi', '.gl', '.gm', '.gn', '.gp', '.gq', '.gr', '.gs', '.gt', '.gu', '.gv', '.gy',
            '.hk', '.hm', '.hn', '.hr', '.ht', '.hu', '.id', '.ie', '.il', '.im', '.in', '.io',
            '.iq', '.ir', '.is', '.it', '.je', '.jm', '.jo', '.jp', '.ke', '.kg', '.kh', '.ki',
            '.km', '.kn', '.kp', '.kr', '.kw', '.ky', '.kz', '.la', '.lb', '.lc', '.li', '.lk',
            '.lr', '.ls', '.lt', '.lu', '.lv', '.ly', '.ma', '.mc', '.md', '.mg', '.mh', '.mk',
            '.ml', '.mm', '.mn', '.mo', '.mp', '.mq', '.mr', '.ms', '.mt', '.mu', '.mv', '.mw',
            '.mx', '.my', '.mz', '.na', '.nc', '.ne', '.nf', '.ng', '.ni', '.nl', '.no', '.np',
            '.nr', '.nu', '.nz', '.om', '.pa', '.pe', '.pf', '.pg', '.ph', '.pk', '.pl', '.pm',
            '.pn', '.pr', '.ps', '.pt', '.pw', '.py', '.qa', '.re', '.ro', '.rw', '.ru', '.sa',
            '.sb', '.sc', '.sd', '.se', '.sg', '.sh', '.si', '.sj', '.sk', '.sl', '.sm', '.sn',
            '.so', '.sr', '.st', '.sv', '.sy', '.sz', '.tc', '.td', '.tf', '.tg', '.th', '.tj',
            '.tk', '.tm', '.tn', '.to', '.tp', '.tr', '.tt', '.tv', '.tw', '.tz', '.ua', '.ug',
            '.uk', '.um', '.us', '.uy', '.uz', '.va', '.vc', '.ve', '.vg', '.vi', '.vn', '.vu',
            '.ws', '.wf', '.ye', '.yt', '.yu', '.za', '.zm', '.zw');
    mailids = mailids.replace(/;/g, ",");
    var sd = mailids;
    var ids = sd.split(",");
    var val = true;
    for (var j = 0; j < ids.length; j++)
    {
        var mai = ids[j];
        var dot = mai.lastIndexOf(".");
        var ext = mai.substring(dot, mai.length);
        //alert(ext);
        var at = mai.indexOf("@");
        if (dot > 5 && at > 1)
        {
            for (var i = 0; i < arr.length; i++)
            {
                if (ext == arr[i])
                {
                    val = true;
                    break;
                } else
                {
                    val = false;
                }
            }
            if (val == false)
            {

                return false;
            }
        } else
        {
            return false;
        }
    }

    return true;
}

function showErrorMessageForMail(id, errMsg) {
    var errText = '<p class="fldErrMail"><span class="topCurve"></span></span>'
            + errMsg + '</p>';
    $('#' + id).closest('.formElem').addClass('errFieldMail');
    $('#' + id).after(errText);
}
/*Validation begins */
var filterJsonData = [];
function validateSdScheduleReports() {
    filterJsonData = [];
    var errMsg = "";
    var reportScheduleType = '0';
    var splChars = "*|,\":<>[]{}`\';()@&$#%";

    if ($("#title").val() === "") {
        $("#title").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("scheduleTitle");
        $('#title').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        //$('#title').focus();
        $('#title').parents(".errField").focus();
        return false;
    }
    if ($("#title").val().length > 175) {
        $("#title").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("name175");
        $('#title').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#title').focus();
        return false;
    }
    if (arCheckSpecialChars($("#title").val())) {
        arFocusFieldError("#title", "Report name should not contain any special charecter.!");
        return false;
    }
	
	
    if ($("#desc").val().trim() === "") {
        $("#desc").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("scheduleDescription");
       
        $('#desc').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#desc').focus();
        return false;
    }
    if (($("#desc").val()).length > 250) {
        $("#desc").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("description250");
       
        $('#desc').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#desc').focus();
        return false;
    }

    if (!validateSiteSelected()) {
        return false;
    }

    if (getSelectValue('#AR_sdcategory') === "") {
        $("#AR_sdcategory").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("reportSelect");
        $('#AR_sdcategory').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
        $('#AR_sdcategory').multipleSelect("focus");
        return false;
    }

    var data = JSON.parse($('#AR_sdcategory option:selected').attr("data-value"));
    if (data.templateType == "chart" || data.templateType === "assetanalytical") {
        if (getSelectValue('#AR_schedule_chartType') === "") {
            $("#AR_schedule_chartType").closest('.frm-field').addClass('errField');
            $(".fldErr").remove();
            errMsg = getARDisplayMessage("reportChartTypeError");
            $('#AR_schedule_chartType').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
            $('#AR_schedule_chartType').multipleSelect("focus");
            return false;
        }
    }

    if ((getComponentValue('#AR_sdrole') === "") && (getComponentValue('#AR_sduser') === "")) {
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("roleUser");
        if (getComponentValue('#AR_sdrole') === "") {
            $("#AR_sdrole").closest('.frm-field').addClass('errField');
            $('#AR_sdrole').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
            $('#AR_sdrole').multipleSelect("focus");
        } else {
            $("#AR_sduser").closest('.frm-field').addClass('errField');
            $('#AR_sduser').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
            $('#AR_sduser').multipleSelect("focus");
        }
        return false;
    }
    if ($('#arScheduleFiltersDiv').children().length != 0) {
        filterJsonData = applyFilters("arScheduleFiltersDiv");
		// code added By Dheeraj Mishra for DREC15497 8th Point
		if(filterJsonData===false){
			return false;
		}
    }
    if (document.getElementById('immCheck').checked == false) {
        if (document.getElementById('AR_FromTime').value == " " || document.getElementById('AR_FromTime').value == "") {
            $("#AR_FromTime").closest('.formElem').addClass('errField');
            $(".fldErr").remove();
            errMsg = getARDisplayMessage("sdscheduleTime1");
            $('#AR_FromTime').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
            //$('#AR_FromTime').focus();
             //$('#AR_FromTime').parents(".errField").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();
				$('#AR_FromTime').parents(".errField").focus();
            }else{
				$('#AR_FromTime').parents(".errField").focus();
			}
            return false;

        }
//        var isvalidTime = checkDateTime(document.getElementById('AR_FromTime').value, 'AR_FromTime');
        var isvalidTime = checkDateTime(document.getElementById('AR_FromTime').value);
        if (isvalidTime == false) {
            //$('#AR_FromTime').focus();
            $('#AR_FromTime').parents(".errField").focus();
            return false;
        }
        if (document.getElementById('AR_FromTime').value.indexOf("0000-00-00") != -1)
        {
            $("#AR_FromTime").closest('.frm-field').addClass('errField');
            $(".fldErr").remove();
            errMsg = getARDisplayMessage("invalidTime");
            $('#AR_FromTime').after('<p class="fldErrTech"><span class="topCurve"></span>' + errMsg + '</p>');
            //$('#AR_FromTime').focus();
            $('#AR_FromTime').parents(".errField").focus();
            return false;
        }
    }
    if ((document.getElementById('AR_ToTime').value) != "") {
        var arEndTime = document.getElementById('AR_ToTime').value;
        var isvalidTime = checkDateTime(arEndTime);
        if (isvalidTime == false) {
            //$('#AR_ToTime').focus();
             $('#AR_ToTime').parents(".errField").focus();
            return false;
        }
        var arStartTime = document.getElementById('immCheck').checked == false ? document.getElementById('AR_FromTime').value : currentDateTime();
        var isValidTimeDiff = arValidateTimeFields(arStartTime, arEndTime, "AR_FromTime", "AR_ToTime");
        if (isValidTimeDiff == false) {
            return false;
        }
    }
    if ((document.getElementById('ARexternalEmailID').value) !== "") {
        var bool = arCheckMailId($('#ARexternalEmailID').val());
        if (bool === false) {
            $("#ARexternalEmailID").closest('.frm-field').addClass('errField');
            $(".fldErr").remove();
            errMsg = getARDisplayMessage("emails");
            $('#ARexternalEmailID').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
           // $('#ARexternalEmailID').focus();
             $('#ARexternalEmailID').parents(".errField").focus();
           
            return false;
        }
        var result = getRepeatValue();
        if (result === false) {
            return false;
        }
    }
    if (document.getElementById('idc').value > 23) {
        $("#idc").closest('.frm-field').addClass('errField');
        $(".fldErr").remove();
        errMsg = getARDisplayMessage("invalidHours");
        $('#idc').after('<p class="fldErrTech"><span class="topCurve"></span>' + errMsg + '</p>');
        //$('#idc').focus();
        $('#idc').parents(".errField").focus();
        return false;
    }
    if (document.getElementById('Weekly').checked == true) {
        if (getSelectedBox().length <= 0) {
            $("#div1").closest('.frm-field').addClass('errField');
            $(".fldErr").remove();
            errMsg = getARDisplayMessage("selectWeekdays");
            $('#div1').after('<p class="fldErr"><span class="topCurve"></span>' + errMsg + '</p>');
            //$('#div1').focus();
            $('#div1').parents(".errField").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();
            }
            return false;
        }
    }
    return true;

}
/*Validations Ends*/

/*Error message display*/
function arCurrentDateTimeDiv(errMsg, id) {
    $('#' + id).parent('.formElem').addClass('errField');
    //$(".fldErr").remove();
    $('#' + id).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();
    }
}


/**To Display appropriate message **/
function getARDisplayMessage(type)
{
    var displayMessage = "";
    if (type === "scheduleTitle") {
        displayMessage = "Report Name is Mandatory";
    } else if (type === "selectedProjectId") {
        displayMessage = "Please select any project";
    } else if (type === "name175") {
        displayMessage = "Name should not be more than 175 characters";
    } else if (type === "nameSpecialChar") {
        displayMessage = "Name field should not contain any special characters";
    } else if (type === "scheduleDescription") {
        displayMessage = "Description is Mandatory";
    } else if (type === "description250") {
        displayMessage = "Only 250 characters are allowed in description field";
    } else if (type === "reportSelect") {
        displayMessage = "Please select any report";
    } else if (type === "scheduleSavedRecord") {
        displayMessage = "Please select any saved record";
    } else if (type === "scheduleTime") {
        displayMessage = "Please select any of the schedule time";
    } else if (type === "sdscheduleTime1") {
        displayMessage = "Please provide value for start time";
    } else if (type === "sdscheduleTime2") {
        displayMessage = "Please provide value for end time";
    } else if (type === "reportDesc") {
        displayMessage = "Please provide report description";
    } else if (type === "roleUser") {
        displayMessage = "Please select any  roles or users";
    } else if (type === "invalidTime") {
        displayMessage = "Invalid date format";
    } else if (type === "selectWeekdays") {
        displayMessage = "select Weekdays";
    } else if (type === "emails") {
        displayMessage = "Please enter valid mailids";
    } else if (type == "invalidHours") {
        displayMessage = "Please enter valid hours between 1 to 23";
    } else if (type == "reportChartTypeError") {
        displayMessage = "Please select chart type";
    }

    return displayMessage;
}
function show_Component(id) {
    if (id !== undefined) {
        document.getElementById(id).style.display = 'block';
    }
}

function hide_Component(id) {
    if (id !== undefined) {
        document.getElementById(id).style.display = 'none';
    }
}

/*To get SD Reports */
function loadARPublishedReports(reportArray) {
    var ARsdcategory = $('#AR_sdcategory').empty();
    $.each(reportArray, function (i, option) {
        var $option = $("<option>", {text: option.reportName, value: option.id, id: option.id + option.reportName.split(' ').join('_'), name: option.reportName, 'data-value': JSON.stringify(option)});
        $option.appendTo(ARsdcategory);
    });
    $('#AR_sdcategory').multipleSelect('refresh');
    $("#AR_sdcategory").multipleSelect("uncheckAll");

}

/*populate roles and user based on projectId*/
function loadSdRolesUsers(sdroles, sdusers,roleuserMap,module) {
    if ((sdroles != null && sdroles != undefined && sdroles.length > 0) ||
        (roleuserMap != null && roleuserMap != undefined)) {
        $('#AR_sdrole').empty();
        var rolesElement = $('#AR_sdrole');
        if(module !== 'MIS'){
            $.each(sdroles, function (i, role) {
                if(module === 'CMDB'){
                    var roleElement = $('<option>', {id: 'sdRolesCmdb_' + role.assetRoleId, text: role.roleName, value: '2_'+role.assetRoleId});
                }else{
                    var roleElement = $('<option>', {id: 'sdRolesItsm_' + role.projectRoleID, text: role.roleDisplayName, value: '1_'+role.projectRoleID});
                }
                roleElement.appendTo(rolesElement);
            });
        }else{
            var count = 1;
            $.each(roleuserMap, function (optgroup, roleusers) {
                $.each(roleusers.accessRoles, function (i, role) {
                    if(optgroup === 'CMDB Roles'){
                        var roleElement = $('<option>', {id: 'sdRolesCmdb_' + role.assetRoleId, text: "CMDB -- " + role.roleName, value: '2_'+role.assetRoleId});
                    }else{
                        var roleElement = $('<option>', {id: 'sdRolesItsm_' + role.projectRoleID, text: "ITSM -- " + role.roleDisplayName, value: '1_'+role.projectRoleID});
                    }
                    roleElement.appendTo(rolesElement);
                    count++;
                });
            });
        }
        $('#AR_sdrole').multipleSelect('refresh');
    }
    /*if (sdusers != null && sdusers != undefined && sdusers.length > 0 ||
        (roleuserMap != null && roleuserMap != undefined)) {
        $('#AR_sduser').empty();
        var usersElement = $('#AR_sduser');
        if(module !== 'MIS') {
            $.each(sdusers, function (i, user) {
                var userElement = $('<option>', {id: 'sdUser_' + user[0], text: user[1], value: user[0]});
                userElement.appendTo(usersElement);
            });
        }else {
            $.each(roleuserMap, function (optgroup, roleusers) {
                $.each(roleusers.userList, function (i, user) {
                    var userElement = $('<option>', {id: 'sdUser_' + user[0], text: user[1], value: user[0]});
                    userElement.appendTo(usersElement);
                });
            });
        }
    }*/
}
function getMode(buttonId) {
    var editMode = false;
    var edit = $(buttonId).val();
    if (edit != null && edit != 'undefined') {
        editMode = (edit === 'Update');
    }
    return editMode;
}

function resetOnEditMode(editMode) {
    $('#ARSaveBtnMode').empty();
    var updateVar = $('<input  type="button"  id="scheduleUpdateBtn" name="Update" value= "Update"  class="btn apply updateBtn"  onClick="submitScheduleInfo(\'scheduleUpdateBtn\')">' +
            '            <input  type="button"  onclick="arScheduleCancelReport(\'arSchedule_cancel\');" value="Cancel" class="btn cancel" />');
    var SaveVar = $('<input  type="button"  id="scheduleSaveBtn" name="Save" value= "Save"  class="btn apply updateBtn"  onClick="submitScheduleInfo(\'scheduleSaveBtn\')">' +
            '            <input  type="button"  onclick="arScheduleCancelReport(\'arSchedule_cancel\');" value="Cancel" class="btn cancel" />');
    var btnMode = $('#ARSaveBtnMode');

    if (editMode) {
        updateVar.appendTo(btnMode);
    } else {
        SaveVar.appendTo(btnMode);
    }
}

/*Form json data for scheduling report strats*/
function submitScheduleInfo(buttonState) {
    $("#scheduleUserMsg.errMsg").remove();
    var editMode = getMode('#' + buttonState);
    var isValid = validateSdScheduleReports();
    if (isValid === true) {
        var schedlerName = $("#title").val();
        var description = getComponentValue('#desc');

        var module = getSelectValue("#arSchModuleType");
        var sites = $('#arSch_siteList').multipleSelect('getSelects');
        if (sites.length <= 0) {
            sites = "|" + $("#siteId").val() + "|";
        } else {
            sites = "|" + sites.join("|") + "|";
        }

        var reports = getSelectValue('#AR_sdcategory');
        //var docId = $("#AR_sdcategory").find(':selected').attr('id');
        var docId = $('#AR_sdcategory option:selected').val();
        var reportScheduleType = validateRadioChecked('reportScheduleType');
        var modeValue = validateRadioChecked('mode');
        var roleList = "";
        var userList = "";
        if (modeValue === "Email" || modeValue === 'Both') {
            roleList = getComponentValue('#AR_sdrole');
            userList = getComponentValue('#AR_sduser');
        }
        var mailidsString = document.getElementById('ARexternalEmailID').value;
        var startdTime = "";
        if (document.getElementById('immCheck').checked == true) {
            startdTime = currentDateTime();
        } else {
            startdTime = document.getElementById('AR_FromTime').value;
            var isValidTimeDiff = ARCurrentDateValidation(startdTime, "\'Start time'", 'AR_FromTime');
            if (isValidTimeDiff == false) {
                return;
            }
        }
        var chartType = "", chartTheme = "";
        var data = JSON.parse($('#AR_sdcategory option:selected').attr("data-value"));
        if (data.templateType == "chart" || data.templateType == "assetanalytical") {
            chartType = $('#AR_schedule_chartType').multipleSelect("getSelects","value")[0].chartType;
            chartTheme = validateRadioChecked('ar_chart_schedule_theme');
        }
        var result = getRepeatValue();
        var jsonDoc = createJobInfo(schedlerName, description,
                reports, docId, modeValue, reportScheduleType, roleList, userList,
                mailidsString, startdTime, result, editMode, filterJsonData, chartType, chartTheme, module, sites);

        savedata(jsonDoc, editMode);

    }
}
function createJobInfo(schedlerName, description,
        reports, docId, modeValue, reportScheduleType, roleList, userList,
        mailidsString, startdTime, result, editMode, filterJsonData, chartType, chartTheme, module, sites) {
    var endTime = document.getElementById('AR_ToTime').value;
    var access_roles = "";
    var access_users = "";
    if (roleList !== null && roleList !== undefined && roleList !== "") {
        access_roles = stringRoleFormatter(roleList);
    }
    if (userList !== null && userList !== undefined && userList !== "") {
        access_users = stringRoleFormatter(userList);
    }
    var jobId = 0;
    var scheduleId = 0;
    var firstStime=startdTime;
    if (editMode) {
        jobId = ARScheduleRecord.jobinfoId;
        scheduleId = ARScheduleRecord.id;
        firstStime="";
    }
    var loginUserId = $('#arUserId').val();
    var loginUserName = $('#arUserName').val();
    var selectedProjectId = $('#selectedProjectId').val();
    var jobInfo = {
        "project": selectedProjectId,
        "schedulerName": schedlerName,
        "descreption": description,
        "reports": reports,
        "modeOfReporting": modeValue,
        "scheduleReportType": reportScheduleType,
        "reportAccessRoles": access_roles,
        "reportAccessUsers": access_users,
        "externalEmails": mailidsString,
        "startDate": startdTime,
        "firstScheduleTime":firstStime,
        "endDate": endTime,
        "repeat": result,
        "logInUserId": loginUserId,
        "editFlag": editMode,
        "jobId": jobId
    };
    var scheduleInfo = {
        "id": scheduleId,
        "platform": false,
        "createdBy": loginUserId,
        "createdUser": loginUserName,
        "projectId": selectedProjectId,
        "projectName": selectedProjectId,
        "scheduleName": schedlerName,
        "description": description,
        "report": reports,
        "docId": docId,
        "modeOfReport": modeValue,
        "scheduleReportType": reportScheduleType,
        "roles": access_roles,
        "users": access_users,
        "externalEmailIds": mailidsString,
        "jobinfoId": jobId,
        "accessUserId": null,
        "emails": null,
        "jobInfo": jobInfo,
        "filterColumns": filterJsonData,
        "chartType": chartType,
        "chartTheme": chartTheme,
        "logInUserId": loginUserId,
        "module": module,
        "siteId": sites
    };
    var jsonDoc = JSON.stringify(scheduleInfo);
    return  jsonDoc;
}
/*Form json data for scheduling report strats*/

/*schedule add call begins*/
function savedata(jsonDoc, editMode) {
    $("#progressMsg").css("display", "block");
     var authDetail=getAuthData(arTenantName);
    var URL = "//" + arIpAddress + "/default-delivery/schedule/doSchedule?tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1];
    $.ajax({
        type: 'POST',
        contentType: "application/json",
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        url: URL,
        data: jsonDoc, // now data come in this function
        crossDomain: true,
        jsonp: true,
        success: function (response) {
            $('#arModule').val($('#arSchModuleType').val());// setting it for listing tab selection.
            var onSubmitModule = $('#arSchModuleType').val();
            arChangeModuleOnReportSubmit(onSubmitModule);
            setScheduleReportCreateSuccess(response);
            saveScheduleReport();
            $('#arSchedule_create').css("display", "none");
        },
        error: function (response) {
//            setScheduleReportCreateError(response.responseJSON.error);
            setScheduleReportCreateError(response.responseText);
            $("#loading").hide();
            $("#progressMsg").css("display", "none");
        },
        complete: function (jqXHR, textStatus) {
            $("#progressMsg").css("display", "none");
        }

    });
}
/*schedule save call ends*/


function setScheduleReportCreateSuccess(msg) {
    $('#arscheduleAddResult').append('<div class="sucessMsg"><i class="ico statusIco"></i><p>' + msg + '</p></div>');
    $('#arscheduleAddResult').focus();
    $('body, html').animate({
        scrollTop: 0
    });
    setTimeout(function () {
        $('#arscheduleAddResult .sucessMsg').fadeOut('fast');
    }, 2000);
}
function setScheduleReportCreateError(msg) {
    $('#arscheduleErrorResult').empty();
    $('#arscheduleErrorResult').append('<div class="errMsg statusIco"></i><p>' + msg + '</p></div>');
   // $('#arscheduleErrorResult').focus();
    $('#arscheduleErrorResult').parents(".errField").focus();
    setTimeout(function () {
        $('#arscheduleErrorResult .errMsg').fadeOut('fast');
    }, 5000);
}
function getScheduleFilters(editMode, reportData) {
    var moduleType = $('#arSchModuleType').val();
    if ('MIS' != moduleType) {
        var filterColumns = (editMode) ? reportData.filterColumns : "";
        var docId =$('#AR_sdcategory').multipleSelect("getSelects");
		if(docId!=""){
        docId=docId[0].id;        
        $('#AR_sdcategory option[value='+docId+']').prop('selected', true);
        var data = JSON.parse($('#AR_sdcategory option:selected').attr("data-value"));
        var template = data.template;
        var templateType = data.templateType;
        var projectId = data.projectId;
        var assetModuleId = data.assetModuleId;
        if (docId !== "" || docId != undefined) {
            formAndRenderDynamicFilters(docId, template, "arScheduleFiltersDiv", editMode, filterColumns, projectId,assetModuleId);
        }
        // Below code is used to get the chart report chart series.
        $('#scheduleChartSeries').css("display", "none");
        if (templateType != undefined && (templateType == 'chart' || templateType == 'assetanalytical') ) {
            var chartSeries = data.chartSeries, chartType = data.chartType;
            getChartSeriesForSelectedChartReport(chartSeries, editMode, reportData);
        }
		}
    } else {
        $("#ScheduleFilters").hide();
    }
}

function getChartSeriesForSelectedChartReport(chartSeries, editMode, reportData) {
     var authDetail=getAuthData(arTenantName);
    $.ajax({
        url: "//" + arIpAddress + "/default-publish/publish/chartseries?series=" + chartSeries + "&tenant_id=" + arTenantName+"&authKey="+authDetail[0]+ "&authToken="+authDetail[1],
        type: "GET",
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        contentType: 'application/json',
        dataType: "json",
        crossDomain: true,
        success: function (data, textStatus, jqXHR) {
            $('#scheduleChartSeries').css("display", "");
            var ARsdcategory = $('#AR_schedule_chartType').empty();
            $.each(data, function (i, option) {
                var $option = $("<option>", {text: option.chartDisplayName, value: option.chartType, id: 'AR_schedule_chartType_' + option.chartType,
                    name: option.chartDisplayName, 'data-value': JSON.stringify(option)});
                $option.appendTo(ARsdcategory);
            });
            $('#AR_schedule_chartType').multipleSelect('refresh');
            $("#AR_schedule_chartType").multipleSelect("uncheckAll");
            if (editMode) {
                document.getElementById("AR_schedule_chartType_" + reportData.chartType).selected = true;
                $('#AR_schedule_chartType').multipleSelect('refresh');
                $("input[name=ar_chart_schedule_theme][value=" + reportData.chartTheme + "]").prop('checked', true);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(" getChartSeriesForSelectedChartReport :: ERROR :: arReportExecute :: " + textStatus);
        },
        complete: function (jqXHR, textStatus) {
        }
    });
}

/*get all initial data onclick of add report begins*/
function getArInitScheduleData(editMode, reportData) {
    var module = $('#arModule').val();
    clearSchedulePageElements();
    resetOnEditMode(editMode);//change button state save/update      
    setSchModuleList(editMode, module, reportData);
    populateSchARSiteList(editMode, reportData);
    if (!editMode) {
        $('#scheduleChartSeries').css("display", "none");
        getSchPrePublishData(editMode, "");
    } else {
        getSchPrePublishData(editMode, reportData);
    }
}
/*get all initial data onclick of add report ends*/

function getSchPrePublishData(editMode, reportData) {
    var selectedProjectId = $('#selectedProjectId').val();
    var module = getSelectValue("#arSchModuleType");
    if(module == 'CMDB'){
         checkSchMultiSelectionSiteId();
    }
    var siteLst = $("#arSch_siteList").multipleSelect("getSelects");
    
    var doAjaxCall = validateModuleAndSiteList(module, siteLst);
   
    //siteLst = siteLst.join(",");
    if (doAjaxCall) {
        if (siteLst.length <= 0) {
            siteLst = $("#siteId").val();
        }
        $("#progressMsg").css("display", "block");
         var authDetail=getAuthData(arTenantName);
        $.ajax({
            type: "GET",
            dataType: "json",
            headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
            },
            contentType: "application/json",
            data: {platform: false,users: reportData.users, inbuilt: false, id: selectedProjectId, userid: $('#arUserId').val(), module: module, siteId: siteLst, tenant_id: arTenantName,authKey:authDetail[0],authToken:authDetail[1]},
            url: "//" + arIpAddress + "/default-publish/publish/scheduleview",
            crossDomain: true,
            jsonp: true,
            async:false,
            success: function (response) {
                $("#progressMsg").css("display", "none");
                ARScheduleRecord = reportData;
                loadSdRolesUsers(response.accessRoles, response.userList,response.rolesUserList,module);
                loadARPublishedReports(response.userAccessibleReports);
                if (editMode) {
                    var docid=reportData.docId;
                    var repName = reportData.docId + reportData.report.split(' ').join('_');
                    var result=userExists(docid,response.userAccessibleReports);
                    if(!result)
                    {
                        $("#scheduleUserMsg.errMsg").remove();
                       $("#arscheduleEditGrid").before('<div class="errMsg statusIco" id="scheduleUserMsg"><i class="ico statusIco"></i><p>Selected Custom Reports have been moved to Inbuilt Reports</p></div>');
//                       setTimeout(function () {
//                            $('#arscheduleEditGrid .errMsg').fadeOut('fast');
//                        }, 2000);                     
                    }
//                  $('#' + repName).attr('selected', true);
                    else{
                    if (repName != null || repName != undefined) {
                        document.getElementById(repName).selected = true;
                       }
                       $('#AR_sdcategory').multipleSelect('refresh');
                       getScheduleFilters(editMode, reportData);
                       arScheduleEditInitData(reportData);
                     }
                 }
            }, error: function (jqXHR, textStatus, errorThrown) {
                $("#progressMsg").css("display", "none");
                redirectToReportTypeView('schedule');
                setScheduleReportCreateError("Failed load data, Please contact Administrator.!");
            },
            complete: function (jqXHR, textStatus) {
                $("#progressMsg").css("display", "none");
            }
        });
    }
}
function userExists(docId,userReport) {
  return userReport.some(function(el) {
    return el.id === docId;
  }); 
}

function getReportsForSchedule(module, siteLst) {
    var selectedProjectId = $('#selectedProjectId').val();
    $("#progressMsg").css("display", "block");
     var authDetail=getAuthData(arTenantName);
    $.ajax({
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        data: {platform: false, inbuilt: false, id: selectedProjectId, userid: $('#arUserId').val(), module: module, siteId: siteLst, tenant_id: arTenantName,authKey:authDetail[0],authToken:authDetail[1]},
        url: "//" + arIpAddress + "/default-publish/publish/getreportforsch",
        crossDomain: true,
        jsonp: true,
        success: function (response) {
            loadARPublishedReports(response);
            $("#arScheduleFiltersDiv").empty();
            $("#progressMsg").css("display", "none");
        }, error: function (jqXHR, textStatus, errorThrown) {
            $("#progressMsg").css("display", "none");
        },
        complete: function (jqXHR, textStatus) {
            $("#progressMsg").css("display", "none");
        }
    });
}

function validateModuleAndSiteList(module, siteLst) {
    var isValid = true;
    if (module.length <= 0) {
        isValid = false;
        $("#arSchSiteDiv").css("display", "none");
       // $("#arSch_siteList").multipleSelect("uncheckAll");
    } else if (module.length > 0) {
        if (module === "CMDB") {
             checkSchMultiSelectionSiteId();
             siteLst = $("#arSch_siteList").multipleSelect("getSelects");
            $("#arSchSiteDiv").css("display", "");
           // if (siteLst.length <= 0) {
           //     isValid = false;
           // }
        } else {
            $("#arSchSiteDiv").css("display", "none");
            $("#arSch_siteList").multipleSelect("uncheckAll");
        }
    }
    return isValid;
}

function onSelectionOfSchModule() {
    var module = getSelectValue("#arSchModuleType");
    var siteId = "";
    if (module === "CMDB") {
        $("#arSchSiteDiv").css("display", "");
        checkSchMultiSelectionSiteId();
        //siteId = $("#arSch_siteList").multipleSelect("getSelects");
         siteId = $("#siteId").val();
        $("#AR_sdcategory").empty();
        $('#AR_sdcategory').multipleSelect('refresh');
        $("#AR_sdcategory").multipleSelect("uncheckAll");
    } else {
        siteId = $("#siteId").val();
        $("#arSchSiteDiv").css("display", "none");
        $("#arSch_siteList").multipleSelect("uncheckAll");
        $("#arSch_siteList").multipleSelect("refresh");
    }
    if (module.length > 0) {
        if (module !== "CMDB") {
            getReportsForSchedule(module, siteId);
            getRolesUserList(module, 'schedule');
        } else if (module == "CMDB" && siteId.length > 0) {
           // siteId = siteId.join(",");
            getReportsForSchedule(module, siteId);
            getRolesUserList(module, 'schedule');
        }
    }
}

function setSchModuleList(editMode, module, reportData) {
    if (!editMode) {
        $('#arSch_' + module).prop('selected', true);
        $('#arSchModuleType').multipleSelect('refresh');
    } else {
        var moduleLst = reportData.module;
        var reports = $('#arSchModuleType').find('option');
        $.each(reports, function (i, option) {
            if (option.value == moduleLst) {
                var doc = document.getElementById(option.id);
                doc.selected = true;
            }
        });
        $('#arSchModuleType').multipleSelect('refresh');
    }
}

function populateSchARSiteList(editMode, reportData) {
     checkSchMultiSelectionSiteId();
 /*   $("#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) {
            $("#progressMsg").css("display", "none");
            $('#arSch_siteList').empty();
            var siteSelect = $("#arSch_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);
            });
            $("#arSch_siteList").multipleSelect("uncheckAll");
            $('#arSch_siteList').multipleSelect('refresh');
            if (editMode) {
                checkSchMultiSelectionSiteId(reportData);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $("#progressMsg").css("display", "none");
            redirectToReportTypeView('schedule');
            setScheduleReportCreateError("Failed load data, Please contact Administrator.!");
        },
        complete: function (jqXHR, textStatus) {
            $("#progressMsg").css("display", "none");
        }
    });*/
}

function checkSchMultiSelectionSiteId() {
    //var siteIdArray = editData.siteId.split(/\|/);
    //for (var j = 0; j < siteIdArray.length; j++) {
        var options = $('#arSch_siteList').find('option');
        $.each(options, function (i, option) {
           // if (option.value == siteIdArray[j]) {
                var doc = document.getElementById(option.id);
                doc.selected = true;
            //}
        });
    //}
    $('#arSch_siteList').multipleSelect('refresh');
}

function validateSiteSelected() {
    var module = getSelectValue("#arSchModuleType");
     checkSchMultiSelectionSiteId();
   // var siteId = $("#arSch_siteList").multipleSelect("getSelects");
   // if (module === "CMDB") {
      //  if (siteId.length <= 0) {
            // Post error for
       //     $("#arSch_siteList").closest('.frm-field').addClass('errField');
       //     $(".fldErr").remove();
       //     $('#arSch_siteList').after('<p class="fldErr"><span class="topCurve"></span> Please provide site </p>');
            //$('#arSch_siteList').focus();
       //      $('#arSch_siteList').parents(".errField").focus();
        //    return false;
     //   }
   // }
    return true;
}

function arScheduleEditInitData(reportData) {

    populateScheduleSavedData(reportData, false);
    if (reportData.modeOfReport === "Offline") {
        hide_Component('sendToUsers');
        document.getElementById('ARexternalEmailID').value = '';
    } else {
        selectRolesUsersValues("sdRoles", reportData.roles);
        selectRolesUsersValues("sdUser_", reportData.users);
    }

}

function  populateScheduleSavedData(record, platform) {
    document.getElementById("title").value = record.scheduleName;
    document.getElementById("desc").value = record.description;
    document.getElementById("AR_FromTime").value = record.jobInfo.startDate;
    document.getElementById("AR_ToTime").value = record.jobInfo.endDate;
    document.getElementById("ARexternalEmailID").value = record.externalEmailIds;
    if ("Excel" == record.scheduleReportType)
    {
        var scheduleReport_type = "xlsx";
    } else {
        var scheduleReport_type = record.scheduleReportType;
    }
    $("input[name=reportScheduleType][value=" + scheduleReport_type + "]").prop('checked', true);
    if ("Email,Offline" == record.modeOfReport)
    {
        var mode_of_Report = "Both";
    } else {
        mode_of_Report = record.modeOfReport;
    }
    $("input[name=mode][value=" + mode_of_Report + "]").prop('checked', true);
    var weeks = [];
    if (record.jobInfo.repeat != null && record.jobInfo.repeat != undefined) {
        $.each(record.jobInfo.repeat.split(/\|/), function (i, val) {
            $.each(val.split(','), function (i, v) {
                weeks.push(v);
            });
        });
        setReapeatValue(weeks);
    }
}
function setReapeatValue(weeks) {
    if (document.getElementById(weeks[0]).value === "Weekly") {
        hide_Component('div2');
        show_Component('div1');
        $("input[name=repeat][value=" + weeks[0] + "]").prop('checked', true);
        for (var i = 1; i < weeks.length; i++) {
            document.getElementById(weeks[i]).checked = true;
        }
    } else if (document.getElementById(weeks[0]).value === "Hourly") {
        show_Component('div2');
        hide_Component('div1');
        $("input[name=repeat][value=" + weeks[0] + "]").prop('checked', true);
        document.getElementById('idc').value = weeks[1];
        var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        for (var i = 0; i < days.length; i++) {
            if (days[i] !== null) {
                document.getElementById(days[i]).checked = false;
            }
        }
    } else {
        hide_Component('div2');
        hide_Component('div1');
        $("input[name=repeat][value=" + weeks[0] + "]").prop('checked', true);
    }
}

//To set selected dynamic filter values
function setSelectedFilters(filterColumns, filterDiv) {
    var filtervalueArray;
    $.each(filterColumns, function (i, option) {
        var filterElementId = arCustomFieldIdCreator(filterDiv, option);
        $('#filter' + filterElementId).multipleSelect('refresh');
        if (option.htmlType == "timeScale") { //html type:timescale 
            $.each(option.filterValues, function (i, filter) {
                if (filter.text === "Custom") {// if "custom" set FromTime and ToTime
                    var value = {value: "custom", text: "Custom"};
                    var optId = arExecutionFilterValueIdCreator(value, option);
                    var doc = document.getElementById(optId);
                    if (doc != null) {
                        doc.selected = true;
                    }
                    filtervalueArray = (filter.value).split(' ');
                    for (var i = 0; i < filtervalueArray.length; i++) {
                        var fromTime = (filtervalueArray[1] + " " + filtervalueArray[2]).replaceAll(/'/, "");
                        var toTime = (filtervalueArray[4] + " " + filtervalueArray[5]).replaceAll(/'/, "");
                        $('#filterFrom' + filterElementId).val(fromTime);
                        $('#filterTo' + filterElementId).val(toTime);
                    }
                } else if(filter.text == 'Publish custom'){
                        
                    var value = filter.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 = arExecutionFilterValueIdCreator(filter, option);
                    var doc = document.getElementById(optId);
                    if (doc != null) {
                        doc.selected = true;
                    }
                    //optIds.push(optId);
                }else {
                    //if not custom
                    var id = arExecutionFilterValueIdCreator(filter, option);
                    var doc = document.getElementById(id);
                    if (doc != null) {
                        doc.selected = true;
                    }
                }
            });
        } else if (option.htmlType == "simple") {//html type:simple 
            $.each(option.filterValues, function (i, filter) {
                var id = arExecutionFilterValueIdCreator(filter, option);
                var doc = document.getElementById(id);
                if (doc != null) {
                    doc.selected = true;
                }
            });
        } else if (option.htmlType == "multi-value") {//html type:multi value
            $.each(option.filterValues, function (i, filter) {
                var id = arExecutionFilterValueIdCreator(filter, option);
                var doc = document.getElementById(id);
                if (doc != null) {
                    doc.selected = true;
                }
            });
        }
        $('#filter' + filterElementId).multipleSelect('refresh');
    });
}
/*Clear page elements begins*/
function clearSchedulePageElements() {
    ARScheduleRecord = {};
    document.getElementById('title').value = '';
    document.getElementById('desc').value = '';
    document.getElementById('immCheck').checked = false;
    disTime();
    show_Component('sendToUsers');
    show_Component('div2');
    hide_Component('div1');

    $("#arSchSiteDiv").css("display", "none");
    $("#arSch_siteList").multipleSelect("uncheckAll");
    $('#arSch_siteList').multipleSelect('refresh');


    document.getElementById('AR_FromTime').value = '';
    document.getElementById('AR_ToTime').value = '';
    document.getElementById('ARexternalEmailID').value = '';
    $("input[name=mode][value=Email]").prop('checked', true);
    $("input[name=reportScheduleType][value=PDF]").prop('checked', true);
    $('#AR_sdrole').multipleSelect('refresh');
    $("#AR_sdrole").multipleSelect("uncheckAll");
    $('#AR_sduser').multipleSelect('refresh');
    $("#AR_sduser").multipleSelect("uncheckAll");
    $("input[name=repeat][value=Hourly]").prop('checked', true);
    document.getElementById('idc').value = 1;
    var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    for (var i = 0; i < days.length; i++) {
        document.getElementById(days[i]).checked = false;
    }
    $('#arSchedule_create .filter-block .filteredBlk .expForm').addClass("expand");
    $('#arSchedule_create .filter-block .filteredBlk .expForm .ico').removeClass("plusIco").addClass("closeIco");
    $('#arSchedule_create .innerDetails').slideDown();

    $('#AR_sdcategory').multipleSelect('refresh');
    var sdCatVal=$('#AR_sdcategory').val();
    if(sdCatVal!=null && sdCatVal!=""){
        $("#AR_sdcategory").multipleSelect("uncheckAll");
    }
}
/*Clear page elements begins*/

function selectRolesUsersValues(idName, recordVals) {
    if (recordVals != undefined && recordVals != "") {
        if(idName.includes('sdUser_')){
            loadSelectedUsersOnDropdown($('#AR_sduser').attr('data-sapphireContext'),'AR_sduser', recordVals);
        }
        var tempIds = "";
        var module = "";
        if (idName != null && idName != undefined && idName !== 0) {
            tempIds = recordVals.split(",");
        } else {
            tempIds = recordVals;
        }
        var id;
        for (var i = 0; i < tempIds.length; i++) {
            if(idName.includes('sdRoles')){
                module = tempIds[i].split("_");
                var tempModule = module[0] === "1"?"Itsm":"Cmdb";
                id = idName+ tempModule+"_" + module[1];
            }
            $('#' + id).attr('selected', true);

        }
    }
    $('#AR_sdrole').multipleSelect('refresh');
    $('#AR_sduser').multipleSelect('refresh');
}

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

function getRolesUserList(module,reportType) {
    var selectedProjectId = $('#selectedProjectId').val();
    authDetail=getAuthData(arTenantName);
    $("#progressMsg").css("display", "block");
    $.ajax({
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        headers:{
            'x-auth-key':authDetail[0],
            'x-auth-token':authDetail[1]
        },
        data: {platform: false,projectId: selectedProjectId,module: module,tenant_id: arTenantName,authKey:authDetail[0],authToken:authDetail[1]},
        url: "//" + arIpAddress + "/default-publish/publish/getRolesUserList",
        crossDomain: true,
        jsonp: true,
        async: false,
        success: function (response) {
            $("#progressMsg").css("display", "none");
            if(reportType === 'schedule'){
                loadSdRolesUsers(response.accessRoles, response.userList,response.rolesUserList,module);
            }else{
                renderMISRoles(response.accessRoles,response.rolesUserList);
                renderMISUsers(response.userList,response.rolesUserList);
            }
        }, error: function (jqXHR, textStatus, errorThrown) {
            $("#progressMsg").css("display", "none");
        },
        complete: function (jqXHR, textStatus) {
            $("#progressMsg").css("display", "none");
        }
    });
}
