var $ = jQuery.noConflict();
var currSelectedcell;
var validationAlertShown=false;
var inActiveRow=[];
$(function (){
    $(document).ajaxSend(function(e, xhr, options){xhr.setRequestHeader("X-CSRF-TOKEN", $('meta[name=_csrf]').attr("content"));});
    var $loader = $('#loading'), timer;
    $( document ).ajaxSend(function(event,xhr,options) {
        var url=options.url;
        if(url.indexOf('displayUsers') === -1){
            timer && clearTimeout(timer);
            timer = setTimeout(function()
                {
                    if($("#mainAssetDiv").is(":visible")===false){
                        $( "#loading" ).show();
                    }
                },
                1000);
        }
    });
    $( document ).ajaxComplete(function(event, xhr, options) {
        var response=xhr.responseText;
        clearTimeout(timer);
        if($("#mainAssetDiv").is(":visible")===false){
            $( "#loading" ).hide();
        }
        if(response !== undefined  && response.indexOf("Session timeout") !== -1 && response.indexOf("name=\"sessionTimeOut\"") !== -1){
            window.location.href="LoginPage.do?loginErrorID=4";
        }
    });
    $(document).ready(function () {
        var moduleId = $("#moduleId").val();
        var projectId = $("#projectId").val();
        var pageNumber=$("#listingGridPager").attr("data-pageno");
        var pageSize=$(".gridViewPort .recordLimit").val();
        loadSdGridData(projectId, moduleId,pageNumber,pageSize);
    });
});
OpenProjectSettings = function(projectId,moduleId){
    window.location.href="getSdSettingsRedirectionPage.do?projectId="+projectId+"&moduleId="+moduleId;
}
var columntest = [];
var editableGridOptions = {
    editable: true,
    enableAddRow: true,
    enableCellNavigation: true,
    asyncEditorLoading: false,
    multiColumnSort: true,
    resizable: true,
    sortable: true,
    autoEdit: false,
    autoHeight: false,
    frozenColumn: -1,
    autoCommitEdit: false,
    autoExpandColumns: true,
    forceFitColumns: true,
    enableColumnReorder:false,
};
var unEditableGridOptions = {
    editable: false,
    enableAddRow: false,
    enableCellNavigation: true,
    asyncEditorLoading: false,
    multiColumnSort: true,
    resizable: true,
    sortable: false,
    autoEdit: false,
    autoHeight: false,
    frozenColumn: 10,
    autoCommitEdit: false,
    forceFitColumns: true,
    enableColumnReorder:false
};
function strip(html)
{
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
}
function getEditorBasedonColumnType(columnType, gridRowDetails) {
    var gridCellAttributes = {};
    var editor = null;

    if (columnType == "1") {
        editor = Slick.Editors.Text;
    } else if (columnType == "2") {
        editor = Slick.Editors.SelectboxMultiple;
    } else if (columnType == "3") {
        editor = Slick.Editors.DateTime;
    } else if (columnType == "7") {
        editor = Slick.Editors.CheckBoxField;
        gridCellAttributes ["formatter"] =  CheckBoxFormatter;
    }
    else if ( columnType == "15" )
    {
        editor = Slick.Editors.Date;
    } else if (columnType == "21") {
        editor = Slick.Editors.Time;
    } else if (columnType == "22") {
        editor = null
    } else if (columnType == "23") {
        editor=null
        gridCellAttributes ["formatter"] = ImageSetterFormatter;
    } else if (columnType == "24") {
        editor = Slick.Editors.CheckBoxField;
        gridCellAttributes ["formatter"] =  CheckBoxFormatter;
    }
    else if (columnType == "25") {
        editor = null
        gridCellAttributes ["formatter"] =  ToggleBtnFormatter;
    }else if (columnType == "26") {
        editor=null
        gridCellAttributes ["formatter"] = singleSelectBoxFormatter;
    }else if (columnType == "27") {
        editor=Slick.Editors.SelectboxSingle
    }
    else if (columnType == "28") {
        editor = null;
        gridCellAttributes ["formatter"] = slickGridCellCustomFormatter;
    }
    else if (columnType == "29") {
        editor = Slick.Editors.jsColorPicker;
        gridCellAttributes ["formatter"] = jsColorPicker;
    }else if (columnType == "30") {
        editor = null;
        gridCellAttributes ["formatter"] = simpleColorPicker;
    }
    else if (columnType == "30") {
        editor = null;
        gridCellAttributes ["formatter"] = simpleColorPicker;
    }
    else if (columnType == "31") {
        editor =Slick.Editors.SelectboxSingle;
    }
    gridCellAttributes ["editor"] = editor;
    return gridCellAttributes;
}
function simpleColorPicker(row, cell, value, columnDef, dataContext) {
    return '<select name="categoryColorPicker" class="categoryColorPicker" id="categoryColorPicker_'+row+'"><option value="#0F93EE">Blue</option><option value="#FFA12F">Orange</option><option value="#06C56A">Green</option><option value="#F72D00">Red</option></select><script type=text/javascript>$("#categoryColorPicker_'+row+' option[value=\''+dataContext.stateCategoryColor+'\']").attr("selected","selected");$(".categoryColorPicker").simplecolorpicker({picker: true, theme: "glyphicons"});</script>';
}
function singleSelectBoxFormatter(row, cell, value, columnDef, dataContext) {
    return '<select id="cell_'+columnDef.id+'"><option>--choose--</option></select>';
}
$(function(){
    if($("#moduleId").val()==19){
        $(document).ready(checkContainer);
        function checkContainer () {
            if ($('#cell_requestFormatId').is(':visible')) {
                $("#cell_requestFormatId").select2({
                    placeholder: 'choose',
                    allowClear: false
                });
                $("#cell_requestFormatId").on("select2:open", function()
                {
                    loadSingleSelectOption("requestFormatId");
                });
            } else {
                setTimeout(checkContainer, 100);
            }
        }
    }
});
function getGridSlickColumnAttribute(columnID, columnName, width, cssClass, title, sortable, elementId, editorAttribute, columnType, columnAttributes, enableColumnReorder,isMandatory) {
    var slickGridColumnAttribute = initializeSlickGridColumns();
    var selectedSlickGrid;
    slickGridColumnAttribute.id = columnID;
    slickGridColumnAttribute.field = columnID;
    slickGridColumnAttribute.name = columnName;
    slickGridColumnAttribute.title = columnName;
    slickGridColumnAttribute.width = width;
    slickGridColumnAttribute.cssClass = cssClass;
    slickGridColumnAttribute.toolTip = columnName;
    slickGridColumnAttribute.elementId = elementId;
    slickGridColumnAttribute.formatter = slickGridCellCustomFormatter;
    slickGridColumnAttribute.columnType = columnType;
    slickGridColumnAttribute.isMandatory = isMandatory;
    if (enableColumnReorder != null && enableColumnReorder != undefined) {
        slickGridColumnAttribute.enableColumnReorder = false;
    }
    if (sortable !== undefined && sortable !== "") {
        slickGridColumnAttribute.sortable = sortable;
        slickGridColumnAttribute.selectable = sortable;
        if (sortable == false)
            slickGridColumnAttribute.behavior = null;
    }
    if (editorAttribute != null && editorAttribute != "" && editorAttribute != undefined) {

        slickGridColumnAttribute.editor = editorAttribute["editor"];

        if (editorAttribute["validator"] != undefined) {
            slickGridColumnAttribute.validator = editorAttribute["validator"];
        }
        if (editorAttribute["formatter"] != undefined) {
            slickGridColumnAttribute.formatter = editorAttribute["formatter"];
        } else {
            slickGridColumnAttribute.formatter = slickGridCellCustomFormatter;
        }
    } else {
        slickGridColumnAttribute.formatter = slickGridCellCustomFormatter;

    }
    if (columnType != undefined && columnType != "" && columnType == "2") {
        slickGridColumnAttribute.dataSource = additionalFieldGridSelectBoxData;
    }
    if (columnAttributes != null && columnAttributes != undefined) {
        slickGridColumnAttribute.columnAttributes = columnAttributes;
    }
    selectedSlickGrid = slickGridColumnAttribute;
    return selectedSlickGrid;
}
function initializeSlickGridColumns() {
    var slickGridColumnAttribute = {
        id: "1",
        name: "",
        width: 20,
        behavior: "selectAndMove",
        selectable: true,
        resizable: true,
        cssClass: "attachIco",
        elementId: "ticketGrid",
        title: "",
        field: "",
        dataSource: "",
        fullWidthRows: true,
        forceFitColumns: true,
        showHeaderRow: true,
        sortable: false,
        editor: Slick.Editors.Text,
        columnAttributes: 0,
        sortAsc: false,
        columnType: ""
    };
    return slickGridColumnAttribute;
}
function slickGridCellCustomFormatter(row, cell, value, columnDef, dataContext) {
    var cellText = value;
    if($(".gridViewPort--main").attr("id")=="SubCategoryGridBlock" && (columnDef.cssClass=="selectCell wgSingleSelectCell" || columnDef.cssClass=="selectCell subCategService") && value != undefined){
        if(value[0].id != undefined && !isNaN(value[0].id)){
            cellText ='<span data-select2-id="'+ value[0].id + '" data-select2-value="'+value[0].value+'">' + value[0].value + '</span>'
        }else{
            cellText ='<span data-select2-id="'+ value + '" data-select2-value="">' + value + '</span>'
        }
        if(columnDef.cssClass=="selectCell subCategService"){
            if (Array.isArray(value) && value.length > 0 && value[0].value !== undefined) {
              var labels = value.map(function(v) { return v.value; }).join(',');
			  var ids = value.map(function(v) { return v.id; }).join(',');
			  cellText = "<span title="+labels+" data-select2-value="+labels+">"+labels+"</span>";
            }
        }
    }
    else if(columnDef.cssClass=="selectCell priorityMatix"){
        cellText = '<span data-attr="priority'+dataContext[columnDef.field][0].urgencyKey +dataContext[columnDef.field][0].impactKey +'">' +dataContext[columnDef.field][0].selectedPriority + '</span>';
    }

    else if(columnDef.cssClass=="showDerivedFieldsPop"|| columnDef.cssClass=="showDerivedFieldsWorkflowPop"){
        if (cellText != undefined && cellText != "") {
            if (cellText.length <= 20) {
                cellText = '<span>' + cellText + '</span>';
            } else {
                cellText = '<a class="expandDerivedFields" style="width: 29px;height: 29px;display: inline-block;color: #333;font-size: 21px;background: #eaebee;text-align: center;left: -10px;top: -10px;position: relative;">+</a><span style="width:calc(100% - 30px);display: inline-block;overflow: hidden;text-overflow: ellipsis;">' + cellText + ' </span>';
            }
        }else{
            if (cellText == undefined || cellText == ""){
                cellText = '<span title="--"> -- </span>';
            }
        }
    }
    else if ((dataContext.natureOfChange != undefined || dataContext.changeDesc != undefined || dataContext.changeType != undefined || dataContext.numberOfDigits != undefined || dataContext.address != undefined || dataContext.comment != undefined || dataContext.cmdbdescription != undefined) && (columnDef.name.trim() === "Old Value" || columnDef.name.trim() === "New Value" || columnDef.name.trim() === "Change From" || columnDef.name.trim() === "Change To" || columnDef.name.trim() === "Address" || columnDef.name.trim() === "Comment" || columnDef.name.trim() === "Description")) {
        if (cellText != undefined && cellText != "") {
            if (cellText.length <= 20) {
                cellText = '<span>' + cellText + '</span>';
            } else {
                cellText = '<div class="decr" style="display:inline;" >' + strip(cellText) + '</div><div id="decr" style="display:none;" >' + cellText + '</div><a href="javascript:void(0);" class="readMoreHistory plus showMore">' + i18n.tr("READ MORE") + '</a>';
            }
        }
    }
    else if (cellText == undefined || cellText == ""){
        cellText = '<span title="--"> -- </span>';
    } else {
        if (isNaN(cellText)) {
            if($("#WorkflowGridBlock").is(":visible")==true){
                if(columnDef.formatter.arguments[4].workflowId!=null){
                     if (cellText != undefined && cellText != "" && cellText.indexOf("<span") != 0) {
                        cellText = "<span title='" + value + "'>" + cellText + "</span>";
                    }
                }else{
                    if(columnDef.name=="Service" && $("#WorkflowGridBlock").is(":visible")==true){
                        value= $("#serviceValue").val();
                        cellText = "<span  title='" + value + "'>" + value + "</span>";
                    }else if(columnDef.name=="Sub Category" && $("#WorkflowGridBlock").is(":visible")==true){
                        value= $("#subCategoryValue").val();
                        cellText = "<span  title='" + value + "'>" + value + "</span>";
                    }
                }
            }else if (cellText != undefined && cellText != "" && cellText.indexOf("<span") != 0) {
                cellText = "<span title='" + value + "'>" + cellText + "</span>";
            }
        } else {
            if(columnDef.name=="Present State"){
                value= $("#presentStateValue").val();
                cellText = "<span  title='" + value + "'>" + value + "</span>";
            }else if(columnDef.name=="Possible State"){
                value= $("#possibleStateValue").val();
                cellText = "<span  title='" + value + "'>" + value + "</span>";
            }else if(columnDef.name=="Service" && $("#WorkflowGridBlock").is(":visible")==true){
                value= $("#serviceValue").val();
                cellText = "<span  title='" + value + "'>" + value + "</span>";
            }else if(columnDef.name=="Sub Category" && $("#WorkflowGridBlock").is(":visible")==true){
                value= $("#subCategoryValue").val();
                cellText = "<span  title='" + value + "'>" + value + "</span>";
            }else{
                cellText = "<span  title='" + value + "'>" + cellText + "</span>";
            }
        }

        if(columnDef.cssClass=="userSpecializationInfo"){
            cellText="";
        }
    }
    return cellText;
}
function CheckBoxFormatter(row, cell, value, columnDef, dataContext) {
    //return value == "Yes" || value == true ? "<img src='assets/images/tick.png'>" : "<img style='width:16px' src='assets/images/uncheck.png'>";
    if (value == "Yes" || value == true) {
        return "<img src='assets/images/tick.png'>";
    } else if (value == "--") {
        return "<span>--</span>";
    } else if(value == undefined && columnDef.field=="isParent"){
        return "<img src='assets/images/tick.png'>";
    }
    else {
        return "<img style='width:16px' src='assets/images/uncheck.png'>";
    }
}
function ToggleBtnFormatter(row, cell, value, columnDef, dataContext){
    if(value == "Active" || value == "Yes"){
        return '<div class="toggleBtn"><input type="checkbox" class="checkbox" value="Yes" checked><div class="btn-cover"><span></span></div><div class="layer"></div></div>';
    }else{
        return '<div class="toggleBtn"><input type="checkbox" class="checkbox" value="No"><div class="btn-cover"><span></span></div><div class="layer"></div></div>';
    }
}
function ImageSetterFormatter(row, cell, value, columnDef, dataContext) {
    if(value!="" && value!=undefined && value.indexOf("assets/images/ServiceCatalogue")>=0){
        return "<img id="+columnDef.field+" class='whiteImg' src='"+value+"'>";
    }if(value!="" && value!=undefined){
        return "<img id="+columnDef.field+" src='"+value+"'>";
    }else{
        return "<img id="+columnDef.field+" src='assets/images/imgAttachment.png'>";
    }
}
function simpleColorPicker(row, cell, value, columnDef, dataContext) {
    return '<select name="categoryColorPicker" class="categoryColorPicker" id="categoryColorPicker_'+row+'"><option value="#0F93EE" selected>Blue</option><option value="#FFA12F">Orange</option><option value="#06C56A">Green</option><option value="#F72D00">Red</option></select><script type=text/javascript>$("#categoryColorPicker_'+row+' option[value=\''+dataContext.stateCategoryColor+'\']").attr("selected","selected");$(".categoryColorPicker").simplecolorpicker({picker: true, theme: "glyphicons"});</script>';
}
function jsColorPicker(row, cell, value, columnDef, dataContext) {
    return "<span id="+columnDef.field+" style='background-color:"+value+"'></span>";
}
function disableNextOrPrevPagingSelection(pagerId) {
    var totalPages = $("div#" + pagerId).attr("data-totalPages");
    var currentPage = $("div#" + pagerId).attr("data-pageno");
    var isNextToDisable = false;
    var isPrevToDisable = false;
    var isFirstToDisable = false;
    var isLastToDisable = false;
    if (totalPages <= (parseInt(currentPage))) {
        isNextToDisable = true;
    }
    if ((parseInt(currentPage) - 1) <= 0) {
        isPrevToDisable = true;
    }
    if (parseInt(currentPage) == 1 || parseInt(totalPages) == 0) {
        isFirstToDisable = true;
    }
    if ((parseInt(currentPage) >= parseInt(totalPages) || parseInt(totalPages) == 0)) {
        isLastToDisable = true;
    }
    if (isNextToDisable) {
        if (!$("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-next").hasClass()) {
            $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-next").addClass("disabled ui-state-disabled");
        }
    } else {
        $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-next").removeClass("disabled ui-state-disabled");
    }
    if (isPrevToDisable) {
        if (!$("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-prev").hasClass()) {
            $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-prev").addClass("disabled ui-state-disabled");
        }
    } else {
        $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-prev").removeClass("disabled ui-state-disabled");
    }
    if (isFirstToDisable) {
        if (!$("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-first").hasClass()) {
            $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-first").addClass("disabled ui-state-disabled");
        }
    } else {
        $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-first").removeClass("disabled ui-state-disabled");
    }
    if (isLastToDisable) {
        if (!$("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-end").hasClass()) {
            $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-end").addClass("disabled ui-state-disabled");
        }
    } else {
        $("div#" + pagerId + " div.slick-pager-nav span.ui-state-default span.ui-icon-seek-end").removeClass("disabled ui-state-disabled");
    }
}
function addNewList(gridId) {
    if($("#commonValidAlert").is(":visible")==false){
        var gridSlick = $("#" + gridId).data("gridInstance1");
        gridSlick.getEditorLock().commitCurrentEdit();
        var dynamicRowValueAttributes = new Object();
        var data = gridSlick.getData();
        var currRowNum = 1;
        if (!gridSlick.getActiveCell()) {
            currRowNum = gridSlick.getDataLength();
        } else {
            currRowNum = gridSlick.getDataLength();
        }
        var newrow = jQuery.extend(dynamicRowValueAttributes, data[currRowNum]);
        var position = (currRowNum + 1);
        data.splice(position, 0, newrow);
        gridSlick.setData(data);
        var prevHeight = $("#"+gridId).css("min-height");
        var newHeight = prevHeight.replace("px","");
        newHeight = parseInt(newHeight)+30;
        $("#"+gridId).css("min-height", newHeight+"px");
        gridSlick.resizeCanvas();
        var rowtest=gridSlick.getData();
        $.each(data, function (key, grid) {
            var currentRow=key+1;
            var parentData;
            var rowData = new Object();
            if(grid.isChild=="No" && grid.parentService==""){
                $("#listingGrid .slick-row:nth-child("+currentRow+") .slick-cell:nth-child(10)").addClass("disabled");
            }
        });
        $.each(rowtest, function (index) {
            var isPreshipped=rowtest[index].isPreshipped;
            if(isPreshipped){
                index++;
                $(".slick-row:nth-child("+ index +") .slick-cell.slick-cell-checkboxsel").addClass("disabled");
                $(".slick-row:nth-child("+ index +")  .slick-cell.slick-cell-checkboxsel input[type=checkbox]").remove();
            }
        });
        if($("#moduleId").val()==5 || $("#moduleId").val()==6){
            $.each(rowtest, function (index) {
                var isInActive=rowtest[index].status;
                if(isInActive=="Not Active"){
                    index++;
                    $("#listingGrid .slick-row:nth-child("+index+") .slick-cell:not(.slick-cell-checkboxsel):not(.toggleCell)").addClass("disabled");
                }
            });
        }
        triggerMandatoryfield(gridId,gridSlick);
        setTimeout(function(){
            $("#listingGrid .slick-row:nth-child("+position+") .slick-cell.ckEditorCol").addClass("ckeditorClickRestricted");
        },500);
    }
    else{
        $(".redAlert").focus();
    }
}
auditLog = function(projectId, moduleId, pageSize, pageNo,columnSort,sortDir){
    $("#auditLogListingGrid").removeClass("disableSorting");
    if(columnSort==undefined)
        columnSort="";
    if(sortDir==undefined)
        sortDir="";
    columntest=[];
    $(".gridViewPort--main").slideUp();
    $(".gridViewPort--auditLog").slideDown();
    var gridData;
    var jsonContent;
    if(pageNo == undefined){
        pageNo = $("#auditLogListingGridPager").attr("data-pageno");
        if(pageNo == undefined){
            pageNo = 1;
        }
    }
    if(pageSize == undefined){
        pageSize = $("#logRecordLimit"+moduleId+"[name='logRecordLimit"+moduleId+"']").val();
        if(pageSize == undefined){
            pageSize = 10;
        }
    }
    
    $.ajax({
        url: "getJSONAuditRecords.do",
        type: "POST",
        dataType: 'json',
        async: false,
        data: "projectId="+projectId+"&pageSize="+pageSize+"&pageNo="+pageNo+"&moduleId="+moduleId+"&columnSort="+columnSort+"&sortDir="+sortDir,
        success: function (result) {
            jsonContent = result;
            for (var i = 0; i < jsonContent.header.length; i++) {
                columntest.push(getGridSlickColumnAttribute(jsonContent.header[i].id, jsonContent.header[i].name, jsonContent.header[i].minWidth, jsonContent.header[i].cssClass, "", true, "", getEditorBasedonColumnType(jsonContent.header[i].editor, ""), "1", "",false,jsonContent.header[i].isMandatory));
            }
            var rowtest = [];
            var columnNames = [];
            $.each(jsonContent.rows, function (key, grid) {
                var i = 0;
                var rowData = new Object();
                $.each(grid, function (key, gridField) {
                    if (gridField === "true") {
                        gridField = true;
                    } else if (gridField === "false") {
                        gridField = false;
                    }
                    rowData [key] = gridField;
                    if (i == 0)
                        columnNames.push(key);
                });
                rowtest.push(rowData);
            });
            gridData = new Slick.Grid("#auditLogListingGrid", rowtest, columntest, unEditableGridOptions);
            $("#auditLogListingGrid").data("gridInstance1", gridData);
            $("#auditLogListingGrid").data("gridInstance1").getEditorLock().cancelCurrentEdit();
            gridData.render();
            var totalHt=(rowtest.length+1)*30;
            $("#auditLogListingGrid").css("min-height", totalHt+"px");
            var auditGrid=$("#auditLogListingGrid").data("gridInstance1");
            auditGrid.resizeCanvas();
            var dataView = new Slick.Data.DataView();
            dataView.setPagingOptions({
                pageNum: jsonContent.pageNo,
                pageSize: jsonContent.pageSize,
                totalPages: jsonContent.NoOfPages,
                totalRows: jsonContent.TotalRecords,
                testRun: 5
            });
            var pager = new Slick.Controls.Pager(dataView, gridData, $("#auditLogListingGridPager"));
            $("#auditLogListingGridPager").attr("data-totalrecords", "" + jsonContent.TotalRecords);
            $("#auditLogListingGridPager").attr("data-totalpages", "" + jsonContent.NoOfPages);
            $("#auditLogListingGridPager").attr("data-pageno", "" + jsonContent.pageNo);
            $("#auditLogListingGridPager").find(".slick-pager .slick-pager-status input[type='text']").attr("title", jsonContent.pageNo);
            disableNextOrPrevPagingSelection("auditLogListingGridPager");
            $("#auditLogListingGridPager #pageTotalPageNumber").html(jsonContent.NoOfPages);
            $("#auditLogListingGridPager").siblings(".rightPagn").find("#slickGridRecordInfo2").html("Displaying records " + jsonContent.startPoint + " - " + jsonContent.endpoint + " of " + jsonContent.TotalRecords);
            $("#auditLogListingGrid").perfectScrollbar();
        },complete:function(){
            var isGridLoaded=setInterval(function(){
                if($("#auditLogListingGrid").is(":visible")){
             var auditLogListingGrid=$("#auditLogListingGrid").data("gridInstance1");
            auditLogListingGrid.resizeCanvas();
                    clearInterval(isGridLoaded);
                }
            },100)
        }});
    
    gridData.onSort.subscribe(function (e, args) {
        console.log("subscribe");
        if ( ! $("#listingGrid").hasClass("disableSorting") )
        {
            var cols = args.sortCols;
            var field = cols[0].sortCol.field;
            var sign = "";
            for (var i = 0; i < cols.length; i++)
            {
                if(cols[i].sortAsc){
                    sign="ASC"
                }
                else{
                    sign="DESC";
                }
            }
            activeSortOrder=sign;
            activeSortColumn=field;
            var projectId=$("#projectId").val();
            var moduleId=$("#moduleId").val();
            var pageNo=$("#auditLogListingGridPager").attr("data-pageno");
            var pageSize=$(".gridViewPort .recordLimit").val();
            $("#auditLogListingGrid").addClass("disableSorting");
            auditLog(projectId,moduleId,pageSize,pageNo,field,sign);
            setBackGridSortColumn(field,sign,"auditLogListingGrid");
        }
        return 0;
    });

}
$(function() {
    $(document).on("change", "input[name='headerCheck']", function (e)
    {
        var parentId = $(this).closest(".ui-widget").attr("id");
        if ($("#"+parentId+" input[name='headerCheck']").prop('checked') == true)
        {
            $("#" + parentId + " .slick-cell-checkboxsel input[type='checkbox'][disabled!='disabled']").prop("checked", true);
        } else
        {
            $("#" + parentId + " .slick-cell-checkboxsel input[type='checkbox'][disabled!='disabled']").prop("checked", false);
        }
        e.stopImmediatePropagation();
    });
    $(document).on( "change" , ".ui-widget input[type='checkbox']", function (e)
    {
        var parentId = $(this).closest(".ui-widget").attr("id");
        var isAllchecked = true;
        $("#"+parentId+" input[type='checkbox'][name!='headerCheck'][disabled!='disabled']").each(function ()
        {
            if ( isAllchecked )
            {
                if ( $(this).prop("checked") != true )
                {
                    $("#"+parentId+" input[name='headerCheck']").prop('checked', false);
                    isAllchecked = false;
                }
            }
        } );
        if ( isAllchecked)
        {
            $("#"+parentId+" input[name='headerCheck']").prop('checked', true);
        }

    });
});
downloadExcelReport = function(projectId, moduleId){
    var searchCriteria = "";
    if(moduleId == 2){
        searchCriteria = "&searchCriteria="+$("#userAttributes").val();
    }
    window.location = "GenerateExcelReport?moduleId=" + moduleId + "&projectId="+projectId+searchCriteria+"&columnToSort="+activeSortColumn+"&sortDir="+activeSortOrder;
}
downloadExcelReportforDerivedFields = function(projectId, moduleId, type){
    window.location = "GenerateExcelReport?moduleId=" + moduleId + "&projectId="+projectId+"&type="+type+"&columnToSort="+activeSortColumn+"&sortDir="+activeSortOrder;
}
downloadAuditLogExcelReport = function(projectId, moduleId){
    window.location = "GenerateExcelReport?moduleId=" + moduleId + "&projectId="+projectId+"&auditLog=yes&columnToSort="+activeSortColumn+"&sortDir="+activeSortOrder;
}
changePagination = function(projectId, moduleId){
    var pageNo = $("#listingGridPager").attr("data-pageno");
    var pageSize = $("#recordLimit"+moduleId+"[name='recordLimit"+moduleId+"']").val();
    setPaginationCountForGrid(pageSize);
    $("#logRecordLimit"+moduleId+"[name='logRecordLimit"+moduleId+"']").val(pageSize);
    $("#logRecordLimit"+moduleId+" option[value='"+pageSize+"']").attr('selected','true');
    $('#logRecordLimit'+moduleId).multipleSelect('refresh');
    $("#licenUserListLimit[name='licenUserListLimit']").val(pageSize);
    $("#licenUserListLimit option[value='"+pageSize+"']").attr('selected','true');
    $('#licenUserListLimit').multipleSelect('refresh');
    loadSdGridData(projectId, moduleId,1,pageSize,activeSortColumn,activeSortOrder);
}
changeAuditPagination = function(projectId, moduleId){
    var pageNo = 1;
    var pageSize = $("#logRecordLimit"+moduleId+"[name='logRecordLimit"+moduleId+"']").val();
    setPaginationCountForGrid(pageSize);
    $("#logRecordLimit"+moduleId+"[name='logRecordLimit"+moduleId+"']").val(pageSize);
    $("#logRecordLimit"+moduleId+" option[value='"+pageSize+"']").attr('selected','true');
    $('#logRecordLimit'+moduleId).multipleSelect('refresh');
    $("#recordLimit"+moduleId+"[name='recordLimit"+moduleId+"']").val(pageSize);
    $("#recordLimit"+moduleId+" option[value='"+pageSize+"']").attr('selected','true');
    $('#recordLimit'+moduleId).multipleSelect('refresh');
    auditLog(projectId, moduleId, pageSize, pageNo);
}
changeLicenseUserPagination = function(projectId, moduleId){
    var pageNo = $("#licenUserListingGridPager").attr("data-pageno");
    var pageSize = $("#licenUserListLimit[name='licenUserListLimit']").val();
    setPaginationCountForGrid(pageSize);
    $("#recordLimit"+moduleId+"[name='recordLimit"+moduleId+"']").val(pageSize);
    $("#recordLimit"+moduleId+" option[value='"+pageSize+"']").attr('selected','true');
    $('#recordLimit'+moduleId).multipleSelect('refresh');
    $("#licenUserListLimit[name='licenUserListLimit']").val(pageSize);
    $("#licenUserListLimit option[value='"+pageSize+"']").attr('selected','true');
    showLicenseUser(projectId, moduleId,pageSize,pageNo);
}
setPaginationCountForGrid =function(pageSize){
    $.ajax({
        url: 'setPaginationCount.do',
        type: "POST",
        data: 'paginationCount='+pageSize
    });
}
setSdGridPaginationCount= function(paginationCount,id){
    var option = "";
    $('#'+id).empty();
    for(var i=10;i<=100;i=i+10){
        if( option === ""){
            if( paginationCount == i ){
                option = "<option value="+i+" selected>"+i+"</>";
            }else{
                option = "<option value="+i+">"+i+"</>";
            }
        }else{
            if( paginationCount == i ){
                option += "<option value="+i+" selected>"+i+"</>";
            }else{
                option += "<option value="+i+">"+i+"</>";
            }
        }
    }
    $('#'+id).append(option);
    $('#'+id).multipleSelect('refresh');
}
var activeSortColumn="";
var activeSortOrder="";
loadSdGridData = function(projectId, moduleId,pageNo,pageSize,sortColumn,sortDir) {
    $("#listingGrid").removeClass("disableSorting");
    if(pageNo == undefined){
        pageNo  = 1;
    }
    if (sortColumn === undefined || sortColumn === "") {
        activeSortColumn = "";
        activeSortOrder = "";
    }
    if(sortColumn==undefined)
        sortColumn="";
    if(sortDir==undefined)
        sortDir="";
    if(pageSize == undefined){
        pageSize = $("#recordLimit"+moduleId+"[name='recordLimit"+moduleId+"']").val();
        if(pageSize == undefined){
            pageSize = 10;
        }
    }
    var appendURL = "";
    if(moduleId == 2 && !$("div.gridViewPort.gridViewPort--licenUserList").is(":visible")){
        var roleId = $("#roles").val();
        var userSearch = $("#userSearch").val();
        var userAttributes = $("#userAttributes").val();
        appendURL = "&roleID="+roleId+"&searchCriteria="+userAttributes+"&searchText="+userSearch;
    }
    if(moduleId == 15){
        var serviceId=$("#serviceList").val();
        appendURL="&serviceId="+serviceId;
    }
    columntest=[];
    $(".gridViewPort--auditLog").slideUp();
    if(!$("div.gridViewPort.gridViewPort--licenUserList").is(":visible")){
        $(".gridViewPort--main").slideDown();
    }
    var gridData;
    var jsonContent;
    $.ajax({
        url: "getJSONListingRecords.do",
        type: "POST",
        dataType: 'json',
        async: false,
        data: "projectId="+$("#projectId").val()+"&pageSize="+pageSize+"&pageNo="+pageNo+"&moduleId="+moduleId+appendURL+"&columnToSort="+sortColumn+"&sortDirection="+sortDir,
        success: function (result) {
            jsonContent = result;
        },complete:function(){
            if (moduleId == 1) {
                var checkboxSelector = new Slick.CheckboxSelectColumn({
                    cssClass: "slick-cell-checkboxsel",
                    elementId: "rolesListcheckbox"
                });
                columntest.push(checkboxSelector.getColumnDefinition());
            }else if(moduleId != 19 && moduleId!=15) {
                var checkboxSelector = new Slick.CheckboxSelectColumn({
                    cssClass: "slick-cell-checkboxsel",
                    elementId: moduleId + "_checkbox"
                });
                columntest.push(checkboxSelector.getColumnDefinition());
            }
            for (var i = 0; i < jsonContent.header.length; i++) {
                columntest.push(getGridSlickColumnAttribute(jsonContent.header[i].id, jsonContent.header[i].name, jsonContent.header[i].minWidth, jsonContent.header[i].cssClass, "", jsonContent.header[i].sortable, "", getEditorBasedonColumnType(jsonContent.header[i].editor, ""), "1", "",false,jsonContent.header[i].isMandatory));
            }
            var rowtest = [];
            inActiveRow=[];
            var parentDisabledRow = [];
            $.each(jsonContent.rows, function (key, grid) {
                var currentRow=key+1;
                var parentData = false;
                var rowData = new Object();
                if(grid.isChild === "No" && grid.parentService === ""){
                    parentDisabledRow.push(currentRow);
                }
                if(grid.status === "Not Active" && (moduleId == 5 || moduleId == 6 || moduleId == 7) ){
                    inActiveRow.push(currentRow);
                }
                $.each(grid, function (key, gridField) {
                    rowData [key] = gridField;
                });
                rowtest.push(rowData);
            });
            if($("#moduleId").val()=="3"){
                editableGridOptions.frozenColumn=2;
                editableGridOptions.forceFitColumns=false;
            }
            gridData = new Slick.Grid("#listingGrid", rowtest, columntest, editableGridOptions);
            $("#listingGrid").data("gridInstance1", gridData);
            $("#listingGrid").data("gridInstance1").getEditorLock().cancelCurrentEdit();

            $.each(rowtest, function (index) {
                var isPreshipped=rowtest[index].isPreshipped;
                if(isPreshipped){
                    index++;
                    $(".slick-row:nth-child("+ index +") .slick-cell.slick-cell-checkboxsel").addClass("disabled");
                    $(".slick-row:nth-child("+ index +")  .slick-cell.slick-cell-checkboxsel input[type=checkbox]").remove();
                }
            });
            gridData.onCellChange.subscribe(function (e, args) {
                var gridSlick = $("#listingGrid").data("gridInstance1");
                var dataToSave=gridSlick.getDataItem(args.row);
                var field = gridSlick.getColumns()[args.cell].field;
                var projectId=$("#projectId").val();
                var moduleId=$("#moduleId").val();
                if(moduleId == 19){
                    saveRecordFormatDetails(dataToSave.requestFormatId, field, projectId, dataToSave[field]);
                }else if(moduleId == 11){
                    saveSourceParameters(dataToSave.sourceId, field, projectId, dataToSave[field]);
                }else if(moduleId == 6){
                    saveCategoryDetails(dataToSave.categoryId, field, projectId, dataToSave[field]);
                }else if(moduleId == 5){
                    var isChild=dataToSave["isChild"];
                    var isParent=dataToSave["isParent"];
                    if(field=="isParent" && dataToSave[field]==false && isChild=="No") {
                        $('#ServiceGridBlock').append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>Check atleast one option for service type <br> (Parent, Child)</p>');
                        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".checkMarkCell.active",collision: "none"});
                        $('#commonValidAlert').show();
                        return false;
                    }else if(field=="isChild" && dataToSave[field]==false && (isParent==false || isParent=="No")) {
                        $('#ServiceGridBlock').append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>Check atleast one option for service type <br> (Parent, Child)</p>');
                        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".checkMarkCell.active",collision: "none"});
                        $('#commonValidAlert').show();
                        return false;
                    }
                    else{
                        saveServiceDetails(dataToSave.serviceId, field, projectId,dataToSave[field],args.item.parentService,args.item.isChild);
                    }
                }else if(moduleId == 4){
                    saveSpecializationDetails(dataToSave.specializationId, field, projectId, dataToSave[field]);
                }else if(moduleId == 1){
                    saveRolesDetails(dataToSave.rolesId, field, projectId, dataToSave[field]);
                }else if(moduleId == 12){
                    saveUIPDetails(dataToSave.uipId, field, projectId, dataToSave[field], 1);
                }else if(moduleId == 13){
                    saveUIPDetails(dataToSave.uipId, field, projectId, dataToSave[field], 2);
                }else if(moduleId == 14){
                    saveUIPDetails(dataToSave.uipId, field, projectId, dataToSave[field], 3);
                }else if(moduleId == 25){
                    saveSlaComment(dataToSave.slaCommentId, field, projectId, dataToSave[field]);
                }else if(moduleId == 3){
                    saveWorkgroupDetails(dataToSave.workgroupId, field, projectId, dataToSave[field]);
                }else if(moduleId == 8){
                    SaveStateCategory(dataToSave.stateCategoryId, field, projectId, dataToSave[field]);
                }
                else if(moduleId == 10){
                    saveWorkFlowDetails(dataToSave.workflowId, field, projectId, dataToSave);
                }
                else if(moduleId == 9){
                    saveStatesDetails(dataToSave.statesId, field, projectId, dataToSave[field]);
                }
                else if(moduleId == 7){
                    saveSubCategoryDetails(dataToSave.subCategoryId, field, projectId, dataToSave);
                }
                else if(moduleId == 15){
                    savePriorityMatrixDetails(projectId, dataToSave[field]);
                }else if(moduleId == 42){
                    saveTemplateDetails(dataToSave.templateId, field, projectId, dataToSave[field], 2);
                }
            });
