﻿<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Entity</title>
    <script src="../../../ClientGlobalContext.js.aspx"></script>
    <script src="Scripts/jquery1.8.3.js" type="text/javascript"></script>
    <script src="Scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">

        // An unordered list element to add Entity list items to 
        var results;
        var entityArray;
        var ViewArray = new Array();
        var fetchXml = new Array();
        // An area to display messages
        var message;
        var select;
        var resultString;

        var allEntityListArray = new Array();
        var allViewListArray = new Array();
        var entityQuery = null;
        var customEntityBirthdayAnniversay = null;
        var noOfAjaxRequest = 0;
        var noOfAjaxResponse = 0;
        var globalmetaId;

        function returnClientURL() {
            return Xrm.Page.context.getClientUrl();            
        }

        window.onload = function () {

            var recordId = window.parent.Xrm.Page.data.entity.getId();

            GlobalEntityMetadataId();

            // Disable to Test email button
            $("#btnValidateFetchXMl").attr("disabled", "disabled");
            if (recordId != null && recordId != "") {
                // Enable for already saved record.
                $("#btnValidateFetchXMl").removeAttr("disabled");
            }
            //Assign the global variables
            message = document.getElementById("message");

            allEntityListArray.length = 0;
            
            ODATA_ENDPOINT = returnClientURL() + "/api/data/v8.0/";

            // Check to Ignore Line Break checkbox if form is opened in edit.
            if (window.parent.Xrm.Page.getAttribute("iotap_removelinebreaks").getValue())
                $('#chkRemoveLineBreaks').attr('checked', true);
            else {
                if (window.parent.Xrm.Page.ui.getFormType() == 1) {     // check to checkbox default in new mode
                    $('#chkRemoveLineBreaks').attr('checked', true);
                    SaveRemoveLineBreaks();
                }
                else
                    $('#chkRemoveLineBreaks').attr('checked', false);
            }
            //Retrieve entities
            RetrieveEntityList(ODATA_ENDPOINT + "/iotap_schedulereportselectedentitieses");

            if (window.parent.Xrm.Page.getAttribute('iotap_1tonrelationship').getValue() != null && window.parent.Xrm.Page.getAttribute('iotap_1tonrelationship').getValue() == true)
                $('#chk1toNRelationship').attr('checked', true);

            if (window.parent.Xrm.Page.getAttribute("iotap_groupby1columnname").getValue() || window.parent.Xrm.Page.getAttribute("iotap_groupby2columnname").getValue() ||
                window.parent.Xrm.Page.getAttribute("iotap_groupby3columnname").getValue()) {
                $('#chkGroupBy').attr('checked', true);
            }
                      

            GroupByRequest();

            if (window.parent.Xrm.Page.getAttribute("iotap_datetimeformat").getValue() != null)
                $("#dateTimeFormat").val(window.parent.Xrm.Page.getAttribute("iotap_datetimeformat").getValue());
                        
            //alert( window.parent.Xrm.Page.getAttribute( "iotap_selectedfilterattributename" ).getValue() )
            if (window.parent.Xrm.Page.getAttribute("iotap_selectedfilterattributename").getValue() != null) {
                // Set expandable if birthday/anniversary is selected
                window.parent.Xrm.Page.ui.tabs.get("BirthdayAnniversaryTab").setDisplayState('expanded');
                
                checkIsBirthdayFrameLoaded();
                
            } else {
                // Set collapsed if birthday/anniversary is not selected
                window.parent.Xrm.Page.ui.tabs.get("BirthdayAnniversaryTab").setDisplayState('collapsed');
            }           
        }


        function checkIsBirthdayFrameLoaded( )
        {
            //var frameDoc = window.parent.document.getElementById( 'WebResource_CustomBirthdayAnniversayFilter' ).contentWindow;
            var frameDoc = parent.Xrm.Page.ui.controls.get( 'WebResource_CustomBirthdayAnniversayFilter' ).getObject().contentWindow; //appsource
            if ( frameDoc == null || frameDoc == "undefined" || frameDoc == "" ) {
                window.setTimeout( checkIsBirthdayFrameLoaded, 2000 ); /* this checks the flag every 2 sec*/               
            }
            else if ( typeof frameDoc.createFrameObject == "undefined" || typeof frameDoc.createFrameObject == null ) {
                window.setTimeout( checkIsBirthdayFrameLoaded, 2000 ); /* this checks the flag every 2 sec*/
            }
            else if ( frameDoc.loadComplete == false ) {
                window.setTimeout( checkIsBirthdayFrameLoaded, 2000 ); /* this checks the flag every 2 sec*/
            }
            else {
                frameDoc.createFrameObject();
                frameDoc.RetrieveOnlyDateTimeFields();
            }
        }

        var counter = 0;
        function ShowLoadingImage() {
            if ($('#selectView :selected').text() != '') {
                if ($('#loadingDiv', window.parent.document).length <= 0) {
                    $('body', window.parent.document).append('<div id="loadingDiv"></div>');
                    $('#loadingDiv', window.parent.document).append('<p id="loadingText">Please wait...</p>');
                }
                $('#loadingDiv', window.parent.document).css('height', '10px')
                    .css('width', '100px')
                    .css('font-weight', 'bold')
                    .css('font-size', '16')
                    .center()
                    .show()
            }
        };

        function HideLoadingImage() {
            $('#loadingDiv', window.parent.document).hide();
        };

        jQuery.fn.center = function () {
            this.css("position", "absolute");
            this.css("top", (($(window.parent.document).height() - this.outerHeight()) / 2) + $(window.parent.document).scrollTop() + "px");
            this.css("left", (($(window.parent.document).width() - this.outerWidth()) / 2) + $(window.parent.document).scrollLeft() + "px");
            return this;
        };


        var GlobalEntityMetadataId = function()
        {
            var httpReq = new XMLHttpRequest();
            httpReq.open( "GET", returnClientURL() + "/api/data/v8.0/EntityDefinitions?$select=LogicalName,MetadataId", false);
            httpReq.setRequestHeader( "Accept", "application/json" );
            httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
            httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
            httpReq.setRequestHeader( "OData-Version", "4.0" );
            httpReq.send( null );

            if ( httpReq.status === 200 ) {
                coll = JSON.parse( httpReq.responseText ).value;

                globalmetaId = new Array( coll.length );

                for ( var i = 0; i < coll.length; i++ ) {
                    globalmetaId[i] = new Array( 2 );
                    globalmetaId[i][0] = coll[i].LogicalName;
                    globalmetaId[i][1] = coll[i].MetadataId;
                }
            }            
        }

        var GetEntityMetadataId = function(entityName)
        {  
            for ( var i = 0; i < globalmetaId.length; i++ ) {
                if ( entityName.toLowerCase() == globalmetaId[i][0].toLowerCase() ) {
                    return globalmetaId[i][1];
                }
            }            
        }

        var RetrieveEntityList = function (odataSetName) {

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                headers: { "Accept": "application/json; odata=verbose" },
                url: odataSetName,
             
                success: function (data, textStatus, XmlHttpRequest) {
                   
                    if (data && data.d && data.d.results) {

                       returnEntityListArray(data.d.results);

                        // if selected entity list & all retrieved entities list length are not equal then add retrieved item into selectEntity
                        if (allEntityListArray.length != (selectEntity.length - 1))
                            LoadSelectedEntityList(allEntityListArray, null, null);
                    }
                    else if (data && data.d) {
                        returnEntityListArray(data.d);
                        
                        // if selected entity list & all retrieved entities list length are not equal then add retrieved item into selectEntity
                        if (allEntityListArray.length != (selectEntity.length - 1))
                            LoadSelectedEntityList(allEntityListArray, null, null);
                    }
                    else {
                        LoadSelectedEntityList(data.value, null, null);
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    errorHandler(XmlHttpRequest);
                },
                async: false
            });
        };

        function returnEntityListArray(entityList) {
            // Add all entity into array            
            $(entityList).each(function () {
                allEntityListArray.push($(this)[0]);
            });
        }

        function errorHandler(XmlHttpRequest) {
            ///<summary>
            /// Helper function to handle any errors when using the REST endpoint.
            ///</summary
            var errorMessage = "";
            try {
                errorMessage = JSON.parse(XmlHttpRequest.responseText).error.message.value;
            }
            catch (e) {
                errorMessage = "Unable to parse Error message."
            }
            showMessage("Error : " +
        XmlHttpRequest.status + ": " +
        XmlHttpRequest.statusText + ": " +
        errorMessage);
        }

        var LoadSelectedEntityList = function (data, successCallback, errorCallback) {
            var entityArray = new Array(data.length);
            var counter = 0;
            for (var i = 0; i < data.length; i++) {
                entityArray[i] = new Array(2);
                entityArray[i][0] = data[i].iotap_entitylogicalname;
                entityArray[i][1] = data[i].iotap_entityname;
                counter++;
            }
            entityArray.sort(sortMultiDimensional);
            for (var i = 0; i < counter; i++) {
                $('#selectEntity').append('<option value="' + entityArray[i][0].toLowerCase() + '">' + entityArray[i][1].toString() + '</option>')
            }

            if (window.parent.Xrm.Page.getAttribute('iotap_entityid').getValue() != null) {
                document.getElementById("selectEntity").value = window.parent.Xrm.Page.getAttribute('iotap_entityid').getValue().toLowerCase();
            }

            if (window.parent.Xrm.Page.getAttribute('iotap_viewid').getValue() != null && window.parent.Xrm.Page.getAttribute('iotap_viewid').getValue() != "") {
                retiriveEntity();
            }
        };
        function sectionVisibility(visibility) {
            var tab = window.parent.Xrm.Page.ui.tabs.get("BirthdayAnniversaryTab");
            if (tab != null) {
                tab.setVisible(visibility);
            }
        }



        function refreshCustomEntityFilter()
        {           
            //var birthdayAnniversaryFilter = returnFrameObject( window.parent.frames['WebResource_CustomBirthdayAnniversayFilter'] );
            var birthdayAnniversaryFilter = returnFrameObject( parent.Xrm.Page.ui.controls.get( 'WebResource_CustomBirthdayAnniversayFilter' ).getObject() );//appsource
            
            // Refresh filter            
            var chkBirthdayAnnReminder = $('#chkBirthdayAnnReminder', birthdayAnniversaryFilter);
            chkBirthdayAnnReminder[0].checked = false;
            window.parent.Xrm.Page.getAttribute('iotap_selectedfilterattributename').setValue(null);
            window.parent.Xrm.Page.getAttribute('iotap_nextxdays').setValue(null);
            //window.parent.document.getElementById('WebResource_CustomBirthdayAnniversayFilter').contentWindow.clearDropdown();
            parent.Xrm.Page.ui.controls.get( 'WebResource_CustomBirthdayAnniversayFilter' ).getObject().contentWindow.clearDropdown(); //appsource
            var txtNextXDays = $('#txtNextXDays', birthdayAnniversaryFilter);
            txtNextXDays.val('');

            var chkIntermediateDays = $('#chkIntermediateDays', birthdayAnniversaryFilter);
            chkIntermediateDays[0].checked = false;
            window.parent.Xrm.Page.getAttribute('iotap_intermediatedays').setValue(null);

            // Refresh to 1:N relationship
            refreshOneToNRelationship();         
        }

        function retiriveEntity() {

            $("#chkGroupBy").attr('checked', false);
            GroupByRequest();

            var filter = selectEntity.value;
            var fieldName = "iotap_entityid";

            sectionVisibility(true);
                       
            var serverUrl = returnClientURL();
            var ODATA_ENDPOINT = "/api/data/v8.0/";

            window.parent.Xrm.Page.getAttribute(fieldName).setValue(filter);
            for (var count = selectView.options.length; count > 1; count--) {
                selectView.options.remove(count - 1);
            }
            if ( filter != "" ) {            
                fetchXml = new Array();

                allViewListArray.length = 0;
                //var entityName = "/SavedQuerySet"; -- Namrata
                var entityName = "savedqueries";
                // entityQuery = serverUrl + ODATA_ENDPOINT + entityName + "?$filter= ReturnedTypeCode eq '" + filter + "' and QueryType eq 0 "; -- Namrata
                entityQuery = serverUrl + ODATA_ENDPOINT + entityName + "?$filter= returnedtypecode eq '" + filter + "' and querytype eq 0 ";
                               
                retrieveMultiple( entityQuery, null, null, null );
                // clear view array
                allViewListArray.length = 0;

                //entityName = "/UserQuerySet"; --Namrata
                entityName = "userqueries";

                //entityQuery = serverUrl + ODATA_ENDPOINT + entityName + "?$filter= ReturnedTypeCode eq '" + filter + "' and OwnerId/Id eq guid'" + window.parent.Xrm.Page.getAttribute('ownerid').getValue()[0].id + "'"; -- Namrata
                entityQuery = serverUrl + ODATA_ENDPOINT + entityName + "?$filter=returnedtypecode eq '" + filter + "' and _ownerid_value eq " + window.parent.Xrm.Page.getAttribute( 'ownerid' ).getValue()[0].id.substring( 1, 37 );
                retrieveMultiple(entityQuery, null, null, null);
                
                var metadataId = GetEntityMetadataId( filter );
                //*******Retrieve selected entity properties success******
                var httpReq = new XMLHttpRequest();
                httpReq.open( "GET", serverUrl + ODATA_ENDPOINT + "EntityDefinitions(" + metadataId + ")?$select=ObjectTypeCode", false );
                httpReq.setRequestHeader( "Accept", "application/json" );
                httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
                httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
                httpReq.setRequestHeader( "OData-Version", "4.0" );
                httpReq.send( null );
                
                if ( httpReq.status === 200 ) {                        
                    var entityData = JSON.parse( httpReq.responseText );
                                           
                    if ( entityData.ObjectTypeCode != null ) {
                        window.parent.Xrm.Page.getAttribute( "iotap_entitytypecode" ).setValue( entityData.ObjectTypeCode.toString() );
                    }
                }
            }
                        
            // Show note special report checkbox if Note entity is selected from entity dropdown
            var entityName = (typeof $("#selectEntity option:selected")[0].innerText == 'undefined' ? $("#selectEntity option:selected")[0].text : $("#selectEntity option:selected")[0].innerText).toLowerCase();
            if (entityName == "note")
                $("#trNotes").show();
            else
                $( "#trNotes" ).hide();
           
        }
        //*******Retrieve selected entity properties success******
        function successRetrieveEntity(entityMetadataCollection) {
            LoadSelectedEntityProperty(entityMetadataCollection, null, null);
        }
        //******* Load Attributes(only string data types)******
        var LoadSelectedEntityProperty = function (data, successCallback, errorCallback) {
            var entityTypeCode = "iotap_entitytypecode";
            var counter = 0;
            if (data.ObjectTypeCode != null) {
                window.parent.Xrm.Page.getAttribute(entityTypeCode).setValue(data.ObjectTypeCode.toString());

            }
        };
        //*************Retrieve attributes error***********
        function errorRetrieveEntity(error) {
            message.innerText = error.message;
        }
        function sortMultiDimensional(a, b) {
            // for instance, this will sort the array using the second element    
            return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
        }

        function retrieveMultiple(odataSetName, filter, successCallback, errorCallback) {
            //odataSetName is required, i.e. "SavedView"    
            if (!odataSetName) {
                alert("odataSetName is required.");
                return;
            }
            //Asynchronous AJAX function to Retrieve CRM records using OData
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: odataSetName,
                beforeSend: function (XMLHttpRequest) {
                    //Specifying this header ensures that the results will be returned as JSON.                 
                    XMLHttpRequest.setRequestHeader( "Accept", "application/json" );
                    XMLHttpRequest.setRequestHeader( "OData-MaxVersion", "4.0" );
                    XMLHttpRequest.setRequestHeader( "OData-Version", "4.0" );
                },
                success: function (data, textStatus, XmlHttpRequest) {
                   
                    // Add all view into array
                    $(data.value).each(function () {
                        allViewListArray.push($(this)[0]);
                    });
                                       
                   
                    // If view dropdown item count not equals to ViewList array then add whole array items into it
                    if (allViewListArray.length != ($("#selectView option").length - 1)) {
                        var viewId = window.parent.Xrm.Page.getAttribute("iotap_viewid").getValue();
                        var entityArray = new Array(allViewListArray.length);
                        var tempFetchXml = new Array(allViewListArray.length)

                        var counter = 0;
                        for ( var i = 0; i < allViewListArray.length; i++ ) {
                           
                            var views = allViewListArray[i];
                            entityArray[i] = new Array(2);
                            tempFetchXml[i] = new Array(3);
                            // if (odataSetName.indexOf("SavedQuerySet") > -1) {--* Namrata
                            if (odataSetName.indexOf("savedqueries") > -1) {
                                tempFetchXml[i][0] = views.savedqueryid;
                                tempFetchXml[i][1] = views.fetchxml;
                                tempFetchXml[i][2] = views.layoutxml;
                                entityArray[i][0] = views.savedqueryid;
                                entityArray[i][2] = "1039";
                            }
                            else {
                                tempFetchXml[i][0] = views.userqueryid;
                                tempFetchXml[i][1] = views.fetchxml;
                                tempFetchXml[i][2] = views.layoutxml;
                                entityArray[i][2] = "4230";
                                entityArray[i][0] = views.userqueryid;   //Namrata*
                            }

                            entityArray[i][1] = views.name;
                            counter++;

                        }
                        entityArray.sort( sortMultiDimensional );
                        
                        for ( var i = 0; i < counter; i++ ) {
                            $('#selectView').append('<option value="' + entityArray[i][0].toLowerCase() + '">' + entityArray[i][1].toString() + '</option>')
                            ViewArray.push(entityArray[i][2]);
                            fetchXml.push(tempFetchXml[i]);
                        }

                        if (viewId != null) {
                            document.getElementById("selectView").value = viewId;
                        }
                    }                   
                },
                error: function ( XmlHttpRequest, textStatus, errorThrown )
                {                   
                    errorHandler(XmlHttpRequest);
                },
                async: false
            });
        }


        function showMessage(error) {
            ///<summary>
            /// Displays the error returned from  SDK.MetaData.RetrieveAllEntitiesAsync if it fails.
            ///</summary>
            alert(error.message)
            message.innerText = error.message;
        }



        function retiriveSavedView() {
            refreshCustomEntityFilter();

            $('#lblFetchXmlValidationMsg').text("");
            $("#chkGroupBy").attr('checked', false);
            GroupByDropdownEmpty();

            var filter = selectView.value;
            var fieldName = "iotap_viewid";
            var viewType = "iotap_viewtype";
            var selectedViewIndex = selectView.selectedIndex;
            if (selectedViewIndex > 0) {
                var viewTypeCode = ViewArray[selectedViewIndex - 1].toString();
                window.parent.Xrm.Page.getAttribute(viewType).setValue(viewTypeCode);
                window.parent.Xrm.Page.getAttribute(fieldName).setValue(filter);
                window.parent.Xrm.Page.getAttribute("iotap_viewname").setValue(document.getElementById("selectView").options[document.getElementById("selectView").selectedIndex].text.toString());

                GroupByRequest();
            } else {

                window.parent.Xrm.Page.getAttribute(viewType).setValue("");
                window.parent.Xrm.Page.getAttribute(fieldName).setValue("");
                window.parent.Xrm.Page.getAttribute("iotap_viewname").setValue("");
            }           
        }


        function GroupByDropdownEmpty() {
            $('#groupByColumn1').empty();
            $('#groupByColumn2').empty();
            $('#groupByColumn3').empty();

            // Groupby summary start
            $('#groupBySummary1').empty();
            $('#groupBySummary2').empty();
            // Groupby summary end

            $("#sortOrder1").val("asc");
            $("#sortOrder2").val("asc");

            $("#chkShowGridlines").attr('checked', false);
            // Clear to hide column checkbox
            $("#chkDisplayCount").attr('checked', false);

            $("#chkHideColumn1").attr('checked', false);
            $("#chkHideColumn2").attr('checked', false);
            $("#chkHideColumn3").attr('checked', false);
        }

        function SaveGroupByValues() {
            var groupBy1 = null;
            var groupBy2 = null;
            var groupBy3 = null;

            // Groupby summary start
            var groupBy1Summary = null;
            var groupBy2Summary = null;
            // Groupby summary end

            var groupBySort1 = null;
            var groupBySort2 = null;
            var groupBySort3 = null;

            var hideGroupByColumn1 = 0;
            var hideGroupByColumn2 = 0;
            var hideGroupByColumn3 = 0;

            var showGridlines = 0;
            var displayGroupByColumnCount = 0;

            var dateTimeFormat = $('#dateTimeFormat :selected').val();

            //alert($("#chkGroupBy").attr('checked'))

            if ($("#chkGroupBy").attr('checked')) {
                groupBy1 = $('#groupByColumn1 :selected').text();
                groupBy2 = $('#groupByColumn2 :selected').text();
                groupBy3 = $('#groupByColumn3 :selected').text();

                // Groupby summary start
                groupBy1Summary = $('#groupBySummary1 :selected').text();
                groupBy2Summary = $('#groupBySummary2 :selected').text();
                // Groupby summary end

                groupBySort1 = $('#sortOrder1 :selected').val();
                groupBySort2 = $('#sortOrder2 :selected').val();
                groupBySort3 = $('#sortOrder3 :selected').val();

                hideGroupByColumn1 = $('#chkHideColumn1').attr('checked') ? 1 : 0;
                hideGroupByColumn2 = $('#chkHideColumn2').attr('checked') ? 1 : 0;
                hideGroupByColumn3 = $('#chkHideColumn3').attr('checked') ? 1 : 0;

                showGridlines = $('#chkShowGridlines').attr('checked') ? 1 : 0;
                displayGroupByColumnCount = $('#chkDisplayCount').attr('checked') ? 1 : 0;

                if (groupBy1 == "") {
                    groupBy1 = null;
                    groupBy2 = null;
                    groupBy3 = null;

                    // Groupby summary start
                    groupBy1Summary = null;
                    groupBy2Summary = null;
                    $('#groupBySummary1').val("");
                    $('#groupBySummary2').val("");
                    // Groupby summary end

                    groupBySort1 = null;
                    groupBySort2 = null;
                    groupBySort3 = null;
                    $('#groupByColumn2').val("");


                }
                if (groupBy2 == "" || groupBy2 == null) {
                    groupBy2 = null;
                    groupBy3 = null;

                    groupBySort2 = null;
                    groupBySort3 = null;
                    $('#groupByColumn3').val("");
                }

                // Groupby summary start
                if (groupBy1Summary == "") {
                    groupBy2Summary = null;
                    $('#groupBySummary2').val("");
                }
                // Groupby summary end
            }
                        
            window.parent.Xrm.Page.getAttribute("iotap_groupby1columnname").setValue(groupBy1);
            window.parent.Xrm.Page.getAttribute("iotap_groupby2columnname").setValue(groupBy2);
            window.parent.Xrm.Page.getAttribute("iotap_groupby3columnname").setValue(groupBy3);

            // Groupby summary start            
            window.parent.Xrm.Page.getAttribute("iotap_groupby1summarycolumnname").setValue(groupBy1Summary);
            window.parent.Xrm.Page.getAttribute("iotap_groupby2summarycolumnname").setValue(groupBy2Summary);
            // Groupby summary end

            window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder1").setValue(groupBySort1);
            window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder2").setValue(groupBySort2);
            window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder3").setValue(groupBySort3);

            window.parent.Xrm.Page.getAttribute("iotap_hidegroupby1column").setValue(hideGroupByColumn1);
            window.parent.Xrm.Page.getAttribute("iotap_hidegroupby2column").setValue(hideGroupByColumn2);
            window.parent.Xrm.Page.getAttribute("iotap_hidegroupby3column").setValue(hideGroupByColumn3);

            window.parent.Xrm.Page.getAttribute("iotap_showgridlines").setValue(showGridlines);
            window.parent.Xrm.Page.getAttribute("iotap_displaygroupbycount").setValue(displayGroupByColumnCount);

            window.parent.Xrm.Page.getAttribute("iotap_datetimeformat").setValue(dateTimeFormat);
        }

        function successRetrieveLinkEntityName(entityCollection) {
            noOfAjaxResponse++;
            var linkAttributeNameList;
            var linkAttributesNameListCounter = 0;

            // Store column & entity name in linkAttributeNameList
            $fetchLayout.find("row").each(function () {
                $fetchLayout.find("cell").each(function (index, value) {
                    // get column name from layout xml 
                    columnName = $(this).attr('name');

                    // process for link-entity attribute only & skip remaining non link-entity attributes
                    if (columnName.indexOf(".") > 0) {
                        if (jQuery.type(linkAttributeNameList) == 'undefined') {
                            linkAttributeNameList = new Array(1);
                        }

                        linkAttributeNameList[linkAttributesNameListCounter] = new Array(2);
                        // column name
                        linkAttributeNameList[linkAttributesNameListCounter][0] = columnName.substring(columnName.indexOf(".") + 1, columnName.length);
                        // Entity name
                        linkAttributeNameList[linkAttributesNameListCounter][1] = columnName.substring(0, columnName.indexOf("."));
                        linkAttributesNameListCounter++;
                    }
                })
            });

            // fill to groupby1 column dropdown           
            for (var i = 0; i < entityCollection.Attributes.length; i++) {
                for (var k = 0; k < linkAttributeNameList.length; k++) {
                    if ( linkAttributeNameList[k][0].toLowerCase() == entityCollection.Attributes[i].LogicalName.toLowerCase() && entityCollection.Attributes[i].DisplayName.UserLocalizedLabel != null ) {
                        var val = linkAttributeNameList[k][0].toLowerCase();
                        var entityName = entityCollection.DisplayName.UserLocalizedLabel.Label;
                        var display = entityCollection.Attributes[i].DisplayName.UserLocalizedLabel.Label + " (" + entityName + ")";

                       // alert(entityName +  "   " +  val + "   " + display) 

                        if ($("#groupByColumn1 option:contains(" + display + ")").text() == "") {
                            $('#groupByColumn1').append('<option value="' + val + '">' + display + '</option>');
                            $('#groupByColumn2').append('<option value="' + val + '">' + display + '</option>');
                            $('#groupByColumn3').append('<option value="' + val + '">' + display + '</option>');
                            break;
                        }
                    }
                }
            }

            LoadSavedGroupBy();
            if (noOfAjaxResponse == noOfAjaxRequest)
                HideLoadingImage();
        }


        function successRetrieveEntityAttribute(entityCollection) {

            var attributeNameList;
            $fetchLayout.find("row").each(function () {
                $fetchLayout.find("cell").each(function (index, value) {
                    if (index <= 0) {
                        attributeNameList = new Array($fetchLayout.find("cell").length);
                    }
                    attributeNameList[index] = new Array(2);
                    // column name
                    columnName = $(this).attr('name');
                    attributeNameList[index][0] = columnName.indexOf(".") > 0 ? "" : columnName;
                    //Entity name
                    attributeNameList[index][1] = columnName.indexOf(".") > 0 ? "" : columnName.substring(0, columnName.indexOf("."));
                })
            });
           
            for (var k = 0; k < attributeNameList.length; k++) {
                for (var i = 0; i < entityCollection.Attributes.length; i++) {
                    var attribute = entityCollection.Attributes[i];
                    if ( attributeNameList[k][0].toLowerCase() == attribute.LogicalName.toLowerCase() && attribute.DisplayName.UserLocalizedLabel != null ) {
                        $( '#groupByColumn1' ).append( '<option value="' + attribute.LogicalName.toLowerCase() + '">' + attribute.DisplayName.UserLocalizedLabel.Label + '</option>' )
                        $( '#groupByColumn2' ).append( '<option value="' + attribute.LogicalName.toLowerCase() + '">' + attribute.DisplayName.UserLocalizedLabel.Label + '</option>' )
                        $( '#groupByColumn3' ).append( '<option value="' + attribute.LogicalName.toLowerCase() + '">' + attribute.DisplayName.UserLocalizedLabel.Label + '</option>' )

                        // group by summary start
                        var attributeType = attribute.AttributeType;
                        if (attributeType == "Money" || attributeType == "Integer" || attributeType == "Decimal" || attributeType == "Double") {
                            $( '#groupBySummary1' ).append( '<option value="' + attribute.LogicalName.toLowerCase() + '">' + attribute.DisplayName.UserLocalizedLabel.Label + '</option>' );
                            $( '#groupBySummary2' ).append( '<option value="' + attribute.LogicalName.toLowerCase() + '">' + attribute.DisplayName.UserLocalizedLabel.Label + '</option>' );
                        }
                        // group by summary end
                        break;
                    }
                }
            }
            LoadSavedGroupBy();

            if (noOfAjaxRequest == 0)
                HideLoadingImage();
           
        }

        function LoadSavedGroupBy() {
            if (window.parent.Xrm.Page.getAttribute("iotap_groupby1columnname").getValue() != null)
                // avoid column names start with the some initial characters 
                $("#groupByColumn1 option").filter(function () { return $(this).text() == window.parent.Xrm.Page.getAttribute("iotap_groupby1columnname").getValue() }).attr("selected", "selected");

            if (window.parent.Xrm.Page.getAttribute("iotap_groupby2columnname").getValue() != null)
                $("#groupByColumn2 option").filter(function () { return $(this).text() == window.parent.Xrm.Page.getAttribute("iotap_groupby2columnname").getValue() }).attr("selected", "selected");

            if (window.parent.Xrm.Page.getAttribute("iotap_groupby3columnname").getValue() != null)
                $("#groupByColumn3 option").filter(function () { return $(this).text() == window.parent.Xrm.Page.getAttribute("iotap_groupby3columnname").getValue() }).attr("selected", "selected");


            // Groupby summary start            
            if (window.parent.Xrm.Page.getAttribute("iotap_groupby1summarycolumnname").getValue() != null)
                $("#groupBySummary1 option").filter(function () { return $(this).text() == window.parent.Xrm.Page.getAttribute("iotap_groupby1summarycolumnname").getValue() }).attr("selected", "selected");
            if (window.parent.Xrm.Page.getAttribute("iotap_groupby2summarycolumnname").getValue() != null)
                $("#groupBySummary2 option").filter(function () { return $(this).text() == window.parent.Xrm.Page.getAttribute("iotap_groupby2summarycolumnname").getValue() }).attr("selected", "selected");

            // Groupby summary end

            if (window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder1").getValue() != null)
                $("#sortOrder1").val(window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder1").getValue());
            if (window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder2").getValue() != null)
                $("#sortOrder2").val(window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder2").getValue());
            if (window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder3").getValue() != null)
                $("#sortOrder3").val(window.parent.Xrm.Page.getAttribute("iotap_groupbysortorder3").getValue());

            if (window.parent.Xrm.Page.getAttribute("iotap_hidegroupby1column").getValue() != null)
                $('#chkHideColumn1').attr('checked', window.parent.Xrm.Page.getAttribute("iotap_hidegroupby1column").getValue());
            if (window.parent.Xrm.Page.getAttribute("iotap_hidegroupby2column").getValue() != null)
                $('#chkHideColumn2').attr('checked', window.parent.Xrm.Page.getAttribute("iotap_hidegroupby2column").getValue());
            if (window.parent.Xrm.Page.getAttribute("iotap_hidegroupby3column").getValue() != null)
                $('#chkHideColumn3').attr('checked', window.parent.Xrm.Page.getAttribute("iotap_hidegroupby3column").getValue());

            if (window.parent.Xrm.Page.getAttribute("iotap_showgridlines").getValue() != null)
                $('#chkShowGridlines').attr('checked', window.parent.Xrm.Page.getAttribute("iotap_showgridlines").getValue());

            if (window.parent.Xrm.Page.getAttribute("iotap_displaygroupbycount").getValue() != null)
                $('#chkDisplayCount').attr('checked', window.parent.Xrm.Page.getAttribute("iotap_displaygroupbycount").getValue());
        }
        function ErrorFunction(error) {
            $('#lblGroupByRequiredWaitMsg').removeClass("msg").addClass("errormsg");
            $('#lblGroupByRequiredWaitMsg').text(error.message);
            alert(error.message);
        }

        var $fetchLayout;
        function GetViewColumName() {           
            var viewId = document.getElementById("selectView").options[document.getElementById("selectView").selectedIndex].value.toString();
            var xmlData = new Array(1);
            jQuery.each(fetchXml, function () {
                var fetchXmlEachRow = $(this);
                if (fetchXmlEachRow[0] == viewId) {
                    xmlData[0] = fetchXmlEachRow;
                }
            });


            var viewFetchXml = xmlData[0][1] //FetchXml;
            var layoutXml = xmlData[0][2] //LayoutXml;
            xmlDocFetchXml = $.parseXML( viewFetchXml );

            // Convert xml reponse object into DOM
            $viewFetchXml = $(xmlDocFetchXml);

            var entityLogicalName = '';
            $viewFetchXml.find("entity").each(function () {
                entityLogicalName = $(this).attr('name');
            });

            $viewFetchXml.find("link-entity").each(function () {
                var linkEntityLogicalName = $(this).attr('name');
                var entityAliasName = $(this).attr('alias');
                // Replace alias name by entity display name.
                layoutXml = layoutXml.replace(new RegExp(entityAliasName, "g"), linkEntityLogicalName);
            });

            xmlDocFetchLayout = $.parseXML(layoutXml);
            $fetchLayout = $(xmlDocFetchLayout);

            // Layout
            var counter = 0;
            noOfAjaxRequest = 0;
            noOfAjaxResponse = 0;
            $fetchLayout.find("row").each(function () {
                $fetchLayout.find("cell").each(function () {
                    var attrLogicalName = $(this).attr('name');
                    // If link entity is there then retrieve link entity information
                    if (attrLogicalName.indexOf(".") > 0) {
                        var link_EntityName = attrLogicalName.substring(0, attrLogicalName.indexOf("."));
                        //daloor
                        var metadataId = GetEntityMetadataId( link_EntityName.toLowerCase() );
                        var query = "EntityDefinitions(" + metadataId + ")?$select=LogicalName,DisplayName&$expand=Attributes($select=LogicalName,DisplayName,AttributeType)";

                        var httpReq = new XMLHttpRequest();                       
                        httpReq.open( "GET", returnClientURL() + "/api/data/v8.0/" + query, false );
                        httpReq.setRequestHeader( "Accept", "application/json" );
                        httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
                        httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
                        httpReq.setRequestHeader( "OData-Version", "4.0" );
                        httpReq.send( null );

                        if ( httpReq.status === 200 ) {                            
                            var entityColl = JSON.parse( httpReq.responseText );
                            successRetrieveLinkEntityName( entityColl );
                        }
                        noOfAjaxRequest++;
                    }
                    else {
                        // Retrieve entity attributes at 1 time only. 
                        if (counter <= 0) {
                            counter++;
                            //daloor

                            var metadataId = GetEntityMetadataId( entityLogicalName.toLowerCase() );
                            var query = "EntityDefinitions(" + metadataId + ")?$select=LogicalName,DisplayName&$expand=Attributes($select=LogicalName,DisplayName,AttributeType)";

                            var httpReq = new XMLHttpRequest();
                            httpReq.open( "GET", returnClientURL() + "/api/data/v8.0/" + query, false );
                            httpReq.setRequestHeader( "Accept", "application/json" );
                            httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
                            httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
                            httpReq.setRequestHeader( "OData-Version", "4.0" );
                            httpReq.send( null );

                            if ( httpReq.status === 200 ) {
                                var entityColl = JSON.parse( httpReq.responseText );
                                successRetrieveEntityAttribute( entityColl );
                            }                            
                        }
                    }
                });
            } );           
        }

        function GroupByRequest() {
            GroupByDropdownEmpty();
            if ($("#chkGroupBy").is(':checked')) {
                $('#lblGroupByRequiredWaitMsg').removeClass("errormsg").addClass("msg");

                $('#groupByColumn1').append('<option value=""></option>')
                $('#groupByColumn2').append('<option value=""></option>')
                $('#groupByColumn3').append('<option value=""></option>')

                // Groupby summary start
                $('#groupBySummary1').append('<option value=""></option>')
                $('#groupBySummary2').append('<option value=""></option>')
                // Groupby summary end

                GetViewColumName();

                // Enable to Group By related controls
                $("#chkShowGridlines").removeAttr("disabled");
                $("#chkDisplayCount").removeAttr("disabled");
                $("#groupByColumn1").removeAttr("disabled");
                $("#sortOrder1").removeAttr("disabled");
                $("#chkHideColumn1").removeAttr("disabled");

                $("#groupByColumn2").removeAttr("disabled");
                $("#sortOrder2").removeAttr("disabled");
                $("#chkHideColumn2").removeAttr("disabled");

                // Groupby summary start
                $("#groupBySummary1").removeAttr("disabled");
                $("#groupBySummary2").removeAttr("disabled");
                // Groupby summary end

                $('#lblGroupByRequiredWaitMsg').text("");
            } else {

                // Disable to Group By related controls
                $("#chkShowGridlines").attr("disabled", "disabled");
                $("#chkDisplayCount").attr("disabled", "disabled");
                $("#groupByColumn1").attr("disabled", "disabled");
                $("#sortOrder1").attr("disabled", "disabled");
                $("#chkHideColumn1").attr("disabled", "disabled");

                $("#groupByColumn2").attr("disabled", "disabled");
                $("#sortOrder2").attr("disabled", "disabled");
                $("#chkHideColumn2").attr("disabled", "disabled");

                // Groupby summary start
                $("#groupBySummary1").attr("disabled", "disabled");
                $("#groupBySummary2").attr("disabled", "disabled");
                // Groupby summary end
            }
        }

        function ActivateGroupBy() {
            if ($('#selectView :selected').text() == '') {
                alert('Please select a view');
                return false;
            }
            else {

                var entityName = window.parent.Xrm.Page.getAttribute('iotap_entityid').getValue().toLowerCase();
                // If groupby checkbox is checked then hide Birthday/Anniversay filter                
                if ($("#chkGroupBy").attr('checked')) {
                    window.parent.Xrm.Page.getAttribute('iotap_nextxdays').setValue(null);
                } else {
                    sectionVisibility(true);
                    HideLoadingImage();
                }
                // Enable group by controls
                GroupByRequest();
                // check all group by checkbox 
                if ($("#chkGroupBy").attr('checked')) {
                    $("#chkShowGridlines").attr('checked', true);
                    $("#chkDisplayCount").attr('checked', true);
                    $("#chkHideColumn1").attr('checked', true);
                    $("#chkHideColumn2").attr('checked', true);
                    $("#chkHideColumn3").attr('checked', true);
                }
                SaveGroupByValues();
                return true;
            }
        }
        
        function SaveRemoveLineBreaks() {
            var removeLineBreaks = $("#chkRemoveLineBreaks").attr('checked') ? true : false;
            window.parent.Xrm.Page.getAttribute('iotap_removelinebreaks').setValue(removeLineBreaks);
        }

        function refreshOneToNRelationship() {
            window.parent.Xrm.Page.getAttribute('iotap_1tonrelationship').setValue(false);
            $('#chk1toNRelationship').attr('checked', false);
        }

        function Save1toNRelationship(checked) {
            if (checked) {
                //var chkBirthdayAnnReminder = $( '#chkBirthdayAnnReminder', window.parent.frames['WebResource_CustomBirthdayAnniversayFilter'].document );
                var chkBirthdayAnnReminder = $( '#chkBirthdayAnnReminder', parent.Xrm.Page.ui.controls.get( 'WebResource_CustomBirthdayAnniversayFilter' ).getObject().document );//appsource
                
                // Make 1 to N grouping relationship exclusive from Birthday & normal group by
                if ($('#chkGroupBy').attr('checked')) {
                    $('#chkGroupBy').attr('checked', false);
                    // disable to group by controls
                    GroupByRequest();
                    // flush the group by values
                    SaveGroupByValues();
                }

                // refresh birthday/anniversary filter. If birthday/anniversary checkbox is unchecked but user later types in next x day's then clean Birthday/Anniversary all fields. 
                refreshCustomEntityFilter();

                // set 1 to N relationship checkbox to true as refreshCustomEntityFilter() reset to it unchecked.
                $('#chk1toNRelationship').attr('checked', checked);
            }
            window.parent.Xrm.Page.getAttribute('iotap_1tonrelationship').setValue(checked);
        }

        function OpenTestEmailPage() {
            // Validate if entity & view are selected
            var entityDropdown = document.getElementById("selectEntity");
            var viewDropdown = document.getElementById("selectView");
            if (entityDropdown == null || entityDropdown.options[entityDropdown.selectedIndex].text == "") {
                alert('Please select Entity');
                return;
            } else if (viewDropdown == null || viewDropdown.options[viewDropdown.selectedIndex].text == "") {
                alert('Please select View');
                return;
            }
            else {

                //var multiUserDocument = returnFrameObject( window.parent.frames['WebResource_RecipientList'] );
                var multiUserDocument = returnFrameObject( parent.Xrm.Page.ui.controls.get( 'WebResource_CustomBirthdayAnniversayFilter' ).getObject() );//appsource
                
                // Refresh filter            
                var drpRecipientList = $('#drpRecipientList', multiUserDocument);
                // If blank is selected in multi user dropdown
                if (drpRecipientList.val() == "") {
                    alert('Test Email functionality is not available on empty Recipient Option.')
                    return;
                }
                    // Test functionality is not available on Multi user option.
                else if (drpRecipientList.val() == "2") {
                    alert('Test Email functionality is not available on Recipient Option : Multi-User Scheduling.')
                    return;
                }
                OpenHtmlPreview();
            }
        }

        function OpenHtmlPreview() {
            var URL = returnClientURL() + "/WebResources/iotap_/Addons/ReportScheduler/SendTestEmail.htm";
            //window.open(URL, null, "dialogWidth:800px;dialogHeight:600px;center :yes on 1;scrollbars=yes");    
            window.open(URL, null, "scrollbars = 1, resizable=1, width = 400, height = 290");
        }

        function FetchXmlValidationMsg(results) {
            $('#lblFetchXmlValidationMsg').text("View validated successfully");
            $('#lblFetchXmlValidationMsg').removeClass("errormsg").addClass('msgColor');
        }

        function returnFrameObject(frameElement) {
            // 
            var frameObject = frameElement.document;
            // If browser is mozila domElement would remain undefined
            if (typeof frameObject == 'undefined')
                frameObject = frameElement.contentDocument;

            return frameObject;
        }
    </script>
    <style type="text/css">
        .label
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            font-weight: normal;
        }
        .style2
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            color: Black;
            ime-mode: auto;
            border: 1px solid #CCCCCC;
            margin: 1px 0 0 1px;
            width: 630px;
        }
        .groupBy
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            color: Black;
            ime-mode: auto;
            border: 1px solid #CCCCCC;
            margin: 1px 0 0 1px;
            width: 180px;
        }
        .sortOrder
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            color: Black;
            ime-mode: auto;
            border: 1px solid #CCCCCC;
            margin: 1px 0 0 1px;
            width: 80px;
        }
        .crmbutton
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            height: 20px;
            padding-right: 5px;
            padding-left: 5px;
            border-top-width: 1px;
            border-right-width: 1px;
            border-bottom-width: 1px;
            border-left-width: 1px;
            border-top-style: solid;
            border-left-style: solid;
            border-bottom-style: solid;
            border-right-style: solid;
            cursor: pointer;
            background-repeat: repeat-x;
            border-bottom-color: #666666;
            border-top-color: #666666;
            border-left-color: #666666;
            border-right-color: #666666;
            
        }
        .body
        {
            margin-left: 0px;
            margin-top: 0px;
            margin-right: 0px;
            margin-bottom: 0px;
            background-color: rgb(246, 248, 250);
            padding: 0px;
        }
        .errormsg
        {
            font-family: "Segoe UI";
            text-align: left;
            color: Red;
            font-size: 11px;
        }
        .msg
        {
            font-family: "Segoe UI";
            text-align: left;
            color: Black;
            font-size: 11px;
        }
        .msgColor
        {
            font-family: "Segoe UI";
            text-align: left;
            color: Green;
            font-size: 11px;
        }
    </style>
