/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

// Custom jQuery functions to modify the abook panel

// Disable the edit button on the toolbar
// TODO: Make this function accept the button-name we are to disable, use globally
$.fn.disable = function() { 
  return this.each(function() {
		$(this).attr("disabled",true); 
		$(this).css('opacity', 0.4);
		$(this).children().children().css('cursor', 'not-allowed');
		$(this).unbind("click");
	}); 
} 

// Enable the edit toolbar on the abook panel
$.fn.enable = function(func) {
  return this.each(function() { 
		if($(this).attr("disabled")) {
		$("strong", this).css('cursor', 'pointer');		
		$(this).unbind("click");
		$(this).bind("click", func );					
		$(this).attr("disabled",false); 
		$(this).css('opacity',1);			
		}
	
	}); 
} 

// Display the updated number of contacts in the view after deletion
$.fn.updateCount = function(count) {
	
	count = Number(count);
	
	// Load the current count
	var current = $(this).text();
	var groupCount = Number(current) + count;
	
	if(groupCount > 0) {

		$(this).text(groupCount);
		$(this).parent().fadeIn('slow');

	} else {

		// Hide the count, do not show (0)
		$(this).parent().fadeOut('slow');
		$(this).text(groupCount);
		
	}
	
}

// Display the updated number of contacts if total specified
$.fn.updateTotal = function(totalCount) {
	
	totalCount = Number(totalCount);
	
	// Load the current count
	if(totalCount > 0) {
	
		$(this).text(totalCount);
		$(this).parent().fadeIn('slow');
			
	} else {
	
		// Hide the count, do not show (0)
		$(this).parent().fadeOut('slow');
	    $(this).text(totalCount);
	
	}
	
}

checkTotalContacts = function(element)
{
	var totalItems = 0;
	
	if(element.parent() == undefined)
		return 0;
		
	return element.parent().children('.address_row').length;
}

$.fn.getAbookRow = function(context) 
{
	var item;
	var current_item;
	var id = false;

	// try the next item
	// but make sure its not being removed!
	current_item = $(this).next();
	if(!current_item.is('.removing'))
	{
		id = current_item.attr('contactid');
	}
	
	if(!id || id == 0 || id == 'pageNumber')
	{
		var searching = true;
		// next item doesn't exist or is being removed
		// lets find the next item which exists and isn't being removed
		
		while(searching)
		{
			current_item = current_item.next();
			if(!current_item.attr('contactid'))
			{
				searching = false;
			}
			else
			{
				if(!current_item.is('.removing'))
				{
					id = current_item.attr('contactid');
					searching = false;
				}
			}
		}
	
	}
	
	if(!id || id == 0 || id == 'pageNumber')
	{
		// didn't find anything after the current item, so lets go back up the list
		current_item = $(this).prev();
		if(!current_item.is('.removing'))
		{
			id = current_item.attr('contactid');
		}
		if(!id || id == 0 || id == 'pageNumber')
		{
			var searching = true;
			// prev item doesn't exist or is being removed
			// lets find the prev item which exists and isn't being removed
			while(searching)
			{
				current_item = current_item.prev();
				if(!current_item.attr('contactid'))
				{
					searching = false;
				}
				else
				{
					if(!current_item.is('.removing'))
					{
						id = current_item.attr('contactid');
						searching = false;
					}
				}
			}
	
		}
		
	}
	item = $('.address_row[contactid=' + id + ']', getVisiblePanelContext());
	totalContactsLeft = checkTotalContacts(item) - item.parent().children(".removing").length;

	// No messages are left to display
	if( !totalContactsLeft || !id || id == 0 || id == 'pageNumber' )
	{
		return $('#contact_info', context).html('');		
	}
		
	setTimeout(function() { $('.address_row[contactid=' + id + ']', getVisiblePanelContext()).trigger('click'); }, 200);	
}

