// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
jQuery(function($) {
  jQuery.ajaxSetup({
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    }
  });

  // source: http://www.justinball.com/2009/07/08/jquery-ajax-get-in-firefox-post-in-internet-explorer/
  jQuery(document).ajaxSend(function(event, request, settings) {
    if (typeof(AUTH_TOKEN) == "undefined") return;
    // This next line is the key!
    if (settings.type.toLowerCase() == 'get') {
      return; // Don't add anything to a get request let IE turn it into a POST.
    }
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });

  jQuery.fn.submitWithAjax = function() {
    this.submit(function() {
      method = jQuery(this).attr('method');
      if(method == "get") {
        jQuery.get(this.action, $(this).serialize(), null, "script");
      } else {
        jQuery.post(this.action, $(this).serialize(), null, "script");
      }
      return false;
    });
    return this;
  };
  jQuery.fn.replace = function(o) { return this.after(o).remove(); };
});


hoverHandle = function() {
  active = '#777';
  passive = '#eee';
  $('li .handle').parent().hover(
    function() {
      $(this).children('.handle').css({'color':active});
    },
    function() {
      $(this).children('.handle').css({'color':passive});
    }
  );
}
setupAutoSubmit = function() {
  $('.autosubmit select').change(function() {
    $(this).parents('.autosubmit').submit();
  });
}
setupPrintLinks = function() {
  $('a#print').click(function() {
    window.print();
    return false;
  })
}
wireUpSearchForm = function() {
  $('#search_form').submitWithAjax(); //.prepend('<input type="text" name="format" value="js" />');

}
$(document).ready(function() {
  hoverHandle();
  setupAutoSubmit();
  setupPrintLinks();
  wireUpSearchForm();
  wireUpMenus();
});


showMenu = function(element) {
  if($('ul', element).css('display') == 'none')
    $('ul', element).show('fast');
}
hideMenu = function(element) {
  if($('ul', element).css('display') == 'block')
    $('ul', element).hide('fast');
}
wireUpMenus = function() {
  $('.menu > li').hover(
    function(){showMenu(this)}, 
    function(){hideMenu(this)}
  );
}

