function OpenPreviewGrid() {
    var templateId;
    var SelectedLayoutCode;
    templateId = document.getElementById('ctl00_MainContent_hdnTemplateID').value;
    SelectedLayoutCodes = document.getElementById('ctl00_MainContent_hdnSelectedLayoutCodes').value;
    var noOfLayouts = SelectedLayoutCodes.split("~");
    var selectedTemplateId;
    selectedTemplateId = document.getElementById("ctl00_MainContent_ddlTemplateName");
    var path_Name = window.location.pathname;
    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
    var strResult, xml;
    var valueToAppend;
    var iteratetdCount = 0
    var obj = {};
    obj.templateID = templateId;
    obj.SelectedLayoutCodes = SelectedLayoutCodes;
    try {
        return $.ajax({
            type: "POST",
            url: "" + myPageName + "/getPreviewDt",
            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;
                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("DUMMY" + t);
                    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]);

                    var getMaxColSize = calculatemaxColSize(labelIdArray);
                    //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;'>" + selectedTemplateId.options[selectedTemplateId.selectedIndex].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();
                $("#divPreview").html(tbl);
            },
            error: function (request, status, error) {
                console.log(request.responseText);
                alert(request.responseText);
            }
        });
    }
    catch (err) {
        throw (err);
    }
}