// Display new contact panel (multipurpose, adds new contact node to list and or brings up edit form)
function newContact(addListNode, showAddForm, id, firstname, lastname, email, pictureUrl, favourite) 
{
	
	if( showAddForm == undefined )
		showAddForm = false;
	if( addListNode == undefined )
		addListNode = true;
	if( favourite == undefined )
		favourite = false;
	if( id == undefined )
		id = '';
	if( firstname == undefined )
		firstname = 'No Name';//TODO: translateable
	if( lastname == undefined )
		lastname = '';
	if( email == undefined )
		email = '';
	
	// Remove previously selected rows
	$('.contactRow:checked', '#Address_Book').each(function(){ 
		this.checked = false;
		$(this).parent().parent().removeClass('selected');
	});

	if( addListNode )
	{
		var newContact = $('.address_row:first', '#Address_Book').clone();
		if(newContact.size() == 0)
		{
			//nothing to clone !, reload the contacts
			$('li.current a', '#Address_Book').click();
			return;
		}
		newContact.removeClass("online")
		//remove cloned image
		newContact.children('.contact-photo').children('img').remove();//prevents cloned image showing wile downloading new image
		newContact.children('.contact-photo').html('<img />');
		newContact.children('.contact-photo').children('img').hide()
		newContact.children('.contact-photo').children('img').load(function() { $(this).fadeIn('slow') })
		newContact.children('.contact-photo').children('img').attr('src', pictureUrl )
		
		//remove global class if needed
		newContact.children('div.check').children('input.contactRow').removeClass('contactGlobal')
		newContact.children('div.check').children('input.contactRow').attr('value', id);
		newContact.attr('contactid', id);

		// set favourite if needed
		if(favourite)
		{
			newContact.find('.contact-fav').show();
		}
		newContact.insertBefore('.address_row:first');
		
		// Add the bind
		$('.check .contactRow').unbind('click');
		$('.address_row .contact_click').unbind('click');

		$('.check .contactRow').bind('click', function() { toggleContact(this); });	
		$('.address_row .contact_click').bind('click', function() { viewContact(this); });
		
		if(firstname == 'No Name' && email != '')
			newContact.find('.first_name').html(email);
		else
			newContact.find('.first_name').html(firstname);	

		newContact.find('.last_name').html(lastname);
	
		newContact.find('.check').children().each(function() 
		{
		
			this.checked = true;
			$(this).parent().parent().addClass('selected');
		
		});
		
		newContact.draggable(
		{
			helper: function() { return dragContact(this); },
			stop: function(event, ui) { dragContactStop(); },
			appendTo:'#draggableContactsContainer',
			cursor:'move',
			scroll:false,
			containment: 'body',
            distance:10,
			cursorAt:{top:15, left:48},
			revert: "invalid",
			revertDuration: 300
		});
	}
	
	if(showAddForm)
	{
		
		// Where are we, in the base folder, or a group
		var GroupID = $('li.current', '#Address_Book').attr('groupid');
		if(GroupID.indexOf("server") != -1 || GroupID > 0)
			$.php(moduleBaseUrl + '/contacts/newcontact/new/1/ui/1/GroupID/' + GroupID )
		else
			$.php(moduleBaseUrl + '/contacts/newcontact/new/1/ui/1' )
		$.jCacher.remove('autocomplete')
		
	}

}

