<script type="text/javascript" language="JavaScript">
function simulateClick(e){
  if(e.which == ENTER_KEY){
		$(this).click();
	}
}

</script>
<?php
	$requiredFields = array(
	'id', 
	'UserTitle', 'UserFirstName', 'UserMiddleName', 'UserLastName', 
	'UserHomeAddress', 'UserHomeCity', 'UserHomeState', 'UserHomeZip', 'UserHomeState', 'UserHomeCountry', 'UserHomePhone', 'UserHomeMobile', 'UserHomeFax', 
	'UserWorkCompany', 'UserWorkTitle', 'UserWorkDept', 'UserWorkAddress', 'UserWorkCity', 'UserWorkState', 'UserWorkZip', 'UserWorkState', 'UserWorkCountry', 'UserWorkPhone', 'UserWorkMobile', 'UserWorkFax', 
	'UserEmail', 'UserEmail2', 'UserEmail3', 'UserEmail4', 'UserEmail5', 
	'UserInfo', 'UserURL', 'UserDOB', 'UserPhoto');
	foreach($requiredFields as $requiredField)
	{
		$this->contact[$requiredField] = array_key_exists($requiredField, $this->contact) ? $this->contact[$requiredField] : '';
	}
?>
<?php	if( !is_array($this->contact) ) : ?>
No contact to edit
<?php	else : ?>
<div id="Flash"></div>
<form id="contactform" action="<?php echo $this->moduleBaseUrl ?>/contacts/updatecontact" ENCTYPE="multipart/form-data">
<input type="hidden" name="contact[id]" value="<?php echo $this->contact['id'] ?>">
<input type="hidden" name="contact[serverID]" value="<?php if(isset($this->contact['serverID'])) echo $this->contact['serverID']; ?>">
<?php	endif; ?>

<?php	if(isset($this->contact['NewContact']) && $this->contact['NewContact'] == 1) : ?>
<input type="hidden" name="contact[NewContact]" value="1">
<?php	endif ?>
<input type="hidden" name="contact[GroupID]" value="<?php if(!empty($this->GroupID)) echo $this->GroupID; ?>">
<?php
$translationHash = array(
	'UserHomePhone' => $this->translate('Home Phone'),
	'UserHomeMobile' => $this->translate('Private Mobile'),
	'UserHomeFax' => $this->translate('Private Fax'),
	'UserWorkPhone' => $this->translate('Work Phone'),
	'UserWorkMobile' => $this->translate('Work Mobile'),
	'UserWorkFax' => $this->translate('Work Fax'),
	'UserHomeAddress' => $this->translate('Home Address'),
	'UserHomeCity' => $this->translate('Home City'),
	'UserHomeState' => $this->translate('Home State'),
	'UserHomeZip' => $this->translate('Home Zip'),
	'UserHomeCountry' => $this->translate('Home Country'),
	'UserWorkAddress' => $this->translate('Work Address'),
	'UserWorkCity' => $this->translate('Work City'),
	'UserWorkState' => $this->translate('Work State'),
	'UserWorkZip' => $this->translate('Work Zip'),
	'UserWorkCountry' => $this->translate('Work Country'),
	'Home' => $this->translate('Home'),
	'Work' => $this->translate('Work'),
	'Home Address' => $this->translate('Home Address'),
	'Work Address' => $this->translate('Work Address'),
	'UserFirstName' => $this->translate('First Name'),
	'UserMiddleName' => $this->translate('Middle Name'),
	'UserLastName' => $this->translate('Last Name'),
	'UserEmail' => $this->translate('Email Address'),
	'Phone' => $this->translate('Phone Number'),
	'Notes' => $this->translate('Notes'),
	'UserInfo' => $this->translate('More Information ...'),
	'UserDOB' => $this->translate('Date of Birth'),
	'UserTitle' => $this->translate('Title'),
	'UserWorkTitle' => $this->translate('Work Title'),
	'UserWorkDept' => $this->translate('Work Department'),
	'UserWorkCompany' => $this->translate('Company'), 
	'EmailAddress' => $this->translate('Email Address'), 
	'UserURL' => $this->translate('User URL'),
	'SIP' => $this->translate('SIP'),
);

