/*
    public/javascripts/enhance_multifields.js
    Copyright (C) 2008, VaVoca Inc.
    Author: Chad Lester

    This script enhances the HTML generated by the multifields helper.

    NOTE: It is very tightly integegrated with the HTML generated by the
    multifields helper.

    The multifields helper generates a list of select, submit, br tuples.
    The "delete" submit next to each select will delete all three elements.
    There is a final "add" submit that creates a new tuple.

    All SELECT and SUBMIT elements in a multifields group have the classname
    equal to the field name that is being input.  No other elements on the
    document should have this classname.

    The SUBMIT elements have an additional class name of "multifield".

	This script simply walks through all of the "multifield" submit elements
    and adds the appropriate "onclick" handler, based on whether the button is a
    "multi_del" or a "multi_add" button.
*/


if  (document.getElementById) {  // This tests whether we are using DOM level 2.
	old_onload = window.onload
	// TODO:  Should use domcontentloaded?
	window.onload = function () {
		if (old_onload) old_onload();
		
		// multi_del will delete an <INPUT><BUTTON><BR> tuple
		function multi_del() {
			input = this.previousSibling;
			br = this.nextSibling;
			input.parentNode.removeChild(input);
			br.parentNode.removeChild(br);
			this.parentNode.removeChild(this);
			elements = document.getElementsByClassName(input.className);
			// If this is the last grouping, then hide the delete button:
			if (elements.length == 3) elements[1].style.display="none";
			return false
		}
		
		// multi_add will clone the first <INPUT><SUBMIT><BR> tuble.
		function multi_add() {
			elements = document.getElementsByClassName(this.className);
			// If there was only one grouping, then the delete button
			// was hidden... go ahead and show it:
			if (elements.length == 3) elements[1].style.display="inline";
			input = elements[0].cloneNode(true);
			if (input.nodeName == "SELECT") input.selectedIndex = 0;
			if (input.nodeName == "INPUT") input.clear();
			del = elements[1].cloneNode(true);
			del.onclick = multi_del;
			br = document.createElement("BR");
			this.parentNode.insertBefore(input, this);
			this.parentNode.insertBefore(del, this);
			this.parentNode.insertBefore(br, this);
			return false
		}
		
		// enhance all of the submit buttons!
		buttons = document.getElementsByClassName("multifield");
		for (i=0; i<buttons.length; i++) {
			button = buttons[i];
			if (button.nodeName != "INPUT" && button.type != "submit") continue;
			if (button.name.substring(0,9) == "multi_del") button.onclick = multi_del;
			else if (button.name.substring(0,9) == "multi_add") button.onclick= multi_add;
		}
	}
}