// Delete a specified contact
function deleteContact(clickedObject) 
{
	if( $('#action_contact_delete a').attr("disabled") == true )
		return;
	
	// Where are we, in the base folder, or a group
	var GroupID = $('li.current', '#Address_Book').attr('GroupID')
	
	if(GroupID > 0)
		$.php(moduleBaseUrl + '/contacts/deletecontactgroup/GroupID/' + GroupID + '/',$("#listcontacts").serializeArray());	 	
	else 
	{
		
	/*	var checkedRows = $('.contactGlobal:checked', '#Address_Book').size();
		if( checkedRows > 0 ) 
		{
		
			//TODO: make translatable
			alert("Cannot delete global contacts.");
			return;
		
		}*/
		nextID = $("input.contactRow:checked:last", '#Address_Book').parent().parent().next('.address_row').attr('contactid');
		$.php(moduleBaseUrl + '/contacts/deletecontact/GroupID/' + GroupID + '/',$("#listcontacts").serializeArray());		
	
	}
	$.jCacher.remove('autocomplete')
	

	// Show the next contact in the view
	// TODO: If 0 contacts, need to show 'null'
	//TODO: unless returning php.complete to previous state - remove all overloading of php.complete and rather use callback function or server push methods
	php.complete = function ()
	{

		php.complete = function() 
		{ 
		
			$('.loading').each( function() { $(this).removeClass('loading') } );
            $('#back_button').each( function() { $(this).fadeTo(100, 1) } );
 		
		}
		
		// If we have additional contacts, show the next user
		
		if(typeof(nextID) != "undefined" && nextID > 0) 
		{
		
			$.php(moduleBaseUrl + '/contacts/viewcontact/id/' + nextID + '/groupid/' + GroupID);
            // Select the next row as the "current view"
			$('.contact_icon:first', '#Address_Book').prev('.check').children().each(function() 
			{
			
				$(this).attr('checked', 'true');
				$(this).parent().parent().addClass('selected');
			
			});
		
		} 
		else 
		{
			
			// Show "empty" contacts otherwise
			setTimeout( "$.php('" + moduleBaseUrl + "/contacts/viewcontacts/GroupID/" + GroupID + "');", 300);
			
		}  
		$('#primary_header').each( function() { $(this).removeClass('loading') } );

	}
	
}

function editContactDblClick(clickedObject) 
{
	var contactID = $('#contact_table', '#Address_Book').attr('contactid');
	var GroupID = $('li.current', '#Address_Book').attr('groupid');
	
	if(contactID)
	{
		
		$.php(moduleBaseUrl + '/contacts/editcontact/id/' + contactID + '/GroupID/' + GroupID );
		
	}
	$.jCacher.remove('autocomplete')

}

function toggleContact(clickedObject) {
	var GroupID = $('li.current', '#Address_Book').attr('GroupID');
	// Add the selected row if checkbox clicked, else remove
	if(clickedObject.checked)
	$(clickedObject).parent().parent().addClass('selected');
	else
	$(clickedObject).parent().parent().removeClass('selected');
	
	
	var checkedRows = $('.contactRow:checked', '#Address_Book').size();
	if(checkedRows == 1)
	{
		clickedObject = $('.contactRow:checked', '#Address_Book');
		var GroupID = $('li.current', '#Address_Book').attr('GroupID')
		$('#contact_table', '#Address_Book').hide();

		url = moduleBaseUrl + '/contacts/viewcontact/id/' + $(clickedObject).parent().parent().attr('contactid') + '/GroupID/' + GroupID;			
		$.php( url );
	}

	if(checkedRows >= 1)	{
		if(GroupID >= 0){
			$('#action_contact_delete a', '#Address_Book').enable(function() { return deleteContact($('#contact_table:first')); });
		}
    $('#action_contact_export a','#Address_Book').enable(function(){ return exportContact() });
	} else {
		$('#action_contact_delete a', '#Address_Book').disable();
	}
	
	// Count how many elements exist, disable the edit button, only for the one selected contact
		if(checkedRows != 1) {
		$('#action_share_contacts a', '#Address_Book').disable();
	} else {
	  if(GroupID >= 0){
			$('#action_share_contacts a', '#Address_Book').enable( function() { return editContactDblClick() } );
		}
	}
	
	if(checkedRows != 1) {
		$('#action_contact_edit a', '#Address_Book').disable();
	} else {
	  if(GroupID >= 0){
			$('#action_contact_edit a', '#Address_Book').enable( function() { return editContactDblClick() } );
		}
	}

	if(checkedRows == 0){
    $('#action_contact_export a','#Address_Book').disable();
	}
}

function viewContact(clickedObject) {
	var GroupID = $('li.current', '#Address_Book').attr('GroupID')
	$('#contact_table', '#Address_Book').hide();

	url = moduleBaseUrl + '/contacts/viewcontact/id/' + $(clickedObject).parent().attr('contactid') + '/GroupID/' + GroupID;			
	$.php( url );

	// Remove previously selected rows
	$('.contactRow:checked', '#Address_Book').each(function(){ 
		this.checked = false;
		$(this).parent().parent().removeClass('selected');
	});
	
	// Create a checkbox of the selection
	$(clickedObject).prev('.check').children().each(function() {
		this.checked = true;
		this.focus();
		$(this).parent().parent().addClass('selected');
		//$('#action_contact_edit').enable();
	});
	
}

