//------------------------------------------------------
// Author : Shubham Podhade
// Date : 08 July 2020
// Page Name : Workbench Drag and Drop Layout Designer
//------------------------------------------------------

//------------------------------------------------------
//******** Regions Present In Code *********************
//          1) varibale declaration
//          2) Interim Processing functions 
//          3) Button Click Events
//          4) Left Nav Bar Redering
//          5) Top Nav Bar Redering
//          6) Load Data from AJAX, Rest Api Calls
//          7) Document.Ready function
//------------------------------------------------------

//#region variable Declarations : START
var saveLayoutArr = [];
var fieldsDisplayList = [];
var actionLinksList = [];
var fieldData = [];
var inputArr1 = "";
var templateId = "";
var layOutCode = "";
var rows = "";
var columns = "";
var rowCount = [];
var colCount = [];
var maxRowNo = 0;
var maxColNo = 0;
var ddlDefaultSelectedRow = 0;
var ddlDefaultSelectedCol = 0;
var templateListArr = [];
var LayoutCodeArr = [];
var currentCssStyle = "";

var elementsTodeletefromSaveLayoutArr = [];
var cssStyleArr = [];
var serverAddress = "";
var dropperLabelArr = [];
var saveFlag=false;
var sHeight = "0";
var sFontWeight = "normal";
var sFontSize = "12";
var sColor = "";
var sWidth = "0";
var sVerticalAlign = "";
var sPaddingLeft = "0";
var sPaddingRight = "0";
var sPaddingTop = "0";
var sPaddingBottom = "0";
var designLabelID;
var sDisplayName = "";
var sTargetField = "";
var sVisibleYN = "";
var sDisplayNameCssStyle = "";
var sTargetFieldCssStyle = "";
var sScreenModeOpen = "";
var sDataType = "";
var sNumberFormat = "0";
var colCountForAL=0;
var colCountForIF=0;
var actionLinkEleId="";
var ALFieldData = [];
var saveLayoutArrForAL = [];
var ramIDAL = "";
var ramFieldPositionAL = "";
var ramFieldNameAL = "";
//#region variable Declarations : ENDS

function setFiniqsServiceURL(serviceUrl) {
    try {
        console.log('Finiq Service IP : ' + serviceUrl);
        serverAddress = serviceUrl;
    }
    catch (err) {
        console.log('Error in function setFiniqsServiceURL : ' + err.message)
    }
}


//#region Interim Processing Functions : START
    function changeFlag() {
   try{
    saveFlag = true;
  }catch(err){
    console.log('Error in function changeFlag : '+err.message)
  }
}

function decideMaxRowandCol() {
  try{
    maxRowNo = rowCount[0];
    maxColNo = colCount[0];
    for (var i = 0; i < rowCount.length; i++) {
      if (rowCount[i] > maxRowNo) {
        maxRowNo = rowCount[i];
      }
    }
    for (var i = 0; i < colCount.length; i++) {
      if (colCount[i] > maxColNo) {
        maxColNo = colCount[i];
      }
    }
  }
  catch(err){
    console.log('Error in function decideMaxRowandCol : ' +err.message);
  }
  
}
function getDBFieldId(fieldLabelId) {
  try{
    var fieldId = "";
    for (var j = 0; j < fieldData.length; j++) {
      if (fieldData[j].DesignLabelID == fieldLabelId) {
        fieldId = fieldData[j].FieldDisplayId;
        break;
      } else {
        fieldId = "";
      }
    }
    return fieldId;
  }
  catch(err){
    console.log('Error in function getDBFieldId : ' +err.message);
  }
 
}
function getDBFieldDispName(fieldLabelId) {
  try{
    var fieldDispName = "";
    for (var j = 0; j < fieldData.length; j++) {
      if (fieldData[j].DesignLabelID == fieldLabelId) {
        fieldDispName = fieldData[j].FieldDisplayName;
        break;
      } else {
        fieldDispName = "";
      }
    }
    return fieldDispName;
  }
  catch(err){
    console.log('Error in function getDBFieldDispName : ' +err.message);
  }
  
}
function getDBCSSStyle(fieldLabelId) {
  try{  
    var cssStyle = "";
    for (var j = 0; j < fieldData.length; j++) {
      if (fieldData[j].DesignLabelID == fieldLabelId) {
        cssStyle = fieldData[j].FieldStyle;
        cssStyle = cssStyle.replace("{", " ");
        cssStyle = cssStyle.replace("}", " ");
        break;
      } else {
        cssStyle = "";
      }
    }
    return cssStyle;

  }
  catch(err){
    console.log('Error in function getDBCSSStyle : ' +err.message);
  }
 
}
function checkForFieldIdPresence(fieldId) {
  try{
    var flag = false;
    for (var j = 0; j < fieldData.length; j++) {
      if (fieldData[j].FieldDisplayId == fieldId) {
        flag = true
        break;
      } else {
        flag = false;
      }
    }
    return flag;
  }
  catch(err){
    console.log('Error in function checkForFieldIdPresence : ' +err.message);
  }
 
}
function modifyMetaDataDisplayList(){
  try{ 
    var flag=false;
    if(dropperLabelArr.length>1){
    for(var i=0;i<(dropperLabelArr.length-1);i++){
      for(var j=0;j<fieldsDisplayList.length;j=j+2){
        //dropperLabelArr[i+1]==labelId && 
        if(dropperLabelArr[i]==fieldsDisplayList[j]){
          //delete fieldsDisplayList[j];
          fieldsDisplayList.splice(j,2);
          //delete fieldsDisplayList[j+1];
          //fieldsDisplayList.splice((j+1),1);
          flag = true;
       // }
        }
      }
    }
  }else{
    flag=false;
  }
    return flag;
  }catch(err){
    console.log('Error im modifyMetaDataDisplayList function :' + err.message);
  }
}

function deleteLabel(labelId) {
  try{
    if (confirm('Are you sure to delete this label ?')) {
      // Save it!
      var mydLabel = ""
    mydLabel = 'label#' + labelId + '';
    $(mydLabel).hide();
    //alert('Are you sure to delete this label ?');
    for(var i=0;i<saveLayoutArr.length;i=i+3){
      if(saveLayoutArr[i+1]==labelId){
          saveFlag=false;
          elementsTodeletefromSaveLayoutArr.push(labelId); 
          saveLayoutToDB();
          loadMatrixData();drawLayout();
          getMetadataFieldsList();
          fillMetadataFieldsList();
		  fillMetadataActionsList();
      }
    }
    } else {
      ;
    }
  }
  catch(err){
    console.log('Error in function deleteLabel : ' +err.message);
  }
}

function deleteLabelAL(labelId) {
    try {
         
        if (confirm('Are you sure to delete this label ?')) {
            // Save it!
            var mydLabel = ""
            mydLabel = labelId;
            $(mydLabel).hide();
            //alert('Are you sure to delete this label ?');
                    saveFlag = false;
                    getALDataActionLink(labelId);
                    saveLayoutToDB();
                    loadMatrixData(); drawLayout();
                    getMetadataFieldsList();
                    fillMetadataFieldsList();
                    fillMetadataActionsList();
                }
            }
    catch (err) {
        console.log('Error in function deleteLabelAL : ' + err.message);
    }
}



function applyCSSStyleOnPopUp() {
    try {
        if (confirm('Apply CSS Style ?')) {
            this1 = designLabelID;
            var myid = "";
            myid = "";
            myid = 'label#' + this1 + '';
            var prerareCSSStyle = "";
            prerareCSSStyle = "{ height:" + sHeight + ";font-weight:" + sFontWeight + ";font-size:" + sFontSize + ";color:" + sColor + ";width:" + sWidth + ";vertical-align:" + sVerticalAlign + ";padding-left:" + sPaddingLeft + ";padding-right:" + sPaddingRight + ";padding-top:" + sPaddingTop + ";padding-bottom:" + sPaddingBottom + "}";
            cssStyleArr.push(this1);
            cssStyleArr.push(prerareCSSStyle);
            $(myid).css({ 'height': sHeight, 'font-weight': sFontWeight, 'font-size': sFontSize, 'color': sColor, 'width': sWidth, 'vertical-align': sVerticalAlign, 'padding-left': sPaddingLeft, 'padding-right': sPaddingRight, 'padding-top': sPaddingTop, 'padding-bottom': sPaddingBottom });
        } else {
            ;
        }
    }
    catch (err) {
        console.log('Error in function applyCSSStyle : ' + err.message);
    }
}

function applyCSSStyle(this1) {
  try{
  if (confirm('Apply CSS Style ?')) {
    var myid = "";
  myid = "";
  myid = 'label#' + this1 + '';
  var prerareCSSStyle = "";
  prerareCSSStyle = "{ height:" + sHeight + "; font-weight:" + sFontWeight + "; font-size:" + sFontSize + "; color:" + sColor + ";width :" + sWidth + ";vertical-align:" + sVerticalAlign + ";padding-left:" + sPaddingLeft + ";padding-right:" + sPaddingRight + ";padding-top:" + sPaddingTop + ";padding-bottom:" + sPaddingBottom + "}";
  cssStyleArr.push(this1);
  cssStyleArr.push(prerareCSSStyle);
  $(myid).css({ 'height': sHeight, 'font-weight': sFontWeight, 'font-size': sFontSize, 'color': sColor, 'width': sWidth, 'vertical-align': sVerticalAlign, 'padding-left': sPaddingLeft, 'padding-right': sPaddingRight, 'padding-top': sPaddingTop, 'padding-bottom': sPaddingBottom });
  } else {
    ;
  }
  }
  catch(err){
    console.log('Error in function applyCSSStyle : ' +err.message);
  }
 }

function updateLatestTemplateId() {
  try{   
  templateId = $("#ddltemplateName option:selected").val();
  $(function () {
    $("#ddltemplateName").change(function () {
          document.getElementById("ddllayoutCode").selectedIndex = 0;
          layOutCode = $("#ddllayoutCode option:selected").text();
      cssStyleArr = [];
      templateId = "";
      templateId = $('option:selected', this).val();
      loadDefaultRowAndColCount();
      updateLatestRow();
      updateLatestColumn();
      fillTopNavBarRow2();
      loadMatrixData();
      drawLayout(); getMetadataFieldsList();
      getActionLinksFromCommonData();
      fillMetadataFieldsList();
      fillMetadataActionsList();
    });
  });
  }
  catch(err){
    console.log('Error in function updateLatestTemplateId : ' +err.message);
  }
}

function updateLatestLayoutCode() {
  try{
    layOutCode = $("#ddllayoutCode option:selected").text();
    $(function () {
      $("#ddllayoutCode").change(function () {
        //alert($('option:selected', this).text());
        layOutCode = "";
        layOutCode = $('option:selected', this).text();
        loadMatrixData();
        drawLayout(); getMetadataFieldsList();
        getActionLinksFromCommonData();
        fillMetadataFieldsList();
        fillMetadataActionsList();
      });
    });
  }
  catch(err){
    console.log('Error in function updateLatestLayoutCode : ' +err.message);
  }
 
}
function updateLatestRow() {
  try{
    rows = $("#rows option:selected").text();
  $(function () {
    $("#rows").change(function () {
      rows = "";
      rows = $('option:selected', this).text();
    });
  });
  }
  catch(err){
    console.log('Error in function updateLatestRow : ' +err.message);
  }
}
function updateLatestColumn() {
  try{
    columns = $("#columns option:selected").text();
    $(function () {
      $("#columns").change(function () {
        columns = "";
        columns = $('option:selected', this).text();
      });
    });
  }
  catch(err){
    console.log('Error in function updateLatestColumn : ' +err.message);
  }
}
//-------------------Action Links Specific Code---------------
function setALFieldPosition(RAM_ID, fieldPosition, fieldName) {
    try {
        var dispName = '';
        if (RAM_ID == 0) {
            var str = {
                "RAM_Id": + RAM_ID,
                "RAM_FieldName": "" + fieldName + "",
                "RAM_FieldPosition": "" + fieldPosition + ""  ,          
                "DisplayName": "" + sDisplayName + "",
                "LayoutCode": "" + layOutCode +"",
                "RAM_DataType": "" + sDataType + "",
                "RAM_DisplayFieldCssStyle": "" +  sDisplayNameCssStyle +  "",
                "RAM_NumberFormat":  + sNumberFormat ,
                "RAM_ScreenOpenMode": "" +  sScreenModeOpen +  "",
                "RAM_TargetField": "" +  sTargetField +  "",
                "RAM_TargetFieldCSSStyle": "" + sTargetFieldCssStyle + "",
                "RAM_TemplateID":  +  templateId  ,
                "RAM_VisibleYN": "" + sVisibleYN +  ""} ;
            ALFieldData.push(str);
            
        }
        for (var k = 0; k < ALFieldData.length; k++) {  
            //if (ALFieldData[k].RAM_Id == RAM_ID && ALFieldData[k].RAM_FieldName == fieldName) {
                if (ALFieldData[k].RAM_Id == RAM_ID ) {
                ALFieldData[k].RAM_FieldPosition = fieldPosition;
                break;
            } 
           
        } 
    }
    catch (err) {
        console.log('Error in function setALFieldPosition : ' + err.message);
    }
}

