/*******************************************************************
*
*	tools.js
*
*	Supports http://www.amittai.com/poetry/tools/assign.php
*
*	Adjusts positions of poems in collections appropriately when
*	user changes the position of an individual poem in a collection.
*
*	Amittai Aviram amittai@amittai.com
*	Begun 21-May-02
*
**********************************************************************/

// Arrays of old and new collection and position values.
var OldOrder = new Array();
var NewOrder = new Array();

// Object representing collection and position of poem.
function Assignment(name, collection, position) {
	this.name = name;
	this.collection = collection;
	this.position = position;
}

// Build an array to save original positions.
function buildOldOrder() {
	var F = document.forms[0];
	var j = 0;
	
	// Every poem listed has a collection select box.
	// Use this to find all the poems and put
	// copies of their info into the OldOrder array.
	for (var i = 0; i < F.elements.length; i++) {
		if (F.elements[i].type == "select-one") {
			
			// Get select value (collection/part).
			var c_name = F.elements[i].name;
			var c_value = F.elements[i].value;
			var n_name = c_name.replace(/c/, "n");
			var n_value = F.elements[n_name].value;
			OldOrder[j++] = new Assignment(n_name, c_value, n_value);
		}
	}
}

function reassign(poem_position) {

	var F = document.forms[0];

	if (F.elements["js_help"].checked) {

		var number = poem_position.name.substr(1);
		var target_collection = F.elements["c" + number].value;
		var original_collection, original_position;
		for (var i = 0; i < OldOrder.length; i++) {
			if (OldOrder[i].name == poem_position.name) {
				original_collection = OldOrder[i].collection;
				original_position = OldOrder[i].position;
			}
		}

		/* Find relevant items in original collection (if it exists)
		* and bump positions down if they are higher than
		* new item's original position. */
		for (var i = 0; i < OldOrder.length; i++) {
			if (OldOrder[i] != "-1_0" &&
				OldOrder[i].collection == original_collection &&
				OldOrder[i].position > original_position) {
				F.elements[OldOrder[i].name].value--;
			}
		}

		buildOldOrder();

		/* Find out what collection the poem is being assigned to.
		* If it is a named collection or Uncollected (i.e., value != -1),
		* bump all position numbers up by 1 in the target collection
		if those position numbers are >= the target position. */

		// Find relevant items in target collection and bump positions up.
		for (var i = 0; i < OldOrder.length; i++) {
			if (target_collection != "-1_0" &&
				OldOrder[i].collection == target_collection &&
				OldOrder[i].position >= poem_position.value &&
				OldOrder[i].name != poem_position.name) {
				F.elements[OldOrder[i].name].value++;
			}
		}
	}

	buildOldOrder();

	return;
}