gridData.onSort.subscribe(function (e, args) {
    console.log("subscribe");
        if ( ! $("#listingGrid").hasClass("disableSorting") )
        {
            var cols = args.sortCols;
            var field = cols[0].sortCol.field;
            var sign = "";
            for (var i = 0; i < cols.length; i++)
            {
                if(cols[i].sortAsc){
                	sign="ASC"
                }
                else{
                	sign="DESC";
                }
            }
            activeSortOrder=sign;
            activeSortColumn=field;
            var projectId=$("#projectId").val();
            var moduleId=$("#moduleId").val();
            var pageNo=$("#listingGridPager").attr("data-pageno");
            var pageSize=$(".gridViewPort .recordLimit").val();
            $("#listingGrid").addClass("disableSorting");
            loadSdGridData(projectId,moduleId,pageNo,pageSize,field,sign);
        setBackGridSortColumn(field,sign,"listingGrid");
        }
        return 0;
    });
            gridData.render();
            var totalHt=(rowtest.length+1)*30;
            $("#listingGrid").css("min-height", totalHt+"px");
            var listingGrid=$("#listingGrid").data("gridInstance1");
            listingGrid.resizeCanvas();
            if(parentDisabledRow!=""){
                for( var i=0;i<parentDisabledRow.length;i++){
                    $("#listingGrid .slick-row:nth-child("+parentDisabledRow[i]+") .slick-cell:nth-child(10)").addClass("disabled");
                }
            }
            if(inActiveRow!=""){
                for( var i=0;i<inActiveRow.length;i++){
                    $("#listingGrid .slick-row:nth-child("+inActiveRow[i]+") .slick-cell:not(.slick-cell-checkboxsel):not(.toggleCell)").addClass("disabled");
                }
            }
            var dataView = new Slick.Data.DataView();
            dataView.setPagingOptions({pageNum: jsonContent.pageNo, pageSize: jsonContent.pageSize, totalPages: jsonContent.NoOfPages, totalRows:jsonContent.TotalRecords, testRun: 5});
            var pager = new Slick.Controls.Pager(dataView, gridData, $("#listingGridPager"));
            $("#listingGridPager").attr("data-totalrecords",""+jsonContent.TotalRecords);
            $("#listingGridPager").attr("data-totalpages",""+jsonContent.NoOfPages);
            $("#listingGridPager").attr("data-pageno",""+jsonContent.pageNo);
            $("#listingGridPager").find(".slick-pager .slick-pager-status input[type='text']").attr("title", jsonContent.pageNo);
            disableNextOrPrevPagingSelection("listingGridPager");
            $("#listingGridPager #pageTotalPageNumber").html(jsonContent.NoOfPages);
            $("#listingGridPager").siblings("div.rightPagn").find("#slickGridRecordInfo").html("Displaying records "+jsonContent.startPoint+" - "+jsonContent.endpoint+" of "+jsonContent.TotalRecords);
            $(".slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
            if($("#moduleId").val()=="3"){
                $(".slick-viewport.slick-viewport-top.slick-viewport-right").perfectScrollbar();

            var gridViewport = $('.slick-viewport');

            gridViewport.on('scroll', function () {
              if ($('.select2-container--open').length) {
                $('ul.select2-results__options').hide();
            }
            });
            }
            if($("#moduleId").val()=="2"){
                $(".userSpecializationInfo").attr("title","Specialization");
        }
        }
    });
    if(sortColumn==""){
        var columnCount=2;
        if(moduleId==2){
            columnCount=3;
}
        $(".slick-header-column:nth-child("+columnCount+") .slick-sort-indicator").addClass("slick-sort-indicator-asc");
    }
    else if(sortDir=="ASC"){
        $(".slick-header-column[id$='"+sortColumn+"'] .slick-sort-indicator").addClass("slick-sort-indicator-asc");
    }else{
        $(".slick-header-column[id$='"+sortColumn+"'] .slick-sort-indicator").addClass("slick-sort-indicator-desc");
    }
}
switchtoListing = function(){
    $(".gridViewPort.gridViewPort--auditLog").hide();
    $(".gridViewPort.gridViewPort--main").show();
}
$(document).on("mouseup",function(e){
    console.log("common alert visible="+$("#commonValidAlert").is(":visible"));
    console.log('Event target:', e.target);
    console.log('Event target class:', e.target.className);
    console.log("e target ="+$(e.target).is(".slick-cell.active,.slick-cell.active *,.select2-container--open,.select2-container--open *,.gridViewPort.gridViewPort--main") );
    if(!$(e.target).is(".slick-cell.active,.slick-cell.active *,.select2-container--open,.select2-container--open *,gridViewPort.gridViewPort--main") && $("#commonValidAlert").is(":visible")==false){
        console.log("Derived Field grid block is visible ="+$("#DerivedFieldGridBlock").is(":visible"));
        if($("#DerivedFieldGridBlock").is(":visible")==true){
            $('#derivedFieldListingGrid').data("gridInstance1").getEditorLock().commitCurrentEdit();
        }else{
        	var selectedOption=[];
        	var activecell;
            $("#requiredField").remove();
            $(".gridViewPort--main .gridActionLeftBlk").css("pointer-events","auto");
            if($("#SubCategoryGridBlock").is(":visible")==true){
                if($(".subCategService.active").length==1){
                    var bound=$(".subCategService.active #service option:selected").length
					for (var index = 0; index < bound; index++) {
					    selectedOption[index]=$(".subCategService.active #service option:selected")[index].text;
					}
					var currGrid=$('#listingGrid').data("gridInstance1");
					activecell=currGrid.getActiveCell()
                }
            }
            $('#listingGrid').data("gridInstance1").getEditorLock().commitCurrentEdit();
             if($("#SubCategoryGridBlock").is(":visible")==true){
             	if(selectedOption!=""){
             		var row=activecell.row + 1;
             		var cell=activecell.cell +1;
             		$(".slick-row:nth-child("+row+") .slick-cell:nth-child("+cell+")").text(selectedOption.join());
             	}
             }
        }
    }
});
triggerMandatoryfield = function(gridId,gridData){
    var gridSlick = $("#"+gridId).data("gridInstance1");
    var field = gridSlick.getColumns().length;
    var rowNumber=$(".slick-row:last").index();
    var isMandatoryCol = gridSlick.getColumns()[1].isMandatory;
    var moduleId = $("#moduleId").val();
    if(isMandatoryCol) {
        if(moduleId==10){
            gridSlick.gotoCell(rowNumber, 5, "true");
        }else {
            gridSlick.gotoCell(rowNumber, 1, "true");
            // $(".slick-row:last .slick-cell:nth-child(2)").addClass("validating mandatory").attr("data-mandatory","true");
            // $(".gridViewPort--main .gridActionLeftBlk").css("pointer-events","none");
        }
    }
}
$(document).on("click",".readMoreHistory",function(e) {
    if($(this).hasClass("opened")==true){
        $("#readMoreAuditBlk").hide();
        $(this).removeClass("opened");
    }else {
        $(".readMoreHistory").removeClass("opened");
        $(this).addClass("opened");
        var moreData = $(this).prev("#decr").html();
        $("#readMoreAuditBlk .loadedData").empty().append(moreData);
        $("#readMoreAuditBlk").show();
        $("#readMoreAuditBlk").position({
            my: "center+30 top",
            at: "left top+20",
            of: ".readMoreHistory.opened",
            collision: "none"
        });
    }
});
$(document).on("click",function(e){
    if(!$(e.target).is(".readMoreHistory,.readMoreHistory *,#readMoreAuditBlk,#readMoreAuditBlk *")){
        $("#readMoreAuditBlk").hide();
        $(".readMoreHistory").removeClass("opened");
    }
});
$(document).on("click", "a#deleteRowIco", function() {
    if($("#commonValidAlert").is(":visible")==false){
        $("#ConfirmationBlk").remove();
        if ($('input[name=check]:checked').length == 0) {
            $("#listingGrid").before('<div id="ConfirmationBlk" class="confirmBlk"><p>Please select at least one row <a href="javascript:void(0)" id="hideAlertBox" class="yesBtn">OK</a></p></div>');
			 $("#ConfirmationBlk").slideDown(300, "easeInOutExpo");
            return;
        }else{
            //    $(".alertMsg").css("display","block");
            $("#listingGrid").before('<div id="ConfirmationBlk" class="confirmBlk" style="display: block;"><p>Do you really want to delete the selected record(s) ? <a href="javascript:void(0)" id="ConfirmDeleteBtn" class="yesBtn">Yes</a><a href="javascript:void(0)" id="hideAlertBox" class="noBtn">No</a></p></div>');
        }
    }else{
        $(".redAlert").focus();
    }
});
$(document).on("click","#hideAlertBox",function(){
    $("#ConfirmationBlk").slideUp().remove();
    $('input[name=check]:checked').prop("checked",false);
});
$(document).on("click","#ConfirmDeleteBtn",function(){
    var moduleId = $("a#deleteRowIco").attr("data-moduleId");
    var projectId = $("a#deleteRowIco").attr("data-projectId");
    var checkboxValues = [];
    $('input[name=check]:checked').map(function () {
        checkboxValues.push($(this).val());
    });
    if (moduleId == 5) {
        deleteSdService(checkboxValues, projectId);
    } else if (moduleId == 6) {
        //  deleteSdCategory(checkboxValues, projectId);
    } else if (moduleId == 4) {
        deleteSdSpecialization(checkboxValues, projectId);
    } else if (moduleId == 11) {
        deleteSdSource(checkboxValues, projectId);
    } else if (moduleId == 1) {
        deleteSdRoles(checkboxValues, projectId);
    }else if (moduleId == 12) {
        deleteUIP(checkboxValues, projectId, 1);
    }else if (moduleId == 13) {
        deleteUIP(checkboxValues, projectId, 2);
    }else if (moduleId == 14) {
        deleteUIP(checkboxValues, projectId, 3);
    }else if (moduleId == 25) {
        deleteSLAComment(checkboxValues, projectId);
    }else if (moduleId == 3) {
        deleteWorkgroup(checkboxValues, projectId);
    }else if (moduleId == 8) {
        deleteStateCategory(checkboxValues, projectId);
    }else if (moduleId == 10) {
        deleteWorkflow(checkboxValues, projectId);
    }else if (moduleId == 42) {
        deletesdTemplate(checkboxValues, projectId);
    }else if (moduleId == 7){
        deletesubCategory(checkboxValues, projectId);
    }
    $("#ConfirmationBlk").slideUp().remove();
});
$(document).on("click", "a#noBtn", function(){
    $(".alertMsg").css("display","none");
});
$(document).on("keyup",".validating",function(){
    $(".fldErr").remove();
    validationAlertShown=false;
});
$(document).on("keyup",".mandatory",function(){
    $(".fldErr").remove();
    $(this).removeClass("mandatory");
    if($(this).find("input").val()==""){
        $(this).addClass("mandatory");
    }
});
$(document).on("mouseup",".slick-cell[data-mandatory=true]",function(){
    var checkFieldExisting=setInterval(function () {
        if ($(".slick-cell[data-mandatory=true]").find("input").length){
            if ($(".slick-cell[data-mandatory=true]").find("input").val() == "") {
                $(".slick-cell[data-mandatory=true]").addClass("mandatory validating");
            }else{
                $(".slick-cell[data-mandatory=true]").addClass("validating");
            }
            clearInterval(checkFieldExisting);
        }
    },100);
});
$(document).on("click", "#listingGridPager .ui-icon-seek-next:not(.disabled)", function (e)
{
    var pageNumber=$("#listingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)+1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    loadSdGridData(projectId,moduleId,nextPgNumber,pageSize,activeSortColumn,activeSortOrder);
    e.preventDefault();
});
$(document).on("click", "#listingGridPager .ui-icon-seek-prev:not(.disabled)", function (e)
{
    var pageNumber=$("#listingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)-1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    loadSdGridData(projectId,moduleId,nextPgNumber,pageSize,activeSortColumn,activeSortOrder);
    e.preventDefault();
});
$(document).on("click", "#listingGridPager .ui-icon-seek-end:not(.disabled)", function (e)
{
    $(this).addClass("disabled");
    var pageNumber=$("#listingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)-1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    var totalRecords=$("#listingGridPager").attr("data-totalrecords");
    var lastPageNumber=Math.ceil(totalRecords/pageSize);
    loadSdGridData(projectId,moduleId,lastPageNumber,pageSize,activeSortColumn,activeSortOrder);
    e.preventDefault();
});
$(document).on("click", "#listingGridPager .ui-icon-seek-first:not(.disabled)", function (e)
{
    $(this).addClass("disabled");
    var pageNumber=$("#listingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)-1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    loadSdGridData(projectId,moduleId,1,pageSize,activeSortColumn,activeSortOrder);
    e.preventDefault();
});

alertMandatoryFields= function(gridId,rowNumber,cellNumber){
    var gridSlick = $("#"+gridId).data("gridInstance1");
    var isMandatoryCol = gridSlick.getColumns()[cellNumber].isMandatory;
    if(isMandatoryCol==true) {
        var slickRowNo=rowNumber+1;
        var slickCellNo=cellNumber+1;
        if($(".slick-row:nth-child("+slickRowNo+") .slick-cell:nth-child("+slickCellNo+")").text()=="" || $(".slick-row:nth-child("+slickRowNo+") .slick-cell:nth-child("+slickCellNo+")").text()==" -- "){
            gridSlick.gotoCell(rowNumber, cellNumber, "true");
            $(".slick-row:nth-child("+slickRowNo+") .slick-cell:nth-child("+slickCellNo+")").addClass("validating mandatory").attr("data-mandatory","true");
            $(".gridViewPort--main .gridActionLeftBlk").css("pointer-events","none");
        }else{
            $(".slick-row .slick-cell").removeClass("validating mandatory").removeAttr("data-mandatory");
            $(".gridViewPort--main .gridActionLeftBlk").css("pointer-events","auto");
        }
    }
}
$(document).on("click", "#auditLogListingGridPager .ui-icon-seek-next:not(.disabled)", function (e)
{
    var pageNumber=$("#auditLogListingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)+1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    auditLog(projectId,moduleId,pageSize,nextPgNumber);
    e.preventDefault();
});
$(document).on("click", "#auditLogListingGridPager .ui-icon-seek-prev:not(.disabled)", function (e)
{
    var pageNumber=$("#auditLogListingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)-1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    auditLog(projectId,moduleId,pageSize,nextPgNumber);
    e.preventDefault();
});
$(document).on("click", "#auditLogListingGridPager .ui-icon-seek-end:not(.disabled)", function (e)
{
    $(this).addClass("disabled");
    var pageNumber=$("#auditLogListingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)+1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    var totalRecords=$("#auditLogListingGridPager").attr("data-totalrecords");
    var lastPageNumber=Math.ceil(totalRecords/pageSize);
    auditLog(projectId,moduleId,pageSize,lastPageNumber);
    e.preventDefault();
});
$(document).on("click", "#auditLogListingGridPager .ui-icon-seek-first:not(.disabled)", function (e)
{
    $(this).addClass("disabled");
    var pageNumber=$("#auditLogListingGridPager").attr("data-pageno");
    var pageSize=$(".gridViewPort .recordLimit").val();
    var nextPgNumber=parseInt(pageNumber)-1;
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
    auditLog(projectId,moduleId,pageSize,1);
    e.preventDefault();
});
var numberOfMacros = 0;
loadSingleSelectOption=function(fieldId){
    var moduleId = $("#moduleId").val();
    var projectId=$("#projectId").val();
    var $input;
    if(fieldId =="rolesInherit"){
        var projectId=$("#projectId").val();
        $.ajax({
            url: "getInheritFromList.do",
            type: "POST",
            dataType: 'json',
            async: false,
            data:"projectId="+projectId,
            success: function (result) {
                $(".select2-results__options").empty();
                $input.append("<option>--------choose----------</option>");
                for(var i=0;i<result.length;i++){
                    $input.append("<option id="+result[i]+" value='"+result[i]+"'>"+result[i]+"</option>");
                }
                $(".select2-results__options").append($input);
                $(".select2-results__options").multipleSelect('refresh');
            }
        });
    }
    if(fieldId =="requestFormatId"){
        var macroArray = [];
        $.ajax({
            url: "getMacrosList.do",
            type: "POST",
            dataType: 'json',
            async: false,
            data:"projectId="+projectId,
            success:function(result){
                numberOfMacros = 0;
                $input=$("#cell_requestFormatId");
                $(".select2-results__options").empty();
                $.each(result, function(key, value){
                    var optGroup="<optgroup label="+key.replaceAll(" ","&nbsp;")+">";
                    $.each(value, function(key1, value1){
                        $.each(value1, function(key2, value2){
                            optGroup+="<option id="+key2+" value='"+key2+"'>"+value2+"</option>";
                            macroArray.push(value2);
                        });
                    });
                    optGroup+="</optgroup>";
                    $input.append(optGroup);
                });
            }
        });
        var prefix= $(".cell-prefix").text();
        //var macroArray=["{Project}","{Service}","{Service Short Name}","{Category}","{Sub Category}","{Derived Field 1}","{Derived Field 2}","{Derived Field 3}","{Location}","{Department}","{Category Short Name}","{Sub-Category Short Name}","{Derived Field 1 Short Name}","{Derived Field 2 Short Name}","{Derived Field 3 Short Name}","{Location Short Name}","{Department Short Name}","{Urgency}","{Impact}","{Priority}","{DD}","{MM}","{YY}","{YYYY}","{Asset_Asset Number}","{Asset_Asset Type}","{Asset_Department}","{Asset_Extension No}","{Asset_Host Name}","{Asset_Location}","{Asset_Project}","{Asset_Site}","{Asset_Site Name}","{Asset_Status}","{Asset_System Name}","{Asset_User Name}"];
        var matches = prefix.match(/{[^}]+}/g);
        if (matches) {
            numberOfMacros = matches.length;
            }
    }
}
$(document).on("click", ".descriptionBlk .cancelDes", function () {
    var fieldName = getFieldName();
    $(".descriptionBlk #"+fieldName+",.descriptionBlk .saveDes,.descriptionBlk .cancelDes,.descriptionBlk .closeBlk").remove();
    CKEDITOR.instances[fieldName].destroy();
    $(".descBlkOverlay,.descriptionBlk").hide();
    $(".ckEditorCol").removeClass("clicked");
});
checkEmpty = function(FieldName, FieldValue, DisplayName, blockName){
    $('#commonValidAlert').remove();
    $(".slick-cell.active").removeClass("redAlert");
    if(blockName=="DerivedFieldGridBlock"){
        var grid =$('#derivedFieldListingGrid').data("gridInstance1");
    }else{
        var grid =$('#listingGrid').data("gridInstance1");
    }
    var row = grid.getActiveCell().row;
    var cell = grid.getActiveCell().cell;
    if(FieldValue.trim() == ""){
        grid.gotoCell(row, cell, true);
        $(".slick-cell.active input").addClass("redAlert");
        validationAlertShown=true;
        if(FieldName=="serviceName" || FieldName=="categoryName" || FieldName=="roleName" || FieldName=="specializationName"  || FieldName=="sourceName" || FieldName=="workGroupName" || FieldName=="comment" || FieldName=="subCategoryName"  || FieldName=="derivedFieldName"  || FieldName=="uipName"){
            $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>Please Enter '+DisplayName+'. It should not be empty <a href="javascript:void(0)" id="cancelNewRow" class="cancelNewRow">Cancel</a></p>');
        }
        else{
            $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not be empty</p>');
        }
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }
}
isDoubleQuoteExists=function(FieldName, FieldValue, DisplayName, blockName){
    $('#commonValidAlert').remove();
    $(".slick-cell.active").removeClass("redAlert");
    if(blockName=="DerivedFieldGridBlock"){
        var grid =$('#derivedFieldListingGrid').data("gridInstance1");
    }else{
        var grid =$('#listingGrid').data("gridInstance1");
    }
    var row = grid.getActiveCell().row;
    var cell = grid.getActiveCell().cell;
    // if(FieldValue.trim() == ""){
    //     grid.gotoCell(row, cell, true);
    //     $(".slick-cell.active input").addClass("redAlert");
    //     validationAlertShown=true;
    //     if(FieldName=="serviceName" || FieldName=="categoryName" || FieldName=="roleName" || FieldName=="specializationName"  || FieldName=="sourceName"){
    //         $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>Please Enter '+DisplayName+'. It should not be empty <a href="javascript:void(0)" id="cancelNewRow" class="cancelNewRow">Cancel</a></p>');
    //     }
    //     else{
    //         $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not be empty</p>');
    //     }
    //     $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
    //     $('#commonValidAlert').show();
    //     return false;
    // }else
    if(checkEmpty(FieldName, FieldValue, DisplayName, blockName)==false){
        return false;
    }
    if(FieldValue.indexOf(",")!=-1){
        grid.gotoCell(row, cell, true);
        $(".slick-cell.active input").addClass("redAlert");
        validationAlertShown=true;
        $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not contain comma (,) </p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }else if(FieldValue.indexOf("\"")!=-1){
        grid.gotoCell(row, cell, true);
        $(".slick-cell.active input").addClass("redAlert");
        validationAlertShown=true;
        $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not contain double quote (\") </p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }else if(FieldValue.indexOf("\'")!=-1){
        grid.gotoCell(row, cell, true);
        $(".slick-cell.active input").addClass("redAlert");
        validationAlertShown=true;
        $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not contain single quote (\') </p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }else if(FieldValue.indexOf("\\")!=-1){
        grid.gotoCell(row, cell, true);
        $(".slick-cell.active input").addClass("redAlert");
        validationAlertShown=true;
        $('#'+blockName).append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>'+DisplayName+' should not contain back slash (\\) </p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".redAlert",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }else{
        return true;
    }
}
validateFieldName = function (FieldValue, FieldName, fieldDisplayName,blockName){
    if(!isDoubleQuoteExists(FieldName,FieldValue,fieldDisplayName,blockName)){
        return false;
    }
    if(FieldValue.trim() == ""){
        $("#"+FieldName).addClass("redAlert");
        validationAlertShown=true;
        $('#CategoryGridBlock').append('<p id="commonValidAlert" class="fldErr"><span class="topCurve">Continuous white space is not allowed</span></p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".validating",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }
    if(FieldValue.length>65){
        $("#"+FieldName).addClass("redAlert");
        validationAlertShown=true;
        $('#CategoryGridBlock').append('<p id="commonValidAlert" class="fldErr"><span class="topCurve"></span>Please limit your '+fieldDisplayName+' content less than or equal to 65 characters</p>');
        $('#commonValidAlert').position({my: "left top",at: "left top+30",of: ".validating",collision: "none"});
        $('#commonValidAlert').show();
        return false;
    }else{
        return true;
    }
}
$(document).on("click","#cancelNewRow",function(){
    var moduleId = $("#moduleId").val();
    var projectId = $("#projectId").val();
     $(".gridViewPort *").removeClass("clickRestricted allowPointerEvent");
    if($(this).parents(".gridViewPort").attr("id")=="DerivedFieldGridBlock"){
        var pageNumber=$("#derivedFieldListingGridPager").attr("data-pageno");
        var pageSize=$(".gridViewPort #derivedFldListLimit").val();
        $(".fldErr").remove();
        $("#DerivedFieldGridBlock .gridActionLeftBlk").css("pointer-events","auto");
        var derivedFieldType = document.querySelector('#DerivedFieldGridBlock .headerTab--ul li.selected').id;
        var type =0;
        if(derivedFieldType == "derivedFieldTab1"){
            type = 1;
        }else if(derivedFieldType == "derivedFieldTab2"){
            type = 2;
        }else{
            type = 3;
        }
        loadDerivedFieldGrid(type);
    }else{
        var pageNumber=$("#listingGridPager").attr("data-pageno");
        var pageSize=$(".gridViewPort .recordLimit").val();
        $(".gridViewPort--main .gridActionLeftBlk").css("pointer-events","auto");
        $(".fldErr").remove();
        loadSdGridData(projectId,moduleId,pageNumber,pageSize);
    }
});
$(document).on("keyup",".redAlert,.redAlert *",function(){
    $(".fldErr").remove();
    $(this).removeClass("redAlert");
});
$(document).on("change",".categoryColorPicker",function(){
    var selectedColor=$(this).val();
    var moduleId = $("#moduleId").val();
    var projectId=$("#projectId").val();
    var grid =$('#listingGrid').data("gridInstance1");
    var row = grid.getActiveCell().row;
    var cell = grid.getActiveCell().cell;
    var stateCategoryId=grid.getData()[row].workflowId;
    $.ajax({
        url: "saveStateCategoryColor.do",
        type: "POST",
        dataType: 'json',
        async: false,
        data: "projectId="+projectId+"&moduleId="+moduleId+"&stateCategoryId="+stateCategoryId+"&stateCategoryColor="+selectedColor,
        success: function (result) {

        }
    });
});
 $(document).on('keydown', '.slick-pager .slick-pager-status input[type="text"]', function (e) {
    if (e.keyCode == 13) {

    var pageSize = $(".singlePag.recordLimit").val();
    var moduleId = $("#moduleId").val();
        var projectId = $("#projectId").val();
        var $pagerDiv = $(this).closest("div.pager");
        var totalPages = $pagerDiv.attr("data-totalpages");
        if (totalPages != undefined)
            totalPages = parseInt(totalPages);
        var pgno = parseInt($(this).val());
        if (pgno > totalPages)
        pgno = totalPages;
        if (pgno> 0 && pgno <= totalPages)
        {
            loadSdGridData(projectId, moduleId, pgno, pageSize);
        }
    }
});
$(document).ready(function () {
    const observer = new MutationObserver(function (mutationsList) {
        for (var i = 0; i < mutationsList.length; i++) {
            var mutation = mutationsList[i];
            for (var j = 0; j < mutation.addedNodes.length; j++) {
                var node = mutation.addedNodes[j];
                if ((node.id === 'commonValidAlert' || $(node).find('#commonValidAlert').length > 0) ) {
                    $(".gridViewPort *").addClass("clickRestricted");
                    $("#commonValidAlert, .redAlert, #commonValidAlert *, .redAlert *").removeClass("clickRestricted").addClass("allowPointerEvent");
                }else{
                    $(".gridViewPort *").removeClass("clickRestricted allowPointerEvent");
                }
            }
        }
    });
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});
$(document).on("mouseup",".selectCell",function(){
    var thisElem=$(this);
    var isCellActive=setInterval(function(){
        if($(thisElem).find(".select2").length){
            $(thisElem).find("select").select2('open');
            clearInterval(isCellActive);
        }
    },100);
});
$(document).on("click","#mainMenu",function(){
    setTimeout(function(){
        $('.mainNav').slick('setPosition');
        var gridID="listingGrid";
        if($("#auditLogListingGrid").is(":visible")==true){
            gridID="auditLogListingGrid";
        }
        if($("#licenUserListingGrid").is(":visible")==true){
            gridID="licenUserListingGrid";
        }
        var grid=$("#"+gridID).data("gridInstance1");
        grid.resizeCanvas();
    },500);
});
function setBackGridSortColumn(columnId, sortDir,id)
{
    var sortAsc = false;
    if (sortDir.toUpperCase() == "ASC")
    {
        sortAsc = true;
    }
    var slickGrid = $("#"+id).data("gridInstance1");
    var obj = {columnId: columnId, sortAsc: sortAsc};
    var cols = [];
    cols.push(obj);
    slickGrid.setSortColumns(cols);
}