function getALDisplayName(fieldPostion){
  try{
    var dispName='';
    for(var k=0;k<ALFieldData.length;k++){
      if(ALFieldData[k].RAM_FieldPosition == fieldPostion){
        dispName = ALFieldData[k].DisplayName;
        break;
      }else{
        dispName = ""
      }
    }
    return dispName;
  }
  catch(err){
    console.log('Error in function getALDisplayName : ' + err.message);
  }

}
function getALDisplayNameFromFieldName(RAM_FieldName){
  try{
    var dispName='';
    for(var k=0;k<ALFieldData.length;k++){
      if(ALFieldData[k].RAM_FieldName == RAM_FieldName){
        dispName = ALFieldData[k].DisplayName;
        break;
      }else{
          dispName = RAM_FieldName;
      }
    }
    return dispName;
  }
  catch(err){
    console.log('Error in function getALDisplayNameFromFieldName : ' + err.message);
  }
}
function getALCssStyle(fieldPostion) {
    try {
        var cssStyle = '';
        for (var k = 0; k < ALFieldData.length; k++) {
            if (ALFieldData[k].RAM_FieldPosition == fieldPostion) {
                cssStyle = ALFieldData[k].RAM_DisplayFieldCssStyle;
                break;
            } else {
                cssStyle = ""
            }
        }
        return cssStyle;
    }
    catch (err) {
        console.log('Error in function getALCssStyle : ' + err.message);
    }
}
function getALData(fieldPostion){
  try{
    var objData=null;
    for(var k=0;k<ALFieldData.length;k++){
      if(ALFieldData[k].RAM_FieldPosition == fieldPostion){
        objData = ALFieldData[k]
        break;
      }else{
        objData = null
      }
    }
    return objData;
  }
  catch(err){
    console.log('Error in function getALDisplayName : ' + err.message);
  }
}
function getALDataActionLink(fieldPostion) {
    try {
        var objData = null;
        for (var k = 0; k < ALFieldData.length; k++) {
            if (ALFieldData[k].RAM_FieldPosition == fieldPostion) {
                ALFieldData[k].RAM_FieldPosition = "";
        objData = ALFieldData[k]
        break;
      }else{
        objData = null
      }
    }
    return objData;
  }
  catch(err){
    console.log('Error in function getALDisplayName : ' + err.message);
  }
}

function setALData(fieldPostion, objData) {
    try {
       
        for (var k = 0; k < ALFieldData.length; k++) {
            if (ALFieldData[k].RAM_FieldPosition == fieldPostion) {
                ALFieldData[k] = objData
                break;
            } 
        }
       
    }
    catch (err) {
        console.log('Error in function getALDisplayName : ' + err.message);
    }
}
//-------------------Action Links Specific Code---------------

//#region Interim Processing Functions : ENDS

