/* 
 * Auto Expanding Text Area (1.2.2)
 * by Chrys Bader (www.chrysbader.com)
 * chrysb@gmail.com
 *
 * Special thanks to:
 * Jake Chapa - jake@hybridstudio.com
 * John Resig - jeresig@gmail.com
 *
 * Copyright (c) 2008 Chrys Bader (www.chrysbader.com)
 * Licensed under the GPL (GPL-LICENSE.txt) license. 
 *
 *
 * NOTE: This script requires jQuery to work.  Download jQuery at www.jquery.com
 *
 *
 * JMT added (hopefully with success) stop_flow as an option: if you put stop_flow to TRUE (FALSE by default),
 * it will stop writing if you attempt to go bigger than max_height. you can specify a callback that will be triggered in that case,
 * named "overflow_callback"
 *
 *
 */
 
(function(jQuery) {
		  
	var self = null;
 
	jQuery.fn.autogrow = function(o)
	{	
		return this.each(function() {
			new jQuery.autogrow(this, o);
		});
	};
	

    /**
     * The autogrow object.
     *
     * @constructor
     * @name jQuery.autogrow
     * @param Object e The textarea to create the autogrow for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/autogrow
     */
	
	jQuery.autogrow = function (e, o)
	{
		this.options		  	= o || {};
		this.dummy			  	= null;
		this.interval	 	  	= null;
		this.line_height	  	= this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
		this.min_height		  	= this.options.minHeight || parseInt(jQuery(e).css('min-height'));
		this.max_height		  	= this.options.maxHeight || parseInt(jQuery(e).css('max-height'));
		this.stop_flow				= this.options.stop_flow && true; // RAJOUTE pour permettre de s'arrêter au moment de dépasser la hauteur.
		this.overflow_callback = this.options.overflow_callback || function(){};
		this.height_changed_callback = this.options.height_changed_callback || function(){};
		this.textarea		  	= jQuery(e);
		
		if(this.line_height == NaN)
		  this.line_height = 0;
		
		// Only one textarea activated at a time, the one being used
		this.init();
	};
	
	jQuery.autogrow.fn = jQuery.autogrow.prototype = {
    autogrow: '1.2.2'
  };
	
 	jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
	
	jQuery.autogrow.fn.extend({
						 
		init: function() {			
			var self = this;
			this.html_temp = '';
			this.textarea.css({overflow: 'hidden', display: 'block'});
			if(this.min_height){
				this.textarea.css({height: Math.max(this.min_height,this.textarea.height())+'px'});
			}
			this.textarea.bind('keypress',function(){}).bind('focus', function() { self.startExpand(); } ).bind('blur', function() { self.stopExpand() });
			this.checkExpand();	
		},
		
		set_temp: function() {
			var self = this;
			if((this.overflow != undefined) && (this.overflow == false)){
				this.html_temp = this.textarea.val();
			}
		},
		
		startExpand: function() {				
		  var self = this;
			this.interval = window.setInterval(function() {self.checkExpand()}, 1);
		},
		
		stopExpand: function() {
			clearInterval(this.interval);	
		},
		
		checkExpand: function() {
			
			if (this.dummy == null)
			{
				this.dummy = jQuery('<div></div>');
				this.dummy.css({
												'font-size'  : this.textarea.css('font-size'),
												'font-family': this.textarea.css('font-family'),
												'width'      : this.textarea.css('width'),
												'padding'    : this.textarea.css('padding'),
												'line-height': this.line_height + 'px',
												'overflow-x' : 'hidden',
												'position'   : 'absolute',
												'top'        : 0,
												'left'		 : -9999
												}).appendTo('body');
			}
			
			// Strip HTML tags
			var html = this.textarea.val().replace(/(<|>)/g, '');
			
			// IE is different, as per usual
			if ($.browser.msie)
			{
				html = html.replace(/\n/g, '<BR>new');
			}
			else
			{
				html = html.replace(/\n/g, '<br>new');
			}
			
			if (this.dummy.html() != html)
			{
				this.dummy.html(html);	
				
				if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height))
				{
					if(this.stop_flow)
					{
						// ICI, on devrait revenir en arrière, en supprimant la dernière action :
						this.overflow = true;
						this.textarea.val(this.html_temp);
						this.overflow_callback();
					}
					else
					{
						this.textarea.css('overflow-y', 'auto');
					}
				}
				else
				{
					this.textarea.css('overflow-y', 'hidden');
					
					this.overflow = false;
					this.set_temp();
					
					if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height()))
					{
						var prev_h = this.textarea.height();
						if(prev_h != Math.max(this.min_height,(this.dummy.height() + this.line_height))){
							if ($.browser.msie)
							{
								// La différence avec les autres est que sous IE, dans le calcul de this.dummy.height(), il ne prend pas en compte les bordures
								// de meme, dans le calcul de this.textarea.height(), il ne prend pas en compte les bordures. Les imprécisions se compensent, et on n'a
								// pas besoin d'inclure le test prev_h != ... dans la condition if($.browser.msie) .
								
								// En toute rigueur, on devrait faire appel aux propriétés borderBottomWidth et borderTopWidth
								this.textarea.animate({height: (Math.max(this.min_height,(this.dummy.height() + this.line_height))+2) + 'px'}, 50);
								this.height_changed_callback();
							}
							else
							{
								this.textarea.animate({height: Math.max(this.min_height,(this.dummy.height() + this.line_height)) + 'px'}, 50);
								this.height_changed_callback();
							}
						}
					}
					
				}
			}
		}
						 
	 });
})(jQuery);