jQuery(document).ready(function() {
	jQuery('a[rel*=facebox]').facebox() 
	$('a[rel*=external]').attr('target', '_blank');
});

//Send a request header of text/javascript with all AJAX requests
jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
});

// Include the authenticity token with all JS requests.

$(document).ajaxSend(function(event, request, settings) {
  if (settings.type == 'GET' || settings.type == 'get' || typeof(AUTHENTICITY_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(AUTHENTICITY_TOKEN);
});

$(document).ready(function() {
		
	// All timestamps should be relatized
  $('span.timestamp').relatizeDate();
  
  // When the user wishes to update a status, display the statuses form...
  $('p.rss a.update-status').click(function() {
    $("#statuses").show();
    $(this).hide();
    return false;
  });
	
	$('div.activity-feed li').mouseover(function() {
	  $(this).find('p.remove').show();
	});
	
	$('div.activity-feed li').mouseout(function() {
	  $(this).find('p.remove').hide();
	});


	$('div.activity-feed li a.delete').click(function() {
	  var parent = $(this).parent().parent().attr('class');
	  var id = parent.split(' ')[0];
	  $("div.activity-feed li." + id).fadeOut();
    $.ajax({ data:"a=b", dataType:'text', type:'delete', url: $(this).attr('href') });
	  return false;
	});
	
	// open id
	$('#sub a.openid').click(function() { 
	  oid_fields = $('#sub *.oid').toggle();
	  auth_fields = $('#sub *.auth').toggle();
    if(oid_fields.css('display') == 'none') {
      // standard auth
      document.cookie = 'authtype=up; expires=Mon, 3 Jan 2012 20:00:00 UTC; path=/;'
      $("form .auth input.focus").focus();
      $(this).html('use OpenID');
    } else {
      // openid auth
      document.cookie = 'authtype=oid; expires=Mon, 3 Jan 2012 20:00:00 UTC; path=/;'
      $("form .oid input.focus").focus();
      $(this).html('use a username/password')
    };
    $("form input[type=text]").attr('value', '');
	});
	
		
	$('#assignments form .new-assignment p a').live('click', function() {
	  $('#assignments form .new-assignment ul.features').slideDown();
	  $(this).fadeOut();
	  return false;
	});
	
	// Dropdowns please
	
	$('#header ul li.drop').mouseover(function() { 
		$(this).find('ul').show();
		$(this).find('a:first').addClass('hover');
		$(this).mouseout(function() { 
			$(this).find('ul').hide();
			$(this).find('a:first').removeClass('hover');
		});
	});
	
	// Focus fields
	
	$('form .focus').focus();
	
	// Activeate assignment access types
	$('#assignments table tbody tr td.access input[type=radio]').click(function() { 
		$(this).parent().parent().find('td.access').removeClass('active');
		$(this).parent().addClass('active');
		value = $(this).attr('value');
		name = $(this).attr('name').split('_')[0];
		id = $(this).attr('name').split('_')[1];
	  url = window.location + '/' + id;
		$(this).after("<img src='/images/spinners/inline_red.gif' alt='' class='spinner' />");
		$(this).hide();
	  $.ajax({data: "assignment["+name+"]="+value, dataType:'script', type:'put', url:url});
	});
	
	
	// E-Mail Address Add
	$('#right .email-addresses .new a').click(function(){ 
	  $('#right .email-addresses .new form, #right .email-addresses .new div.text').toggle();
	  $('#right .email-addresses .new form input.text').focus();
	  return false;
	});
	

	// Default Forms
	
  $('form input.defaulted').focus(function(e) { 
    if($(this).hasClass('defaulted')) {
      $(this).attr('originalValue', $(this).attr('value'));
      $(this).attr('value', '');
      $(this).removeClass('defaulted');
    }
  });
  
  $('form input.defaulted').blur(function(e) { 
    if($(this).attr('value') == '') { 
      $(this).attr('value', $(this).attr('originalValue'));
      $(this).addClass('defaulted');
    }
  });
  
  $("form").submit(function(e) { 
    $(this).find('input.defaulted').attr('value', '');
    if (! $(this).hasClass('noDisable')) {
      $(this).find('input[type=submit]').attr('disabled', 'disabled');
    };
  });
  
	$('input[type=text], input[type=password], textarea').focus(function(){
		$(this).addClass('focused');
	});
	
	$('input[type=text], input[type=password], textarea').blur(function(){
			$(this).removeClass('focused');
		});
	
	$('input[disabled=disabled]').addClass('disabled');

  $('form[rel=remote]').submit(function() { 
		if($(this).hasClass('small-spinner')) { 
    	$(this).find('input[type=submit]').after(" <img src='/images/spinners/inline_red.gif' alt='' class='spinner' />");
		} else {
			$(this).find('input[type=submit]').after(" <img src='/images/spinners/blue_bar.gif' alt='' class='spinner' />");
		}
		data_to_send = $.param($(this).serializeArray());
    request = { data: data_to_send, dataType:'script', type:this.method, url: this.action };
    $.ajax(request);
		return false;
	});

  $('a.errors-refresh').click(function() { 
		$('#hoptoad .list').remove();
		$('#hoptoad .loading').show();
    request = { dataType:'script', type:'get', url: $(this).attr('href') };
    $.ajax(request);
		return false;
	});

	
	$('#ticket-search .filters .filter .title a').click(function() { 
	  parent = $(this).parent().parent();
	  if(parent.hasClass('visible')) {
	    parent.find('input[type=hidden]').attr('value', '0');
	    parent.removeClass('visible');
	    parent.find('input[type=checkbox]').attr('disabled', true);
    } else {
	    parent.addClass('visible');
	    parent.find('input[type=checkbox]').attr('disabled', false);
	    parent.find('input[type=checkbox]').attr('checked', true);
	    parent.find('input[type=hidden]').attr('value', '');
    };
    $("#ticket-search form").submit();
    return false;
	});
	
	$('#right a#advanced').click(function() {
	  $("#ticket-search dl.terms.advanced").toggle();
	  return false;
	});
	
	$('#ticket-search .filters .filter input[type=checkbox]').click(function() { 
	  $("#ticket-search form").submit();
  });
  
  $('#right form#notifications input[type=checkbox]').click(function() { 
    $(this).after(" <img src='/images/spinners/inline_red.gif' alt='' class='spinner' />");
    $(this).hide();
    form = $('#right form#notifications');
		data_to_send = $.param(form.serializeArray());
    request = { data: data_to_send, dataType:'script', type:form.attr('method'), url: form.attr('action'), success:function() { form.find('img').remove(); form.find('input[type=checkbox]').show(); } };
    $.ajax(request);
  });
  
  // Display a message automatically
  
  if($('#content .showmessage a').attr('href')) { 
    jQuery.facebox({ ajax: $('#content .showmessage a').attr('href') + '.dialog' }, 'wide')
  };
  
  // Tabs
  $('#content ul.tabs a[rel=tab]').click(function(){ 
	  // remove classes from other tabs
	  $('#content ul.tabs a[rel=tab]').removeClass('active');
	  $(this).addClass('active');
	  $('div.tabbed').addClass('hidden');
    var target = $(this).attr('href');
    
	  $(target).removeClass('hidden');
	  // activate hidden fields
	  if ($('input[type=hidden].tab-toggler').attr('value') == '1') {
	    $('input[type=hidden].tab-toggler').attr('value', '');
	  } else {
	    $('input[type=hidden].tab-toggler').attr('value', '1');	    
	  };
	  return false;
	});
	
	$('.activity-feed .push a.showhide').click(function() { 
		commits = $(this).parent().parent().find(' .commit.details');
		if(commits.css('display') == 'none') {
			$(this).attr('original_value', $(this).text());
			$(this).parent().addClass('hide');
			$(this).text('hide commits');
			commits.show();
		} else {
			$(this).text($(this).attr('original_value'));
			$(this).parent().removeClass('hide');
			commits.hide();
		}
		return false;		
	});
	
	project_browser = $('#header .preamble div.project-browser');
	
	$('#header .preamble a.project-browser').click(function() {
		project_browser.show("blind", { direction: "vertical" }, 200);
		if ($('#facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', 0)
      .click(function(h) { 
				project_browser.hide("blind", { direction: "vertical" }, 200); 
				$(this).remove();
			})
      .show();
		return false;
	});
	
	$('#header .preamble div.project-browser select').change(function() {
		var v = $(this).attr('value');
		window.location = "/"+v;
		project_browser.fadeOut(200);
	});

	$('#header .preamble div.project-browser li a').click(function() {
		project_browser.fadeOut(200);
	});

  $('#ticket a.add-time').click(function() { 
	  $('#ticket span.add-time').show();
	  $('#ticket span.add-time input').focus();
	  $(this).hide();
	  return false;
	});
	
	$('#right .wiki p select').change(function() {
		var v = $(this).attr('value');
		window.location = v;
	});
	
	$('.hoptoad-tab').click(function() { 
		var area = $(this).attr('href').split('#')[1]
		$('#content .hideable').hide();
		$('#content #' +area).show();
		return false;
	});
	
	$('a[rel=bulktickets]').click(function() {
	  $('#tickets .bulk input[type=checkbox]').attr('checked', '');
	  $('#tickets .bulk select').attr('value', '');
	  $('#tickets .bulk').toggle();
	  return false;
	});
	
	$('#tickets .bulk input[type=checkbox].all').click(function() {

	  if($(this).attr('checked') == false) {
	    $('#tickets .bulk input[type=checkbox]').attr('checked', '');
    } else {
      $('#tickets .bulk input[type=checkbox]').attr('checked', 'checked');
    }
	});

  // Browser Highligh Code
  // Highlight Row
  $('#browser .viewer').each(function() {
    //
    //  Split the two line numbers
    //
    var anchor = window.location.href.split('#')[1];
    if (anchor != null) {
      //
      //  If not multiple lines set end to empty string
      //
      if(anchor.match(/-/)) {
        var begin = anchor.split('-')[0];
        var end   = anchor.split('-')[1];
      } else {
        var begin = anchor
        var end = ''
      }
    
      //
      //  Remove the L
      //
      begin = parseInt(begin.replace(/^L/, ''));
      end = parseInt(end.replace(/^L/, ''));
    
      //
      //  If the numbers both exist and are the wrong way around swap them
      //
      if(begin > end) {
        var temp = begin;
        begin = end;
        end = temp;
      }

      if($('span[class=line L' + begin + ']').length > 0) {
        first_line = $('#browser .viewer table tr td span[class=line L' + begin + ']')
        first_line.addClass('hl');
        if($('span[class=line L' + end + ']').length > 0) {
          first_line.nextAll().each(function() {
            $(this).addClass('hl')
            if($(this).hasClass('L' + end)) {
              return false;
            }
          })
        }
      }
    }
    
  });

  $('input[name=submitFormat]').click(function() {
    var input = "<input type='hidden' name='format' value='" + $(this).attr('rel') + "' />"
    $(this).before(input);
  });

});


// Submit Facebox Forms

$(document).bind('reveal.facebox', function() { 
	SetupFacebox();
});


function SetupFacebox() { 
	// All timestamps should be relatized
  $('#facebox span.timestamp').relatizeDate();
	
	// TODO: remove the massive un-dryness of all this - the form stuff should be in one place and one place only
	
	$('#facebox form').unbind('submit');
	$('#facebox form').submit(function() { 
	  
	  if($(this).attr('enctype') == 'multipart/form-data') {
	    $(this).submit();
	    return true;
	  };
	  
	  $(this).find('input[type=submit]').after(" <img src='/images/spinners/inline_red.gif' alt='' class='spinner' />");
		data_to_send = $.param($(this).serializeArray());
    request = { data: data_to_send, dataType:'script', type:this.method, url: this.action };
    $.ajax(request);
		return false;
	});
	
	$('#facebox .footer a[rel=submit]').unbind('click');
	$('#facebox .footer a[rel=submit]').click(function() {
		$('#facebox form').submit();
		$(this).addClass('submitting');
		return false;
	});
	
	$('#facebox form .focus').focus();
	$('#facebox form .focus').addClass('focused');
	$('#facebox form .focus').blur(function(){ $(this).removeClass('focused'); });
	
	$('#facebox a[rel=close]').unbind('click');
	$('#facebox a[rel=close]').click(function() { 
		$(document).trigger('close.facebox');
		return false;
	});
	
	$('input[type=text], input[type=password], textarea').focus(function(){
		$(this).addClass('focused');
		$(this).blur(function(){
			$(this).removeClass('focused');
		});
	});
	
	// property editor
	$('#facebox #property-editor table.data a.edit').unbind('click');
	$('#facebox #property-editor table.data a.edit').click(function() { 
		var parent = $(this).parent().parent().attr('id');
		// hide all other forms
		$('#facebox #property-editor form').hide();
		// show the form which is appropriate
		$('#facebox #property-editor .edits form#' + parent + '-form').show().effect('highlight', {}, 1000);
		return false;
	});
	
	$('#facebox #property-editor a.cancel').unbind('click');
	$('#facebox #property-editor a.cancel').click(function() { 
		// hide all other forms
		$('#facebox #property-editor form').hide();
		// show the form which is appropriate
		$('#facebox #property-editor form.new').show();
		return false;
	});
	

	$('#facebox #archive-downloader .selection a').click(function() {
		$("#facebox #archive-downloader .generating").show();
		$("#facebox #archive-downloader .selection").hide();
	});
	
	
	$('#facebox .watchers a').click(function() {
    elements_to_hide = $(this).parent().find('a:visible');
    $(this).parent().find('a:hidden').css('display', 'block');
    elements_to_hide.hide();
	  if($(this).attr('rel') == 'add') { var method = 'post'; } else { var method = 'delete'; }  
	  $.ajax({ data:"a=b", dataType:'text', type:method, url: $(this).attr('href') });
	  return false;
	});
	
}

$(document).bind('loading.facebox', function() { 
  // close dropdowns when a facebox is opened (really only useful when the box has been opened via the 
  // menu but heh, might as well happen all the time.)
  $('#header ul li.drop ul').hide();
});
