/* Author: Jakub Roztocil -aka- Oswald | jakub@roztocil.name | webkitchen.cz */
/* Licence GNU GPL v2+ */


// pro ie 5 vubec v DOMU OPTGROUP neexistuji, protoze je nezna
function Sel(origSelect, groups, place) {
	this.origSelect = origSelect;
	this.groups = groups;
	this.place = place;
	this.newSelect = document.createElement('select');
}
Sel.prototype.init = function() {
	var option, text, i;
	for (i = 0; i < this.groups.length; i++) {
		text = this.groups[i].name;
		option = document.createElement('option');
		option.appendChild(document.createTextNode(text));
		this.newSelect.appendChild(option);
	}
	if (this.place) {
		this.place.appendChild(this.newSelect)
	} else {
		this.origSelect.parentNode.insertBefore(this.newSelect, this.origSelect);
	}
	this.setChoise(this.groups[0]);
	this.newSelect.oSel = this;
	this.newSelect.onchange = function() {
		this.oSel.setChoise(this.oSel.groups[this.selectedIndex]);
	}
}
Sel.prototype.setChoise = function(group) {
	var options;
	this.clearOrigSelect();
	for (var i = 0; i < group.options.length; i++) {
		this.origSelect.appendChild(group.options[i]);
	}
}
Sel.prototype.clearOrigSelect = function() {
	while (this.origSelect.hasChildNodes()) {
		this.origSelect.removeChild(this.origSelect.firstChild);
	}
}

Sel.initAll = function() {
	var selectsNodeList,  selectsArray = [], select, groups;
	selectsNodeList = document.getElementsByTagName('select');
	for (var i = 0; i < selectsNodeList.length; i++) {
		selectsArray[i] = selectsNodeList[i];
	}
	for (var i = 0; i < selectsArray.length; i++) {
		select = selectsArray[i];
		groups = select.getElementsByTagName('optgroup');
		if (groups.length > 0) {
			Sel.initSelect(select, groups);
		}
	}
}

Sel.initSelect = function(select, groups) {
	var arrGroups = [], group, goptions, i, j = [];
	for (i = 0; i < groups.length; i++) {
		group = groups[i];
		arrGroups[i] = {name: group.getAttribute('label'), options: []}
		goptions = group.getElementsByTagName('option');
		if (goptions.length < 1) {
			return;
		}
		for (j = 0; j < goptions.length; j++) {
			arrGroups[i].options[j] = goptions[j];
		}
	}
	var sel = new Sel(select, arrGroups);
	sel.init();
}
