/*  jog.nestedBox.js JavaScript Nested SelectBox Menu, version 1.0
 *  Copyright (c) 2009 Johannes Gamperl, http://jg-webdesign.de
 *  Details:
 *
 *  jog.Form.NestedSelect.js is distributable under the terms of an "Creative 
 *  Commons-Lizenz" license. http://creativecommons.org/licenses/by-nc-nd/3.0/
 *
 *  jog.Form.NestedSelect.js ist unter einer "Creative Commons-Lizenz" lizenziert.
 *  http://creativecommons.org/licenses/by-nc-nd/3.0/deed.de
 *
 *--------------------------------------------------------------------------*/
	Function.prototype.bind = function(obj) {
		var method = this, temp = function() {
			return method.apply(obj, arguments);
		};
		return temp;
	}
	var jog = {'Form':{}};
	jog.Form.NestedSelect = function (options) {
		this.DB = options.db;
		this.NO = document.getElementsByName(options.prefix+'[]').length;
		this.PREFIX = options.prefix;
		this.SELECT_TEXT = options.sText || '--SELECT--';
		this.SELECT_EMPTY = options.sEmpty || '--EMPTY--';
		this.__init();
	}
	jog.Form.NestedSelect.prototype = {
		__$ : function(id) { return document.getElementById(id); },
		__init : function() {
			for (var i=1; i < this.NO; i++)
			{
				this.__$(this.PREFIX+i).onchange = function(i) {
					return function() {
						this.makeChoice(this.__$(this.PREFIX+i).value, i+1);
					};
				}(i).bind(this);			
			}
			this.writeOptions(1,0);
		},
		writeOptions : function (element_id, pid, path) {
			var j = 1;
			var e = this.__$(this.PREFIX+element_id);
			e.options[0] = new Option(this.SELECT_TEXT, -1);
			for (var i=0; i < this.DB.length; i++)
			{
				if (this.DB[i].pid == pid)
				{
					e.options[j] = new Option(this.DB[i].title, this.DB[i].id);
					if (path && path == this.DB[i].id) { e.selectedIndex = j; }
					j++;
				}
			}
			if (j==1)
			{
				for (var m=e.options.length-1;m>0;m--) { e.options[m]=null; }
				e.options[0] = new Option(this.SELECT_EMPTY, -1);
			}
		},
		makeChoice : function (db_id, next_element_id) { //alert(db_id+' : '+next_element_id);
			if (next_element_id == 2)
			{
				for (var i=2; i <= this.NO; i++)
				{
					var e = this.__$(this.PREFIX+i);
					for (var m=e.options.length-1;m>0;m--) { e.options[m]=null; }
					e.options[0] = new Option(this.SELECT_EMPTY, -1);
				}
			}
			if (db_id == -1) { return; }
			this.writeOptions(next_element_id, db_id);
		}
	};