/**
 * @author Rytis Alekna
 */
( function($) {
	
	/**
	 *	Truncates line to given line number default line number is 1. 
	 * @param {Object} options 
	 * lines : {Number} (default 1)
	 * leading : {String} (default '...') 
	 */
	$.fn.raTextTruncator = function ( options ) {
		
		$(this).each(
			function () {
				truncate( this, options );
			}
		)
		
		return this;
		
	}
	
	function truncate ( ref, options ) {
		
		var that = ref;
		
		var opts = {
			
			lines 	:	1,
			
			leading	: '...'
			
		}
		
		opts = $.extend( opts, options );
		
		var text = $(that).text()
		
		var textLength = text.length;
		
		var fontSize = parseFloat( $(that).css('font-size') );
		
		var lineHeight = $(that).css('line-height');
		
		if ( lineHeight == 'normal' ) {
			lineHeight = 1.2;
		} else {
			
			lineHeight = parseFloat( lineHeight ) / fontSize;
			
		}
		
		var linesCount = Math.floor($(that).height() / ( fontSize * lineHeight ));
		
		if ( linesCount > 1 ) { // && that.scrollHeight > $( that ).height()) {
			
			var sliceLength = textLength / linesCount * ( opts.lines + 1);

			
			text = text.slice( 0, sliceLength );
			
			var cutEnd = ( text.indexOf(' ', sliceLength - 1 ) == -1 ? true : false )
			
			if ( cutEnd ) {
				
				text = text.slice( 0, text.lastIndexOf(' ') );
			} else {
				text = text.slice(0,-1)
			}
			
		} else {
			// text = text.slice( 0, text.lastIndexOf(' ') );
		}
		

		$(that).css('height', Number(fontSize * lineHeight * opts.lines) + 'px' );
		$(that).css('overflow', 'hidden');
		if (text != $(that).text()) {
			$(that).text(text + opts.leading)
		} else {
			$(that).text(text)
		}
				
		var wordsArray = text.split(' ');
		
		while( that.scrollHeight > $( that ).height() && wordsArray.length > 1 ) {
			wordsArray.pop();
			$(that).text( wordsArray.join(' ') + opts.leading );
		}
		
		
	}
	
	
} )(jQuery)

