App.EmailChrome = Backbone.View.extend({

	messagePane:null,
	messageList:null,
	emailPager:null,
	buttonBar  :null,
	verticalBar:null,
	accountsMenu:null,
	pgrTmpl: _.template( $('#mail-list-pager-template').html() ),
	accountMenuTemplate:_.template( $('#main-account-dropdown-template').html() ),
	draggableOptions: {
		cursor:"move",
		helper:function(e){
			var msgCount  = ($('.email-selection-checkbox:checked').length || 1),
				container = $('<div class="draggable-helper"></div>');
				countSpan = $('<span>'+msgCount+'</span>');
				// console.log( countSpan.html() )
				return container.append(countSpan);
		},
		stop: function(event, ui){
			
		},

		disabled:false,
		cursorAt: { top: 5, left: 5 },
		appendTo:"#email-pane"
	},
	
	initialize: function(){
		_.bindAll(this,'render','sendMail','expandMessagePane','showFolderMail',
			'contractMessagePane','closeMessagePane','onMessageSelect',
			'setFolder','saveDraft', 'createDraft', 'reply', 
			'getNextPage','getPrevPage', 'changeAccounts');
	},

	events: {
		'click #mark-mail-read' : 'markMailRead',
		'click #mark-mail-unread' : "markMailUnread",
		'click #mark-mail-flagged' : 'markMailToggleFlag',
		'click #mark-mail-spam' : 'markMailSpam',
		'click #more-mail-move' : 'showMoveMailDialog',
		'click #compose-mail-button' : 'composeNewMail',
		'click #reply-mail-button' : 'reply',
		'click #send-mail-button' : 'sendMail',
		'click #compose-tab-buttons' : 'showComposePane',
		'click #adv-search-submit' : 'searchMailAdvanced',
		'click #reg-search-submit' : 'searchMail',
		'click #delete-mail-button' : 'deleteMail',
		'click #save-draft-mail-button' : 'saveDraft',
		'click #attach-mail-button' : 'attachFiles',
		'click #reply-all-mail-button' : 'reply',
		'click #forward-mail-button' : 'reply',
		'click .message-display-more-mail-print' : 'printEmail',
		'click .mail-page-less' : 'getPrevPage',
		'click .mail-page-more' : 'getNextPage',
		'change #mail-list-pager-selection': 'jumpToPage',
		'click #attach-mail-button' : 'showAddAttachmentDialog',
		'click #read-receipt-mail-button' : 'setReadReceipt'
	},


	render: function(){

		this.verticalBar = new App.Views.ImapFolders({
			el: $('#email-pane #imap-folder-container'),
			collection: App.imapFolders
		}).render();
		
		this.verticalBar
			.bind('folder-select',this.showFolderMail)
			.bind('render',this.setPager);

		// this.listenTo(this.verticalBar, 'folder-select', this.showFolderMail);

		this.accountsMenu = new App.Views.AccountsMenu({
			el: $('#email-pane .top-level-menus'),
			collection: App.accounts
		}).render();

		if (App.email.getCurrentAcct() == -1)
		{
			this.$el.find('#email-account-dropdown-button').html('Show All Accounts');
		}
		else
		{
			this.$el.find('#email-account-dropdown-button').html(App.accounts.getActiveAccount().get('accountName'));
		}

		this.buttonBar = new App.Views.EmailButtonBar({
			el: $('#email-pane .button-bar')
		}).render();

		this.buttonBar.setStateInit();

		this.listenTo(this.buttonBar, 'get-mail', this.getNewMail);
		this.listenTo(this.buttonBar, 'get-to-help', this.goToHelpFiles);
		this.listenTo(this.buttonBar, 'mark-email-read', this.markEmailAsRead);	


		this.messageList = new App.Views.MessageList({
			el: $('#message-list'),
			collection:App.email
		}).render();

		this.listenTo(this.messageList, 'create-draft', this.createDraft);

		this.bindDraggable();

		this.messagePane = new App.Views.MessagePane({
			el: $('#message-pane')
		});

		App.envelopes = new App.Collections.Envelopes();

		this.composePane = new App.Views.ComposePane({
			el: $('#compose-pane'),
			collection: App.envelopes
		});

		
		this.composePane.$el.hide();
		this.composePane
			.bind('close-compose-pane',this.setFolder);

		this.messageList
			.bind('message-select', this.onMessageSelect)
			.bind('select-none', this.buttonBar.setStateInit)
			.bind('select-multiple', this.buttonBar.setStateMulti)
			.bind('select-single', this.buttonBar.setStateSingle)
			// .bind('render',this.bindDraggable);

		this.messagePane
			.bind('auto-resize-expand',this.expandMessagePane)
			.bind('auto-resize-contract',this.contractMessagePane)
			.bind('close',this.closeMessagePane);

		this.accountsMenu
			.bind('change-account-button-press', this.changeAccounts);

		return this;
	},

	setReadReceipt : function(e){
		var env,msg;

		env = this.composePane.getActiveEnvelope();
		env.toggleReadReceipt();

		if(env.readReceipt()){
			msg = 'A read receipt will be requested.';
		} else {
			msg = 'The read receipt request has been removed.';
		}

		App.alert(msg,'alert-info');

	},

	showAddAttachmentDialog : function(e){
		this.composePane.showAddAttachmentDialog(e);
	},

	getPrevPage : function(e){
		// console.log('getPrevPage...');
		if(App.email.currentPage > 1 ){
			App.email.decrementPage();
			this.verticalBar.$el.find('.imap-folder-button.active').click();
		}
	},

	getNextPage : function(e){
		App.email.incrementPage();
		this.verticalBar.$el.find('.imap-folder-button.active').click();
	},

	jumpToPage: function(e){
		var page = $(e.target).val();
		App.email.setCurrentPage( page );
		this.verticalBar.$el.find('.imap-folder-button.active').click();
	},

	changeAccounts: function(e){
		var id = e.target.id;
		var name = e.target.innerText;
		var cid = $(e.target).data('accountId');

		App.email.setCurrentFolder("inbox");

		if(undefined != cid) {
			var id = (cid <= 0) ? cid : App.accounts.get(cid).get('id');
			App.email.setCurrentAcct(id);
			App.imapFolders.setCurrentAcct(id);
			App.accounts.setActiveAccount(id);
		}

		$('#message-list').empty().append('<span class="ajax-loader"></span>');
		$('#message-display-pane').empty();

		if (id == 0)
		{
			this.$el.find('#email-account-dropdown-button').html('Charter');
		}
		else if (id == -1)
		{
			this.$el.find('#email-account-dropdown-button').html('Show All Accounts');
		}
		else
		{
			this.$el.find('#email-account-dropdown-button').html(App.accounts.getActiveAccount().get('accountName'));
		}

		this.accountsMenu.render();

		App.email.setSearch('false');
		App.email.reset();
		App.email.fetch();
		App.imapFolders.reset();
		App.imapFolders.fetch();

		this.$el.find('#search-term').empty();

		$('#email-account-dropdown-menu.dropdown-menu').chtrmenu({
			blur: function(e, ui){ 
				App.blurTimer = setTimeout(function(){
					$('.dropdown-menu-button').removeClass('active');
					$('.dropdown-menu').hide();
				},App.blurTimerAbandoned)
			},
			focus: function(e,ui){
				clearTimeout(App.blurTimer);
			}
		});
	},

	sendMail: function(e){
		var env;

		env = this.composePane.getActiveEnvelope();
		// very important to set this, otherwise
		// this will be simply saved as a draft!
		env.set('isDraft',false);
		env.prepare();

		if( (env.get('emailBodyHtml').length === 0) && (env.get('emailSubject')==='Untitled Message') ){
			App.alert("Cannot send empty email, please specify a subject and message.");
			return;
		}

		if( env.get('emailTo').length === 0 ){
			App.alert("Please specify a recipient");
		 	return;
		}

		env.save();

		env.destroy();
		this.setFolder();
	},

	/*
	sendMail: function(e){
		var to,subject,cc,bcc,body,folder;

		to = '';
		subject='';
		cc='';
		bcc='';
		body='';
		folder='';
		
		//send email
		folder = document.getElementById("current-folder").innerHTML;
		
		//get values
		var formid = document.getElementById('current-form-cid').innerHTML,
		to = document.getElementById('compose-envelope-recipients-'+formid).value,
		subject = document.getElementById('compose-envelope-subject-'+formid).value;
		if( document.getElementById('compose-envelope-cc-'+formid)!== null){
			cc = document.getElementById('compose-envelope-cc-'+formid).value;
			
		}
		if( document.getElementById('compose-envelope-bcc-'+formid) !== null){
					bcc = document.getElementById('compose-envelope-bcc-'+formid).value;
		}

		body = $(".cke_wysiwyg_frame").contents().find("body").html();
		
		if(to == ''){
			App.alert('You must include a primary recipient in the "to" field')
			return;
		}
		
		var finalTo = '';
		if (to.indexOf(",")  != -1){
			var res = to.split(","); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
			//	console.log (res[i]);
				if(emailValidator(res[i], 'to') ==false){
					return;
				}
				finalTo = finalTo+','+res[i];
			}
			
		}
		else if (to.indexOf(";")  != -1){
			var res = to.split(";"); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
				//console.log (res[i]);
				if(emailValidator(res[i], 'to') ==false){
					return;
				}
				finalTo = finalTo+','+res[i];
			}
			
		}
		else{
			to = cleanUpEmail(to);
			
				if(emailValidator(to, 'to') ==false){
					return;
				}
			finalTo = finalTo+','+to;
		}
		
		var finalCC = '';
		if (cc.indexOf(",")  != -1){
			var res = cc.split(","); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
			//	console.log (res[i]);
				if(emailValidator(res[i], 'cc') ==false){
					return;
				}
				finalCC = finalCC+','+res[i];
			}
			
		}
		else if (cc.indexOf(";")  != -1){
			var res = cc.split(";"); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
				//console.log (res[i]);
				if(emailValidator(res[i], 'cc') ==false){
					return;
				}
				finalCC = finalCC+','+res[i];
			}
			
		}
		else{
			cc = cleanUpEmail(cc);
			
				if(emailValidator(cc, 'cc') ==false){
					return;
				}
			finalCC = finalCC+','+cc;
		}
		
		var finalBCC = '';
		if (bcc.indexOf(",")  != -1){
			var res = bcc.split(","); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
			//	console.log (res[i]);
				if(emailValidator(res[i], 'bcc') ==false){
					return;
				}
				finalBCC = finalBCC+','+res[i];
			}
			
		}
		else if (bcc.indexOf(";")  != -1){
			var res = bcc.split(";"); 
			
			for (var i=0; i<res.length; i++ ){
				res[i] = cleanUpEmail(res[i]);
				//console.log (res[i]);
				if(emailValidator(res[i], 'bcc') ==false){
					return;
				}
				finalBCC = finalBCC+','+res[i];
			}
			
		}
		else{
			bcc = cleanUpEmail(bcc);
			
				if(emailValidator(bcc, 'bcc') ==false){
					return;
				}
			finalBCC = finalBCC+','+bcc;
		}
		
		function emailValidator(email, type){
		    var emailvalid = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	
			if (email ==''){
				return true;
			}
		    else if(email.match(emailvalid))
		    {
		    	return true;
		    }else{
 			   alert('Please enter a valid email for the '+type+' field.');
		        return false;
		    }
		}

		function cleanUpEmail(email) {
			email = email.trim();	
			if (email.indexOf("(") != -1){
				email = email.replace("(",""); 			
			}
			if (email.indexOf(")") != -1){
				email = email.replace(")",""); 
			
			}
			if (email.indexOf(";") != -1){
				email = email.replace(";",""); 
			
			}
			if (email.indexOf(",") != -1){
				email = email.replace(",",""); 
			
			}						
			email = email.trim();	
			return email;
			
		}
		
			
		
		//console.log(to );
		//console.log(from );
		//console.log(subject );
		//console.log(cc );
		//console.log(bcc );
		//console.log(body );
		
		App.envelopes.setBcc(finalBCC);
		App.envelopes.setBodyText(body);
		App.envelopes.setCc(finalCC);
		App.envelopes.setSubject(subject);
		App.envelopes.setEmailTo(finalTo);
		App.envelopes.fetch();
		
		finalBCC = '';
		finalCC='';
		finalTo='';
		subject='';
		body='';
		
		var num  = this.composePane.$el.find('#compose-tab-buttons li').length,
			idx  = this.composePane.tabs.tabs("option","active"),
			tab, btn;

		if(num > 1){
			tab = this.composePane.$el.find('#compose-tab-buttons li')[idx];
			btn = $(tab).find('.tab-close-ctrl').click();
			//console.log(tab);
		} else {
			this.closeMessagePane();
			this.composePane.$el.hide();
			this.messageList.$el.show();
			this.buttonBar.setState('initial');
			console.log(App.envelopes);
			App.envelopes.pop();
			console.log(App.envelopes);
		}

		
		App.alert("Your message has been sent.");
	},
	
	*/

	setFolder: function(e){
		var top,reveal;
		
		this.closeMessagePane();
		reveal = this._revealComposeTabs();
		top = reveal? '48px':'0';

		this.messageList.triggerListState();
		this.messageList.$el.show().css('top',top);
		this.messagePane.$el.show().css('top',top);

		if(this.composePane.tabs){
		this.composePane.tabs.tabs('option','disabled',reveal);
		}

		if(!reveal){
			this.composePane.$el.hide();
		}
	},

	composeNewMail: function(){

		var env = new App.Models.Envelope({isNew:true}),
			hasBlank = false,
			focusCid;

		App.envelopes.each(function(e){

			if(_.isEqual(e.attributes,env.attributes)){
				hasBlank = true;
				focusCid = e.cid;
			}
		});

		if(hasBlank===false){
			var activeAccount = App.accounts.getActiveAccount();
			var signature = activeAccount.get('signature');
			env.set('body',  "<br /><br />" + signature);
			env = App.envelopes.add(env);
			focusCid = env.cid;
		} 

		this.showComposePane(env);
		this.composePane.$el.find('#compose-envelope-recipients-'+focusCid).focus();
	   	document.getElementById(focusCid).className = '';
	   	document.getElementById('current-form-cid').innerHTML = focusCid;
	},
	
	
	/*
	createDraft: function(e, msg){
		body='';
		bcc ='';
		to  ='';
		cc ='';
		subject  ='';
		from_email  ='';

		var env = new App.Models.Envelope({isNew:true}),
			hasBlank = false,
			focusCid;
		var idSplit = msg.id.split(":"); 
				var id = idSplit[1];
			//	console.log(id);
		//console.log();
		var message = new App.Models.Message( { UID: id } );
	//	message.fetch();
		//body = message.attributes[0].bodyPreparedHtml;
		 message.fetch({
		  success: function (collection, response) {
		  	//console.log(response);

		 	 bcc = response[0].Bcc;
		 	 body = response[0].bodyPreparedHtml;
		 	 cc = response[0].headers.cc;
		 	 to = response[0].headers.to;
		 	 subject = response[0].headers.subject;
		 	 from_email = response[0].headers.from; 
		 	
		 		if(  typeof body !== 'undefined'){
		 			 body = '<p></p><hr><p></p><p></p><p></p>'+body;
		 	 		$(".cke_wysiwyg_frame").contents().find("body").html(body);
		 	 	}
		 	 	
		 		if(  typeof bcc !== 'undefined'){
		 			if( document.getElementById('compose-envelope-bcc-'+focusCid)!== null){
				 	 	document.getElementById('compose-envelope-bcc-'+focusCid).value =bcc;
				 	 }
   	
				}
		 		if(  typeof to !== 'undefined'){
		 			toFinal ='';
		 			if (to.indexOf(',') >= 0){
						toItem = to.split(',');
						for(var i =0; i<toItem.length;i++){
							if( toItem[i].indexOf('<') >= 0){
				 			  	var toSplit = toItem[i].split("<");
		
							  	var toSplit2 = toSplit[1].split(">");
							  	var toFormated = toSplit2[0];
							  	 toFinal = toFinal +', '+toFormated;
						  	}
						}
						toFinal = toFinal.substring(1);
					}
					else{
						toFinal = to;
						if( toFinal.indexOf('<') >= 0){
			 			  	var toFinalSplit = toFinal.split("<");
	
						  	var toFinalSplit2 =toFinalSplit[1].split(">");
						  	var toFormated = toFinalSplit2[0];
						  	toFinal = toFormated;
					  	}
					}
					
					toFinal = toFinal.trim();
					 	document.getElementById('compose-envelope-recipients-'+focusCid).value = toFinal;
   	
				}		
		 		if(  typeof cc !== 'undefined'){
		 				if( document.getElementById('compose-envelope-cc-'+focusCid)!== null){
		 					
		 				ccFinal ='';
			 			if (cc.indexOf(',') >= 0){
							ccItem = cc.split(',');
							for(var i =0; i<ccItem.length;i++){
								if( ccItem[i].indexOf('<') >= 0){
					 			  	var ccSplit = ccItem[i].split("<");
			
								  	var ccSplit2 = ccSplit[1].split(">");
								  	var ccFormated = ccSplit2[0];
								  	 ccFinal = ccFinal +', '+ccFormated;
							  	}
								
							}
							ccFinal = ccFinal.substring(1);
						}
						else{
							ccFinal = cc;
							if( ccFinal.indexOf('<') >= 0){
				 			  	var ccFinalSplit = ccFinal.split("<");
		
							  	var ccFinalSplit2 =ccFinalSplit[1].split(">");
							  	var ccFormated = ccFinalSplit2[0];
							  	ccFinal = ccFormated;
						  	}
						}
						
						ccFinal = ccFinal.trim();
						document.getElementById('compose-envelope-cc-'+focusCid).value = ccFinal;
					}
   	
				}
		 		if(  typeof subject !== 'undefined'){
				 		document.getElementById('compose-envelope-subject-'+focusCid).value = subject;
				 		$('a[href="#compose-mail-envelope-'+focusCid+'"]').text(subject);
   	
				}				

	   			if(  typeof from_email !== 'undefined'){
					document.getElementById('compose-envelope-account-'+focusCid).value = from_email;	
   	
				}	
	   		
		    }
		});
		
		App.envelopes.each(function(e){

			if(_.isEqual(e.attributes,env.attributes)){
				hasBlank = true;
				focusCid = e.cid;
			}
		});

		if(hasBlank===false){
			env = App.envelopes.add(env);
			focusCid = env.cid;
		} 
		
		this.showComposePane(env);
		this.composePane.$el.find('#compose-envelope-recipients-'+focusCid).focus();
	 
	 	document.getElementById(focusCid).className = msg.id;
	   	document.getElementById('current-form-cid').innerHTML = focusCid;
		   
	 
	   
	},
*/

	showComposePane: function(envelope){
		var env, cid;

		cid ='';
		env = envelope || new App.Models.Envelope();

		// There is no target property in an envelope,
		// are we checking to see if this is an event?
		// is this hold over from CKEditor???
		if(env.target){
			cidHREF = env.target.attributes[0].nodeValue;
			cid = cidHREF;
		}
		else{
			cid = env.cid;
		}
		
		if(cid.indexOf("compose" != -1)){
			cid = cid.replace("#compose-mail-envelope-",""); 
		}

		this.buttonBar.setStateCompose();
		this.messageList.$el.hide();
		this.messagePane.$el.hide();
		if(this.composePane.tabs && this.composePane.tabs.tabs('option','disabled')){
		this.composePane.tabs.tabs('option','disabled',false);
		}
		this.composePane.$el.show();
		//this.composePane.$el.find('a[href="#compose-mail-envelope-'+cid+'"]').click();
				
		//console.log(cid);
		// 
		// DO NOT USE
		// this is not necessary, please use this.composePane.getActiveEnvelope()
		// to retrieve the envelope object and it's property enevelope.cid
		// document.getElementById('current-form-cid').innerHTML = cid;
	},

	reply: function(e){
		var msgid,msg,message,reply,all,env,view,$btn;

		view = this;
		msgid = $('.email-selection-checkbox:checked:first').val();
		msg   = App.email.get(msgid);
		message = App.messages.get(msg.get('UID'));
		$btn  = (e.target.tagName.toLowerCase()==='li')? $(e.target) : $(e.target).parent();
		reply = $btn.prop('id').indexOf('reply-') === 0;
		all   = $btn.prop('id').indexOf('reply-all') === 0;

		if(_.isUndefined( message) ){
			
			message = new App.Models.Message({UID:msg.get('UID'),acct:msg.get('acct')});
			message
				.fetch()
				.always(function(model,textStatus,xhr){
					if(model.fail){
						App.alert(model.fail);
					} else {
						App.messages.add(message);
						message.set('0',model[0]);
						env = view._createEnvelopeFromMsg(message,reply,all);
						view.showComposePane(env);
		 	 	}
				});
		} else {
			env = this._createEnvelopeFromMsg(msg,reply,all);
			view.showComposePane(env);
					  	}
						
		/*
		App.envelopes.each(function(e){

			if(_.isEqual(e.attributes,env.attributes)){
				hasBlank = true;
				focusCid = e.cid;
			}
		});

		if(hasBlank===false){
			env = App.envelopes.add(env);
			focusCid = env.cid;
		} 
		
		this.showComposePane(env);
		this.composePane.$el.find('#compose-envelope-recipients-'+focusCid).focus();
	 	document.getElementById(focusCid).className = msg.id;
	   	document.getElementById('current-form-cid').innerHTML = focusCid;
	  	*/
	},
	
	_createEnvelopeFromMsg: function(msg,isReply,all){
		var hdrs,env,pfx,subject,acct,acctEmail,body,addrUnion;

		console.log(msg);
	
		pfx     = isReply? 'Re: ' : 'Fwd: ';
		env     = new App.Models.Envelope();
		hdrs    = msg.get('0')['headers'];
		acct    = App.accounts.get(msg.get('acct'));
		signature = acct.get('signature');

		body    = '<br /><br />' + signature + '<br /><p>--------</p><blockquote>' + msg.get('0')['bodyPreparedHtml'] + '</blockquote>';
		acctEmail = acct ? acct.get('accountEmail') : App.primaryEmail;

		if(isReply){
			subject = /^\s*RE:/i.test(hdrs.subject)? hdrs.subject : pfx+hdrs.subject;
			if(all){
				addrUnion = _.union(
					msg.emailStrToList('reply-to'),
					msg.emailStrToList('to'),
					msg.emailStrToList('cc'),
					msg.emailStrToList('bcc')				
				);

				_.each(addrUnion, function(addr,i){
					var adro = new App.Models.EmailAddress({address:addr});
					if(adro.validate() && adro.get('recipientAddress') != acctEmail){
						env.setRecipient('to',adro);
					}
				});
			} else {
				var adro = new App.Models.EmailAddress({address:hdrs['reply-to']});
				if(adro.validate()){
					env.setRecipient('to',adro);
				}
			}
		} else {
			subject = /^\s*FWD?:/i.test(hdrs.subject)? hdrs.subject : pfx+hdrs.subject;
		}
	   	
		env.set('body', body);
		env.set('emailSubject',subject);
		env.set('acct', acct);
		return App.envelopes.add(env);
	},
	
	createDraft: function(e,email){
		var hdrs,msg,env,to,cc,bcc,subject,body,reciept,draftUID;

		msg = App.messages.get(email.id) || 
				new App.Models.Message({UID: email.get('UID'), acct: email.get('acct')});

		// Because this can take a while...
		this.messageList.$el.empty().append('<span class="ajax-loader"></span>');

		msg.fetch().done(function(data){
			var env,to,cc,bcc,hdrs;
			
			env  = new App.Models.Envelope();
			to   = msg.emailStrToList('to');
			cc   = msg.emailStrToList('cc');
			bcc  = msg.emailStrToList('x-atmail-bcc');
			hdrs = msg.get('0')['headers'];
			atcm = {};

			_.each(to,function(addr,i){
				var adro = new App.Models.EmailAddress({address:addr});
				if(adro.validate()){
					env.setRecipient('to',adro);
				}
			});

			_.each(cc,function(addr,i){
				var adro = new App.Models.EmailAddress({address:addr});
				if(adro.validate()){
					env.setRecipient('cc',adro);
				}
			});

			_.each(bcc,function(addr,i){
				var adro = new App.Models.EmailAddress({address:addr});
				if(adro.validate()){
					env.setRecipient('bcc',adro);
				}
			});
			
			env.set('emailSubject', hdrs.subject );
			env.set('body', msg.get('0')['bodyPreparedHtml'] );
			env.set('isDraft', true);
			env.set('relatedDraftUID', msg.get('0')['UID'] );
			msg.get('0')['attachmentsList'].forEach(function(atch,i){
				atcm[atch['filenameFS']] = {
					filenameFS: atch['filenameFS'],
					filenameOriginal: atch['filenameOriginal'],
					fileTypeName: atch['fileTypeName'],
					mimeType: atch['mimeType'],
					sizeRaw: atch['sizeRaw'],
					iconClass: atch['iconClass']
				}
			});
			env.set('attachments', _.clone(atcm));

			// add attachments here and you should be done
			App.emailChrome.showComposePane( App.envelopes.add(env) );
		});
	},

	/*
	replyall: function(){
		var msgid = $('.email-selection-checkbox:checked:first').val(),
			msg   = App.email.get(msgid);
			
		
		body='';
		to  ='';
		cc ='';
		subject  ='';
		from_email  ='';

		var env = new App.Models.Envelope({isNew:true}),
			hasBlank = false,
			focusCid;
		
	
		//console.log();
		var message = new App.Models.Message( { UID: msg.id } );
		//	message.fetch();

		 message.fetch({
		  success: function (collection, response) {
			//console.log(response);

		 	 body = response[0].bodyPreparedHtml;
		 	 cc = response[0].headers.cc;
		 	 to = response[0].headers.to;
		 	 subject = response[0].headers.subject;
		 	 from_email = response[0].headers.from;
		 	 
		 	  	if(  typeof body !== 'undefined'){
		 			 body = '<p></p><hr><p></p><p></p><p></p>'+body;
		 	 		$(".cke_wysiwyg_frame").contents().find("body").html(body);
		 	 	}
		 	 	

		 		if(  typeof to !== 'undefined'){
		 			toFinal ='';
		 			if (to.indexOf(',') >= 0){
						toItem = to.split(',');
						for(var i =0; i<toItem.length;i++){
							if( toItem[i].indexOf('<') >= 0){
				 			  	var toSplit = toItem[i].split("<");
		
							  	var toSplit2 = toSplit[1].split(">");
							  	var toFormated = toSplit2[0];
							  	 toFinal = toFinal +', '+toFormated;
						  	}
						}
						toFinal = toFinal.substring(1);
					}
					else{
						toFinal = to;
						if( toFinal.indexOf('<') >= 0){
			 			  	var toFinalSplit = toFinal.split("<");
	
						  	var toFinalSplit2 =toFinalSplit[1].split(">");
						  	var toFormated = toFinalSplit2[0];
						  	toFinal = toFormated;
					  	}
					}
					
					toFinal = toFinal.trim();
					
					
					document.getElementById('compose-envelope-recipients-'+focusCid).value = toFinal;
   	
				}	
					
		 		if(typeof cc !== 'undefined'){
		 			
		 			ccFinal ='';
		 			if (cc.indexOf(',') >= 0){
						ccItem = cc.split(',');
						for(var i =0; i<ccItem.length;i++){
							if( ccItem[i].indexOf('<') >= 0){
				 			  	var ccSplit = ccItem[i].split("<");
		
							  	var ccSplit2 = ccSplit[1].split(">");
							  	var ccFormated = ccSplit2[0];
							  	 ccFinal = ccFinal +', '+ccFormated;
						  	}
							
						}
						ccFinal = ccFinal.substring(1);
					}
					else{
						ccFinal = cc;
						if( ccFinal.indexOf('<') >= 0){
			 			  	var ccFinalSplit = ccFinal.split("<");
	
						  	var ccFinalSplit2 =ccFinalSplit[1].split(">");
						  	var ccFormated = ccFinalSplit2[0];
						  	ccFinal = ccFormated;
					  	}
					}
					
					ccFinal = ccFinal.trim();
			
		 				if( document.getElementById('compose-envelope-cc-'+focusCid)!== null){
					 document.getElementById('compose-envelope-cc-'+focusCid).value = ccFinal;
					 }
   	
				}
		 		if(  typeof subject !== 'undefined'){
		 			subject = "RE: "+subject;
				 		document.getElementById('compose-envelope-subject-'+focusCid).value = subject;
				 		$('a[href="#compose-mail-envelope-'+focusCid+'"]').text(subject);
   	
				}				
		 	 
		    }
		});
		
		App.envelopes.each(function(e){

			if(_.isEqual(e.attributes,env.attributes)){
				hasBlank = true;
				focusCid = e.cid;
			}
		});

		if(hasBlank===false){
			env = App.envelopes.add(env);
			focusCid = env.cid;
		} 
		
		this.showComposePane(env);
		this.composePane.$el.find('#compose-envelope-recipients-'+focusCid).focus();
	 
	 	document.getElementById(focusCid).className = msg.id;
	   	document.getElementById('current-form-cid').innerHTML = focusCid;
	
	   	
	},

	forward: function(){
		var msgid = $('.email-selection-checkbox:checked:first').val(),
			msg   = App.email.get(msgid);
			
		
		body='';
		subject  ='';

		var env = new App.Models.Envelope({isNew:true}),
			hasBlank = false,
			focusCid;

		//console.log();
		var message = new App.Models.Message( { UID: msg.id } );
		//	message.fetch();
		//body = message.attributes[0].bodyPreparedHtml;
		 message.fetch({
		  success: function (collection, response) {

		 	 body = response[0].bodyPreparedHtml;
		 	 subject = response[0].headers.subject;
		 	 
		 	  	if(  typeof body !== 'undefined'){
		 			 body = '<p></p><hr><p></p><p></p><p></p>'+body;
		 	 		$(".cke_wysiwyg_frame").contents().find("body").html(body);
		 	 	}
		 	 	
		 		
		 		if(  typeof subject !== 'undefined'){
		 			subject = "RE: "+subject;
				 		document.getElementById('compose-envelope-subject-'+focusCid).value = subject;
				 		$('a[href="#compose-mail-envelope-'+focusCid+'"]').text(subject);
   	
				}				

		    }
		});
		
		App.envelopes.each(function(e){

			if(_.isEqual(e.attributes,env.attributes)){
				hasBlank = true;
				focusCid = e.cid;
			}
		});

		if(hasBlank===false){
			env = App.envelopes.add(env);
			focusCid = env.cid;
		} 
		
		this.showComposePane(env);
		this.composePane.$el.find('#compose-envelope-recipients-'+focusCid).focus();
	 
	 	document.getElementById(focusCid).className = msg.id;
	   	document.getElementById('current-form-cid').innerHTML = focusCid;
	
	   	
	},
	*/

	bindDroppable: function(){
		var view, eCallback, sCallback; 

		view = this;
		eCallback = function(){};
		sCallback = function(){};

		$('.imap-folder-button').droppable({
			drop: function(event,ui){
				var path, msgs, activePath, activeMsgs, cids, ids;
				var acct = App.email.getCurrentAcct();

				path   = $(this).data('folder-path');
				activeMsgs = view.$el.find('.message-item.active');
				msgs   = (activeMsgs.length > 0) ? activeMsgs : $(ui.draggable[0]);
				activePath = $('.imap-folder-button.active').data('folder-path');
				cids = _.pluck( msgs, 'id' );
				ids  = [];

				if(path != activePath){
					_.each(cids,function(id,i){
						var model = App.email.get(id);
						ids.push(acct+':'+model.get('UID'));
					});

					view.moveMail(activePath,path,ids);
				}
						}
					});
	},

	showMoveMailDialog: function(e){
		var view, popup;

		view = this;

		popup = $('#move-mail-dialog').dialog({
			modal:true,
			buttons: {
				move : function(){
					var from, to, cids, msgs, mailIds;
					
					from = $('.imap-folder-button.active').data('folder-path');
					to   = $('#to-folder-selector').val();
					cids = _.pluck( $('.message-item.active'), 'id');
					mailIds = [];

					if(to != from){
						_.each(cids,function(cid,i){
							var model = App.email.get(cid);
							mailIds.push( model.get('UID') );
						});
						view.moveMail(from,to,mailIds);
						$(this).dialog("close");
						$(this).dialog("destroy");
				}
				},
				cancel : function(){
					$(this).dialog("close");
					$(this).dialog("destroy");
				}
			}
		});

		_.each($('.imap-folder-button'), function(btn,i){
			var $opt;
			$opt = $('<option>'+$(btn).data('folder-path')+'</option>');
			popup.find('#to-folder-selector').append( $opt );
		});

		popup.dialog("open");
	},

	moveMail: function(from,to,mailIds){
		var view, url;

		view = this;
		url = App.baseUrl + '/api/mail/movemailtofolder';
				
		$.get(url,{
			fromfolder: from,
			tofolder: to,
			uids: mailIds.join(',')
		}).always(function(response){
			var acct,fid,msg,data,renderFolderList;
			
			renderFolderList = false;
			data = $.parseJSON(response.responseText);

			if(data.error){
				App.alert(data.error);
			} else {
				_.each(data.uids.split(/,/),function(id,i){
					msg  = App.email.get(id);
					if( !msg.isRead() ){
						App.imapFolders.subFromFolderUnread(from,1);
						App.imapFolders.addToFolderUnread(to,1);
						renderFolderList = true;
					}
					App.email.remove(id);
				});
				if(renderFolderList){
					App.emailChrome.verticalBar.render();
				}
				view.messageList.render();
			}
		});
	},

	bindDraggable:function(){
		var draggable = $('.message-item').draggable(this.draggableOptions);
	},

	markMailRead: function(e){
		var msg, id, ids;
		ids = [];

		$('td .email-selection-checkbox:checked').each(function(i,cb){
			id  = $(cb).val();
			msg = App.email.get(id);
			if( !msg.isRead() ){
				msg.setSeen();
				ids.push(id);
			}
			
			$('td .email-selection-checkbox[value="'+id+'"]').click();
		});

		if(ids.length){
			folder = App.email.getCurrentFolder();
		this.messageList.render();

			App.imapFolders.subFromFolderUnread(folder,ids.length);
			this.verticalBar.render();

		App.flag.setCurrentFolder(folder);
		App.flag.setIDs(ids);
		App.flag.setFlag('seen');
		App.flag.fetch();
		//console.log(idsArray);
		}
	},

	markMailUnread: function(e){
		var msg, id, ids;
		ids = [];

		$('td .email-selection-checkbox:checked').each(function(i,cb){
			id  = $(cb).val();
			msg = App.email.get(id);
			
			if(msg.isRead()){
				msg.setUnseen();
			ids.push(id);
			}

			$('td .email-selection-checkbox[value="'+id+'"]').click();
		});

		if(ids.length){
			folder = App.email.getCurrentFolder(); 
		this.messageList.render();

			App.imapFolders.addToFolderUnread(folder,ids.length);
			this.verticalBar.render();
		
		App.flag.setCurrentFolder(folder);
		App.flag.setIDs(ids);
		App.flag.setFlag('unseen');
		App.flag.fetch();
		}
	},

	markMailToggleFlag: function(e){
		// console.log('recieved flagged...');
		var ids = [];
		$('td .email-selection-checkbox:checked').each(function(i,cb){
			var id = $(cb).val(),
			msg = App.email.get(id);

			ids.push(id);

			if(msg.isFlagged()){
				msg.setUnflagged();
				folder = document.getElementById("current-folder").innerHTML;
				App.flag.setCurrentFolder(folder);
				App.flag.setIDs(ids);
				App.flag.setFlag('-flagged');
				App.flag.fetch();
			} else {
				msg.setFlagged();
				folder = document.getElementById("current-folder").innerHTML;
				App.flag.setCurrentFolder(folder);
				App.flag.setIDs(ids);
				App.flag.setFlag('flagged');
				App.flag.fetch();
			}
		});

		this.messageList.render();

		_.each(ids,function(id){
			$('td .email-selection-checkbox[value="'+id+'"]').click();
		});
	},

	markMailSpam: function(e){
		
		var ids = [];
		$('td .email-selection-checkbox:checked').each(function(i,cb){
			var id = $(cb).val();
			
		
			ids.push(id);
		});

		folder = document.getElementById("current-folder").innerHTML;
		App.move.setCurrentFolder(folder);
		App.move.setIDs(ids);
		App.move.setToFolder('Spam');
		App.move.fetch();
		
		$('.email-selection-checkbox:checked').parents('tr').remove();
		
		
	},
	
	deleteMail: function(e){
		
		var r=confirm("Are you sure you want to delete this email?");
		if (r==true)
		  {
		 
		  }
		else
		  {
				return;
		  }
		
		var ids = [];
		$('td .email-selection-checkbox:checked').each(function(i,cb){
			var id = $(cb).val();
			
			ids.push(id);
		});
		
		// folder = document.getElementById("current-folder").innerHTML;
		folder = App.email.getCurrentFolder();
		
		App.move.setCurrentFolder(folder);
		App.move.setIDs(ids);
		App.move.setToFolder('Trash');
		App.move.fetch();
		
		$('.email-selection-checkbox:checked').parents('tr').remove();
		
		
	},

	expandMessagePane: function(){
		this.messageList.close();
		this.messagePane.expand();
	},

	contractMessagePane: function(){
		this.messageList.contract();
		this.messagePane.open();
	},

	closeMessagePane: function(){
		this.messageList.open();
		this.messagePane.close();
	},

	onMessageSelect: function(msgUid, acct){
		var msg,pane;

		msg  = new App.Models.Message( { UID: msgUid, acct: acct } );
		pane = this.$el.find('#message-display-pane').empty();
		
		msg.deferred = msg.fetch();
		App.messages.add( msg );
		
		// folder = document.getElementById("current-folder").innerHTML;
		folder = App.email.getCurrentFolder();
		
		App.flag.setCurrentFolder(folder);
		App.flag.setIDs(acct + ':' + msgUid);
		App.flag.setFlag('seen');
		App.flag.fetch();
		this.messagePane.model = msg;
		this.messagePane.render();
		this.messageList.contract();
		this.messagePane.open();

	},


	showFolderMail: function(e){
		var $btn, path, folder, status;
		
		$btn    = $(e.target),
		path  = $btn.data('folder-path');

		this.setFolder();
		this.messageList.$el.empty().append('<span class="ajax-loader"></span>');
		// this.composePane.$el.empty();
		App.email.setSearch('false');

		// TODO: REMOVE THIS
		// document.getElementById("current-folder").innerHTML = path;

		if(App.email.getCurrentFolder()!==path){
			console.log('showFolderMail(): path: ' + path);
			folder = App.imapFolders.getByGlobalName(path);
			status = folder.get('messageCount');

			// TODO: deal with this.
			if(typeof status !=='undefined'){
				App.folderMsgCount = status.exists;
			} 
			
			App.email.setCurrentPage(1);
		}

		App.email.setCurrentFolder(path);

		// App.email.reset();
		App.email.fetch({reset:true});
		this.$el.find('#search-term').empty();
	},
	
	getNewMail: function(e){
		App.emailChrome.verticalBar.$el.scrollTop(0).find('button').first().click();

		// THE FOLLOWING CODE IS NOT NECESSARY, INCOMPLETE, AND CAUSES ERRORS. 
		// THE SIMULATION OF THE BUTTON CLICK SHOULD BE MORE THAN SUFFICIENT. 
		// IF YOU ARE EXPERIENCING PROBLEMS FIX THE CODE IN THE setFolder METHOD
		// IN THE FILE emailverticalbar.js.
/*
		this.$el.find('#message-list').empty();
		this.$el.find('#message-display-pane').empty();
		App.email.setCurrentFolder("inbox");
		App.email.setSearch('false');
		App.email.reset();
		App.email.fetch();
		//App.emailChrome.messageList.render();
*/		
		this.$el.find('#search-term').empty();
	},
	
	saveDraft: function(e){
		//console.log(this)
		to = '';
		subject='';
		cc='';
		bcc='';
		body='';
		folder='';
		relatedDraftUID = '';
		 
		//send email
		//folder = document.getElementById("current-folder").innerHTML;
		
		//get values
		//avar formid = document.forms[0].id;
		var formid  = e.target.id;
	
	
		var formid = document.getElementById('current-form-cid').innerHTML;
		var stuff = document.getElementById('compose-envelope-recipients-'+formid);
		var env;

		env = this.composePane.getActiveEnvelope();
		env.prepare();
		//console.log(env);
	
		to = env.get('emailTo'),
		subject =env.get('emailSubject'),
		cc =env.get('emailCc'),
		bcc = env.get('emailBcc'),
		body =env.get('emailBodyHtml');
		if(formid){	
			relatedDraftUID =document.getElementById(formid).className;
		}
		var	 now = new Date()
	    .getTime() / 1000,
	   	microTime = parseInt(now, 10),
	   	composeID = 'uid'+microTime;

	   	
		App.draft.setcomposeID(composeID);
		App.draft.setreadReceipt("");
		App.draft.setTo(to);
		App.draft.setCC(cc);
		App.draft.setBCC(bcc);
		App.draft.setSubject(subject);
		App.draft.setBody(body);
		App.draft.setRelatedDraftUID(relatedDraftUID);
		App.draft.setRelatedMessageUIDs("");
		App.draft.setRelatedMessageFolder("");
		App.draft.setAttachmentsFilename("");
		App.draft.setAttachmentsfilenameOriginal("");
		App.draft.setAttachmentsmimeType("");
		App.draft.setAttachmentName("");
		App.draft.setRelatedMessageMessageId("");
		App.draft.setRelatedMessageResponseType("");

		App.draft.fetch({
		  success: function (collection, response) {
			var relatedDraftUIDNew = '';

			if (response.a.evalScript === undefined)
			{
				// From external account
			}
			else
			{
				// From primary account
				var responseInitial = response.a.evalScript[0].foo;
				var res = responseInitial.split("'value',");
				// console.log(res[1]);
				relatedDraftUIDNew = res[1];
				relatedDraftUIDNew = relatedDraftUIDNew.replace("');",""); 
				relatedDraftUIDNew = relatedDraftUIDNew.replace("'","");
				relatedDraftUIDNew = relatedDraftUIDNew.trim();
			}

			console.log(relatedDraftUID);
			document.getElementById(formid).className = relatedDraftUIDNew;
		}
		});
	
		//App.emailChrome.messageList.render();
		App.alert("Your message has been saved to the drafts folder.",'alert-info');
	},
	
	goToHelpFiles: function(e){
		
		window.open("http://mscharter.custhelp.com/ci/fattach/get/43/1394814216/redirect/1/session/L2F2LzEvdGltZS8xMzk1ODQ4ODIwL3NpZC9sSTV1VGNRbA==/filename/Charter%20Email%2020140314v1.pdf");
		
	},
	
	searchMail: function(e){
		this.$el.find('#message-list').empty();
		this.$el.find('#message-display-pane').empty();
		var mainSearch = document.getElementById("email-search-term").value;
		//
		folder  = "Inbox";
		//	console.log(folder);
		App.email.setSearch('true');
		App.email.setSearchTerm(mainSearch);
		App.email.setCurrentFolder(folder);
		App.email.reset();
		App.email.fetch();
		//App.emailChrome.messageList.render();
		document.getElementById("search-term").innerHTML =	mainSearch;
		
	},
	
	searchMailAdvanced: function(e){
		 		this.$el.find('#message-list').empty();
		this.$el.find('#message-display-pane').empty();
		 var fromSearch = document.getElementById("adv-search-from").value,
		 toSearch = document.getElementById("adv-search-to").value,
		 subjectSearch = document.getElementById("adv-search-subject").value,
		 bodySearch = document.getElementById("adv-search-body").value,
		 dateField = document.getElementById("adv-search-date"),
		 date = dateField.options[dateField.selectedIndex].value;

		//console.log(mainSearch);
		
		// console.log(fromSearch);
		// console.log(toSearch);
		// console.log(subjectSearch);
		// console.log(bodySearch);
		// console.log(date);	
		
		folder  = "Inbox";
		//	console.log(folder);
				 
		App.email.setFrom(fromSearch);
		App.email.setTo(toSearch);
		App.email.setSubject(subjectSearch);
		App.email.setBody(bodySearch);
		App.email.setDate(date);		 
		App.email.setSearch('true');
		App.email.setSearchTerm('');
		App.email.setCurrentFolder(folder);
		App.email.reset();
		App.email.fetch();
		//App.emailChrome.messageList.render();
		document.getElementById("search-term").innerHTML =	fromSearch+ ' ' + toSearch+ ' ' + bodySearch + ' ' +subjectSearch;
	
		
		
		
	},
	printEmail: function(e){
		 
	    Popup($('#message-display-pane').html());
	
	    function Popup(data) 
	    {
	        var mywindow = window.open('', 'Print Email', 'height=400,width=600');
	        mywindow.document.write('<html><head><title>Print Email</title>');
	        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
	        mywindow.document.write('</head><body >');
	        mywindow.document.write(data);
	        mywindow.document.write('</body></html>');
	
	        mywindow.print();
	        mywindow.close();
	
	        return true;
	    }
	
	},
	
	attachFiles: function(e){
		var view, upload;
		view = this;

		upload = $('#file-upload-dialog').dialog({
			modal:true,
			buttons: {
				upload: function(){
					var image = new FormData( $('#fileupload')[0] );

					$.ajax({
						url: App.baseUrl + '/inbox/photo',
						data:image,
						contentType: false,
						cache:false,
						processData:false,
						type:'POST'
					}).done(function(data){
						console.log('attachFiles: ' + data);
						view._setUserPhoto(data.filename);
					}).fail(function(jqhxr,status,text){

					})

					$(this).dialog("close");
				},
				cancel: function(){
					$(this).dialog('close');
				}
			}
		});

		upload.dialog("open");
	},

	_revealComposeTabs: function(){
		return ( (this.composePane.getNumberOfTabs() > 0) || !(this.composePane.getFirstTabIsEmpty() === false) );
		//  
	}
})





