function apostropheReady() 
{
	// -- Pogil Form Error Class & Focus --
	if ($('.a-form-error .error_list:first').length > 0)
	{
		$('.a-form-error .error_list:first').parent().prev().addClass('has-errors'); // Applies error class to .a-form-field
		$('.has-errors :input').focus();
	}
	
	// -- Pogil Sidebar Filters --
	var filterToggles = $('.pogil-filter-sidebar h5');
	filterToggles.attr('title','Click to toggle');
	filterToggles.click(function(){
		$(this).parent().toggleClass('open');
	});
	$('.pogil-filter-sidebar a').prepend('<span class="close"></span>');
	
	// Single-option select elements with that option selected -> static text.
	// Select element sticks around, hidden but submitted
	aSelectToStatic('body');
	pogilDropdown();
};

function pogilDropdown()
{
	// -- Pogil Top Bar Dropdown --
	var aDrop = $('.a-header-dropdown');

	aDrop.prev().click(function(event){
		event.preventDefault();
	});

	var config = {
		over: function()
		{
			$(this).addClass('open');
		}, 
	  timeout: 200, 
	  out: function()
		{
			$(this).removeClass('open');
		}
	};
	
	aDrop.parent().hoverIntent( config );
}


// Convert 'Full Name (username)' to { username: 'username', fullname: 'Full Name' }
function aParseUniqueName(name)
{
	var result = name.match(/^\s*(.*?)\s*\((\w+)\)\s*$/);
	if (result)
	{
		return { fullname: result[1], username: result[2] };
	}
	else
	{
		return false;
	}
}

// Convert a string containing a |-separated list of addresses of
// the form Full Name (username) to [ { username: 'username', fullname: 'fullname' }, { ... }, ... ]

function aParseUniqueNames(to)
{
	var users = [];
	var to = to.split(/\s*\|\s*/);
  // split() returns an array that has an extra 'index' property which shows up
  // if you try to do for (var i in to), ending up in a JS error (at least in Mac Chrome)
  for (var i = 0; (i < to.length); i++)
  {
    var uniquename = to[i];
    var user = aParseUniqueName(uniquename);
		if (user === false)
		{
			continue;
		}
		users[users.length] = user;
	}
	return users;
}

// Add one or more |-separated unique names to an existing list,
// without duplication
function aAddUniqueNames(to, toMore)
{
	var users = aParseUniqueNames(to);
	var moreUsers = aParseUniqueNames(toMore);
	var hash = {};
	for (var i = 0; (i < users.length); i++)
	{
		hash[users[i].username] = users[i];
	}
	for (var i = 0; (i < moreUsers.length); i++)
	{
		if (hash[moreUsers[i].username] === undefined)
		{
			users[users.length] = moreUsers[i];
		}
	}
	return aFormatUniqueNames(users);
}

function aRemoveUniqueNames(to, toLess)
{
  var users = aParseUniqueNames(to);
	var lessUsers = aParseUniqueNames(toLess);
	var newUsers = [];
	var hash = {};
	for (var i = 0; (i < lessUsers.length); i++)
	{
		hash[lessUsers[i].username] = lessUsers[i];
	}
	for (var i = 0; (i < users.length); i++)
	{
		if (hash[users[i].username] !== undefined)
		{
			continue;
		}
		newUsers[newUsers.length] = users[i];
	}
	return aFormatUniqueNames(newUsers);
}

function aFormatUniqueNames(users)
{
	var to = '';
	for (var i = 0; (i < users.length); i++)
	{
		if (i > 0)
		{
			to += '|';
		}
		to += users[i].fullname + ' (' + users[i].username + ')';
	}
	return to;
}

function viewableLockToggle(){
	$(document).ready(function() {

		$('.viewable_toggle_lock').remove();

		var toggle = $('.viewable_toggle');
		var toggleRow = toggle.parents('.a-form-row')

		toggleRow.hide(); // Hide the Checkboxes

		toggleRow.prev().find('.a-form-field').append('<a href="#" class="viewable_toggle_lock">locked</a><p class="viewable_toggle_lock_text">This field is private. Other POGIL users will not be able to view the information above. Click the lock icon to make this field public.</p>'); // Inject the locks

		var lock = $('.viewable_toggle_lock');
		
		lock.each(function(){
			
			lockID = $(this).prev().attr('id')+'-lock';
			toggleID = $(this).parents('.a-form-row').next().find('input[type="checkbox"]').attr('id');
			lockLabel = $(this).parents('.a-form-row').children('label').html();
			$(this).attr({'id':lockID, 'rel':toggleID}); //We aren't using them but you never know. the locks get semantic ID and Rel tags

			var checkbox = $("#"+toggleID);
			var tooltipLocked = "Unlock "+lockLabel;
			var tooltipUnlocked = "Lock "+lockLabel;			
			
			// Initial setup on DOMReady
			if (!checkbox.attr('checked'))
			{
				$(this).addClass('locked').html('locked').attr('title',tooltipLocked);
				$(this).parents('.a-form-field').addClass('locked');									
			}
			else
			{
				$(this).removeClass('locked').html('unlocked').attr('title',tooltipUnlocked);
				$(this).parents('.a-form-field').removeClass('locked');				
			}

			// Flip states on Click
			$(this).click(function(event){
				event.preventDefault();

				if (!checkbox.attr('checked'))
				{
					checkbox.attr('checked',true);
					$(this).removeClass('locked').html('unlocked').attr('title',tooltipUnlocked);
					$(this).parents('.a-form-field').removeClass('locked');
				}
				else
				{
					checkbox.attr('checked',false);
					$(this).addClass('locked').html('locked').attr('title',tooltipLocked);
					$(this).parents('.a-form-field').addClass('locked');					
				}
			});
		})
		
	});
}


