document.observe('dom:loaded', function() {
	FormStyle.work();
});

var FormStyle = {
		
	work: function() {
		$$('body').each(function(el) {
			el.observe('click', function(){
				Tips.hideAll();
			});
		});
	
		$$('.j-formstyle').each(function (el) {
			var select = el.down('select');
			//vytvorim potrebne elementy
			input = new Element('span', {'class': 'formstyle-input'}).insert(new Element('input', {
				'id'   : select.id,
				'name' : select.name,
				'value': select.value,
				'type' : 'hidden',
				'class' : 'h'
			})).insert(new Element('span', {'class': 'formstyle-data'}).update(select.options[select.selectedIndex].text));
			var button = new Element('span', {'class': 'formstyle-button'});
			//vytvorim list ktory bude v tipe
			var list = new Element('span', {'class': 'formstyle-list '+el.classNames().toArray().last() });
			$w(select.className).each(function (className) {list.addClassName(className)});
			select.childElements().each(function (opt) {
				var option = new Element('span').update(opt.innerHTML);
				if (opt.selected) option.addClassName('formstyle-selected');
				$w(opt.className).each(function (className) {option.addClassName(className)});
				
				// nastavenie hoveru
				option.observe('mouseover', function (e) {
					e.stop();
					this.addClassName('formstyle-active');
				}.bindAsEventListener(option));
				option.observe('mouseout', function (e) {
					e.stop();
					this.removeClassName('formstyle-active');
				}.bindAsEventListener(option));
				option.onclick = opt.ondblclick;
				
				// nastavenie clicku -> skrytie tipu, nastavenie hodnoty inputu
				option.observe('click', function (e, value) {
					e.stop();
					var target = e.element();
					this.prototip.hide();
					document.stopObserving('click', this.prototip.fx);
					this.down('span.formstyle-input').down('input').value = value;
					this.down('span.formstyle-input').down('span.formstyle-data').update(target.innerHTML);
					target.up().childElements().invoke('removeClassName', 'formstyle-selected');
					target.addClassName('formstyle-selected');
				}.bindAsEventListener(el, opt.value));
				
				list.insert(option);
			});
			
			list.insert('<b></b>');
			
			Element.remove(select);
			el.insert(input).insert(button);
			new Tip(el, list, {
				hook: {target: 'bottomLeft', tip: 'topLeft'},
				showOn: 'click',
				hideOn: false,
				width: 'auto',
				hideOthers: true,
				offset: { x: 0, y: 2}
			});
			el.prototip.combobox = true;
			
			el.removeClassName('.j-formstyle');
			
		});
	}
}