//#region Button Click Events : START
function drawLayout() {
  try{
    saveLayoutArr = [];
    saveLayoutArrForAL = [];
    dropperLabelArr = [];
    var e = document.getElementById("rows");
    var selectedRow = e.options[e.selectedIndex].value;
    rows = selectedRow;
    var e = "";
    var e = document.getElementById("columns");
    var selectedColumn = e.options[e.selectedIndex].value;
    columns = selectedColumn;
    var rowsToDraw = 0;
    var colsToDraw = 0;
    var rowsToDrawFlag = false;
    var fieldDisplayName = "";
    var fieldCSSStyle = "";
    $("#threeDiv").empty();
    $("#threeDiv").append(
      '<table style="margin-top: 10px;margin-bottom: 3px;" id="tableForHeader" >'
    );
    if (selectedRow > 2) {
      rowsToDraw = 2;
      rowsToDrawFlag = true;
    } else {
      rowsToDraw = selectedRow;
      rowsToDrawFlag = false;
    }
    //----- Iterations Starts ----------
    for (j = 0; j < rowsToDraw; j++) {
      $("#tableForHeader").append('<tr  id="SecondTrId' + j + '" >');
      if (j <= 9) {
        for (i = 0; i < selectedColumn; i++) {
          if (i <= 9) {
            var exp = "";
            var exp1 = "";
            var exp = "Label0" + j + "0" + i + "";
            fieldDisplayName = getDBFieldDispName(exp);
            fieldCSSStyle = ""; 
            fieldCSSStyle = getDBCSSStyle(exp);
            if (!fieldDisplayName == "") {
              saveLayoutArr.push(getDBFieldId(exp));
              saveLayoutArr.push(exp);
              saveLayoutArr.push(fieldCSSStyle);
            }
            //if row number is :: 01 then align all items to center
            if(j==1){
              $("#SecondTrId" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdone'  ><div class='ui-widget-header myUIWidgetStyle'    style='text-align: center;font-weight: normal;height: 12px;padding: 7px 0px 7px 5px;margin-right: -12px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "'  id='" + exp + "'>"
                + fieldDisplayName +
                "</label><button type = 'button' class='btnHoverCloseForCSS'  onclick='cssDivPopUp(this.id);' id='" + exp + "' style ='visibility :hidden;'>CSS</button><button  type='button' class='btnHoverClose' onclick='deleteLabel(this.id);' id='" + exp + "' style='visibility: hidden;'></button></div></td>"
              );
            }else{
              $("#SecondTrId" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdone'  ><div class='ui-widget-header myUIWidgetStyle'   style='font-weight: normal;height: 12px;padding: 7px 0px 7px 5px;margin-right: -12px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "'  id='" + exp + "'>"
                + fieldDisplayName +
                "</label><button type = 'button' class='btnHoverCloseForCSS'  onclick='cssDivPopUp(this.id);' id='" + exp + "' style ='visibility :hidden;'>CSS</button><button  type='button' class='btnHoverClose' onclick='deleteLabel(this.id);' id='" + exp + "' style='visibility: hidden;'></button></div></td>"
              );
            } 
            $(".mytdone").droppable({
              drop: function (event, ui) {
                saveLayoutArr.push(ui.draggable.prop("id"));
                saveLayoutArr.push($(this).attr("id"));
                    saveLayoutArr.push("");

                    $('#' + ui.draggable.prop("id")).parent().css({ 'display': 'none' });
                    var textVal = $('#' + ui.draggable.prop("id")).text();
                    var lVal = $(this).attr("id");
                    $(this).find('div > label').text(textVal);
                    $('#' + ui.draggable.prop("id")).on("click", function () { applyCSSStyle(lVal); });
              },
            });
          } else {
            var exp = "";
            var exp1 = "";
            var exp = "Label0" + j + "" + i + "";
            fieldCSSStyle = "";
            fieldCSSStyle = getDBCSSStyle(exp);
            fieldDisplayName = getDBFieldDispName(exp);
            if (!fieldDisplayName == "") {
              saveLayoutArr.push(getDBFieldId(exp));
              saveLayoutArr.push(exp);
              saveLayoutArr.push(fieldCSSStyle);
            }
            //if row number is :: 01 then align all items to center
            if(j==1){
              $("#SecondTrId" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdtwo'  ><div class='ui-widget-header myUIWidgetStyle'    style='text-align: center;font-weight: normal;height: 12px;padding: 7px 0px 7px 5px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "'  id='" + exp + "'>"
                + fieldDisplayName +
                "</label></div></td>"
              );
            }else{
              $("#SecondTrId" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdtwo'  ><div class='ui-widget-header myUIWidgetStyle'    style='font-weight: normal;height: 12px;padding: 7px 0px 7px 5px;margin-right: -12px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "'  id='" + exp + "'>"
                + fieldDisplayName +
                "</label><button type = 'button' class='btnHoverCloseForCSS'  onclick='cssDivPopUp(this.id);' id='" + exp + "' style ='visibility :hidden;'>CSS</button><button  type='button' class='btnHoverClose' onclick='deleteLabel(this.id);' id='" + exp + "' style='visibility: hidden;'></button></div></td>"
              );
            }
            $(".mytdtwo").droppable({
              drop: function (event, ui) {
                saveLayoutArr.push(ui.draggable.prop("id"));
                saveLayoutArr.push($(this).attr("id"));
                    saveLayoutArr.push("");
                    $('#' + ui.draggable.prop("id")).parent().css({ 'display': 'none' });
                    var textVal = $('#' + ui.draggable.prop("id")).text();
                    var lVal = $(this).attr("id");
                    $(this).find('div > label').text(textVal);
                    $('#' + ui.draggable.prop("id")).on("click", function () { applyCSSStyle(lVal); });
              },
            });
          }
        }
      } else {
        $("#SecondTrId" + j + "").append("<td class='mytd'>Row " + j + "</td>");
        for (i = 0; i < selectedColumn; i++) {
          if (i <= 9) {
            $("#SecondTrId" + j + "").append("<td class='mytd'>Drop Here</td>");
          } else {
            $("#SecondTrId" + j + "").append("<td class='mytd'>Drop Here</td>");
          }
        }
      }
      $("#SecondTrId" + j + "").append("</tr>");
    }
    $("#tableForHeader").append("</table>");
  
    $("#fourDiv").empty();
    if (rowsToDrawFlag == true) {
      $("#threeDiv").append(
        '<table style="margin-top: 40px;margin-bottom: 3px;width: max-content;" id="tableForData" >'
      );
      for (j = 2; j < selectedRow; j++) {
        $("#tableForData").append('<tr  id="SecondTrId4Div' + j + '" >');
        if (j <= 9) {
          for (i = 0; i < selectedColumn; i++) {
            if (i <= 9) {
              var exp = "";
              var exp = "Label0" + j + "0" + i + "";
              fieldCSSStyle = "";
              fieldCSSStyle = getDBCSSStyle(exp);
              fieldDisplayName = getDBFieldDispName(exp);
              if (!fieldDisplayName == "") {
                saveLayoutArr.push(getDBFieldId(exp));
                saveLayoutArr.push(exp);
                saveLayoutArr.push(fieldCSSStyle);
              }
              $("#SecondTrId4Div" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdthree'><div class='ui-widget-header myUIWidgetStyle buttonhide' style='font-weight: normal; height: 12px;padding: 7px 0px 7px 5px;margin-right: -12px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "' id='" + exp + "'>" +
                fieldDisplayName +
                "</label><button type = 'button' class='btnHoverCloseForCSS'  onclick='cssDivPopUp(this.id);' id='" + exp + "' style ='visibility :hidden;'>CSS</button><button  type='button' class='btnHoverClose' onclick='deleteLabel(this.id);' id='" + exp + "' style='visibility: hidden;'></button></div></td>"
              );
                try{
                    $(".mytdthree").droppable({
                        drop: function (event, ui) {

                            saveLayoutArr.push(ui.draggable.prop("id"));
                            saveLayoutArr.push($(this).prev().attr("id"));
                            saveLayoutArr.push("");

                            $('#' + ui.draggable.prop("id")).parent().css({ 'display': 'none' });
                            var textVal = $('#' + ui.draggable.prop("id")).text();
                            var lVal = $(this).prev().attr("id");
                            $(this).prev().find('div > label').text(textVal);
                            $('#' + ui.draggable.prop("id")).on("click", function () { applyCSSStyle(lVal); });

                            //dropperLabelArr.push(ui.draggable.prop("id"));
                            //dropperLabelArr.push($(this).attr("id"));
                        },
                    });
                }
                catch (err) {
                    alert("Error in 3");
                }
              
            } else {
              var exp = "";
              var exp = "Label0" + j + "" + i + "";
              fieldCSSStyle = "";
              fieldCSSStyle = getDBCSSStyle(exp);
              fieldDisplayName = getDBFieldDispName(exp);
              if (!fieldDisplayName == "") {
                saveLayoutArr.push(getDBFieldId(exp));
                saveLayoutArr.push(exp);
                saveLayoutArr.push(fieldCSSStyle);
              }
              $("#SecondTrId4Div" + j + "").append(
                "<td id='" +
                exp +
                "' class='mytd mytdfour'><div class='ui-widget-header myUIWidgetStyle buttonhide'  style='font-weight: normal;  height: 12px; padding: 7px 0px 7px 5px;margin-right: -12px;'><label onclick='applyCSSStyle(this.id);' style='" + fieldCSSStyle + "' id='" + exp + "'>" +
                fieldDisplayName +
                "</label><button type = 'button' class='btnHoverCloseForCSS'  onclick='cssDivPopUp(this.id);' id='" + exp + "' style ='visibility :hidden;'>CSS</button><button  type='button' class='btnHoverClose' onclick='deleteLabel(this.id);' id='" + exp + "' style='visibility: hidden;'></button></div></td>"
              );
                try{
                    $(".mytdfour").droppable({
                        drop: function (event, ui) {
                            saveLayoutArr.push(ui.draggable.prop("id"));
                            saveLayoutArr.push($(this).prev().attr("id"));
                            saveLayoutArr.push("");
                            $('#' + ui.draggable.prop("id")).parent().css({ 'display': 'none' });
                            var textVal = $('#' + ui.draggable.prop("id")).text();
                            var lVal = $(this).prev().attr("id");
                            $(this).prev().find('div > label').text(textVal);
                            $('#' + ui.draggable.prop("id")).on("click", function () { applyCSSStyle(lVal); });
                        },
                    });
                }
                catch (err) {
                    alert("Error in 4");
                }
             
            }
          }
        } else {
          $("#SecondTrId4Div" + j + "").append(
            "<td class='mytd'>Row " + j + "</td>"
          );
          for (i = 0; i < selectedColumn; i++) {
            if (i <= 9) {
              $("#SecondTrId4Div" + j + "").append(
                "<td class='mytd'>Drop Here</td>"
              );
            } else {
              $("#SecondTrId4Div" + j + "").append(
                "<td class='mytd'>Drop Here</td>"
              );
            }
          }
        }
        $("#SecondTrId4Div" + j + "").append("</tr>");
      }
      $("#tableForData").append("</table>");
    }
    $("#threeDiv").append(
    '<table><tr id="LikeBtnMainTbl"><td><fieldset style="margin-top: 20px;margin-left: -8px;border: 1px solid #ffffff;width: max-content;">'+
    '<legend class="fieldsetlegend" style="font-size: 11px;color: #203455;">Like Button</legend>'+
    '<table style="margin-bottom: 3px;width: max-content;" id="tableForLikeButton">'
    );  
    $("#tableForLikeButton").append('<tr><td id="LikeBtn0000" class="mytd1 tdLike"><a style="text-decoration: revert; font-size: 13px;color: #0368b6;  ' + getALCssStyle('LikeBtn0000') + ' " href="#">' + getALDisplayName('LikeBtn0000') + '</a><input type="button" class="btnHoverCloseAL" onclick="deleteLabelAL(this.id);" id="LikeBtn0000" style="visibility: hidden;"></input></td></tr></table></fieldset></td>');
    $(".tdLike").droppable({
      drop: function (event, ui) {
       
            //if (ui.draggable.prop("id").includes('InfoField')) {
            //    alert('Info field cannot be dropped here.');
            //fillMetadataFieldsList()
            //    fillMetadataActionsList();
            //} else if (ui.draggable.prop("id").includes('ActionLink')) {
            //    alert('Action Link cannot be dropped here.');
          //fillMetadataFieldsList()
            //    fillMetadataActionsList();
            //}
        //if(ui.draggable.prop("id").includes('Label')){
        //  saveLayoutArrForAL.push('0');
        //}else{
        //  saveLayoutArrForAL.push(ui.draggable.prop("id"));
        //}
        //saveLayoutArrForAL.push('LikeButton');
        //saveLayoutArrForAL.push('LikeBtn0000');
            var ramId = 0;
            if (ui.draggable.prop("id").includes('Label')) {
                ramId = 0;
            }
            else
                ramId = ui.draggable.prop("id");

            setALFieldPosition(ramId, $(this).attr("id"), ui.draggable[0].innerText);

      },
    });
    $("#LikeBtnMainTbl").append(
      '<td><fieldset style="margin-top: 20px;margin-left: -11px;border: 1px solid #ffffff;width: max-content;">'+
      '<legend class="fieldsetlegend" style="font-size: 11px;color: #203455;">Action Links</legend>'+
      '<table style="margin-bottom: 3px;width: max-content;" id="tableForActionLinks">'
      );  
    $("#tableForActionLinks").append('<tr id="tableForActionLinksTr1">');
    for(var qq=0;qq<colCountForAL;qq++){
     
        $("#tableForActionLinksTr1").append('<td id="ActionLnk000' + qq + '" class="mytd1 tdAL"><a id="ActionLnk000' + qq + '" style="text-decoration: revert;font-size: 13px;color: #0368b6; ' + getALCssStyle('ActionLnk000' + qq) + '"  onclick="openActionLinksData(this.id);">' + getALDisplayName('ActionLnk000' + qq) + '</a><input type="button" class="btnHoverCloseAL" onclick="deleteLabelAL(this.id);" id="ActionLnk000' + qq + '" style="visibility: hidden;"></input></td>');
      $(".tdAL").droppable({
        drop: function (event, ui) {
         
                //if (ui.draggable.prop("id").includes('InfoField')) {
                //    alert('Info field cannot be dropped here.');
            //fillMetadataFieldsList()
                //    fillMetadataActionsList();
                //} else if (ui.draggable.prop("id").includes('LikeButton')) {
                //    alert('Like Button cannot be dropped here.');
            //fillMetadataFieldsList()
                //    fillMetadataActionsList();
                //}
          //if(ui.draggable.prop("id").includes('Label')){
          //  saveLayoutArrForAL.push('0');
          //}else{
          //  saveLayoutArrForAL.push(ui.draggable.prop("id"));
          //}
          //saveLayoutArrForAL.push(ui.draggable[0].innerText);
          //    saveLayoutArrForAL.push($(this).attr("id"));
             
              var ramId = 0;
              if (ui.draggable.prop("id").includes('Label')) {
                  ramId = 0;
              }
              else
                  ramId = ui.draggable.prop("id");

              setALFieldPosition(ramId, $(this).attr("id"), ui.draggable[0].innerText);

        
        },
      });
    }
    $("#tableForActionLinks").append('</tr></table></fieldset></td>');
    $("#LikeBtnMainTbl").append(
      '<td><fieldset style="margin-top: 20px;margin-left: -11px;border: 1px solid #ffffff;width: max-content;">'+
      '<legend class="fieldsetlegend" style="font-size: 11px;color: #203455;">Info Fields</legend>'+
      '<table style="margin-bottom: 3px;width: max-content;" id="tableForInfoFields">'
      );  
    $("#tableForInfoFields").append('<tr id="tableForInfoFieldsTr1">');
    for(var i=0;i<colCountForAL;i++){
        $("#tableForInfoFieldsTr1").append('<td id="InfoFld000' + (i + 1) + '" class="mytd1 tdIF"><a id="InfoFld000' + (i + 1) + '" style="text-decoration: revert; font-size: 13px;color: #0368b6; ' + getALCssStyle('InfoFld000' + (i + 1)) + '"  onclick="openActionLinksData(this.id);">' + getALDisplayName('InfoFld000' + (i + 1)) + '</a><input type="button" class="btnHoverCloseAL" onclick="deleteLabelAL(this.id);" id="InfoFld000' + (i + 1) + '" style="visibility: hidden;"></td>');
      $(".tdIF").droppable({
        drop: function (event, ui) {
         
          //if(ui.draggable.prop("id").includes('ActionLink')){
          //  alert('Action Link cannot be dropped here.');
            //fillMetadataFieldsList()
          //    fillMetadataActionsList();
          //}else if(ui.draggable.prop("id").includes('LikeButton')){
          //  alert('Like Button cannot be dropped here.');
              //fillMetadataFieldsList()
          //    fillMetadataActionsList();
          //}
          //if(ui.draggable.prop("id").includes('Label')){
          //  saveLayoutArrForAL.push('0');
          //}else{
          //  saveLayoutArrForAL.push(ui.draggable.prop("id"));
          //}
          //saveLayoutArrForAL.push(ui.draggable[0].innerText);
          //saveLayoutArrForAL.push($(this).attr("id"));
              var ramId = 0;
              if (ui.draggable.prop("id").includes('Label')) {
                  ramId = 0;
              }
              else
                  ramId = ui.draggable.prop("id");

              setALFieldPosition(ramId, $(this).attr("id"), ui.draggable[0].innerText);

        },
      });
    }
    $("#tableForInfoFields").append('</tr></table></fieldset></td></tr></table>');
    //------------------Code to set width for Header and Data Tables Elements Dyanamically----------------
    //===================----------START--------------====================================================
   var widthArrForData=[];
    var widthArrForData1=[];
    var maxi=0;
    for (var c = 0; c < columns; c++) {
      maxi=90;
      for (var r = 0; r < rows; r++) {
        if(r==0 || r==1){
          ;
        }else{
          if(c<=9){ 
            if(!$('#tableForData td#Label0'+r+'0'+c).text()==""){
              if($('#tableForData td#Label0'+r+'0'+c).width()>90){
                widthArrForData.push({key:'Label0'+r+'0'+c,value:$('#tableForData td#Label0'+r+'0'+c).width()});
                $('#tableForData td#Label0'+r+'0'+c).css('min-width',$('#tableForData td#Label0'+r+'0'+c).width());
                if($('#tableForData td#Label0'+r+'0'+c).width()>maxi)
                maxi=$('#tableForData td#Label0'+r+'0'+c).width();
              }else{
                widthArrForData.push({key:'Label0'+r+'0'+c,value:90});
                $('#tableForData td#Label0'+r+'0'+c).css('min-width',90);
              }
            }else{
             widthArrForData.push({key:'Label0'+r+'0'+c,value:90});
              $('#tableForData td#Label0'+r+'0'+c).css('min-width',90);
            }
          }else{
            if(!$('#tableForData td#Label0'+r+''+c).text()==""){
              if($('#tableForData td#Label0'+r+''+c).width()>90){
               widthArrForData.push({key:'Label0'+r+''+c,value:$('#tableForData td#Label0'+r+''+c).width()});
                $('#tableForData td#Label0'+r+''+c).css('min-width',$('#tableForData td#Label0'+r+''+c).width());
                if($('#tableForData td#Label0'+r+''+c).width()>maxi)
                maxi=$('#tableForData td#Label0'+r+''+c).width();
              }else{
                widthArrForData.push({key:'Label0'+r+''+c,value:90});
                $('#tableForData td#Label0'+r+''+c).css('min-width',90);
              }
            }else{
             widthArrForData.push({key:'Label0'+r+''+c,value:90});
              $('#tableForData td#Label0'+r+''+c).css('min-width',90);
            }
          }
        }
      }
      widthArrForData1.push(maxi);
    }
    var fffCount=0
    for(var q=0;q<widthArrForData1.length;q=q+2){
      if(fffCount<=9){   
        $('#tableForHeader td#Label000'+fffCount+'').css('min-width',widthArrForData1[q]+widthArrForData1[q+1]+3);
        $('#tableForHeader td#Label010'+fffCount+'').css('min-width',widthArrForData1[q]+widthArrForData1[q+1]+3);
      }else{
        $('#tableForHeader td#Label00'+fffCount+'').css('min-width',widthArrForData1[q]+widthArrForData1[q+1]+3);
        $('#tableForHeader td#Label01'+fffCount+'').css('min-width',widthArrForData1[q]+widthArrForData1[q+1]+3);
      }
      fffCount++;
    }
    //-----Code to set default width for remaining header columns-------------START
    for(var i=fffCount;i<columns;i++){
        if(i<=9){
          $('#tableForHeader td#Label000'+i+'').css('min-width',180);
          $('#tableForHeader td#Label010'+i+'').css('min-width',180);
        }else{
          $('#tableForHeader td#Label00'+i+'').css('min-width',180);
          $('#tableForHeader td#Label01'+i+'').css('min-width',180);
        }
    }
    //-----Code to set default width for remaining header columns-------------ENDS
    //===================----------END--------------====================================================
    //------------------Code to set width for Header and Data Tables Elements Dyanamically----------------
  }
  catch(err){
    console.log('Error in function drawLayout: ' +err.message);
  }
}


