$(function(){
  $('label[for]').fable()
  $.navi()
  $.thunder()
})

// Fading Label - Fable 0.1
jQuery.fn.fable = function(){
  return this.each(function(){
    var label = $(this)
    var input = jQuery('#' + label.attr('for'))
    input.bind({
      'focusin': function(){
        if (input.val() == '') label.fadeTo('fast', 0.5)
      },
      'focusout': function(){
        if (input.val() == '') label.fadeTo('fast', 1)
      },
      'keydown': function(e){
        if (e.keyCode != 9 || e.keyCode != 13) label.hide()
      },
      'keyup': function(e){
        if (input.val() == '' && e.keyCode == 8) label.fadeTo('fast', 0.5)
      }
    })
  })
}

// Modals - Navi 0.1
// Usage:
//    $.navi()
//    <a href="{fallback_url}" data-modal="{ID_of_modal}">Hey! Listen!</a>

jQuery.navi = function(){
  jQuery('[data-modal]').click(function(e){
    e.preventDefault()
    var modal = jQuery('#' + $(this).attr('data-modal'))
    
    // Create overlay mask
    var overlay = jQuery('<div>', {
      'class': 'overlay',
      'css': {
        'background-color': '#000',
        'opacity': 0.85,
        'position': 'fixed',
        'width': '100%',
        'height': '100%',
        'top': 0,
        'left': 0,
        'z-index': 1000,
        'display': 'none'
      }
    })

    // Close modal when overlay or close link is clicked    
    var close = function(){
      overlay.remove()
      modal.hide()
    }
    
    overlay.click(close)
    modal.find('[href="#close"]').click(function(e){
      e.preventDefault()
      close()
    })
    
    // Position modal
    modal.css({
      'position': 'fixed',
      'top': '50%',
      'left': '50%',
      'margin-left': -Math.floor(modal.width() / 2),
      'margin-top': -Math.floor(modal.height() / 2),
      'z-index': 1001
    })

    modal.show()
    
    // Let there be light
    overlay.appendTo(document.body).fadeIn()
  })
}

// Flash Notices - Thunder 0.1
// Usage:
//    $.thunder(html_or_text, custom_class)
//    $.thunder('<strong>Login or Password invalid</strong>', 'error')

jQuery.thunder = function(){
  // Fetch flash element
  var flash = jQuery('.flash')
  
  flash.css({
    position: 'fixed', 
    top: 0,
    'z-index': 2000
  })
  
  flash.detach().appendTo(document.body)
  
  // Hide flash after 4 seconds
  setTimeout(function(){
    flash.animate({
      top: -flash.outerHeight(),
      opacity: 0
    }, 300, function(){ flash.hide })
  }, 4000)
}

