function getNormalizedContactName(s)
{
	// Drop Symbols, Trim and Case Insensitive
	s = s.replace(/[^\w\d\s]/g, ' ').replace(/^\s\s*/g, '').replace(/\s\s*$/g, '').toLowerCase();
	if(s == '') return s;
	
	// Sort by Lastname, Firstname
	if(s.indexOf(',') == -1)
	{
		// Remove Salutation
		s = s.replace(/m[rs]+\s*/, '');

		// Replace Whitespace with spaces
		s = s.replace(/\s+/, ' ');
		
		var names = s.split(' ');

		if(names.length > 1)
			s = names.pop() + ' ' + names.join(' ');
		else
			s = names[0];
	}

	return s;
}

function getNormalizedCompanyName(s)
{
	// Drop Symbols, Trim and Case Insensitive
	s = s.replace(/[^\w\d\s]/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '').toLowerCase();
	if(s == '') return s;
	
	// format your data for normalization 
	s = s.replace(/^the\s*/, '')

	return s;
}

var positionsForNormalization = ['art director', 'art buyer', 'creative director', 'graphic designer', 'print producer', 'photo editor', 'editor', 'copywriter', 'tv producer', 'vp of', 'director of'];
function getNormalizedJobPosition(s)
{
	s = s.toLowerCase();
	
	for(var i = 0; i < positionsForNormalization.length; i++)
	{
		if(s.indexOf(positionsForNormalization[i]) != -1)
		{
			var ordinal = 5;
			
			if(s.indexOf('managing') != -1 || s == 'creative director') ordinal = 1;
			else if(s.indexOf('group') != -1) ordinal = 2;
			else if(s.indexOf('senior') != -1) ordinal = 3;
			else if(s.indexOf('interactive') != -1) ordinal = 6;
			else if(s.indexOf('assistant') != -1) ordinal = 8;
			else if(s.indexOf('freelance') != -1) ordinal = 9;
			
			return positionsForNormalization[i] + ordinal;
		}
	}

	return s;
}

function getNormalizedHiringRole(s)
{
	s = s.toLowerCase();
	
	if(s.indexOf('decision') == 0) return 1;
	else if(s.indexOf('buyer') == 0) return 2;
	else if(s.indexOf('influence') == 0) return 3;
	else return 4;
}

function chartSortStart()
{
	var table = $(this);

	// Remove class from there being no sort
	table.find('thead th').removeClass('sortNone');
}

function chartSortEnd()
{
	var table = $(this);
	
	// NOTE: :even and :odd are flipped because elements are zero indexed.
	
	// Alternate row backgrounds
	if(table.find('tbody > tr.odd').size() > 0)
	{
		table.find('tbody > tr').removeClass('odd');
		table.find('tbody > tr:even').addClass('odd');
	}
	
	// Change Images matched to backgrounds
	if(table.find("tbody > tr img[src *= '-odd']").size() > 0)
	{
		table.find("tbody > tr:even img[src *= '-even']").each(function(index) { $(this).attr('src', $(this).attr('src').replace('-even', '-odd')); });
		table.find("tbody > tr:odd img[src *= '-odd']").each(function(index) { $(this).attr('src', $(this).attr('src').replace('-odd', '-even')); });
	}
}

$(document).ready(function() {

	$.tablesorter.addParser({ 
		id: 'name', 
		is: function(s) { return false; },	// return false so this parser is not auto detected 
		format: getNormalizedContactName, 
		type: 'text'						// set type, either numeric or text 
	}); 

	$.tablesorter.addParser({ 
		id: 'company', 
		is: function(s) { return false; },	// return false so this parser is not auto detected 
		format: getNormalizedCompanyName, 
		type: 'text'						// set type, either numeric or text 
	}); 

	$.tablesorter.addParser({ 
		id: 'jobposition', 
		is: function(s) { return false; },	// return false so this parser is not auto detected 
		format: getNormalizedJobPosition, 
		type: 'text'						// set type, either numeric or text 
	}); 

	$.tablesorter.addParser({ 
		id: 'hiringRole', 
		is: function(s) { return false; },	// return false so this parser is not auto detected 
		format: getNormalizedHiringRole, 
		type: 'numeric'						// set type, either numeric or text 
	}); 

	var chartSortPersistCalled = new Array();
	$.tablesorter.addWidget({
		// give the widget a id
		id: "sortPersist",

		// format is called when the on init and when a sorting has finished
		format: function(table) {
			var COOKIE_NAME = 'ChartSortPersist';
			var cookie = $.cookie(COOKIE_NAME);
			var options = {path: '/'};

			var data = [];
			var sortList = table.config.sortList;
			var id = $(table).attr('id');

			// If the existing sortList isn't empty, set it into the cookie and get out
			if(sortList.length > 0 && chartSortPersistCalled[id] != undefined)
			{
				if(typeof(cookie) == "undefined" || cookie == null)
				{
					data = {id: sortList};
				}
				else
				{
					data = $.evalJSON(cookie);
					data[id] = sortList;
				}
				
				$.cookie(COOKIE_NAME, $.toJSON(data), options);
			}
			else
			{
				chartSortPersistCalled[id] = true;
				
				if(typeof(cookie) != "undefined" && cookie != null)
				{
					// Get the cookie data
					var data = $.evalJSON($.cookie(COOKIE_NAME));
					
					// If it exists
					if(typeof(data[id]) != "undefined" && data[id] != null && sortList != data[id])
					{
						// Get the list
						sortList = data[id];
						
						// And finally, if the list is NOT empty, trigger the sort with the new list
						if(sortList.length > 0)
							$(table).trigger("sorton", [sortList]);
					}
				}
			}
		}
	});

});