function saveLayoutToDB() {
    try {
        //
  var inputArr = "";
  for (var j = 0; j < elementsTodeletefromSaveLayoutArr.length; j++) {
    for (var i = 0; i < saveLayoutArr.length; i++) {
      //console.log('save layout array in db function '+ saveLayoutArr[i])
      if (elementsTodeletefromSaveLayoutArr[j] == saveLayoutArr[i]) {
        saveLayoutArr[i] = "";
      }
    }
  }
  for (var j = 0; j < cssStyleArr.length; j = j + 2) {
    for (var i = 0; i < saveLayoutArr.length; i = i + 3) {
      //console.log('save layout array in db function '+ saveLayoutArr[i])
      if (cssStyleArr[j] == saveLayoutArr[i + 1]) {
        saveLayoutArr[i + 2] = "";
        saveLayoutArr[i + 2] = cssStyleArr[j + 1];
      }
    }
  }

  inputArr = "{" + '"TemplateId":"' + templateId + '","LayoutCode":"' + layOutCode + '","fieldGridData" : [';
  var cssStyleRemoveEnter="";
  for (var i = 0; i < saveLayoutArr.length; i = i + 3) {
    //console.log("Element " + i + " " + saveLayoutArr[i]);
    cssStyleRemoveEnter = "";
    cssStyleRemoveEnter = (saveLayoutArr[i + 2].replace(/[\n\r\s]/g,''));
    if (i != saveLayoutArr.length - 3) {
      inputArr +=
        '{"FieldDisplayId": "' +
        saveLayoutArr[i] +
        '","DesignLabelID": "' +
        saveLayoutArr[i + 1] +
        '","FieldStyle": "' +
        cssStyleRemoveEnter  +
        '"},';
    } else {
      inputArr +=
        '{"FieldDisplayId": "' +
        saveLayoutArr[i] +
        '","DesignLabelID": "' +
        saveLayoutArr[i + 1] +
        '","FieldStyle": "' +
        cssStyleRemoveEnter  +
        '"}';
    }
  }
       
  //inputArr += '],' + '"actionData":[' 
  //for(var i=0;i<saveLayoutArrForAL.length;i=i+3){
  //  if(i!=saveLayoutArrForAL.length-3){
  //    inputArr +=
  //      '{"RAM_Id": "' +
  //      saveLayoutArrForAL[i] +
  //      '","RAM_FieldName": "' +
  //      saveLayoutArrForAL[i + 1] +
  //      '","RAM_FieldPosition": "' +
  //      saveLayoutArrForAL[i+2]  +
  //      '"},';
  //  }else{
  //    inputArr +=
  //    '{"RAM_Id": "' +
  //    saveLayoutArrForAL[i] +
  //    '","RAM_FieldName": "' +
  //    saveLayoutArrForAL[i + 1] +
  //    '","RAM_FieldPosition": "' +
  //    saveLayoutArrForAL[i+2]  +
  //    '"}';

  //  }
  //} 
        inputArr += '],' + '"actionData":['
        if (ALFieldData != null && ALFieldData.length > 0) {
            for (var i = 0; i < ALFieldData.length; i++) {
                


                inputArr += '{"DisplayName": "';
                inputArr += (typeof ALFieldData[i].DisplayName == "undefined" || ALFieldData[i].DisplayName == null) ? '' : ALFieldData[i].DisplayName.trim()
                inputArr +=  '" , "RAM_DataType": "'
                inputArr += (typeof ALFieldData[i].RAM_DataType == "undefined" || ALFieldData[i].RAM_DataType == null) ? '' : ALFieldData[i].RAM_DataType.trim() + '","RAM_DisplayFieldCssStyle": "'
                inputArr += (typeof ALFieldData[i].RAM_DisplayFieldCssStyle == "undefined" || ALFieldData[i].RAM_DisplayFieldCssStyle == null) ? '' : ALFieldData[i].RAM_DisplayFieldCssStyle.trim() + '","RAM_NumberFormat": "'
                if (ALFieldData[i].RAM_NumberFormat == 0) {
                    ALFieldData[i].RAM_NumberFormat = ALFieldData[i].RAM_NumberFormat.toString();
                }
                inputArr += (typeof ALFieldData[i].RAM_NumberFormat == "undefined" || ALFieldData[i].RAM_NumberFormat == null) ? '' : ALFieldData[i].RAM_NumberFormat.trim() + '","RAM_ScreenOpenMode": "'
                inputArr += (typeof ALFieldData[i].RAM_ScreenOpenMode == "undefined" || ALFieldData[i].RAM_ScreenOpenMode == null) ? '' : ALFieldData[i].RAM_ScreenOpenMode.trim() + '","RAM_TargetField": "'
                inputArr += (typeof ALFieldData[i].RAM_TargetField == "undefined" || ALFieldData[i].RAM_TargetField == null) ? '' : ALFieldData[i].RAM_TargetField.trim() + '","RAM_TargetFieldCSSStyle": "'
                inputArr += (typeof ALFieldData[i].RAM_TargetFieldCSSStyle == "undefined" || ALFieldData[i].RAM_TargetFieldCSSStyle == null) ? '' : ALFieldData[i].RAM_TargetFieldCSSStyle.trim() + '","RAM_VisibleYN": "'
                inputArr += (typeof ALFieldData[i].RAM_VisibleYN == "undefined" || ALFieldData[i].RAM_VisibleYN == null) ? '' : ALFieldData[i].RAM_VisibleYN.trim() + '","LayoutCode": "'
                inputArr += layOutCode + '","RAM_TemplateID": '
                inputArr += templateId + ',"RAM_Id": '
                inputArr += ALFieldData[i].RAM_Id + ',"RAM_FieldName": "'
                inputArr += (typeof ALFieldData[i].RAM_FieldName == "undefined" || ALFieldData[i].RAM_FieldName == null) ? '' : ALFieldData[i].RAM_FieldName.trim()
                inputArr += '","RAM_FieldPosition": "'
                    inputArr +=(typeof ALFieldData[i].RAM_FieldPosition == "undefined" || ALFieldData[i].RAM_FieldPosition == null)? '' : ALFieldData[i].RAM_FieldPosition.trim()
                inputArr += '"}';
                if (i < ALFieldData.length - 1) {
                    inputArr += ","
                }

                }
            }

  inputArr += ']}'
  saveLayout(inputArr);
  //console.log("---"+ inputArr);
  if(saveFlag==true){
    alert("Layout style saved.");
  }
  elementsTodeletefromSaveLayoutArr = [];
  cssStyleArr = [];
  loadMatrixData();drawLayout();
  getMetadataFieldsList(); 
        fillMetadataFieldsList();
        getActionLinksFromCommonData();
        fillMetadataActionsList();
  }
  catch(err){
    console.log('Error in function saveLayoutToDB : ' +err.message);
  }
}
//#region Button Click Events : ENDS

//#region ==================================================================================== CSS Style UI changes Code --- STARTS
//--- Function for : on click event of CSS Style Button UI Components ::: STARTS
function cssDivPopUp(this2) {
    try {

        designLabelID = this2;
    $("#divCssStyle").append("<table ID='table1'>");
    $("#table1").append("<tr id='tr1'>");
  
    $("#tr1").append("<td><input type='button' ID='btnSaveCssStyle' value='Apply' onclick='saveCssValues();applyCSSStyleOnPopUp();cssDivClose(); ' Class='btnGroupbox btn'/></td>");
  
    $("#tr1").append("<td><input type='button' ID='btnCancelCssStyle' value='X' onclick='cssDivClose();' Class='btn btnClose'/></td>");
    $("#table1").append("</tr></table>");
  
    $("#table1").append("<tr id='tr2'>");
    $("#tr2").append("<td><Label ID='lblPageHeight'>Height :</Label></td>");
    $("#tr2").append("<td><input type='Text' ID='txtPageHeight' tabIndex='1' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);'</td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr3'>");
    $("#tr3").append("<td><Label ID='lblFontWeigth'>Font-weight :</Label></td>");
      $("#tr3").append("<td><input type='Text' ID='txtFontWeigth' tabIndex='2'/></td> />");
    $("#tr3").append("</tr>");
  
    $("#table1").append("<tr id='tr4'>");
    $("#tr4").append("<td><Label ID='lblPageFontSize'>Font-size :</Label></td>");
      $("#tr4").append("<td><input type='Text' ID='txtPageFontSize' tabIndex='3' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);'/><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td> />");
    $("#tr4").append("</tr>");
  
    $("#table1").append("<tr id='tr5'>");
    $("#tr5").append("<td><Label ID='lblFontcolor'>Color :</Label></td>");
      $("#tr5").append("<td><input type='Color' ID='txtPageFontColor' tabIndex='4' style='width:160px;''/></td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr6'>");
    $("#tr6").append("<td><Label ID='lblWidth'>Width :</Label></td>");
      $("#tr6").append("<td><input type='Text' ID='txtWidth' tabIndex='5' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr7'>");
    $("#tr7").append("<td><Label ID='lblVerticalAlign'>Vertical-align :</Label></td>");
      $("#tr7").append("<td><input type='Text' ID='txtVerticalAlign' tabIndex='6' value=''/></td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr8'>");
    $("#tr8").append("<td><Label ID='lblPaddingLeft'>Padding-Left :</Label></td>");
      $("#tr8").append("<td><input type='Text' ID='txtPaddingLeft' tabIndex='7' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td>");
    $("table1").append("</tr>");
  
    $("#table1").append("<tr id='tr9'>");
    $("#tr9").append("<td><Label ID='lblPaddingRight'>Padding-Right :</Label></td>");
      $("#tr9").append("<td><input type='Text' ID='txtPaddingRight' tabIndex='8' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr10'>");
    $("#tr10").append("<td><Label ID='lblPaddingTop'>Padding-Top :</Label></td>");
      $("#tr10").append("<td><input type='Text' ID='txtPaddingTop' tabIndex='9' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td>");
    $("table1").append("</tr>");
  
    $("#table1").append("<tr id='tr11'>");
    $("#tr11").append("<td><Label ID='lblPaddingBottom'>Padding-Bottom :</Label></td>");
      $("#tr11").append("<td><input type='Text' ID='txtPaddingBottom' tabIndex='10' Class='changeSizeTextBox' value='0' onkeypress='return isNumberKey(event);'/><input type='button' class='btn btnSize' value='+' onclick='changeSize(this);' /><input type='button' class='btn btnSize' value='-' onclick='changeSize(this);' /></td>");
    $("#table1").append("</tr>");
  
    $("#table1").append("<tr id='tr12'>");
    $("#tr12").append("<td><Label ID='lblOther'>Other :</Label></td>");
  
      $("#tr12").append("<td><textarea ID='txtOther' tabIndex='11' value='' style='Height:85px; Width:190px;'></textarea></td>");
    $("#table1").append("</tr>");
  
  
    $("#divCssStyle").append("</table>");
    $('#btnCssPanelOpen').attr('disabled', 'disabled');
    document.getElementById("divCssStyle").style.display = "block";

    if (sHeight.includes("px")){
        sHeight = sHeight.replace("px", "");
        document.getElementById("txtPageHeight").value = sHeight;
    }
    else
    {
        document.getElementById("txtPageHeight").value = sHeight;
    }
    if (sFontSize.includes("px")) {
        sFontSize = sFontSize.replace("px", "");
        document.getElementById("txtPageFontSize").value = sFontSize;
    }
    else {
        document.getElementById("txtPageFontSize").value = sFontSize;
    }

    if (sWidth.includes("px")) {
        sWidth = sWidth.replace("px", "");
        document.getElementById("txtWidth").value = sWidth;
    }
    else {
        document.getElementById("txtWidth").value = sWidth;
    }
    if (sPaddingLeft.includes("px")) {
        sPaddingLeft = sPaddingLeft.replace("px", "");
        document.getElementById("txtPaddingLeft").value = sPaddingLeft;
    }
    else {
        document.getElementById("txtPaddingLeft").value = sPaddingLeft;
    }
    if (sPaddingRight.includes("px")) {
        sPaddingRight = sPaddingRight.replace("px", "");
        document.getElementById("txtPaddingRight").value = sPaddingRight;
    }
    else {
        document.getElementById("txtPaddingRight").value = sPaddingRight;
    }
    if (sPaddingTop.includes("px")) {
        sPaddingTop = sPaddingTop.replace("px", "");
        document.getElementById("txtPaddingTop").value = sPaddingTop;
    }
    else {
        document.getElementById("txtPaddingTop").value = sPaddingTop;
    }
    if (sPaddingBottom.includes("px")) {
        sPaddingBottom = sPaddingBottom.replace("px", "");
        document.getElementById("txtPaddingBottom").value = sPaddingBottom;
    }
    else {
        document.getElementById("txtPaddingBottom").value = sPaddingBottom;
    }
    document.getElementById("txtFontWeigth").value = sFontWeight;          
    document.getElementById("txtPageFontColor").value = sColor;            
    document.getElementById("txtVerticalAlign").value = sVerticalAlign;   
      
       
        
    
  }
  catch(err){
    console.log('Error in function cssDivPopUp : ' +err.message);
  }
 
}
//--- Function for : on click event of CSS Style Button UI Components ::: ENDS

