;(function () {

  safeConsoleLogging()
  addjQueryExtensions()
  $(ready)

  function ready () {
    console.log('running global ready')

    // Initialize inputs with placeholder attributes
    $('input[placeholder]').placeholder();   

    // Clicking cancel link clears form
    $('.cancel-submission').click(resetForm)
  }

  // Reset the closest form, including uniform selects
  function resetForm (e) {
    var form, validator

    form = $(this).closest('form').or(null)
    if (!form)  return console.error('.cancel-submission el is not inside a form')  

    // Clear fields and any validation errors
    form[0].reset()
    if (validator = form.data('validator'))  validator.resetForm()
    $.uniform.update('select')
    e.preventDefault()
  }

  // Make console{log,warn,error,info} safe to use everywhere
  function safeConsoleLogging () {
    var c, k, keys = 'log warn error info count'.split(' '), noop = function(){} 
    c = window.console || (window.console = {})
    while(k = keys.pop())  c[k] || (c[k] = noop)
  }

  // Extend jquery with useful stuff
  function addjQueryExtensions () {
    jQuery.fn.extend({
      // Return given value if this jquery's list is empty.
      //
      //  cats = $('.cats').or(null)
      //
      //  // instead of:
      //  cats = $('.cats')
      //  if (!cats.length)  cats = null
      //
      or: function (value) {
        if (this.length)  return this
        return value
      },

      // Throws an error if this jquery's list is empty.
      // Can provide an optional message.
      orThrow: function (msg) {
        if (this.length)  return this
        msg = "Could not find element with selector: `" + this.selector + "`. " + msg
        throw new Error(msg)
      },

      backgroundImage: function (url) {
        return this.css('background-image', 'url("' + url + '")')
      }
    })
  }                   

})();



