App.Models.EmailAddress = Backbone.Model.extend({

	defaults: {
		recipientName:'',
		recipientAddress: ''
	},

	initialize: function(attrs, opts){
		var words,address,name;


		if(attrs.address && typeof attrs.address == "string"){
			
			words = attrs.address.trim().split(' ');
			address = words.pop();
			name = words.join(' ');

			if(address.match(/^\<.*\>$/)){
				address = address.substring(1,(address.length-1));
			}

			this.set('recipientAddress',address);
			this.set('recipientName',name.replace(/['"]/g,'')); 
		}
	},

	validate : function(){
		var re,address,addr;

		re = /^(([^<>()[\]\\.,;:\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,}))$/;
		address = this.get('recipientAddress');
		
		if(address.match(re)){
			return true;
		}

		return false;
	}
});

App.Models.EmailAddress.prototype.getFullFormatedAddress = function(){
	var name, addr;

	name = this.get('recipientName');
	addr = this.get('recipientAddress');

	name = name.length? name : addr;
	return '"'+name+'" <'+addr+'>';
};

App.Models.EmailAddress.prototype.getDisplayName = function(){
	if(this.get('recipientName')){
		return this.get('recipientName');
	}

	if(this.get('recipientAddress')){
		return this.get('recipientAddress');
	}

	return this.get('address');
}

App.Models.EmailAddress.prototype.getFirstName = function(){
	var fname,tmpName;

	tmpName = this.get('recipientName');
	if(tmpName){
		if(tmpName.indexOf(',') === -1){
			fname = tmpName.split(' ');
			return _.first(fname, ( (fname.length-1) || fname )).join(' ');
		} else { 
			fname = tmpName.split(',');
			return _.last(_.map(fname,function(name){ return name.trim() }));
		}
	}
}

App.Models.EmailAddress.prototype.getLastName = function(){
	var lname,tmpName;

	tmpName = this.get('recipientName');
	if(tmpName){
		if(tmpName.indexOf(',') === -1){
			lname = tmpName.split(' ');
			return _.last(_.map(lname,function(name){ return name.trim(); }));
		} else {
			lname = tmpName.split(',');
			return _.first(lname);
		}
	}
}