//--- Function for : to make CSS div draggable :: STARTS
$(function () {
  $("#divCssStyle").draggable();
  $("#divPreview").draggable();
  $("#divActionlinksPanel").draggable();
});
//--- Function for : to make CSS div draggable :: ENDS

//--- Function for : to save CSS values in global variables on apply button click :: STARTS
function saveCssValues() {
  try{
    //currentCssStyle = "";
  sHeight = "";
  sHeight = document.getElementById("txtPageHeight").value + 'px';
  sFontWeight = "";
  sFontWeight = document.getElementById("txtFontWeigth").value;
  sFontSize = "";
  sFontSize = document.getElementById("txtPageFontSize").value + 'px';
  sColor = "";
  sColor = document.getElementById("txtPageFontColor").value;
  sWidth = "";
  sWidth = document.getElementById("txtWidth").value + 'px';
  sVerticalAlign = "";
  sVerticalAlign = document.getElementById("txtVerticalAlign").value;
  sPaddingLeft = "";
  sPaddingLeft = document.getElementById("txtPaddingLeft").value + 'px';
  sPaddingRight = "";
  sPaddingRight = document.getElementById("txtPaddingRight").value + 'px';
  sPaddingTop = "";
  sPaddingTop = document.getElementById("txtPaddingTop").value + 'px';
  sPaddingBottom = "";
  sPaddingBottom = document.getElementById("txtPaddingBottom").value + 'px';
  }
  catch(err){
    console.log('Error in function saveCssValues : ' +err.message);
  }
  
}
//--- Function for : to save CSS values in global variables on apply button click :: ENDS

//--- Function to stick default values on UI of CSS Style Div  :: STARTS
function saveCssValues3() {
  try{   
  var a = "{height: 0px !important; font-weight: normal; font-size: 15px !important; color: #623232 !important; width: 0px !important; vertical-align: Left; padding-left: 0px !important; padding-right: 0px !important; padding-top: 0px !important; padding-bottom: 0px !important;}"
  var value = "";
  var record = "";
  var splitstring = a.split(";");
  splitstring.forEach(function (record) {
    record = record.replace("}", "");
    record = record.replace("{", "");

    if (record.toUpperCase().includes("FONT-SIZE")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPageFontSize").value = value;
      value = "";
    } else if (record.toUpperCase().includes("HEIGHT")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPageHeight").value = value;
      value = "";
    } else if (record.toUpperCase().includes("PADDING-LEFT")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPaddingLeft").value = value;
      value = "";
    } else if (record.toUpperCase().includes("PADDING-RIGHT")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPaddingRight").value = value;
      value = "";
    } else if (record.toUpperCase().includes("PADDING-TOP")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPaddingTop").value = value;
      value = "";
    } else if (record.toUpperCase().includes("PADDING-BOTTOM")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch) && ch != '-') {
          value = value + ch;
        }
      });
      document.getElementById("txtPaddingBottom").value = value;
      value = "";

    }
    else if (record.toUpperCase().includes("FONT-WEIGHT")) {
      splitvar = record.split("!");
      i = "";
      if (splitvar.length = 1) {
        for (i = 0; i < splitvar.length; i++) {
          if (splitvar[i].toUpperCase().includes("FONT-WEIGHT:")) {
            value = splitvar[i].replace("font-weight: ", "");
            value = value.replace(/\s/g, "");
            document.getElementById("txtFontWeigth").value = value.toString();
            value = "";
          }
        }
      }
      else {
        for (i = 0; i < splitvar.length - 1; i++) {
          if (splitvar[i].toUpperCase().includes("FONT-WEIGHT:")) {
            value = splitvar[i].replace("font-weight:", "");
            value = value.replace(/\s/g, "");
            document.getElementById("txtFontWeigth").value = value.toString();
            value = "";
          }
        }
      }
    } else if (record.toUpperCase().includes("VERTICAL-ALIGN")) {
      splitvar = record.split("!");
      i = "";
      if (splitvar.length = 1) {
        for (i = 0; i < splitvar.length; i++) {
          if (splitvar[i].toUpperCase().includes("VERTICAL-ALIGN:")) {
            value = splitvar[i].replace("vertical-align: ", "");
            value = value.replace(/\s/g, "");
            document.getElementById("txtVerticalAlign").value = value.toString();
            value = "";
          }
        }
      }
      for (i = 0; i < splitvar.length - 1; i++) {
        if (splitvar[i].toUpperCase().includes("VERTICAL-ALIGN:")) {
          value = splitvar[i].replace("vertical-align:", "");
          value = value.replace(/\s/g, "");
          document.getElementById("txtVerticalAlign").value = value.toString();
          value = "";
        }
      }
    } else if (record.toUpperCase().includes("WIDTH")) {
      record.split('').forEach(function (ch) {
        if (isCharDigit(ch)) {
          value = value + ch;
        }
      });
      document.getElementById("txtWidth").value = value;
      //console.log("txtWidth :-> " + document.getElementById("txtWidth").text);
      value = "";
    } else if (record.toUpperCase().includes("COLOR")) {
      splitvar = record.split("!");
      i = "";
      if (splitvar.length = 1) {
        for (i = 0; i < splitvar.length; i++) {
          if (splitvar[i].toUpperCase().includes("COLOR")) {
            value = splitvar[i].replace("color:", "");
            document.getElementById("txtPageFontColor").value = value.trim();
            value = "";
          }
        }
      }
      else {
        for (i = 0; i < splitvar.length - 1; i++) {
          if (splitvar[i].toUpperCase().includes("COLOR")) {
            value = splitvar[i].replace("color: #", "");
            document.getElementById("txtPageFontColor").text = value.toString();
            value = "";
          }
        }
      }
    } else {
      if (document.getElementById("txtOther").text = "undefined") {
        document.getElementById("txtOther").text = "";
        document.getElementById("txtOther").value = document.getElementById("txtOther").value + document.getElementById("txtOther").text + record.toString() + "";
      }
      else {
        document.getElementById("txtOther").value = document.getElementById("txtOther").text + record.toString();
      }
    }

  });
  }
  catch(err){
    console.log('Error in function saveCssValues3 : ' +err.message);
  }
}
//--- Function to stick default values on UI of CSS Style Div  :: ENDS

//--- Function for : to close CSS Style div  :: STARTS  
function cssDivClose() {
  try{
    $('#btnCssPanelOpen').removeAttr('disabled');
    document.getElementById("divCssStyle").innerHTML = "";
    document.getElementById("divCssStyle").style.display = "none";
  }
  catch(err){
    console.log('Error in function cssDivClose : ' +err.message);
  }
}
//--- Function for : to close CSS Style div  :: ENDS  

//--- Function for : to change values in text boxes on + and - button click of  CSS Style div  :: STARTS  
function changeSize(that) {
  try{
    if (that.value == "+") {
      $(that).parent().find('.changeSizeTextBox')[0].value = parseInt($(that).parent().find('.changeSizeTextBox')[0].value) + 1
    }
    else if ($(that).parent().find('.changeSizeTextBox')[0].value > 0) {
      $(that).parent().find('.changeSizeTextBox')[0].value = parseInt($(that).parent().find('.changeSizeTextBox')[0].value) - 1
    }
  }
  catch(err){
    console.log('Error in function changeSize : ' +err.message);
  }
}
//--- Function for : to change values in text boxes on + and - button click of  CSS Style div  :: STARTS  

//--- Function for : to validate values in text boxes on + and - button click of  CSS Style div  :: STARTS  
function isNumberKey(evt) {
  try{

    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;
    return true;
  }
  catch(err){
    console.log('Error in function isNumberKey : ' +err.message);
  }
}

function isCharDigit(n) {
  try{
    return !!n.trim() && !!Number(n + .1);

  }
  catch(err){
    console.log('Error in function isCharDigit : ' +err.message);
  }
  
}
//--- Function for : to validate values in text boxes on + and - button click of  CSS Style div  :: STARTS  