function dragContact(clickedObject) 
{ 

	$(clickedObject).addClass('selected')
	$('.contactRow', $(clickedObject)).attr('checked',true);

	var size = $('.contactRow:checked', '#Address_Book').size();
	
	$('.contactRow:checked', '#Address_Book').each(function() {
	
		$(this).parent().parent().css('opacity', 0.6);
		
	});
	
	if(!size)
		size = 1;
    return $('<div class="contact_icon_drag"><img alt="dragging '+size+' contacts" src="../images/draggable.png" style="display:inline;" /><div class="contact_drag_no"><span class="drag"><strong>' + size + '</strong></span></div></div>');

}

function dragContactStop(clickedObject) 
{ 

	$('.contactRow', '#Address_Book').each(function() {
	
		$(this).parent().parent().css('opacity', 1);
		
	});
	
}

function resetDroppables() 
{
	$("ul#nav_secondary li:not('.current'):not('li[groupid=-1]'):not('li[groupid=-3]')", '#Address_Book').droppable("destroy").droppable(
	{
		accept: "div.address_row",
		activeClass: 'droppable-active',
		hoverClass: 'droppable-hover',
		drop: function(ev, ui) 
		{
			$.jCacher.remove('autocomplete')
			$.jCacher.remove('autocomplete_global')
			contactId = $(ui.draggable).attr('contactid')
			GroupID = $(this).attr('groupid');

			var dragMatch;			
			// First, check the contacts we are dragging has been selected on the DnD
			$('.contactRow:checked', '#Address_Book').each(function() 
			{
		
				var checkedID = $(this).parent().parent().attr('contactid');
				if(checkedID == contactId)
				dragMatch = 1;
		
			});
					
			// Drag multiple contacts, or a single element
			if($('.contactRow:checked', '#Address_Book').size() > 0 && dragMatch == 1)
			{
		
				$.php(moduleBaseUrl + '/contacts/addcontacttogroup/GroupID/' + GroupID, $("#listcontacts:first").serializeArray())
		
			}
			else
			{
		
				$.php(moduleBaseUrl + '/contacts/addcontacttogroup/GroupID/' + GroupID + '/id/' + contactId)
		
			}
		
		}

	})
	
}

/*
Functions used for listGroups.phtml
*/

function listContactsClick(clickedObject)
{
	if(!currentlyEditingAGroup) {
		$('ul#nav_secondary li', '#Address_Book').removeClass('current')
		$(clickedObject).parent().addClass('current')
		
		// Disable delete button if a system group is selected (all user created groups have groupid > 0)	
		if( $(clickedObject).parent().attr('groupid') < 1 ) {
			$('#Address_Book #folder_remove a').removeClass('enabled');           
			$('#Address_Book #folder_remove a').addClass('disabled');           

			$('#folder_actions', '#Address_Book').removeClass('folder-removable');
		} else {
			$('#Address_Book #folder_remove a').removeClass('disabled');
			$('#Address_Book #folder_remove a').addClass('enabled');

			$('#folder_actions', '#Address_Book').addClass('folder-removable');
		}
		
		$('#listcontacts', '#Address_Book').hide();
		$('#contact_table', '#Address_Book').hide();
				
		$.php( moduleBaseUrl + "/contacts/viewcontacts/GroupID/" + $(clickedObject).parent().attr('GroupID'));
		resetDroppables();
	}

	return false
}  

