window.addEvent('domready', function(){
	var Configurator = new Class({
		params: {},

		startPrice: 100,
		price: 0,

		ptag: $$('#ptag p span')[0],
		ptag2: $$('#ptag2 p span')[0],
		firstProcess: true,

		initialize: function() {
			$('simpleControls').dispose();
			this.startPrice = parseFloat(this.startPrice);
			if ($H(this.params).getLength() < 1) {
				$('ptag').dispose();
				$('ugHost').dispose();

				return;
			}
			this.injectTo = 'bottom';
			if (Browser.Engine.trident) {
				this.injectTo = 'top';
			}
			$H(this.params).each(function(v, k) {
				this.createControl(v).inject($( v.graphic ? 'controlHost' : 'ugHost'), this.injectTo);
			}.bind(this));
			this.firstProcess = false;
		},

		createControl: function(control) {
			var ce = {};

			// Связываем элемент и породивший его объект
			control.element = ce;
			ce.cObj = control;

			//this.divclear = new Element('div', {'class': 'clear'});



			/*-------------------------------------------------------------------------*/
			// Особые функции для биндов
			/*-------------------------------------------------------------------------*/
			var f_SimularPodlok = function(e, node) {
				if (!e) return;
				var newid = node.id.replace(/bcolour/, 'podlok');
				if (newid == node.id) {
					 newid = node.id.replace(/podlok/, 'bcolour');
				}
				if ($(newid)) $(newid).fireEvent('click');
			}

			if (control.onClick) {
				eval("control.onClick = " + control.onClick);
			}

			if (control.graphic) {
				ce = new Element('div', {'class': 'selector'});
				var st = new Element('div');

				//if (control.radio) {
					st.set('class', 'radio')
				//} else { }

				// Создаём инпут, который будет дублировать всё
				var dublicator = new Element('input', {type: 'hidden', name: control.name});

				var counter = 1;
				if (Browser.Engine.trident) counter = $H(control.values).getLength();

				$H(control.values).each(function(v, k) {
					if (typeof k == 'string') v.value = k;
					var it = new Element('a', {
						href: '#',
						'class': 'opt',
						'id': control.name + '_opt' + counter,
						title: v.name
					});

					if (Browser.Engine.trident) {
						counter--;
					} else {
						counter++;
					}

					if (control.autotexture && !v.image)
						v.image = '/img/textures/' + control.name + '/' + v.value + '.png';

					it.adopt(new Element('img', {
						src: v.image,
						alt: v.name
					}));

					if (control.showNames) {
						var tn = document.createTextNode(v.name);
						it.adopt(tn);
					}


					it.addEvent('click', function(e) {
						dublicator.value = v.value;
						control.current = v;

						st.getChildren().removeClass('active');
						it.addClass('active');

						this.recountPrice();

						// если у нас есть эвент на клик
						if (control.onClick) {
							control.onClick(e, it);
						}

						return false;
					}.bind(this));

					it.inject(st, this.injectTo);
					if (v.def) it.fireEvent('click');
				}.bind(this));

				ce.adopt([
					new Element('h4', {
						'text': control.lname,
						'id': control.name + '_h4'
					}),
					st,
					dublicator
					//this.divclear
				]);


				if (typeof control.desc == 'string') {
					ce.adopt(new Element('p', {
						'html': control.desc,
						'id': control.name + '_desc',
						'styles': {
							'clear': 'both',
							'font-size': 'smaller'
						}
					}));
				}
			}
			else {
				ce = new Element('div', {'class': 'column'});

				new Element('h4', {'text': control.lname}).inject(ce);
				new Element('div').inject(ce); // container for inputs

				var i = 0;
				$H(control.values).each(function(v, k) {
					if (typeof k == 'string') v.value = k;
					var iid = 'cin-'+ (control.radio ? control.name + i : v.iname);
					var inp = new Element('input', {
						type: (control.radio ? 'radio' : 'checkbox'),
						name: (control.radio ? control.name : v.iname),
						value: (control.radio ? v.iname : ''),
						id: iid
					});

					Browser.Engine.trident && (v.checked = false);

					control.radio || inp.set('checked', v.checked ? true : false);

					inp.addEvent((!Browser.Engine.trident ? 'change' : 'click'), function() {
						control.current = (control.radio ? v : false);
						v.checked = inp.checked;
						this.recountPrice();
					}.bind(this));

					new Element('p', {'class': 'irow'}).adopt([
						inp,
						new Element('label', {text: v.name, 'for': iid})
					]).inject(ce.getLast(), this.injectTo);
					i++;
				}.bind(this));
			}

			return ce;
		},

		recountPrice: function() {
			var oldPrice = this.price;
			this.price = this.startPrice;
			$H(this.params).each(function(v, k) {
				if ($chk(v.current))
					this.price += (v.current.price ? v.current.price : 0);
				else if (!v.graphic && !v.radio)
					$H(v.values).each(function(t) { if (t.checked) this.price += (t.price ? t.price : 0) }.bind(this));
			}.bind(this));

			this.ptag.set('html', this.price + " &euro;");
			this.ptag2.set('html', this.price + " &euro;");
			// пиздец, ну зачем так? :( — rush


			this.price != oldPrice && !this.firstProcess && $('ptag').highlight() & $('ptag2').highlight();
			// this.price == oldPrice || this.firstProcess && $('ptag').highlight(); непонятнее, но короче ))
		}
	});

	if ($chk($('controlHost'))) {
		Configurator.implement(window.jrJSON.configurator);
		window.configuratorInstance = new Configurator();
	}
});
