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

{% block title %}Mailbox{% endblock %}

{% block pageContent %}
	<div class="uv-inner-section">
		{{ include('@UVDeskCore/Templates/panel-sidebar.html.twig') }}
		<div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
			{% set resources = false %}
			<div class="mailbox-list-view">
				<div class="uv-action-bar">
					<div class="uv-action-bar-col-lt">
						<h1>
							{{ 'Mailbox(es)'|trans }}
						</h1>
					</div>
					<div class="uv-action-bar-col-rt">
						<div class="uv-app-list-action-rt"><a class="uv-btn-action add-mailbox" id="add-mailbox-button" data-target="add-mailbox-form" >{{ 'New Mailbox'|trans }}</a></div>
					</div>
				</div>

				{% if resources %}
					<div class="uv-message-wrapper" id="upgrade-plan-message"  {% if not (resources and resources.mailboxes.showAlert) %} style="display: none;"{% endif %}>
						<p>	{{ resources.mailboxes.alertMessage |  raw }}</p>
						<a href="" class="uv-btn-small">{{ 'Upgrade Plan'|trans }}</a>
					</div>
				{% endif %}

				<div class="uv-app-screen">
					<div id="mailbox-list" class="uv-app-list-channels">
					</div>
				</div>
			</div>
			<div class="mailbox-form">
				<form>
				</form>
			</div>
			<div id="mailbox-added">
			</div>
			<div id="add-mailbox-form" style="display: none;">
				<form id="uv-add-mailbox-form">			
					<!-- .fade-out-white -->
					<div style="width: 500px;max-width: 80%;">
						<!-- .jelly-out -->
						<h2>{{ 'New Mailbox'|trans }}</h2>
						<p>{{ 'You can setup your each support/query email address as a mailbox to receive all mails directly into helpdesk as tickets'|trans }}</p>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'Mailbox Id'|trans }}</label>
							<div class="uv-field-block">
								<input class="uv-field" type="text" name="mailbox_id">
							</div>
						</div>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'Sender Name'|trans }}</label>
							<div class="uv-field-block">
								<input class="uv-field" type="text" name="sender-name">
							</div>
						</div>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'Swiftmailer id (Select from drop down)'|trans }}</label>
							<div class="uv-field-block">
								<select name="swiftmailer-id" class="uv-select" type="text" value="">
									<option>Select swiftmailer</option>

									{% for swiftmailer in swiftmailers %}
										<option>{{ swiftmailer }}</option>
									{% endfor %}
								</select>
							</div>
						</div>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'IMAP Host'|trans }}</label>
							<div class="uv-field-block">
								<input class="uv-field" type="text" name="imap['host']" placeholder="{imap.gmail.com:993/imap/ssl}INBOX">
							</div>
						</div>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'IMAP username'|trans }}</label>
							<div class="uv-field-block">
								<input class="uv-field" type="text" name="imap['email']">
							</div>
							<span class="uv-field-info">{{ 'All mails from this email address will be created as tickets'|trans }}</span>
						</div>
						<div class="uv-element-block">
							<label class="uv-field-label">{{ 'IMAP Password'|trans }}</label>
							<div class="uv-field-block">
								<input class="uv-field" type="password" name="imap['password']">
							</div>
						</div>
						<div class="uv-pop-up-actions">
							<button type="submit" class="uv-btn save-mailbox">{{ 'Proceed'|trans }}</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div id="confirm-existing-user" class="uv-pop-up-overlay" style="display: none">
			<div class="uv-pop-up-box uv-pop-up-slim uv-no-error-success-icon">	
				<span class="uv-pop-up-close"></span>
				<h2>{{ 'Add Mailbox Confirmation'|trans }}</h2>
				<div class="uv-element-block">				
					<p class="uv-field-info">
						{{ "You are trying to use %existing-email% as Mailbox email. There is also a user with email %existing-email%. If you want to add this email as mailbox, then user with email: %existing-email% cannot create ticket via mail." | trans({"%existing-email%": "<b><i class='existing-user-email-span'>" ~ "ipdeer@ipdeer.com"|trans ~ "</i></b>"}) | raw }}
						{#<a href="" target="_blank">{{ 'Read more'|trans }}</a>#}
					</p>
				</div>
				<div class="uv-element-block">
					<div class="uv-action-buttons">
						<div class="uv-btn" id="confirm-existing-user-btn">{{ 'Proceed'|trans }}</div>
						<div class="uv-btn" id="cancel-existing-user-btn">{{ 'change email'|trans }}</div>
					</div>
				</div>
			</div>
		</div>
		</div>
	</div>
{% endblock %}

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

	{# Mailboxes Collection template #}
	<script id="mailbox_list_item_tmp" type="text/template">
		<div class="uv-app-list-brick-lt" title="<%= imap_server.email %>">
			<span class="uv-channel-count">#<%= parseInt(document.getElementsByClassName('uv-app-list-brick').length)+1 %></span>
		</div>
		<div class="uv-app-list-brick-rt">
			{# <a href="{{ path('ticket_list') }}#mailbox/<%= id %>" class="semibold"> #}
			<a href="" class="semibold">
				<p>					
					<%- name %>
				</p>
			</a>
			<p>
				<% if(enabled) { %>
					<span class="uv-app-list-flag-active">{{'verified'|trans }}</span>
				<% } else { %>
					<span class="uv-app-list-flag-inactive">{{ 'unverified'|trans }}</span>
				<% } %>
			</p>
			<div class="uv-app-list-actions">
				<a href class="edit-mailbox">{{ 'Edit'|trans }}</a>
				<a href class="uv-delete delete-mailbox">{{ 'Delete'|trans }}</a>
			</div>
		</div>
	</script>

	{# Mailbox Edit template #}
	<script id="mailbox_form_tmp" type="text/template">
		<h1>
			{{ 'Edit Mailbox'|trans }}
		</h1>
		<!--Form-->
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'Mailbox Id'|trans }}</label>
				<div class="uv-field-block">
					<input name="mailbox_id" id="mailbox_id" class="uv-field" type="text" value="<% if ('undefined' !== typeof(mailbox_id)) print(mailbox_id);  %>" disabled>
				</div>
			</div>
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'Sender Name'|trans }}</label>
				<div class="uv-field-block">
					<input name="sender-name" class="uv-field" type="text" value="<% if ('undefined' !== typeof(name)) print(name);  %>">
				</div>
			</div>
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'Swiftmailer Id'|trans }}</label>
				<div class="uv-field-block">
					<select name="swiftmailer-id" class="uv-select" type="text" value="">
						<option><%- smtp_server.mailer_id !== null ? smtp_server.mailer_id : "Select swiftmailer"  %></option>
						{% for swiftmailer in swiftmailers %}
							<% if (smtp_server.mailer_id !== "{{ swiftmailer }}") { %>
								<option>{{ swiftmailer }}</option>
							<% } %>
						{% endfor %}
					</select>
				</div>
			</div>
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'IMAP Host'|trans }}</label>
				<div class="uv-field-block">
					<input name="imap['host']" class="uv-field" type="text" value="<% if ('undefined' !== typeof(imap_server.host)) print(imap_server.host);  %>" placeholder="{imap.gmail.com:993/imap/ssl}INBOX">
				</div>
			</div>
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'IMAP Email'|trans }}</label>
				<div class="uv-field-block">
					<input name="imap['email']" class="uv-field" type="text" value="<% if ('undefined' !== typeof(imap_server.username)) print(imap_server.username);  %>">
				</div>
				<span class="uv-field-info">{{ 'All mails from this email address will be created as tickets'|trans }}</span>
			</div>
			<div class="uv-element-block">
				<label class="uv-field-label">{{ 'IMAP Password'|trans }}</label>
				<div class="uv-field-block">
					<input name="imap['password']" class="uv-field" type="password" value="<% if ('undefined' !== typeof(imap_server.password)) print(imap_server.password);  %>">
				</div>
			</div>
			<!--CTA-->
				<input type="button" class="uv-btn save-mailbox" value="Save Changes">
			<!--//CTA-->
		<!--Form-->
	</script>

	{# Mailbox Added template #}
	<script id="mailbox_added_tmp" type="text/template">
		<div class="uv-pop-up-overlay">
			<!-- .fade-out-white -->
			<div class="uv-pop-up-box uv-pop-up-slim">
				<!-- .jelly-out -->
				<span class="uv-pop-up-close"></span>
				<h2>Mailbox Created</h2>
				<p><%= "{{ 'Forward %email% to'|trans({'%email%': '<span>%replaceEmail%</span>'})|raw }}".replace('%replaceEmail%', 'sender-mail') %></p>
				<div class="uv-element-block">
					<div class="uv-split-copy">
						<input type="text" class="uv-split-field" readonly value="<% if('undefined' !== typeof(mailboxEmail)) { print(mailboxEmail) } %>">
						<button type="button" class="uv-btn uv-split-btn">{{ 'Copy'|trans }}</button>
					</div>
					<span class="uv-field-info">{{ 'You can easily copy the secret email address by clicking the Copy button.'|trans }}</span>
				</div>
				<div class="uv-pop-up-actions">
					<a href="#" class="uv-btn cancel">{{ 'Got It'|trans }}</a>
				</div>
			</div>
		</div>
	</script>

	{# No Mailbox found screen template #}
	<script type="text/template" id="no-mailbox-template">
        <div class="uv-app-screen">
            <div class="uv-app-splash" style="text-align: center;">
                <img class="uv-app-splash-image" src="{{ asset('bundles/uvdeskcore/images/splash/mailbox.png') }}" alt="Tasks">
                <h2 class="uv-margin-top-10">{{ 'No mailbox Found.'|trans }}</h2>
                <p><a href="https://support.uvdesk.com/en/blog/how-to-create-mailbox" target="_blank">{{ "Need help?"|trans }}</a></p>
            </div>
        </div>	
	</script>

	<script type="text/javascript">
		{# https://blog.aweber.com/email-deliverability/top-10-email-domains-of-2006.html #}
		publicEmailDomains = ['uvdesk.com', 'webkul.com', 'gmail.com', 'zoho.com' , 'yahoo.in', 'yahoo.com', 'yahoo.co.in' , 'yahoo.co.uk', 'yahoo.ca', 'hotmail.com', 'hotmail.co.uk', 'aol.com', 'msn.com', 'rediffmail.com'];
		defaultEmailDomain = 'uvdesk.com';
		publicEmailDomains.push(defaultEmailDomain);
		_.extend(Backbone.Validation.validators, {
		    validateEmailValidator: function(value, attr, customValue, model) {
				if('undefined' == typeof(value) || value.toLowerCase().indexOf('@uvdesk.com') > -1) {
					return '{{ "You can not add UVdesk Email as a mailbox !!"|trans }}';
				}
			},
		});

		var MailboxModel = Backbone.Model.extend({
			idAttribute : "id",
		    validation: {
				"mailbox_id": [
					{
						required: true,
						msg: '{{ "Please enter a mailer id"|trans }}'
					}, {
						pattern: '^[a-zA-Z0-9_-]*$',
						msg: '{{ "Only characters and numbers are allowed"|trans }}'
					}
				],
				"sender-name": [
					{
						required: true,
						msg: '{{ "Please enter a sender name"|trans }}'
					},
				],
				"swiftmailer-id": function (id) {
					if (id == "Select swiftmailer")
						return '{{ "Please select a swiftmailer id"|trans }}';
				},
				"imap['host']": [
					{
						required: true,
						msg: '{{ "Please enter a imap host"|trans }}'
					}, {
						pattern: '^[a-zA-Z:{}.\/0-9]+$',
						msg: '{{ "Please enter a valid imap host"|trans }}'
					}
				],
				"imap['password']": [
					{
						required: true,
						msg: '{{ "Please enter a imap password"|trans }}'
					},
				],
				"imap['email']": [
					{
						required: true,
						msg: '{{ "Please enter an email address"|trans }}'
					},{
						pattern: 'email',
						msg: '{{ "Please enter a valid email"|trans }}'
					},{
						validateEmailValidator: true,
				}],
		    },
		    parse: function (resp) {
			    return resp.mailbox;
			},
			urlRoot : "{{ path('helpdesk_member_mailbox_settings_create_mailbox_xhr') }}"
		});

		var MailboxCollection = Backbone.PageableCollection.extend({
			model : MailboxModel
		});

		var FullView = Backbone.View.extend({
			el: $('body'),
			events: {
				'click #cancel-existing-user-btn': 'cancelExistingUserPrompt',
				'click #confirm-existing-user-btn': 'confirmExistingUserPrompt',
				'click #mailbox-added .uv-pop-up-close,#mailbox-added .cancel': 'showMobAside',
			},
			showMobAside: function(e) {
				$('.uv-mob-aside').show();
			},
			cancelExistingUserPrompt: function(e) {
				$('#confirm-existing-user').hide();
			},
			confirmExistingUserPrompt: function(e) {
				$('#confirm-existing-user').hide();
				continueForm.find('.save-mailbox').before('<input type="hidden" name="confirmed" value="1">');
				setTimeout(function() {
					console.log($('input[name="confirmed"]'));
					$('input[name="confirmed"]').remove();
				},1000);
				continueForm.find('.save-mailbox').trigger('click');
			}
		});

		var MailboxList = Backbone.View.extend({
			el : $(".mailbox-list-view"),
			listEl: $('#mailbox-list'),
			noResultTemplate: _.template($('#no-mailbox-template').html()),
			initialize : function() {
		        this.render();
		    },
			events: {
				'click .add-mailbox': 'addMailboxForm',
			},
	        render : function () {
	        	this.listEl.html('');
	        	if(mailboxCollection.length) {
		            _.each(mailboxCollection.models, function (item) {
		                this.renderMailbox(item);
		            }, this);
		        } else {
					this.listEl.append(this.noResultTemplate())
		        }
	        },
	        renderMailbox : function (item) {
	            var mailboxItem = new MailboxItem({
	                model: item
	            });
	            this.listEl.append(mailboxItem.render().el);
	        },
			addMailboxForm: function(e) {
				e.preventDefault();
				$('.mailbox-list-view').hide();
				addMailboxForm.resetModel();
				$(".mailbox-list-view").hide();
				$('#add-mailbox-form').show();
				$('.uv-aside-back span').attr('onclick', '');
				$('.uv-aside-back span').click(function () {
					$('#add-mailbox-form').hide();
				});
			},
			checkMailboxLimit: function(response) {
				if(typeof(response.allowedToAdd) != 'undefined' && response.allowedToAdd) {
					$('#upgrade-plan-message').hide();
					$('.add-mailbox').show();
				} else {
					$('#upgrade-plan-message').show();
					$('.add-mailbox').hide();					
				}
			}
		});

		var MailboxForm = Backbone.View.extend({
			el: $('.mailbox-form>form'),
			initialize : function() {
		        Backbone.Validation.bind(this);
		    },
		    mailboxFormTemplate : _.template($("#mailbox_form_tmp").html()),
		    events : {
				'click .close-edit': 'showMailboxList',
				'blur input': 'formChanged',
				'click .save-mailbox': 'editMailboxXHR',
		    	'click .send-test-email' : 'sendTestEmailEvent'
		    },
			render: function() {
				this.$el.html('');
				this.$el.html(this.mailboxFormTemplate(this.model.toJSON()));
			},
		    editMailboxXHR: function (e) {
	            e.preventDefault();
		        Backbone.Validation.bind(this);				
	            var currentElement = Backbone.$(e.currentTarget);
				var data = currentElement.closest('form').serializeObject();
				this.model.set(data);
				self = this;
				if (this.model.isValid(true)) {
					app.appView.showLoader();
					currentElement.attr("disabled","disabled");
					this.model.save({}, {
						url : "{{ path('helpdesk_member_mailbox_settings_update_mailbox_xhr') }}?id=" + $('#mailbox_id').val(),
					    success: function (model, response, options) {
							if (response.alertClass !== "error") {
								self.model.attributes = response.mailbox;
								app.appView.hideLoader();
								currentElement.removeAttr("disabled");;
								globalMessageResponse = response;
								app.appView.renderResponseAlert(response);
								mailboxCollection.set(model, {remove: false});
								mailboxForm.showMailboxList();
								mailboxList.render();
								// mailboxList.checkMailboxLimit(response);							
							} else {
								app.appView.hideLoader();
								currentElement.removeAttr("disabled");;
								globalMessageResponse = response;
								app.appView.renderResponseAlert(response);
							}
					    },
					    error: function (model, xhr, options) {
							app.appView.hideLoader();
					    	currentElement.removeAttr("disabled");;
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
							var response = warningResponse;
							if(xhr.responseJSON)
								response = xhr.responseJSON;
							try {
								errors = JSON.parse(response['alertMessage'])
								for (var field in errors) {
									Backbone.Validation.callbacks.invalid(self, field, errors[field], 'input');
								}
							} catch(e) {
								app.appView.renderResponseAlert(response);
								mailboxForm.showMailboxList();							
							}
							mailboxList.checkMailboxLimit(xhr);
							if(response && response.existingUserEmail) {
								if(self.model.get('email')) {
									continueForm = currentElement.closest('form');
									$('.existing-user-email-span').html(self.model.get('email'));
									$('#confirm-existing-user').show();
								}
							}
		                }
					});
				}
	        },
			showMailboxList: function(e) {
				$(".mailbox-list-view").show();
				$('.mailbox-form').hide();
				$('.uv-aside-back span').attr('onclick' ,'history.go(-1);');
			},
			formChanged: function(e) {
				this.model.set(Backbone.$(e.currentTarget).attr('name'), Backbone.$(e.currentTarget).val())
				this.model.isValid([Backbone.$(e.currentTarget).attr('name')])
			},
			setModel(model) {
				this.model = model;
		        Backbone.Validation.bind(this);				
			},
		    sendTestEmailEvent : function(e) {
				e.preventDefault();
	        	this.requestCount = 0;
	        	this.sendTestEmail();
	        },
		    sendTestEmail : function () {
	        	self = this;
	        	$('.send-test-email').attr("disabled","disabled");
	        	self.$el.find('.send-test-email').val('{{ "Sending test mail"|trans }} ...');
				if(!self.$el.find('.send-test-email').next().hasClass('uv-loader')) {
					self.$el.find('.send-test-email').after('<div class="uv-loader sending-mail-loader" style="display: inline-block;margin-left:10px;margin-top:5px;vertical-align:top;"><span></span><span></span><span></span></div>');
				}
								
				var testModel = new MailboxModel({ id: this.model.id });
		        testModel.save({
		        		data : {flag: self.requestCount}
		        	},{
					PATCH: true,
		        	{# url : "{{ path('mailbox_send_test_email_action') }}", #}
		        	success : function (model, response, options) {
	        			if(!model.attributes.isActive) {
	        				self.requestCount++;
	        				if(self.requestCount < 5) {
	        					setTimeout(function() {
								  	self.sendTestEmail();
								}, 10000);
	        				} else {
	        					response['alertMessage'] = "{{ 'Warning! Cannot verifiy that Auto forwarding is enabled for this email. Make sure forwarding is enabled.'|trans }}";
								app.appView.renderResponseAlert(response);
								self.$el.find('.send-test-email').val('{{ "SEND TEST MAIL"|trans }}');
								$('.sending-mail-loader').remove();
	        					$('.send-test-email').removeAttr("disabled");
	        				}
	        			} else {
	        				response['alertMessage'] = "{% trans %}Success ! Auto forwarding is enabled.{% endtrans %}";
							app.appView.renderResponseAlert(response);
							self.$el.find('.send-test-email').val('{{ "SEND TEST MAIL"|trans }}');
							$('.sending-mail-loader').remove();							
	        				$('.send-test-email').removeAttr("disabled");
	        				mailboxCollection.set(model,{remove: false});
	        				mailboxList.render();
	        			}
				    },
				    error: function (model, xhr, options) {
						self.$el.find('.send-test-email').val('{{ "SEND TEST MAIL"|trans }}');
						$('.sending-mail-loader').remove();						
				    	if(url = xhr.getResponseHeader('Location'))
	                		window.location = url;
	                    var response = warningResponse;
				    	if(xhr.responseJSON)
				    		response = xhr.responseJSON;
				    	
						app.appView.renderResponseAlert(response);
	                }
		        });
	        },
		});

		var AddMailboxForm = Backbone.View.extend({
			el: $('#add-mailbox-form'),
		    mailBoxAddedTemplate : _.template($("#mailbox_added_tmp").html()),
			events: {
				'blur input': 'formChanged',
				'click .save-mailbox': 'saveMailbox',
			},
			initialize:  function() {
		        Backbone.Validation.bind(this);				
			},
			formChanged: function(e) {
		        Backbone.Validation.bind(this);				
				this.model.set(Backbone.$(e.currentTarget).attr('name'), Backbone.$(e.currentTarget).val());
				this.model.isValid([Backbone.$(e.currentTarget).attr('name')])
			},
			saveMailbox: function(e) {
	            e.preventDefault();
		        Backbone.Validation.bind(this);				
	            var currentElement = Backbone.$(e.currentTarget);
				var data = currentElement.closest('form').serializeObject();
				this.model.set(data);
				self = this;
				if(this.model.isValid(true)) {
					app.appView.showLoader();
					currentElement.attr("disabled","disabled");
					this.model.save({}, {
					    success: function (model, response, options) {
							if(response.alertClass !== "error") {
								mailboxCollection.add(model);
								currentElement.removeAttr("disabled");
								$("#mailbox-added").html(self.mailBoxAddedTemplate(self.model.toJSON())); //change
								$('.uv-mob-aside').hide();
								$('#add-mailbox-form').hide();
								$('.mailbox-list-view').show();
								mailboxList.render();
								self.resetModel();
								$('#add-mailbox-button').css('display', 'inline-block');
								app.appView.hideLoader();
								globalMessageResponse = response;
								app.appView.renderResponseAlert(response);
								$('#uv-add-mailbox-form').trigger('reset');
							} else {
								currentElement.removeAttr("disabled");
								app.appView.hideLoader();
								globalMessageResponse = response;
								app.appView.renderResponseAlert(response);
							}
					    },
					    error: function (model, xhr, options) {
							app.appView.hideLoader();
					    	currentElement.removeAttr("disabled");;
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
							var response = warningResponse;
							if(xhr.responseJSON)
								response = xhr.responseJSON;
							try {
								errors = JSON.parse(response['alertMessage'])
								for (var field in errors) {
									Backbone.Validation.callbacks.invalid(self, field, errors[field], 'input');
								}
							} catch(e) {
								if(Object.keys(response.alertMessage).length) {
									response.alertMessage = response.alertMessage[Object.keys(response.alertMessage)[0]];
									app.appView.renderResponseAlert(response);
								}
							}
							if(response && response.existingUserEmail) {
								if(self.model.get('email')) {
									continueForm = currentElement.closest('form');
									$('.existing-user-email-span').html(self.model.get('email'));
									$('#confirm-existing-user').show();
								}
							}
							mailboxList.checkMailboxLimit(response);
		                }
					});
				}
				// this.model = new MailboxModel();
			},
			resetModel: function() {
				this.model = new MailboxModel();
			},
		});

		var MailboxItem = Backbone.View.extend({
			tagName : "div",
			className:'uv-app-list-brick',
			template : _.template($("#mailbox_list_item_tmp").html()),
			requestCount : 0,
		    events : {
		    	'click .edit-mailbox' : "editMailbox",
		    	'click .delete-mailbox' : "confirmRemove",
		    },
		    render : function() {
	            this.$el.html(this.template(this.model.toJSON()));
	            return this;
	        },
		    editMailbox : function(e) {
				e.preventDefault();
				mailboxForm.setModel(this.model);
				mailboxForm.render();
				$(".mailbox-list-view").hide();
				$('.mailbox-form').show();
				$('.uv-aside-back span').attr('onclick', '');
		    },
			confirmRemove: function(e) {
				e.preventDefault();
				app.appView.openConfirmModal(this);
			},
			removeItem : function (e) {
				app.appView.showLoader();
		    	self = this;
				$.ajax({
					type: 'DELETE',
					url:"{{ path('helpdesk_member_mailbox_settings_remove_mailbox_xhr') }}?id=" + self.model.attributes.mailbox_id,
					success: function (response) {
						app.appView.renderResponseAlert(JSON.parse(response));
						self.model.destroy({
							success: function (model, response, options) {
								app.appView.hideLoader();
								mailboxList.render();
								mailboxForm.showMailboxList();
								mailboxList.checkMailboxLimit(response);
							},
							error: function (model, xhr, options) {
								app.appView.hideLoader();
								if(url = xhr.getResponseHeader('Location'))
									window.location = url;
								var response = warningResponse;
								if(xhr.responseJSON)
									response = xhr.responseJSON;
								
								app.appView.renderResponseAlert(response);
							}
						});
					},
					error: function (error) {
						console.log("Error:", error);
	                }
				});

		    },
		});

		var fullView = new FullView();
		var mailboxCollection = new MailboxCollection($.parseJSON('{{ mailboxes|raw }}'));
		var mailboxList = new MailboxList();
		
		mailboxForm = new MailboxForm({
	        model : new MailboxModel()
	    });
		addMailboxForm = new AddMailboxForm({
			model : new MailboxModel()
		});
		$('.uv-aside-back').click(function() {
			mailboxForm.showMailboxList();
		});
	</script>
{% endblock %}
