<div id="primary_header" class="mainLayoutHeaderReset">
	<h1>
		<?php echo $this->params['calendar_name']; ?> > <?php print $this->translate('Edit Permissions')?>
	</h1>
	<div id="back_button" class="savecontact" style="width:120px"  onclick="save_and_exit(true);"><a href="#"><span><?php echo $this->translate('Save') ?> <strong><?php echo $this->translate('Settings') ?></strong></span></a></div>
</div>


<div id="primary_content" class="mainLayoutContentReset">
	<div id="primary_content_inner">
		<form id="calSettingsForm" method="post">
			<input type="hidden" name="save" value="1" />
			<table class="settings">
				<?php if ($this->params['display_urls']) : ?>
				<tr>
					<td class="label"><label for="calDavAccountManagement"><?php print $this->translate('Calendar URIs')?></label></td>
					<td><label class="label"><?php print $this->translate('Server URL (iCal)')?> : <?php echo $this->params['server_url'] ?></label></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><label class="label"><?php print $this->translate('Principal URL')?> : <?php echo $this->params['principal_url'] ?></label></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><label class="label"><?php print $this->translate('Calendar URL')?> : <?php echo $this->params['calendar_url'] ?></label></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td>
						<small><?php print $this->translate("Please use the above suggested URI's for your external calendar client software.")?></small>
						<small><?php print $this->translate('Your normal account username and password are required.')?></small>
						<small><?php print $this->translate('For more information please see the <a href="#" onClick="launchHelp();">Calendar help guide</a>'); ?></small>
					</td>
				</tr>
				<?php endif; ?>
<?php if ($this->global['groupwareenable'] != 'off' && $this->supportsDelegates) { ?>
				<tr>
					<td colspan="2"><div class="divider"></div></td>
				</tr>
				<tr>
					<td class="label"><label for="calDavAccountManagement"><?php print $this->translate('Read/Write Calendar Access')?>
					</label></td>
					<td colspan="5">
						<table id="user_div">
							<tbody>
								<tr id="new_user_div">
									<td><input id="new_user" style="padding: 2px;" type="text" />
									</td>
								</tr>
							</tbody>
						</table>
						<small><?php print $this->translate('The above list contains your list of accounts that can read and write to this calendar.')?></small>
					</td>
				</tr>

				<tr>
					<td class="label"><label for="calDavAccountManagement"><?php print $this->translate('Read Calendar Access')?>
					</label></td>
					<td colspan="5">
						<table id="read_user_div">
							<tbody>
								<tr id="new_read_user_div">
									<td><input id="new_read_user" style="padding: 2px;" type="text" />
									</td>
								</tr>
							</tbody>
						</table>
						<small><?php print $this->translate('The above list contains your list of accounts that can only read to this calendar.')?></small>
					</td>
				</tr>

				<tr>
					<td class="label"><label for="calDavAccountManagement"></label></td>
					<td colspan="5">
						<small><?php print $this->translate('You may add any user by typing their email address in the above boxes.')?></small>
						<small><?php print $this->translate('You cannot share with external email addresses which some groups will contain.')?></small>
					</td>
				</tr>
				<?php } ?>
			</td>
		</form>

		<div id="modify_calendar_permision_save" class="bottomFormMainButtonArea">
			<div id="back_button" onclick="save_and_exit(true);"><a href="#"><span class="stronglastword">Save<strong> Settings</strong></span></a></div>
		</div>

			

	</div>