//--- Function For Action Links UI Starts-----------------
function openActionLinksData(fieldId) {
    try {
        //
      $("#divActionlinksPanel").append("<table ID='table2' cellpadding='2' >");
      $("#table2").append("<tr id='tr1'>");

        $("#tr1").append("<td><input type='button' ID='btnSaveActionLinksData' value='Apply' onclick='saveActionLinksData1(" + fieldId+");' Class='btnGroupbox btn'/></td>");

      $("#tr1").append("<td><input type='button' ID='btnCancelActionLinksData' value='X' onclick='cancelActionLinksData();' Class='btn btnClose'/></td>");
      $("#table2").append("</tr></table>")

      $("#table2").append("<tr id='tr2'>");
      $("#tr2").append("<td><Label ID='lblDisplayName'>Display Name :</Label></td>");
      $("#tr2").append("<td><input type='Text' ID='txtDisplayName' tabIndex='1' Class='actionlinkstextbox'/></td>");
      $("#table2").append("</tr>");

      $("#table2").append("<tr id='tr3'>");
      $("#tr3").append("<td><Label ID='lblTargetField'>Target Field :</Label></td>");
      $("#tr3").append("<td><input type='Text' ID='txtTargetField' tabIndex='2' class='actionlinkstextbox'/></td> />");
      $("#tr3").append("</tr>");

      $("#table2").append("<tr id='tr4'>");
      $("#tr4").append("<td><Label ID='lblVisibleYN'>Visible Y/N:</Label></td>");
      $("#tr4").append("<td><select id = 'ddlVisibleYN' tabIndex='3' class ='selectwidth1'><option value='Y'>Y</option><option value='N'>N</option></select></td>/>");
      $("#tr4").append("</tr>");

      $("#table2").append("<tr id='tr5'>");
      $("#tr5").append("<td><Label ID='lblDisplayNameCSSStyle'>Display Name CSS Style :</Label></td>");
      $("#tr5").append("<td><textarea ID='txtDisplayNameCSSStyle' tabIndex='4' style='Height:54px; Width:140px;'></textarea></td>");
      $("#table1").append("</tr>");

      $("#table2").append("<tr id='tr6'>");
      $("#tr6").append("<td><Label ID='lblTargetFieldCSSStyle'>Target Field CSS Style :</Label></td>");
      $("#tr6").append("<td><textarea ID='txtTargetFieldCSSStyle' tabIndex='5' style='Height:54px; Width:140px;'></textarea></td>");
      $("#table1").append("</tr>");

      $("#table2").append("<tr id='tr7'>");
      $("#tr7").append("<td><Label ID='lblScreenOpenMode'>Screen Open Mode :</Label></td>");
      $("#tr7").append("<td><select id = 'ddlScreenOpenMode' tabIndex='6' class ='selectwidth1'><option value='Inline'>Inline</option><option value='PopUp'>PopUp</option></select></td>");
      $("#table2").append("</tr>");

      $("#table2").append("<tr id='tr8'>");
      $("#tr8").append("<td><Label ID='lblDataType'>Data Type	:</Label></td>");
      $("#tr8").append("<td><select id = 'ddlDataType' tabIndex='7' class ='selectwidth1'><option value='Text'>Text</option><option value='Number'>Number</option><option value='Amount'>Amount</option></select></td>");
      $("table2").append("</tr>");

      $("#table2").append("<tr id='tr9'>");
      $("#tr9").append("<td><Label ID='lblNumberFormat'>Number Format :</Label></td>");
      $("#tr9").append("<td><select id = 'ddlNumberFormat' tabIndex='8' class ='selectwidth1'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option></select></td>");
      $("#table2").append("</tr>");

      $("#divActionlinksPanel").append("</table>");
      document.getElementById("divActionlinksPanel").style.display = "block";
      document.getElementById("ddlVisibleYN").selectedIndex = -1;
      document.getElementById("ddlScreenOpenMode").selectedIndex = -1;
      document.getElementById("ddlDataType").selectedIndex = -1;
      document.getElementById("ddlNumberFormat").selectedIndex = -1;

       
      var myObjAL=null;
        myObjAL = getALData(fieldId);
        if (myObjAL != null) {
            document.getElementById("txtDisplayName").value = myObjAL.DisplayName;
            document.getElementById("txtTargetField").value = myObjAL.RAM_TargetField;
            document.getElementById("txtDisplayNameCSSStyle").value = myObjAL.RAM_DisplayFieldCssStyle;
            document.getElementById("txtTargetFieldCSSStyle").value = myObjAL.RAM_TargetFieldCSSStyle;
            ramIDAL = myObjAL.RAM_Id;
            ramFieldNameAL = myObjAL.RAM_FieldName;
            ramFieldPositionAL = myObjAL.RAM_FieldPosition;
            if (myObjAL.RAM_VisibleYN == 'Y') {
                ddlVisibleYN.selectedIndex = 0;
            }
            else if (myObjAL.RAM_VisibleYN == 'N') {
                ddlVisibleYN.selectedIndex = 1;
            }
            else {
                ddlVisibleYN.selectedIndex = -1;
            }

            if (myObjAL.RAM_ScreenOpenMode == 'Inline') {
                ddlScreenOpenMode.selectedIndex = 0;
            }
            else if (myObjAL.RAM_ScreenOpenMode == 'PopUp') {
                ddlScreenOpenMode.selectedIndex = 1;
            }
            else {
                ddlScreenOpenMode.selectedIndex = -1;
            }

            if (myObjAL.RAM_DataType == 'Text') {
                ddlDataType.selectedIndex = 0;
            }
            else if (myObjAL.RAM_DataType == 'Number') {
                ddlDataType.selectedIndex = 1;
            }
            else if (myObjAL.RAM_DataType == 'Amount') {
                ddlDataType.selectedIndex = 2;
            }
            else {
                ddlDataType.selectedIndex = -1;
            }

            if (myObjAL.RAM_NumberFormat == '1') {
                ddlNumberFormat.selectedIndex = 0;
            }
            else if (myObjAL.RAM_NumberFormat == '2') {
                ddlNumberFormat.selectedIndex = 1;
            }
            else if (myObjAL.RAM_NumberFormat == '3') {
                ddlNumberFormat.selectedIndex = 2;
            }
            else if (myObjAL.RAM_NumberFormat == '4') {
                ddlNumberFormat.selectedIndex = 3;
            }
            else if (myObjAL.RAM_NumberFormat == '5') {
                ddlNumberFormat.selectedIndex = 4;
            }
            else if (myObjAL.RAM_NumberFormat == '6') {
                ddlNumberFormat.selectedIndex = 5;
            }
            else {
                ddlNumberFormat.selectedIndex = -1;
            }
        }
        else {

        }

      

     



      // "DisplayName": "LikeButton",
      // "LayoutCode": "Default",
      // "RAM_ApplyCssStyleTo": "DisplayName",
      // "RAM_DataType": "",
      // "RAM_DisplayFieldCssStyle": "",
      // "RAM_FieldName": "LikeButton",
      // "RAM_FieldPosition": "LikeBtn0000",
      // "RAM_Id": 84,
      // "RAM_NumberFormat": "0",
      // "RAM_ScreenOpenMode": "Inline",
      // "RAM_TargetField": "",
      // "RAM_TargetFieldCSSStyle": "",
      // "RAM_TemplateID": "20040",
      // "RAM_VisibleYN": "Y"

  }

  catch (err) {
      console.log('Error in function openActionLinksData : ' + err.message);
  }
}
function saveActionLinksData1(fieldId) {
    
  try {
      sDisplayName = "";
      sDisplayName = document.getElementById("txtDisplayName").value;
      sTargetField = "";
      sTargetField = document.getElementById("txtTargetField").value;
      sVisibleYN = "";
      sVisibleYN =  document.getElementById("ddlVisibleYN").value;
      sScreenModeOpen = "";
      sScreenModeOpen = document.getElementById("ddlScreenOpenMode").value;
      sDataType = "";
      sDataType = document.getElementById("ddlDataType").value;
      sNumberFormat = "";
      sNumberFormat = document.getElementById("ddlNumberFormat").value;
      if (sNumberFormat != null)
      {
          sNumberFormat = sNumberFormat.toString();
      }
      sDisplayNameCssStyle = "";
      sDisplayNameCssStyle = document.getElementById("txtDisplayNameCSSStyle").value; 
      sTargetFieldCssStyle = "";
      sTargetFieldCssStyle = document.getElementById("txtTargetFieldCSSStyle").value;



      applyCssStyleonAL(fieldId);

      var myObjAL = null;
      myObjAL = getALData(fieldId.id);
      if (myObjAL != null) {
          myObjAL.DisplayName = sDisplayName;
          myObjAL.RAM_TargetField = sTargetField;
          myObjAL.RAM_DisplayFieldCssStyle = sDisplayNameCssStyle;
          myObjAL.RAM_TargetFieldCSSStyle = sTargetFieldCssStyle ;
          ramIDAL = myObjAL.RAM_Id;
          ramFieldNameAL = myObjAL.RAM_FieldName;
          ramFieldPositionAL = myObjAL.RAM_FieldPosition;
          myObjAL.RAM_VisibleYN = sVisibleYN;
          myObjAL.RAM_ScreenOpenMode = sScreenModeOpen;
          myObjAL.RAM_DataType = sDataType;        
          myObjAL.RAM_NumberFormat = sNumberFormat;

          setALData(myObjAL.RAM_FieldPosition, myObjAL);
      }
      sDisplayName = "";
      sTargetField = "";
      sVisibleYN = "";
      sScreenModeOpen = "";
      sDataType = "";
      sNumberFormat = "";
      sDisplayNameCssStyle = "";
      sTargetFieldCssStyle = "";

      

      //var inputArrAL = "";
      //
      //var inputArrAL = "{" + '"TemplateId":"' + templateId + '","LayoutCode":"' + layOutCode + '","actionsLinkData" : [';
      //inputArrAL +=
      //  '{"DisplayName": "' +
      //  sDisplayName +
      //  '","RAM_DataType": "' +
      //  sDataType +
      //  '","RAM_DisplayFieldCssStyle": "' +
      //  sDisplayNameCssStyle +
      //  '","RAM_NumberFormat": "' +
      //  sNumberFormat +
      //  '","RAM_ScreenOpenMode": "' +
      //  sScreenModeOpen +
      //  '","RAM_TargetField": "' +
      //  sTargetField +
      //  '","RAM_TargetFieldCSSStyle": "' +
      //  sTargetFieldCssStyle +
      //  '","RAM_VisibleYN": "' +
      //  sVisibleYN +
      //  '","LayoutCode": "' +
      //  layOutCode +
      //  '","RAM_TemplateID": "' +
      //  templateId +
      // '","RAM_Id": "' +
      //  ramIDAL +
      //'","RAM_FieldName": "' +
      //  ramFieldNameAL +
      //'","RAM_FieldPosition": "' +
      //  ramFieldPositionAL;

      //inputArrAL += '"}]}'    
      //saveActionLinksData(inputArrAL);

      
      document.getElementById("divActionlinksPanel").innerHTML = "";
      document.getElementById("divActionlinksPanel").style.display = "none";

      //prepare input array here :: format is below 
      //Format of input array for AL
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  //   {
  //     "TemplateId": "20040",
  //   "LayoutCode":"Default",
  //    "actionsLinkData": [
  //          {
  //             "DisplayName": "Factsheet_test_test",
  //             "LayoutCode": "Default",
  //             "RAM_ApplyCssStyleTo": "DisplayName_Test",
  //             "RAM_DataType": "",
  //             "RAM_DisplayFieldCssStyle": "",
  //             "RAM_FieldName": "ActionLink4",
  //             "RAM_FieldPosition": "ActionLnk0000",
  //             "RAM_Id": 174,
  //             "RAM_NumberFormat": "",
  //             "RAM_ScreenOpenMode": "Inline",
  //             "RAM_TargetField": "RMW_OpenFactSheet",
  //             "RAM_TargetFieldCSSStyle": "",
  //             "RAM_TemplateID": "20040",
  //             "RAM_VisibleYN": "N"
  //         }]
   
  // }
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //prepare input array for Action Links

      //call rest api function :: saveActionLinksData here
  }
  catch(err) {
      console.log('Error in function saveActionLinksData : ' +err.message);
  }
}

function applyCssStyleonAL(idAL) {
  try {
       
          var myid = "";
          var sMyFontSize = "";
          var sMyColor ="";

          myid = idAL;

          var splitstring = sDisplayNameCssStyle.split(";");
          if (splitstring == '') {
              $(myid).siblings().css({ 'font-size': '13', 'color': '#0368b6' });
          } else {
              var splitFont = "";
              splitstring.forEach(function (record) {
                  record = record.replace("}", "");
                  record = record.replace("{", "");
                  if (record.toUpperCase().includes("FONT-SIZE")) {
                      splitFont = record.split(":")
                      splitFont.forEach(function (ch) {
                          if (isCharDigit(ch)) {
                              value = value + ch;
                          }
                      });
                      sMyFontSize = value + 'px';
                      value = "";
                  }
                  //color: red !impotant;
                  //color: #1212bh !impotant;
                  if (record.toUpperCase().includes("COLOR")) {
                      splitvar = record.split("!");
                      i = "";
                      if (splitvar.length = 1) {
                          for (i = 0; i < splitvar.length; i++) {
                              if (splitvar[i].toUpperCase().includes("COLOR")) {
                                  value = splitvar[i].replace("color:", "");
                                  sMyColor = value.trim();
                                  value = "";
                              }
                              else {
                                  sMyColor = '#0368b6';
                              }
                          }
                      }
                      else {
                          for (i = 0; i < splitvar.length - 1; i++) {
                              if (splitvar[i].toUpperCase().includes("COLOR")) {
                                  value = splitvar[i].replace("color: #", "");
                                  sMyColor = value.toString();
                                  value = "";
                              }
                              else {
                                  sMyColor = '#0368b6';
                              }
                          }
                      }
                  }
              });
              $(myid).siblings().css({ 'font-size': sMyFontSize, 'color': sMyColor });
          }
         
          //$(myid).siblings().css({ "color": "black" });
          
          
  }
  catch (err) {
      console.log('Error in function applyCssStyle');
  }
}
function cancelActionLinksData() {
  try {
      document.getElementById("divActionlinksPanel").innerHTML = "";
      document.getElementById("divActionlinksPanel").style.display = "none";
  }
  catch (err) {
      console.log('Error in function cancelActionLinksData : ' + err.message);
  }
}
//--- Function For Action Links UI ENDS-----------------

//#region ==================================================================================== CSS Style UI changes Code --- ENDS

//#region Left Nav Bar Redering Function : START
function fillMetadataFieldsList() {
  try{
    
  $("#oneDiv").empty();
  var fieldDivDyanamicId = "";
  $("#oneDiv").append(
    '<fieldset class="fieldSetBorder"><legend class="fieldsetlegend">MetaData Fields</legend><table style="margin-top: 10px;margin-bottom: 3px;min-width: 227px;" id="FieldsTable">'
  );
  for (var i = 0; i < fieldsDisplayList.length; i = i + 2) {
    $("#FieldsTable").append(
      '<tr><td class="FieldsTDStyle gridItem"> <div class="fieldsTableDiv" id="' +
      fieldsDisplayList[i] +
      '" class="ui-widget-content" style="position: relative; height: 19px;"><label >' +
      fieldsDisplayList[i + 1] +
      '</label></div></td></tr>'
    );
    fieldDivDyanamicId = "#" + fieldsDisplayList[i];
    $(fieldDivDyanamicId).draggable();
    fieldDivDyanamicId = "";
  }
  $("#oneDiv").append("</table></fieldset>");
  }
  catch(err){
    console.log('Error in function : ' +err.message);
  }
  
}

