// Attributes > Classes: Custom DOM Attributes for Fun and Profit
// v1.00 Jan 9/2007 by Pete Forde @ Unspace Interactive
// http://unspace.ca/innovation/attributes/

// This is designed to be a drop-in addition to your application.js.
// Much of this code is adapted/ganked from Prototype v1.5 RC2. Sam is our hero and saviour.

// This code is free, under an MIT attribution license. Please make cool things.

// document.getElementsByAttribute accepts a mandatory attribute to search for, as well as
// an optional second parameter which is the id to search under; it's a lot faster. The function
// returns an array containing the DOM elements that feature your specified attribute. Note that
// it doesn't matter what the value is.

// .pluck re-defines the function built-in to Prototype so that it supports attributes.

// .sum is another enumerables method which will total any numerics in an array. You're welcome.

// $P is a shortcut function which scans your DOM and then plucks the value of an attribute. Ninja!

document.getElementsByAttribute = function(attribute, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.getAttribute(attribute))
      elements.push(Element.extend(child));
    return elements;
  });
}

Object.extend(Enumerable, {
  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value.getAttribute ? value.getAttribute(property) || value[property] : value[property]);
    });
    return results;
  },
	sum: function() {
		var result = 0;
		this.each(function(value, index) {
			if (!isNaN(parseInt(value)))
				result += parseInt(value);
		});
		return result;
	}
});

Object.extend(Array.prototype, Enumerable);

function $P(property) {
  return document.getElementsByAttribute(property).pluck(property);
}