// Creates the Persapient namespace
var Persapient = {}

// Returns the value of the String as an integer
String.prototype.toInt = function() { return parseInt(this, 10) }

// Helper methods added to Prototype's Element class
Element.addMethods(
{
  // Methods for adding elements before, after, and inside other elements
  insertionBefore: function(element, child) {
    element.parentNode.insertBefore(child, element)
  },
  insertionTop: function(element, child) {
    if (element.hasChildNodes())
      element.insertBefore(child, element.firstChild)
    else
      element.appendChild(child)
  },
  insertionBottom: function(element, child) {
    element.appendChild(child)
  },
  insertionAfter: function (element, child) {
    var nextSibling = element.nextSibling
    if (nextSibling)
      element.parentNode.insertBefore(child, nextSibling)
    else
      element.parentNode.appendChild(child)
  },

  // Methods for determining the top and left offsets of an element relative
  // to the page
  getOffsetTop: function(element) {
    var offsetTop = -(element.clientTop || 0)
    while (element) {
      offsetTop += element.offsetTop + (element.clientTop || 0)
      element = element.offsetParent
    }
    return offsetTop
  },
  getOffsetLeft: function(element) {
    var offsetLeft = -(element.clientLeft || 0)
    while (element) {
      offsetLeft += element.offsetLeft + (element.clientLeft || 0)
      element = element.offsetParent
    }
    return offsetLeft
  }
})

Element.addMethods('table',
{
  // Checks and adjusts the class attributes of the table's rows so that they
  // alternate between 'odd' and 'even'.
  updateAlternatingRowClasses: function(table) {
    var tbody = table.down('tbody')
    var rows = (tbody || table).immediateDescendants()
    var parity = ['odd', 'even']
    rows.each(function(row, index) {
      row.removeClassName(parity[(index + 1) % 2])
      if (!row.hasClassName(parity[index % 2]))
        row.addClassName(parity[index % 2])
    })
  }
})


// JavaScript styles...

// Adjust textarea fonts to match text fields (this can't be done via CSS,
// because the defaults are browser-dependent)
function adjustTextareaFont()
{
  textfield = $$('input[type="text"]').first()
  textareas = $$('textarea')
  if (textfield && (textareas.size() > 0)) {
    textfieldFontFamily = textfield.getStyle('font-family')
    textfieldFontSize = textfield.getStyle('font-size')
    textareas.each(function(textarea) {
      if (textarea.hasClassName('monospaced'))
        textarea.setStyle({fontFamily: 'monospace', fontSize: textfieldFontSize})
      else
        textarea.setStyle({fontFamily: textfieldFontFamily, fontSize: textfieldFontSize})
    })
  }
}

Event.observe(window, 'load', adjustTextareaFont)
