//
// Utility to enable external links in new window.  
//

var LinkHandler = {

  init: function() 
  {
    $('a.ext').click(function(){ window.open(this.href); return false; });
    $('a[href$=".pdf"]').click(function(){ window.open(this.href); return false; });
  }
  
};

$(document).ready(LinkHandler.init);

// 
// Alias Completion
//

var AliasCompletion = {
	
	init:function()
	{
		// variable is so that the ajax request is only fired on the first time you complete the text box
		var name_entered = 0;
		
		// put the link in properly
		$('.permalink-helper').hide();
		$('#edit-alias').hide();
		$('#edit-buttons').html('<span><a href="#" rel="edit"><img src="' + web_root + '/admin/images/pencil.png" alt="edit" title="edit" /></a></span><span class="hidden"><a href="#" rel="save"><img src="' + web_root + '/admin/images/accept.png" alt="save" title="save" /></a> <a href="#" rel="cancel"><img src="' + web_root + '/admin/images/cancel.png" alt="cancel" title="cancel" /></a></span>');
		$('#edit-buttons').show();
		$('#editable-alias').show();
		
		// show if there is already an alias (ie editing), and prevent auto firing if the name/title is edited
		if ($('input#alias-creator').val() != '') {
			name_entered = 1;
			$('.permalink-helper').show();
		}
		
		// when focus is lost, if it is the first time, then firs off the request auto
		$('input#alias-creator').blur(function()
		{
			if (name_entered == 0){
				AliasCompletion.updateAlias($('input#alias-creator').val());
				name_entered = 1;
			}
		});
		
		// when clicking a button
		$('#edit-buttons a').live('click', function()
		{	
			// need to know which button
			var rel = $(this).attr('rel');

			// show/hide the alias text box, and hint
			$('#editable-alias').toggle();
			$('#edit-alias').toggle();				
			
			if (rel == 'edit') {
				$('#edit-buttons span').toggleClass('hidden');
			} else {
	
				if (rel == 'save'){
					AliasCompletion.updateAlias($('input#alias_sample').val());
					name_entered = 1;
				} else if (rel == 'cancel'){				
					$('#edit-alias input').attr('value',$('input#alias').val());
				}
				$('#edit-buttons span').toggleClass('hidden');	
			}		
			
			
			return false;	
		});
		
	},
	
	// is called to set the alias
	updateAlias : function(alias)
	{
		
		// only bother if it has changed
		if (alias != $('input#alias_original').val()) {

			alias = alias.toLowerCase().replace(/[^a-z0-9]+/,'-');
	
		  	// set the new alias in all the right places
	        $('#editable-alias').text(alias);
	        $('input#alias_sample').val(alias);	
	        $('input#alias').val(alias);
	        // get rid of on screen hint, as the alias hint will act as this
			$('#primary .confirmation').html('');
			// finally, if it is still hidden show the helper
			$('.permalink-helper').show();
      			    		
		}
	}
	
}
$(document).ready(AliasCompletion.init);