function editGroupDblClick(clickedObject) 
{

	a = $(clickedObject)
	
	if(a.parent().attr('groupid') <= 0)
	{
		
		return;
		
	}

	currentlyEditingAGroup = true
	
	li = a.parent()
	span = a.children('span')
	oldGroupName = li.attr('groupname')
	
	// Create a form to specify the new name
	$('<form id="updateGroupForm" method="post" target="_blank"><input name="newGroupName" oldGroupName="' + oldGroupName + '" value="' + oldGroupName + '"></form>').insertAfter(a); 

	// Hide the label text
	a.hide();

	form = li.children('form');
	input = form.children('input');
	input.focus();
	input.select();

	input.bind('blur', function() 
	{
	
		$(this).parent().submit()
	
	})
	
	form.submit( function() 
	{ 
	
		form = $(this)
		GroupID = $(this).parent().attr('groupid')
		newGroupName = $(this).children('input').attr('value')
		oldGroupName = $(this).children('input').attr('oldGroupName')
		// Change the text to the new groupname
		$('.groupLink:hidden .label span.labelname', '#Address_Book').text(newGroupName);
		$(this).parent().attr('GroupName', newGroupName);
		
		// Show the original div
		$('.groupLink:hidden', '#Address_Book').show();
		// Remove from the DOM the html form for editing
		form.remove();
		$.jCacher.remove('autocomplete')
		if( newGroupName != oldGroupName )
		{
			
			$.php(moduleBaseUrl + '/contacts/updategroupname/GroupID/' + GroupID + '/newGroupName/' + newGroupName )
			
		}
		currentlyEditingAGroup = false
		return false
	
	})
	  
}

function addGroup(clickedObject) 
{
  $(this).blur();

	if( $('#newGroupForm', '#Address_Book').length == 0 ) 
	{
	
		$('#nav_secondary', '#Address_Book').append('<li>' + 
										   '<form id="newGroupForm" method="post" target="_blank">' + 
										   '<input name="newGroupName" value="' + jsTranslate("New Group") + '" style="width:130px;">' + 
										   '</form>' + 
										   '</li>')
		$("#secondary", '#Address_Book').attr({ scrollTop: $("#Address_Book #secondary").attr("scrollHeight") });		
		$('#newGroupForm input', '#Address_Book').select()
		$('#newGroupForm input', '#Address_Book').bind('blur', function() 
		{
			$(this).parent().submit()
		})
	
		$('#newGroupForm', '#Address_Book').submit( function() 
		{
			args = $('#newGroupForm').serializeArray(); 
	        li = $(this).parent()
			newGroupName = htmlentities($(this).children('input').attr('value'), 'ENT_QUOTES');
		
			// TODO: Remove language string
			if( newGroupName == jsTranslate('New Group') ) {
				li.remove()                                          
				return false
			}
		
	        //CONSIDER: use clone instead to transparently cope with html changes to the list
			li.attr('groupname', newGroupName )
			li.attr('groupid', '' )
			li.attr('newgroup', 'true' )
			li.addClass('ui-droppable')
			li.html('<a class="groupLink" tabindex="0" href="#"><span class="label"><span class="labelname">' + newGroupName + '</span></span><span class="unread" style="display:none;"><strong>0</strong></a></span></a>');
		
			a = li.children('a')
			a.bind('click', function() { return listContactsClick(this) } )     
			a.bind("dblclick", function() { return editGroupDblClick(this) } )

			$.php(moduleBaseUrl + '/contacts/creategroup/', args);
		    $.jCacher.remove('autocomplete')
			resetDroppables()
			return false
	    })
  
	}

	return false;
	
}

function resetMyGroupButtons()
{
	$('#folder_actions', '#Address_Book').removeClass('folder-removable'); 
}

function removeGroup(clickedObject) 
{
    
	// TODO: Remove any english language strings from the JS array
	if( !$(clickedObject).hasClass('enabled') )
	{
		
		return false
		
	}
	else if($('#Address_Book li.current').length > 0 && confirm(jsTranslate('Are you sure you want to delete') + ' ' + html_entity_decode($('#Address_Book li.current').attr('GroupName') )) ) 
	{
	
		$.jCacher.remove('autocomplete')
		$.php(moduleBaseUrl + '/contacts/deletegroup/GroupID/' + $('#Address_Book li.current').attr('GroupID') )
		//listContactsClick($('#Address_Book ul#nav_secondary li:first a'));
	
	}
	return false;

}

function searchAbook(clickedObject)
{
	query = $(clickedObject).attr('value');
	
	if(query.length > 1)
	{
		$.php(moduleBaseUrl + "/contacts/searchFuzzy/GroupID/" + $('#Address_Book li.current').attr('GroupID') + '/', { "query" : query} );
	}
	else
	{
		$.php(moduleBaseUrl + '/contacts/viewcontacts/GroupID/' + $("#Address_Book li.current").attr("GroupID") + '/');
	}
	
	return true;
}

