{% extends "@UVDeskCoreFramework//Templates//layout.html.twig" %}

{% block title %} 
	{{ 'Mailbox Settings'|trans }}
{% endblock %}

{% block pageContent %}
	<style>
		.section-heading {
			font-size: 16px;
			margin: 0px;
			line-height: 1.4em;
		}

		.section-description {
			color: #6F6F6F;
			margin-top: unset !important;
			margin-bottom: 20px;
			line-height: 1.4em;
		}

		.uv-element-block .uv-field-message {
			font-style: normal;
			margin: 0px 0px 20px 0px;
		}
	</style>

	<div class="uv-inner-section">
		{# Append Panel Aside #}
		{% set asideTemplate = 'Webkul\\UVDesk\\CoreFrameworkBundle\\Dashboard\\AsideTemplate' %}
		{% set asideSidebarReference = 'Webkul\\UVDesk\\CoreFrameworkBundle\\UIComponents\\Dashboard\\Panel\\Sidebars\\Settings' %}

		{{ uvdesk_extensibles.getRegisteredComponent(asideTemplate).renderSidebar(asideSidebarReference) | raw }}

		<div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
			{% if mailbox is defined and mailbox.id is not empty %}
				<h1>{{ 'Update Mailbox'|trans }}</h1>
			{% else %}
				<h1>{{ 'Add Mailbox'|trans }}</h1>
			{% endif %}

            <div class="uv-hr"></div>
			
			<form method="post" action="" id="mailbox-settings-view">
				{# Mailer Id #}
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'ID'|trans }}</label>

					<div class="uv-field-block">
						{% if mailbox is defined and mailbox.id is not empty %}
							<input type="text" name="id" class="uv-field" value="{{ mailbox.id }}" placeholder="{{ 'Mailbox ID - Leave blank to automatically create id'|trans }}" />
						{% else %}
							<input type="text" name="id" class="uv-field" value="" placeholder="{{ 'Mailbox ID - Leave blank to automatically create id'|trans }}" />
						{% endif %}
					</div>
				</div>

				{# Mailer Name #}
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Name'|trans }}</label>

					<div class="uv-field-block">
						{% if mailbox is defined and mailbox.name is not empty %}
							<input type="text" name="name" class="uv-field" value="{{ mailbox.name }}" placeholder="{{ 'Mailbox Name'|trans }}" />
						{% else %}
							<input type="text" name="name" class="uv-field" value="" placeholder="{{ 'Mailbox Name'|trans }}" />
						{% endif %}
					</div>
				</div>

				{# Status #}
				<div class="uv-element-block">
					<label>
						<div class="uv-checkbox">
							{% if mailbox.isEnabled is defined and mailbox.isEnabled == true %}
								<input name="isEnabled" type="checkbox" checked="">
							{% else %}
								<input name="isEnabled" type="checkbox" checked="checked">
							{% endif %}

							<span class="uv-checkbox-view"></span>
						</div>

						<span class="uv-checkbox-label">{{ 'Enable Mailbox'|trans }}</span>
					</label>
				</div>

				{# Delivery Status #}
				<div class="uv-element-block">
					<label>
						<div class="uv-checkbox">
							{% if mailbox.isEmailDeliveryDisabled is defined and mailbox.isEmailDeliveryDisabled == true %}
								<input name="isEmailDeliveryDisabled" type="checkbox" checked="">
							{% else %}
								<input name="isEmailDeliveryDisabled" type="checkbox">
							{% endif %}

							<span class="uv-checkbox-view"></span>
						</div>

						<span class="uv-checkbox-label">{{ 'Disable email delivery'|trans }}</span>
					</label>
				</div>

				{# Default Mailbox #}
				<div class="uv-element-block">
					<label>
						<div class="uv-checkbox">
							{% if isDefaultMailbox is defined and isDefaultMailbox == true %}
								<input name="isDefault" type="checkbox" checked="checked">
							{% else %}
								<input name="isDefault" type="checkbox">
							{% endif %}

							<span class="uv-checkbox-view"></span>
						</div>

						<span class="uv-checkbox-label">{{ 'Use as default mailbox for sending emails'|trans }}</span>
					</label>
				</div>

				<div class="uv-hr"></div>

				{# IMAP Settings #}
				<h3 class="section-heading">{{ 'Inbound Emails'|trans }}</h3>
				<p class="section-description">{{ 'Manage how you wish to retrieve and process emails from your mailbox.'|trans }}</p>

				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Transport'|trans }}</label>

					{% if mailbox is defined and mailbox.imapConfiguration is not empty %}
						<select name="imap[transport]" id="mailboxIncomingTransportType" class="uv-select">
							<option value="">{{ 'None Selected'|trans }}</option>
							<option value="gmail" {% if mailbox.imapConfiguration.code == 'gmail' %}selected{% endif %}>{{ 'Gmail'|trans }}</option>
							<option value="imap" {% if mailbox.imapConfiguration.code == 'imap' %}selected{% endif %}>{{ 'IMAP'|trans }}</option>
							<option value="outlook" {% if mailbox.imapConfiguration.code == 'outlook' %}selected{% endif %}>{{ 'Outlook'|trans }}</option>
							<option value="outlook_oauth" {% if mailbox.imapConfiguration.code == 'outlook_oauth' %}selected{% endif %}>{{ 'Outlook Modern Auth'|trans }}</option>
							<option value="webhook" {% if mailbox.imapConfiguration.code == 'webhook' %}selected{% endif %}>{{ 'Webhook'|trans }}</option>
							<option value="yahoo" {% if mailbox.imapConfiguration.code == 'yahoo' %}selected{% endif %}>{{ 'Yahoo'|trans }}</option>
						</select>
					{% else %}
						<select name="imap[transport]" id="mailboxIncomingTransportType" class="uv-select">
							<option value="" selected>{{ 'None Selected'|trans }}</option>
							<option value="gmail">{{ 'Gmail'|trans }}</option>
							<option value="imap">{{ 'IMAP'|trans }}</option>
							<option value="outlook">{{ 'Outlook'|trans }}</option>
							<option value="outlook_oauth">{{ 'Outlook Modern Auth'|trans }}</option>
							<option value="webhook">{{ 'Webhook'|trans }}</option>
							<option value="yahoo">{{ 'Yahoo'|trans }}</option>
						</select>
					{% endif %}
				</div>

				<div class="imap-setting-references"></div>

				<div class="uv-hr"></div>

				{# SMTP Settings #}
				<h3 class="section-heading">{{ 'Outbound Emails'|trans }}</h3>
				<p class="section-description">{{ 'Manage how you wish to send emails from your mailbox.'|trans }}</p>

				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Transport'|trans }}</label>

					{% if mailbox is defined and mailbox.smtpConfiguration is not empty %}
						<select name="smtp[transport]" id="mailboxOutgoingTransportType" class="uv-select">
							<option value="">{{ 'None Selected'|trans }}</option>
							<option value="smtp" {% if mailbox.smtpConfiguration.code == 'smtp' %}selected{% endif %}>{{ 'SMTP'|trans }}</option>
							<option value="gmail" {% if mailbox.smtpConfiguration.code == 'gmail' %}selected{% endif %}>{{ 'Gmail'|trans }}</option>
							<option value="yahoo" {% if mailbox.smtpConfiguration.code == 'yahoo' %}selected{% endif %}>{{ 'Yahoo'|trans }} </option>
							<option value="outlook" {% if mailbox.smtpConfiguration.code == 'outlook' %}selected{% endif %}>{{ 'Outlook'|trans }} </option>
							<option value="outlook_oauth" {% if mailbox.smtpConfiguration.code == 'outlook_oauth' %}selected{% endif %}>{{ 'Outlook Modern Auth'|trans }} </option>
						</select>
					{% else %}
						<select name="smtp[transport]" id="mailboxOutgoingTransportType" class="uv-select">
							<option value="" selected>{{ 'None Selected'|trans }}</option>
							<option value="smtp">{{ 'SMTP'|trans }}</option>
							<option value="gmail">{{ 'Gmail'|trans }}</option>
							<option value="yahoo">{{ 'Yahoo'|trans }}</option>
							<option value="outlook">{{ 'Outlook'|trans }} </option>
							<option value="outlook_oauth">{{ 'Outlook Modern Auth'|trans }} </option>
						</select>
					{% endif %}
				</div>

				<div class="smtp-setting-references"></div>

				<div class="uv-hr"></div>
				
				{% if mailbox is defined and mailbox.id is not empty %}
					<input id="saveConfigurationSettings" class="uv-btn" href="#" value="{{ 'Update Mailbox'|trans }}" type="submit">
				{% else %}
					<input id="saveConfigurationSettings" class="uv-btn" href="#" value="{{ 'Create Mailbox'|trans }}" type="submit">
				{% endif %}
			</form>
		</div>
	</div>
{% endblock %}

{% block footer %}
	{{ parent() }}

	<script id="default_imap_configuration_template" type="text/template">
        <div class="uv-element-block">
			<label class="uv-field-label">{{ 'Host'|trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(host) != 'undefined' && host != '') { %>
					<input class="uv-field" type="text" name="imap[host]" value="<%- host %>" placeholder="<%- host %>">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[host]" value="" placeholder="{{'IMAP Host'|trans }}">
                <% } %>
			</div>
		</div>

		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Username'|trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(username) != 'undefined' && username != '') { %>
					<input class="uv-field" type="text" name="imap[username]" value="<%- username %>" placeholder="{{'username@domain.com'|trans }}">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[username]" value="" placeholder="{{'username@domain.com'|trans }}">
                <% } %>
			</div>
		</div>
		
		<div class="uv-element-block">
			<label class="uv-field-label">{{'Password'|trans }}</label>

			<div class="uv-field-block">
				<input class="uv-field" type="password" name="imap[password]" placeholder="{{'Associated Password'|trans }}">
			</div>
		</div>
	</script>

    <script id="gmail_imap_configuration_template" type="text/template">
        <div class="uv-element-block">
			<label class="uv-field-label">{{ 'Username' |trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(username) != 'undefined' && username != '') { %>
					<input class="uv-field" type="text" name="imap[username]" value="<%- username %>" placeholder="{{ 'username@domain.com'|trans }}">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[username]" value="" placeholder="{{ 'username@domain.com'|trans }}">
                <% } %>
			</div>
		</div>
		
		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Password' |trans }}</label>

			<div class="uv-field-block">
				<input class="uv-field" type="password" name="imap[password]" placeholder="{{ 'Associated Password'|trans }}">
			</div>
		</div>
	</script>

	<script id="yahoo_imap_configuration_template" type="text/template">
        <div class="uv-element-block">
			<label class="uv-field-label">{{ 'Username' |trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(username) != 'undefined' && username != '') { %>
					<input class="uv-field" type="text" name="imap[username]" value="<%- username %>" placeholder="{{ 'username@domain.com'|trans }}">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[username]" value="" placeholder="{{ 'username@domain.com'|trans }}">
                <% } %>
			</div>
		</div>
		
		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Password' |trans }}</label>

			<div class="uv-field-block">
				<input class="uv-field" type="password" name="imap[password]" placeholder="{{ 'Associated Password'|trans }}">
			</div>
		</div>
	</script>

	<script id="outlook_imap_configuration_template" type="text/template">
        <div class="uv-element-block">
			<label class="uv-field-label">{{ 'Username' |trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(username) != 'undefined' && username != '') { %>
					<input class="uv-field" type="text" name="imap[username]" value="<%- username %>" placeholder="{{ 'username@domain.com'|trans }}">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[username]" value="" placeholder="{{ 'username@domain.com'|trans }}">
                <% } %>
			</div>
		</div>
		
		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Password' |trans }}</label>

			<div class="uv-field-block">
				<input class="uv-field" type="password" name="imap[password]" placeholder="{{ 'Associated Password'|trans }}">
			</div>
		</div>
	</script>

	<script id="outlook_oauth_imap_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Email'|trans }}</label>

            {% if microsoftAccountCollection is defined and microsoftAccountCollection is not empty %}
                <select name="imap[username]" class="uv-select">
					<option value="" selected>No account selected</option>

                    {% for microsoftAccount in microsoftAccountCollection %}
                        <option value="{{ microsoftAccount.id }}">{{ microsoftAccount.email }}</option>
                    {% endfor %}
                </select>
            {% else %}
                <select name="imap[username]" class="uv-select" disabled>
                    <option selected>{{ 'No microsoft account currently available'|trans }}</option>
                </select>
            {% endif %}

			<p class="uv-field-info" style="margin-top: unset;">Select from one of the previously configured microsoft accounts.</p>
        </div>

		<div class="uv-hr"></div>

		<div class="uv-element-block">
            <p class="uv-field-label" style="margin-bottom: 6px;">{{ 'Microsoft App'|trans }}</p>
			<p class="uv-field-info" style="font-style: normal; margin-top: unset;">Continue by signing in through microsoft to add a new account.</p>

            {% if microsoftAppCollection is defined and microsoftAppCollection is not empty %}
                <select id="imap-microsoftAppId" name="imap[microsoftAppId]" class="uv-select">
					<option value="" selected>No app selected</option>

                    {% for microsoftApp in microsoftAppCollection %}
                        <option value="{{ microsoftApp.id }}">{{ microsoftApp.name }}</option>
                    {% endfor %}
                </select>

				<button class="uv-btn continue-with-microsoft-app" data-reference="imap-microsoftAppId" style="background-color: #00a1f1;">Continue with Microsoft</button>
            {% else %}
                <select id="imap-microsoftAppId" name="imap[microsoftAppId]" class="uv-select" disabled>
                    <option selected>{{ 'No configured microsoft app currently available'|trans }}</option>
                </select>

				<a href="{{ path('uvdesk_member_core_framework_microsoft_apps_settings') }}" class="uv-btn" style="background-color: #00a1f1;">Manage Microsoft Apps</a>
            {% endif %}
        </div>
	</script>

	<script id="webhook_imap_configuration_template" type="text/template">
		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Username'|trans }}</label>
			
			<div class="uv-field-block">
				<% if (typeof(username) != 'undefined' && username != '') { %>
					<input class="uv-field" type="text" name="imap[username]" value="<%- username %>" placeholder="{{'username@domain.com'|trans }}">
				<% } else { %>
					<input class="uv-field" type="text" name="imap[username]" value="" placeholder="{{'username@domain.com'|trans }}">
                <% } %>
			</div>
		</div>

		<div class="uv-element-block">
			<label class="uv-field-label">{{ 'Webhook Endpoint'|trans }}</label>
			
			<p>{{ url('helpdesk_member_mailbox_notification') }}</p>
		</div>
	</script>

	<script id="default_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Server'|trans }}</label>

            <div class="uv-field-block">
                <% if (typeof(host) != 'undefined' && host != '') { %>
                    <input type="text" name="smtp[host]" class="uv-field" value="<%- host %>" />
                <% } else { %>
                    <input type="text" name="smtp[host]" class="uv-field" value="" />
                <% } %>
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Username'|trans }}</label>
            
            <div class="uv-field-block">
                <% if (typeof(username) != 'undefined' && username != '') { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="<%- username %>" />
                <% } else { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="" />
                <% } %>
            </div>
        </div>

		<div class="uv-element-block">
            <label class="uv-field-label">{{ 'Sender Address'|trans }}</label>
            
            <div class="uv-field-block">
                <% if (typeof(senderAddress) != 'undefined' && senderAddress != '') { %>
                    <input type="text" name="smtp[senderAddress]" class="uv-field" value="<%- senderAddress %>" placeholder="Send emails using this email address" />
                <% } else { %>
                    <input type="text" name="smtp[senderAddress]" class="uv-field" value="" placeholder="Send emails using this email address" />
                <% } %>
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Password'|trans }}</label>
            
            <div class="uv-field-block">
                <input type="password" name="smtp[password]" class="uv-field" value="" placeholder="Associated Password" />
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Port'|trans }}</label>
            
            <div class="uv-field-block">
                <% if (typeof(port) != 'undefined' && port != '') { %>
                    <input type="text" name="smtp[port]" class="uv-field" value="<%- port %>" />
                <% } else { %>
                    <input type="text" name="smtp[port]" class="uv-field" value="465" />
                <% } %>
            </div>
        </div>
	</script>

    <script id="gmail_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Username'|trans }}</label>

            <div class="uv-field-block">
                <% if (typeof(username) != 'undefined' && username != '') { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="<%- username %>" />
                <% } else { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="" />
                <% } %>
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Password'|trans }}</label>

            <div class="uv-field-block">
                <input type="password" name="smtp[password]" class="uv-field" value="" placeholder="Associated Password" />
            </div>
        </div>
	</script>

    <script id="yahoo_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Username'|trans }}</label>

            <div class="uv-field-block">
                <% if (typeof(username) != 'undefined' && username != '') { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="<%- username %>" />
                <% } else { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="" />
                <% } %>
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Password'|trans }}</label>

            <div class="uv-field-block">
                <input type="password" name="smtp[password]" class="uv-field" value="" placeholder="Associated Password" />
            </div>
        </div>
	</script>

    <script id="outlook_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Username'|trans }}</label>

            <div class="uv-field-block">
                <% if (typeof(username) != 'undefined' && username != '') { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="<%- username %>" />
                <% } else { %>
                    <input type="text" name="smtp[username]" class="uv-field" value="" />
                <% } %>
            </div>
        </div>

        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Password'|trans }}</label>

            <div class="uv-field-block">
                <input type="password" name="smtp[password]" class="uv-field" value="" placeholder="Associated Password" />
            </div>
        </div>
	</script>

    <script id="outlook_oauth_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
            <label class="uv-field-label">{{ 'Username'|trans }}</label>

            {% if microsoftAccountCollection is defined and microsoftAccountCollection is not empty %}
                <select name="smtp[username]" class="uv-select">
					<option value="" selected>No account selected</option>

                    {% for microsoftAccount in microsoftAccountCollection %}
                        <option value="{{ microsoftAccount.id }}">{{ microsoftAccount.email }}</option>
                    {% endfor %}
                </select>
            {% else %}
                <select name="smtp[username]" class="uv-select" disabled>
                    <option selected>{{ 'No microsoft account currently available'|trans }}</option>
                </select>
            {% endif %}

			<p class="uv-field-info" style="margin-top: unset;">Select from one of the previously configured microsoft accounts.</p>
        </div>

		<div class="uv-hr"></div>

        <div class="uv-element-block">
			<p class="uv-field-label" style="margin-bottom: 6px;">{{ 'Microsoft App'|trans }}</p>
			<p class="uv-field-info" style="font-style: normal; margin-top: unset;">Continue by signing in through microsoft to add a new account.</p>

            {% if microsoftAppCollection is defined and microsoftAppCollection is not empty %}
                <select id="smtp-microsoftAppId" name="smtp[microsoftAppId]" class="uv-select">
					<option value="" selected>No app selected</option>

                    {% for microsoftApp in microsoftAppCollection %}
                        <option value="{{ microsoftApp.id }}">{{ microsoftApp.name }}</option>
                    {% endfor %}
                </select>

				<button class="uv-btn continue-with-microsoft-app" data-reference="smtp-microsoftAppId" style="background-color: #00a1f1;" type="button">Continue with Microsoft</button>
            {% else %}
                <select id="smtp-microsoftAppId" name="smtp[microsoftAppId]" class="uv-select" disabled>
                    <option selected>{{ 'No configured microsoft app currently available'|trans }}</option>
                </select>

				<a href="{{ path('uvdesk_member_core_framework_microsoft_apps_settings') }}" class="uv-btn" style="background-color: #00a1f1;">Manage Microsoft Apps</a>
            {% endif %}
        </div>
	</script>

	<script type="text/javascript">
		let microsoftAuthPlaceholderUri = "{{ url('uvdesk_member_core_framework_integrations_microsoft_apps_add_account', { appId: 'placeholder', origin: 'helpdesk_member_mailbox_create_configuration' }) }}";

		$(function () {
			var MailboxConfigurationModel = Backbone.Model.extend({
                idAttribute: "id",
                validation: {
					name: function(value) {
						if (value == undefined || value == '') {
							return "Please specify a valid name for your mailbox.";
						}
                    },
					"imap[host]": function(value) {
						let incomingEmailSettings = this.get('incoming');

                        if ('imap' == incomingEmailSettings.transport) {
                            if (value == undefined || value == '') {
                                return "Please specify a valid host address.";
                            }
                        }
                    },
                    "imap[username]": function(value) {
						let incomingEmailSettings = this.get('incoming');

						if (incomingEmailSettings.transport != "") {
							if ('outlook_oauth' != incomingEmailSettings.transport) {
								if (value == undefined || value == '') {
									return "Please enter a valid email address";
								} else if (/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value) == false) {
									return "Please specify a valid email address";
								}
							} else {
								if (value == undefined || value == '') {
									return "Please select from one of the available microsoft accounts";
								}
							}
						}
                    },
                    "imap[password]": function(value) {
						let incomingEmailSettings = this.get('incoming');
						
						if (incomingEmailSettings.transport != "") {
							if ((value == undefined || value == '') && this.attributes['imap[transport]'] != 'webhook' && this.attributes['imap[transport]'] != 'outlook_oauth') {
								return "Please enter the associated account password.";
							}
						}
                    },
					"smtp[host]": function(value) {
						let outgoingEmailSettings = this.get('outgoing');

                        if ('smtp' == outgoingEmailSettings.transport) {
                            if (value == undefined || value == '') {
                                return "Please enter your server host address";
                            }
                        }
                    },
					"smtp[username]": function(value) {
						let outgoingEmailSettings = this.get('outgoing');

						if (outgoingEmailSettings.transport != "") {
							if ('outlook_oauth' != outgoingEmailSettings.transport) {
								if (value == undefined || value == '') {
									return "Please enter a valid username";
								}
							} else {
								if (value == undefined || value == '') {
									return "Please select from one of the available microsoft accounts";
								}
							}
						}
                    },
					"smtp[senderAddress]": function(value) {
						let outgoingEmailSettings = this.get('outgoing');

						if (outgoingEmailSettings.transport == "default") {
                            if (value != undefined && value != '') {
								if (/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value) == false) {
									return "Please specify a valid email address";
								}
							}
						}
                    },
                    "smtp[password]": function(value) {
						let outgoingEmailSettings = this.get('outgoing');
						
						if (outgoingEmailSettings.transport != "") {
							if ((value == undefined || value == '') && 'outlook_oauth' != outgoingEmailSettings.transport) {
								return "Please enter the password associated with your email address";
							}
						}
                    },
                    "smtp[port]": function(value) {
						let outgoingEmailSettings = this.get('outgoing');

                        if ('smtp' == outgoingEmailSettings.transport) {
                            if (value == undefined || value == '') {
                                return "Please specify a port number to connect with your mail server";
                            }
                        }
                    }
				}
			});

			var MailboxConfigurationView = Backbone.View.extend({
                default_imap_configuration_template: _.template($("#default_imap_configuration_template").html()),
                gmail_imap_configuration_template: _.template($("#gmail_imap_configuration_template").html()),
				yahoo_imap_configuration_template: _.template($("#yahoo_imap_configuration_template").html()),
				outlook_imap_configuration_template: _.template($("#outlook_imap_configuration_template").html()),
				outlook_oauth_imap_configuration_template: _.template($("#outlook_oauth_imap_configuration_template").html()),
				webhook_imap_configuration_template: _.template($("#webhook_imap_configuration_template").html()),
				default_smtp_configuration_template: _.template($("#default_smtp_configuration_template").html()),
                gmail_smtp_configuration_template: _.template($("#gmail_smtp_configuration_template").html()),
                yahoo_smtp_configuration_template: _.template($("#yahoo_smtp_configuration_template").html()),
                outlook_smtp_configuration_template: _.template($("#outlook_smtp_configuration_template").html()),
                outlook_oauth_smtp_configuration_template: _.template($("#outlook_oauth_smtp_configuration_template").html()),
				events: {
                    'change #mailboxIncomingTransportType': 'changeIncomingTransportType', 
					'change #mailboxOutgoingTransportType': 'changeOutgoingTransportType', 
					'click #saveConfigurationSettings' : "submitConfigurationSettings", 
					'click .continue-with-microsoft-app': "continueWithMicrosoftApp"
				},
				initialize: function() {
                    Backbone.Validation.bind(this);

                    this.renderIncomingTransportConfigurations();
					this.renderOutgoingTransportConfigurations();
				},
                changeIncomingTransportType: function(e) {
					let transport = $(e.target).val();
					let incomingEmailSettings = this.model.get('incoming');
					
					incomingEmailSettings.transport = transport;
					this.model.set('incoming', incomingEmailSettings);

					console.log('changeIncomingTransportType model:', incomingEmailSettings);

                    this.renderIncomingTransportConfigurations();
                },
				changeOutgoingTransportType: function(e) {
					let transport = $(e.target).val();
					let outgoingEmailSettings = this.model.get('outgoing');
					
					outgoingEmailSettings.transport = transport;
					this.model.set('outgoing', outgoingEmailSettings);

					console.log('changeOutgoingTransportType model:', this.model);

                    if (true) {
                        this.model.set('transport', $(e.target).val());
                    }

                    this.renderOutgoingTransportConfigurations();
                },
				continueWithMicrosoftApp: function(e) {
					e.preventDefault();

					let reference = $(e.target).data('reference');
					let microsoftAppId = $("#" + reference).val();

					if (microsoftAppId != "") {
						window.location.href = microsoftAuthPlaceholderUri.replace('placeholder', microsoftAppId);
					} else {
						console.log('select a valid microsoft app');
					}
                },
                renderIncomingTransportConfigurations: function() {
					let incomingEmailSettings = this.model.get('incoming');

					console.log('renderIncomingTransportConfigurations:', incomingEmailSettings);

                    switch (incomingEmailSettings.transport) {
                        case 'imap':
                            $('.imap-setting-references').html(this.default_imap_configuration_template(incomingEmailSettings));
                            break;
                        case 'gmail':
                            $('.imap-setting-references').html(this.gmail_imap_configuration_template(incomingEmailSettings));
                            break;
                        case 'yahoo':
                            $('.imap-setting-references').html(this.yahoo_imap_configuration_template(incomingEmailSettings));
                            break;
						case 'outlook':
                            $('.imap-setting-references').html(this.outlook_imap_configuration_template(incomingEmailSettings));
                            break;
						case 'outlook_oauth':
                            $('.imap-setting-references').html(this.outlook_oauth_imap_configuration_template(incomingEmailSettings));
                            break;
						case 'webhook':
                            $('.imap-setting-references').html(this.webhook_imap_configuration_template(incomingEmailSettings));
                            break;
                        default:
                            break;
                    }
                },
				renderOutgoingTransportConfigurations: function() {
					let outgoingEmailSettings = this.model.get('outgoing');

					console.log('renderOutgoingTransportConfigurations:', outgoingEmailSettings);

                    switch (outgoingEmailSettings.transport) {
						case 'smtp':
                            $('.smtp-setting-references').html(this.default_smtp_configuration_template(outgoingEmailSettings));
                            break;
                        case 'gmail':
                            $('.smtp-setting-references').html(this.gmail_smtp_configuration_template(outgoingEmailSettings));
                            break;
                        case 'yahoo':
                            $('.smtp-setting-references').html(this.yahoo_smtp_configuration_template(outgoingEmailSettings));
                            break;
						case 'outlook':
                            $('.smtp-setting-references').html(this.outlook_smtp_configuration_template(outgoingEmailSettings));
                            break;
						case 'outlook_oauth':
                            $('.smtp-setting-references').html(this.outlook_oauth_smtp_configuration_template(outgoingEmailSettings));
                            break;
                        default:
                            break;
                    }
                },
                submitConfigurationSettings: function(e) {
                    e.preventDefault();

                    this.model.set(this.$el.serializeObject());

			        if (this.model.isValid(true)) {
			            this.$el.submit();
			        }
                }
			});

            {% if mailbox is defined %}
				new MailboxConfigurationView({
					el: $("#mailbox-settings-view"),
					model: new MailboxConfigurationModel({
						incoming: {
							transport: "{{ mailbox.imapConfiguration.code is defined and mailbox.imapConfiguration.code is not empty ? mailbox.imapConfiguration.code : '' }}",
							host: "{{ mailbox.imapConfiguration.host is defined and mailbox.imapConfiguration.host is not empty ? mailbox.imapConfiguration.host : '' }}",
							username: "{{ mailbox.imapConfiguration.username is defined and mailbox.imapConfiguration.username is not empty ? mailbox.imapConfiguration.username : '' }}",
						},
						outgoing: {
							transport: "{{ mailbox.smtpConfiguration.code is defined and mailbox.smtpConfiguration.code is not empty ? mailbox.smtpConfiguration.code : '' }}",
							host: "{{ mailbox.smtpConfiguration.host is defined and mailbox.smtpConfiguration.host is not empty ? mailbox.smtpConfiguration.host : '' }}",
							username: "{{ mailbox.smtpConfiguration.username is defined and mailbox.smtpConfiguration.username is not empty ? mailbox.smtpConfiguration.username : '' }}",
						}
					})
				});
            {% else %}
                new MailboxConfigurationView({
                    el: $("#mailbox-settings-view"),
                    model: new MailboxConfigurationModel({ incoming: { transport: '' }, outgoing: { transport: '' } })
                });
            {% endif %}
		});
	</script>
{% endblock %}
