/*
---
name: ExpandableText
description: jQuery plugin for an expandable text block with shortening facility

authors:
  - Magic Web Solutions (http://www.magicwebsolutions.co.uk)

license:
  - MIT-style license

*/

(function($) {
	// jQuery plugin definition
	$.fn.expandableText = function(params) {
		// merge default and user parameters
		params = $.extend( {
			width: 300, 
			height: 45,
			more: '[more...]',
			less: '[less]'
		}, params);
		// traverse all nodes
		this.each(function() {
			// express a single node as a jQuery object
			el = $(this);
			var self = this;
			self.params = params;
			self.longText = el.html();
			self.shortText = '';
			var splitText = self.longText.split(' ');

			el.width(params.width).html('').height('');
			var i = 0;
			var text = '';
			$.each(splitText, function(index, value){
				text += value + ' ';
				el.html(text + params.more);
				++i;
				if (el.height() > params.height) {
					return false;
				} else {
					self.shortText = text;
				}
			});
			if (i < splitText.length)
				lessClick(self, el);
			else
				el.html(self.longText);
		});
		// allow jQuery chaining
		return this;
	};
	
	function moreClick($this, elem) {
		var less = $('<a></a>').html($this.params.less).attr('href','javascript:;').click(function(){
			lessClick($this, elem);
		});
		elem.empty().html($this.longText).append(less);
	}
	
	function lessClick($this, elem) {
		var more = $('<a></a>').html($this.params.more).attr('href','javascript:;').click(function(){
			moreClick($this, elem);
		});			
		elem.empty().html($this.shortText).append(more);
	}
	
})(jQuery);
