// Application JS

$(function(){
	
	// Ajax tweaks to play nicely with CSRF
  // All non-GET requests will add the authenticity token if not already present in the data packet
  $("body").bind("ajaxSend", function(elm, xhr, s) {
    if (s.type == "GET") return;
    if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
    if (s.data) {
      s.data = s.data + "&";
    } else {
      s.data = "";
      // if there was no data, jQuery didn't set the content-type
      xhr.setRequestHeader("Content-Type", s.contentType);
    }
    s.data = s.data + encodeURIComponent(window._auth_token_name) + "=" + encodeURIComponent(window._auth_token);
  });

	// All ajax requests will trigger the wants.js block of +respond_to do |wants|+ declarations
	jQuery.ajaxSetup({
	  beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); },
	  dataType: 'script'
	});

	/* removed for now
	$('ul#import_items.incomplete').sortable({ opacity: 0.7,
																						 revert: true,
																						 scroll: true,
																						 axis: "y",
	  																				 cursor: "pointer",
																						 items: "li",
																						 placeholder: "empty_item_space",
																				     update: function(event, ui) { $(event.originalTarget).addClass("altered_item_space"); },
																				   	 stop: function(event, ui) {
																							 var ids = $('ul#import_items.incomplete').sortable("toArray").toString();
																							 $.post("/backend/import_batches/" + window._batch_id + "/sort", { items: ids }, null, "script");
																						 }});
	*/
	
	// open box filters
	if($("#filters").is(':visible'))
	{
		$("#filters_trigger_holder").hide();
	}
	else
	{
		$("#filters_trigger").live("click", function(){
			$("#filters").show();
			$("#filters_trgger_holder").hide();
		});
	}
	
	
	// adding new box form on the fly from collections
	$("#remote_box_submit").live("click", function(e){
		e.preventDefault;
		$("#remote_box_form").submit();
	});
	$("#remote_box_form").submit(function(e){
		e.preventDefault();
		
		if($("#box_destruction_date_1i").val() == "" && $("#box_destruction_date_2i").val() == "" && $("#box_destruction_date_3i").val() == "")
		{
			if(!confirm("Are you sure you wish to leave the destruction date for this box empty?")) return false;
		}
		
		$.ajax({ type: "POST",
		 				 url: this.action,
						 data: $(this).serialize(),
						 success: function(response){ $('.no_boxes_message').hide(); $(".errors").hide(); $("#queued_boxes").prepend(response); },
						 error: function(response){ $('.no_boxes_message').hide(); $(".errors").hide(); $("#queued_boxes").prepend(response.responseText); }
		});
		return false;
  });
	
	// select all checkboxes on a row on change
	$('.manage_row').live("change", function(event, element){
		$(this).parent().parent().find("INPUT[type='checkbox']").attr('checked', true);
		// TODO: make it uncheck too
	});
	
	// Auto clear text box
	$(".clear_default").each(function(index, element){
		$(element).focus(function(){
			if(this.value == this.defaultValue) this.value = ''
		})
	})
	
	// For the filtering and searching of boxes within collection/deliveries
	$('#box_searches_remote_form').submit(function(event){
		event.preventDefault();
		
		$.ajax({ type: "POST",
		 				 url: this.action,
						 data: $(this).serialize(),
						 success: function(response){
							 $('#search_results').empty().html(response);
						 },
						 error: function(response){
							 $('#search_results').empty().html(response.responseText);
						 }
		});
		return false;
	});
	
	$('.search_result').live("click", function(event, row){
		// remove no boxes message
		$('.no_boxes_message').hide();
		
		// remove current row and append new row to form
		var current_row = $(this);
		var new_row = current_row.clone();
		
		current_row.remove();
		
		// set the boxes to ignore for future queries
		amendBoxIgnoreList(this.id);
		
		$('#queued_boxes').append(new_row);
	})
	
	function amendBoxIgnoreList(id)
	{
		var list = $('.ignore_boxes').val() ? ($('.ignore_boxes').val() + "," + id) : id;
		$('.ignore_boxes').val(list);
	}
	
	$('#callback_form_wrapper').hide();
	$('.callback_form_trigger').live("click", function(){ $('#callback_form_wrapper').toggle(); });
	
});