(function($) {
  Drupal.behaviors.inlineThreadedComments = {
    attach: function(context) {
      // Loop through each comment on the site
      $('.comment', context).each(function(index, comment) {
        // Get the ID of the comment..
        var commentId = parseInt($(comment).attr('id').split(/-/)[1], 10),
            commentTitle = $('.comment-title a', comment).text(),
            replyBtn = $('.comment-reply a', comment) // Find the reply btn..

        // Bind onClick on the btn
        replyBtn.click(function() {
          // Get the user Selection
          var selection = getUserSelection(),
              text      = getSelectionText(selection)

          // Check if the selection is inside the comment whos reply btn was clicked
          if (text) {
            var range        = getRangeObject(selection),
                quoteComment = $(range.commonAncestorContainer).parents('.comment')
            if (quoteComment.length) {
              // Selection is inside of a comment, find the ID of said comment
              var quoteCommentId = parseInt($(quoteComment).attr('id').split(/-/)[1], 10)
              if (commentId != quoteCommentId)
                // The selection doesn't lie in the same comment as the btn
                text = ''
            } else
              // The selection isn't inside of a comment
              text = '';
          }

          var form = $('#comment-form'),
              action = form.attr('action'),
              title = $('#edit-subject', form),
              textarea = $('textarea', form) // TODO: This should find the one named "comment_body[something]",
              existing = textarea.val(),
              quote = '[quote id=' + commentId + ']' + "\n" + text + "\n" + '[/quote]' + "\n"

          form.attr('action', action.replace(/^((.*?)\/comment\/reply\/[0-9]*)(.*)$/, '$1/' + commentId) )
          title.val('Re: ' + commentTitle.replace(/^\s*(Re:\s+)*/, ''))
          if (text)
            textarea.val( existing ? existing + "\n\n" + quote : quote)
          window.location.hash = 'comment-form';
          return false
        })
      })
    }
  }
})(jQuery)

//
// The following three functions are adaptions from QuirksMode
// http://www.quirksmode.org/dom/range%5Fintro.html
//
function getUserSelection() {
    if (window.getSelection)
      return window.getSelection()
    else if (document.selection) // should come last; Opera!
      return document.selection.createRange()
}

function getSelectionText(selectionObject) {
	if (selectionObject.text)
		return selectionObject.text
	else
		return selectionObject.toString()
}

function getRangeObject(selectionObject) {
	if (selectionObject.getRangeAt)
		return selectionObject.getRangeAt(0)
	else { // Safari!
		var range = document.createRange()
		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset)
		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset)
		return range
	}
};
(function ($) {
  Drupal.behaviors.rate = {
    attach: function(context) {
      $('.rate-widget:not(.rate-processed)', context).addClass('rate-processed').each(function () {
        var widget = $(this);
        var ids = widget.attr('id').match(/^rate\-([a-z]+)\-([0-9]+)\-([0-9]+)\-([0-9])$/);
        var data = {
          content_type: ids[1],
          content_id: ids[2],
          widget_id: ids[3],
          widget_mode: ids[4]
        };

        $('a.rate-button', widget).click(function() {
          var token = this.getAttribute('href').match(/rate\=([a-zA-Z0-9\-_]{32,64})/)[1];
          return Drupal.rateVote(widget, data, token);
        });
      });
    }
  };

  Drupal.rateVote = function(widget, data, token) {
    // Invoke JavaScript hook.
    $.event.trigger('eventBeforeRate', [data]);

    $(".rate-info", widget).text(Drupal.t('Saving vote...'));

    // Random number to prevent caching, see http://drupal.org/node/1042216#comment-4046618
    var random = Math.floor(Math.random() * 99999);

    var q = '?q=rate%2Fvote%2Fjs&widget_id=' + data.widget_id + '&content_type=' + data.content_type + '&content_id=' + data.content_id + '&widget_mode=' + data.widget_mode + '&token=' + token + '&destination=' + escape(document.location) + '&r=' + random;
    if (data.value) {
      q = q + '&value=' + data.value;
    }

    $.get(Drupal.settings.basePath + q, function(data) {
      if (data.match(/^https?\:\/\/[^\/]+\/(.*)$/)) {
        // We got a redirect.
        document.location = data;
      }
      else {
        // get parent object
        var p = widget.parent();

        // Invoke JavaScript hook.
        $.event.trigger('eventAfterRate', [data]);

        widget.before(data);

        // remove widget
        widget.remove();
        widget = undefined;

        Drupal.attachBehaviors(p.get(0));
      }
    });

    return false;
  }
})(jQuery);;
(function($) {
  Drupal.behaviors.pressReleases = {
    attach: function(context) {
      $('article.node div.press-release').each(function(i, elem) {
        $(elem).hide().before(
          $('<div>').addClass('press-release-toggle').append(
            $('<a>')
              .text(Drupal.t('Show press release'))
              .click(function(link) {
                $(this).text( $(this).text() ==  Drupal.t('Show press release')
                              ? Drupal.t('Hide press release')
                              : Drupal.t('Show press release'));
                $(elem).slideToggle();
              })
          )
        );
      });
    }
  }
})(jQuery);;

