App.Views.Directory = Backbone.View.extend({
	initialize: function(){
		_.bindAll(this,'render','createContact');
	},

	render: function(){
		var $header = this.$('#contacts-list > thead:first-child');
		var $container = this.$('#contacts-list').empty();

		App.contacts.each(function(contact){
			new App.Views.Contact({
				model: contact,
				$container: $container
			}).render();
		});

		$header.insertBefore('#contacts-list > tbody:first-child');
		return this;
	},

	events: {
		'click #add-contact-button': 'addCreateForm',
		'submit #save-contact-button': 'createContact'
	},

	createContact: function(e){
		e.preventDefault();
		var $form = this.$('form.contact-editor'),
			email = [], phone = [], address = [];

		$('.email-control-label').each(function(i,ctrl){
			var attr = {location:'',email:'',primary:false};

			attr.primary  = $('.keyval-select-button',$(ctrl)).hasClass('toggle-state-on');
			attr.location = $('input',$(ctrl)).prop('placeholder');
			attr.email    = $('input').val();

			email.push(attr);
		});

		var newContact = new App.Models.Contact({
			firstName: $('input#first-name',$form),
			lastName: $('input#last-name', $form),
			email: email,
			phone: phone,
			address:address,
			company: $('input#company',$form),
			title: $('input#title',$form),
			url: $('input#url',$form),
			dob: $('input#dob', $form),
			notes: $('textarea#notes',$form)
		});

		if(newContact.isValid()){
			App.Contacts.add(newContact);
		} else {
			alert(newContact.validationError);
		}
	}
});