﻿(function($) {
    $.fn.truncate = function(options) {

        var defaults = {
            length: 200,
            minTrail: 20,
            moreText: "... more",
            lessText: " ... hide",
            ellipsisText: "",
            moreAni: "",
            lessAni: ""
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
            obj = $(this);
            var body = obj.html();

            if (body.length > options.length + options.minTrail) {

                var splitLocation = body.indexOf(' ', options.length);
                if (splitLocation != -1) {

                    var splitLocation = body.indexOf(' ', options.length);
                    var str1 = body.substring(0, splitLocation);

                    /* adding this space on to the end to seperate the '...more' from the end of the text.  If I add a space in the moreText variable, 
                        it causes a weird bug in IE that requires you to initally click on the '...more' link twice before it'll work. */
                    str1 += " ";
                    
                    var str2 = body.substring(splitLocation, body.length);

                    obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText + '</span>' + '<span class="truncate_more">' + str2 + '</span>');
                    obj.find('.truncate_more').css("display", "none");

                    // insert more link
                    obj.append('<a href="#" class="truncate_more_link">' + options.moreText + '</a>');

                    // set onclick event for more/less link
                    var moreLink = $('.truncate_more_link', obj);
                    var moreContent = $('.truncate_more', obj);
                    var ellipsis = $('.truncate_ellipsis', obj);

                    moreLink.click(function() {
                        if (moreLink.text() == options.moreText) {
                            moreContent.show(options.moreAni);
                            moreContent.show();
                            moreLink.text(options.lessText);
                            ellipsis.css("display", "none");
                        } else {
                            moreContent.hide(options.lessAni);
                            moreContent.hide();
                            moreLink.text(options.moreText);
                            ellipsis.css("display", "inline");
                        }
                        return false;
                    });
                }
            } // end if

        });
    };
})(jQuery);