function fillMetadataActionsList() {
    try {

        $("#oneDiv").append(
            '<fieldset class="fieldSetBorder" style="margin-top: 20px;"><legend class="fieldsetlegend">Action Links Fields</legend><table style="margin-top: 10px;margin-bottom: 3px;min-width: 227px;" id="FieldsTable1">'
        );
        for (var i = 0; i < actionLinksList.length; i = i + 3) {

            if (actionLinksList[i] == '0')
                actionLinkEleId = 'Label' + i;
            else
                actionLinkEleId = actionLinksList[i];
            $("#FieldsTable1").append(
                '<tr><td class="FieldsTDStyle gridItem"> <div class="fieldsTableDiv class="ui-widget-content" style="position: relative; height: 19px;"><label id=' + actionLinkEleId + '>' + getALDisplayNameFromFieldName( actionLinksList[i + 1]) + '</label></div></td></tr>'
            );
            fieldDivDyanamicId = '#' + actionLinkEleId;
            $(fieldDivDyanamicId).draggable();
            fieldDivDyanamicId = '';
        }
    }
    catch (err) {
        console.log('Error in function : ' + err.message);
    }

}
//#region Left Nav Bar Redering Function : ENDS

//#region Top Nav Bar Redering Function : START
function fillTopNavBarRow1() {
  try{
    $("#topNavBarDivRow1").empty();

  $("#topNavBarDivRow1").append('<table id="TNB1Table">');
  $("#TNB1Table").append('<tr id="TNB1TableTr1">');
  $("#TNB1TableTr1").append('<td id="TNB1TableTr1Td1"><label style="padding-right: 12px;">Template Name</label>');
  $("#TNB1TableTr1Td1").append('<select id="ddltemplateName" name="TemplateName_1" style="max-width:150px" class="select">');
  for (var templateListCnt = 0; templateListCnt < templateListArr.length; templateListCnt = templateListCnt + 2) {
    $("#ddltemplateName").append('<option value="' + templateListArr[templateListCnt] + '">' + templateListArr[templateListCnt + 1] + '</option>');
  }
  $("#TNB1TableTr1").append('</select></td>');
  $("#TNB1TableTr1").append('</tr>');
  $("#TNB1Table").append('<tr id="TNB1TableTr2">');
  $("#TNB1TableTr2").append('<td id="TNB1TableTr2Td1" style="padding-top: 12px;"><label style="padding-right: 29px;">Layout Code</label>');
  $("#TNB1TableTr2Td1").append('<select id="ddllayoutCode" style="min-width: 150px;" name="LayoutCode_1"  class="select">');
  for (var layoutCodeListCnt = 0; layoutCodeListCnt < LayoutCodeArr.length; layoutCodeListCnt++) {
    $("#ddllayoutCode").append('<option value="' + layoutCodeListCnt + '">' + LayoutCodeArr[layoutCodeListCnt] + '</option>');
  }
  $("#TNB1TableTr2").append('</select></td>');
  $("#TNB1TableTr2").append('</tr>');
  $("#TNB1TableTr2").append('</table>');
  }
  catch(err){
    console.log('Error in function : ' +err.message);
  }
}
function fillTopNavBarRow2() {
  try{ 
  $("#topNavBarDivRow2").empty();
  $("#topNavBarDivRow2").append('<fieldset style="width: 1000px !important;"class="fieldSetBorder"><legend class="fieldsetlegend">Layout Style Menu</legend><table id="TNB2Table">');
  $("#TNB2Table").append('<tr id="TNB2TableTr1">');
  $("#TNB2TableTr1").append('<td id="TNB2TableTr1Td1" style="padding-top: 10px;"><label style="padding-right: 50px;">Rows</label>');
  $("#TNB2TableTr1Td1").append('<select id="rows" name="rows" class="select">"');
  for (k = 1; k <= maxRowNo; k++) {
    if ((k == ddlDefaultSelectedRow)) {
      $("#rows").append('<option selected value="' + k + '">' + k + '</option>');
    } else {
      $("#rows").append('<option value="' + k + '">' + k + '</option>');
    }
  }
  $("#TNB2TableTr1").append('</select>');
  $("#TNB2TableTr1Td1").append('<label style="padding-left: 35px;"></label>');
      $("#TNB2TableTr1Td1").append('<button  type="button" onclick="loadMatrixData();drawLayout();getMetadataFieldsList();getActionLinksFromCommonData();fillMetadataFieldsList();fillMetadataActionsList();" style="width: 125px !important;" class="btn btnSaveLayout">Draw Layout Matrix</button>');
  $("#TNB2TableTr1Td1").append('<label style="padding-left: 10px;"></label>');
  $("#TNB2TableTr1Td1").append('<button  type="button" class="btn btnSaveLayout" style="width: 125px !important;" onclick="changeFlag();saveLayoutToDB();">Save Layout</button>');
  $("#TNB2TableTr1Td1").append('<label style="padding-left: 10px;"></label>');
  $("#TNB2TableTr1Td1").append('<button type="button" id="btnLayoutPreview" class="btn btnSaveLayout" style="width: 125px !important;" onclick="loadLayoutPreview();">Layout Preview</button>');
  $("#TNB2TableTr1").append('</td>');

  $("#TNB2TableTr1").append('</tr>');
  $("#TNB2Table").append('<tr id="TNB2TableTr2">');
  $("#TNB2TableTr2").append('<td id="TNB2TableTr2Td1" style="padding-top: 10px;"><label style="padding-right: 29px;">Columns</label>');
  $("#TNB2TableTr2Td1").append('<select id="columns" name="columns" class="select">');
  for (m = 1; m <= maxColNo; m++) {
    if ((m == ddlDefaultSelectedCol)) {
      $("#columns").append('<option selected value="' + m + '">' + m + '</option>');
    } else {
      $("#columns").append('<option value="' + m + '">' + m + '</option>');
    }
  }
  $("#TNB2TableTr2").append('</select></td><td style="border: none !important;">');
  $("#TNB2TableTr2").append('</tr>');
  $("#TNB2TableTr2").append('</table></fieldset>');

  }
  catch(err){
    console.log('Error in function : ' +err.message);
  }
}
//#region Top Nav Bar Redering Function : ENDS

//# -----------------region for Layout Preview Starts--------------
function calculatemaxColSize(arr) {
  var localArr = [];
  var intArr = [];
  var maxColSize = 0;
  for (var i = 0; i < arr.length; i++) {
      if (arr[i].includes("Label01") || arr[i].includes("Label00")) {
          localArr.push(arr[i]);
      }
  }
  for (var j = 0; j < localArr.length; j++) {
      intArr.push(parseInt(localArr[j].substr((localArr[j].length - 2))));
  }
  for (var k = 0; k < intArr.length; k++) {
      //console.log("int Elemets:" + intArr[k]);
      if (intArr[k] > maxColSize)
          maxColSize = intArr[k];
  }

  return maxColSize;// intArr.max();
}
function CheckIfCSSStyleExists(arr, LabelId) {
  for (var i = 0; i < arr.length; i++) {
      if (!arr[i].localeCompare(LabelId))
          return arr[i + 2];
  }
  return "";
}
function CheckIfLabelExists(arr, LabelId) {
  for (var i = 0; i < arr.length; i++) {
      if (!arr[i].localeCompare(LabelId))
          return arr[i + 1];
  }
  return "";
}
function HidePreview() {
  try{ 
    document.getElementById("divPreview").innerHTML = "";
    document.getElementById("divPreview").style.display = "none";
  }
  catch(err){
    console.log('Error in function layoutDivClose : ' +err.message);
  }
}
function loadLayoutPreview(){
  var noOfLayouts = layOutCode.split("~");
  var obj = {};
    obj.templateId = templateId;
    obj.SelectedLayoutCodes = layOutCode;
  try{
    return $.ajax({
      type: "POST",
      url: "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getWorkbenchLayoutPreview",
      contentType: "application/json; charset=utf-8",
      datatype: "json",
      cache: false,
      data: JSON.stringify(obj),
      crossDomain: true,
      success: function (result) {
          //get your result data here 
          //strResult = result.d;
          //GET_WorkbenchLayoutPreviewResult
          strResult = result.GET_WorkbenchLayoutPreviewResult;
          table = document.createElement('table');
          table.setAttribute('border', '1');
          tbdy = document.createElement('tbody');
          tr = tbdy.insertRow();
          tr.id = 'header';
          // Parse the xml
          if (window.DOMParser) { // Standard browsers
              var parser = new DOMParser();
              xml = parser.parseFromString(strResult, "text/xml");
          }
          else { // Internet Explorer
              xml = new ActiveXObject("Microsoft.XMLDOM");
              xml.async = false;
              xml.loadXML(xmlString);
          }
          var tbl = "";

          var tables = xml.getElementsByTagName("NewDataSet");
          //for each table [newdataset]
          for (var t = 0; t < noOfLayouts.length; t++) {
              tbl += "<table><tr><th><label for ='Text' style='margin-left: 15px;margin-right: 5px;'>Layout Code : " + noOfLayouts[t] + "</label></th></tr></table>";
              tbl += "<table>";
              var rows = tables[0].getElementsByTagName("DUMMY0");
              var myArray = new Array();
              var labelIdArray = new Array();
              for (var j = 0; j < rows.length; j++) {
                  for (var k = 0; k < rows[j].children.length; k++) {
                      myArray.push(rows[j].children[k].innerHTML);
                      //labelIdArray.push(rows[j].children[0].innerHTML);
                  }
                  for (var k = 0; k < (rows[j].children.length) / 2 ; k++) {
                      //   myArray.push(rows[j].children[k].innerHTML);
                      labelIdArray.push(rows[j].children[0].innerHTML);
                  }
              }
              //for (var i = 0; i < myArray.length; i++)
              //    console.log("Array Elemets:" + myArray[i]);
              //for (var i = 0; i < labelIdArray.length; i++)
              //    console.log("labelIdArray Elemets:" + labelIdArray[i]);

              //Below line commented by Shubham Podhade on 28-July-2020 
              //var getMaxColSize = calculatemaxColSize(labelIdArray);
              var getMaxColSize = (parseInt(columns)/2);
              //console.log("Max Col Size" + getMaxColSize);

              for (var j = 0; j < 5; j++) {

                  if (j == 0 || j == 1)
                      iteratetdCount = getMaxColSize + 1;
                  else if (j == 2 || j == 3 || j == 4)
                      iteratetdCount = (getMaxColSize + 1) * 2;
                  else
                      iteratetdCount = 13;
                  if (j == 0)
                      tbl += "<tr style='height: 60px;'>";
                  else if (j == 1)
                      tbl += "<tr style='height: 50px;'>";
                  else
                      tbl += "<tr style='height: 35px;'>";


                  for (var k = 0; k < iteratetdCount; k++) {
                      valueToAppend = ""
                      if (k < 10)
                          valueToAppend = "Label0" + j + "0" + k;
                      else
                          valueToAppend = "Label0" + j + "" + k;

                      if (j == 1 || j == 0) {
                          tbl += "<td colspan='2' title='" + valueToAppend + "' style='white-space: nowrap;text-align: center;" + CheckIfCSSStyleExists(myArray, valueToAppend) + "'>"
                          // k += 2;
                      }
                      else {
                          tbl += "<td title='" + valueToAppend + "' style='white-space: nowrap;text-align: center;padding: 5px 15px 5px 15px;" + CheckIfCSSStyleExists(myArray, valueToAppend) + "'>";
                          //k++
                      }


                      if (CheckIfLabelExists(myArray, valueToAppend).localeCompare(""))
                          valueToAppend = CheckIfLabelExists(myArray, valueToAppend);
                      else
                          valueToAppend = "    ";

                      tbl += valueToAppend;
                      tbl += "</td>"
                  }

                  tbl += "</tr>";
              }
              tbl += "</table>"
          }

          tbl = "<table style='border-radius: 15px !important;box-shadow: 0 0 20px #c2cfda;border-color: white;background-color: white;'  cellspacing='0' cellpadding='0'><tr><td><table><tr style='height: 80px;'><th colspan='" + (((getMaxColSize + 1) * 2) + 1) + "' style='text-align: left;'><label for ='Text' style='margin-left: 15px;margin-right: 5px;'>Layout preview for template :</label><label id='previewTemplateLabel' style='margin-right: 50px;'>" + $("#ddltemplateName option:selected").text() + "</label><button type='button' class='btn' style='width:75px;' onclick='HidePreview()'>Close</button></th></tr></table></td></tr><tr><td>" + tbl + "</td></tr></table>";

          $("#divPreview").show();
          //console.log(tbl);
          $("#divPreview").html(tbl);
      },
      error: function (request, status, error) {
          console.log(request.responseText);
          alert(request.responseText);
      }
  });
  }
  catch(err){
    console.log('Error in function loadLayoutPreview :' + err.message);
  }
}
//# -----------------region for Layout Preview Ends--------------