$emailTranslationHash = array(
	'UserEmail' => $this->translate('User Email 1'),
	'UserEmail2' => $this->translate('User Email 2'),
	'UserEmail3' => $this->translate('User Email 3'),
	'UserEmail4' => $this->translate('User Email 4'),
	'UserEmail5' => $this->translate('User Email 5')
);

?>
<script type="text/javascript">
</script>
<?php 	if( is_array($this->contact) ) : ?>
<table id="contact_table">
<tbody>
	<tr>
		<td alt="Contact photo" class="photo photoEditable photoHelpText" title="<?php print addslashes($this->translate('Click to change the picture')) ?>">
			<div id="UserPhoto" style="width:69px">
				<img id="Photo" alt="User Photo" src="<?php echo $this->moduleBaseUrl ?>/contacts/viewphoto/<?php if(isset($this->contact['serverID'])) echo 'serverID/' . $this->contact['serverID'] . '/'; ?>id/<?php if(isset($this->contact['serverID'])) echo $this->contact['UID']; else echo $this->contact['id']; ?><?php echo '' . md5( (empty($this->contact['UserPhoto']) ? rand() : $this->contact['UserPhoto']) ); ?>" style='max-height: 80px; max-width: 60px;' tabindex="0" id='Photo'/>
				<span class="photoEditable photoHelpText"><?php print $this->translate('Click to change the picture')?></span>
			</div>
		</td>
		<td>
			<span class="full_name"><label for="UserFirstName" class="offscreen">User first name</label>
				<input style="position:relative;top:0px;left:0px;display:inline" name="contact[UserFirstName]" id="UserFirstName" value="<?php echo addslashes($this->contact['UserFirstName']) ?>" tabindex="0" /><br />
				<script type="text/javascript" language="JavaScript">$("input[name='contact[UserFirstName]']").focus();</script>
				<label for="UserLastName" class="offscreen">User last name</label>
				<input name="contact[UserLastName]" id="UserLastName" value="<?php echo addslashes($this->contact['UserLastName']) ?>" tabindex="0" />
			</span>
		</td>
		<!--
		<img alt="favorites toggle" src="../images/icons/grey-star.png" id="fav-toggle" class="fav-toggle <?php if(isset($this->contact['Favourite']) && $this->contact['Favourite'] == 1) echo 'fav-active'; ?>" tabindex="0" />
		  <label for="favourite" class="offscreen">Mark contact as favorite</label>
			<input type="hidden" id="favourite" name="contact[favourite]" value="<?php echo (isset($this->contact['Favourite']) && $this->contact['Favourite'] == 1 ? 1 : 0); ?>"></input>
			-->
	  <tr>
	</tbody>
<tbody>
<?php $allNumberFields = array('UserHomePhone', 'UserHomeMobile', 'UserWorkPhone','UserHomeFax', 'UserWorkMobile', 'UserWorkFax') ?>
<?php foreach($allNumberFields as $f): ?>
	<tr>
		<td class="contact_field"><label for="<?php echo $f ?>"><?php echo $translationHash[$f] ?></label></td>
		<td class="contact_field_phone">
		  <input tabindex="0" type="text" name="contact[numberValue][]" id="<?php echo $f ?>" value="<?php echo $this->contact[$f] ?>" />
			<input type="hidden" name="contact[numberFieldName][]" value="<?php echo $f ?>" />
		</td>
	</tr>
<?php	 endforeach; ?>
</tbody>
<tbody>
<?php	
	$allEmailFields = array('UserEmail', 'UserEmail2', 'UserEmail3', 'UserEmail4', 'UserEmail5');
	$index = 1;
?>
<?php foreach($allEmailFields as $f): ?>
	<tr>
		<td class="contact_field"><label for="<?php echo $f ?>"><?php echo $translationHash['UserEmail'] ." ".$index++ ?></label></td>
		<td class='contact_field_value'>
			<input tabindex="0" type=text" name="contact[emailValue][]" id="EmailAddress" value="<?php echo $this->contact[$f] ?>" />
			<input type="hidden" name="contact[emailFieldName][]" value="<?php echo $f ?>" />
		</td>
	</tr>
