 /*
 *  2009-2019, Tecknodreams Software Consulting Pvt. Ltd.
 */
var slickGridTempVariable;
var slickGridTempPagerVariable;
var rowtest = [];
var columntest = [];
var rowtest1 = [];
var columntest1 = [];
var slickGridOptions = {
    editable: false,
    enableAddRow: false,
    enableCellNavigation: true,
    asyncEditorLoading: false,
    multiColumnSort: true,
    resizable: true,
    sortable: true,
    autoEdit: false,
    autoHeight: true,
    frozenColumn: 5
};

var slickGridrecordParams = {
    startpoint: 1,
    endpoint: 1,
    totalrecords: 1,
    totalpages: 1,
    currentpage: 1,
    sortcolumn: "",
    sortdir: ""
}

function getSlickGridRecordParams()
{
    return slickGridrecordParams;
}

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 getGridSlickColumnAttribute(columnID, columnName, width, cssClass, title, sortable, elementId, editorAttribute, columnType, columnAttributes, enableColumnReorder)
{
    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;
    if ( enableColumnReorder != null && enableColumnReorder != undefined)
    {
        slickGridColumnAttribute.enableColumnReorder = enableColumnReorder;
    }
    if (sortable !== undefined && sortable !== "")
    {
        slickGridColumnAttribute.sortable = sortable;
        slickGridColumnAttribute.selectable = sortable;
        slickGridColumnAttribute.resizable = 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;
        }
//        slickGridColumnAttribute.validator = requiredFieldValidator;
    } 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 slickGridCellCustomFormatter(row, cell, value, columnDef, dataContext)
{
    var cellText = value;
    if (dataContext.sopMasterDataModelChild != undefined && cell > 2)
    {
        var dotClass = "greyDot";
        var sopActions = "";
        var sopComplianceData = dataContext.sopMasterDataModelChild[cell - 3];
        if (sopComplianceData != undefined)
        {
            var savedRecordId = dataContext.savedRecordId;
            if (sopComplianceData.savedRecordId != undefined)
            {
                savedRecordId = sopComplianceData.savedRecordId;
            }
            if (sopComplianceData.intervalTime != undefined && sopComplianceData.intervalTime.trim() != "")
            {
                dotClass = "greenDot";
                sopActions = "<span class='sop-action'><i title='"+i18n.tr("View")+"' class='ico viewSopLnk' data-ticketid='" + sopComplianceData.problemId + "'></i><i title='"+i18n.tr("Delete")+"' data-savedrecordid='" + savedRecordId + "' data-locatioid='" + sopComplianceData.locationId + "' data-scheduleRecordId='" + sopComplianceData.scheduleRecordId + "' class='ico deleteSopLnk'></i></span>";
            }
            cellText = "<span class='upperSurface " + (sopComplianceData.color).trim().toLowerCase() + " " + dotClass + "' >" + sopComplianceData.intervalTime + " " + sopActions + " <span class='lowerSurface'>" + sopComplianceData.scheduleTime + "</span></span>";
        }
    }
    if ( dataContext.sopMasterDataModelChild != undefined &&  columnDef.name.trim()=="" && cell == 0 )
    {
        cellText = '<li class ="collRec wid200"> <a href="javascript:void(0)" class="view-history-lnk histLnk" title="'+i18n.tr("History")+'" ><i class="ico"></i></a></li>';
    }
    else if (dataContext.processInstanceId != undefined && dataContext.logId != undefined && ( columnDef.name.trim()=="Status" || columnDef.name.trim()=="Retry" ))
    {
        if ( columnDef.name.trim()=="Status" && dataContext.success == true)
        {
            cellText = '<span><img src="assets/images/save2.png" alt="" title="True" class="successIco"></span>';
        }
        else if ( columnDef.name.trim()=="Status" && dataContext.success == false)
        {
            cellText = '<span><img src="assets/images/err_temp.png" alt="" title="False" class="failureIco"></span>';
        }
        else if ( columnDef.name.trim()=="Retry" && dataContext.retry == true)
        {
            cellText = '<span><img src="assets/images/save2.png" alt="" title="True" class="successIco"></span>';
        }
        else if ( columnDef.name.trim()=="Retry" && dataContext.retry == false)
        {
            cellText = '<span><img src="assets/images/err_temp.png" alt="" title="False" class="failureIco"></span>';
        }
    }
    else if (dataContext.natureOfChange != undefined &&  columnDef.name.trim()=="")
    {
        if (dataContext.childOf == "1")
        {
            cellText = '<i class="ico expandIco historyChild" title="Expand" id="expandHistoryIco'+dataContext.historyId+'" data-historyid="'+dataContext.historyId+'" data-problemid="'+dataContext.problemId+'" data-projectId="'+dataContext.projectId+'"></i>';
        }
        else if (dataContext.descShow == undefined)
        {
             cellText = '<i class="ico historyChild collapseIco disabled"  id="expandHistoryIco0" data-historyid="0" data-problemid="0" ></i>';
        }

    }
    else if (dataContext.processInstanceId != undefined && dataContext.logId != undefined && ( columnDef.name.trim()=="Creation Time"))
    {
        var date = dataContext.createTime;
        var d = new Date(date);
        var ds = [d.getFullYear(),d.getMonth()+1,d.getDate()].join('-')+' '+[d.getHours(),d.getMinutes(),d.getSeconds()].join(':');
        cellText = '<span title="' + ds + '">' + ds + '</span>';
    }
    else if ( dataContext.processInstanceId != undefined && dataContext.logId != undefined && ( columnDef.name.trim()=="Transaction Details" ) )
    {
        cellText = '<div class="reqXMLBlk"> <a href="javascript:void(0)" class="rpaReqContent" data-logId="'+dataContext.logId+'" data-problemid="'+dataContext.problemId+'" data-count="'+dataContext.retryCount+'"></a> <a href="javascript:void(0)" class="rpaRespContent" data-logId="'+dataContext.logId+'" data-problemid="'+dataContext.problemId+'" data-count="'+dataContext.retryCount+'"> </a> </div>';
    }
    else if (dataContext.problemId != undefined &&  columnDef.name.trim()=="Send Mail")
    {
       cellText = '<a href="javascript:void(0)" title="Send Mail" class="ico sendMailLnk" data-logId="'+dataContext.logId+'" onclick="sendEmailReminder('+dataContext.problemId+',\''+dataContext.forState+'\',\''+dataContext.emailAddress+'\',\''+dataContext.userName+'\','+dataContext.templateId+');"></a>';
    }
    else if ((dataContext.currentTime != undefined && dataContext.natureOfChange != undefined && columnDef.name=="Time Period") || (dataContext.timePeriod != undefined && dataContext.timePeriod != '' && dataContext.changeType != undefined && columnDef.name.trim()=="Time Period") )
    {
        var timeInMilliseconds = dataContext.currentTime;
        if(dataContext.currentTime == undefined){
           timeInMilliseconds = dataContext.timePeriod;
        }
        if ( timeInMilliseconds != undefined)
        {
            var d= new Date(timeInMilliseconds);
            var dateValue = d.getDate();
            if ( dateValue.toString().length == 1 )
            {
                dateValue = "0"+dateValue;
            }
            var month = (d.getMonth()+1);
            if ( month.toString().length == 1 )
            {
                month = "0"+month;
            }
            var hours = d.getHours();
            if ( hours.toString().length == 1 )
            {
                hours = "0"+hours;
            }
            var min = d.getMinutes();
            if ( min.toString().length == 1 )
            {
                min = "0"+min;
            }
            var formattedDate = dateValue  + "-" + month + "-" + d.getFullYear() + " " +hours + ":" + min;
            cellText = '<span title="' + formattedDate + '">' + formattedDate + '</span>';
        }
        else
        {
            cellText = '<span title="' + cellText + '">' + cellText + '</span>';
        }
    }


    else if (dataContext.autoReportId != undefined && dataContext.scheduleTime != undefined && cell == 4)
    {
        var projectId = $("input#selectedProject").val();
        cellText = ' <div class="redirectToOfflineReports comSprite" style="cursor:pointer;" onclick="offlineReportsClick(' + projectId + ',\'' + dataContext.autoReportId + '\',\'' + dataContext.reportName + '\')" ></div>';
    }
    else if (columnDef.title == "slickAdditionalFieldGrid")
    {
        if (cellText != undefined && cellText != "")
            cellText = '<span title="' + cellText + '">' + cellText + '</span>';
    }
	else if(dataContext.parameter != undefined && dataContext.access!= undefined && columnDef.name.trim()=="Parameter"){//ticket history grid view to display publi/private access types
        if(cellText != undefined && cellText != ""){
            if(dataContext.access===1){
              cellText="<span title='"+dataContext.parameter+"'>"+dataContext.parameter+"<i class='ico privateIco' title='Private'></i></span>";
            }else if(dataContext.access===0){
              cellText="<span title='"+dataContext.parameter+"'>"+dataContext.parameter+"<i class='ico publicIco' title='Public'></i></span>"
            }
        }
    }
    else if ((dataContext.natureOfChange != undefined || dataContext.changeDesc != undefined || dataContext.changeType != 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<=28){
                 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 (dataContext.isManaged != undefined && cell == 5){
        var cssClass = "";
        if(dataContext.isManaged == 1){
           cssClass = " green";
        }else if(dataContext.isManaged == 0){
           cssClass = " red0";
        }else if(dataContext.isManaged == -1){
           cssClass = " red-1";
        }else if(dataContext.isManaged == -2){
           cssClass = " red-2";
        }else if(dataContext.isManaged == -3){
           cssClass = " red-3";
        }
        if (cellText != undefined && cellText != ""&& cellText.indexOf("<span")!=0)
            cellText = '<div class="slick-innercell isManagedState '+cssClass+'"><span title="' + cellText + '">' + cellText + '</span></div>';
    }else if (dataContext.status != undefined && cell == 6){
        var cssClass = "";
        if(dataContext.status == 1){
           cssClass = " green";
        }else if(dataContext.status == 0){
           cssClass = " red";
        }
        if (cellText != undefined && cellText != ""&& cellText.indexOf("<span")!=0)
            cellText = '<div class="slick-innercell reconStatus '+cssClass+'"><span title="' + cellText + '">' + cellText + '</span></div>';
    }else if (dataContext.Action != undefined && cell == 0){
        var pageType = dataContext.pageType;
        if (cellText != undefined && cellText != "" && cellText.indexOf("<span")!=0){
            if(dataContext.pageType == 'defaultMyAssetView'){
                if(dataContext.Action == 'Not Applicable'){
                    cssClass = "action0";
                    cellText = '<span id="inotapplicable'+dataContext.assetId+'" class="statusTag notAppl">Not Applicable</span>';
                 }else if(dataContext.Action == 'Accepted'){
                    cssClass = "action1";
                    cellText = '<span id="iaccepted'+dataContext.assetId+'" class="statusTag accept">Accepted</span>';
                 }else if(dataContext.Action == 'Denied'){
                    cssClass = "action2";
                    cellText = '<span id="idenied'+dataContext.assetId+'" class="statusTag denied">Denied</span>';
                 }else if(dataContext.Action == 'Auto Accepted'){
                    cssClass = "action3";
                    cellText = '<span id="iautoaccepted'+dataContext.assetId+'" class="statusTag accept">Auto Accepted</span>';
                 }else if(dataContext.Action == 'Waiting for action'){
                    cssClass = "action4";
                    cellText = "<div class=\"slick-innercell myAsset "+cssClass+"\">\n\
                     <a href=\"javascript:void(0)\" id=\"acceptButtonDefault"+dataContext.assetId+"\" class=\"accptIco\" data-assetId='"+dataContext.assetId+"' data-parentId=\"myAssetGrid\" \">\n\
                         <img src='assets/images/accept.png' alt=''/><span class='hovOver'><i></i>Accept</span></a>\n\
                     <a href='javascript:void(0)' id='denyButtonDefault"+dataContext.assetId+"' class='deniedIco' data-parentId='myAssetGrid' data-pageType='defaultMyAssetView' data-assetId='"+dataContext.assetId+"'>\n\
                         <img src='assets/images/reject.png' alt=''/><span class='hovOver'><i></i>Deny</span></a></div>";
                 }
             }else{
                cellText = "<div class=\"slick-innercell myAsset action4\">\n\
                     <a href=\"javascript:void(0)\" id=\"acceptButtonAudit"+dataContext.assetId+"\" class=\"accptIco\" data-assetId='"+dataContext.assetId+"' data-parentId=\"myAssetAuditGrid\" \">\n\
                         <img src='assets/images/accept.png' alt=''/><span class='hovOver'><i></i>Accept</span></a>\n\
                     <a href='javascript:void(0)' id='denyButtonAudit"+dataContext.assetId+"' class='deniedIco' data-parentId='myAssetAuditGrid' data-pageType='auditMyAssetView' data-assetId='"+dataContext.assetId+"' '>\n\
                         <img src='assets/images/reject.png' alt=''/><span class='hovOver'><i></i>Deny</span></a></div>";
                    if(dataContext.Action == 'Accepted'){
                        cellText += '<span id="iaccepted'+dataContext.assetId+'" class="statusTag accept">Accepted</span>';
                    }else if(dataContext.Action == 'Denied'){
                        cellText += '<span id="idenied'+dataContext.assetId+'" class="statusTag denied">Denied</span>';
                    }

             }
        }
    }else if (dataContext.changeType != undefined &&  columnDef.name.trim()=="") {
        if (dataContext.count != "0") {
            cellText = '<i class="ico expandIco assetHistoryChild" title="Expand" id="expandAssetHistoryIco'+dataContext.assetHistoryID+'" data-historyid="'+dataContext.assetHistoryID+'" data-assetid="'+dataContext.assetId+'"></i>';
        } else  {
             cellText = '<i class="ico assetHistoryChild collapseIco disabled"  id="expandAssetHistoryIco0" data-historyid="0" data-assetid="0" ></i>';
        }

    }else if (dataContext.latitude != undefined &&  dataContext.longitude != undefined && cell == 0) {
       cellText = "<div class=\"slick-innercell pavLocation\">\n\
                     <a href=\"javascript:void(0)\" id=\"pavLocation\" title=\"Location View\" onclick=\"getPAVLocation("+dataContext.longitude+","+dataContext.latitude+",'"+dataContext.PAVassetNumber+"','"+dataContext.pavPageType+"','"+dataContext.pavAssetId+"','"+dataContext.pavItemTypeId+"','"+dataContext.fromPAVlog+"')\">\n\
                         <img src='assets/images/locationIco.png' alt=''/><span class='hovOver'><i></i></span></a></div>";
    }else if(dataContext.itemTypeId != undefined && dataContext.assetId != undefined && cell >8 && (cellText==undefined || cellText == "")){
        cellText = '<span title="--"> -- </span>';
    }else if(columnDef.id!=undefined && columnDef.id ==="Allocate To" && cellText.indexOf("&&::&&")!==-1){
        var spanTitle=cellText.split("&&::&&")[1];
        var cellValue=cellText.replace("&&::&&","");
        cellText = '<span title="' +spanTitle + '">' + cellValue + '</span>';
    }
    else
    {

        if (cellText != undefined && cellText != ""&& cellText.indexOf("<span")!=0)
            cellText = "<span class='slickCellText'>" + cellText + "</span>";
                }
    return cellText;
}
$(document).on("mouseover",".gridParentClass .slick-cell,.gridParentClass1 .slick-cell",function(){
    $(this).addClass("hovered");
   var content=$(this).find(".slickCellText").text();
     $(".titleOnHover").remove();  
    if(content!=""){
		 if($(this).parents("div").hasClass("gridParentClass")==true){
         	$(this).parents(".gridParentClass").after("<span class='titleOnHover'>"+content+"</span>");
		 }
		  if($(this).parents("div").hasClass("gridParentClass1")==true){
         	$(this).parents(".gridParentClass1").after("<span class='titleOnHover'>"+content+"</span>");
		 }
         $(".titleOnHover").position({
            my: "left top",
            at: "left-15 top+25",
            of: ".hovered .slickCellText",
            collision: "none"
        });
    }
});
$(document).on("mouseout mouseup",".gridParentClass .slick-cell.hovered,.gridParentClass1 .slick-cell.hovered",function(){
    $(".titleOnHover").remove();
    $(this).removeClass("hovered");
});
function getEditableSlickGridOptions(optionType, slickGridOptions, value, autoHeight)
{

   if ( autoHeight != undefined )
            slickGridOptions.autoHeight = autoHeight;
            else
                slickGridOptions.autoHeight = true;
    switch (optionType)
    {
        case "additionalField":
            slickGridOptions.editable = true;
            slickGridOptions.enableAddRow = true;
            slickGridOptions.sortable = true;
            slickGridOptions.resizable = true;
            slickGridOptions.autoEdit = true;
            if (value != null)
            slickGridOptions.frozenColumn = parseInt(value);
            break;
        case "ticket":
            slickGridOptions.asyncEditorLoading = true;
            slickGridOptions.enableAddRow = false;
            slickGridOptions.editable = false;
            slickGridOptions.sortable = true;
            if (value != null)
            slickGridOptions.frozenColumn = parseInt(value);
            break;
        case "reports":
            slickGridOptions.enableColumnReorder = false;
            break;
        default:
            if (value != null)
            slickGridOptions.frozenColumn = parseInt(value);


    }
    return slickGridOptions;
}
$(document).on("click", "div.slick-header-columns span.slick-sort-indicator", function (e)
{

    if ($(this).hasClass("slick-sort-indicator-desc"))
    {
        $(this).removeClass("slick-sort-indicator-desc");
        $(this).addClass("slick-sort-indicator-asc");
    } else if ($(this).hasClass("slick-sort-indicator-asc"))
    {
        $(this).removeClass("slick-sort-indicator-asc");
        $(this).addClass("slick-sort-indicator-desc");
    }

});
function applySlickGridAttributes(parentDivId, slickGrid, rows, columns, options, checkboxSelector, gridPageNo, gridPageSize, recordParams)
{
    var totalPages = 1;
    $("#"+parentDivId).removeClass("disableSorting");
    var totalRecords = 1;
    if (recordParams != undefined)
    {
        totalPages = recordParams.totalpages;
        totalRecords = recordParams.totalrecords;
    }
    slickGrid = new Slick.Grid("#" + parentDivId, rows, columns, options);
    //slickGrid.setSelectionModel(new Slick.RowSelectionModel());
    $("#" + parentDivId).data("gridInstance1", slickGrid);
    $("#" + parentDivId).data("gridInstance1").getEditorLock().cancelCurrentEdit();
    if (checkboxSelector != null && checkboxSelector != undefined)
        slickGrid.registerPlugin(checkboxSelector);
    var dataView = new Slick.Data.DataView();
    dataView.setPagingOptions({pageNum: gridPageNo, pageSize: gridPageSize, totalPages: totalPages, totalRows: totalRecords, testRun: 5});
    var pager = new Slick.Controls.Pager(dataView, slickGrid,$("#"+parentDivId+"Pager"));
    if (recordParams != undefined)
    {
        $("#" + parentDivId + "Pager").attr("data-sortdir", recordParams.sortdir);
        $("#" + parentDivId + "Pager").attr("data-sortcolumn", recordParams.sortcolumn);
    }
    slickGrid.onSort.subscribe(function (e, args) {
        if ( ! $("#"+parentDivId).hasClass("disableSorting") )
        {
            var cols = args.sortCols;
            var field = "";
            var sign = "";
            for (var i = 0; i < cols.length; i++)
            {
                field = cols[i].sortCol.field;
                sign = cols[i].sortAsc ? "ASC" : "DESC";
            }

            var pageType = $("#" + parentDivId + "Pager").attr("data-pagetype");
            $("#"+parentDivId).addClass("disableSorting");

            navigateSlickGridSortingPage(pageType, field, sign, parentDivId + "Pager",$(this));
        }
        return 0;
    });
//    slickGrid.onKeyDown.subscribe(function(event) {
//        if (event.keyCode === 9 && event.shiftKey === false) {
//          if (slickGrid.getActiveCell().cell === (slickGrid.getColumns().length-1)) {
//              slickGrid.getEditorLock().commitCurrentEdit();
//            event.stopImmediatePropagation();
//          }
//        }
//      });
    slickGrid.updateRowCount();
    slickGrid.resizeCanvas();
    slickGrid.render();
    var rowLen=rows.length;
    for(var i=0;i<rowLen;i++){
        if(rows[i].isCreatedByLoggedUser==0){
            var nthChild=i+1;
           $(".grid-canvas.grid-canvas-top.grid-canvas-left .ui-widget-content:nth-child("+nthChild+") .slick-cell-checkboxsel").addClass("disabled");
        }
    }
    slickGridTempVariable = slickGrid;
    $("#"+parentDivId+"Pager").find(".slick-pager .slick-pager-status input[type='text']").attr("title", gridPageNo);
    var pglength = 1;
    if ( gridPageNo != undefined )
     pglength = ( gridPageNo+"" ).length;
    if ( ( pglength ) > 3 )
    {
        pglength  = pglength -3;
        pglength = (pglength*10)+30;
        $("#"+parentDivId+"Pager").find(".slick-pager .slick-pager-status input[type='text']").css("width", pglength+"px");
    }
    if ( options != undefined && (options.autoHeight == undefined || options.autoHeight == true))
        $("#" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-right").perfectScrollbar();
    if(parentDivId == "myAssetGrid" || parentDivId == "myAssetAuditGrid"){
        $("#myAssetGrid .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
    }
    $("#slickGridLoader").hide();
    $("#cmdbMainContainer #slickGridLoader").hide();
    $("#slickPaginationLoader").hide();
    $('#'+parentDivId+' .slick-viewport').change(function(e) {
        if(!$(".xdsoft_datetimepicker").is(":visible")){
            var isSelect2Exist=setInterval(function(){
            if($(".select2.select2-container.select2-container--default").hasClass("select2-container--open") === false){ // other than select box all other cells will be committed
                $('#'+parentDivId).data("gridInstance1").getEditorLock().commitCurrentEdit();
                clearInterval(isSelect2Exist);
            }
        },100);
            $(".xdsoft_datetimepicker").remove(); // calendar was visible on left top corner when we click on date/date time field
        }
    });
    $(document).on("click", function(e){//only select box cell to commit
        if(!$(e.target).is('div.gridParentClass *') && !$(e.target).is('div#CUSTOMFIELDMAXGRIDTR *')  && $(".slick-cell .select2-container").is(":visible")){//
            $('#'+parentDivId).data("gridInstance1").getEditorLock().commitCurrentEdit();
        }
    });
    if($("#archivedView").hasClass("myTicketsIcon open")===true){
        $("#slickgrid .slick-cell.l4.editTicket").addClass("disable");
    }
}


function navigateSlickGridSortingPage(pageType, columnName, direction, pagerId,eventObj )
{
    var pageNo = 1;
    $("#" + pagerId).attr("data-pageno", pageNo);
    $("#" + pagerId).attr("data-sortdir", direction.toLowerCase());
    $("#" + pagerId).attr("data-sortcolumn", columnName);
    var recordParams = getSlickGridRecordParams();
    recordParams.sortdir = direction;
    recordParams.sortcolumn = columnName;
    var currentObject = $("#" + pagerId);
    loadPageTypeBasedonPageLimit(pageType, "", "", currentObject, true, recordParams);
}
function getAssociatedRecordColumns(isSingle,isSlickGrid)
{
    var className = "editableLnk multiAssociatedRecReqBlk";
    if (isSingle != undefined && isSingle == true)
    {
        className = "singleAssociatedRecReqBlk";
    }
    var columns = [];
    if (isSlickGrid != undefined && isSlickGrid == true) {
        columns.push(getGridSlickColumnAttribute("RequestId", i18n.tr("Request Id"), 120, className, "", true));
        columns.push(getGridSlickColumnAttribute("title", i18n.tr(" Title"), 150, "", "", false));
        columns.push(getGridSlickColumnAttribute("cmdbdescription", i18n.tr(" Description"), 500, "", "", false));
        columns.push(getGridSlickColumnAttribute("owner", i18n.tr(" Owner"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("statusName", i18n.tr(" Current Status"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("currentDate", i18n.tr(" Submitted Time"), 150, "", "", true));
    }else{
        columns.push(getGridSlickColumnAttribute("RequestId", i18n.tr("Request Id"), 200, className, "", true));
        columns.push(getGridSlickColumnAttribute("title", i18n.tr(" Title"), 250, "", "", false));
        columns.push(getGridSlickColumnAttribute("owner", i18n.tr(" Owner"), 300, "", "", true));
        columns.push(getGridSlickColumnAttribute("statusName", i18n.tr(" Current Status"), 250, "", "", true));
        columns.push(getGridSlickColumnAttribute("currentDate", i18n.tr(" Submitted Time"), 210, "", "", true));
    }
    return columns;
}



function getKbHistoryColumns()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("changeDesc", i18n.tr("Nature Of Change"), 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("oldValue", i18n.tr("Change From"), 250, "", "", false));
    columns.push(getGridSlickColumnAttribute("newValue", i18n.tr("Change To"), 300, "", "", false));
    columns.push(getGridSlickColumnAttribute("modifiedBy", i18n.tr("Action Performed By"), 250, "", "", false));
    columns.push(getGridSlickColumnAttribute("kbTime", i18n.tr("Time Period"), 210, "", "", false));
    return columns;
}

function getTicketNotificationHistoryColumn(notifyType, mailType, isReadOnly)
{

    var columns = [];
    var columnWidth = 250;
    if ( mailType == undefined || mailType != "waitingForApproval")
    {
        columnWidth = 250;
    }
    else
        columnWidth = 230;

    if ( mailType !== undefined && mailType === "slaNotification"){
        columns.push(getGridSlickColumnAttribute("slaName", "SLA Name", 200, "", ""));
        columnWidth = 200;
    }
    columns.push(getGridSlickColumnAttribute("forState", i18n.tr("Notification For"), 210, "", ""));
    columns.push(getGridSlickColumnAttribute("userName", i18n.tr("Notified To"), columnWidth, "", ""));
    if (notifyType == "SMS")
        columns.push(getGridSlickColumnAttribute("cellNo", i18n.tr("Notified Contact Number"), columnWidth, ""));
    else
        columns.push(getGridSlickColumnAttribute("emailAddress", i18n.tr("Notified MailId"), columnWidth, ""));
    if (notifyType == "SMS")
        columns.push(getGridSlickColumnAttribute("smsTemplateName", i18n.tr("Template"), columnWidth, ""));
    else
        columns.push(getGridSlickColumnAttribute("templateName", i18n.tr("Template"), columnWidth, ""));
    if (notifyType == "SMS")
        columns.push(getGridSlickColumnAttribute("smsSentTimeStr", i18n.tr("Sent Time"), columnWidth, ""));
    else
        columns.push(getGridSlickColumnAttribute("sentTimeStr", i18n.tr("Sent Time"), columnWidth, ""));
    if ( notifyType != "SMS" && mailType != undefined && mailType == "waitingForApproval")
    {
        var cssClass = "sendApprovalMail";
        if(isReadOnly===1){
            cssClass = "sendApprovalMail disabled";
        }
        columns.push(getGridSlickColumnAttribute("problemId",i18n.tr( " Send Mail"), 100, cssClass));
    }
    return columns;
}

function getRPAIntegrationLogColumns( )
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("eventName", "Event Name", 460, "", ""));
    columns.push(getGridSlickColumnAttribute("connectionFailed", "Status", 150, "rpaConnectionStatus", ""));
    columns.push(getGridSlickColumnAttribute("retry", " Retry", 150, "rpaRetryStatus"));
    columns.push(getGridSlickColumnAttribute("retryCount", " Retry Count", 150, ""));
    columns.push(getGridSlickColumnAttribute("createTime", " Creation Time", 150, ""));
    columns.push(getGridSlickColumnAttribute("", "Transaction Details", 150, ""));
    return columns;
}
function getAssetAssociatedRecordColumns( )
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("RequestId", "Request Id", 200, "editableLnk multiAssociatedRecReqBlk", ""));
    columns.push(getGridSlickColumnAttribute("title", " Title", 250, "", ""));
    columns.push(getGridSlickColumnAttribute("owner", " Description", 300, ""));
    columns.push(getGridSlickColumnAttribute("statusName", " Current Status", 250, ""));
    columns.push(getGridSlickColumnAttribute("currentDate", " Submitted Time", 250, ""));
    return columns;
}
//RequestId
function getAdvancedSearchViewTicketColumns( )
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("AssetNumber", i18n.tr("Asset Number"), 300, "editableLnk advancedSearchAssetNoFld", "",true));
    columns.push(getGridSlickColumnAttribute("AssetType", i18n.tr("Asset Type"), 350, "", "", true));
    columns.push(getGridSlickColumnAttribute("Status", i18n.tr(" Status"), 300, "","",true));
    columns.push(getGridSlickColumnAttribute("AllocateTo", i18n.tr("Allocated To "), 260, "","",true));
    return columns;
}


function getGridViewHistoryColumnNames()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("", "", 20, "historyChild1", "", "", false));
    columns.push(getGridSlickColumnAttribute("natureOfChange", "Nature of Change", 257, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("parameter", "Parameter", 200, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("oldValue", " Old Value", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("newValue", "New Value", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("actionPerformedBy", "Action Performed By", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("currentTime", "Time Period", 160, "", "", true));
    return columns;
}
function getGridViewAssetHistoryColumnNames()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("", "", 20, "assetHistoryChild1", "", "", false));
    columns.push(getGridSlickColumnAttribute("changeType", "Nature of Change", 257, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("fieldDisplayName", "Parameter", 200, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("oldValue", " Old Value", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("newValue", "New Value", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("userFullname", "Action Performed By", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("timePeriod", "Time Period", 160, "", "", true));
    return columns;
}
function getGridViewAssetAuditColumnNames()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("actionType", "Nature of Change", 200, "", "", true));
    columns.push(getGridSlickColumnAttribute("assetNumber", "Asset Number", 260, "", "", true));
    columns.push(getGridSlickColumnAttribute("itemtype", "Item Type", 200, "", "", true));
    columns.push(getGridSlickColumnAttribute("ipAddress", "IP Address", 200, "", "", true));
    columns.push(getGridSlickColumnAttribute("actionPerformedby", "By", 200, "", "",true));
    columns.push(getGridSlickColumnAttribute("timeperiod", "At", 200, "", "", true));
    return columns;
}
function getGridViewPhysicalAuditColumnNames(fromPAVlog)
{
    var columns = [];
    var n = 20;
    if(fromPAVlog == 0){
       n = 0;
    }
    columns.push(getGridSlickColumnAttribute("", "", 50, "pavLocation1", "", "", false));
    columns.push(getGridSlickColumnAttribute("userName", "User Name", 180+n+n, "", "", true));
    columns.push(getGridSlickColumnAttribute("scanTime", "Scan Time", 180+n, "", "", true));
    columns.push(getGridSlickColumnAttribute("latitude", "Latitude", 130+n, "", "", true));
    columns.push(getGridSlickColumnAttribute("longitude", "Longitude", 130+n, "", "",true));
    columns.push(getGridSlickColumnAttribute("physicalAuditstatus", "Status", 140+n, "", "",true));
    if(fromPAVlog == 0){
        columns.push(getGridSlickColumnAttribute("comment", "Comment", 200, "", "", false));
    }
    columns.push(getGridSlickColumnAttribute("address", "Address", 235+n+n+n, "", "", true));
    return columns;
}
function getGridViewDepreciationColumnNames()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("yearMonth", "Year / Month", 320, "", "", true, false));
    columns.push(getGridSlickColumnAttribute("depreciation", "Depreciation", 320, "", "", true, false));
    columns.push(getGridSlickColumnAttribute("accDepreciation", "Accumulated Depreciation", 320, "", "", true));
    columns.push(getGridSlickColumnAttribute("bookValue", "Book Value", 310, "", "", true));
    return columns;
}
function getGridViewMyAssetColumnNames()
{
    var columns = [];

    columns.push(getGridSlickColumnAttribute("action", "Action", 160, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("assetNumber", "Asset Number", 370, "editableLnk slickGridMyAssetLnk", "", true));
    columns.push(getGridSlickColumnAttribute("assetType", "Asset Type", 370, "", "", true));
    columns.push(getGridSlickColumnAttribute("moduleName", "Module Name", 370, "", "", true));
    return columns;
}
function getReconcilationColumnNames()
{
    var checkboxSelector = new Slick.CheckboxSelectColumn({
        cssClass: "slick-cell-checkboxsel",
        elementId: "reconList"
    });
    var columns = [];
    columns.push(checkboxSelector.getColumnDefinition());
    columns.push(getGridSlickColumnAttribute("assetNumber", "Asset Number", 210, "editableLnk slickGridReconLnk", "", "", false));
    columns.push(getGridSlickColumnAttribute("hostName", "Host Name", 210, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("ipAddress", "IP Address", 210, "", "", "", false));
    columns.push(getGridSlickColumnAttribute("os", "OS", 210, "", "", false));
    columns.push(getGridSlickColumnAttribute("isManaged", "Is Managed", 200, "", "", false));
    columns.push(getGridSlickColumnAttribute("status", "Status", 200, "", "", false));
    return columns;
}

function getEmailToTicketColumns(isFailureType)
{
    var checkboxSelector = new Slick.CheckboxSelectColumn({
        cssClass: "slick-cell-checkboxsel",
        elementId: "emailToTicketList"
    });
    var columns = [];
    columns.push(checkboxSelector.getColumnDefinition());
    if (!isFailureType)
    {
        columns.push(getGridSlickColumnAttribute("problemId", i18n.tr("Id"), 50, "", "", true, ""));
        columns.push(getGridSlickColumnAttribute("title", i18n.tr("Title"), 250, "editableLnk emailToRecordSuccesMailBlk", "", true, "emailReqIDDiv"));
        columns.push(getGridSlickColumnAttribute("description", i18n.tr("Description"), 329, "", "", true));
        columns.push(getGridSlickColumnAttribute("service", i18n.tr("Service"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("category", i18n.tr("Category"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("submitter", i18n.tr("Submitted By"), 150, "emailSubmitter", "", true));
        columns.push(getGridSlickColumnAttribute("location", i18n.tr("Location"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("department", i18n.tr("Department"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("emailAddress", i18n.tr("Email Address"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("submitTime", i18n.tr("Creation Time"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("mailSentTime", i18n.tr("Mail Sent Time"), 150, "", "", true));
    }
    else
    {
        columns.push(getGridSlickColumnAttribute("failureFromTime", i18n.tr("From"), 250, "", "", true));
        columns.push(getGridSlickColumnAttribute("failureSubject", i18n.tr("Subject"), 250, "", "", true));
        columns.push(getGridSlickColumnAttribute("failureMailSentTime",i18n.tr("Mail Sent Time"), 250, "", "", true));
        columns.push(getGridSlickColumnAttribute("failureDescription", i18n.tr("Failure Description"), 478, "", "", true));
    }
    return columns;
}

function getScheduleHistoryColumns()
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("requestId", " Request Id", 630, "", "", true));
    columns.push(getGridSlickColumnAttribute("creationTime", " Creation Time", 630, "", "", true));
    return columns;
}


function getSavedRecordColumns(isscheduleRecord, checkboxSelector)
{
    var columns = [];
    if (!isscheduleRecord)
    {
        columns.push(checkboxSelector.getColumnDefinition());

        columns.push(getGridSlickColumnAttribute("title", i18n.tr("Task Name"), 400, "editableLnk savedRecordRequestIdLnk", "", true));
        columns.push(getGridSlickColumnAttribute("description", i18n.tr("Description"), 400, "", "", true));
        columns.push(getGridSlickColumnAttribute("creationTime", i18n.tr("Creation Time"), 215, "", "", true));
        columns.push(getGridSlickColumnAttribute("createdBy", i18n.tr("Created By"), 215, "", "", true));
    } else
    {
        columns.push(checkboxSelector.getColumnDefinition());
        columns.push(getGridSlickColumnAttribute("scheduleName", i18n.tr("Task Name"), 250, "editableLnk scheduleRecordRequestIdBlk", "", true));
        columns.push(getGridSlickColumnAttribute("scheduleDesc", i18n.tr("Description"), 300, "", "", true));
        columns.push(getGridSlickColumnAttribute("scheduleInterval", i18n.tr("Schedule Interval"), 170, "", "", true));
        columns.push(getGridSlickColumnAttribute("startTime", i18n.tr("Start Time"), 170, "", "", true));
        columns.push(getGridSlickColumnAttribute("scheduleTime", i18n.tr("Last Scheduled Time"), 170, "", "", true));
        columns.push(getGridSlickColumnAttribute("nextScheduleTime", i18n.tr("Next Schedule Time"), 170, "", "", true));
    }
    return columns;
}

function getSOPComplianceColumns(gridData, locationIdsForGlobal)
{
    var columns = [];
    columns.push(getGridSlickColumnAttribute("savedRecordHistory", " ", 50, "editSopComplianceHistoryBlk", "",false));
    columns.push(getGridSlickColumnAttribute("savedRecordName", i18n.tr("Saved Task"), 250, "editSopComplianceSavedRecordBlk editableLnk", "",false));
    columns.push(getGridSlickColumnAttribute("dataAvail", i18n.tr("Global"), 100, "globalCss", "",false));
    var updatedLocationList = getUpdatedLocationList(gridData.locationList, locationIdsForGlobal);
    var totalGridSize = $("#sopComplianceGridULContentBlk").width() - 400;
    var individualLength = 152;
    if ( updatedLocationList.length <= 6)
    {
        individualLength = totalGridSize/( updatedLocationList.length);
    }
    for (var i=0; i<updatedLocationList.length; i++)
    {
        columns.push(getGridSlickColumnAttribute("intervalTime", updatedLocationList[i], individualLength, "sopComplianceColorBlk", "",false));
    }
    return columns;
}

function getUpdatedLocationList(locationList, locationIdsForGlobal)
{

    var updatedLocationList = [];
    if (locationIdsForGlobal != undefined)
    {
        var locations = locationIdsForGlobal.split(",");
        for (var i = 0; i < locations.length; i++)
        {
            updatedLocationList.push( locationList [ parseInt(locations[i])]);
        }
    }
    return updatedLocationList;
}


function getAllProjectSummaryProjectData(type)
{
    var columns = [];
    var sortColumn = false;
    if(type===0){
        sortColumn = true;
    }
    columns.push(getGridSlickColumnAttribute("ticketId", "Request ID", 150, "editableLnk allProjectSummaryRequestLnk", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("title", "Title", 360, "editableLnk allProjectSummaryRequestTitleLnk", "", false));
    columns.push(getGridSlickColumnAttribute("projectName", " Project Name", 150, "", "", false));
    columns.push(getGridSlickColumnAttribute("serviceName", " Service Name", 150, "", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("submittedBy", "Submitted By", 150, "", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("submittedTime", "Submitted Time", 150, "", "", false));
    columns.push(getGridSlickColumnAttribute("currentStatus", "Current Status", 150, "", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("owner", "Owner", 150, "", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("approvalManager", "Approval Manager", 150, "", "", sortColumn));
    columns.push(getGridSlickColumnAttribute("slaStatus", "SLA Status", 150, "", "", false));

    return columns;
}
function getReportGridColumns(reportType)
{
    var columns = [];
    if (reportType == "Inbuilt")
    {
        var checkboxSelector = new Slick.CheckboxSelectColumn({
            cssClass: "slick-cell-checkboxsel",
            elementId: "inbuiltReportCheckbox"
        });
        columns.push(checkboxSelector.getColumnDefinition());
        columns.push(getGridSlickColumnAttribute("", "", 40, "editReport inbuiltReport", "", false,"",null,"",null,false));
        columns.push(getGridSlickColumnAttribute("", "", 40, "copyReport inbuiltReport", "", false,"",null,"",null,false));
        columns.push(getGridSlickColumnAttribute("", "", 40, "exportReport inbuiltReport", "", false,"",null,"",null,false));
        columns.push(getGridSlickColumnAttribute("reportTitle", i18n.tr("Title"), 550, "editableLnk inbuiltReportTitleBlk", "", true));
        columns.push(getGridSlickColumnAttribute("reportDescription", i18n.tr("Description"), 560, "", ""));
    }
    if (reportType == "Custom")
    {
        var checkboxSelector = new Slick.CheckboxSelectColumn({
            cssClass: "slick-cell-checkboxsel",
            elementId: "customReportCheckbox"
        });
        columns.push(checkboxSelector.getColumnDefinition());
        columns.push(getGridSlickColumnAttribute("", "", 40, "editReport customReport", "", false));
        columns.push(getGridSlickColumnAttribute("", "", 40, "copyReport customReport", "", false));
        columns.push(getGridSlickColumnAttribute("", "", 40, "exportReport customReport", "", false));
        columns.push(getGridSlickColumnAttribute("reportTitle", i18n.tr("Title"), 200, "editableLnk customReportTitleLnk", "", true));
        columns.push(getGridSlickColumnAttribute("reportDesc", i18n.tr("Description"), 300, "", "", false));
        columns.push(getGridSlickColumnAttribute("reportTemplete", i18n.tr("Template"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("createBy", i18n.tr("Created By"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("createTime", i18n.tr("Creation Time"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("lastaccessed", i18n.tr("Last Accessed Time"), 170, "", "", true));
    }
    if (reportType == "Schedule")
    {
        var checkboxSelector = new Slick.CheckboxSelectColumn({
            cssClass: "slick-cell-checkboxsel",
            elementId: "scheduleReportCheckbox"
        });
        columns.push(checkboxSelector.getColumnDefinition());
        columns.push(getGridSlickColumnAttribute("reportName", i18n.tr("Report Name"), 300, "editableLnk scheduleReportLnk", "", true));
        columns.push(getGridSlickColumnAttribute("reportTitle", i18n.tr("Title"), 320, "", "", true));
        columns.push(getGridSlickColumnAttribute("modeOfReport", i18n.tr("Report Mode"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("redirectToOfflineReports", i18n.tr("Redirect to Offline Reports"), 250, "", ""));

        columns.push(getGridSlickColumnAttribute("scheduleTime", i18n.tr("Next Schedule Time"), 250, "", "", true));
    }
    if (reportType == "Offline")
    {
        var checkboxSelector = new Slick.CheckboxSelectColumn({
            cssClass: "slick-cell-checkboxsel",
            elementId: "OfflineReportCheckbox"
        });
        columns.push(checkboxSelector.getColumnDefinition());
        columns.push(getGridSlickColumnAttribute("autoReportName", i18n.tr("Report Name"), 200, "editableLnk offlineReportsNameBlk", "", true));
        columns.push(getGridSlickColumnAttribute("reportTitle", i18n.tr("Title"), 200, "", "", true));
        columns.push(getGridSlickColumnAttribute("generatedBy", i18n.tr("Generated By"), 150, "", "", true));
        columns.push(getGridSlickColumnAttribute("creationTime", i18n.tr("Creation Time"), 250, "", "", true));
        columns.push(getGridSlickColumnAttribute("reportType", i18n.tr("Report Type"), 250, "", ""));
        columns.push(getGridSlickColumnAttribute("scheduleType", i18n.tr("Schedule Type"), 178, "", ""));
    }
    return columns;
}


var additionalFieldGridSelectBoxData = [{"text": "--Choose--", "value": 0}];


$(document).on("click", "div.slick-pager-nav span.ui-state-default span.ui-icon-seek-next", function (e)
{
    var isDisabled = false;
    var navigationType = "next";
    if ($(this).hasClass("disabled"))
    {
        isDisabled = true;
    }
    if (!isDisabled)
    {
        $(this).addClass("disabled");
        var pageType = $(this).closest("div.pager").attr('data-pagetype');
        var template=$("#arConfiguredReportsFiltersList").find("#arAppliedFilterSpan").attr("value");
        if(pageType=="ARInbuiltReports" && template!="undefined" && template!="" && template!=null){
            var recordParams = ARGetSlickRecordParams();
            recordParams.start = 1;
            loadPageTypeBasedonPageLimitInbuiltReport(pageType, navigationType, "", '#arInbuiltGridPager', false, recordParams, false,template);
        }else{
            loadPageTypeBasedonPageLimit(pageType, navigationType, e, this);
        }
    }
    e.preventDefault();
});

$(document).on("click", "div.slick-pager-nav span.ui-state-default span.ui-icon-seek-first", function (e)
{
    var isDisabled = false;
    var navigationType = "first";
    if ($(this).hasClass("disabled"))
    {
        isDisabled = true;
    }
    if (!isDisabled)
    {
        $(this).addClass("disabled");
        var pageType = $(this).closest("div.pager").attr('data-pagetype');
        var template=$("#arConfiguredReportsFiltersList").find("#arAppliedFilterSpan").attr("value");
        if(pageType=="ARInbuiltReports" && template!="undefined" && template!="" && template!=null){
            var recordParams = ARGetSlickRecordParams();
            recordParams.start = 1;
            loadPageTypeBasedonPageLimitInbuiltReport(pageType, navigationType, "", '#arInbuiltGridPager', false, recordParams, false,template);
        }else{
            loadPageTypeBasedonPageLimit(pageType, navigationType, e, this);
        }
    }
    e.preventDefault();
});

$(document).on("click", "div.slick-pager-nav span.ui-state-default span.ui-icon-seek-end", function (e)
{
    var isDisabled = false;
    var navigationType = "last";
    if ($(this).hasClass("disabled"))
    {
        isDisabled = true;
    }
    if (!isDisabled)
    {
        $(this).addClass("disabled");
        var pageType = $(this).closest("div.pager").attr('data-pagetype');
        var template=$("#arConfiguredReportsFiltersList").find("#arAppliedFilterSpan").attr("value");
        if(pageType=="ARInbuiltReports" && template!="undefined" && template!="" && template!=null){
            var recordParams = ARGetSlickRecordParams();
            recordParams.start = 1;
            loadPageTypeBasedonPageLimitInbuiltReport(pageType, navigationType, "", '#arInbuiltGridPager', false, recordParams, false,template);
        }else{
            loadPageTypeBasedonPageLimit(pageType, navigationType, e, this);
        }
    }
    e.preventDefault();
});


$(document).on("click", "div.slick-pager-nav span.ui-state-default span.ui-icon-seek-prev", function (e)
{
    var isDisabled = false;
    var navigationType = "prev";
    if ($(this).hasClass("disabled"))
    {
        isDisabled = true;
    }
    if (!isDisabled)
    {
        $(this).addClass("disabled");
        var pageType = $(this).closest("div.pager").attr('data-pagetype');
        var template=$("#arConfiguredReportsFiltersList").find("#arAppliedFilterSpan").attr("value");
        if(pageType=="ARInbuiltReports" && template!="undefined" && template!="" && template!=null){
            var recordParams = ARGetSlickRecordParams();
            recordParams.start = 1;
            loadPageTypeBasedonPageLimitInbuiltReport(pageType, navigationType, "", '#arInbuiltGridPager', false, recordParams, false,template);
        }else{
            loadPageTypeBasedonPageLimit(pageType, navigationType, e, this);
        }
    }
    e.preventDefault();
});



function loadPageTypeBasedonPageLimit(pageType, navigationType, e, currentObject, isSorting, recordParams,isPagelimit)
{
    var pageSize = $("#recordLimit").val();
    if(pageType==="summaryReport"){
        var pageSize = $("#reportRecordLimit").val();
    }
    var contentDivId = "slickgrid";
    var pagerId = "";
    var pageNo = 0;
    var totalPages = 1;
    switch (pageType)
    {

        default:
            contentDivId = $(currentObject).closest("div.pager").siblings("div.ui-widget").attr("id");
            pagerId = $(currentObject).closest("div.pager").attr("id");
        break;

        case "allProjectSummary" :
            contentDivId = "allProjectSummaryGridData";
            pagerId = "allProjectSummaryGridDataPager";
            break;

        case "ticket" :
            contentDivId = "slickgrid";
            pagerId = "slickgridPager";

            break;

        case "savedRecords":
        case "scheduleRecords":
            contentDivId = "mainSavedRecordGridULContentBlk";
            pagerId = "mainSavedRecordGridULContentBlkPager";
            break;

        case "inbuiltReports":
            contentDivId = "InbuiltReportsListingBlk";
            pagerId = "InbuiltReportsListingBlkPager";
            break;

        case "summaryReport":
            contentDivId = "reportViewGrid";
            pagerId = "reportViewGridPager";
            break;

        case "customReports":
            contentDivId = "CustomReportsListingBlk";
            pagerId = "CustomReportsListingBlkPager";
            break;

        case "scheduleReports":
            contentDivId = "scheduleReportsDataBlk";
            pagerId = "scheduleReportsDataBlkPager";
            break;

        case "offlineReports":
            contentDivId = "offlineReportsDataBlk";
            pagerId = "offlineReportsDataBlkPager";
            break;

        case "multiAssociatedRecords":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            contentDivId = "assoRecBlk" + problemId;
            pagerId = "assoRecBlk" + problemId + "Pager[data-pagetype='multiAssociatedRecords']";
            break;

        case "ticketGridHistory":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            contentDivId = "ticketHistoryGrid" + problemId;
            pagerId = "ticketHistoryGrid" + problemId + "Pager";
            break;
        case "ticketOwnerHistoryGrid":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            contentDivId = "ticketOwnerHistoryGrid" + problemId;
            pagerId = "ticketOwnerHistoryGrid" + problemId + "Pager";
            break;
        case "ticketAppMgrHistoryGrid":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            contentDivId = "ticketAppMgrHistoryGrid" + problemId;
            pagerId = "ticketAppMgrHistoryGrid" + problemId + "Pager";
            break;
        case "ticketNotificationHistory":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var notificationFlag = $(currentObject).closest("div.pager").attr("data-notificationflag");
            contentDivId = $(currentObject).closest("div.pager").attr("id").replace("Pager","");
            pagerId = $(currentObject).closest("div.pager").attr("id") + "[data-notificationflag='"+notificationFlag+"']";
            break;

        case "scheduleRecordHistoryPage":
            contentDivId = $(currentObject).closest("div.pager").siblings(".edit-block-history").attr("id");
            pagerId = $(currentObject).closest("div.pager").attr("id");
            break;

        case "assetTicketAssociatedRecords":
            contentDivId = $(currentObject).closest("div.pager").siblings(".gridBody").attr("id");
            pagerId = $(currentObject).closest("div.pager").attr("id");
            break;

        case "sopCompliance":
            contentDivId = "sopComplianceGridULContentBlk";
            pagerId = "sopComplianceGridULContentBlkPager";
            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");
            }
            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");
            }
            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");
            }
            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");
            }
            break;

        case "emailToTicket":
            contentDivId = "emailRecordGridData";
            pagerId = "emailRecordGridDataPager";
            break;

        case "kbHistory":
            contentDivId = $(currentObject).closest("div.pager").siblings(".gridBody").attr("id");
            pagerId = $(currentObject).closest("div.pager").attr("id");
            break;
        case "rpaIntegrationLog":
            contentDivId = $(currentObject).closest("div.pager").siblings(".gridBody").attr("id");
            pagerId = $(currentObject).closest("div.pager").attr("id");
            break;
	case "ARScheduleReports":
            contentDivId = "ARScheduleGrid";
            pagerId = "ARScheduleGridPager";
            break;
        case "ARCustomReports":
            contentDivId = "arCustomGrid";
            pagerId = "arCustomGridPager";
            break;
        case "AROfflineReports":
            contentDivId = "AROfflineGrid";
            pagerId = "AROfflineGridPager";
            break;
        case "ARTabularReports":
            contentDivId = "ARTabularExecutionDiv";
            pagerId = "ARTabularExecutionDivPager";
            break;
        case "ARInbuiltReports":
            contentDivId = "arInbuiltGrid";
            pagerId = "arInbuiltGridPager";
            break;
        case "ARMISReports":
            contentDivId = "arMISGrid";
            pagerId = "arMISGridPager";
            break;
        case "cmdb":
            contentDivId = "CMDBslickgrid";
            pagerId = "CMDBslickgridPager";
            break;
        case "assetRecon":
            contentDivId = "assetReconGrid";
            pagerId = "assetReconGridPager";
            break;
        case "myAssetDefault":
            contentDivId = "myAssetGrid";
            pagerId = "myAssetGridPager";
            break;
        case "myAssetAudit":
            contentDivId = "myAssetAuditGrid";
            pagerId = "myAssetAuditGridPager";
            break;
        case "assetGridHistory":
            var assetId = $(currentObject).closest("div.pager").attr("data-assetId");
            contentDivId = "assetHistoryGrid" + assetId;
            pagerId = "assetHistoryGrid" + assetId + "Pager";
            break;
        case "cmdbAudit":
            contentDivId = "CMDBAuditSlickgrid";
            pagerId = "CMDBAuditSlickgridPager";
            break;
        case "cmdbPhysicalAudit":
            contentDivId = "CMDBPhysicalAuditgrid";
            pagerId = "CMDBPhysicalAuditgridPager";
            break;
        case "cmdbDepreciation":
            contentDivId = "CMDBDepreciationgrid";
            pagerId = "CMDBDepreciationgridPager";
            break;
        case "cmdbChangeLog":
            contentDivId = "CMDBChangeLogGrid";
            pagerId = "CMDBChangeLogGridPager";
            break;
        case "cmdbNotificationLog":
            contentDivId = "CMDBNotificationLogGrid";
            pagerId = "CMDBNotificationLogGridPager";
            break;
    }

    if (isSorting == undefined || isSorting == false)
    {
        if (pageType == "ticketNotificationHistory")
        {
            var notificationFlag = $(currentObject).closest("div.pager").attr("data-notificationflag");
            pageNo = $(currentObject).closest("div.pager[data-notificationflag='"+notificationFlag+"']").attr("data-pageno");
        }
        else if ($("#" + pagerId).attr("data-pageNo") != undefined)
            pageNo = $(currentObject).closest("div.pager").attr("data-pageNo");

        totalPages = $(currentObject).closest("div.pager").attr("data-totalpages");
        if ($(currentObject).closest("div.pager").attr("data-totalpages") != undefined)
        {
            if (pageType == "ticketNotificationHistory")
            {
                var notificationFlag = $(currentObject).closest("div.pager").attr("data-notificationflag");
                totalPages = $(currentObject).closest("div.pager").attr("data-totalpages");
            }
            else
            totalPages =$(currentObject).closest("div.pager").attr("data-totalpages");
        }
        if (pageNo != 0)
        {
            if (navigationType == "next")
                pageNo = parseInt(pageNo) + 1;
            else if (navigationType == "last")
            {
                pageNo = totalPages;
            } else if (navigationType == "first")
            {
                pageNo = 1;
            }
            else if (navigationType == "current")
            {
                pageNo = parseInt(pageNo);
            }
            else
                pageNo = parseInt(pageNo) - 1;
        }
        if (pageType == "ticketNotificationHistory")
        {
            var notificationFlag = $(currentObject).closest("div.pager").attr("data-notificationflag");
            $("#" + pagerId+"[data-notificationflag='"+notificationFlag+"']").attr("data-pageNo", parseInt(pageNo));
            $("div#" + pagerId + "[data-notificationflag='"+notificationFlag+"'] div.slick-pager span.slick-pager-status input[type='text']").val(parseInt(pageNo));
        }
        else
        {
            $("#" + pagerId).attr("data-pageNo", parseInt(pageNo));
            $(currentObject).closest("div.pager").find("div.slick-pager span.slick-pager-status input[type='text']").val(parseInt(pageNo));
        }
    }
    else
    {
        $("#" + pagerId+"[style!='display: none;']").attr("data-sortdir", recordParams.sortdir);
        $("#" + pagerId+"[style!='display: none;']").attr("data-sortcolumn", recordParams.sortcolumn);
        pageNo = $("#" + pagerId+"[style!='display: none;']").attr("data-pageno");
    }
    $(currentObject).closest("div.pager").find("#slickPaginationLoader").remove();
    $(currentObject).closest("div.pager").find(".slick-pager").append('<img id="slickPaginationLoader" src="assets/images/indicator.gif" />');
    $("#slickPaginationLoader").show();
    switch (pageType)
    {
        case "allProjectSummary" :
            getApplyFiltersAllProjectData("pageNumberClick", e);
            break;

        case "searchTicket" :
            var projectId = $('#projectId').val();
            var searchText = $(currentObject).closest("div.pager").attr("data-searchText");//data-searchText
            searchRecords( searchText ,false, projectId, true);
//            getGridViewJSONData(incidentType, "", "", true);
            break;

         case "rpaIntegrationLog":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            getRpaIntegrationlogData(problemId,0,0,0,pageNo,0,0);
            break;

         case "ticket" :
            var incidentType = getRequestType();
            var isFromDashboard = $(currentObject).closest("div.pager").attr("data-isFromDashboardRedirection");
            var dataParams = "";
            if(isFromDashboard == "yes"){
                dataParams = "&isFromDashboardRedirection=yes";
            }
            var isFromBookmark = $(currentObject).closest("div.pager").attr("data-isFromBookMarkClick");
            if(isFromBookmark != undefined && isFromBookmark > 0){
                dataParams = "&bookmarkId="+isFromBookmark;
            }
            getGridViewJSONData ( incidentType,"" , dataParams, true );
            break;

        case "savedRecords":
            loadSavedRecords();
            break;

        case "scheduleRecords":
            var projectId = $("#mainSavedRecordGridULContentBlkPager").attr("data-projectId");
            loadScheduleRecordList(projectId, 1);
            break;

        case "scheduleReports":
            var reportId = $("#scheduleReportsDataBlkPager").attr("data-reportId");
            var projectId = $("#scheduleReportsDataBlkPager").attr("data-projectId");
            loadScheduleReportData(projectId, pageNo, reportId, null);
            break;

        case "inbuiltReports":
            var template = $("input#template").val();
            var projectId = $("input#selectedProject").val();
            loadInbuiltReportsGridData(projectId, template);
            break;

        case "summaryReport":
            var reportid = $("#reportid").val();
            var sdReportsPageSize = $("#reportRecordLimit").val();
            var pageNo = $("#reportViewGridPager .slick-pager-status input[type=text]").val();
            loadReportData(reportid, "&pageSize=" + sdReportsPageSize + "&pageNo=" + pageNo);
            break;
            
        case "kbHistory":
        var kbId = $(currentObject).closest("div.pager").attr("data-kbid");
            var pageNo = $(currentObject).closest("div.pager").attr("data-pageno");
            var pageSize = $("#recordLimit" + kbId + "[name='singlePag" + kbId + "']").val();
            var start = ( pageNo -1 )*pageSize;
            openArticleHistory(kbId, 10, start);
            break;

        case "multiAssociatedRecords":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var pageNo = $(currentObject).closest("div.pager").attr("data-pageno");
            pageSize = $("#recordLimit" + problemId + "[name='singlePag" + problemId + "']").val();
            projectId = $(currentObject).closest("div.pager").attr("data-projectId");
            getAssociatedRecordsList(problemId, projectId, pageSize, (pageSize * pageNo) - pageSize, '', '', pageNo, e);
            break;

        case "ticketGridHistory":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var pageSize = $("#recordLimit" + problemId + "[name='historyGridPag']").val();
            var start = (parseInt(pageNo) - 1) * parseInt(pageSize);
            loadGridHistory(problemId, start, 'asc', 1);
            break;
        case "ticketOwnerHistoryGrid":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var pageSize = $("#recordLimit" + problemId + "[name='historyOwnerShipGridPag']").val();
            var start = (parseInt(pageNo) - 1) * parseInt(pageSize);
            loadOwnerShipChangeGridHistory(problemId, start, 'asc', 1, 1);
            break;
        case "ticketAppMgrHistoryGrid":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var pageSize = $("#recordLimit" + problemId + "[name='historyOwnerShipGridPag']").val();
            var start = (parseInt(pageNo) - 1) * parseInt(pageSize);
            loadOwnerShipChangeGridHistory(problemId, start, 'asc', 1, 2);
            break;
        case "ticketNotificationHistory":
            var notificationFlag = $(currentObject).closest("div.pager").attr("data-notificationflag");
            var problemId = $(currentObject).closest("div.pager[data-notificationflag='"+notificationFlag+"']").attr("data-problemId");
            var notificationFilter = $(currentObject).closest("div.pager").attr("data-notificationfilter");
            var notificationId = $(currentObject).closest("div.pager").attr("data-notificationid");
            var pageSize = $("#recordLimit" + problemId + "[name='mailNotify" + problemId + "']").val();
            var start = (parseInt(pageNo) - 1) * parseInt(pageSize);
            getNotificationMailSentData(problemId, notificationFilter, notificationId, start, pageSize, null, notificationFlag);
            break;

        case "assetTicketAssociatedRecords":
            var problemId = $(currentObject).closest("div.pager").attr("data-problemId");
            var projectId = $(currentObject).closest("div.pager").attr("data-projectId");
            var limit = $("#singlePagAssetAssociate" + problemId + "[name='singlePagAssetAssociate']").val();
            if (limit == undefined )
            {
                limit = $("#recordLimit"+problemId+"[name='singlePagAssetAssociate']").val();
            }
            if (limit == undefined )
            {
                limit = $("#recordLimit"+problemId+"[name='singlePag"+problemId+"']").val();
            }
            var start = (parseInt(pageNo) - 1) * parseInt(limit);
            var pgType = "";
           var parent = "sort";
            if ( $(currentObject).closest("div.pager").attr("data-pageType1") != undefined )
            {
                pgType = $(currentObject).closest("div.pager").attr("data-pageType1");
                parent = "";
            }
            var sortDir = $(currentObject).closest("div.pager").attr("data-sortdir");
            parent = $(currentObject).closest("div.pager").attr("data-parent");
           getAssetAssociatedRecordsList(problemId, projectId, limit, start, 'requestId', sortDir, pageNo,pgType, e, false, parent, '');
            break;

        case "scheduleRecordHistoryPage":
            var scheduleId = $(currentObject).closest("div.pager").attr("data-scheduleId");
            showScheduleRecordsEdit(scheduleId, 0, 1);
            break;

        case "customReports":
            var reportGridStartLimit = 0;
            var reportGridPageSize = $("#reports #recordLimit").val();
            var projectId = $('#customReportsProjectId').val();
            var searchText = $('#customReportSearch').val();
            var urlParams = 'projectId=' + projectId + '&searchText=' + searchText + '&pageSize=' + reportGridPageSize + '&pageNo=' + pageNo + '&customReportsgridStartLimit=' + reportGridStartLimit;
            if($("#fromFolder").val()=="1"){
                var ref = $('#jstree_div_list').jstree(true),
                sel = ref.get_selected();
                if((sel=="") || (($("#jstree_div_list").find("#"+sel).attr("aria-selected"))!="true")){
                    sel="defaultNode";
                }
                var params='folderStructure=yes&selectedNode='+sel+'&projectId=' + projectId;
                $("#CustomReportsListingBlkPager").attr("data-pageno",pageNo);
                urlParams = 'projectId=' + projectId + '&searchText=' + searchText + '&pageSize=' + reportGridPageSize + '&pageNo=' + pageNo + '&customReportsgridStartLimit=' + reportGridStartLimit;
                getCustomScriptFolderList(sel,urlParams+"&"+params);
            }else{
                loadCustomReportsGridData(urlParams);
            }
            break;

        case "offlineReports":
            var projectId = $("#OfflineReportSelectedProject").val();
            var pageSize = $("#reports #recordLimit").val();
            var offlineReportsgridStartLimit = (parseInt(pageNo) - 1) * parseInt(pageSize);
            var reportID = $("#ReportNameList option:selected").val();
            var params = "";
            var reportIDName = $("#ReportNameList option:selected").text();
            params = "projectId=" + projectId + "&pageSize=" + pageSize + "&pageNo=" + pageNo + "&offlineReportsgridStartLimit=" + offlineReportsgridStartLimit + "&reportID=" + reportID + "&reportIDName=" + reportIDName;
            getOfflineReportsGridData(params);
            break;
        case "sopCompliance":
            var projectId =$("#mainContentDiv input#projectId").val();
            loadSOPComplianceGridData( projectId ,pageNo);
            break;
        case "emailToTicket":

            getEmailRecordAdvanceViewRecords('pageNo='+pageNo,false);
            break;

       case "ticketAdvancedSearch":
           var problemId = $("#"+pagerId).attr("data-problemId");
           var projectId = $("#"+pagerId).attr("data-projectId");
           var pgType = $("#"+pagerId).attr("data-pgType");
           var limit = $("#"+pagerId).attr("data-limit");
            var start = ( pageNo- 1)* limit;
			getAssetAdvanceSearch(problemId,projectId,limit,start,'','',null,pgType,e);

           break;
        case "ARScheduleReports":
            var projectId = $('#selectedProjectId').val();
            arScheduleListGridData(projectId, pageNo, "schedule", isPagelimit);
            break;
        case "ARCustomReports":
            var projectId = $('#selectedProjectId').val();//arInbuiltListGridData
            arCustomListGridData(projectId, pageNo, "Custom", isPagelimit);
            break;
        case "AROfflineReports":
            var projectId = $('#selectedProjectId').val();
            arOfflineListGridData(projectId, pageNo, "Offline", isPagelimit);
            break;
        case "ARTabularReports":
			var authDetail=getAuthData(arTenantName);
            var url = "", docId = $('#arDocId').val();
            var template = $('#arTemplateType').val();
            var isChild=$('#ar_isChild').val()=='true';
            var filterJsonData="";
            if(template === 'tabular'){
                url = "//" + arIpAddress + "/default-delivery/execute/tabular?procedure="+globalIsProcedure+"&tenant_id=" + arTenantName+ "&authKey="+authDetail[0]+ "&authToken="+authDetail[1];
                filterJsonData=globalFilterParams;
            }else if(template === 'chart'){
                if($('#ar_chartType').val() === 'tabular'){
                    $('#ar_isChild').val(false);
                    isChild = $('#ar_isChild').val() == 'true';
                    url = "//" + arIpAddress + "/default-delivery/execute/drilldown/chartTabularReport?tenant_id=" + arTenantName + "&authKey="+authDetail[0]+ "&authToken="+authDetail[1];
                    filterJsonData=globalFilterParams;
                }else if(isChild){
                    url = "//" + arIpAddress + "/default-delivery/execute/drilldown/childreport?tenant_id=" + arTenantName+ "&authKey="+authDetail[0]+ "&authToken="+authDetail[1];
                    filterJsonData=globalFilterParams;
                }
            }
            executeAndRender(url, docId, "html", pageNo, "tabular", isChild,filterJsonData );
            break;
        case "ARInbuiltReports":
            var projectId = $('#selectedProjectId').val();//
            arInbuiltListGridData(projectId, pageNo, "Inbuilt", isPagelimit);
            break;
        case "ARMISReports":
            var projectId = $('#selectedProjectId').val();
            arMISListGridData(projectId, pageNo, "MIS", isPagelimit);
            break;
        case "cmdb" :
            var moduleId = $(currentObject).closest("div.pager").attr("data-moduleId");
            getCMDBGridViewJSONData(moduleId,"",true);
            break;
        case "assetRecon" :
            loadReconciationData(true);
            break;
        case "myAssetDefault":
            loadMyAssetData(true,'defaultMyAssetView');
            break;
        case "myAssetAudit":
            loadMyAssetData(true,'auditMyAssetView');
            break;
        case "assetGridHistory":
            var assetId = $(currentObject).closest("div.pager").attr("data-assetId");
            var historyPageNo = $("#assetHistoryGrid"+assetId+"Pager").attr("data-pageno");
            var historyPageSize = $("#recordAssetLimit" + assetId + "[name='assetHistoryGridPag']").val();
            var start = (parseInt(historyPageNo) - 1) * parseInt(historyPageSize);
            var pageType = $(currentObject).closest("div.pager").attr("data-pageType");
            var assetNumber = $(currentObject).closest("div.pager").attr("data-assetNumber");
            collapseDataSetObject = {};
            loadAssetGridHistory(assetId, start, 'asc', assetNumber,pageType, 1);
            break;
        case "cmdbAudit":
            loadAssetAuditGrid(true);
            break;
        case "cmdbPhysicalAudit":
            var pageType = $(currentObject).closest("div.pager").attr("data-viewType");
            var fromPAVlog = $(currentObject).closest("div.pager").attr("data-fromPAVlog");
            var assetNumber = '';
            if(pageType == 'assetPhysicalAuditListView'){
              assetNumber = $(currentObject).closest("div.pager").attr("data-assetNumber");
            }
            var physicalAuditAssetId = $(currentObject).closest("div.pager").attr("data-assetId");

            loadPhysicalAuditData(fromPAVlog,physicalAuditAssetId,pageType,assetNumber,true);
            break;
        case "cmdbDepreciation":
            var pageType = $(currentObject).closest("div.pager").attr("data-viewType");
            var assetNumber = '';
            if(pageType == 'assetDepreciationListView'){
              assetNumber = $(currentObject).closest("div.pager").attr("data-assetNumber");
              assetId = $(currentObject).closest("div.pager").attr("data-assetid");
            }else{
              assetId = $(currentObject).closest("div.pager").attr("data-assetid");
            }
            var monthYear = "month";
            if($('#depreciationScheduleBlock #yearId').is(":checked")){
               monthYear = "year";
            }
            loadDepreciationData(assetId,pageType,assetNumber,monthYear,true);
            break;
        case "cmdbChangeLog":
            var pageType = $(currentObject).closest("div.pager").attr("data-viewType");
            if(pageType == 'assetChangeLogListView'){
                assetNumber = $(currentObject).closest("div.pager").attr("data-assetNumber");
                assetId = $(currentObject).closest("div.pager").attr("data-assetid");
            }else{
                assetId = $(currentObject).closest("div.pager").attr("data-assetid");
}
            getAssetChangeLog(assetId,pageType,true,assetNumber);
            break;
        case "cmdbNotificationLog":
            var pageType = $(currentObject).closest("div.pager").attr("data-viewType");
            if(pageType == 'assetNotificationLogListView'){
                assetNumber = $(currentObject).closest("div.pager").attr("data-assetNumber");
                assetId = $(currentObject).closest("div.pager").attr("data-assetid");
            }else{
                assetId = $(currentObject).closest("div.pager").attr("data-assetid");
            }
            getAssetNotificationLog(assetId,pageType,true,assetNumber);
            break;
}
}

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 getAppliedSlickGridParents()
{
    var slickGridParentContainers = [];
    slickGridParentContainers.push("allProjectSummaryGridData");
    slickGridParentContainers.push("slickgrid");
    slickGridParentContainers.push("mainContentDiv");
    return slickGridParentContainers;
}


function getSortDataColumnName(pageType, columnName)
{
    var dataColumnName = "";
    switch (pageType)
    {
        case "allProjectSummary" :
            if (columnName == "ticketId")
            {
                dataColumnName = "s.RequestId";
            }
            if (columnName == "serviceName")
            {
                dataColumnName = "srv.ServiceName";
            }
            if (columnName == "submittedBy")
            {
                dataColumnName = "um1.FullName";
            }
            if (columnName == "currentStatus")
            {
                dataColumnName = "sm.StateName";
            }
            if (columnName == "owner")
            {
                dataColumnName = "um2.FullName";
            }
            if (columnName == "approvalManager")
            {
                dataColumnName = "um3.FullName";
            }
            break;

        case "customReports" :
            if (columnName == "reportTitle")
            {
                dataColumnName = "sr.ReportTitle";
            }
            if (columnName == "reportTemplete")
            {
                dataColumnName = "sr.ReportTemplete";
            }
            if (columnName == "createBy")
            {
                dataColumnName = "sr.Create_By";
            }
            if (columnName == "createTime")
            {
                dataColumnName = "sr.Create_Time";
            }
            if (columnName == "lastaccessed")
            {
                dataColumnName = "sr.lastaccessed";
            }

            break;

        case "offlineReports":
            if (columnName == "autoReportName")
            {
                dataColumnName = "offr.autoReportName"
            }
            if (columnName == "reportTitle")
            {
                dataColumnName = "offr.reportTitle"
            }
            if (columnName == "generatedBy")
            {
                dataColumnName = "offr.generatedBy"
            }
            if (columnName == "creationTime")
            {
                dataColumnName = "offr.creationTime"
            }
            break;

        case "emailToRequest":
            if (columnName == "problemId")
            {
                dataColumnName = "emailRequestId";
            }
            if (columnName == "category")
            {
                dataColumnName = "category";
            }
            if (columnName == "submitter")
            {
                dataColumnName = "submittedBy";
            }
            if (columnName == "emailAddress")
            {
                dataColumnName = "submittedBy";
            }

            if (columnName == "emailAddress")
            {
                dataColumnName = "submittedBy";
            }

            if (columnName == "emailAddress")
            {
                dataColumnName = "submittedBy";
            }

            if (columnName == "service")
            {
                dataColumnName = "submittedBy";
            }

            if (columnName == "submitTime")
            {
                dataColumnName = "creationTime";
            }

            if (columnName == "mailSentTime")
            {
                dataColumnName = "mailSentTime";
            }

            if (columnName == "location")
            {
                dataColumnName = "locationName";
            }

            if (columnName == "department")
            {
                dataColumnName = "departmentName";
            }
            break;

    }
    return dataColumnName;
}

function getPaginationLimitOptions()
{
    var paginationLimit = new Object();
    paginationLimit["10"] = "10";
    paginationLimit["20"] = "20";
    paginationLimit["30"] = "30";
    paginationLimit["40"] = "40";
    paginationLimit["50"] = "50";
    paginationLimit["60"] = "60";
    paginationLimit["70"] = "70";
    paginationLimit["80"] = "80";
    paginationLimit["90"] = "90";
    paginationLimit["100"] = "100";
    return paginationLimit;
}

function reInitSlickGridComponent(divElement)
{
    var selector = "#" + divElement;
    var className = $(selector).attr("class");
    var classes = [];
    if (className != undefined)
        className.split(" ");
    var expr = /slickgrid/;
    if (className != undefined && className.search(expr) != -1)
    {
        for (var i = 0; i < classes.length; i++)
        {
            if (classes[i].indexOf("slickgrid") != -1)
            {
                $(selector).removeClass(classes[i]);
                break;
            }
        }
        $(selector).removeClass("ui-widget");
        $(selector).css("overflow", "");
        $(selector).css("outline", "");
        $(selector).css("height", "");
    }
}

$(document).on("click", "#gridMaxViewIco", function (e)
{
    var checkboxSelector = new Slick.CheckboxSelectColumn({
        cssClass: "slick-cell-checkboxsel",
        elementId: "ticketList"
    });
    $("#gridAdditionalFldMaxView").show();
    $("body").css("overflow", "hidden");
    var totalWidth = parseInt($("#CUSTOMFIELDMAXGRIDTR").width());
    var individualWidth = 200;
    var fieldId = $(this).attr("data-gridFieldId");
    var displayName = $(this).attr("data-gridName");
    var fieldType = $(this).attr("data-gridFieldType");
    var projectId = $(this).siblings(".gridDataImpBlk").find(".closeBlk").children("#impGridUpload").attr("data-gridprojectid");
    var problemId = $(this).siblings(".gridDataImpBlk").find(".closeBlk").children("#impGridUpload").attr("data-gridproblemid");
    var cols = $("#" + displayName).data("gridInstance1").getColumns();
    var rows = $("#" + displayName).data("gridInstance1").getData();
    $("#maxViewGridBlk").attr("data-gridFieldId", fieldId);
    $("#maxViewGridBlk").attr("data-gridName", displayName);
    $("#maxViewGridBlk").attr("data-gridFieldType", fieldType);
    $("#maxViewGridBlk").find("#impGridUpload").attr("data-gridprojectid", projectId);
    $("#maxViewGridBlk").find("#impGridUpload").attr("data-gridproblemid", problemId);
   //data-gridproblemid
    if ( cols.length <= 7 )
        individualWidth = (totalWidth-30) / (cols.length-1 );

    for (var i = 0; i < cols.length; i++)
    {
        var columnObj = cols[i];
        if ( i==0 )
        {
            columnObj.width = 30;
        }
        else
        columnObj.width = individualWidth;
        cols[i] = columnObj;
    }

    var slickGridOption = getEditableSlickGridOptions("additionalField", slickGridOptions, -1);
    var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    if(($("#viewWithMenu").is(":visible")===true || $("#submitTicketParent").is(":visible")===true)||($("#assetMainContainer").is(":visible")&&($(window).width()<1290 || browserZoomLevel!==100))){
        slickGridOption.autoHeight=false;
    }
    applySlickGridAttributes("CUSTOMFIELDMAXGRIDTR", slickGrid, rows, cols, slickGridOption, checkboxSelector);
    $(".slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
    var exportLnk = $("#"+displayName).siblings(".gridActionBtnBlk").find(".gridActionRightBlk a.exportIco").attr("href");
    $("#gridAdditionalFldMaxView .maxAdditionalGridViewBlk .gridActionBtnBlk .gridActionRightBlk a.exportIco").attr("href", exportLnk);
    var gridTitle = $("#"+displayName).siblings(".gridActionBtnBlk").find("h3").html();
    $("#gridAdditionalFldMaxView .gridActionBtnBlk h3").html(gridTitle);
    $("#gridAdditionalFldMaxView .gridActionBtnBlk h3").find("#infoIco"+fieldId).remove();
     if($("#"+displayName).siblings(".gridActionBtnBlk").find("#btnAddgrid").length===0){
      $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnAddgrid").hide();
      $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnAddGridMax").hide();
    }else{
      $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnAddgrid").show();
    }
    if($("#"+displayName).siblings(".gridActionBtnBlk").find("#btnDeltgrid").length===0){
        $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnDeltgrid").hide();
        $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnDeltGridMax").hide();
    }else{
        $("#gridAdditionalFldMaxView .gridActionBtnBlk").find("#btnDeltgrid").show();
    }
    if ( rows == undefined || rows.length < 1)
    addNewSlickGridMaxRow(displayName,false);
    var height = $("#" + displayName).css("min-height");
    $("#CUSTOMFIELDMAXGRIDTR").css( "min-height",height);

    var existingMethod = $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnAddgrid").attr("onclick");
    if(existingMethod==undefined){
        existingMethod = $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnAddGridMax").attr("onclick");
    }
    var currentMethod = $("#CUSTOMFIELDTR"+fieldId+" #newGridRowAdd").attr("onclick");
    if(currentMethod == undefined){
        currentMethod = $("#LifeCycleCONFIG_TR"+fieldId+" #newGridRowAdd").attr("onclick");
    }
  
    if(currentMethod.toString().indexOf(",addNewGridSlickRow( "+fieldType+",'"+displayName+"',"+fieldId+" )") !== -1){
        currentMethod = currentMethod.replace(",addNewGridSlickRow( "+fieldType+",'"+displayName+"',"+fieldId+" )", "");
    } else if(currentMethod.toString().indexOf("addNewGridSlickRow( "+fieldType+",'"+displayName+"',"+fieldId+" )") !== -1){
        currentMethod = currentMethod.replace("addNewGridSlickRow( "+fieldType+",'"+displayName+"',"+fieldId+" )", "");
    }
  
    if ( existingMethod != null && existingMethod != undefined && existingMethod != "" && existingMethod.indexOf(currentMethod) == -1 )
        currentMethod = currentMethod + "," + existingMethod;
    else if ( existingMethod != undefined && existingMethod != "" )
        currentMethod = existingMethod;
    
    $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnAddgrid").attr("onclick", currentMethod);
    $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnAddGridMax").attr("onclick", currentMethod);


    existingMethod = $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnDeltgrid").attr("onclick");
    if(existingMethod==undefined){
        existingMethod = $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnDeltGridMax").attr("onclick");
    }
   
    currentMethod = $("#CUSTOMFIELDTR"+fieldId+" #deleteRowIco").attr("onclick");
    if(currentMethod == undefined){
        currentMethod = $("#LifeCycleCONFIG_TR"+fieldId+" #deleteRowIco").attr("onclick");
    }
   
    if(currentMethod.toString().indexOf(",deleteSlickGridRow( '"+displayName+"',"+fieldId+" )") !== -1){
        currentMethod = currentMethod.replace(",deleteSlickGridRow( '"+displayName+"',"+fieldId+" )", "");
    } else if(currentMethod.toString().indexOf("deleteSlickGridRow( '"+displayName+"',"+fieldId+" )") !== -1){
        currentMethod = currentMethod.replace("deleteSlickGridRow( '"+displayName+"',"+fieldId+" )", "");
    }
  
    if ( existingMethod != null && existingMethod != undefined && existingMethod != "" && existingMethod.indexOf(currentMethod) == -1 )
        currentMethod = currentMethod + "," + existingMethod;
    else if ( existingMethod != undefined && existingMethod != "" )
        currentMethod = existingMethod;
    
    $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnDeltgrid").attr("onclick", currentMethod);
    $("#maxViewGridBlk[data-gridfieldid='"+fieldId+"'] #btnDeltGridMax").attr("onclick", currentMethod);
    var updateFunction = $(this).attr("data-updateFunction");
    if ( updateFunction != undefined && updateFunction != "")
    {
        var grid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
        grid.onCellChange.subscribe(function(e, args) {
            eval( updateFunction +"()");
});
    }
	$("#btnAddgrid").show();
    $("#btnDeltgrid").show();
    $("#btnAddGridMax").show();
    $("#btnDeltGridMax").show();
    //data-updateFunction
    var divGrid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
    divGrid .resizeCanvas();
    if($("#CUSTOMFIELDMAXGRIDTR").parents(".sdMaxGrid").length==1){
        $("#gridAdditionalFldMaxView .inner-wrapper").perfectScrollbar("destroy");
    }
    $("#CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
});
$(document).on("click", "#gridMinimizeViewIco", function (e)
{
    var checkboxSelector = new Slick.CheckboxSelectColumn({
        cssClass: "slick-cell-checkboxsel",
        elementId: "ticketList"
    });
    //For remove customize methods added
    $("#gridAdditionalFldMaxView.cmdbGrid #btnAddGridMax").attr("onclick",'addNewSlickGridMaxRow()');
    $("#gridAdditionalFldMaxView.cmdbGrid #btnDeltGridMax").attr("onclick",'deleteNewSlickGridMaxRow()');
    $("#gridAdditionalFldMaxView.sdMaxGrid #btnAddgrid").attr("onclick",'addNewSlickGridMaxRow()');
    $("#gridAdditionalFldMaxView.sdMaxGrid #btnDeltgrid").attr("onclick",'deleteNewSlickGridMaxRow()');
    var fieldId = $("#maxViewGridBlk").attr("data-gridFieldId");
    var displayName = $("#maxViewGridBlk").attr("data-gridName");
    $('#'+displayName).data("gridInstance1").getEditorLock().commitCurrentEdit();
    $("#gridAdditionalFldMaxView").hide();
    $("body").css("overflow", "");
    var totalWidth = parseInt($("#" + displayName).width());
    var cols = $("#" + displayName).data("gridInstance1").getColumns();
    var rows = $("#" + displayName).data("gridInstance1").getData();

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

        var columnObj = cols[i];
        if (i !== 0) {
            individualWidth = ((columnObj.columnAttributes.colWidth / $(window).width()) * 100);
        } else {
            individualWidth = ((columnObj.width / $(window).width()) * 100);
        }
        individualWidth = (individualWidth * $(window).width()) / 100;

        columnObj.width = individualWidth;
    }

    var slickGridOption = getEditableSlickGridOptions("additionalField", slickGridOptions, -1);
    var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    if(((($("#viewWithMenu").is(":visible")===true  || $("#submitTicketParent").is(":visible")===true))&& $("#"+displayName).hasClass("gridParentClass")) || ($("#assetMainContainer").is(":visible")&&($(window).width()<1290 || browserZoomLevel!==100))){
        slickGridOption.autoHeight=false;
    }
    applySlickGridAttributes("" + displayName, slickGrid, rows, cols, slickGridOption, checkboxSelector);
    var height = $("#CUSTOMFIELDMAXGRIDTR" ).css("min-height");
    $("#"+displayName).css( "min-height",height);
    $(".slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
    var gridMinView=$("#" + displayName).data("gridInstance1");
    var updateFunction=$('#'+displayName).siblings('.gridActionBtnBlk').find('#gridMaxViewIco').attr("data-updatefunction");
    if(updateFunction!=undefined) {
        gridMinView.onCellChange.subscribe(function (e, args) {
            eval(updateFunction+"()");
        });
    }
    gridMinView.resizeCanvas();
    var mainContainer;
    if($("#"+displayName).parents("#viewWithMenu").length==1){
        mainContainer="viewWithMenu";
    }
    else if($("#"+displayName).parents("#submitTicketParent").length==1){
        mainContainer="submitTicketParent";
    }
    else{
        mainContainer=""
    }
    if(mainContainer!="") {
        $("#" + mainContainer + " #" + displayName).addClass("minHtGridFld");
    }
    $(".slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
});

function addNewGridSlickRow(fieldType, gridDisplayName, fieldId, isHeightTobeSetted)
{
	inputHeadChecked=false;
    var isCalenderField = false;
    var displayName = gridDisplayName;
    var defaultId = 'CUSTOMFIELD';
    if(fieldType == 1){
       defaultId = 'LifeCycleCONFIG_';
    }else{
       defaultId = 'CUSTOMFIELD';
    }
    if ( $("div#CUSTOMFIELDTR"+fieldId+".editable #calGridName").val() != undefined )
    {
        isCalenderField = true;
        displayName= "calGridView"+displayName;
    }
    var parentDivId = displayName;
    var gridSlick = $("#" + displayName).data("gridInstance1");
    $('#'+displayName).data("gridInstance1").getEditorLock().commitCurrentEdit();
    var dynamicRowValueAttributes = new Object();
    var data = gridSlick.getData();
    var fieldIdName = parentDivId.replace("gridView", "gridFieldIds");
    if ( isCalenderField)
    {
        fieldIdName = "calGridFieldIds"+$('#CUSTOMFIELDTR' + fieldId+".editable").find("input#gridBlkId").val();
    }
    var fieldIds = ($("#" + fieldIdName).val().trim()).split(",");
    var defaultValues = "";
    if($("#gridColumnDefaultData"+fieldId).length && $("#gridColumnDefaultData"+fieldId).val() != ""){
        defaultValues = JSON.parse($("#gridColumnDefaultData"+fieldId).val());
    }

    for (var fieldCount = 0; fieldCount < fieldIds.length; fieldCount++)
    {
        if(defaultValues === ""){
            dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = "";
        } else {
            var flag = true;
            $.each(defaultValues, function(key,val){
                if(""+key === defaultId + fieldIds[fieldCount]){
                    if(val === "true"){
                        val = true;
                    } else if(val === "false"){
                        val = false;
                    }
                    dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = val;
                    flag = false;
                }
            });
            if(flag){
                dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = "";
            }
        }
    }
    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);
    gridSlick.resizeCanvas();
    $("#" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-right").perfectScrollbar();
    if ( (isHeightTobeSetted == undefined ||  isHeightTobeSetted != false) && currRowNum != 0)
    {
    var prevHeight = $("#"+parentDivId).css("min-height");
    var newHeight = prevHeight.replace("px","");
    newHeight = parseInt(newHeight)+30;
    $("#"+parentDivId).css("min-height", newHeight+"px");
        var mainContainer;
        if($("#"+parentDivId).parents("#viewWithMenu").length==1){
            mainContainer="viewWithMenu";
        }
        else if($("#"+parentDivId).parents("#submitTicketParent").length==1){
            mainContainer="submitTicketParent";
        }
        else{
            mainContainer=""
        }
        if(mainContainer!="") {
            if ($("#" + mainContainer + " #" + parentDivId + " .grid-canvas.grid-canvas-top.grid-canvas-left .slick-row").length > 6) {
				var checkboxSelector = new Slick.CheckboxSelectColumn({
					cssClass: "slick-cell-checkboxsel",
					elementId: "ticketList"
				});
				var slickGridOption = getEditableSlickGridOptions("additionalField", slickGridOptions, -1);
				var cols = $("#" + parentDivId).data("gridInstance1").getColumns();
				var rows = $("#" + parentDivId).data("gridInstance1").getData();gridSlick.destroy();
				applySlickGridAttributes("" + parentDivId, slickGrid, rows, cols, slickGridOption, checkboxSelector);
                $("#" + mainContainer + " #" + parentDivId).addClass("minHtGridFld");
                $("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
                $("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left").scrollTop($("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left .grid-canvas.grid-canvas-top.grid-canvas-left").height());
            }
        }
    var updatedGrid = $("#"+parentDivId).data("gridInstance1");
    updatedGrid.resizeCanvas();
}
    if ( currRowNum == 0)
    {
        var divGrid = $("#"+parentDivId).data("gridInstance1");
        divGrid.updateRowCount();
        divGrid .resizeCanvas();
    }
     $("#"+parentDivId+" input[name='headerCheck']").attr("disabled",false);
      $("#"+parentDivId+" input[name='headerCheck']").prop("checked",false);
}
function deleteSlickGridRow(gridDisplayName, fieldId, isHeightTobeSetted)
{
	inputHeadChecked=false;
    var displayName = gridDisplayName;
    if ( $("div#CUSTOMFIELDTR"+fieldId+".editable #calGridName").val() != undefined )
    {
        displayName= "calGridView"+displayName;
    }
    var parentDivId = displayName;
    var mainContainer;
    if($("#"+parentDivId).parents("#viewWithMenu").length==1){
        mainContainer="viewWithMenu";
    }
    else if($("#"+parentDivId).parents("#submitTicketParent").length==1){
        mainContainer="submitTicketParent";
    }
    else{
        mainContainer=""
    }
	var setDefaultMinHt=false;
    var gridSlick = $("#" + displayName).data("gridInstance1");
    $('#'+displayName).data("gridInstance1").getEditorLock().commitCurrentEdit();
    var dd = gridSlick.getData();
    var totalLength = dd.length;
    var i=0;
    var checkedRows = [];
    var isHeaderCheckSelected=$("#"+parentDivId+" input[name='headerCheck']").prop("checked");
    if(isHeaderCheckSelected===true && mainContainer!="") {
        for(i=0;i<totalLength;i++) {
			checkedRows.push(i);
            dd[i] = null;
        }
		setDefaultMinHt=true;
    }
    else {
    $("#"+parentDivId+" .ui-widget-content .slick-cell-checkboxsel input[type='checkbox']").each(function ()
    {
        if ( $(this).prop("checked") == true)
        {
            checkedRows.push(i);
            dd[i] =null;
        }
        i++;
    } );
    }
    dd.clean(null);
    $("#"+parentDivId+" input[name='headerCheck']").prop("checked",false);
    for (var rowLength =0; rowLength < checkedRows.length; rowLength++ )
    {
        gridSlick.invalidateRow(checkedRows[rowLength]);
         gridSlick.setData(dd);
         gridSlick.updateRowCount();
         gridSlick.resizeCanvas();
         gridSlick.render();
         totalLength = totalLength -1;
         gridSlick.scrollRowIntoView(totalLength);
        if ( isHeightTobeSetted == undefined || isHeightTobeSetted != false )
        {
            var prevHeight = $("#"+parentDivId).css("min-height");
            var newHeight = prevHeight.replace("px","");
            newHeight = parseInt( newHeight )-30;
            if ( newHeight >= 85 )
                $("#"+parentDivId).css("min-height", newHeight+"px");
            else
            {
                $("#"+parentDivId).css("min-height", "85px");
            }
         }
    }
    if( mainContainer!="") {
        if ($("#" + mainContainer + " #" + parentDivId + " .grid-canvas.grid-canvas-top.grid-canvas-left .slick-row").length > 6) {
            $("#" + mainContainer + " #" + parentDivId).addClass("minHtGridFld");
            $("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
            $("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left").scrollTop(0);
            var divGrid = $("#"+parentDivId).data("gridInstance1");
            divGrid .resizeCanvas();
        }
		if ($("#" + mainContainer + " #" + parentDivId + " .grid-canvas.grid-canvas-top.grid-canvas-left .slick-row").length < 6) {
			$("#" + mainContainer + " #" + parentDivId).removeClass("minHtGridFld");
			if(setDefaultMinHt===true){
				$("#" + mainContainer + " #" + parentDivId).css("min-height","85px");
				$("#" + mainContainer + " #" + parentDivId + ".slick-viewport.slick-viewport-top.slick-viewport-left,#" + mainContainer + " #" + parentDivId + "  .slick-pane.slick-pane-top.slick-pane-left,#" + mainContainer + " #" + parentDivId + "  .grid-canvas.grid-canvas-top.grid-canvas-left").css("height","60px");
				$("#" + mainContainer + " #" + parentDivId + " .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
			}else{
                var totRows=gridSlick.getData().length;
                var finalHt=(totRows * 30) + 50;
                $("#" + mainContainer + " #" + parentDivId).css("min-height",finalHt+"px");
            }
		}
    }
     if($("#"+parentDivId+" .ui-widget-content .slick-cell-checkboxsel input[type='checkbox']").length==0)
       $("#"+parentDivId+" input[name='headerCheck']").attr("disabled","disabled");
    var divGrid = $("#"+parentDivId).data("gridInstance1");
    divGrid .resizeCanvas();


}



clean = function ( deleteValue )
{
  for (var i = 0; i < this.length; i++)
  {
    if (this[i] == deleteValue)
    {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

function addNewSlickGridMaxRow( isHeightTobeSetted )
{
    inputHeadChecked=false;
    var fieldId = $("#maxViewGridBlk").attr("data-gridFieldId");
    var isActionPermitted = $("#btnAddgrid[data-fieldid='"+fieldId+"']").attr("data-isActionPermitted");
    //if ( isActionPermitted == undefined || isActionPermitted == )
    var displayName = $("#maxViewGridBlk").attr("data-gridName");
    var fieldType = $("#maxViewGridBlk").attr("data-gridFieldType");
    var defaultId = 'CUSTOMFIELD';
    if(fieldType == 1){
       defaultId = 'LifeCycleCONFIG_';
    }else{
       defaultId = 'CUSTOMFIELD';
    }
    var parentDivId = displayName;
    $('#'+displayName).data("gridInstance1").getEditorLock().commitCurrentEdit();
    var gridSlick = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
    var dynamicRowValueAttributes = new Object();
    var data = gridSlick.getData();
    var fieldIdName = parentDivId.replace("gridView", "gridFieldIds");
    var fieldIds = ($("#" + fieldIdName).val().trim()).split(",");
    var defaultValues = "";
    if($("#gridColumnDefaultData"+fieldId).length && $("#gridColumnDefaultData"+fieldId).val() != ""){
        defaultValues = JSON.parse($("#gridColumnDefaultData"+fieldId).val());
    }
    for (var fieldCount = 0; fieldCount < fieldIds.length; fieldCount++)
    {
        if(defaultValues === ""){
            dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = "";
        } else {
            var flag = true;
            $.each(defaultValues, function(key,val){
                if(""+key === defaultId + fieldIds[fieldCount]){
                    if(val === "true"){
                        val = true;
                    } else if(val === "false"){
                        val = false;
                    }
                    dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = val;
                    flag = false;
                }
            });
            if(flag){
                dynamicRowValueAttributes[defaultId + fieldIds[fieldCount]] = "";
            }
        }
    }

    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);
    if ( (isHeightTobeSetted == undefined ||  isHeightTobeSetted != false) && currRowNum != 0 )
    {

    var prevHeight = $("#CUSTOMFIELDMAXGRIDTR").css("min-height");
    var mainContainer;
        if($("#CUSTOMFIELDMAXGRIDTR").parents(".sdMaxGrid").length==1){
            mainContainer="sdMaxGrid";
        }
        else{
            mainContainer=""
        }
        if(mainContainer!="") {
            if ($("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1").getData().length > 6) {
                var checkboxSelector = new Slick.CheckboxSelectColumn({
                    cssClass: "slick-cell-checkboxsel",
                    elementId: "ticketList"
                });
                var slickGridOption = getEditableSlickGridOptions("additionalField", slickGridOptions, -1);
                var cols = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1").getColumns();
                var rows = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1").getData();gridSlick.destroy();
                applySlickGridAttributes("CUSTOMFIELDMAXGRIDTR", slickGrid, rows, cols, slickGridOption, checkboxSelector);
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR").addClass("minHtGridFld");
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar();
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").scrollTop($("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left .grid-canvas.grid-canvas-top.grid-canvas-left").height());            }
        }
    var newHeight = prevHeight.replace("px","");
    newHeight = parseInt(newHeight)+30;
    if (newHeight >= 85)
    $("#CUSTOMFIELDMAXGRIDTR").css("min-height", newHeight+"px");
    var divGrid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
    divGrid.resizeCanvas();
}
   if ( currRowNum == 0)
    {
        var divGrid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
        divGrid .resizeCanvas();
    }
    if(mainContainer!="sdMaxGrid"){
$("#gridAdditionalFldMaxView .inner-wrapper").perfectScrollbar();
    }
$("#CUSTOMFIELDMAXGRIDTR input[name='headerCheck']").attr("disabled",false);
$("#CUSTOMFIELDMAXGRIDTR input[name='headerCheck']").prop("checked",false);
}

function deleteNewSlickGridMaxRow(fieldId, isHeightTobeSetted)
{
    inputHeadChecked=false;
    var fieldId = $("#maxViewGridBlk").attr("data-gridFieldId");
    var displayName = $('#CUSTOMFIELDTR' + fieldId+".editable").find("input#gridBlkId").val();
    var fieldType = $("#maxViewGridBlk").attr("data-gridFieldType");
    if(fieldType==1 && displayName==undefined){
        displayName = $('#LifeCycleCONFIG_TR' + fieldId+".editable").find("input#gridBlkId").val();
    }
    var parentDivId = displayName;
    var mainContainer;
    if($('#CUSTOMFIELDMAXGRIDTR').parents(".sdMaxGrid").length==1){
        mainContainer="sdMaxGrid";
    }
    else{
        mainContainer=""
    }
    var setDefaultMinHt=false;
    $('#'+displayName).data("gridInstance1").getEditorLock().commitCurrentEdit();
    var gridSlick = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
    var dd = gridSlick.getData();
    var totalLength = dd.length;
    var i=0;
    var checkedRows = [];
      var isHeaderCheckSelected=$("#CUSTOMFIELDMAXGRIDTR input[name='headerCheck']").prop("checked");
    if(isHeaderCheckSelected===true && mainContainer!="") {
        for(i=0;i<totalLength;i++) {
            checkedRows.push(i);
            dd[i] = null;
        }
        setDefaultMinHt=true;
    }
    else {
    $("#CUSTOMFIELDMAXGRIDTR .ui-widget-content .slick-cell-checkboxsel input[type='checkbox']").each(function ()
    {
        if ( $(this).prop("checked") == true)
        {
            checkedRows.push(i);
            dd[i] =null;
        }
        i++;
    } );
    }
    dd.clean(null);
    $("#CUSTOMFIELDMAXGRIDTR input[name='headerCheck']").prop("checked",false);
    for (var rowLength =0; rowLength < checkedRows.length; rowLength++ )
    {
         gridSlick.invalidateRow(checkedRows[rowLength]);
         gridSlick.setData(dd);
         gridSlick.updateRowCount();
         gridSlick.resizeCanvas();
         gridSlick.render();
         totalLength = totalLength -1;
         gridSlick.scrollRowIntoView(totalLength);
        if ( isHeightTobeSetted == undefined || isHeightTobeSetted != false )
        {
            var prevHeight = $("#CUSTOMFIELDMAXGRIDTR").css("min-height");
            var newHeight = prevHeight.replace("px","");
            newHeight = parseInt( newHeight )-30;
            if (newHeight >= 85)
                $("#CUSTOMFIELDMAXGRIDTR").css("min-height", newHeight+"px");
         }
    }
     if( mainContainer!="") {
        if ($("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1").getData()> 6) {
            $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR").addClass("minHtGridFld");
            $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
            $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").scrollTop(0);
            var divGrid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
            divGrid .resizeCanvas();
        }
        if ($("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1").getData() < 6) {
            $("#" + mainContainer + " #CUSTOMFIELDMAXGRIDTR").removeClass("minHtGridFld");
            if(setDefaultMinHt===true){
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR").css("min-height","85px");
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left,." + mainContainer + " #CUSTOMFIELDMAXGRIDTR  .slick-pane.slick-pane-top.slick-pane-left,." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .grid-canvas.grid-canvas-top.grid-canvas-left").css("height","60px");
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR .slick-viewport.slick-viewport-top.slick-viewport-left").perfectScrollbar("update");
            }else{
                var totRows=gridSlick.getData().length;
                var finalHt=(totRows * 30) + 50;
                $("." + mainContainer + " #CUSTOMFIELDMAXGRIDTR").css("min-height",finalHt+"px");
            }
        }
    }
     if($("#CUSTOMFIELDMAXGRIDTR .ui-widget-content .slick-cell-checkboxsel input[type='checkbox']").length==0)
       $("#CUSTOMFIELDMAXGRIDTR input[name='headerCheck']").attr("disabled","disabled");
    var divGrid = $("#CUSTOMFIELDMAXGRIDTR").data("gridInstance1");
    divGrid .resizeCanvas();


}

function importGrid(obj) {
    if ($(obj).hasClass("active")) {
        $(obj).removeClass("active");
        $(obj).siblings(".gridDataImpBlk").fadeOut(500);
    } else {
        $(".gridDataImpBlk").fadeOut(500);
        $(".importGrid").removeClass("active");
        $(obj).addClass("active");
        $(obj).siblings(".gridDataImpBlk").fadeIn(500);
        $("#impGridUpload").show();
        $("#importGridFile").val("");
        $('.choose').text('Choose a file...');
    }
}

$(document).on('click', '.cancelImpGrid', function () {
    $(".importGrid").removeClass("active");
    $(".gridDataImpBlk").fadeOut(500);
});

function validateGridImport(thisId, isMaximizeView) {
    var filePath = $('#importGridFile').val();
    if (filePath === '') {
        showImportErrorMsg('fileGrid');
        return false;
    }
    if (!validateFileFormate(filePath, 'SD_GRID_UPLOAD_FILE')) {
        showImportErrorMsg('gridFileFormat');
        return false;
    }

    var problemId = $(thisId).attr('data-gridProblemId');
    var projectId = $(thisId).attr('data-gridProjectId');
    var gridControlFieldId = $(thisId).attr('data-gridControlFieldId');
    var mainContentId = $("#CUSTOMFIELDTR" + gridControlFieldId+".editable").find("#gridBlkId").val();
    var displayName = $(thisId).attr('data-displayName');
    var formData = new FormData();
    formData.append("importGridFile", $('#importGridFile')[0].files[0]);
    formData.append("projectId", projectId);
    formData.append("problemId", problemId);
    formData.append("gridControlFieldId", gridControlFieldId);
    var rowDetails = [];
    if ( isMaximizeView != undefined && isMaximizeView == true)
    {
        mainContentId = "CUSTOMFIELDMAXGRIDTR";
    }
    var slickGrid = $("#" + mainContentId).data("gridInstance1");
    var columnDetails = slickGrid.getColumns();
    $.ajax({
        url: 'importTicketGridData.do',
        type: "POST",
        data: formData,
        async: false,
        dataType: 'json',
        success: function (data) {
            $(".gridDataImpBlk").fadeOut(500);
            $(".importGrid").removeClass("active");


            $.each(data, function (i, rowdata)
            {
                var fieldObject = new Object();
                $.each(rowdata, function (j, columnData)
                {
                    var fieldId = columnData.fieldid;
                    var data = columnData.data;
                    fieldObject["CUSTOMFIELD" + fieldId] = data;
                });
                rowDetails.push(fieldObject);

            });
            slickGrid.setData(rowDetails);
            slickGrid.updateRowCount();
            slickGrid.resizeCanvas();
            slickGrid.render();

            for (var x in data) {
                if (x == 0 || x % 2 == 0) {
                    $("#gridBody" + gridControlFieldId).append("<ul id=\"row" + x + "\" class=\" rowElem clicked\">");
                } else {
                    $("#gridBody" + gridControlFieldId).append("<ul id=\"row" + x + "\" class=\" greyLst rowElem clicked\">");
                }
                var attrData = "";
                var rowVals = "";
            }
        },
        error: function (data) {
            var resp = data.responseText;
            if (resp == "") {
                $(".gridDataImpBlk").fadeOut(500);
                $(".importGrid").removeClass("active");
            } else {
                showUploadErrorForImportGrid("<br><p><strong></strong>Upload Failed</p>");
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });
}
function rowValFunc(rowVals, attrData) {
    if (attrData == "Yes") {
        attrData = "1";
    } else if (attrData == "No") {
        attrData = "0";
    }
    var t = rowVals + "=" + attrData;
    return t;
}
function appendData(attrData) {
    if (attrData == "Yes") {
        attrData = "true";
    } else if (attrData == "No") {
        attrData = "false";
    }
    var s = "<input type=\"hidden\" name=\"columnValToSave\" id=\"columnValToSave\" value=\"" + attrData + "\">" +
            "<li class=\"wid25\">";
    var t = "";
    if (attrData == "true") {
        t = "<img src=\"assets/images/check.png\" class=\"checkedStat\"/>";
    } else if (attrData == "false") {
        t = "<img src=\"assets/images/uncheck.png\" class=\"checkedStat\"/>";
    } else if (attrData == "") {
        t = "&nbsp;";
    } else {
        t = "<span class=\"gridLabel\" title=\"" + attrData + "\">" + attrData + "</span>";
    }
    t = t + "</li>";
    var val = s + t;
    return val;
}

function showUploadErrorForImportGrid(message) {
    message = message.replace("<br><p><strong>", "");
    message = message.replace("</strong>", "");
    message = message.replace("</p>", "");
    message = '<p class="fldErr"><span class="topCurve"></span>' + message + '</p>';
    $('.fileGridSelect').addClass('impFld impRec mb0 errField');
    $('.errorMsgGrid').append(message);
}
function setBackSlickGridSortColumn(parentDivId, columnId, sortDir)
{
    var sortAsc = false;
    if (sortDir.toUpperCase() == "ASC")
    {
        sortAsc = true;
    }
    var slickGrid = $("#" + parentDivId).data("gridInstance1");
    var obj = {columnId: columnId, sortAsc: sortAsc};
    var cols = [];
    cols.push(obj);
    slickGrid.setSortColumns(cols);
}


$(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 + " input[type='checkbox'][disabled!='disabled']").prop("checked", true);
    } else
    {
        $("#" + parentId + " input[type='checkbox'][disabled!='disabled']").prop("checked", false);
    }
});

$(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 )
            {
            }
            else
            {
                $("#"+parentId+" input[name='headerCheck']").prop('checked', false);
                isAllchecked = false;
            }
        }
    } );
    if ( isAllchecked)
    {
        $("#"+parentId+" input[name='headerCheck']").prop('checked', true);
    }

});

function requiredFieldValidator(value) {
    if (value == null || value == "" || value == undefined || !value.length) {
        return {valid: false, msg: "This is a required field"};
    } else {
        return {valid: true, msg: null};
    }
}


function getColumnWidthBasedonTotalColumns(totalColumns, headerdata, totalSize, neglectedColumn, requestWidth, titleWidth)
{
   var columnWidth = 370;
    if (headerdata.field == "RequestID")
    {
        columnWidth = requestWidth;
    }
    else if (headerdata.field == "Title")
    {
        columnWidth = titleWidth;
    }else if (totalColumns <= 6){
        columnWidth = totalSize / ( totalColumns- neglectedColumn);
    }else if(headerdata.Fieldype == "ADF"){
        var tempWidth = totalSize / ( totalColumns- neglectedColumn);
        columnWidth = headerdata.maxWidth - (totalSize / ( totalColumns- neglectedColumn));
        columnWidth = columnWidth + tempWidth;
    }else{
        columnWidth = 180;
    }
    return columnWidth;
}

function getImportFileName(fieldId) {
    var parentDiv  ="";
    if (fieldId != undefined )
     parentDiv = "#CUSTOMFIELDTR"+fieldId+".editable";
    var filename = $(parentDiv+' #importGridFile').val().split('\\').pop();
    if($(parentDiv+' #importGridFile').val() !== ''){
         $(parentDiv+' #gridFileSelect').removeClass('impFld impRec mb0 errField').addClass('impFld impRec mb0');
         $('.choose').addClass('uploaded');
         $('.fldErr').remove();
    }
    if(filename==''){
        filename = 'Choose a file...';
    }
    $(parentDiv+" #importGridFile").siblings("label").find(".choose").text(filename);
}

function CheckmarkFormatter(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'>";
  }

  $(document).on('keydown', '.slick-pager .slick-pager-status input[type="text"]', function (e) {
    if (e.keyCode == 13) {
        var $pagerDiv = $(this).closest("div.pager");
        var totalPages = $pagerDiv.attr("data-totalpages");
        var pageType = $(this).closest("div.pager").attr('data-pagetype');
        var navigationType = "current";
        if (totalPages != undefined)
            totalPages = parseInt(totalPages);
        var pgno = parseInt($(this).val());
        if (pgno > totalPages)
        pgno = totalPages;
        if (pgno> 0 && pgno <= totalPages)
        {
            $pagerDiv.attr("data-pageno", pgno);
            loadPageTypeBasedonPageLimit(pageType, navigationType, e, this);
        }
    }
});

function getChangeViewHistoryColumnNames(changeType){
    var columns = [];
    if(changeType === 1){
        columns.push(getGridSlickColumnAttribute("assignFrom", "Owner Changed From", 300, "", "", "", false));
        columns.push(getGridSlickColumnAttribute("assignTo", "Owner Changed To", 300, "", "", "", false));
    }else{
        columns.push(getGridSlickColumnAttribute("assignFrom", "Approval Manager Changed From", 300, "", "", "", false));
        columns.push(getGridSlickColumnAttribute("assignTo", "Approval Manager Changed To", 300, "", "", "", false));
    }
    columns.push(getGridSlickColumnAttribute("modifiedBy", "Action Performed By", 310, "", "", false));
    columns.push(getGridSlickColumnAttribute("timeperiod", "Time Period", 300, "", "", true));
    return columns;
}


//$(document).on("click", ".readMoreHistory", function (e) {
//    $("#overlayHistoryDesc").empty();
//    $("#overlayHistoryDesc").fadeIn(400, "easeInOutCubic");
//    $("#overlayHistoryDesc").append('<div class="innerOverlay"><div class="attachBlk"><div class="attachFlds" id="attachFlds"></div><div class="fldAction" id="fldAction"> <a href="#" class="cancelLnk">Cancel</a></div></div></div>');
//
//    var cellText = $(this).prev("#decr").html();
//    $("#attachFlds").append(cellText);
//      $("#overlayHistoryDesc").perfectScrollbar();
//    e.stopPropagation();
//});

function resetExpandedDescription(el){
        var top = 0;
        $(el).parents(".grid-canvas.grid-canvas-top.grid-canvas-left").children(".ui-widget-content.slick-row").each(function (index) {
            if (index !== 0)
                top = top + 30;
            $(this).css("top", top + "px");
        });
        slickGridTempVariable.updateRowCount();
        slickGridTempVariable.resizeCanvas();
        slickGridTempVariable.render();
}
function strip(html)
{
    if (html.indexOf("&lt;script&gt;") > -1) {
        return html;
    }
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}
$(document).on("click",function(e){
	if(!$(e.target).is("#readMoreBlk *,.showMore")){
		$("#readMoreBlk").fadeOut().remove();$(".showMore").removeClass("opened");
	}
});
$(document).on("click", ".showMore", function() {

    if (!$(this).hasClass("opened")) {

            $("#readMoreBlk").fadeOut().remove();
            $(".showMore").removeClass("opened");
            $(this).addClass("opened");
        if($(this).parents(".ui-widget").hasClass("ticketHistoryGrid"))
        {
            var a = $(this).prev("#decr").html();
            var b = $(this).parents("div.slick-cell").siblings("div.slick-cell.l2.r2").find("span").text();
            $(this).parents(".ticketHistoryGrid").after('<div id="readMoreBlk" class="readMoreBlk"><h3>' + b + '</h3><div class="loadedData">' + a + "</div></div>");
            $("#readMoreBlk").fadeIn();
            $("#readMoreBlk").position({
                my: "center+30 top",
                at: "left top+20",
                of: ".showMore.opened",
                collision: "none"
            });
        }else if($(this).parents(".ui-widget").hasClass("assetHistoryGrid"))
        {
            var a = $(this).prev("#decr").html();
            var b = $(this).parents("div.slick-cell").siblings("div.slick-cell.l2.r2").find("span").text();
            $(this).parents(".assetHistoryGrid").after('<div id="readMoreBlk" class="readMoreBlk"><h3>' + b + '</h3><div class="loadedData">' + a + "</div></div>");
            $("#readMoreBlk").fadeIn();
            $("#readMoreBlk").position({
                my: "center+30 top",
                at: "left top+20",
                of: ".showMore.opened",
                collision: "none"
            });
        }else if($(this).parents(".ui-widget").hasClass("assetAssociatedRec"))
        {
            var a = $(this).prev("#decr").html();
            $(this).parents(".assetAssociatedRec").after('<div id="readMoreBlk" class="readMoreBlk"><h3>Description</h3><div class="loadedData">' + a + "</div></div>");
            $("#readMoreBlk").fadeIn();
            $("#readMoreBlk").position({
                my: "center+30 top",
                at: "left top+20",
                of: ".showMore.opened",
                collision: "none"
            });
        }else if($(this).parents(".ui-widget").hasClass("CMDBPhysicalAuditgrid"))
        {
            var a = $(this).prev("#decr").html();
            var b = "Address";
            if($(this).closest("div").hasClass("r7")){
              b = "Address";
            }else{
              b = "Comment";
            }
            $(this).parents(".CMDBPhysicalAuditgrid").after('<div id="readMoreBlk" class="readMoreBlk"><h3>'+ b +'</h3><div class="loadedData">' + a + "</div></div>");
            $("#readMoreBlk").fadeIn();
            $("#readMoreBlk").position({
                my: "right top",
                at: "right+20 top+20",
                of: ".showMore.opened",
                collision: "none"
            });
        }
        else
        {
            var c = $(this).prev("#decr").html();
            var d = $(this).parents("div.slick-cell").siblings("div.slick-cell.l0.r0").find("span").text();
            d=d.replace("changed","");
            $(this).parents("[id^='knowledgeBaseHistory']").after('<div id="readMoreBlk" class="readMoreBlk kb"><h3>' + d + '</h3><div class="loadedData">' + c + "</div></div>");
            $("#readMoreBlk.kb").fadeIn();
            $("#readMoreBlk.kb").position({
                my: "center+30 top",
                at: "left top+20",
                of: "[id^='knowledgeBaseHistory'] .showMore.opened",
                collision: "none"
            });
        }
    } else {
        $("#readMoreBlk").fadeOut();
        $(this).removeClass("opened");
    }
});
function setSlickgridScrollAdjuster()
{
    $(".slick-viewport.slick-viewport-top.slick-viewport-left").css("height",slickGridScrollHeight+"px");
}
function resetSlickGridCells()
{
$("#additionalFieldDiv .gridParentClass").each(function ()
    { var slickGrid = $(this).data("gridInstance1"); slickGrid.resetActiveCell();
});
}

// code added By Dheeraj Mishra for Drec16666
function gotoReportsOnInbuiltTemplate(a,template){
    arInbuiltCancelReport();
    var tempalteValue=template;
    var isPagelimit=false;
    var pageNo=0;
  var projectId = $('#selectedProjectId').val();
  arInbuiltListGridDataBasedonTemplate(projectId, pageNo, "Inbuilt", isPagelimit,template);
}

function loadPageTypeBasedonPageLimitInbuiltReport(pageType, navigationType, e, currentObject, isSorting, recordParams,isPagelimit,template)
{

    var pageSize = $("#recordLimit").val();
    var contentDivId = "slickgrid";
    var pagerId = "";
    var pageNo = 0;
    var totalPages = 1;

   contentDivId = "arInbuiltGrid";
   pagerId = "arInbuiltGridPager";

    if (isSorting == undefined || isSorting == false)
    {

           ($("#" + pagerId).attr("data-pageNo") != undefined)
            pageNo = $(currentObject).closest("div.pager").attr("data-pageNo");

        totalPages = $(currentObject).closest("div.pager").attr("data-totalpages");
        if ($(currentObject).closest("div.pager").attr("data-totalpages") != undefined)
        {
            totalPages =$(currentObject).closest("div.pager").attr("data-totalpages");
        }
        if (pageNo != 0)
        {
            if (navigationType == "next")
                pageNo = parseInt(pageNo) + 1;
            else if (navigationType == "last")
            {
                pageNo = totalPages;
            } else if (navigationType == "first")
            {
                pageNo = 1;
            }
            else if (navigationType == "current")
            {
                pageNo = parseInt(pageNo);
            }
            else
                pageNo = parseInt(pageNo) - 1;
        }


            $("#" + pagerId).attr("data-pageNo", parseInt(pageNo));
            $(currentObject).closest("div.pager").find("div.slick-pager span.slick-pager-status input[type='text']").val(parseInt(pageNo));

    }
    else
    {
        $("#" + pagerId+"[style!='display: none;']").attr("data-sortdir", recordParams.sortdir);
        $("#" + pagerId+"[style!='display: none;']").attr("data-sortcolumn", recordParams.sortcolumn);
        pageNo = $("#" + pagerId+"[style!='display: none;']").attr("data-pageno");
    }
    $(currentObject).closest("div.pager").find("#slickPaginationLoader").remove();
    $(currentObject).closest("div.pager").find(".slick-pager").append('<img id="slickPaginationLoader" src="assets/images/indicator.gif" />');
    $("#slickPaginationLoader").show();

	var projectId = $('#selectedProjectId').val();//
    arInbuiltListGridDataBasedonTemplate(projectId, pageNo, "Inbuilt", isPagelimit,template);
}
 var inputHeadChecked=false;
 $(document).on("mouseover","#additionalFieldDiv .minHtGridFld .slick-viewport.slick-viewport-top.slick-viewport-left.ps-container .slick-row",function(){
     var parentDivId=$(this).parents(".minHtGridFld").attr("id")
     var isHeaderCheckSelected=$("#"+parentDivId+" input[name='headerCheck']").prop("checked");
     if(isHeaderCheckSelected===true ||inputHeadChecked === true){
         inputHeadChecked=true;
         $("#"+parentDivId+" .slick-cell-checkboxsel input[type='checkbox']:not(:checked):not(.clicked)").attr("checked","checked").addClass("clicked");
     }else{
         inputHeadChecked=false;
     }
 });
 $(document).on("mousemove","#additionalFieldDiv .minHtGridFld .slick-viewport.slick-viewport-top.slick-viewport-left *",function(e){
	 if(!$(e.target).is(".ps-scrollbar-y-rail,.ps-scrollbar-y-rail *,.ps-scrollbar-x-rail,.ps-scrollbar-x-rail *")){
		$(".slick-viewport.slick-viewport-top.slick-viewport-left .ps-scrollbar-y-rail").mouseup()
	 }
 });
 function getChangeLogGridColumnNames()
 {
     var columns = [];
     columns.push(getGridSlickColumnAttribute("hostName", "Host Name", 210, "", "", false, false));
     columns.push(getGridSlickColumnAttribute("osName", "OS Name", 210, "", "", false, false));
     columns.push(getGridSlickColumnAttribute("moduleName", "Module Name", 210, "", "", false));
     columns.push(getGridSlickColumnAttribute("changeType", "Change Type", 210, "", "", false));
     columns.push(getGridSlickColumnAttribute("tableDesc", "Table Description", 210, "", "", false));
     columns.push(getGridSlickColumnAttribute("changeTime", "Change Detected Time", 210, "", "", false));
     return columns;
}
$(document).on("click",".longTextSaveBtn",function(){
    $(".longTextContainer").css("opacity","0").hide();
	setTimeout(function(){
    	$('.slick-cell.active.editable').parents(".gridParentClass").data("gridInstance1").getEditorLock().commitCurrentEdit();
	},100);
});
$(function(){
	var copiedSlickCellData;
	$("body").append('<div id="contextMenu" class="slickCellContextMenu" style="display: none; left: 538px; top: 84px;"><span id="copySlickCellData">Copy</span></div><textarea id="tempTextarea" style="width:0;height:0"></textarea>');
	var $contextMenu = $("#contextMenu");
    $("body").on("contextmenu", "#viewWithMenu .slick-cell,#additionalFieldDiv .gridParentClass .slick-cell,.viewDetailsBgBlk .gridParentClass1 .slick-cell,#allProjectSummary .slick-cell,#knowledgeBase .slick-cell,#reports .slick-cell,.sdMaxGrid #CUSTOMFIELDMAXGRIDTR .slick-cell", function(e) {
		$("#copySlickCellData").removeClass("disabled");
		var selection = window.getSelection();
		copiedSlickCellData=selection.toString();
		if($(this).hasClass("slick-cell-checkboxsel")==false && $(this).hasClass("mailIc")==false && $(this).hasClass("slickNoAttachIco")==false && $(this).hasClass("slickAttachIco")==false && $(this).hasClass("bookmarkTag")==false && $(this).hasClass("editTicket")==false && $(this).hasClass("ticketchangeState")==false && $(this).hasClass("quickView")==false && $(this).hasClass("editReport")==false && $(this).hasClass("copyReport")==false && $(this).hasClass("exportReport")==false && $(this).find(".redirectToOfflineReports").length==0 && $(this).hasClass("editLnkSop")==false && $(this).hasClass("editSopComplianceHistoryBlk")==false){
			 $(".slick-cell").removeClass("thisCell");
		     $(this).addClass("thisCell");
			 $contextMenu.show();
             if($(this).parents().hasClass("sdMaxGrid")||$(this).parents().hasClass("gridParentClass")||$(this).parents().hasClass("gridParentClass1")){
    		     $("#contextMenu").position({
    	            my: "left top",
    	            at: "center top+20",
    	            of: ".thisCell",
    	            collision: "none"
    	         });
             }else{
                $("#contextMenu").position({
	            my: "center+30 top",
	            at: "left top+20",
	            of: ".thisCell",
	            collision: "none"
	         });
             }
				if($(this).text()==""){
					$contextMenu.hide();
				}
	         return false;
		}
    });
    $('html').click(function() {
         $contextMenu.hide();
    });
	$(document).on("click","#copySlickCellData",function(){
		var textToCopy;		
		if(copiedSlickCellData != ""){
			$("#tempTextarea").val(copiedSlickCellData).select();
			document.execCommand('copy');	    
		}
        else{
			textToCopy=$(".thisCell span").text();
			$("#tempTextarea").val(textToCopy).select();
        	document.execCommand('copy');
		}		
        $("#tempTextarea").val("");
		$("#tempTextarea").empty();
	})
});
 function getNotificationLogGridColumnNames()
 {
     var columns = [];
     columns.push(getGridSlickColumnAttribute("notificationFor", "Notification For", 210, "", "", true, false));
     columns.push(getGridSlickColumnAttribute("notifiedTo", "Notified To", 210, "", "", true, false));
     columns.push(getGridSlickColumnAttribute("toMailId", "To Mail Address", 210, "", "", true));
	columns.push(getGridSlickColumnAttribute("ccMailId", "CC Mail Address", 210, "", "", true));
     columns.push(getGridSlickColumnAttribute("template", "Template", 210, "", "", true));
     columns.push(getGridSlickColumnAttribute("sentTime", "Sent Time", 210, "", "", true));

     return columns;
 }
 var action = "start"; // Assuming action is defined somewhere in your code
 function quickAnalysis(){
     var params = getTicketGridUrl($projectId);
     var changeType = $("a.switcher").attr("isChangeType");
     if(changeType !== undefined){
         params += "&changeType="+changeType;
     }
     var incidentType = getRequestType();
     params += '&requestType='+incidentType+'&profileId='+getSelectedFilterId();
     var urlParams = 'param1=' + encodeURIComponent(params) ;
     //window.open(jspPageUrl, '_blank');
     $.ajax({
         url: 'loadQuickAnalysis.do',
         type: "POST",
         data: urlParams,
         async: false,
         beforeSend: function() {
             $(".ringOverlay").show();
             action = "start";
             displayStatus(); // Start the loop
         },
         success: function(data){
             $("#sdFilterSetIcLnk,#projectRefresh").hide();
             $("#quickAnalysis").append(data);
             $("#quickAnalysis").show();
             $(".container #main-wrapper").hide();
         },
         error: function(xhr, status, error){
             console.error('Failed to fetch JSON data:', error);
         },complete : function(){
             $(".ringOverlay").hide();
             action = "stop";
             displayStatus(); // stop the loop
         }
     });
 }
 $(document).on("click", "#goBack", function(){
     $("#quickAnalysis").empty();
     $("#quickAnalysis").hide();
     $(".container #main-wrapper").show();
     $("#sdFilterSetIcLnk,#projectRefresh").show();
 });

 function displayStatus() {
     var statuses = ["Fetching Data", "Doing Analysis", "Preparing Screen", "Rendering", "Please wait..."];
     var index = 0;
     var statusElement = document.getElementById("load_qa");
     if (action == "stop") {
         statusElement.style.display = "none";
         return;
     }
     statusElement.textContent = statuses[index];
     index = (index + 1) % statuses.length;
     statusElement.style.display = "block";

     setTimeout(displayStatus, 3000); // Call displayStatus function recursively after 3000 milliseconds
 }
 function displayStatus() {
     var statuses = ["Fetching Data", "Doing Analysis", "Preparing Screen", "Rendering", "Please wait..."];
     var index = 0;
     var statusElement = document.getElementById("load_qa");
     if (action == "stop") {
         statusElement.style.display = "none";
         return;
     }
     statusElement.textContent = statuses[index];
     index = (index + 1) % statuses.length;
     statusElement.style.display = "block";

     setTimeout(displayStatus, 3000); // Call displayStatus function recursively after 3000 milliseconds
 }