//#region Load Data from AJAX, Rest Api Calls => START
function getMetadataFieldsList() {
  try{
    fieldsDisplayList = [];
  return $.ajax({
    type: "POST",
    url: "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getRMWFields",
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    cache: false,
    data: JSON.stringify({ TemplateId: templateId, LayoutCode : layOutCode }),
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      data = jQuery.parseJSON(data);
      var myData = data.Get_RMWMetadataFieldsResult;
      jQuery(myData).each(function (i, item) {
        fieldsDisplayList.push(item.FieldDisplayId);
        fieldsDisplayList.push(item.FieldDisplayName);
      });
    },
    error: function (x, e) {
      alert("Error in getMetadataFieldsList" + e);
    },
  });

  }
  catch(err){
    console.log('Error in function getMetadataFieldsList : ' +err.message);
  }
  
}
function getRowColumnCountFromCommonData() {
  try{
    return $.ajax({
      type: "GET",
      url:
        "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getRMWFieldRowsColumns",
      contentType: "application/json; charset=utf-8",
      dataType: "text",
      cache: false,
      crossDomain: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      async: false,
      success: function (data) {
        data = jQuery.parseJSON(data);
        var myData = data.Get_RMWRowColumnDataForFieldsResult;
        jQuery(myData).each(function (i, item) {
          rowCount.push(item.Rows);
          colCount.push(item.Columns);
        });
      },
      error: function (x, e) {
        alert("Error in getRowColumnCountFromCommonData" + e);
      },
    });

  }
  catch(err){
    console.log('Error in function getRowColumnCountFromCommonData : ' +err.message);
  }
 
}
function saveLayout(inputArr) {
  try{
    //console.log("=====INPUT ARR on save layout ===" + inputArr);
  return $.ajax({
    type: "POST",
    url:
      "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/SaveFieldsGridData",
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    cache: false,
    data: inputArr,
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      //console.log("Data Received 0 :" + data);
    },
    error: function (x, e) {
      alert("Error in saveLayout" + e);
    },
  });
  }
  catch(err){
    console.log('Error in function saveLayout : ' +err.message);
  }
  
}
function loadMatrixData() {
    try {
        
  fieldData = [];
  ALFieldData = [];
  var e = document.getElementById("rows");
  var selectedRow = e.options[e.selectedIndex].value;
  rows = selectedRow;
  var e = "";
  var e = document.getElementById("columns");
  var selectedColumn = e.options[e.selectedIndex].value;
  columns = selectedColumn;
  var inputArr1 = "";
  inputArr1 = '{ "TemplateId":' + templateId + ',"LayoutCode":"' + layOutCode + '","Rows":"' + rows + '","Columns":"' + columns + '"}';
  //console.log("=====loadMatrixData===");
  return $.ajax({
    type: "POST",
    url:
      "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/SaveAndGetRMWMSequenceGridData",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: false,
    data: inputArr1,
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      
      // console.log(
      //   "Data Received loadMatrixData Cols :" +
      //   data.SaveRMWMSequenceFieldDataResult[0].Columns
      // );
      // console.log(
      //   "Data Received loadMatrixData Rows : " +
      //   data.SaveRMWMSequenceFieldDataResult[0].Rows
      // );
      // console.log(
      //   "Data Received 3 Data :" +
      //     JSON.stringify(
      //       data.SaveRMWMSequenceFieldDataResult[0].fieldData
      //     )
      // );
      for (
        var j = 0;
        j < data.SaveRMWMSequenceFieldDataResult[0].fieldData.length;
        j++
      ) {
        // console.log(
        //   "loadMatrixData fieldData :--- " + data.SaveRMWMSequenceFieldDataResult[0].fieldData[j].FieldDisplayId + data.SaveRMWMSequenceFieldDataResult[0].fieldData[j].DesignLabelID + " --- " +
        //   data.SaveRMWMSequenceFieldDataResult[0].fieldData[j].FieldDisplayName
        // );
        fieldData.push(
          data.SaveRMWMSequenceFieldDataResult[0].fieldData[j]
        );
      }
      for(a=0;a<data.SaveRMWMSequenceFieldDataResult[0].actionLinkData.length;a++){
        ALFieldData.push(data.SaveRMWMSequenceFieldDataResult[0].actionLinkData[a])
      }
    },
    error: function (x, e) {
      alert("Error in loadMatrixData" + e);
    },
  });

  }
  catch(err){
    console.log('Error in function loadMatrixData : ' +err.message);
  }
 
}
function loadDefaultRowAndColCount() {
  try{
   
  var inputArr1 = "";
  //console.log(' loadDefaultRowAndColCount template id ' + templateId);
  //console.log(' loadDefaultRowAndColCount lay code ' + layOutCode);
  inputArr1 = '{ "TemplateId":"' + templateId + '","LayoutCode":"' + layOutCode + '"}';
  //console.log("=====loadMatrixData===");
  return $.ajax({
    type: "POST",
    url:
      "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getRMWMSequenceRowsColumns",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: false,
    data: inputArr1,
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      // console.log(
      //   "Data Received loadDefaultRowAndColCount: Cols" +
      //   data.GET_RMWMSequenceRowColumnResult[0].Columns
      // );
      // console.log(
      //   "Data Received loadDefaultRowAndColCount: Rows " +
      //   data.GET_RMWMSequenceRowColumnResult[0].Rows
      // );
      ddlDefaultSelectedRow = data.GET_RMWMSequenceRowColumnResult[0].Rows;
      rows = ddlDefaultSelectedRow;
      ddlDefaultSelectedCol = data.GET_RMWMSequenceRowColumnResult[0].Columns;
      columns = ddlDefaultSelectedCol;
    },
    //.GET_RMWMSequenceRowColumnResult[0]
    error: function (x, e) {
      alert("Error in loadDefaultRowAndColCount" + e);
    },
  });

  }
  catch(err){
    console.log('Error in function loadDefaultRowAndColCount : ' +err.message);
  }
  
}
function loadTemplates() {
  try{
    return $.ajax({
      type: "GET",
      url:
        "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getTemplates",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      cache: false,
      crossDomain: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      async: false,
      success: function (data) {
       
        for (
          var j = 0;
          j < data.GET_TemplateDataResult.length;
          j++
        ) {
          templateListArr.push(
            data.GET_TemplateDataResult[j].Id
          );
          templateListArr.push(
            data.GET_TemplateDataResult[j].Template_Name
          );
        }
      },
      error: function (x, e) {
        alert("Error in loadTemplates" + e);
      },
    });

  }
  catch(err){
    console.log('Error in function loadTemplates : ' +err.message);
  }
 
}
function loadLayoutCodes() {
  var inputArr2 = "";
  try{
  inputArr2 = '{ "TemplateId":""}';
    return $.ajax({
      type: "POST",
      url:
        "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getLayoutCodesForTemplate",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      cache: false,
      data: inputArr2,
      crossDomain: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      async: false,
      success: function (data) {
        for (
          var j = 0;
          j < data.Get_LayoutCodesForTemplateResult.length;
          j++
        ) {
          LayoutCodeArr.push(
            data.Get_LayoutCodesForTemplateResult[j].RFMD_Layout_Code
          );
        }
      },
      error: function (x, e) {
        alert("Error in loadLayoutCodes" + e);
      },
    });
  }
  catch(err){
    console.log('Error in function  loadLayoutCodes :  ' +err.message);
  }
}
function getActionLinksFromCommonData(){

  try{
    actionLinksList = [];
   
  return $.ajax({
    
    type: "POST",
    url: "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getActionsCommonData",
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    cache: false,
    data: JSON.stringify({ TemplateId: templateId, LayoutCode : layOutCode }),
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      data = jQuery.parseJSON(data);
      var myData = data.GET_ActionsCommonDataResult;
      jQuery(myData).each(function (i, item) {
        actionLinksList.push(item.RAM_Id);
        actionLinksList.push(item.Misc1);
        actionLinksList.push(item.DisplayName);
        //fieldsDisplayList.push(item.FieldDisplayName);
      });
    },
    error: function (x, e) {
      alert("Error in getActionLinksFromCommonData" + e);
    },
  });
  }
  catch(err){
    console.log('Error in function getActionLinksFromCommonData : ' +err.message);
  }
}
function getColumnCountForALIF() {
  try{
    return $.ajax({

      type: "GET",
      url:
        "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/getActionsInfoFieldsCommonnData",
      contentType: "application/json; charset=utf-8",
      dataType: "text",
      cache: false,
      crossDomain: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      async: false,
      success: function (data) {
        data = jQuery.parseJSON(data);
        colCountForAL = data.Get_ActionsInfoFieldsCommonnDataResult[0].ActionsLinkData;
        colCountForIF = data.Get_ActionsInfoFieldsCommonnDataResult[0].InfoFieldData;
        //console.log('colCountForAL ' + colCountForAL)
        //console.log('colCountForIF ' + colCountForIF)
      },
      error: function (x, e) {
        alert("Error in getColumnCountForALIF" + e);
      },
    });

  }
  catch(err){
    console.log('Error in function getColumnCountForALIF : ' +err.message);
  }
 
}
function saveActionLinksData(inputArrForAL) {
  try{
      //
  return $.ajax({
    type: "POST",
    url:
      "http://"+serverAddress+"/FinIQService/RMWMetadataService.svc/saveActionsLinkData",
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    cache: false,
    data: inputArrForAL,
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    async: false,
    success: function (data) {
      //console.log("Data Received 0 :" + data);
    },
    error: function (x, e) {
      alert("Error in saveActionLinksData" + e);
    },
  });
  }
  catch(err){
    console.log('Error in function saveActionLinksData : ' +err.message);
  }
  
}
//#region Load Data from AJAX, Rest Api Calls => END
function printArr(){
  console.log()
  for(var i=0;i<actionLinksList.length;i++){
    console.log('Data---'+actionLinksList[i]);
  }
}
//#region Document.Ready function call => START
$(document).ready(function () {
  //-----Strictly Dont Change the order of below function calls---------
  loadTemplates();
  loadLayoutCodes();
  fillTopNavBarRow1();
  updateLatestTemplateId();
  updateLatestLayoutCode();

  getRowColumnCountFromCommonData();
  decideMaxRowandCol();
  loadDefaultRowAndColCount();
  fillTopNavBarRow2();
  updateLatestRow();
  updateLatestColumn();

  getActionLinksFromCommonData();
  getColumnCountForALIF();
  //-----Strictly Dont Change the order of Above function calls---------
  //printArr();

  //------------On Mouse Hover of Layout Matrix Elements Button Visible Starts--------------
  $(document).on('mouseenter', '.mytd', function () {
    if($(this).find("label")[0].innerText.length!=undefined && $(this).find("label")[0].innerText.length>0)
    {
      $(this).find(":button").css('visibility', 'visible');
    }else{
      //console.log('text not present');
      ;
    }
  }).on('mouseleave', '.mytd', function () {
      $(this).find(":button").css('visibility', 'hidden');
  });

    $(document).on('mouseenter', '.mytd1', function () {

        if ($(this).find("a")[0].innerText.length != undefined && $(this).find("a")[0].innerText.length > 0) {
        //    $(this).find(":button").css('visibility', 'visible');
        //}
        $(this).find(":button").css('visibility', 'visible');
        } else { }
    }).on('mouseleave', '.mytd1', function () {
      $(this).find(":button").css('visibility', 'hidden');
  });
  //------------On Mouse Hover of Layout Matrix Elements Button Visible Ends--------------
});
//#region Document.Ready function call => END