/**
 * Get the set of section, key and value fields for the page
 * @return {Object}[] An array of section, key, value triplets
 **/
function getDatabaseInputs() {
	var inputs = [];
	$('.database-input').each(function() {
		if ($(this).attr('type') == 'checkbox') {
			inputs.push({section: $(this).attr("data-section"), key: $(this).attr("data-key"),
				value: $(this).is(':checked')});
		} else if ($(this).attr('type') == 'radio') {
			if ($(this).is(':checked')) {
				inputs.push({section: $(this).attr("data-section"), key: $(this).attr("data-key"),
					value: $(this).val()});
			}
		} else {
			inputs.push({section: $(this).attr("data-section"), key: $(this).attr("data-key"),
				value: $(this).val()});
		}
	});
	return inputs;
}

/**
 * Post fields for writing to database
 * @param [{'section' : , 'key' : , 'value'}] inputs Array of triplets to write
 * @param {string} category The category to update processor
 * @return {jqXHR} XMLHttpRequest response of $.ajax() query
 **/
function writeToDatabase(inputs, category) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'writeArray', data: JSON.stringify(inputs), category: category}
	});
}

/**
 * Post a single field to database
 * @param {string} section The section to update
 * @param {string} key The key to update
 * @param {string} value The value to update
 * @param {string} category The category to update
 * @return {jqXHR} XMLHttpRequest response of $.ajax() query
 **/
function writeSingle(section, key, value, category) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'write', section: section, key: key, value: value, category: category}
	});
}

function readDatabase(data) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'readArray', data: JSON.stringify(data)}
	});
}

function readSingle(section, key) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'read', section: section, key: key}
	});
}

function readSection(section, toLower) {
	if (toLower === undefined) {
		toLower = 1;
	}
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'readSection', section: section, toLower: toLower}
	});
}

function deleteFromDatabase(section, key, category) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'delete', section: section, key: key, category: category}
	})
}

function deleteSection(section) {
	return $.ajax({
		type: 'POST',
		url: '/database.php',
		data: {action: 'deleteSection', section: section}
	})
}

function updateProcessor(category) {
	return $.ajax({
		type: 'POST',
		url: '/helpers.php',
		data: {action: 'alertProcessor', alert: category}
	});
}