$(document).ready(function(){
	$('.int-count').each(function(){
		var c = new IntCount(this);
		c.trigger();
	});
});

var IntCount = function(field){
	this.$field = $(field);
	this.$input = $('.' + this.$field.attr('id'));
	this.value = parseInt(this.$field.text());
	this.max = this.value;
	
	this.$input.attr('maxlength', this.max);
};

IntCount.prototype.trigger = function(){
	this.$input.bind('keydown', {context: this}, IntCount.keyPress);
	this.$input.bind('blur', {context: this}, IntCount.check);
};

IntCount.prototype.refresh = function(ev){
	var c = this;
	
	setTimeout(function(){
		c.value = c.max - c.$input.attr('value').length;
		
		if(c.value < 0 && !c.$field.data('color')){
			c.$field.data('color', c.$field.css('color'));			
			c.$field.css('color', 'red');
		}
		else if(c.value >= 0 && c.$field.data('color')){		
			c.$field.css('color', c.$field.data('color'));
			c.$field.removeData('color');	
		}
		
		c.$field.text(c.value);
	}, 5);
};

IntCount.check = function(ev){
	var c = ev.data.context;
	var l = c.$input.attr('value');
	
	if(l.length > c.max){		
		var v = l.substr(0, c.max);
		var s = c.$input.scrollTop(); 
		c.$input.attr('value', v);
		c.$input.scrollTop(s);
	}
	
	c.refresh(ev);
}

IntCount.keyPress = function(ev){
	var context = ev.data.context;

	context.refresh(ev);
}

IntCount.prototype.$field = null;
IntCount.prototype.$input = null;
IntCount.prototype.value = null;
IntCount.prototype.max = null;