function exportContact(clickedObject) {

	url = moduleBaseUrl + '/contacts/exportcontact/GroupID/' + $('li.current', '#Address_Book').attr('groupid') + '/id/';
	urlArgs = '';
	
	// Which elements to export?
	$('.contactRow:checked', '#Address_Book').each(function(){
		var checkedID = $(this).parent().parent().attr('contactid');		
		urlArgs = urlArgs + checkedID + ":";
	});
	
	url = url + urlArgs + '/vcard.vcf';
	
	location.href=url;
}

function emailSelected() {

	// Which elements to export?
	var contacts = Array();
	
	$('.contactRow:checked', '#Address_Book').each(function(){
		var email = $(this).parent().parent().find('SPAN.email').text();
		
		if(email != '' && email != undefined)
			contacts.push(email);
			
	});
	
	openNewComposerTab( {'to': contacts } ); 
	
}

function selectAll(clickedObject) {
	jsddm_close();
	$('.contactRow', '#Address_Book').each(function(){ 
		this.checked = true;
		// toggleContact(this)
		$(this).parent().parent().addClass('selected');
	});
	$('#action_contact_edit a', '#Address_Book').disable().attr('tabindex','-1');
		$('#action_share_contacts a', '#Address_Book').disable().attr('tabindex','-1');
	$('#action_contact_delete a', '#Address_Book').enable(function() { return deleteContact($('#contact_table:first')); });
  $('#action_more_contacts > .moredrop').focus();
	$('.menu_drop_more > a').css('outline','none');
}

function deselectAll(clickedObject) {
	jsddm_close();
	
	$('.contactRow', '#Address_Book').each(function(){ 
		this.checked = false;
		$(this).parent().parent().removeClass('selected');
	});
 $('#action_contact_delete a', '#Address_Book').disable().attr('tabindex','-1');
 $('#action_contact_edit a', '#Address_Book').disable();
  $('#action_share_contacts a', '#Address_Book').disable();
 $('#action_more_contacts > .moredrop').focus();
 $('.menu_drop_more a').css('outline','none');
}

// Edit addressbook functions
// Functions to handle default states
function changeDefault(fieldObject) 
{
    //TODO: still used? cleanup (remove references to external dependant data), remote Javascript specific code (not jQueryalized)
	if( fieldObject.value == formNames[fieldObject.id] ) 
		fieldObject.select()
	
}

function checkDefault(fieldObject) 
{

	//TODO: still used? cleanup (remove references to external dependant data), remote Javascript specific code (not jQueryalized)
	if( !fieldObject.value || fieldObject.value == formNames[fieldObject.id]) 
	{
		
		fieldObject.value = formNames[fieldObject.id]
		fieldObject.className='default'
	
	}

}

function updateDependantSelects(selectorName, allOptions) {

	usedOptions = Array();
	unusedOptions = Array();
	
	$("[name='" + selectorName + "']", '#Address_Book').children('option:selected').each( function() {
		usedOptions[$(this).attr('value')] = $(this).attr('value');
	})                           

	// Build a list of unused options
	for(var item in allOptions) {
		if(usedOptions[item] == undefined) {
			unusedOptions[item] = allOptions[item];
		}
	}
	
	$("[name='" + selectorName + "']", '#Address_Book').children('option:not(:selected)').remove()
	appendOptions = ''
	for( var item in unusedOptions ) {
		appendOptions += '<option value="' + item + '">' + unusedOptions[item] + '</option>\n'
	}

	$("[name='" + selectorName + "']").each( function() {
		$(this).append(appendOptions)
	})
}

