/*
 *	jQuery Curtail 0.7 - Text truncation plugin
 *
 *	Copyright (c) 2011 Ralf Heumann,
 *  JANUS DIE WERBEMANUFAKTUR
 *	http://www.janus-wa.de/
 *
 */

(function($){

	var methods = {

		init : function(o) {

			var options = $.extend({}, $.fn.curtail.defaults, o);
			//var options = $.meta ? $.extend({}, opts, $this.data()) : opts;
			$(this).data('curtail', $.extend({}, options, ($.metadata ? $(this).metadata() : {})));

			return this.each(function() {
				$this = $(this);
				methods.curtail();
			});

		},

		curtail : function(obj) {

			$this = obj ? obj : $this;

			var options		= $this.data('curtail');
			var content		= $this.html();
			var firstElm	= $this.children().filter(':first');
			var text 		= firstElm.html();
			var $thisHeight	= $this.height();
			var splitPos 	= text.indexOf(' ', options.maxChars);
			var fp			= text.substring(0, splitPos);
			var sp			= text.substring(splitPos, text.length)

			$this.attr('height', $thisHeight);
			var cloned = firstElm.clone();
			$this.children().hide();
			firstElm.after(cloned);
			cloned.html(
				fp+'<span class="jc-ellipsis">'+options.ellipsis+
				'</span><span class="jc-hidden">'+sp+'</span>'
			).addClass('jc-curtailed');
			$this.append('<p class="'+ options.moreLinkClass +'"><a href="#">'+ options.moreLinkText +'</a></p>');
			$('.jc-hidden',$this).hide();
			firstElm.remove();

			$('.'+options.moreLinkClass, $this).click(function(e) {
				e.preventDefault();
				var parent = $(this).parent();
				$(this).remove();
				methods.open(parent);
			});
		},

		open : function(obj) {
			var options	= $this.data('curtail');
			//parent.html(c).append('<p class="'+ options.lessLinkClass +'"><a href="#">'+ options.lessLinkText +'</a></p>');
			obj.find('.jc-ellipsis').remove();
			obj.find(':hidden').show(0,function(){
				$('.jc-hidden',obj).replaceWith($('.jc-hidden',obj).html()); // ToDo: Also FadeIn the hidden span and replacing it with its inner HTML.
			});
			obj.append('<p class="'+ options.lessLinkClass +'"><a href="#">'+ options.lessLinkText +'</a></p>');

			$('.'+options.lessLinkClass, obj).click(function(e) {
				e.preventDefault();
				$(this).remove();
				methods.curtail(obj);
			});
		}

	}

	$.fn.curtail = function(method) {

		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'methods ' +  method + ' does not exist on jQuery.curtail' );
		}

	};

	$.fn.curtail.defaults = {
		maxChars:			165,
		moreLinkText:		"more",
		lessLinkText:		"less",
		moreLinkClass:		"jc-link",
		lessLinkClass:		"jc-link",
		ellipsis: "&nbsp;&hellip;"
	};

})(jQuery);
