/**
 *	Enable the checkbox functionality of the address book. 
 *	
 *	TODO	The contact list might be similar is <input type="checkbox" class='recipient_input' name="contact_list" value="{contacts_id}" /> used
 *				the email as a value.
 */
function setupContactList(){

	$('.add_recipient_contact_icon').click(openRecipientContactList);
	$('.add_recipient_contact_link').click(openRecipientContactList);
	$('.add_contributor_contact_link').click(openContributorContactList);
  	$('.add_contributor_contact_icon').click(openContributorContactList);  
  
	//	Add the calls that will close
	$('.close_contacts_list').click(closeContactsBook);
	$('.add_contacts_btn').click(closeContactsBook);	
	
	//	TODO	There is probably a better itteration technique
	var contacts = $('.recipient_input');
	for(var i=0;i<contacts.length;i++){
		$(contacts[i]).change(function(){
			updateActiveContacts(this,'add_recipient','recipient');
		});
	}	
	var contributors = $('.contributor_input');
	for(var i=0;i<contributors.length;i++){
		$(contributors[i]).change(function(){
			updateActiveContacts(this,'add_contributor','contributor');
		});
	}		
	
}
/**
 * 
 *	@param {Object} e 
 */
function closeContactsBook(e){
	e.preventDefault();		
	$('.contacts_content').css('display','none');
	$('.black_overlay').css('display','none');			
}
/**
 *	Opens the modal panel with the list of recipients. 
 *
 *	TODO	I would perfer to use the modal call
 */
function openRecipientContactList(e){
	e.preventDefault();
	$('#contacts_book').css('display','block');
	$('.black_overlay').css('display','block');
	delayhideToolTip2();
}
/**
 * 
 * @param {Object} e
 */
function openContributorContactList(e){
	e.preventDefault();
	$('#contributer_contacts_book').css('display','block');
	$('.black_overlay').css('display','block');	
	delayhideToolTip3();	
}
/**
 *	Removes the contact from either the contributor address book 
 *	or the recipient address book. 
 *
 *	@param	type		Flag indicating either 'contributor' or 'recipient'
 */
function updateContactsBook(type){
	
	//	Retrieve all the checked address book
	var checkedContacts = checkedAddressBookEntries(type);
	
	//	Retrieve the emails of all the added contacts
	var emails = currentContacts(type);
	
	//	Any checkedContacts that aren't in the contact list should be unchecked
	for (var i = 0; i < checkedContacts.length; i++) {
  	var exists = false;
  	var contactID = $(checkedContacts[i]).attr('value');
  	var contactEmail = $('#email_' + contactID + ' em').html();
  	for (var j = 0; j < emails.length; j++) {
  		if (contactEmail == emails[j]) {
  			exists = true;
  			continue;
  		}
  	}
  	if (!exists)$(checkedContacts[i]).attr('checked', false);
  }
}
/**
 * 	Returns an array of check box inputs that have been checked.
 * 
 * 	@param type
 */
function checkedAddressBookEntries(type){
	var checkedEntries = [];
	var recipientAddressBookEntries = $('.'+type+'_input');
	for (var i = 0; i < recipientAddressBookEntries.length; i++) {
		if ($(recipientAddressBookEntries[i]).attr('checked')) {
			checkedEntries.push(recipientAddressBookEntries[i]);
		}
  }
	return checkedEntries;
}
/**
 *  @param	input			The check box in the contact list that was checkd or unchecked
 *  @param	tableID		The id of the body that contains the selected contacts e.g. 'add_contributor' or 'add_recipient'
 */
