/*
 * jQuery Name Case Plugin
 *
 * Copyright (c) 2011 Imran Nazar <imran@imrannazar.com>
 * Copyright (c) 2011 David Hyland <code@dhyland.com>
 * Copyright (c) 2010 Sean Flanagan <sean@redflannelgroup.com>
 * Based on David Hyland's jQuery toTitleCase2 plugin <http://plugins.jquery.com/project/titlecase2>
 * Which is based on Sean Flanagan's jQuery toTitleCase plugin <http://plugins.jquery.com/project/titlecase>
 * Based in turn on David Gouch's To Title Case Javascript <http://individed.com/code/to-title-case/>
 * Itself based on John Gruber's Title Case Perl Script <http://daringfireball.net/2008/05/title_case, http://daringfireball.net/2008/08/title_case_update>
 *
 * To use, add .namecase() to a selector. NOTE: All elements in the selector must have an ID.
 */
var NameCaseChecksum = {};
(function($) {

	$.fn.toNameCase = function() {
		$(this).each(function(){
		var headline = $(this).val();
		$(this).val(headline.replace(/([\w&`'".@:\/\{\(\[<>_]+-? *)/g,function(match, pl, index, title){
			if (index > 0 && title.charAt(index - 2) !== ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via|der?|van)[ \-]/i) > -1)
				return match.toLowerCase();
			if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1)
				return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
			if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
				return match;
			return match.charAt(0).toUpperCase() + match.substr(1);
		}));
		headline = $(this).val();
		$(this).val(headline.replace(/(Mac|Mc|O')([a-z])/g, function(match, prefix, pl, index, title){
			return prefix + pl.charAt(0).toUpperCase() + pl.substr(1).toLowerCase();
		}));
		});
	};
	$.fn.namecase = function() {
		$(this).each(function(){
		jQuery(this).change(function(){
			var cksum = 0;
			var headline = $(this).val().toLowerCase();
			for (var i=0; i<headline.length; i++) {
				cksum += ((i+1) * (headline.charCodeAt(i)-32));
			}
			if (cksum != NameCaseChecksum[this.id]) {
				NameCaseChecksum[this.id] = cksum;
				jQuery(this).toNameCase();
			}
		});
		});
	};

})(jQuery);


