/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
(function($) {
	$.autosize = {
		delay: 50,
		height: 'auto',
		overflow: 'auto',
		remove: false
	};
	
	var els = [];
	var autosize = null;
	var timeout = null;
	
	$.fn.autosize = function(params) {
		if ($.browser.ios || $.browser.android) {
			return this;
		}

		params = $.extend({}, $.autosize, params);
		
		if (typeof(autosize) != 'function') {
			autosize = function() {
				if (!timeout) {
					timeout = setTimeout(function() {
						timeout = null;
						for (var i = 0; i < els.length; i++) {
							var $t = els[i];
							$t.css({
								width: '1px',
								height: $t.height() + 'px',
								overflow: 'hidden'
							});
						}
						for (var i = 0; i < els.length; i++) {
							var $t = els[i];
							var $p = $t.parent();
							var w = $p.width() 
								- Number.parseInt($t.css('border-left-width')) 
								- Number.parseInt($t.css('border-right-width'));
							var d = $t.data('autosize');
							$t.css({
								width: (w > 0 ? w : 0) + 'px',
								height: d.height,
								overflow: d.overflow
							});
						}
						for (var i = 0; i < els.length; i++) {
							var $t = els[i];
							var d = $t.data('autosize');
							if (d.callback) {
								d.callback();
							}
						}
					}, params.delay);
				}
			};
			$(window).resize(autosize);
		}
		
		this.each(function() {
			var $t = $(this);
			if (params.remove) {
				els.remove($t);
			}
			else {
				$t.data('autosize', params);
				if (!els.contains($t)) {
					els.push($t);
				}
			}
		});

		if (!params.remove && params.delay > 0) {
			setTimeout(autosize, params.delay);
		}
		
		return this;
	};
})(jQuery);
