App.Views.MessagePane = Backbone.View.extend({
	template: _.template( $('#message-pane-template').html() ),

	render: function(){
		
		if(this.model.deferred){
			var view = this;
			this.model.deferred.done(function(){
				view.$el.empty().append( view.template() );
				view.$el.find('#add-contact-dropdown-menu').chtrmenu({posOnClick:true});
				view._ie8ScrollFix();
			});
		} else {
			this.$el.empty().append( view.template() );
			this.$el.find('#add-contact-dropdown-menu').chtrmenu({posOnClick:true});
			this._id8ScrollFix();
		}
		
		return this;
	},

	events : {
		'click .message-display-attachments' : 'getAttachments',
		'click .message-display-more-actions': 'moreActions',
		'click .auto-resize-button-left' : 'triggerExpandMessagePane',
		'click .auto-resize-button-right': 'triggerContractMessagePane',
		'click #message-display-pane-close-button' : 'triggerClose',
		'click .add-contact-from-email-button' : 'addContact'
	},


	_ie8ScrollFix : function(){
		// all major supported browsers have the method addEventListener
		// except IE 8. Test for IE8 to fix broken scrolling in #message-pane
		if( !document.addEventListener ){
			var height;
			height = $('.message-display-body').height() + 200;
			$('.message-display').height(height);
		}
	},

	open: function(){
		this.$el.css('left','268px').show();
		this.$el.find('.auto-resize-button-right')
			.removeClass('auto-resize-button-right')
			.addClass('auto-resize-button-left');
	},

	expand: function(){
		this.$el.css('left','38px');
		this.$el.find('.auto-resize-button-left')
			.removeClass('auto-resize-button-left')
			.addClass('auto-resize-button-right');
	},

	close: function(){
		this.$el.hide();
	},
	
	triggerExpandMessagePane: function(e){ 
		this.trigger('auto-resize-expand'); 
	},

	triggerContractMessagePane: function(e){
		this.trigger('auto-resize-contract');
	},

	triggerClose: function(e){
		this.trigger('close');
	},

	addContact: function(e){
		var addr,text,contact,fname,lname,email;

		$('.dropdown-menu').hide();
		text  = $(e.target).text();
		addr  = new App.Models.EmailAddress({address:text});
		fname = addr.getFirstName();
		lname = addr.getLastName();
		email = addr.get('recipientAddress');

		App.contacts.each(function(c,i){
			if(_.contains(c.getAllEmail(),email)){
				var fname, lname,msg;
				
				fname = c.get('UserFirstName');
				lname = c.get('UserLastName');
				msg   = "Contact "+fname+" "+lname+" already has "+email+" listed as an email address.";
			 	return App.alert(msg);
			}
		});

		App.contacts.create({UserFirstName:fname,UserLastName:lname,UserEmail:email},{wait:true});
	},

	getAttachments: function(e){
		// console.log(e.target.className+' triggered a '+e.type+' event...');
	},

	moreActions: function(e){
		// console.log(e.target.className+' triggered a '+e.type+' event...');
	}
});