function removeClicked(clickedObject, allOptions) {
	//remove row then unhide last add button
	var rowType = $(clickedObject).parent().parent().children('td:first').children('select').attr('name');
	
	if( $("[name='" + rowType + "']", '#Address_Book').length <= 1) {
		$(clickedObject).parent().children('input').attr('value', '');
		$(clickedObject).parent().children('input').effect('highlight', {}, 500);
		$(clickedObject).parent().children('input').focus();
		return;
	}
	
	$(clickedObject).parent().parent().remove();                   

	$("[name='" + rowType + "']:last", '#Address_Book').each( function() { $(this).parent().parent().find('img').show(); });

	updateDependantSelects( $(clickedObject).parent().parent().children('td:first').children('select').attr('name'), allOptions );
}

function addClicked(clickedObject, allOptions) {


	if( $(clickedObject).parent().children('input').attr('value') == 'Email Address') {
		$(clickedObject).parent().children('input').effect('highlight', {}, 500);
		$(clickedObject).parent().children('input').focus();
		return false;
	}
	
	newRow = $(clickedObject).parent().parent().clone(true);
	newRow.children('td').children('select').children('option').each(function() { $(this).remove(); }); //.remove();
	newRow.children('td').children('select').children('option:first').attr('selected','selected');

	var total = 0;
	for(var item in allOptions) {
		total ++;
	}

	console.log("[name='" + $(clickedObject).parent().parent().children('td:first').children('select').attr('name') + "']");
	if( $("[name='" + $(clickedObject).parent().parent().children('td:first').children('select').attr('name') + "']", '#Address_Book').length >= total -1)
	{
		$(newRow).children('td').children('img.contactFieldAdd').css('display','none');
	}
	
	$(clickedObject).parent().parent().after( newRow );
       
	newRow = $(clickedObject).parent().parent().next();
	
	$(newRow).children('td').children('input').attr('value', '');
	$(newRow).children('td').children('input').select();
	$(newRow).children('td').children('input').keypress( function(e) { 
		if($(this).attr('value') == '' && (e.which == 32 || e.which == 8 || e.which == 0 ))
			$(this).parent().children('img.contactFieldAdd').css('display','none');
		else if( $(this).parent().parent().children('td').children('select').children('option').length > 1 )
			$(this).parent().children('img.contactFieldAdd').css('display','');
	})
	$(clickedObject).css('display','none');
	
	updateDependantSelects( $(clickedObject).parent().parent().children('td:first').children('select').attr('name'), allOptions );
}