</head>
<body class="body">
    <div id="loadingDiv"></div>
    <table style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px;
        padding-top: 0px">
        <tbody>
            <tr>
                <td width="120">
                    <span class="label">Entity</span>
                </td>
                <td>
                    <select id="selectEntity" class="style2" onchange="refreshCustomEntityFilter();retiriveEntity();SaveGroupByValues();">
                        <option selected></option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="label">
                    View
                </td>
                <td>
                    <select id="selectView" class="style2" onchange="refreshCustomEntityFilter();retiriveSavedView();SaveGroupByValues();">
                        <option selected></option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="label">
                </td>
                <td>                   
                    <input type="button" id="btnValidateFetchXMl" name="btnValidateFetchXMl" value="Test Email"
                        onclick="OpenTestEmailPage()" class="crmbutton" />
                    <span id="lblFetchXmlValidationMsg" name="lblFetchXmlValidationMsg"></span>
                </td>
            </tr>
            <tr id="trNotes">
                <td class="label">Notes Special Report</td>
                <td>    
                    <input type="checkbox" name="chk1toNRelationship" id="chk1toNRelationship" onclick="Save1toNRelationship(this.checked);"/>
                </td>
            </tr>
            <tr>
                <td class="label">
                    Date-Time Format
                </td>
                <td>
                    <select id="dateTimeFormat" name="dateTimeFormat" class="groupBy" onchange="SaveGroupByValues()">
                        <option selected value=""></option>
                        <option value="MM/dd/yyyy">MM/dd/yyyy</option>
                        <option value="dd/MM/yyyy">dd/MM/yyyy</option>
                        <option value="MM/dd/yyyy HH:mm">MM/dd/yyyy HH:mm</option>
                        <option value="dd/MM/yyyy HH:mm">dd/MM/yyyy HH:mm</option>
                        <option value="MMMM">Month</option>
                        <option value="yyyy">Year</option>
                        <option value="HH:mm">HH:mm</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="label">Remove Line Breaks (if any)</td>
                <td><input type="checkbox" name="chkRemoveLineBreaks" id="chkRemoveLineBreaks" onclick="SaveRemoveLineBreaks()" /></td>
            </tr>
            <tr id="groupByRequired">
                <td class="label">
                    Group By
                </td>
                <td>
                    <input type="checkbox" name="chkGroupBy" id="chkGroupBy" onclick="ShowLoadingImage(); refreshCustomEntityFilter(); return ActivateGroupBy();" />
                    <span id="lblGroupByRequiredWaitMsg" name="lblGroupByRequiredWaitMsg"></span>
                </td>
            </tr>
        </tbody>
    </table>
    <table id="tblGroupBy">
        <tbody>
            <tr>
                <td class="label">
                    Show Gridlines</td>
                <td colspan="7">
                    <input id="chkShowGridlines" name="chkShowGridlines" value="select" type="checkbox" onclick="SaveGroupByValues()"  />
                </td>
            </tr>
            <tr>
                <td class="label">
                    Display Count
                </td>
                <td colspan="7">
                    <input id="chkDisplayCount" name="chkDisplayCount" value="select" type="checkbox" onclick="SaveGroupByValues()" />
                </td>
            </tr>
            <tr>
                <td width="100">
                    <span class="label">Group By 1</span>
                </td>
                <td>
                    <select id="groupByColumn1" name="groupByColumn1" class="groupBy" onchange="SaveGroupByValues()">
                    </select>
                </td>
                <td class="label" width="100">
                    &nbsp;&nbsp;&nbsp; Hide Column
                </td>
                <td>
                    <input id="chkHideColumn1" type="checkbox" name="chkHideColumn1" onclick="SaveGroupByValues()" />
                </td>
                <td width="100">
                    &nbsp;&nbsp;&nbsp; <span class="label">Sort Order</span>
                </td>
                <td>
                    <select id="sortOrder1" class="sortOrder" name="sortOrder1" onchange="SaveGroupByValues()">
                        <option selected value="asc">Ascending</option>
                        <option value="desc">Descending</option>
                    </select>
                </td>
                <td class="label" width="100">
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td width="100">
                    <span class="label">Group By 2</span>
                </td>
                <td>
                    <select id="groupByColumn2" class="groupBy" name="groupByColumn2" onchange="SaveGroupByValues()">
                    </select>
                </td>
                <td class="label">
                    &nbsp;&nbsp;&nbsp; Hide Column
                </td>
                <td>
                    <input id="chkHideColumn2" type="checkbox" name="chkHideColumn2" onclick="SaveGroupByValues()" />
                </td>
                <td style="visibility:hidden;">
                    &nbsp;&nbsp;&nbsp; <span class="label">Sort Order</span>
                </td>
                <td style="visibility:hidden;">
                    <select id="sortOrder2" class="sortOrder" name="sortOrder2" onchange="SaveGroupByValues()">
                        <option selected value="asc">Ascending</option>
                        <option value="desc">Descending</option>
                    </select>
                </td>
                <td class="label">
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr style="display: none;">
                <!-- hide the group by 3 temporarily -->
                <td width="100">
                    <span class="label">Group By 3</span>
                </td>
                <td>
                    <select id="groupByColumn3" name="groupByColumn3" class="groupBy" onchange="SaveGroupByValues()">
                    </select>
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp; <span class="label">Sort Order</span>
                </td>
                <td>
                    <select id="sortOrder3" class="sortOrder" name="sortOrder3" onchange="SaveGroupByValues()">
                        <option selected value="asc">Ascending</option>
                        <option value="desc">Descending</option>
                    </select>
                </td>
                <td class="label">
                    &nbsp;&nbsp;&nbsp; Hide Column
                </td>
                <td>
                    <input id="chkHideColumn3" type="checkbox" name="chkHideColumn3" onclick="SaveGroupByValues()" />
                </td>
                <td class="label">
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            
            <tr>
                <td width="100">
                    <span class="label">Summary 1</span>
                </td>
                <td colspan="6">
                    <select id="groupBySummary1" class="groupBy" name="groupBySummary1" onchange="SaveGroupByValues()">
                    </select>
                </td>                
            </tr>
			
            <tr>
                <td width="100">
                    <span class="label">Summary 2</span>
                </td>
                <td colspan="6">
                    <select id="groupBySummary2" class="groupBy" name="groupBySummary2" onchange="SaveGroupByValues()">
                    </select>
                </td>                
            </tr>
        </tbody>
    </table>
</body>
</html>