function updateActiveContacts(input,tableID,type){

	//	Add the contact if the checkbox is checked - otherwise remove it from the list
	var value = $(input).attr('value');
	if ($(input).attr('checked')) {
		
		if(($('#f_email').attr('value')=='')&&(type=='recipient')){
    
			//  TODO  Not sure if the recipient count should go up for the first entry
			var email = $('#email_'+value+' em').html();
			var name = $('#name_'+value+' strong').html();
			$('#f_email').attr('value',email);
			$('#f_name').attr('value',name);
			
			//  Clear the labels 
			$('#f_name_label,#f_email_label').html('');
			return;
			
		}
		
		//	TODO	Not DRY - see below
		//	TODO Not like this method for exiting a loop
		var recipientUpdated = false;
		if (type == 'recipient') {
			$('#add_recipient').find("tr").each(function(i){
				if($(this).find("[class='required email ie_input']").attr('value')==DEFAULT_EMAIL){
					if(recipientUpdated)return;
					var email = $('#email_'+value+' em').html();
					var name = $('#name_'+value+' strong').html();
					$(this).find("[class='required email ie_input']").attr('value',email);
					$(this).find("[class='required ie_input']").attr('value',name);		
					recipientUpdated = true;
					return;			
				}
			});
		}
		if(recipientUpdated)return;
		
		
	if(($('#c_email').attr('value')=='')&&(type=='contributor')){
		var email = $('#email_'+value+' em').html();
      	var name = $('#name_'+value+' strong').html();      
      	$('#c_email').attr('value',email);
      	$('#c_name').attr('value',name);

      //  Clear the labels 
      $('#c_name_label,#c_email_label').html('');
	  return;
    }
		
	//	TODO Not like this method for exiting a loop
		var contributorUpdated = false;
		if (type == 'contributor') {
			$('#add_contributor').find("tr").each(function(i){
				if(contributorUpdated)return;
				if($(this).find("[class='required email ie_input']").attr('value')==DEFAULT_EMAIL){
					var email = $('#email_'+value+' em').html();
					var name = $('#name_'+value+' strong').html();
					$(this).find("[class='required email ie_input']").attr('value',email);
					$(this).find("[class='required ie_input']").attr('value',name);		
					contributorUpdated = true;
					return;			
				}
			});
		}		
		if(contributorUpdated)return;
		
		//	TODO	Should add to the first field (if it is blank)
  	addContactToMessage(value, tableID,type);
  }else{
		
		//	Retrieve the email address for the input
		var email = $('#email_'+value+' em').html();
		switch(type){
			case 'recipient':
				uncheckRecipient(email,tableID);
				break;
			case 'contributor':
				uncheckContributor(email,tableID);
				break;
			default:
				alert('Unknown contact type('+type+')');
				break;
		}
	}	
}
/**
 * 	Remove the recipient in the recipeient list with the specified
 * 	email address.  This is similar funcitonality to the "removeMyLine"
 *  call in "dynamic_fields".
 *  
 *  @param	email			The name of the email to remove the recipient list 
 *  									e.g. 'warren.sangster@designbyfront.com'
 *  @param	tableID		The id of the body that contains the selected contacts e.g. 'add_contributor' or 'add_recipient'
 */
function uncheckRecipient(email,tableID){

  
	var rows = $('#'+tableID+' tr');
	for(var i=0;i<rows.length;i++){
		var row = rows[i];
		var inputs = $(row).find("[class='required email ie_input']");
		for(var j=0;j<inputs.length;j++){
			if($(inputs[j]).attr('value')==email){
				$(row).remove();	
				removeRecipient();
				break;
			}
		}
	}
}
/**
 * 
 * 	Remove the recipient in the recipeient list with the specified
 * 	email address.  This is similar funcitonality to the "removeMyLine"
 *  call in "dynamic_fields".
 *  
 *  @param	email			The name of the email to remove the recipient list 
 *  									e.g. 'warren.sangster@designbyfront.com'
 *  @param	tableID		The id of the body that contains the selected contacts e.g. 'add_contributor' or 'add_recipient' 
 */
function uncheckContributor(email,tableID){
	var rows = $('#'+tableID+' tr');
	for(var i=0;i<rows.length;i++){
		var row = rows[i];
		var inputs = $(row).find("[class='required email ie_input']");
		for(var j=0;j<inputs.length;j++){
			if($(inputs[j]).attr('value')==email){
				$(row).remove();	
				removeContributor();
				break;
			}
		}
	}	
}
/**
 *	@param	type 
 */
function currentContacts(type){
	var emails = [];
	var rows = $('#add_'+type+' tr');
	for(var i=0;i<rows.length;i++){
		var row = rows[i];
		var inputs = $(row).find("[class='required email ie_input']");
		for(var j=0;j<inputs.length;j++){
			emails.push($(inputs[j]).attr('value'));
		}
		
		//	Check the primary input field - (it has a different class)
		var primaryInputs = $(row).find("[class='required email']");
		for(var j=0;j<primaryInputs.length;j++){
			emails.push($(primaryInputs[j]).attr('value'));
		}		
	}	
	return emails;	
}
/**
 *	Return the email of all the currently added recipients.  These
 *	are the add recipients NOT the recipients in the contact list.
 */
function currentAddedRecipients(){
	var emails = [];
	var rows = $('#add_recipient tr');
	for(var i=0;i<rows.length;i++){
		var row = rows[i];
		var inputs = $(row).find("[class='required email ie_input']");
		for(var j=0;j<inputs.length;j++){
			emails.push($(inputs[j]).attr('value'));
		}
	}	
	return emails;
} 

