﻿// plugin definition
$.fn.charactercount = function(options) {

	// Extend our default options with those provided.
	var opts = $.extend({}, $.fn.charactercount.defaults, options);
	// Our plugin implementation code goes here.

	var length = $(this).val().length;

	if (opts.limitCharacters) {
		$(this).parent().find('.counter').html(opts.limitedText.replace(/AmountCharacter/g, length).replace(/MaxCharacter/g, opts.maxCharacters));
	}
	else {
		$(this).parent().find('.counter').html(opts.normalText.replace(/AmountCharacter/g, length));
	}

	$(this).keyup(function() {
		// get new length of characters
		var new_length = $(this).val().length;
		// get new length of words
		//var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;
		// update
		if (opts.limitCharacters) {
			if (new_length > opts.maxCharacters) {
				new_length = opts.maxCharacters;
				$(this).val($(this).val().substr(0, opts.maxCharacters));
			}
			$(this).parent().find('.counter').html(opts.limitedText.replace(/AmountCharacter/g, new_length).replace(/MaxCharacter/g, opts.maxCharacters));
		}
		else {
			$(this).parent().find('.counter').html(opts.normalText.replace(/AmountCharacter/g, new_length));
		}
	});
};

$.fn.charactercount.defaults = {
	limitCharacters: false,
	maxCharacters: 0,
	limitedText: 'Anzahl Zeichen: AmountCharacter von MaxCharacter',
	normalText: 'Anzahl Zeichen: AmountCharacter'
};