App.Views.ComposePane = Backbone.View.extend({
	notInited: true,
	template: _.template( $('#compose-pane-template').html() ),
	pillTemplate: _.template( $('#recipient-pill-template').html() ),
	tabs:null,
	defaultTabWidth:157,
	_attchDialog: null,
	_editors:{},

	initialize: function(options){
		var view = this;
		_.bindAll(this,'render','showAddAttachmentDialog','observeRecipientInput','removePill','_addAttachmentDetails');
		this.listenTo(this.collection,'add remove',this.render);
	},

	render:function(){
	
		var contacts = _.flatten(App.contacts.map(function(c){ return c.getAllEmailNamed(); })),
			numOfTab = this.collection.length,
			ctrWidth = this.$el.width(),
			view = this;

		this.$el.find('#compose-tabs').remove();
		
		this.$el.append( this.template() );

		// check tab sizes for fitting in container
		if(ctrWidth < (numOfTab*this.defaultTabWidth)){
			var newTabWidth = Math.floor(ctrWidth/numOfTab),
				anchor      = this.$el.find('#compose-tab-buttons li a'),
				anchorWidth = Math.floor( newTabWidth-25 )-1;

			anchor.width( anchorWidth-1 );
			this.$el.find('#compose-tab-buttons li').width( newTabWidth-1 );
		}

		this.$el.find('div.auto-email')
		  // don't navigate away from the field on tab when selecting an item
		  .bind( "keydown", function( event ) {
		    if ( event.keyCode === $.ui.keyCode.TAB &&
		        $( this ).data( "ui-autocomplete" ).menu.active ) {
		      event.preventDefault();
		    }
		  })
		  .autocomplete({
		    minLength: 0,
		    source: function( request, response ) {
		      // delegate back to autocomplete, but extract the last term
		      response( $.ui.autocomplete.filter(
		        contacts, request.term.split( /; / ).pop() ) );
		    },
		    focus: function(event,ui) {
		    // console.log(event);
		      // prevent value inserted on focus
		      return false;
		    },
		    select: function( event, ui ) {
		      /*
		      var terms = this.value.split( /; / );
		      // remove the current input
		      terms.pop();
		      // add the selected item
		      terms.push( ui.item.value );
		      // add placeholder to get the comma-and-space at the end
		      terms.push( "" );
		      this.value = terms.join( "; " );
		      */
		      view.createRecipientPill(event,ui.item.value);
		      return false;
		    },
		    _renderItem: function( ul, item ){
		    	return $('<li>')
		    		.data('value',item.value)
		    		.append( $('<a onfocus="this.style.bgColor=\"red\">').text( item.label ) )
		    		.appendTo( ul );
		    },
		    _resizeMenu: function(){
		    	this.menu.element.outerWidth(350);
		    },
		    open: function(){
		    	view.$el.find('ul.ui-autocomplete').css('width','350px');
		    },

		    appendTo: this.$el
		  });

		this.tabs = this.$el.find('#compose-tabs').tabs();
		
		this.collection.each(function(env,i){
			var ta, tb, ed, frame, noLoad, doc;
			ta = "compose-envelope-body-"+env.cid;
			tb = "wysihtml5-toolbar-"+env.cid;
			ed = view._editors[env.cid] = new wysihtml5.Editor(ta,{toolbar:tb,parserRules:App.wysihtml5ParserRules});
			frame = ed.composer.iframe;
			noLoad = true;
			
			$(frame).load(function(){
				noLoad = false;
				doc    = this.contentDocument? this.contentDocument : this.contentWindow;
				$(doc.body).bind('blur',function(){
				env.set( 'emailBodyHtml', view.$el.find('#'+ta).val() );
				});
			});
			
			// noLoad fail means the iframe object does not have an onload event
			// (Chrome), and therefore we can simply set the blur event directly
			// on the body
			if(noLoad){
				$(frame.contentDocument.body).bind('blur',function(){
					env.set( 'emailBodyHtml', view.$el.find('#'+ta).val() );
				});                             
			}
		});

		$('#from-account-dropdown-menu').chtrmenu().chtrmenu('option','left','87px');
		
		return this;
	},

	events: {
		'click .tab-close-ctrl' : 'removeTab',
		'blur .evenlope-attr' : 'updateEnvelope',
		'click label.attachment-btn' : 'showAddAttachmentDialog',
		'keydown .attr-pill-maker' : 'preventDefault',
		'keyup .attr-pill-maker' : 'observeRecipientInput',
		'click i.icon-x_circle_fill' : 'removePill',
		'click #from-account-dropdown-menu li a' : 'setEnvelopeFrom',
		'click div.auto-email' : 'showContactsMenu'
	},

	showContactsMenu:function(e){
		/*
		var evt, $btn;
		$btn = $(e.target);
		evt = jQuery.Event('keyup');
		evt.which = 40;
		
		$btn.trigger(evt);
		*/

		if( $(e.target).data('ui-autocomplete') != undefined ){
		$(e.target).autocomplete("search","");
		}
	},

	setEnvelopeFrom : function(e){
		var $item,acct,env,addr;

		$item = $(e.target);
		env   = App.envelopes.get($item.data('envelope-id'));
		acct  = App.accounts.get($item.data('account-id'));
		addr  = new App.Models.EmailAddress({address:acct.get('realName')+' '+acct.get('accountEmail')})
		signature = acct.get('signature');

		cid = env.cid;
		editor = this._editors[cid];
		currHtml = editor.composer.iframe.contentDocument.body.innerHTML;
		editor.composer.iframe.contentDocument.body.innerHTML = signature + "<br /><br /><br />" + currHtml;

		env.set('emailFrom', addr.getFullFormatedAddress());
		this.$el.find('#from-account-dropdown-button').text( $item.text() );
	},
	
	removePill : function(e){
		var $pill, cid;

		$pill = $(e.target).parent();
		cid   = $pill.data('cid');

		if($pill.hasClass('info')){
			env = this.getActiveEnvelope();
			env.removeAddress(cid);
		}

		$pill.remove();
	},

	createRecipientPill : function(e,addressText){
		var $mkr, text, addr, env, field, attr, pill;

		$mkr  = $(e.target);
		field = $mkr.data('name');
		text  = addressText || $mkr.html();

		if(text.length > 0){
			addr  = new App.Models.EmailAddress({address:text});
			attr  = addr? addr.toJSON() : {badAddr:text};
			pill  = this.pillTemplate( {model:addr} );

			$mkr.before( pill );
			$mkr.html('');

			if(addr){
				env  = this.getActiveEnvelope();
				env.setRecipient(field,addr);
			}
		}

	},

	observeRecipientInput : function(e){
		var key, $mkr, text, addr, env, field, attr, pill;

		key = e.which;
		
		switch(key){
			case App.keyCode.ENTER:
			case App.keyCode.COMMA:
			case App.keyCode.SEMICOLON:
				this.createRecipientPill(e);
				/*
				$mkr  = $(e.target);
				field = $mkr.data('name');
				text  = $mkr.html();
				addr  = new App.Models.EmailAddress({address:text});
				attr  = addr? addr.toJSON() : {badAddr:text};
				pill  = this.pillTemplate( {model:addr} );

				$mkr.before( pill );
				$mkr.html('');

				if(addr){
					env  = this.getActiveEnvelope();
					env.setRecipient(field,addr);
				}
			*/
		}
	},

	preventDefault : function(e){
		var key;

		key = e.which;

		switch(key){
			case App.keyCode.TAB:
				$(e.target).html(' ');
				break;
			case App.keyCode.ENTER:
			case App.keyCode.COMMA:
			case App.keyCode.SEMICOLON:
				e.preventDefault();
				break;
		}
		
	},

	showAddAttachmentDialog: function(e){
		var $btn, cid, view;
		console.log('fired...');

		$btn = $(e.target);
		view = this;

		$('#attachment-upload-dialog').dialog({
			resizeable: false,
			dialogClass: "no-close",
			height: 181,
			modal: true,
			position: {my:'center',at:'center',of:'body'},
			buttons: {
				Attach: function(){

					var form, xhr;

					form = $('#attachment-upload-dialog-form').ajaxSubmit({
						url: App.baseUrl + '/mail/composemessage/addattachment',
						cache:false,
						processData:false,
						type:'POST',
						resetForm:true
					});

					xhr = form.data('jqxhr');

					xhr.done(function(response){
						data = $.parseJSON(response);
						if(data.error){
							App.alert(data.error);
						} else {
							view._addAttachmentDetails(data);
						}
					});
					$(this).dialog('close');
					$(this).dialog('destroy');
				},
				Cancel: function(){
					$(this).dialog('close');
				}
			}
		});
	},

	_addAttachmentDetails:function(data){
		var env;
		env = this.getActiveEnvelope();
		env.setAttachment(data);
		this.$el
			.find('#compose-envelope-attachments-'+env.cid)
			.append(data.filenameOriginal+'&emsp;');
		/*
		var file, fsname, fsorig, mime, form;

		file = data.filenameOriginal.replace(/\W/,'');

		// TODO: all this horribleness will change when 
		//       the code for envelope models gets put
		//       in the correct place
		fsname = "attachments["+file+"][filenameFS]";
		fsorig = "attachments["+file+"][filenameOriginal]";
		mime   = "attachments["+file+"][mimeType]";

		App.envelopes.setAttachmentsQueryString(fsname,data.filenamefs);
		App.envelopes.setAttachmentsQueryString(fsorig,data.filenameOriginal);
		App.envelopes.setAttachmentsQueryString(mime,data.mimeType);

		
		file = data.filenameOriginal.replace(/\W/,'');
		form = this.$el.find('form[id="'+cid+'"]');

		form
			.append( $('<input type="hidden" name="attachments['+file+'][filenameFS]" value="'+data.filenamefs+'"/>'))
			.append( $('<input type="hidden" name="attachments['+file+'][filenameOriginal]" value="'+data.filenameOriginal+'"/>') )
			.append( $('<input type="hidden" name="attachments['+file+'][mimeType]" value="'+data.mimeType+'"/>'))
		console.log(form);
		*/
	},

	removeTab: function(e){

		var $btn = $(e.target),
			pane = $btn.siblings('a').attr('href'),
			num  = this.$el.find('#compose-tab-buttons li').length,
			eid  = pane.match(/\d+$/);
		
		App.envelopes.remove('c'+eid);
		$(pane).remove();
		$btn.closest('li').prev().find('a').click();
		$btn.closest('li').remove();
		if(num == 1){
			// App.envelopes.add(new App.Models.Envelope());
			this.trigger('close-compose-pane',e);
		}
		
	},

	getActiveEnvelope: function(){
		var cid = this.getActiveEnvelopeId();
		return this.collection.get( cid );
	},

	getActiveEnvelopeId: function(){
		var index = this.tabs.tabs("option","active"),
			tab = this.$el.find('#compose-tab-buttons li')[index],
			id = $(tab).find('a:first').prop('href'),
			match = id.match(/c\d+$/);

			if( _.isArray(match) ){
				return match[0];
			}

		return undefined;
	},

	removeActiveEnvelope: function(){
		var cid = this.getActiveEnvelope();
		return this.collection.remove(cid);
	},


	updateEnvelope: function(e){
		var eid, key, env, val

		eid = this.getActiveEnvelopeId();
		key = e.target.name;
		env = this.getActiveEnvelope();
		val = env.get( key );

		// attachments need to be set differently so end
		// processing here
		if(key==="attachments"){
			return;
		}

		if( _.isArray( val ) ){
			// replace commas and split on semi-colons
			var addrs = e.target.value
				.replace(/,/g,';')
				.split(';');

			_.each(addrs,function(addr,i){ addrs[i] = addr.trim(); });

			val = _.compact( addrs );

		} else {
			val = e.target.value;
		}

		console.log('updateEnvelope(): val: ' + val);
		env.set(e.target.name,val);

		if(e.target.name==='subject'){
			$('a[href="#compose-mail-envelope-'+eid+'"]').text(e.target.value);
		}
	},

	getNumberOfTabs: function(){
		return this.$el.find('#compose-tab-buttons li').length;
	},

	getFirstTabIsEmpty: function(){
		var model = App.envelopes.at(0);
		if(model){
			return App.envelopes.at(0).changedAttributes();
		}

		return false;
	}
});
