/*
 * Allows for cropping text and placing a link at
 * the end which toggles display of the full text
 *
 * Author: Mathias Brodala <mathias.brodala@dtele.de>
 */
$(function() {

  $(".ellipsize").each(function() {
  
    var $text = $(this);
    var $original = $text.clone().hide();
    var $ellipseMore = $("<a class='ellipse more' href=''>mehr</a>");
    var $ellipseLess = $("<a class='ellipse less' href=''>weniger</a>");
    var content = $text.html();
    var max = $text.attr("data-ellipsize-max") || 50;
    var cutOff = ($text.attr("data-ellipsize-cutoff") == "true" ? true : false);
    
    if (!cutOff) {
    
      // Make sure to cut before the last word within the text length maximum
      max = content.lastIndexOf(" ", max);
    }
    
    content = content.substr(0, max);
    
    $ellipseMore.click({$text: $text, $original: $original}, function(e) {
    
      e.data.$text.hide();
      e.data.$original.slideDown("fast");
      
      return false;
    });
    
    $ellipseLess.click({$text: $text, $original: $original}, function(e) {
    
      e.data.$original.slideUp("fast");
      e.data.$text.show();
      
      return false;
    });
    
    $text.after($original).html(content);

    // Do not show ellipse if content was completely cut off
    if (content.length > 0) {
    
      $text.append((cutOff ? "" : "&nbsp;") + "…&nbsp;");
    }
    
    $text.append($ellipseMore);
    
    $original.append("&nbsp;")
             .append($ellipseLess);
  });
});