function PhTypeCtrl(type,number)
{
  this.types = [
		{value:'UserHomePhone', text:'Home Phone',     set:false},
		{value:'UserHomeMobile',text:'Private Mobile', set:false},
		{value:'UserHomeFax',   text:'Private Fax',    set:false},
		{value:'UserWorkPhone', text:'Work Phone',     set:false},
		{value:'UserWorkMobile',text:'Work Mobile',    set:false},
		{value:'UserWorkFax',   text:'Work Fax',       set:false}
	]
	this.count = 0;
  this.ctrlClass = 'PHTYPECTRL__';
	this.rowClass  = 'PHCTRLROW__';
	this.getCtrl = getCtrl;
	this.getAddBtn = getAddBtn;
	this.getRemBtn = getRemBtn;
  this.getCtrlContainer = getCtrlContainer;
  this.existingOptions  = existingOptions;

	/*
	this.init = init;

	if(type && number){
		this.init();
	}

	function init()
	{
		var $pos = $('#contact_table tbody tr:first');
		{
			$tr = this.getCtrlContainer()
			$pos.after($tr);

			$sel = $tr.find('td:first select');
			$img = $tr.find('td:last img:last');
			$val = $tr.find('td:last input');
			$sel.val(type);
			$val.val(number);

		}
	}
	*/

  function existingOptions(sref)
	{
		var thus   = sref ? sref : this;
		var exists = [];
		$('.'+thus.ctrlClass+ ' option:selected').each(function(i,o){ exists.push(o.value) });
		return exists;
	}

	function getCtrl(sref)
	{
		var $control = $('<select class="'+this.ctrlClass+'" name="contact[numberFieldName][]"></select>');
		var self     = sref ? sref : this;
		var exists   = self.existingOptions(sref);
		
		for(var i = 0; i < self.types.length; i++)
		{
			if( $.inArray(self.types[i].value, exists) == -1 )
			{
				var option = $('<option value="'+self.types[i].value+'">'+self.types[i].text+'</option>');
				// console.log(type+":"+self.types[i].value);

				$control.append(option);
			
				$control.bind('change',function(e){
				  var type = $(this).children(':selected').text();
					$(this)
						.parents('tr')
						.find('td:last input')
						.attr('placeholder',type);
					$(this)
				  	.parents('tr')
						.find('td:last label').text(type)
				});
			}
		}
		return $control;
	}

  function getRemBtn(sref)
	{
		var thus = sref ? sref : this;
		var $btn = $('<img class="REMPHFIELD__ contactImgBtn" src="../images/icons/btn_remove.png" />');
		$btn.bind('click',function(e){
			if( $('.'+thus.ctrlClass).length > 1)
			{
				var $row = $(this).parents('tr');
				var $opt = $row.find('td:first select option');
				$row.remove();
				$('#ADDPHFIELD__').remove();
				$('.'+thus.rowClass+':last td:last').append(thus.getAddBtn(sref))
				val = $('.'+thus.rowClass+':last td:first select').val();
				$('.'+thus.rowClass+':last td:first select').append($opt);
				$('.'+thus.rowClass+':last td:first select').val(val);
			}
		}).bind('keydown',function(e){
			if(e.which==ENTER_KEY){
				$(this).click();
			}
		});
		return $btn;
	}

  function getAddBtn(sref)
	{
		var $btn = $('<img id="ADDPHFIELD__" class="contactImgBtn" src="../images/icons/btn_add.png" />');
	  var thus = sref ? sref : this;
		$btn.bind('click',function(e){
			$row = $(this).parents('tr');
			$row.after(thus.getCtrlContainer(thus));
			$row.find('td:first select :not(option:selected)').remove();

		}).bind('keydown',function(e){
		  if(e.which==ENTER_KEY){
				$(this).click();
			}
		});
		return $btn
	}

	function getCtrlContainer(sref)
	{
		var thus = (sref) ? sref : this;
		
	  if(thus.count < thus.types.length)
		{
			thus.count += 1;
			$('#ADDPHFIELD__').remove();
			var $addBtn = thus.getAddBtn(sref);
			var $remBtn = thus.getRemBtn(sref);
		  var $ctrl = thus.getCtrl(sref);
		  var tbid  = thus.ctrlClass+'VAL'+thus.count+'__';
			var tbtx  = $ctrl.children(':selected').text();
			var $lbl  = $(
			  '<label for="'+tbid+'" class="offscreen">' + $ctrl.children(':selected').text() + '</label>'
		  );
			var $row  = $('<tr class="'+thus.rowClass+'"></tr>');
			var $co1  = $('<td></td>');
			var $co2  = $('<td></td>');
			var $input = $('<input id="'+tbid+'" name="contact[numberValue][]" maxlength="128"' +
				' tabindex="0" class="default" placeholder="'+tbtx+'" value="' + (num?num:'') + '" />'
			);
			if($('.'+thus.ctrlClass).length == 0){
				$remBtn.css('display','none');
			}

		  $co1.append($ctrl);
			$co2.append($lbl).append($input).append($remBtn).append($addBtn);
		  $row.append($co1).append($co2);
			return $row;
		}
	}
}

function UserContact(fields){
  this.fields = fields;
  this.phoneFields = ['UserHomePhone','UserHomeMobile','UserHomeFax','UserWorkPhone','UserWorkMobile','UserWorkFax'];
	this.emailFields = ['UserEmail','UserEmail2','UserEmail3','UserEmail4','UserEmail5'];
	this.get = get;
	this.getPhoneNumber = getPhoneNumber;
  this.fieldExists = fieldExists;

	function fieldExists(field){
		return ( (typeof this.fields[field] === 'undefined') ? false : true);
	}

	function getPhoneNumber(field){
		if(this.fieldExists(field)){
		  num = this.fields[field].replace(/\D/,'');
			if(num.length == 10){
				var area = num.substr(0,3);
				var prfx = num.substr(2,3);
				var post = num.substr(5,4);
				return area+"-"+prfx+"-"+post;
			}
			return num;
		}
	}

	function get(field){
		if(this.fieldExits(field)){
			return this.fields[field];
		}
	}
}