<?php	 endforeach; ?>
</tbody>
<!-- Address div -->
<tr id='UserHome'>
	<td class="contact_field" valign='top'>
		<label for="UserHomeAddress"><?php echo translateHash('Home Address', $translationHash) ?></label>
	</td>
	<td>		
		<input tabindex="0" name="contact[UserHomeAddress]" id="UserHomeAddress" value="<?php echo addslashes($this->contact['UserHomeAddress']) ?>" />
		<!--
		<img tabindex="0" id='deleteUserHome' src="<?php echo $this->siteBaseUrl ?>images/icons/btn_remove.png" width="12" height="12" alt="<?php print $this->translate('remove')?>" style="cursor:pointer">
		<img tabindex="0" id='addUserWork' src="<?php echo $this->siteBaseUrl ?>images/icons/btn_add.png" width="12" height="12" alt="add" onclick="$('#UserWork').css('display', '');$(this).css('display','none')" style="cursor:pointer;  <?php
		if($a+1 < $usedEmailFieldsC || $a+1 == count($allEmailFields) ) echo ' display:none;'	?>">
		-->
		<br/>
		<label for="UserHomeCity" class="offscreen">Home City</label>
		<input tabindex="0" name="contact[UserHomeCity]" id="UserHomeCity" value="<?php echo addslashes($this->contact['UserHomeCity']) ?>" />
		<br/>
		<label for="UserHomeState" class="offscreen">Home State</label>
		<input tabindex="0" name="contact[UserHomeState]" id="UserHomeState" value="<?php echo addslashes($this->contact['UserHomeState']) ?>" />
		<label for="UserHomeZip" class="offscreen">Home Zip Code</label>
		<input tabindex="0" name="contact[UserHomeZip]" id="UserHomeZip" value="<?php echo addslashes($this->contact['UserHomeZip']) ?>" />
		<br/>
		<label for="UserHomeCountry" class="offscreen">Home Country</label>
		<input tabindex="0" name="contact[UserHomeCountry]" id="UserHomeCountry" value="<?php echo addslashes($this->contact['UserHomeCountry']) ?>" />
		<br/>
	</td>
</tr>

<!-- SIP -->
<?php if($this->ucsettings['SIPEnabled']): ?>
<tr>
	<td class="contact_field" valign='top'>
		<?php echo translateHash('SIP', $translationHash) ?>
	</td>

	<td>
		<input tabindex="0" name="contact[SIP]" id="SIP" value="<?php echo addslashes($this->contact['SIP']) ?>" />
	</td>
</tr>
<?php endif ?>

<tr id='UserWork'>
	<td class="contact_field" valign='top'>
		<label for="UserWorkAddress"><?php echo translateHash('Work Address', $translationHash) ?></label>
	</td>
	<td>		
	  
		<input tabindex="0" name="contact[UserWorkAddress]" id="UserWorkAddress" value="<?php echo addslashes($this->contact['UserWorkAddress']) ?>" />
		
		<!-- <img tabindex="0" id='deleteUserWork' src="<?php echo $this->siteBaseUrl ?>images/icons/btn_remove.png" width="12" height="12" alt="<?php print $this->translate('remove')?>" style="cursor:pointer"> -->
		<br/>
		<label for="UserWorkCity" class="offscreen">Work City</label>
		<input tabindex="0" name="contact[UserWorkCity]" id="UserWorkCity" value="<?php echo addslashes($this->contact['UserWorkCity']) ?>" />
		<br/>
		<label for="UserWorkState" class="offscreen">Work State</label>
		<input tabindex="0" name="contact[UserWorkState]" id="UserWorkState" value="<?php echo addslashes($this->contact['UserWorkState']) ?>" />
		<label for="UserWorkZip" class="offscreen">Work Zip Code</label>
		<input tabindex="0" name="contact[UserWorkZip]" id="UserWorkZip" value="<?php echo addslashes($this->contact['UserWorkZip']) ?>" />
		<br/>
		<label for="UserWorkCountry" class="offscreen">Work Country</label>
		<input tabindex="0" name="contact[UserWorkCountry]" id="UserWorkCountry" value="<?php echo addslashes($this->contact['UserWorkCountry']) ?>" />
		<br/>

	</td>
