$(function() {

$.fn.extend({
    Counter: function(givenOptions) {
        return this.each(function() {
            var $this = $(this),
                options = $.extend({
                    maxChars: 100,
					maxCharsWarning: 80,
					stripTags: false,
					msgFontSize: '12px',
					msgFontColor: '#000000',
					msgFontFamily: 'Arial',
					msgTextAlign: 'right',
					msgWarningColor: '#F00',
					msgAppendMethod: 'insertAfter'
                }, givenOptions);
	
			if(options.maxChars <= 0) return;
			
			// create counter element
			var CounterMsg = $("<div class=\"CounterMsg\">&nbsp;</div>");
			var CounterMsgStyle = {
				'font-size' : options.msgFontSize,
				'font-family' : options.msgFontFamily,
				'color' : options.msgFontColor,
				'text-align' : options.msgTextAlign,
				'width' : $this.width(),
				'opacity' : 0
			};
			CounterMsg.css(CounterMsgStyle);
			// append counter element to DOM
			CounterMsg[options.msgAppendMethod]($this);
			
			// bind events to this element
			$this
				.bind('keydown keyup keypress', doCount)
				.bind('change focus paste', function(){setTimeout(doCount, 10);});
				//.bind('blur', function(){CounterMsg.stop().fadeTo( 'fast', 0);return false;});
			
			function doCount(){
				var val = $this.val();
				if(options.stripTags){
					val = stripTags(val);
					$this.val(val);
				}
				//console.info(options.stripTags);
				var	length = val.length;
				
//				if(length >= options.maxChars) {
//					val = val.substring(0, options.maxChars); 				
//				};
				
				if(length > options.maxChars){
					// keep scroll bar position
					var originalScrollTopPosition = $this.scrollTop();
//					$this.val(val.substring(0, options.maxChars));
					$this.scrollTop(originalScrollTopPosition);
				};
				
				if(length >= options.maxCharsWarning){
					CounterMsg.css({"color" : options.msgWarningColor});
				}else {
					CounterMsg.css({"color" : options.msgFontColor});
				};
				
				CounterMsg.html('Оставащи символи: ' + (options.maxChars - $this.val().length));
                CounterMsg.stop().fadeTo( 'fast', 1);
			};
			
			function stripTags(val){
				return val.replace(/<\/?[^>]+>/gi, '');
			}
        });
    }
});

});