function calculatemaxColSize(arr) {
    var localArr = [];
    var intArr = [];
    var maxColSize = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].includes("Label01")) {
            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 CheckIfLabelExists(arr, LabelId) {
    for (var i = 0; i < arr.length; i++) {
        if (!arr[i].localeCompare(LabelId))
            return arr[i + 1];
    }
    return "";
}

function CheckIfCSSStyleExists(arr, LabelId) {
    for (var i = 0; i < arr.length; i++) {
        if (!arr[i].localeCompare(LabelId))
            return arr[i + 2];
    }
    return "";
}

function ShowClonePanel() {
    try {
        if ($('#ctl00_MainContent_ddlTemplateName').val() === '%%') {
            $('#ctl00_MainContent_lblError').html('Please select template name.');
            return false;
        }

        document.getElementById("divClone").style.display = "";
        $('.overlaySearch1').show();
        $("#ctl00_MainContent_pnlClone").toggleClass("visible");
        $("#ctl00_MainContent_pnlClone").toggleClass("invisible");
        $('#ctl00_MainContent_lblerrorpop').html('');
        $('#ctl00_MainContent_lblTableExistingPop').html('');
        return false;
    }
    catch (err) {
        throw (err);
    }
}

function HideClonePanel() {
    try {
        $("#ctl00_MainContent_pnlClone").toggleClass("visible");
        $("#ctl00_MainContent_pnlClone").toggleClass("invisible");
        return false;
    }
    catch (err) {
        throw (err);
    }
}

function ddlTemplateCloneChanged() {
    try {
        if ($('#ctl00_MainContent_ddlTemplateName').val() === $('#ctl00_MainContent_ddlTemplateClone').val()) {
            $('#ctl00_MainContent_lblerrorpop').html('Target template should be different than source template.');
            $('#ctl00_MainContent_lblerrorpop').css('color', '#FF4E4E');
            $('#ctl00_MainContent_btnConfirmClone').attr('disabled', 'disabled');
        }
        else {
            $('#ctl00_MainContent_lblerrorpop').html('');
            $('#ctl00_MainContent_btnConfirmClone').removeAttr("disabled")
        }

        return false;
    } catch (e) {
        throw (e);
    }
}

function CloneTemplate() {
    try {
        var obj = {};
        obj.sourceTemplateId = $('#ctl00_MainContent_ddlTemplateName').val();;
        obj.targetTemplateId = $('#ctl00_MainContent_ddlTemplateClone').val();;

        $.ajax({
            type: "POST",
            url: "RMWorkstationMetadata.aspx/cloneTemplate",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            data: JSON.stringify(obj),

            success: function (data) {
                $('#ctl00_MainContent_lblerrorpop').css('color', '#008000');
                $('#ctl00_MainContent_lblerrorpop').html('Field(s) successfully cloned from template ' + $('#ctl00_MainContent_ddlTemplateName option:selected').text() + ' to template ' + $('#ctl00_MainContent_ddlTemplateClone option:selected').text());
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#ctl00_MainContent_lblerrorpop').css('color', '#FF4E4E');
                $('#ctl00_MainContent_lblerrorpop').html(errorThrown);
                return false;
            }
        });

        return false;
    }
    catch (e) {
        throw (e);
    }
}

function OpenLayoutPreview() {
    try {
        $('#ctl00_MainContent_lblError').html('');
        if ($('#ctl00_MainContent_ddlTemplateName').val() === "%%") {
            $('#ctl00_MainContent_lblError').html('Please select template name.');
        }
        else {
            $('#ctl00_MainContent_pnlPreview').show(300);
            //$('#ctl00_MainContent_pnlPreview').toggleClass('invisible');
            //$('#ctl00_MainContent_pnlPreview').toggleClass('visible');
            $('#ctl00_MainContent_pnlPreview').toggleClass('VideoUploadPopup');
            OpenPreviewGrid();
            OpenPreviewPopUp();
            $('.VideoUploadPopup .overlaySearch').show();
        }
        return false;
    } catch (e) {
        throw (e);
    }
}

function OpenPreviewPopUp() {
    try {
        document.getElementById("overlayPreview").style.display = "block";
    }
    catch (err) {
        throw (e);
    }
}

function OpenRMWGenericPopup(cntrl) {
    try {
        if ($('#ctl00_MainContent_ddlTemplateName').val() === "%%") {
            $('#ctl00_MainContent_lblError').html('Please select template name.');
        }
        else {
            var Mode = $("#" + cntrl.id).attr('Mode');
            var Title = $("#" + cntrl.id).attr('Title');
            OpenEmbeddedPopUp('../RMWorkstationMetadata/RMWGenericFiltersAndSortingMetaData.aspx?TemplateId=' + $('#ctl00_MainContent_ddlTemplateName').val() + '&LayoutCodeFilter=' + $('#ctl00_MainContent_ddlLayoutCode').val() + '&Mode=' + Mode, Title, 1800, 1000);
        }

        return false;
    } catch (e) {
        throw (e);
    }
}

function OpenEmbeddedPopUp(PageName, templateName, POPUPWidth, POPUPHeight) {
    $('body').find("#ModalBoxInside112").remove();
    $('body').append('<div id="ModalBoxInside112" title="' + templateName + '" style="top:0px; left:0px;width:' + POPUPWidth + 'px !important;height:' + POPUPHeight + 'px !important"><iframe id="ifrm11" frameborder="0" width="' + POPUPWidth + 'px " height="' + POPUPHeight + 'px " Src=' + PageName + '&Master_Popup=POPUP></iframe></div>')
    //var dialog = $("<div id='divIframe'></div>").append(iframe).appendTo("body").dialog({
    //    height: 480,
    //    width: 570,
    //    modal: true,
    //    resizable: true,
    //    draggable: true,
    //    autoOpen: true,
    //    bgiframe: true,

    //    close: function (event, ui) { $('html').find('#collDialog').html(); },
    //    open: function (event, ui) { $('html').find('#collDialog').html(''); }
    //});
    $('body').find("#ModalBoxInside112").dialog({
        modal: true,
        resizable: true,
        draggable: true,
        autoOpen: true,
        width: POPUPWidth,
        height: POPUPHeight,
        open: function (event, ui) {
            //$("body").css({
            //    overflow: 'hidden'
            //});
            $(".ui-widget-overlay").css({
                background: "rgb(50, 50, 50) !important",
                opacity: ".50 !important",
                filter: "Alpha(Opacity=50) !important",
            });

            wleft = Number(Math.abs($(window)[0].innerWidth - ($('.ui-dialog').width())) / 2).toFixed(0);
            if (($(window)[0].innerHeight - 50) >= $('.ui-dialog').height()) {
                wtop = Number(Math.abs($(window)[0].innerHeight - $('.ui-dialog').height()) / 2).toFixed(0);
            } else {
                wtop = Number($(window)[0].innerHeight / 4).toFixed(0);
            }
            wtop = (wtop - 62);
            $('.ui-dialog').css({ "left": wleft + 'px', "top": wtop + 'px', "max-width": "max-content", "max-height": "max-content" });
            //"position": "fixed"
            //$('.ui-dialog.ui-dialog-content').css({ "left": "0px", "top": "20px" });
        },
        //beforeClose: function (event, ui) {
        //    $("body").css({ overflow: 'inherit' })
        //},
        //close: function (event, ui) {
        //    if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
        //    }
        //}

    });

    window.scrollTo(0, 0);
}

function OnTextChanged(cntrl) {
    try {
        key = window.event.keyCode;
        if (key == 9 || key == 13) {
            __doPostBack("ctl00_MainContent_txtRowsPerPage", "TextChanged");
        }
        return true;
    } catch (e) {
        throw (e);
    }
}