</tr>

<tr id='moreInformation'>
	<td class="contact_field" colspan="2">

		<div tabindex="0" id='expandMoreInfo' title="Toggle more information" class="<?php echo ( empty($this->contact['ExpandMoreOptions']) ) ? "moreinfo" : "lessinfo"; ?>"><span id="expandMoreInfoText"><?php print $this->translate('More Information')?></span></div>
				
	</td>
</tr>

<?php if( !$this->editingOwnProfile && $this->GroupwareZone != 'Off' && $this->SharedAbook == 1 && !isset($this->contact['serverID'])) : ?>
<tr id='moreInformation'>
	<td class="contact_field" colspan="2">

		<div id='expandShared' class="<?php echo ( empty($this->contact['ExpandSharedOptions']) ) ? "moreinfo" : "lessinfo"; ?>"><span id="expandSharedText"><?php echo $this->translate('Shared Permissions') ?></span></div>
				
	</td>
</tr>
<?php endif ?>
</table>

<div class='moreInformationField dividerContact' style='display: <?php echo ( empty($this->contact['ExpandMoreOptions']) ) ? "none" : ""; ?>'></div>
<table class='moreInformationField' style='display: <?php echo ( empty($this->contact['ExpandMoreOptions']) ) ? "none" : ""; ?>'>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserTitle"><?php	echo translateHash('UserTitle', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserTitle]" id="UserTitle" value="<?php echo addslashes($this->contact['UserTitle']) ?>" />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserMiddleName"><?php		 echo translateHash('UserMiddleName', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserMiddleName]" id="UserMiddleName" value="<?php echo addslashes($this->contact['UserMiddleName']) ?>" />
	</td>
</tr>

<?php
$UserDOB = $this->contact['UserDOB'];
$UserDOB = str_replace("0000-00-00", '', $UserDOB);
$UserDOB = str_replace("00:00:00", '', $UserDOB);
?>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserDOB"><?php		 echo translateHash('UserDOB', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserDOB]" id="UserDOB" value="<?php echo $UserDOB ?>" class='datepicker'/>
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserURL"><?php		 echo translateHash('UserURL', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserURL]" id="UserURL" value="<?php echo addslashes($this->contact['UserURL']) ?>" />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserWorkCompany"><?php		 echo translateHash('UserWorkCompany', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserWorkCompany]" id="UserWorkCompany" value="<?php echo addslashes($this->contact['UserWorkCompany']) ?>" />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserWorkTitle"><?php		 echo translateHash('UserWorkTitle', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserWorkTitle]" id="UserWorkTitle" value="<?php echo addslashes($this->contact['UserWorkTitle']) ?>" />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserWorkDept"><?php		 echo translateHash('UserWorkDept', $translationHash) ?></label>
	</td>
	<td>
		<input tabindex="0" name="contact[UserWorkDept]" id="UserWorkDept" value="<?php echo addslashes($this->contact['UserWorkDept']) ?>" />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		<label for="UserInfo"><?php		 echo translateHash('Notes', $translationHash) ?></label>
	</td>
	<td>
		<textarea tabindex="0" id="UserInfo" name="contact[UserInfo]" id='UserInfo'><?php echo $this->contact['UserInfo'] ?></textarea>
	</td>
</tr>

</table>

<?php if( strtolower($this->GroupwareZone) != 'off' && $this->SharedAbook == 1 ) : ?>
<div class='sharedField dividerContact' style='display: <?php echo ( empty($this->contact['ExpandSharedOptions']) ) ? "none" : ""; ?>'></div>	

<table class='sharedField' style='display: <?php echo ( empty($this->contact['ExpandSharedOptions']) ) ? "none" : ""; ?>'>

<tr>
	<td class="contact_field" align='top'>
