////
// zoned
////
// $('element').scrollTo()
// $('element').scrollTo(speed)
$.fn.scrollTo = function(speed) {
  var offset = $(this).offset().top - 30
  $('html,body').animate({scrollTop: offset}, speed || 1000)
  return this
}

////
// $('element').spin()
$.fn.spin = function(append) {
  if (append)
    $(this).append('<img src="http://www.femina.in/images/spinner.gif"/>')
  else
    $(this).after('<img src="http://www.femina.in/images/spinner.gif"/>')
}

////
// generic error and success faceboxes
$.errorBox = function(text) {
  $.facebox('<h2 class="title icon_warning">Whoops</h2>' + text)
}

$.successBox = function(text) {
  $.facebox('<h2 class="title icon_check">Success</h2>' + text)
}

////
// Callback receives responseText and 'success' / 'error'
// based on response.
//
// settings hash:
//   facebox: true        // a facebox 'loading' will open pre-submit
//   confirmation: string // a confirm pop-up will open with the supplied string
//
$.fn.spamjax = function(callback, settings) {
  var settings = settings || {}
  var options  = {}

  options.complete = function(xhr, ok) { callback.call(this, xhr.responseText, ok) }

  if (settings.confirmation) {
    options.beforeSubmit = function() {
      var execute = confirm(settings.confirmation)
      if (!execute) return false
      if (settings.facebox) $.facebox.loading()
    }
  } else if (settings.facebox) { 
    options.beforeSubmit = $.facebox.loading
  }

  // TODO: test this, yo
  $(this).ajaxForm($.extend(settings, options))
  return this
}

////
// Behaviors
$(document).ready(function() {
  ////
  // new conversation scroller
  $('.jump_to_new_conversation').click(function() {
    $('#new-conversation').scrollTo().queue(function() {
      $('#message_subject').focus()
    })
    return false
  })
  
  ////
  // lightbox activation
  if ($.facebox) 
    $('a[rel*=facebox]').facebox({
      next_image    : 'http://www.femina.in/images/fast_forward.png',
      play_image    : 'http://www.femina.in/images/play.png',
      pause_image   : 'http://www.femina.in/images/pause.png',
      prev_image    : 'http://www.femina.in/images/rewind.png'
    }) 
    if ($.facebox) 
    $('a[rel*=vikas1]').facebox({
      next_image    : 'http://www.femina.in/images/fast_forward.png',
      play_image    : 'http://www.femina.in/images/play.png',
      pause_image   : 'http://www.femina.in/images/pause.png',
      prev_image    : 'http://www.femina.in/images/rewind.png'
    })
});

////
// add Accept:text/javascript header to jQuery ajax requests
$.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} })
