// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$(document).ready(function(){
	
	// $("li.current").parents("li").addClass("current");
	var cur_location = window.location.href;
	var cur_max_length = -1;
	var cur_best_match = null;
	$("ul.sf-menu li ul a").each(function(index, element){
		if (this.href.length >= cur_max_length) {
			var match = cur_location.match(RegExp.escape(this.href));
			if (match) {
				var match_length = match[0].length
				if (match != null && match[0].length > cur_max_length) {
					cur_max_length = match_length;
					cur_best_match = this
				};
			};
		};
	});
	$(cur_best_match).addClass("current").parents("li").addClass("current");
	
	$("ul.sf-menu").superfish({
		pathClass:  'current',
		pathLevels: 2,
		dropShadows: false,
    delay: 1600
	});
	
	$("input.calendar").datepicker({
		closeAtTop: false,
		dateFormat: 'yy-mm-dd'
	});
	
	$("input.calendar_range").datepicker({
		closeAtTop: false,
		dateFormat: 'yy-mm-dd',
		changeMonth: true,
		changeYear: true,
		minDate: '-1y',
		maxDate: '+4y'
	});
	
	
	$('.pp-email-check-box').bind('click', function(){
	  if ($(this).attr('checked')) {
	    $(this).nextAll("div").show();
	  } else {
	     $(this).nextAll("div").hide();
	  }
	});
	
	$('.toggle-people').bind('click', function(){
	  $(this).nextAll('ul').find("input:checkbox").each(function(i){
	    if ($(this).attr('checked')) {
          $(this).attr('checked', false);
  	  } else {
          $(this).attr('checked', true);
  	  }
	  });
	  return false;
	});
	
	$('.collaspable').live('click', function(){
	  $(this).nextAll('div.toggleable').toggle();
	})
	
	$('#patroller-test-questions').sortable({
	  opacity: 0.6,
	  handle: '.grippie',
	  update: function(event, ui){
	    new_position = ui.item.prevAll('fieldset').length + 1
	    question_id = ui.item.attr('id').match(/\d+$/);
	    path = window.location.pathname.replace(/edit$/, 'update_position');
	    $.post(path, "_method=put&question_id="+question_id+"&position="+new_position);
	  }
	});
	
});

$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}


