$(function(){

	$('.attachment-button').click(function(){

		$('#file-attachment-input').trigger('click');

	});

	$('#file-attachment-input').change(function(){

		var xhr = new XMLHttpRequest, data = new FormData(), files = $('#file-attachment-input')[0].files;

		xhr.open("POST", '/support/file', true);
		xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

		data.append("_csrf", $('meta[name="csrf-token"]').attr('content'));

		$.each(files, function(i, file){
			data.append("files[]", file);
		});

		xhr.send(data);

		xhr.onreadystatechange = function()
	    {
	        if (xhr.readyState == 4)
	        {
	            try
	            {
	                var response = JSON.parse(xhr.responseText);
	            }
	            catch(e)
	            {
	                var response = xhr.responseText;
	            }

	            if(response.success) 
	            {
	            	$('#file-container').append(response.html);
	            }
	        }
	    }        

		$(this).val('');

	});

	$(document).delegate('.file_box_wr .delete-file', 'click', function(){

		$(this).closest('.file_box_wr').remove();

		return false;

	});

});