﻿<html><head>
    <title>Send test email</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">
        $( document ).ready( function ()
        {
            var ownerid = window.opener.window.parent.Xrm.Page.getAttribute( "ownerid" ).getValue()[0].id;
            GetLoggedInUserEmailId( ownerid );

            $( "#btnSendTestEmail" ).click( function ()
            {
                var emailIds = $.trim( $( "#txtMultipleEmailId" ).val() );
                if ( emailIds == "" ) {
                    alert( "Please enter valid email address in To" );
                    return;
                }
                else if ( !EmailValidation( emailIds ) ) {
                    alert( "Please enter valid email address in To" );
                    return;
                }
                SendTestEmail();
            } );

            var EmailValidation = function ( emailIds )
            {
                emailIds = emailIds.replace( ",", ";" );
                if ( emailIds.charAt( emailIds.length - 1 ) == ';' ) {
                    emailIds = emailIds.substring( 0, emailIds.length - 1 );
                }
                var emailIdList = emailIds.split( ";" );
                for ( var i = 0; i < emailIdList.length; i++ ) {
                    var validEmail = ValidateEachEmail( emailIdList[i] )
                    if ( !validEmail ) {
                        return false;
                    }
                }
                return true;
            }

            var ValidateEachEmail = function ( EmailId )
            {
                var EmailRegExp = "\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
                var regex = new RegExp( EmailRegExp );
                if ( EmailId.match( regex ) )
                    return true;
                else
                    return false;
            }

            var SendTestEmail = function ()
            {
                var testEmail = new Object();

                var one2NRelationshipValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_1tonrelationship" ).getValue();
                if ( one2NRelationshipValue != null )
                    testEmail.iotap_1tonrelationship = one2NRelationshipValue;

                var isAttachmentRequiredValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_attachment" ).getValue();
                if ( isAttachmentRequiredValue != null )
                    testEmail.iotap_attachment = isAttachmentRequiredValue;

                var attachmentTypeValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_attachmenttype" ).getValue();
                if ( attachmentTypeValue != null )
                    testEmail.iotap_attachmenttype = attachmentTypeValue;

                var autoUpdateRSNameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_autoupdate" ).getValue();
                if ( autoUpdateRSNameValue != null )
                    testEmail.iotap_autoupdate = autoUpdateRSNameValue;

                testEmail.iotap_emailreceipients = $( "#txtMultipleEmailId" ).text();

                var recordCountLengthValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_checkrecordcountlength" ).getValue();
                if ( recordCountLengthValue != null )
                    testEmail.iotap_checkrecordcountlength = recordCountLengthValue;

                var commentValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_comment" ).getValue();
                if ( commentValue != null )
                    testEmail.iotap_comment = commentValue;


                var displayGroupCountValueValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_displaygroupbycount" ).getValue();
                if ( displayGroupCountValueValue != null )
                    testEmail.iotap_displaygroupbycount = displayGroupCountValueValue;

                var emailTemplateValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_emailtemplateoptional" ).getValue();
                if ( emailTemplateValue != null )
                    testEmail["iotap_emailtemplateoptional@odata.bind"] = "/iotap_htmltemplateses(" + emailTemplateValue[0].id.replace( "{", "" ).replace( "}", "" ) + ")";

                var entityIdValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_entityid" ).getValue();
                if ( entityIdValue != null )
                    testEmail.iotap_entityid = entityIdValue;

                var fromRecipientValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_from" ).getValue();
                if ( fromRecipientValue != null )
                    testEmail.iotap_from = fromRecipientValue;

                var groupbyColumn1NameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_groupby1columnname" ).getValue();
                if ( groupbyColumn1NameValue != null )
                    testEmail.iotap_groupby1columnname = groupbyColumn1NameValue;

                var groupbySummaryColumn1NameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_groupby1summarycolumnname" ).getValue();
                if ( groupbySummaryColumn1NameValue != null )
                    testEmail.iotap_groupby1summarycolumnname = groupbySummaryColumn1NameValue;

                var groupbyColumn2NameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_groupby2columnname" ).getValue();
                if ( groupbyColumn2NameValue != null )
                    testEmail.iotap_groupby2columnname = groupbyColumn2NameValue;

                var groupbyColumn1SortOrderValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_groupbysortorder1" ).getValue();
                if ( groupbyColumn1SortOrderValue != null )
                    testEmail.iotap_groupbysortorder1 = groupbyColumn1SortOrderValue;

                var hideGroupbyColumn1NameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_hidegroupby1column" ).getValue();
                if ( hideGroupbyColumn1NameValue != null )
                    testEmail.iotap_hidegroupby1column = hideGroupbyColumn1NameValue;

                var hideGroupbyColumn2NameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_hidegroupby2column" ).getValue();
                if ( hideGroupbyColumn2NameValue != null )
                    testEmail.iotap_hidegroupby2column = hideGroupbyColumn2NameValue;

                var includeHyperlinkValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_includelink" ).getValue();
                if ( includeHyperlinkValue != null )
                    testEmail.iotap_includelink = includeHyperlinkValue;

                var includeRelatedEntityHyperlinkValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_includerelatedentitylink" ).getValue();
                if ( includeRelatedEntityHyperlinkValue != null )
                    testEmail.iotap_includerelatedentitylink = includeRelatedEntityHyperlinkValue;

                var inlineEmailOutputValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_inline" ).getValue();
                if ( inlineEmailOutputValue != null )
                    testEmail.iotap_inline = inlineEmailOutputValue;

                // Selected user view
                var userEntityViewIdValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_userentityviewid" ).getValue();
                if ( userEntityViewIdValue != null )
                    testEmail.iotap_userentityviewid = userEntityViewIdValue;

                var reportSchedulerIdValue = window.opener.window.parent.Xrm.Page.data.entity.getId() == "" ? null : window.opener.window.parent.Xrm.Page.data.entity.getId();
                if ( reportSchedulerIdValue != null )
                    testEmail["iotap_rsid@odata.bind"] = "/iotap_scheduledreports(" + reportSchedulerIdValue.replace( "{", "" ).replace( "}", "" ) + ")";

                var xmlQueryValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_xmlquery" ).getValue();
                if ( xmlQueryValue != null ) {
                    xmlQueryValue = xmlQueryValue.replace( new RegExp( "<", "g" ), "&lt;" )
                    xmlQueryValue = xmlQueryValue.replace( new RegExp( ">", "g" ), "&gt;" )
                }

                if ( xmlQueryValue != null )
                    testEmail.iotap_xmlquery = xmlQueryValue;

                var weekday = new Array( 7 );
                weekday[0] = "Sun";
                weekday[1] = "Mon";
                weekday[2] = "Tue";
                weekday[3] = "Wed";
                weekday[4] = "Thu";
                weekday[5] = "Fri";
                weekday[6] = "Sat";

                //View name
                var viewNameValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_viewname" ).getValue();
                var day = weekday[new Date().getDay()];
                var currentLocalHour = new Date().getHours();
                var currentHours = currentLocalHour % 12 || 12;

                // Shows actual current time with AM/PM.
                var timeValue = currentHours + ":00 " + ( currentLocalHour == 24 ? "AM" : currentLocalHour < 12 ? "AM" : "PM" );

                testEmail.iotap_currentday = day;

                var ownerName = window.opener.window.parent.Xrm.Page.getAttribute( "ownerid" ).getValue()[0].name;
                var rsNameValue = "[" + viewNameValue + "]" + "[" + day + " - " + timeValue + "]" + "[" + ownerName + "]";
                testEmail.iotap_name = rsNameValue;

                var removeLineBreakValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_removelinebreaks" ).getValue();
                if ( removeLineBreakValue != null )
                    testEmail.iotap_removelinebreaks = removeLineBreakValue;

                // For birthday. Birthday related fields are getting saved on save button therefore need to read value from birthday reminder's html controls.
                var customEntityBirthdayAnniversayDocument = window.opener.window.parent.frames['WebResource_CustomBirthdayAnniversayFilter'].document;
                // If browser is mozila domElement would remain undefined
                if ( typeof customEntityBirthdayAnniversayDocument == 'undefined' )
                    customEntityBirthdayAnniversayDocument = window.opener.window.parent.frames['WebResource_CustomBirthdayAnniversayFilter'].contentDocument;

                var birthdaySelectedAttributeNameValue = $.trim( customEntityBirthdayAnniversayDocument.getElementById( "drpFieldName" ).value ) != "" ? customEntityBirthdayAnniversayDocument.getElementById( "drpFieldName" ).value : null;
                if ( birthdaySelectedAttributeNameValue != null )
                    testEmail.iotap_selectedfilterattributename = birthdaySelectedAttributeNameValue;

                var birthdayIntermediateDaysValue = customEntityBirthdayAnniversayDocument.getElementById( "chkIntermediateDays" ).checked;
                if ( birthdayIntermediateDaysValue != null )
                    testEmail.iotap_intermediatedays = birthdayIntermediateDaysValue;

                var birthdayNextXDaysValue = $.trim( customEntityBirthdayAnniversayDocument.getElementById( "txtNextXDays" ).value ) != "" ? customEntityBirthdayAnniversayDocument.getElementById( "txtNextXDays" ).value : null;
                if ( birthdaySelectedAttributeNameValue != null )
                    testEmail.iotap_nextxdays = birthdayNextXDaysValue;

                if ( birthdayIntermediateDaysValue != null )
                    testEmail.iotap_upcomingeventfilter = 100000000;

                var serverURLValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_serverurl" ).getValue();
                testEmail.iotap_serverurl = serverURLValue;

                var showGridLinesValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_showgridlines" ).getValue();
                testEmail.iotap_showgridlines = showGridLinesValue;

                var emailSubjectValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_subject" ).getValue();
                testEmail.iotap_subject = emailSubjectValue;

                var entityTypeCodeValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_entitytypecode" ).getValue();
                testEmail.iotap_entitytypecode = entityTypeCodeValue;

                var viewIdValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_viewid" ).getValue();
                testEmail.iotap_viewid = viewIdValue;

                var viewTypeCodeValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_viewtype" ).getValue();
                testEmail.iotap_viewtype = viewTypeCodeValue;

                testEmail.iotap_viewname = viewNameValue;

                var dateTimeFormatValue = window.opener.window.parent.Xrm.Page.getAttribute( "iotap_datetimeformat" ).getValue();
                dateTimeFormatValue = dateTimeFormatValue == null ? null : ( $.trim( dateTimeFormatValue ) == "" ? null : dateTimeFormatValue );
                if ( dateTimeFormatValue != null )
                    testEmail.iotap_datetimeformat = dateTimeFormatValue;


                $.ajax( {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    url: window.parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.0/iotap_testemails",
                    data: JSON.stringify( testEmail ),
                    beforeSend: function ( XMLHttpRequest )
                    {
                        XMLHttpRequest.setRequestHeader( "Accept", "application/json" );
                        XMLHttpRequest.setRequestHeader( "OData-MaxVersion", "4.0" );
                        XMLHttpRequest.setRequestHeader( "OData-Version", "4.0" );
                    },
                    success: function ( data, textStatus, XmlHttpRequest )
                    {
                        alert( 'Your test email request has been added successfully to the queue. To view present status, kindly check section "Test Email status".' )
                        window.close();
                    },
                    error: function ( XmlHttpRequest, textStatus, errorThrown )
                    {
                        alert( "Error " + textStatus + errorThrown );

                    }
                } );

            }
        } );
      
        function GetLoggedInUserEmailId( ownerid )
        {
            context = window.opener.window.parent.Xrm.Page.context;
            serverUrl = context.getClientUrl();
            
            ODATA_ENDPOINT = "/api/data/v8.0/systemusers(" + ownerid.replace( "{", "" ).replace( "}", "" ) + " )?$select=internalemailaddress";
            var odataUri = serverUrl + ODATA_ENDPOINT;
            
            var httpReq = new XMLHttpRequest();
            httpReq.onreadystatechange = function ()
            {
                if ( this.readyState == 4 && (this.status == 200 || this.status == 1223) ) {
                    var result = JSON.parse( this.responseText );
                    var emailaddress = result["internalemailaddress"];
                    $( "#txtMultipleEmailId" ).text( emailaddress + ";" );
                }   
            };

            httpReq.open( "GET", odataUri, 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 );
        }

    </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;
        }

        #txtMultipleEmailId {
            width: 273px;
            height: 151px;
        }
    </style>

</head>
<body>
    ﻿
    <table style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px;padding-top: 0px">
        <tbody>
            <tr>
                <td colspan="2"><span class="label" style="font-size:14px;">Email Testing</span></td>
            </tr>
            <tr><td colspan="2">&nbsp;</td></tr>
            <tr>
                <td colspan="2"><span class="label">Send Test Email To:</span></td>
            </tr>
            <tr>
                <td colspan="2">
                    <textarea id="txtMultipleEmailId" name="txtMultipleEmailId" class="label"></textarea>
                </td>
            </tr>
            <tr>
                <td> <span class="label">(Seperate additional emails with a semi-colon)</span></td>
                <td> <input name="btnSendTestEmail" id="btnSendTestEmail" value="Send" class="crmbutton" type="button"> </td>
            </tr>
        </tbody>
    </table>


</body></html>