function pogilRosterContactInfo(options)
{
	var people = $('.user-listing-row li.name');
	
	people.each(function(){
		var person = $(this);
		var personInfo = person.children('div.contact-info');
	
		if (!personInfo.find('li').length) // Remove any contact boxes without contact information
		{
			personInfo.remove();
		}
		
		function personShowInfo()
		{
			person.css('z-index',999);
			personInfo.show();			
		}

		function personHideInfo()
		{
			person.css('z-index',1);			
			personInfo.hide();			
		}

		person.hoverIntent(personShowInfo, personHideInfo);

	});
}

function pogilRosterExpandToggles()
{
	var userRow = $('.user-listing-row');

	userRow.addClass('closed'); // They all start closed
	userRow.find('.user-listing-rsvp-info').addClass('hidden'); //Grab the LI's that aren't the first one and Class them hidden (CSS hides them)

	userRow.each(function(){
		var row = $(this);
		roleCount = row.find('.hidden'); // collect the hidden fields and count them
		if (roleCount.length && !row.find('.pogil-roster-controls').length) 
		{
			$(this).find('.name').prepend('<div class="pogil-roster-controls"><a href="#" onclick="return false;" class="expand-all">expand</a><a href="#" onclick="return false;" class="collapse-all">collapse	</a><div class="pogil-toggle-arrow">Toggle</div></div>'); // only apply toggle arrows to the user rows with extra hidden fields
		};		
	});
	
	$('.pogil-roster-controls').mouseenter(function(){
		$(this).addClass('over').siblings('.contact-info').hide();
	}).mouseleave(function(){
		$(this).removeClass('over').siblings('.contact-info').hide();
	});

	$('.pogil-toggle-arrow').click(function(){
		$(this).parents('.user-listing-row').toggleClass('closed'); 
	});
	
	$('.expand-all').click(function(){
		$('.user-listing-row').removeClass('closed'); 			
	});

	$('.collapse-all').click(function(){
		$('.user-listing-row').addClass('closed'); 			
	});
}

function pogilRosterRolesForPrint()
{
	var userRowForm = $('.user-listing-form');
	var userRowFormSelects = userRowForm.find('select');
	userRowFormSelects.each(function()
	{
		var className = $(this).val().replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
	 	if (!$(this).next().length) 
		{
			$(this).after('<span class="for-print-value ' + className + '">' + $(this)[0].value + '</span>');				
		};
	});
}

function rosterEmail(to, template)
{
  if (template === undefined)
  {
    template = '';
  }
  $('#email-form').fadeIn("slow");
	$('#email_subject').focus();

  var to = aAddUniqueNames($('#email_to').val(), to);
  $('#email_to').val(to);
  var m = $('#email_message');

  if ((template && template.length) || (!m.val().length))
  {
    m.val(template);
  }
  var toVisible = '';
  // Rick doesn't like the raw uniquename microformat as something to show end users,
  // so reformat it pretty. Also add a way to delete someone
  var first = true;
  var users = aParseUniqueNames(to);
  for (var i = 0; (i < users.length); i++)
  {
    if (first)
    {
      first = false;
    }
    else
    {
      toVisible += "";
    }
    // <?php // Do not remove email_username or tamper with its contents (just the username), ?>
    // <?php // I need it to figure out who is being removed from the list ?>
    toVisible += ('<span class="email-address"><span class="email_fullname">' + users[i].fullname + '</span> <span class="email_username">(' + users[i].username + ')</span> <a href="/#remove-email-address" class="a-ui a-btn icon no-label a-close email_remove"><span class="icon"></span>Remove</a></span>');
  }
  $('#email_toVisible').html(toVisible);
  $('#email_toVisible .email-address').click(function() {
    var username = $(this).find('.email_username').text();
    // We don't really need the full name to remove a username
    $('#email_to').val(aRemoveUniqueNames($('#email_to').val(), 'dummy ' + username));
    $(this).remove();
    return false;
  });
}

function pogilCheckForUnsavedChanges()
{
	// <?php // Use the standard dialog box to warn users before they leave with unsaved changes. ?>
  // <?php // Before you ask, no, it can't be changed or customized. It's a hardcoded browser ?>
  // <?php // feature that tries to prevent fraud while still giving you a chance to say no to ?>
  // <?php // leaving the page ?>

  // <?php // Wrap it mostly for the closure so we don't have to worry about namespacing the variable ?>
  
	var changed = false;

  // <?php // Trigger this conservatively, it can be very annoying if it goes off needlessly ?>
  $('#event_update_roster .role select,#event_update_roster .status select,#event_evaluate_users .evaluation select').change(function() {
    changed = true;
  });

  $('#event_update_roster .reset,#event_evaluate_users .reset').click(function() {
    changed = false;
    return true;
  });

  $('#event_update_roster .submit,#event_evaluate_users .submit').click(function() {
    changed = false;
    return true;
  });

  window.onbeforeunload = function() {
    if (changed)
    {
      return "Are you sure? Any unsaved role, status or evaluation changes will be lost.";
    }
    else
    {
      return undefined;
    }
  }
}
