App.Views.ImapFolders = Backbone.View.extend({
	// This is very upsetting.
	template: _.template( $('#imap-folder-template').html() ),
	
	paddingLeftMin: 28,
	paddingLeftStep: 10,
	events : {
		'click .imap-folder-button':'setFolder',
		'doubleclick .imap-folder-button' : 'changeFolderName',
		'click #add-imap-folder-button':'showNewFolderCtrl',
		'click button.create-imap-folder':'addFolder',
		'click .cancel-folder-create':'cancelNewFolderCtrl',
		'click #remove-imap-folder-button':'removeFolder'
	},

	initialize: function(){
		_.bindAll(this,'render');
		this.collection.on("sync", this.render);
		// this.collection.bind('add remove', this.render );
	},

	render: function(){
		var view = this;
		// console.log('emailverticalbar: model.render() called...');

		this.collection.deferred.done(function(){
			view.$el = $(view.el).empty();
			view.$el.append( view.template( view ) );

			App.emailChrome.bindDroppable();

			var activeAccount = App.accounts.getActiveAccount();
			var activeEmailAccount = App.email.getCurrentAcct();
			if (activeEmailAccount == -1)
			{
				view.$el.find('#imap-folder-button-drafts').hide();
				view.$el.find('#imap-folder-button-sent').hide();
				view.$el.find('#imap-folder-button-spam').hide();
				view.$el.find('#imap-folder-button-trash').hide();
				view.$el.find('#imap-folders-menu').hide();
			}
			else
			{
				view.$el.find('#imap-folder-button-drafts').show();
				view.$el.find('#imap-folder-button-sent').show();
				view.$el.find('#imap-folder-button-spam').show();
				view.$el.find('#imap-folder-button-trash').show();
				view.$el.find('#imap-folders-menu').show();
			}
		});

		return this;
	},

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

		e['selectedFolder'] = path;
		$('.imap-folder-button').removeClass('active');
		$btn.addClass('active');
		
		if( $btn.data('custom-folder') ){
			$('#remove-imap-folder-button').show();
		} else {
			$('#remove-imap-folder-button').hide();
		}

		if($btn.find('span').hasClass('icon-folder_fill')){
			var prefix = path+'/';
			this.collection.each(function(f){
				var path  = f.get('globalName'),
					cPath = path.substr(0,prefix.length);
				
				if(cPath===prefix && path.match(/\//g).length===prefix.match(/\//g).length){
					if( $("[data-folder-path='"+path+"']:visible").length ){
						// console.log("[data-folder-path^='"+f.path+"']");
						$("[data-folder-path^='"+path+"']").hide();
					} else {
						$("[data-folder-path='"+path+"']").show();
					}
				}
			});
		}
		
		this.trigger('folder-select',e);
	},

	showNewFolderCtrl: function(e){
		var $btn  = $('.imap-folder-button.active'),
			$ctrl = $('.new-folder-control').remove(),
			isCustom = $btn.data('custom-folder'),
			fullPath = '', padding;

			if(isCustom){
				padding  = parseInt($btn.css('padding-left'),10) + this.paddingLeftStep;
				$ctrl.css('padding-left',padding+'px').insertAfter( $btn );
				
			} else {
				$ctrl.css('padding-left', $btn.css('padding-left') );
				$(e.target).parents('.folder-list-divider').after($ctrl);
			}

			$('.imap-folder-button').prop('disabled',true).css('opacity','0.5');
			$ctrl.show().find('input').focus();
	},

	addFolder: function(e){
		
		var $btn = $('.imap-folder-button.active'),
			view = this,
			usrInput = $('#imap-folder-name-control').val().replace(/\/|\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,""),
			isCustom = $btn.data('custom-folder'),
			fullPath,makeRootFolder,newFolder;

		// Test here for safe input values
		
		if(usrInput){
			fullPath = isCustom? $btn.data('folder-path') +'/'+ usrInput : usrInput;
			makeRootFolder = isCustom? 0 : 1;
		}
		
		// this.model.addImapFolder({path:fullPath,unread:0});
		newFolder = new App.Models.ImapFolder({localName:usrInput,globalName:fullPath});
		this.collection.add(newFolder);

		newFolder.save({localName:usrInput,globalName:fullPath},{
			success:function(data,response){
				if(data.error){
					view.collection.remove(newFolder);
					view.render();
				}
			}
		});

		$('.new-folder-control').hide();
		
	},

	removeFolder: function(e){
		
		var r=confirm("Are you sure you want to delete this folder?");
		if (r==true)
		  {
		 
		  }
		else
		  {
				return;
		  }
		var $btn  = $('.imap-folder-button.active'),
			model = null,
			fullPath  = $btn.data('folder-path'),
			isCustom  = $btn.data('custom-folder'),
			fnSuccess = function(model,response){

				if(response.statusCode!=204){
					App.imapFolders.add(new App.Models.ImapFolder(model));
					App.emailChrome.verticalBar.render();
				} 
			},
			fnError    = function(model,response){
				App.emailChrome.verticalBar.render();
				console.log(response);
			};
			
			if(isCustom){
				model = this.collection.getByGobalName(fullPath);
				if(model){
					model.destroy({
						success:fnError,
						error:fnSuccess
					});
				} else {
					console.log('model does not exist!')
				}
				console.log('.imap-folder-button[data-folder-path="'+fullPath+'"]');
			}
			this.render();
	},

	cancelNewFolderCtrl: function(e){
		$('.new-folder-control').hide().find('input').val('');
		$('.imap-folder-button').prop('disabled',false).css('opacity',1);
	}

});

