function init_edit(partID) {
	$('table#details tr#location td p').hide();
	$('#location-dropdown').show();
	$('#container-dropdown').show();

	$('table#details tr#partno td p').hide();
	$('table#details tr#partno td input').show();

	$('table#details tr#description td p').hide();
	$('table#details tr#description td input').show();

	$('table#details tr#datasheet td input').show();

	$('#duplicate-button').closest('div').hide();

	var datasheet_input = $('<input type="file" class="part-edit-file" id="datasheet-input" accept=".pdf">')
	$('#datasheet-info').replaceWith(datasheet_input);

	var newButton = '<div class="round-button-left"><a href="#" onclick="save(' + partID + ')"><i class="fa fa-check" aria-hidden="true"></i></a></div>';
	$('.round-button-left').replaceWith(newButton);
}

function new_entry() {
	$('table#details tr#location td p').text('');
	$('table#details tr#partno td p').text('');
	$('table#details tr#description td p').text('');
	$('table#details tr#partno td input').val('');
	$('table#details tr#description td input').val('');
	container_onchange();
	init_edit(-1);
	overlay_in();
}

function end_edit() {

	$('table#details tr#location td p').text($('table#details tr#location td select option:checked').text());
	$('table#details tr#location td p').show();
	$('#location-dropdown').hide();
	$('#container-dropdown').hide();

	$('table#details tr#partno td p').text($('table#details tr#partno td input').val());
	$('table#details tr#partno td p').show();
	$('table#details tr#partno td input').hide();

	$('table#details tr#description td p').text($('table#details tr#description td input').val());
	$('table#details tr#description td p').show();
	$('table#details tr#description td input').hide();

	$('table#details tr#datasheet td input').hide();

	$('#duplicate-button').closest('div').show();

	var newButton = '<div class="round-button-left"><a href="#" id="edit-button"><i class="fa fa-pencil" aria-hidden="true"></i></a></div>';
	$('.round-button-left').replaceWith(newButton);
}

function save(partID) {
	var location_id_v = $('table#details tr#location td select').val();
	var partno_v = $('table#details tr#partno td input').val();
	var description_v = $('table#details tr#description td input').val();
	var datasheet = $('table#details tr#datasheet td input')[0].files;
	if(partno_v.length == 0){
		alert('Please enter a part number.');
		return;
	}
	if(description_v.length > 200) {
		alert('Description too long (max 200 characters).');
		return;
	}
	if(description_v.length == 0) {
		alert('Please enter a description.');
		return;
	}
	var data = new FormData();

	if (datasheet.length == 1)
		if(! datasheet[0]['name'].match(/^[\w\-]+\.pdf$/g)) {
			alert('Invalid filename. Please match /^[\w\-]+\.pdf$/g');
			return;
		}
		data.append('datasheet-file', datasheet[0]);
	data.append('partno', partno_v);
	data.append('location_id', location_id_v)
	data.append('description', description_v);

	$.ajax({
	        // Your server script to process the upload
	    url: rootURL + 'alter/' + partID,
	    type: 'POST',

      data: data,

      // Tell jQuery not to process data or worry about content-type
      // You *must* include these options!
      cache: false,
      contentType: false,
      processData: false,
			success: function(data) {
				var datasheet_par = '<p id="datasheet-info"><i class="fa fa-check"></i></p>';
				$('#datasheet-info').replaceWith(datasheet_par); // Fix addressing
				$('#edit-button').click(function() {
					init_edit(JSON.parse(data).part_id);
				});
			},
			error: function() {
				alert("Couldn't update the part information. Please retry.");
			}

	  });

	end_edit();
	perform_query();
}

function text_filter(string) {
	if (string != null)
		return string;
	else
		return '';
}

function delete_entry(partID) {
	if (partID < 0)
		return;
	if (!confirm('Delete the selected entry?'))
		return;
	$.ajax({
		url: rootURL + 'delete/' + partID,
		type: 'GET',
		cache: false,
		contentType: false,
		processData: false,
		success: function() {
			overlay_out();
			perform_query();
		},
		fail: function() {
			console.log('An error occurred while deleting the entry');
		},
	});
}

function show_part_info(partID) {
	$.getJSON(rootURL + 'getpartinfo/' + partID, function(data) {
		$('table#details tr#location td p').text(text_filter(data.location_descriptor)); // name is the location friendly name
		$('#location-dropdown').val(data.location_id);
		$('#container-dropdown').val(data.container_id);
		$('table#details tr#partno td p').text(text_filter(data.partno));
		$('table#details tr#partno td input').val(text_filter(data.partno));
		$('table#details tr#description td p').text(text_filter(data.description));
		$('table#details tr#description td input').val(text_filter(data.description));
		container_onchange();
		if (data.datasheet != null) {
			$('tr#datasheet-head').html($('<td>DATASHEET: <a href=""><i class="fa fa-file-text" aria-hidden="true"></i></a></td>'));
		}
		else
			$('tr#datasheet-head td').text('DATASHEET: ');
		$('#edit-button').click(function() {
			init_edit(partID);
		});
		$('#delete-button').click(function() {
			delete_entry(partID);
		});
		overlay_in();
	}).fail(function() {
		console.log( "Fetching part info failed" );
	});
}

function perform_query() {
	$('#no-results').css("opacity", 0);
	var query = $('.search-bar').val();
	var data = {
		l:$('#type').is(':checked'),
		p:$('#partno').is(':checked'),
		d:$('#description').is(':checked'),
		n:$('#notes').is(':checked')
	};
	filter = '0';
	$.getJSON(rootURL + 'query/' + filter  + '/' + query, data, function(data) {
		$("#results").find("tr:not(:first)").remove(); // Delete all table rows
		for(var i = 0; i < data.length; i++) {
			var newRow = $('<tr onclick="show_part_info(' + data[i].id + ')"></tr>');

			newRow.append($('<td id="location"></td>').text(text_filter(data[i].location_descriptor)));
			newRow.append($('<td id="partno"></td>').text(text_filter(data[i].partno)));
			newRow.append($('<td id="description"></td>').text(text_filter(data[i].description)));
			$('#results').append(newRow);
		}
		if(data.length == 0) {
				$('#no-results').animate({opacity:1},2000);
		}
	}).fail(function() {
		var newResults = '<div class="results">';
		newResults += '<h3>No results.</h3>';
		newResults += '</div>';
		$('.results').replaceWith(newResults);
		console.log( "Query failed" );
	});
}

function container_onchange() {
	var selected_container_id = $('#container-dropdown').val();
	if (selected_container_id > 0) {
		$('img#map').attr('src', 'parts/map/' + selected_container_id);
		$('#location-dropdown').empty();
		$.getJSON('parts/getlocationsInContainer/' + selected_container_id,  function(data) {
			$.each(data, function(location_id, location_name) {
				$('#location-dropdown').append('<option val="' + location_id + '">' + location_name + '</option>');
			});
		});
	}
}

$(document).ready(function() {
    $.ajaxSetup({ cache: false });
    $('.search-bar').on('keyup', function() {
			perform_query();
    });
    $('.checkbox').change( function() {
        if (   !$('#location').is(':checked')
            && !$('#partno').is(':checked')
            && !$('#description').is(':checked')
            && !$('#notes').is(':checked'))
		$(this).prop('checked', true);
	else
		perform_query();
    });
});