var AddressBook = {
	settings: { 
		containerId: 'addressBookContainer',
		toRecipientEle: 'toList',
		showAddressBook: 'a.showAddressBook',		
		addEmailsClass: '.addAddresses'
	},
	/*
	 * init() - initializes the Address Book, grabs all the elements on the page for the address
	 * 				book and initializes them if they exist on the page
	 */
	init: function() {
		try {
			var showAddressBookEles = $$(AddressBook.settings.showAddressBook);
			showAddressBookEles.each(function(showAddressEle) {
				
				if( $defined( showAddressEle.getAttribute("addressBookEle") ) ) {
          var addressListEle = $( showAddressEle.findParent("addressList") );
					var addressBookEle = $( showAddressEle.getAttribute("addressBookEle") );
					var toRecipientEle = $( showAddressEle.getAttribute("toRecipientEle") );
					var itemCollection = addressBookEle.getElement(UI.settings.collectionClass);
					var addEmailEle = addressBookEle.getElement(AddressBook.settings.addEmailsClass);
				} else {
					var addressBookEle = $(AddressBook.settings.containerId);
					var addressBookCollection = $$(UI.settings.collectionClass)[0];
					var toRecipientEle = $(AddressBook.settings.toRecipientEle);
				}

				if( addressBookEle ) {
					UI.initCloseButton( addressBookEle );
					UI.initSelectAll( addressBookEle );
					
					showAddressEle.href = UI.settings.voidLink;
					showAddressEle.addEvent( 'click', function() {
						UI.initSelectAll( addressBookEle, false );
						UI.fadeInElement( addressBookEle );
					});
				}
				
				if( addressBookEle && itemCollection && addEmailEle && toRecipientEle ) {
					// add behavior to add button
					AddressBook.integrityTest(toRecipientEle,itemCollection);
					addEmailEle.href = UI.settings.voidLink;
					addEmailEle.addEvent( 'click', function() { 
					var checkboxs = $$("#addressBookContent input");
					    if( addressListEle ) {
                var checkboxs = addressListEle.getElements(".addressBookContent input");
					    }
                        var numChecked = 0;
                        checkboxs.each(function(item){
                            if(item.checked) {
                                numChecked++;
                            }
                        });
                        if(numChecked > 0) {
					        $("addressesError").addClass("hidden");
						    UI.fadeOutElement( addressBookEle );
						    /*
						     * parseEmailItem()
						     */
						    var parseEmailItem = function(checkBoxValue) { 
							    var td = this.getElements("td");
							    var obj = { 
								    name: td[1].getText() + " " + td[2].getText(),
								    email: checkBoxValue
							    }
							    return obj;
						    };
						    var selectEmailAddresses = UI.getCheckedItems( itemCollection, 'tr', parseEmailItem );
						    AddressBook.addItem( selectEmailAddresses, toRecipientEle );
						}
						else {
						    $("addressesError").removeClass("hidden");
						}
					});
	
					// remove behavior on prepopulated emails
					var removeEles = toRecipientEle.getElements('a');
					removeEles.each( function(item) {
						//if( item.href != UI.settings.voidLink ) {
						item.href = UI.settings.voidLink;
						item.addEvent('click', function() {
							AddressBook.removeItem( item, toRecipientEle );
						});
						//}
					});
				}

			});
		} catch( e ) {
			debug.log( AddressBook.errorMessages.init(e) );
		}
	},
	/*
	 * addEmail() - takes an email address, adds tries to add it into the hidden input
	 * 					if the email gets added, it returns true, otherwise returns false
	 * @params
	 * 		string email - email address to be added
	 */
	addEmail: function( email, toRecipientInput ) {
		var toArray = toRecipientInput.value.split(";");
		if( toArray.contains( email ) ) {
			return false;
		}
		toArray.push(email);
		toRecipientInput.value = toArray.join(";");
		return true;
	},
	/*
	 * addItem() - takes an array of email objs, and adds them to the UI as well as the
 	 * 					hidden input
 	 * @params
 	 *   	Array objs - array of 'email' objects, email object consists of { name, email }
 	 *   	HTMLDivElement toRecipientEle - the DIV element of the item to add the email addresses 
 	 *   		to, a hidden input and a UL can be placed inside this div to add to
	 */
	addItem: function(objs,toRecipientEle) {
		try {
			var ulElement = toRecipientEle.getElement("ul");
			var inputElement = toRecipientEle.getElement("input[type=hidden]");
			objs.each( function(item) {
				if( AddressBook.addEmail(item.email,inputElement) ) {
					ulElement.adopt( AddressBook.newHTMLItem(item, toRecipientEle) );				
				}
			});
		} catch( e ) {
			debug.log( AddressBook.errorMessages.addEmails(e) );
		}
	},
	errorMessages: {
		init: function( e ){
			return( "[ERROR] AddressBook.init() failed.\nJavascript says it's " + e );
		},
		addEmails: function( e ) {
			return( "[ERROR] AddressBook.addEmails() failed.\nJavascript says it's " + e );
		},
		integrityTest: function() {
			return( '[ERROR] AddressBook.integrityTest() failed. The amount of elements in the <ul> is different than in the hidden input. Perform a hard refresh to fix this problem.' );
		}
	},
	newHTMLItem: function( obj, toRecipientEle ) {
		var removeLink = new Element( "a", {
			'href': UI.settings.voidLink,
			'title': 'remove: ' + obj.name
		}).setText("remove");
		removeLink.addEvent( 'click', function() {
			AddressBook.removeItem( this, toRecipientEle );
		});
		var nameAndEmail = obj.name + " &lt;<span>" + obj.email + "</span>&gt;&nbsp;&nbsp;&nbsp;";
		var newItem = new Element( "li" ).setHTML( nameAndEmail ).adopt( removeLink );
		return newItem;
	},
	removeItem: function(obj, toRecipientEle) {
	    try {
		    var emailItem = obj.parentNode;
		    var emailAddress = emailItem.getElement('span').getText();
		    var toRecipientInput = toRecipientEle.getElement('input[type=hidden]');
		    var toArray = toRecipientInput.value.split(";");
		    toArray.remove( emailAddress );
		    toRecipientInput.value = toArray.join(";");
		    emailItem.remove();
		}catch(e) {}
	},
	integrityTest: function( toRecipientEle ) {
		var inputElement = toRecipientEle.getElement('input[type=hidden]');
		var ulElement = toRecipientEle.getElement('ul');
		if( ulElement && inputElement ) {
			if( inputElement.length != 0 ) {
				var eleCount = ulElement.getElements('li').length;
				var inputCount = inputElement.value.split(";").length;
				if( inputCount != eleCount ){ 
					debug.log( AddressBook.errorMessages.integrityTest() );
				}
			} else if( ulElement.getElements("li").length != 0 ) {
				debug.log( AddressBook.errorMessages.integrityTest() );
			}
		}
	}
};
