/**
 * Truncator.js - Truncate text by hiding paragraphs
 * 
 * @author  Webstores <info at webstores dot nl>
 *          Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */
function Truncator(el, options) {
	this.el = $(el);
	this.options = options;
	this.toggler = null;
	this.construct();
};

Truncator.prototype = {
	/**
	 * @constructor
	 */
	construct: function() {
		if(this.el.length) {
			this.options = $.extend({
				maxHeight: 0,
				includeMargin: true,
				truncateElements: ['p'],
				excludeElements: [],
				truncateClass: 'truncated',
				togglerClass: 'truncator-toggler',
				togglerRestoreText: 'Toon alle tekst',
				togglerTruncateText: 'Toon minder tekst'
			}, this.options || {});
			
			if(this.options.maxHeight && this.el.outerHeight(this.options.includeMargin) > this.options.maxHeight) {
				this.truncate();
			}
		}
	},
	
	/**
	 * Truncate elements
	 */
	truncate: function() {
		while(this.el.outerHeight(this.options.includeMargin) > this.options.maxHeight) {
			this.el.find(this.options.truncateElements.join(',')).not('.' + this.options.truncateClass + ', ' + this.options.excludeElements.join(', ')).last().addClass(this.options.truncateClass);
		}
		
		this.addToggler();
	},
	
	/**
	 * Restore truncated elements
	 */
	restore: function() {
		this.el.find('.' + this.options.truncateClass).removeClass(this.options.truncateClass);
	},
	
	/**
	 * Append a toggler to restore/truncate elements
	 */
	addToggler: function() {
		if(!this.toggler) {
			var self = this;
			this.toggler = $('<a href="" title="' + this.options.togglerRestoreText + '">' + this.options.togglerRestoreText + '</a>');
			
			this.toggler.click(function(e) {
				e.preventDefault();
				self.togglerClickHandler();
			}).addClass(this.options.togglerClass);
			
			this.toggler.insertAfter(this.el.find(this.options.truncateElements.join(',')).last());
		}
	},
	
	/**
	 * When the toggler fires onclick
	 */
	togglerClickHandler: function() {
		if(this.el.find('.' + this.options.truncateClass).length) {
			this.restore();
			this.toggler.text(this.options.togglerTruncateText).attr('title', this.options.togglerTruncateText);
		}
		else {
			this.truncate();
			this.toggler.text(this.options.togglerRestoreText).attr('title', this.options.togglerRestoreText);
		}
	}
};