</div>
<script type="text/javascript">
	function launchHelp()
	{
		var left = parseInt((screen.availWidth/2) - (700/2));
		var top = parseInt((screen.availHeight/2) - (500/2));

		window.open("<?php echo $this->moduleBaseUrl ?>/settings/help/helpFile/calendar", null, "height=500,width=720,status=yes,toolbar=no,menubar=no,location=no,left=" + left + ",top=" + top);
	}
	
	function refresh_user_perms_list()
	{
		var calendar_url = "<?php echo $this->params['calendar_path']; ?>";
		
		$datastr="&func=getusers";
		$datastr+="&calendar_url=" + calendar_url;
			
		$.ajax({
			type: "POST",
			cache: false,
			url: "<?php echo $this->siteBaseUrl ?>index.php/mail/calendar/caldavglue",
			data: $datastr,
			complete: getusers_completed
			});

	}
	
	function perform_user_binds()
	{	
		$('.textboxlist-bit.textboxlist-bit-box.textboxlist-bit-box-deletable', '#calSettingsForm').each(function() 
		{ 
			if( $(this).text() == "<?php echo $this->account?>")
			{
				$(this).removeClass("textboxlist-bit-box-deletable");
				$(this).children('.textboxlist-bit-box-deletebutton').remove();	
			}
		});
	}
	
	function getusers_completed(XMLHttpRequest, textStatus)
	{
		if(XMLHttpRequest.readyState == 4 && XMLHttpRequest.status == 200)
		{
			if(XMLHttpRequest.responseXML && XMLHttpRequest.responseXML.getElementsByTagName('User'))
			{
				$users = XMLHttpRequest.responseXML.getElementsByTagName('User');
				for (var i = 0; i < $users.length; i ++) {
					var username = $users[i].getAttribute("username");
					if($users[i].getAttribute("permissions") == 'write')
					{
						addUser(username, 'write');
					}
					else
					{
						addUser(username, 'read');
					}
				}
			}
		}
	}
	
	function addusers_completed(XMLHttpRequest, textStatus)
	{
		if(XMLHttpRequest.readyState == 4 && XMLHttpRequest.status == 200)
		{
			if(XMLHttpRequest.responseXML && XMLHttpRequest.responseXML.getElementsByTagName('Error'))
			{
				$users = XMLHttpRequest.responseXML.getElementsByTagName('Error');
				for (var i = 0; i < $users.length; i ++) {
					var usernames = $users[i].getAttribute("Status");
					if(usernames.length > 1)
					{
						usernames = usernames.split(',').join(', ');
						usernames = usernames.slice(0, -2);
						$.simpleFlash('<?php echo addslashes($this->translate('The following addresses were not able to be shared with:')) ?> ' + usernames, 'error');
					}
				}
			}
		}
	}

	function makeDelegate_completed(XMLHttpRequest, textStatus)
	{
		if(XMLHttpRequest.readyState == 4 && XMLHttpRequest.status == 200)
		{
			if(XMLHttpRequest.responseXML && XMLHttpRequest.responseXML.getElementsByTagName('Error'))
			{
			/*	$users = XMLHttpRequest.responseXML.getElementsByTagName('Error');
				for (var i = 0; i < $users.length; i ++) {
					var usernames = $users[i].getAttribute("Status");
					if(usernames.length > 1)
					{
						usernames = usernames.split(',').join(', ');
						usernames = usernames.slice(0, -2);
						$.simpleFlash('<?php echo "The following addresses were not able to be shared with : "; ?>' + usernames, 'error');
					}
				}*/
			}
		}
	}
	
	function deleteUser(username, mode)
	{		
		$datastr="&func=deluser";
		$datastr+="&mode=" + mode;
		$datastr+="&proxy_username=" + myescape(username);
		$datastr+="&calendar_url=<?php echo $this->params['calendar_path']; ?>";
		
		$.ajax({
			type: "POST",
			cache: false,
			url: "<?php echo $this->siteBaseUrl ?>index.php/mail/calendar/caldavglue",
			data: $datastr
		});
	}

				
	var new_userTextBoxListHandle;
	var deleteAction = false;
	var debounce = false;

	function bitRemoveHandler(item) 
	{ 
		if(!debounce && !deleteAction)
		{
			if(confirm("<?php print addslashes($this->translate('Are you sure you want to stop sharing with that user?')); ?>") )
			{
				deleteAction = true;
			}
			else
			{
				deleteAction = false;
			}
		}

		if(debounce)
			debounce = false;
		else
			debounce = true;
	}

	function bitBoxRemoveHandler(item, mode) 
	{
		if(typeof(mode) == 'undefined')
		{
			mode = 'write';
		}
		if(deleteAction)
		{
			deleteAction = false;
			deleteUser(item.value[1], mode);
		}
		else
		{
			addUser(item.value[1], mode);
		}
		debounce = false;
	}

	function bitBoxRemoveHandler_Read(item) 
	{
		return bitBoxRemoveHandler(item, 'read');
	}
	
	
	$(function(){
		
		if ($.browser.msie && $.browser.version == 7) 
		{
			// ie7 user_div size patch
			$("#user_div").css({width : "76%"});
		}
		//deselect_all();
		//enableTextSelection();
		refresh_user_perms_list();

		$('#calSettingsForm').submit(function() {
			return false;
		});
		$('.savecontact').bind("click", function() { return $('#calSettingsForm').submit()})
		
		new_userArray = $('#new_user', '#calSettingsForm').attr('value').split(",");
		$('#new_user', '#calSettingsForm').attr('value', '');
		new_readuserArray = $('#new_read_user', '#calSettingsForm').attr('value').split(",");
		$('#new_read_user', '#calSettingsForm').attr('value', '');
		
		
		/*
		minLength: 3,
			queryRemote: true,
			remote: {url: 'autocomplete2.php'}
		*/
		// this textbox list can't have the unique property!
		new_userTextBoxListHandle = new TextboxList(  $('#new_user', '#calSettingsForm'), {bitsOptions:{editable:{addOnBlur:true}}, plugins: {autocomplete: {placeholder: false,cacheSize: <?php echo $this->autocompleteCacheSize; ?>,}}});
		new_readuserTextBoxListHandle = new TextboxList(  $('#new_read_user', '#calSettingsForm'), {bitsOptions:{editable:{addOnBlur:true}}, plugins: {autocomplete: {placeholder: false,cacheSize: <?php echo $this->autocompleteCacheSize; ?>,}}});
		
		// Support clicking anywhere in the div box to get to the last "bitbox selection"
		$("#new_user_div", '#calSettingsForm').bind('click', function() {
			$("#new_user_div INPUT.textboxlist-bit-editable-input:last", '#calSettingsForm').focus();
		});
		$("#new_read_user_div", '#calSettingsForm').bind('click', function() {
			$("#new_read_user_div INPUT.textboxlist-bit-editable-input:last", '#calSettingsForm').focus();
		});
		new_userTextBoxListHandle.getContainer().addClass('textboxlist-loading');
		new_readuserTextBoxListHandle.getContainer().addClass('textboxlist-loading');
		
		if( $.jCacher.get('autocomplete_global') )
		{
			autocomplete_values = $.jCacher.get('autocomplete_global').value;
			new_userTextBoxListHandle.plugins['autocomplete'].setValues( $.jCacher.get('autocomplete_global').value )
			new_readuserTextBoxListHandle.plugins['autocomplete'].setValues( $.jCacher.get('autocomplete_global').value )
			
			// above static lookup, enable dynamic lookup
			if(autocomplete_values.length >= <?php echo $this->autocompleteFetchThreshold ?>)
			{
				$options = {
						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.plugins['autocomplete'].setOptions( $options );
				new_readuserTextBoxListHandle.plugins['autocomplete'].setOptions( $options );					
			}
		}
		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 ?>)
					{
						$options = {
								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.plugins['autocomplete'].setOptions( $options );
						new_readuserTextBoxListHandle.plugins['autocomplete'].setOptions( $options );
					}
					new_userTextBoxListHandle.plugins['autocomplete'].setValues(r)
					new_readuserTextBoxListHandle.plugins['autocomplete'].setValues(r)
					$.jCacher.add('autocomplete_global', r, 3600);
				}
			})	
		}
		
		
		new_userTextBoxListHandle.getContainer().removeClass('textboxlist-loading');
		new_readuserTextBoxListHandle.getContainer().removeClass('textboxlist-loading');
		
		new_userTextBoxListHandle.addEvent('bitRemove', bitRemoveHandler);
		new_userTextBoxListHandle.addEvent('bitBoxRemove', bitBoxRemoveHandler);
		new_readuserTextBoxListHandle.addEvent('bitRemove', bitRemoveHandler);
		new_readuserTextBoxListHandle.addEvent('bitBoxRemove', bitBoxRemoveHandler_Read);
		
		//need to set a delay because latency of loading other components causes interference
		// Expand the textbox results to the width of the input area for usability
		setTimeout( function() {

			$('.textboxlist-bit-editable-input:first', '#calSettingsForm').focus()

			len = $("#new_user_div", '#calSettingsForm').width(); 
			if(len > 0)
			{
				$('.textboxlist-autocomplete-results', '#calSettingsForm'); 
			}
		}, 200 )
	
	});

	function addUser(username, mode)
	{
		if( username != "<?php echo $this->account?>")
		{
			if(mode == 'write')
			{
				new_userTextBoxListHandle.add(username);
			}
			else
			{
				new_readuserTextBoxListHandle.add(username);
			}
			perform_user_binds();
		}
	}

	function unique(a)
	{
	   var r = new Array();
	   o:for(var i = 0, n = a.length; i < n; i++)
	   {
	      for(var x = 0, y = r.length; x < y; x++)
	      {
	         if(r[x]==a[i]) continue o;
	      }
	      r[r.length] = a[i];
	   }
	   return r;
	}

	function prepare_usernames(inarray)
	{
		var outstring = '';
		var total = 0;
		
		inarray = unique(inarray);
		for(var a =0;a<inarray.length;a++)
		{
			if(inarray[a] != '' && inarray[a] != "<?php echo $this->account; ?>")
			{
				// not the default account, as we can't share with ourselves
				var username = inarray[a];
				outstring += myescape(username) + ',';
				total += 1;
			}
		}
		return outstring;
	}
	
	function alldone()
	{
		var total = 0;
		var users = prepare_usernames($('#new_user', '#calSettingsForm').attr('value').split(","));
		var read_users = prepare_usernames($('#new_read_user', '#calSettingsForm').attr('value').split(","));

		if(users != '')
		{
			$datastr="&func=adduser";
			$datastr+="&proxy_username=" + users;
			$datastr+="&calendar_url=<?php echo $this->params['calendar_path']; ?>";
			$datastr+="&mode=write";
			
		
			$.ajax({
				type: "POST",
				cache: false,
				url: "<?php echo $this->siteBaseUrl ?>index.php/mail/calendar/caldavglue",
				data: $datastr,
				complete: addusers_completed
			});
		}
		if(read_users != '')
		{
			$datastr="&func=adduser";
			$datastr+="&proxy_username=" + read_users;
			$datastr+="&calendar_url=<?php echo $this->params['calendar_path']; ?>";
			$datastr+="&mode=read";
			
			$.ajax({
				type: "POST",
				cache: false,
				url: "<?php echo $this->siteBaseUrl ?>index.php/mail/calendar/caldavglue",
				data: $datastr,
				complete: addusers_completed
			});
		}
			
		tabId = $('#calSettingsForm').parent().parent().parent().attr('id');
		$('a[name="#' + tabId + '"]', '#navMessages').trigger('click');
		FieldInFocus = false;
	}

	function save_and_exit(save)
	{
		alldone();
	}

</script>
