$(function() {
  
  // Autocomplete Awesomeness
	function format(item) {
	  if (!item.company.city && !item.company.state)
    	return item.company.name	
		else
  		return item.company.name + " (" + item.company.city +", " + item.company.state + ")";
	}
	
	$("#company-search").autocomplete('/companies/autocomplete.js', {
		matchContains: true,
		parse: function(data) {
			return $.map(eval(data), function(row) {
				return {
					data: row,
					value: row.company.name,
					result: row.company.name
				}
			});
		},
		formatItem: function(item) {
			return format(item);
		}
	}).result(function(e, item) {
		$("#suggestions").empty().append('<input type="hidden" name="dispute[company_ids][]" value="'+ item.company.id +'">');
	});
  
  $('input:text').hint();
  
  $('#disputes .dispute-content').hide();

  $('.dispute .dispute-content').hide();

  $('.dispute-header .details').click(function(event){
    event.preventDefault();
    var id = $(this).parent().parent().parent().attr('id');
    $('#'+id+' .dispute-content').slideToggle('fast');
    $('#'+id+' .dispute-header').toggleClass('active');
  });

  $('.vcard div').hide();

  $('.vcard .more').click(function(){
    var id = $(this).closest('[id]').attr('id');
    $('#'+id+' div').slideToggle('fast');
    $('#'+id+' .more').toggleClass('active');
  });

  $('#new-company').hide();
  
  // Choose or create a company
  $('#claim-new-company').click(function(event){
    event.preventDefault();
    $('#new-dispute-form').hide();
    $('#new-company').show();
  });
  
  $('#claim-choose-company').click(function(event){
    event.preventDefault();
    $('#new-company').hide();
    $('#new-dispute-form').show();
  });
  
  var options = {
    clearForm: true,
    dataType: 'json',
    success: processJson
  };
  
  function processJson(data) {
    $('#new-company').hide();
    $('#new-dispute-form').show();
    $('#company-search').toggleClass('blur').val(data.company.name);
    $("#suggestions").empty().append('<input type="hidden" name="dispute[company_ids][]" value="'+ data.company.id +'">');
  }
  
  $('#new_company').ajaxForm(options);
});