<?php		 echo $this->translate('Shared Contact') ?>
	</td>
	<td>
		<input tabindex="0" type='checkbox' name="contact[Shared]" id="Shared" class="iPhoneStyle" value="1"<?php if($this->contact['Shared']) echo ' checked'; ?> />
	</td>
</tr>

<tr>
	<td class="contact_field" align='top'>
		Permissions
	</td>
	<td>
		<input tabindex="0" name="contact[Permissions]" id='Permissions' value="<?php echo $this->contact['Permissions'] ?>" />
		<small><?php echo $this->translate('Define a list of local users by email address which will have access to this shared entry.') ?></small>
	</td>	
</tr>

</table>
<?php endif ?>
<div id="back_button" style="width:96px" class='savecontact' style="filter:0;" ><a class="focusable"  tabindex="0" href=""><span class="stronglastword"><?php echo $this->translate('Save Contact') ?></span></a></div>

</form>
<script type="text/javascript" language="JavaScript">
var new_userTextBoxListHandle

function loadAutocomplete()
{
	new_userTextBoxListHandle.getContainer().addClass('textboxlist-loading');
	
	if( $.jCacher.get('autocomplete_global') )
	{
		autocomplete_values = $.jCacher.get('autocomplete_global').value;
		new_userTextBoxListHandle.plugins['autocomplete'].setValues( autocomplete_values )
		
		// above static lookup, enable dynamic lookup
		if(autocomplete_values.length >= <?php echo $this->autocompleteFetchThreshold ?>)
		{
			new_userTextBoxListHandle.plugins['autocomplete'].setOptions( 
				{
					placeholder: false,
					cacheSize: <?php echo $this->autocompleteCacheSize; ?>,
					minRemoteLength: <?php echo $this->autocompleteMinFetchLength; ?>,
					queryRemote: true,
					remote: {url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/type/global/limit/<?php echo $this->autocompleteFetchSize; ?>'}
				});						
		}
		
		new_userTextBoxListHandle.getContainer().removeClass('textboxlist-loading');
	}
	else
	{
	
		$.ajax(
		{
			cache:false, 
			url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/type/global/limit/<?php echo $this->autocompleteFetchThreshold ?>', 
			dataType: 'json', 
			success: function(r) 
			{
				// above static lookup, enable dynamic lookup
				if(r.length >= <?php echo $this->autocompleteFetchThreshold ?>)
				{
					
						new_userTextBoxListHandle.plugins['autocomplete'].setOptions( 
							{
								placeholder: false,
								cacheSize: <?php echo $this->autocompleteCacheSize; ?>,
								minRemoteLength: <?php echo $this->autocompleteMinFetchLength; ?>,
								queryRemote: true,
								remote: {url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/type/global/limit/<?php echo $this->autocompleteFetchSize; ?>'}
							});
				}
				new_userTextBoxListHandle.getContainer().removeClass('textboxlist-loading');
				new_userTextBoxListHandle.plugins['autocomplete'].setValues(r)
				$.jCacher.add('autocomplete_global', r, 3600);
			}			
		})
		
	}	
}
$( function() {
  
	$('#UserPhoto>div', '#Address_Book').unbind().bind('click', function(e) {
		e.preventDefault();
		e.stopPropagation();

		var uploader = $('.attach-holder>input[name=UserPhoto]');
		if(uploader.length) {
			uploader.click();
		}

		return false;
	})

	//iphone style
	$('.iPhoneStyle').iphoneStyle() 
	$('.stronglastword').each( function() { $(this).stronglastword() });
	
	// Add the contactid for a "New" record
	$('.address_row[contactid=]').find('.contactRow').attr('value', '<?php echo $this->contact['id'] ?>');
	$('.address_row[contactid=]').attr('contactid', '<?php echo $this->contact['id'] ?>');
		
	// Configure Ajax uploader for image
	if($('#UserPhoto').size() != 0)
	{
		new AjaxUpload('#UserPhoto',
		{
			// Location of the server-side upload script
			action: "<?php echo $this->moduleBaseUrl ?>/contacts/addphoto",
			// File upload name
			name: 'UserPhoto',
			// Additional data to send
			data: 
			{
				id: '<?php echo $this->contact['id'] ?>',
				GroupID: '<?php if(isset($this->contact["serverID"])) echo $this->contact["serverID"]; ?>'
			},

			addClass: 'contact-img-holder',
			
			//parent: $('#primary #UserPhoto', '#Address_Book'),

			// Submit file after selection
			autoSubmit: true,
			onChange: function(file, extension){ },
			onSubmit: function(file, extension) 
			{ 
	
				if (! (extension && extension.match(/^(jpg|png|jpeg|gif)$/i)))
				{
					// extension is not allowed
					alert('<?php echo addslashes($this->translate('Error: Invalid file extension - Jpeg, PNG or GIF allowed')) ?>');
					// cancel upload
					return false;
				
				}

				// Replace the existing image with a spinner
				$("#Photo").attr('src', '<?php echo $this->siteBaseUrl ?>images/25.gif');
				$("#Photo").hide();
				$($("#Photo")[0]).load(function() { $("#Photo").show(); $("#Photo").css('padding', '18px'); });
		
			},
	
			onComplete: function(file, response) 
			{
				if( response.indexOf('<?php echo addslashes($this->translate('Unable to upload photo')) ?>') != -1 )
					$.simpleFlash(response, 'error'); //alert( response )
				else
				{
					if ( response.indexOf('id=') != -1)
					{

						$('input[name="contact[id]"]').val(response.substring(3));
						$('input[name="contact[id]"]').removeClass('default');

					}
					$('img', '.address_row[contactid=' + $('input[name="contact[id]"]').val() + ']').attr('src', "<?php echo $this->moduleBaseUrl ?>/contacts/viewphoto/id/" + $('input[name="contact[id]"]').val() + "<?php if(isset($this->contact['serverID'])) echo '/serverID/' . $this->contact['serverID']; ?>/resize/1/" + Math.round(Math.random() * 9999));
					$('#Photo').attr('src', "<?php echo $this->moduleBaseUrl ?>/contacts/viewphoto/id/" + $('input[name="contact[id]"]').val() + "<?php if(isset($this->contact['serverID'])) echo '/serverID/' . $this->contact['serverID']; ?>" + Math.round(Math.random() * 9999));
					$($("#Photo")[0]).load(function() { $("#Photo").css('padding', '0px'); });
					
					refreshAccountPhoto();
				}
		  	}

		});
	}
	// Set default lengths
	$('#contactform input:text').attr('maxlength', '128');
	
	// Translations of default state names
	formNames = new Array()
	<?php
	foreach( $translationHash as $hash => &$translation )
		echo "\tformNames['" . $hash . "'] = \"" . addslashes(translateHash($hash, $translationHash)) . "\"\n";
	?>
	// Remove default name suggestions
	$('input, textarea', '#contactform').bind('focus click', function() 
	{
		if( formNames[$(this).attr('id')] && $(this).attr('value') == formNames[$(this).attr('id')] )
		{ 
			
			$(this).attr('value','')
			$(this).select()
			$(this).removeClass('default')
			
		}
		
	})

	$('input:not(#Permissions), textarea', '#contactform').bind('blur', function() 
	{
		//alert(fieldObject.id);
		if( !$(this).attr('value') || $(this).attr('value') == formNames[$(this).attr('id')]) 
		{

			$(this).attr('value', formNames[$(this).attr('id')] )
			$(this).attr('class', 'default')

		}
	})
	//prepopulate empty fields
	$('input, textarea', '#contactform').trigger('blur')

	// Live update the Firstname / Lastname on the view
	$('#UserFirstName', '#contactform').bind('blur', function() 
	{
		
		$('.address_row[contactid=]').attr('contactid', '<?php echo $this->contact['id'] ?>')
		//if defaultvalue then dont update
		if( $(this).attr('value') == formNames[$(this).attr('id')] || $(this).attr('value') == '' )
			var string = '';
		else
			var string = htmlentities($('#UserFirstName').attr('value'))
		$(".address_row[contactid=<?php echo $this->contact['id'] ?>]").find('.first_name').html(string)
	
	})
	
	$('#UserLastName', '#contactform').bind('blur', function() 
	{
		
		$('.address_row[contactid=]').attr('contactid', '<?php echo $this->contact['id'] ?>')
		//if defaultvalue then dont update
		if( $(this).attr('value') == formNames[$(this).attr('id')] || $(this).attr('value') == '' )
			var string = '';
		else
			var string = htmlentities($('#UserLastName').attr('value'))
		$(".address_row[contactid=<?php echo $this->contact['id'] ?>]").find('.last_name').html(string)
	
	})

	// Address handling to remove/set Home defaults
	$('#deleteUserWork').bind('click', function() 
	{
	  $('#addUserWork').css('display','');
		$.each( ['#UserWorkAddress', '#UserWorkCity', '#UserWorkState', '#UserWorkZip', '#UserWorkCountry'], function(i, n) 
		{
		  $(n).attr('value',  formNames[$(n).attr("id")] )
		  $(n).addClass('default')
		})
		$('#UserWork').hide()
	
	})

	// Address handling to remove/set Work defaults
	$('#deleteUserHome').bind('click', function() 
	{
		$.each( ['#UserHomeAddress', '#UserHomeCity', '#UserHomeState', '#UserHomeZip', '#UserHomeCountry'], function(i, n) 
		{
		  $(n).attr('value',  formNames[$(n).attr("id")] )
		  $(n).addClass('default')
		})			
	})

	// Show more information ( Notes )
	$('#expandMoreInfo').bind('click', function() 
	{
		
		if($('.moreInformationField').is(':hidden')) {
			$('.moreInformationField').show();
			$('#expandMoreInfo').removeClass('moreinfo');
			$('#expandMoreInfo').addClass('lessinfo');
		} else {
			$('.moreInformationField').hide();
			$('#expandMoreInfo').removeClass('lessinfo');
			$('#expandMoreInfo').addClass('moreinfo');
		}
		
		 $('#UserInfo').attr('value',  formNames[$('#UserInfo').attr("id")] );
		 $('#UserInfo').addClass('default');
		
	});
	
	if($('#Address_Book li.current').length > 0 && $('#Address_Book li.current').attr('GroupID') == <?php echo GROUP_FAV; ?>)
	{
		$('#Address_Book div.contact-fav').show();
	}

	//Toggle favorite contact
	$(".fav-toggle").click(function(){
		$(this).toggleClass("fav-active");

		if($(this).is(".fav-active"))
		{
			$('div.contact-fav', '.address_row[contactid=' + $('input[name="contact[id]"]').val() + ']').show();
			$(this).attr('src','../images/icons/star-fav.png');
			$fav = 1;
		}
		else
		{
			$('div.contact-fav', '.address_row[contactid=' + $('input[name="contact[id]"]').val() + ']').hide();
			$(this).attr('src','../images/icons/grey-star.png');
			$fav = 0;
		}
		$('#favourite', '#Address_Book').val($fav);
		$.php('<?php echo $this->moduleBaseUrl ?>/contacts/favourite/set/' + $fav + '/id/<?php echo $this->contact['id'] ?>');
	});

	// Show shared information
	$('#expandShared').bind('click', function() 
	{
		loadAutocomplete();
		if($('.sharedField').is(':hidden')) {
			$('.sharedField').show();
			$('#expandShared').removeClass('moreinfo');
			$('#expandShared').addClass('lessinfo');
		} else {
			$('.sharedField').hide();
			$('#expandShared').removeClass('lessinfo');
			$('#expandShared').addClass('moreinfo');
		}

	})
	
	// UserDOB toggle
	$('#UserDOB').datepicker(
		{ 
		showStatus: true, 
		initStatus: 'UserDOB', 
		rangeSelect: false, 
		defaultDate: 'today',
		dateFormat: 'yy-mm-dd',
		yearRange: '-90:+25',
		defaultDate: '-25y', 
		changeMonth: true, 
		changeYear: true,
		onClose: function(dateText, inst) { if(dateText != '') $(this).removeClass('default'); }
    });
	
	if ($.browser.msie && $.browser.version == 7) // ie7 user_div size workaround 
		$("#Permissions", '#contactform').css({width : "76%"})

	//new_userArray = $('#Permissions', '#contactform').attr('value').split(",")
	//new_userArray = unique(new_userArray)
	//$('#Permissions', '#contactform').attr('value', '');
	// this textbox list can't have the unique property!
	new_userTextBoxListHandle = new TextboxList(  $('#Permissions', '#contactform'), {bitsOptions:{editable:{addOnBlur:true}}, plugins: {autocomplete: {placeholder:false, cacheSize: <?php echo $this->autocompleteCacheSize; ?>}}});	
	loadAutocomplete();
	
	// Support clicking anywhere in the div box to get to the last "bitbox selection"
	$('#Permissions', '#contactform').parent().bind('click', function() {
		$("input.textboxlist-bit-editable-input:last", $(this) ).focus()
	})
	
	//automatically slide shared to On if they touch Permissions
	$('#Permissions', '#contactform').parent().bind('focus blur', function() {
		$('#Shared', '#contactform').attr('checked','true')
		$('#Shared', '#contactform').trigger('change')
	})
		
	// bind to the form's submit event and cancel legacy submit 
	$('.savecontact').bind('click', function() {
        var isValidEmail = true;
		$('input#EmailAddress','#contact_table').not('.default').each(function(){
			var email = $(this).val()
			if(email && !email.match(/^[^@ ]+@([a-z0-9\-]+\.)+[a-z]+(.[a-z]+)?$/)) {
				isValidEmail = false;
				return;
			}
		})

		if(!isValidEmail) {
			$.simpleFlash('Email address is invalid!', 'error');
			return false;
		}

		$('form#contactform').submit();
		return false;
	})

	$('form#contactform').submit(function(event) 
	{ 

		if( $(this).attr("action") == false ) 
		{
			alert('<?php echo addslashes($this->translate('Form submission aborted: Action must be set')) ?>');
			return false;
		}
	
		// Set all default values to null, not to pollute the DB with default text
		$(".default").attr('value', '');
		$.php($(this).attr("action"),$(this).serializeArray());
		$.jCacher.remove('autocomplete')
		$.jCacher.remove('autocomplete_global')
	    return false;

	})

<?php
$attr_tmpl = "'%s':'%s'";
$js_contact = "";
$js_attribs = array();

foreach($translationHash as $key => $val){
	if(strlen($this->contact[$key]) > 0){
  	array_push($js_attribs,sprintf($attr_tmpl,$key,addslashes($this->contact[$key])));
	}
}

foreach($emailTranslationHash as $key => $val){
	if(strlen($this->contact[$key]) > 0){
  	array_push($js_attribs,sprintf($attr_tmpl,$key,addslashes($this->contact[$key])));
	}
}

$js_contact = "user_contact = new UserContact({" . join(",",$js_attribs) . "})";
echo $js_contact;
?>

for(var i = 0; i < user_contact.phoneFields.length; i++){
  var type = user_contact.phoneFields[i];
	
	if(user_contact.fieldExists(type)){
		var num  = user_contact.getPhoneNumber(type);
		var ctrl = new PhTypeCtrl(type,num);
		var $tr  = ctrl.getCtrlContainer()
		$tr.find('td:first select').val(type);
		$tr.find('td:first input').val(num);
		
		// $('#contact_phone_numbers').append( $tr );
	}
}

})

// setFocusableElements();
setContactsContextTabOrder();
$('img[class^="contactField"]').keydown( function(e){if(e.which==ENTER_KEY){$(this).click() }} );
$('#fav-toggle').keydown( simulateClick );
$('#expandMoreInfo').keydown( simulateClick )
/* $('#Photo').keypress( simulateClick ); */
$('#UserFirstName').focus();
$('#Photo').keydown(function(e){
  if(e.which == ENTER_KEY){
    var uploader = $('.attach-holder>input[name=UserPhoto]');
    // console.log(uploader)
		$('td#UserPhoto').focus().mouseenter().mouseleave().mouseover();
    // console.log(uploader);
    if(uploader.length) {
      uploader.click();
    }
    return false;
	}
});
</script>

<?php endif; ?>

