var TED_URLS = {
	'CS':'http://www.epoptavka.cz/ted/',
	'SK':'http://www.epoptavka.cz/ted/',
	'HU':'http://www.epoptavka.cz/ted/',
	'PL':'http://www.epoptavka.cz/ted/',
	'DE':'http://www.epoptavka.cz/ted/',
	'AT':'http://www.epoptavka.cz/ted/'
};

var DATA_URLS = {
	'CS':'http://www.epoptavka.cz/',
	'SK':'http://www.123dopyt.sk/',
	'PL':'http://www.123zapytanie.pl/',
	'HU':'http://www.123profit.hu/',
	'DE':'http://www.123anfrage.de/',
	'AT':'http://www.123anfrage.at/'
};

var TED_URL = TED_URLS[lang];
var DATA_URL = DATA_URLS[lang];


var lngs = {
	'CS' : {
		'hledej' : 'Hledej',
		'hledat' : 'Hledat',
		'Zobrazit' : 'Zobrazit vše',
		'Hledam' : 'Hledám',
		'Vyberte' : 'Vyberte (pokud chcete zpřesnit dotaz)',
		'Nacitam' : 'Načítám',
		'Odebrat' : 'Odebrat',
		'HledaniKratke' : 'Hledaný výraz musí mít minimálně 4 znaky.',
		'NicNenalezeno' : 'Nic nenalezeno!',
		'Vybrane' : 'Vybrané'
	},
	'SK' : {
		'hledej' : 'Hľadaj',
		'hledat' : 'Hľadať',
		'Hledam' : 'Hľadám',
		'Zobrazit' : 'Zobraziť všetko',
		'Vyberte' : 'Vyberte (pokiaľ chcete upresniť zadanie)',
		'Nacitam' : 'Načítám',
		'Odebrat' : 'Odobrať',
		'HledaniKratke' : 'Hľadaný výraz musí mať minimálne 4 znaky.',
		'NicNenalezeno' : 'Nič nenájdené!',
		'Vybrane' : 'Vybrané'
	},
	'PL' : {
		'hledej' : 'Szukaj',
		'hledat' : 'Szukać',
		'Hledam' : 'Hľadám',
		'Zobrazit' : 'Pokazać wszystko',
		'Vyberte' : 'Proszę wybrać ( jeśli chcą Państwo uściślić zapytanie )',
		'Nacitam' : 'Naliczam',
		'Odebrat' : 'Wykreślić',
		'HledaniKratke' : 'Szukane słowo powinno zawierać minimalnie 4 znaki.',
		'NicNenalezeno' : 'Nie wyszukano!',
		'Vybrane' : 'Wybrane'
	},
	'HU' : {
		'hledej' : 'Keresés',
		'hledat' : 'Keress',
		'Zobrazit' : 'Az összes ajánlatkérés megjelenítése',
		'Vyberte' : 'Válasszon (ha pontosítani szeretne keresésén)',
		'Hledam' : 'Keresem',
		'Nacitam' : 'Töltés',
		'Odebrat' : 'Kikapcsolni',
		'HledaniKratke' : 'A keresett kifejezés legalább 4 karaktert kell hogy tartalmazzon.',
		'NicNenalezeno' : 'Nincs találat!',
		'Vybrane' : 'Kiválasztott'
	},
	'DE' : {
        'hledej' : 'Such',
        'hledat' : 'Suchen', 
        'Zobrazit' : 'Alles zeigen', 
        'Hledam' : 'Ich suche',
        'Vyberte' : 'Wählen Sie aus (falls Sie Ihre Frage präzisieren)',
        'Nacitam' : 'Ich lese ein',
        'Odebrat' : 'Entnehmen',
        'HledaniKratke' : 'Der gesuchte Ausdruck muss mindestens 4 Zeichen haben',
        'NicNenalezeno' : 'Nichts gefunden!',
        'Vybrane' : 'Ausgewählt'
    },
	'AT' : {
        'hledej' : 'Such',
        'hledat' : 'Suchen', 
        'Zobrazit' : 'Alles zeigen', 
        'Hledam' : 'Ich suche',
        'Vyberte' : 'Wählen Sie aus (falls Sie Ihre Frage präzisieren)',
        'Nacitam' : 'Ich lese ein',
        'Odebrat' : 'Entnehmen',
        'HledaniKratke' : 'Der gesuchte Ausdruck muss mindestens 4 Zeichen haben',
        'NicNenalezeno' : 'Nichts gefunden!',
        'Vybrane' : 'Ausgewählt'
    }
};

var toLoad = 0;

var treeSelect = new Class({
	container:null,
	stack: null,
	select: null,
	selected: new Array(),
	data: null,
	lasts: new Array(),
	loaded: new Array(),
	searched: false,
	notSend: false,
	id: null,
	searchDiv: null,
	options : {
		className: 'whisperer',
		dataSource: 'cpv'

	},


	initialize: function(element, id, options) {
		this.setOptions(options);
		this.element = element;
		this.id = id;
		toLoad += 1;
		this.selected[this.id] = new Array();

		this.build();
		this.id = id;
	},

	build: function() {
		// Sestaveni fomrulare
		var table = new Element('table',{
			'border' : '0',
			'styles': {
				'width': '95%',
				'border-collapse': 'collapse',
				'margin-bottom':'5px'
			}
		}).injectAfter(this.element);

		var tbody = new Element('tbody').inject(table);
		var row = new Element('tr').inject(tbody);
		var td = new Element('td', {
			'colspan':'2'
		}).inject(row);

		this.searchDiv = new Element('div', {
			'align' : 'center',
			'styles': {
				'border':'1px solid #ccc',
				'background' : '#fff',
				'padding': '5px'
			}}
		).inject(td);

		new Element('label', {'for' : this.id + 'searchBox'}).appendText(lngs[lang]['hledej']+': ').inject(this.searchDiv);
		input = new Element('input', {'id' : this.id + 'searchBox', 'rel': this.id, 'type': 'text'}).inject(this.searchDiv);
		input.addEvent('keydown', function(e) {
			e = new Event(e);
		    if (e.code == 13) {
				e.stop();
				$('commissionForm').setAttribute('onsubmit', 'return false;');
				id = e.target.getAttribute('rel');
				$(id + 'searchBtn').click();
			}
		});
		
		
		this.searchButton = new Element('input', {'type' : 'button', 'id' : this.id + 'searchBtn', 'value': lngs[lang]['hledat']}).inject(this.searchDiv);
		clearButton = new Element('input', {'type' : 'button', 'value': lngs[lang]['Zobrazit']}).inject(this.searchDiv);

		clearButton.addEvent('click' , function(e) {
			e = new Event(e);
			$(this.id + 'searchBox').value = '';
			this.search('');
		}.bind(this));
		
		this.searchButton.addEvent('click', function(e) {
			e = new Event(e);
			this.search($(this.id + 'searchBox').value);
		}.bind(this));
        //this.searchDiv.innerHTML = 'Hledat: <input type="text" /> <input type="submit" value="Hledej"/>';

		var row = new Element('tr').inject(tbody);
		var leftTd = new Element('td', {
			'styles': {
				'border':'1px solid #ccc',
				'width': '200px',
				'padding': '0px'
			}
		}).inject(row);
		var rightTd = new Element('td', {
			'styles': {
				'border':'1px solid #ccc',
				'padding': '0px'
			}
		}).injectAfter(leftTd);
		
		if (!window.gecko) {
			rightTd.setStyles({'margin-left':'-20px'});
		}

		//alert(this.element.parentNode.innerHTML);

		// Input zneviditelnit ...
		this.element.setStyle('position', 'absolute');
		this.element.setStyle('top', '0');
		this.element.setStyle('left', '0');
		this.element.setStyle('visibility', 'hidden');

		// Vytvoreni stacku
		elem = new Element('div', {'styles' : {'margin':'5px'}}).inject(leftTd);
		elem.innerHTML = '<strong>'+lngs[lang]['Vybrane']+'</strong>';
		this.stack = new Element('div',{
			'class': this.options.className + '-stack',
			'styles': {
				'background-color': '#fff',
				'height':'410px',
				'width':'200px',
				'overflow':'auto'
			}
		}).inject(leftTd);

		// Vytvoreni select boxu
		this.select = new Element('div', {
			'class': this.options.className + '-box',
			'styles': {
				'background-color': '#fff',
				'height':'415px',
				'width':'480px',
				'overflow':'auto',
				'float':'right'
			}
		}).inject(rightTd);

		// Velikost containeru ...
		this.container = this.element.parentNode;

		// Rozsirit, pokud to neni firefox
		if (!window.gecko) {
			this.select.setStyle('width', '480px');
		}

		// Vetsi container
		if (!window.ie) {
			// this.container.setStyle('height', '405px');
		}

		// Nacist vybrane hodnoty
		var inputText = this.element.value;
		if (inputText != '') {
			inputText = inputText.split(', ');
			for (x = 0; x < inputText.length; x++) {
				if (!this.selected[this.id].contains(inputText[x])) {
					this.selected[this.id].push(inputText[x]);
				}
			}
		}
		// Nacist puvodni obsah		
		this.loadCodeData();		
		this.select.innerHTML = '<center><img src="' + TED_URL + '/images/tree/ajax-loader.gif" /> '+lngs[lang]['Nacitam']+' ...</center>';
		this.displayData();
		toLoad -= 1;
	},
	
	/**
	 * Vyhledávání
	 */
	search: function(pattern) {
		if (!this.searched) {
			this.tmpHTML = this.select.innerHTML;
  		}
		if (pattern == '') {
			this.searched = false;
			this.searchString = '';
			this.select.innerHTML = this.tmpHTML;
			
			/* Zaškrtnout všechno co je vybrané */
			$$('.'+this.id+'ch').each(function(element) {
				element.src = TED_URL + '/images/tree/chck.jpg';
			}.bind(this));

			for (i = 0; i < this.selected[this.id].length; i++) {
				if ($('chc'+this.selected[this.id][i]) != null) {
                    $('chc'+this.selected[this.id][i]).src = TED_URL + '/images/tree/chck_a.jpg';
				}
			}
			
			this.searchButton.removeAttribute('disabled');
			$('commissionForm').setAttribute('onsubmit', 'return true;');
			this.loaded = new Array();
			this.lasts = this.lastsTmp;
		} else {
		    if (pattern.length <= 3) {
				alert(lngs[lang]['HledaniKratke']);
				return;
			}
			this.searched = true;
			this.searchString = pattern;
			this.searchButton.setAttribute('disabled', 'disabled');
			this.select.innerHTML = '<center><img src="' + TED_URL + '/images/tree/ajax-loader.gif" /> '+lngs[lang]['Hledam']+' "'+pattern+'" ...</center>';
			// Odeslat JSON na vyhledání výrazu.
			if (this.options.dataSource == 'cpv') {
				var url = DATA_URL + 'ted_components.php?component=cpv&action=searchCPV&pattern='+encodeURIComponent(pattern);
				var jSonRequest = new Json.Remote(url, {onComplete: function(object){
					childs = object['cpv'];
					if (childs.length == 0) {
						this.select.innerHTML = '<center style="font-size: 10pt;">'+lngs[lang]['NicNenalezeno']+'</center>';
					} else {
						this.select.innerHTML = "<ul class=\"tree\">" + this.formatHTML(childs) + "</ul>";
					}
					this.makeDragable();
					this.lastsTmp = this.lasts;
					this.lasts = new Object();
					$('commissionForm').setAttribute('onsubmit', 'return true;');
					this.searchButton.removeAttribute('disabled');
					this.loaded = new Array()
				}.bind(this)}).send();
			}
			if (this.options.dataSource == 'nut') {
				var url = DATA_URL + 'ted_components.php?component=nut&action=searchNUT&pattern='+encodeURIComponent(pattern);
				var jSonRequest = new Json.Remote(url, {onComplete: function(object){
					childs = object['nut'];
					this.select.innerHTML = "<ul class=\"tree\">" + this.formatHTML(childs) + "</ul>";
					this.makeDragable();
					this.lastsTmp = this.lasts;
					this.lasts = new Object();
					$('commissionForm').setAttribute('onsubmit', 'return true;');
					this.searchButton.removeAttribute('disabled');
					this.loaded = new Array()
				}.bind(this)}).send();
			}
		}
	},

	/**
	 * Nacte vsechna data do selectu
	 */

	loadData: function() {
		// Loader
		this.select.innerHTML = '<center><img src="' + TED_URL + '/images/tree/ajax-loader.gif" /> '+lngs[lang]['Nacitam']+' ...</center>';
		var url = DATA_URL + 'ted_components.php?component='+this.options.dataSource+'&action=getData';
 		var jSonRequest = new Json.Remote(url, {onComplete: function(object){
				this.data = object[this.options.dataSource];
				this.displayData();
		}.bind(this)}).send();

	},

	makeDragable: function() {
		return false;
		var drop = this.stack;
		$$('.draggAble').each(function(item){
			item.addEvent('mousedown', function(e) {
					e = new Event(e);
					var coor = this.getCoordinates();
					var x = e.page.x - 10;
					var y = e.page.y + 5;
					//alert(x + '+' + y);
					e.stop();
					var clone = this.clone()
						.setStyles({'opacity': 0.7, 'position': 'absolute', 'height': '30', 'top': y, 'left': x})
						.addEvent('emptydrop', function() {
							this.remove();
							drop.removeEvents();
						}).inject(document.body);

					drop.addEvents({
						'drop': function() {
							clone.setStyle('display', 'none');
							drop.removeEvents();
							// Zjistit co to bylo ...
							clone.remove();
							if (!components[clone.getAttribute('rel')].selected[this.id].contains(clone.id)) {
								components[clone.getAttribute('rel')].chckClick(clone.id);
							}
							//dropFx.start('ffffff');

						}.bind(this),
						'over': function() {
							//dropFx.start('f1f1f1');
						},
						'leave': function() {
							//dropFx.start('ffffff');
						}
					});

					var drag = clone.makeDraggable({
						droppables: [drop]
					}); // this returns the dragged element

					drag.start(e); // start the event manual
				});
		}.bind(this));
	},

	displayData: function() {
		if (this.options.dataSource == 'cpv') {
			var url = DATA_URL + 'ted_components.php?component=cpv&action=getChilds&parent=NULL';
			var jSonRequest = new Json.Remote(url, {onComplete: function(object){			    
				childs = object['cpv'];
				this.select.innerHTML = '<ul class=\"tree\">' + this.formatHTML(childs) + '</ul>';
				this.makeDragable();
				this.loaded.push(parent);
			}.bind(this)}).send();
		}
		if (this.options.dataSource == 'nut') {
			var url = DATA_URL + 'ted_components.php?component=nut&action=getChilds&parent=NULL';
			var jSonRequest = new Json.Remote(url, {onComplete: function(object){
				childs = object['nut'];
				this.select.innerHTML = '<ul class=\"tree\">' + this.formatHTML(childs) + '</ul>';
				this.makeDragable();
				this.loaded.push(parent);
			}.bind(this)}).send();
		}
	},

	formatHTML: function(root) {
		var innerHTML = '';
		for (x=0; x < root.length; x++) {
			icon = '';
/*			treeLine = (root[x].hasChild) ?
				((x+1 != root.length) ? '<a href="" onclick="components[\'' + this.id + '\'].loadChilds(\''+root[x].code+'\', true, '+root[x].depth+'); return false;"><img id="img'+root[x].code+'" src="' + TED_URL + '/images/tree/plus-cross.gif" /></a>' : '<a href="" onclick="components[\'' + this.id + '\'].loadChilds(\''+root[x].code+'\', true, '+root[x].depth+'); return false;"><img id="img'+root[x].code+'" src="' + TED_URL + '/images/tree/plus-corner.gif" /></a>') :
				((x+1 != root.length) ? '<img src="' + TED_URL + '/images/tree/line-cross.gif" />' : '<img src="' + TED_URL + '/images/tree/line-corner.gif" />');*/

			var flag = "";
			if (this.options.dataSource == 'nut' && root[x].depth == 0) {
				flag = '<img src="'+TED_URL+'images/flags/png/'+root[x].code.toLowerCase().substr(0, 2)+'.png" width="16px"> ';
			}

/*			this.lasts[root[x].code] = (x+1 == root.length) ? true : false;
			var prefix = '';
			for (var i = 0; i < root[x].depth; i++) {
				prefix += ( (this.lasts[this.getCode(root[x].code, i+1)] == true) ? '<img width="19" height="16" src="' + TED_URL + '/images/tree/invisible.gif">' : '<img src="' + TED_URL + '/images/tree/line.gif">');
			}*/

			var toolT = false;
			var text = root[x][this.options.dataSource];
			/*if (root[x][this.options.dataSource].length > 80) {
				toolT = true;
				root[x][this.options.dataSource] = root[x][this.options.dataSource].substr(0,80) + ' ... ';
			}*/

			var chckImg = (this.selected[this.id].contains(root[x].code)) ? '/images/tree/chck_a.jpg' : '/images/tree/chck.jpg';
			className = this.lasts[root[x].code] = (x+1 == root.length) ? 'last_' : '';
			className += 'line';
			
			expandButton = (root[x].hasChild) ? '<a href="" class="expandBtn" onclick="components[\'' + this.id + '\'].loadChilds(\''+root[x].code+'\', true, '+root[x].depth+'); return false;"><img id="img'+root[x].code+'" src="' + DATA_URL + 'images2/tree/plus.png" /></a>' : '<a class="expandBtn"><img id="img'+root[x].code+'" src="' + DATA_URL + 'images2/tree/none.gif" /></a>';



			innerHTML += '<li class="'+className+'"><table cellspacing="0" cellpadding="0"><tr><td valign="top">'+expandButton+'</td><td valign="top"><a href="" onclick="components[\'' + this.id + '\'].chckClick(\''+root[x].code+'\'); return false;"><img id="chc'+root[x].code+'" class="'+this.id+'ch" src="' + TED_URL + chckImg +'" /></a></td><td style="cursor:hand;" onclick="components[\'' + this.id + '\'].chckClick(\''+root[x].code+'\');">'+ flag + root[x][this.options.dataSource] + '</td></tr></table>' +
				'<ul id="sub'+root[x].code+'" style="display:none"></ul></li>';
		}
		return innerHTML;
	},

	getCode: function(code, index) {
		if (this.options.dataSource == 'cpv') {
			return code.substr(0,index+1) + this.strRepeat('0', (8 - index));
		}
		if (this.options.dataSource == 'nut') {
			return code.substr(0,index+1);
		}
	},

	strRepeat: function(inp, multiplier) {
	        var ret = "";
	        while (--multiplier > 0) ret += inp;
	        return ret;
	},

	chckClick: function(code) {
		var element = $('chc'+code);
		if (element != null) {
			var pic = element.getAttribute('src').split('/');
			pic = pic[pic.length - 1];
			if (pic == 'chck.jpg') {
				element.src = TED_URL + 'images/tree/chck_a.jpg'
				this.selected[this.id].push(code);
			} else {
				element.src = TED_URL + 'images/tree/chck.jpg'
				this.selected[this.id].remove(code);
			}
		} else {
			if (this.selected[this.id].contains(code)) {
				this.selected[this.id].remove(code);
			} else {
				this.selected[this.id].push(code);
			}
		}
		this.stack.innerHTML = '<center><div class="selectedItem" style="border: 0;"><img src="' + TED_URL + '/images/tree/ajax-loader.gif" /> '+lngs[lang]['Nacitam']+' ...</div></center>';
		this.loadCodeData();
	},

	loadCodeData: function() {
		this.element.value = this.selected[this.id].join(', ');
		if (this.selected[this.id].length == 0) {
			this.stack.innerHTML = '';
			return;
		}

		var code = this.selected[this.id].join(',');
		var url = DATA_URL + 'ted_components.php?component='+this.options.dataSource+'&action=getSingle&code='+code;
		var innerHTML = '';
		var jSonRequest = new Json.Remote(url, {onComplete: function(object){
			for (var x = 0; x < object[this.options.dataSource].length; x++) {
				innerHTML += '<div class="selectedItem"><span style="float: right; margin-right: -3px; margin-top: -3px;"><a href="" title="'+lngs[lang]['Odebrat']+'" onclick="components[\'' + this.id + '\'].chckClick(\''+object[this.options.dataSource][x].code+'\'); return false;"><img style="border:0;margin-bottom:2px;" src="'+TED_URL+'/images/page_delete.gif" alt="'+lngs[lang]['Odebrat']+'" /></a></span>'+
				object[this.options.dataSource][x][this.options.dataSource] + ''+
				//lngs[lang]['Odebrat']+
				'&nbsp;</div>';
				//'<span style="font-size: 8px;">Kód: '+ object[this.options.dataSource][x].code + '</span></div>';
			}
			this.stack.innerHTML = '<div class="" id="stackContent">' + innerHTML + '<div>';
		}.bind(this)}).send();
	},

	loadChilds: function(parent, bool, depth) {
		// Nastaveni obrazku
		if ($('img'+parent) != null) {

			$('img'+parent).src = ($('img'+parent).src == DATA_URL + 'images2/tree/plus.png') ?
				DATA_URL+ 'images2/tree/minus.png' : DATA_URL + 'images2/tree/plus.png';

		}
		if (!this.loaded.contains(parent)) {
			if (this.options.dataSource == 'cpv') {
			    addon = (this.searchString != '') ? '&yellow='+this.searchString : '';
				var url = DATA_URL + 'ted_components.php?component=cpv&action=getChilds&parent='+parent+'&depth='+depth+'&search='+this.searched+addon;
				var jSonRequest = new Json.Remote(url, {onComplete: function(object){
					childs = object['cpv'];
					$('sub'+parent).innerHTML = this.formatHTML(childs);
					this.makeDragable();
					this.loaded.push(parent);
				}.bind(this)}).send();
			}
			if (this.options.dataSource == 'nut') {
			    addon = (this.searchString != '') ? '&yellow='+this.searchString : '';
				var url = DATA_URL + 'ted_components.php?component=nut&action=getChilds&parent='+parent+'&depth='+depth+'&search='+this.searched+addon;
				//alert(url);
				var jSonRequest = new Json.Remote(url, {onComplete: function(object){
					childs = object['nut'];
					$('sub'+parent).innerHTML = this.formatHTML(childs);
					this.makeDragable();
					this.loaded.push(parent);
				}.bind(this)}).send();
			}
			$('sub'+parent).setStyle('display', '');
		} else {
			$('sub'+parent).setStyle('display', (($('sub'+parent).getStyle('display') == 'none') ? '' : 'none'));
		}
	}
});

var CpvList = new Class({
	data: null,

	initialize: function(data) {
		this.data = data;
	},

	getLevel: function(level) {
		var result = new Array();
		for (x=0; x < this.data.length; x++) {
			if (this.data[x].depth == level) {
				result.push(this.data[x]);
			}
		}
		return result;
	},

	getChilds: function(parent) {
		var result = new Array();
		var parentWithoutZeroes = parent.substr(0,2);
		for (x=2; x < parent.length; x++) {
			if (parent.charAt(x) != '0') {
				parentWithoutZeroes += parent.charAt(x);
			} else {
				break;
			}
		}

		var endZeroes = String.repeat(null, '0', 8 - parentWithoutZeroes.length);

		for (x=0; x < this.data.length; x++) {
			if (this.data[x].code.startswith(parentWithoutZeroes) &&
				this.data[x].code.endswith(endZeroes) &&
				this.data[x].code.charAt(parentWithoutZeroes.length) != '0'
				) {
				result.push(this.data[x]);
			}
		}
		return result;
	}

});

var NutList = new Class({
	data: null,

	initialize: function(data) {
		this.data = data;
	},

	getLevel: function(level) {
		var result = new Array();
		for (x=0; x < this.data.length; x++) {
			if (this.data[x].depth == level) {
				result.push(this.data[x]);
			}
		}
		return result;
	},

	getChilds: function(parent) {
		var result = new Array();
		var parentWithoutZeroes = parent.substr(0,2);
		for (x=2; x < parent.length; x++) {
			if (parent.charAt(x) != '0' && parent.charAt(x+1) != '0') {
				parentWithoutZeroes += parent.charAt(x);
			} else {
				break;
			}
		}

		var endZeroes = String.repeat(null, '0', 5 - parentWithoutZeroes.length);

		for (x=0; x < this.data.length; x++) {
			if (this.data[x].code.startswith(parentWithoutZeroes)
				&& parent != this.data[x].code
				) {
				result.push(this.data[x]);
			}
		}
		return result;
	}

});

var StepForm = new Class({
	nextStep: 'second',
	previousStep: 'third',
	initialize: function(){
		this.build();
	},

	build: function() {
		if ($('secondStep') != null) {
			$('secondStep').setStyle('display', 'none');
			$('thirdStep').setStyle('display', 'none');

			/*$('nextButton').setStyle('display', '');
			$('previousButton').setStyle('display', '');

			$('nextButton').addEvent('click', function() {
				this.step(this.nextStep);
			}.bind(this));
			$('previousButton').addEvent('click', function() {
				this.step(this.previousStep);
			}.bind(this));
			$('previousButton').setAttribute('disabled', 'disabled');*/
		}

	},


	step: function(step) {
		if (step == 'first') {
			/*$('previousButton').setAttribute('disabled', 'disabled');
			$('nextButton').removeAttribute('disabled');*/
			this.nextStep = 'second';
		}
		if (step == 'second') {
			this.nextStep = 'third';
			this.previousStep = 'first';
			/*$('previousButton').removeAttribute('disabled');
			$('nextButton').removeAttribute('disabled');*/
		}
		if (step == 'third') {
			/*$('nextButton').setAttribute('disabled', 'disabled');
			$('previousButton').removeAttribute('disabled');*/
			this.previousStep = 'second';
		}

		this.hideAll();
		$(step + 'Step').setStyle('display', '');
		$(step + 'Link').addClass('active');
		return false;
	},

	hideAll: function() {
		$('firstLink').removeClass('active');
		$('secondLink').removeClass('active');
		$('thirdLink').removeClass('active');

		$('firstStep').setStyle('display', 'none');
		$('secondStep').setStyle('display', 'none');
		$('thirdStep').setStyle('display', 'none');
	}

});

treeSelect.implement(new Events, new Options);

var SelectCheckBox = new Class({

	container : new Object(),
	closeA : new Object(),
	statusBar : new Object(),
	notHide: false,
	loaded: new Array(),
	notDisplay: false,
	ownFocus: false,
	lastFocus: null,
	hidden: null,
	iFrame: null,
	showed: null,
	data: new Object(),
	selected: new Object(),
	selectedText: new Object(),

	initialize: function(options) {
		this.setOptions(options);
		toLoad += 1;
		this.build();
	},

	// Iteratovat okolo vsech inputu, najit ty ktere jsou type = select a rel = check
	build: function() {

		$$('body').addEvent('click', function(e) {
			e = new Event(e);
			if (this.showed != null) {
				var position = this.showed.getCoordinates();
			}
			if (this.showed != null && (e.page.x < position.left || e.page.x > position.right ||
				e.page.y < position.top || e.page.y > position.bottom)) {
				// klik mimo container
				//alert('click');
				this.hideAll();
			} else {
				if (this.showed != null && this.showed.getStyle('display') != 'none') {
					this.notDisplay = true;
					if (e.target.type == 'checkbox') {
						this.ownFocus = true;
						if ($(e.target.getAttribute('rel') + 'field') != null) {
							$(e.target.getAttribute('rel') + 'field').focus();
						}
					} else {
						if (!window.opera) {
							this.ownFocus = true;
						}
						if ($(e.target.id + 'field') != null) {
							$(e.target.id + 'field').focus();
						}
					}
				}
			}
		}.bind(this));

		/* IE hack */
		if (window.ie) {
			this.iframe = new Element('iframe', {
				'scrolling' : 'no',
				'frameborde' : '0',
				'styles' : {
					'position': 'absolute',
					'border':'none',
					'display':'block',
					'z-index':'0',
					'display': 'none'
				}
			}).inject(document.body);
		}


		$$('input').forEach(function(element, index) {
			element.addEvent('focus',function(){
				this.hideAll();
			}.bind(this));
		}.bind(this));

		$$('textarea').forEach(function(element, index) {
			element.addEvent('focus',function(){
				this.hideAll();
			}.bind(this));
		}.bind(this));

		$$('select').forEach(function(element, index) {
			element.addEvent('focus',function(){
				this.hideAll();
			}.bind(this));
			var classNames = element.className;
			if (classNames != null) {
				classNames = classNames.split(' ');
			} else {
				classNames = new Array();
			}
			var name = element.name.substr(0, element.name.length-2);
			if (classNames.contains('check')) {
				var newElement = new Element((window.ie) ? 'input' : 'input', {
					'type' : 'text',
					'id' : name + 'field',
					'rel' : name,
					'styles': {
						'cursor' : 'hand',
						'width' : element.getStyle('width')
					}
				}).injectAfter(element);
				
				var textElement = new Element('input', {
					'type' : 'hidden',
					'id' : name + '_text',
					'name' : name + '_text'
				}).injectAfter(element);

				//if (window.ie) {
					newElement.setStyles({'background-image': 'url("'+TED_URL + 'images/selectArrow.jpg")',
						'background-repeat': 'no-repeat',
						'background-position' : 'center right',
						'border':'1px solid #ccc',
						'padding': '2px',
						'padding-right': '15px',
						'background-color':'#fff'});
				//}

				this.selected[name] = new Array();
				this.selectedText[name] = lngs[lang]['Vyberte'];
				this.container[name] = new Element('div',{
					'class' : 'containerCheckSelect',
					'id' : name,
					'styles' : {
						'border' : '1px solid gray',
						'border-bottom':'0',
						'padding' : '5px',
						'background-color': '#fff',
						'position' : 'absolute',
						'display' : 'none',
						'overflow':'auto',
						'z-index': '999999'
					}
				}).inject(document.body);
				this.data[name] = new Object();
			
				this.createText(name);
				this.statusBar[name] = new Element('div', {
					'styles' : {
						'background-color' : '#f9f9fb',
						'border' : '1px solid gray',
						'border-top':'0',
						'padding': '2px',
						'display': 'none',
						'text-align':'center'
					}
				}).inject(document.body);
				var img = new Element('input', {'type':'button', 'value':'OK', 'styles':{
					'width' : '50px'
				}}).inject(this.statusBar[name]);


				img.addEvent('click', function() {
					this.hideAll();
				}.bind(this));

				element.setStyle('position', 'absolute');
				element.setStyle('top', '0');
				element.setStyle('left', '0');
				element.setStyle('visibility', 'hidden');
				element.setAttribute('id', name+'_base');

				var position = newElement.getCoordinates();
				newElement.addEvent('click', function(e){
					this.eventHandler(e);
				}.bind(this));
				newElement.addEvent('focus', function(e){
					e = new Event(e);
					if (this.lastFocus != e.target) {
						this.eventHandler(e);
					}
					this.lastFocus = e.target;
				}.bind(this));

                this.selectedText[name] = lngs[lang]['Vyberte'];
				var first = true;
   			    for (var i = 0; i < element.options.length; i++) {
					if (element.options[i].selected) {
						if (first) {
                            this.selectedText[name] = '';
						}
						this.selectedText[name] += ((!first) ? ', ':'') + element.options[i].innerHTML;
					    first = false;
					}
				}

				this.showed = this.container[name];
				
				/* Nacist pouze vybrane */
				
				
				this.showSelection();
			}
		}.bind(this));

		toLoad -= 1;
		this.showed = null;
	},

	createText: function(name) {
		if (this.selected[name].length == 0) {
			this.selectedText[name] = lngs[lang]['Vyberte'];
		} else {
			this.selectedText[name] = '';
			for (i = 0; i < this.selected[name].length; i++) {
				if (i != 0) {
					this.selectedText[name] += ', ';
				}
				this.selectedText[name] += this.data[name][this.selected[name][i]];
			}
		}
	},

	eventHandler: function(event) {
		event = new Event(event);
		if (event.type == 'focus' || event.type == 'click') {
			// Focus na prvek ...
			if (event.type == 'click') {
				this.notHide = true;
			}
			this.display(event);
			this.notDisplay = false;
		}
	},

	getData: function(element) {
		var result = new Array();
		$$('select#'+element.id+' option').forEach(function(option, index){
			result.push({'value':option.value, 'text':option.innerHTML});
		}.bind(this));
		return result;
	},

	display: function(event) {
		var position = event.target.getCoordinates();
		var container = this.container[event.target.getAttribute('rel')];
		var close = this.statusBar[event.target.getAttribute('rel')];
		var _notHide = this.notHide
		this.hideAll();
		this.notHide = _notHide;
		
		/**
		 * Pokud je potreba nacist udaje
		 */
		if (!this.loaded.contains(event.target.getAttribute('rel'))) {
			this.loaded.push(event.target.getAttribute('rel'));
			name = event.target.getAttribute('rel');
			element = $(event.target.getAttribute('rel')+'_base');
			var opt = element.options;
				for (i = 0; i < opt.length; i ++) {
					var item = opt[i];
					this.data[name][item.value] = item.text;
					var chck = new Element('input', {
					 	'type' : 'checkbox',
						'value': item.value,
						'rel' : name,
						'id' : item.value+name
					}).inject(this.container[name]);
					var lbl = new Element('label', {
						'for' : item.value+name
					}).inject(this.container[name]);
					lbl.innerHTML = ' ' + item.text + '<br />';
					if (item.selected) {
						this.selected[name].push(item.value);
						item.selected = true;
					} else {
						this.selected[name].remove(item.value);
						item.selected = false;
					}
					chck.checked = item.selected;
					 // Pridavani hodnot do pole ....
					chck.addEvent('click', function(e) {
						e = new Event(e);
						var element = $(e.target.getAttribute('rel')+'_base');
						for (i=0; i < element.options.length; i++) {
							if (element.options[i].value == e.target.value) {
								element.options[i].selected = e.target.checked;
								if (e.target.checked) {
									this.selected[e.target.getAttribute('rel')].push(e.target.value);
								} else {
									this.selected[e.target.getAttribute('rel')].remove(e.target.value);
								}
								this.createText(e.target.getAttribute('rel'));
								break;
							}
						}
					}.bind(this));
				}
		}

		container.setStyle('top', position.top);
		if (window.ie) {
			container.setStyle('left', position.left + 1);
		} else {
			container.setStyle('left', position.left);
		}

		var minWidth = position.width - 12;
		container.setStyle('width', 'auto');
		container.setStyle('height', 'auto');

		container.setStyle('min-width', position.width - 12);
		container.setStyle('max-height', '200px');

		this.showed = container;
		container.setStyle('display', '');
		var size = container.getCoordinates();

			if (window.ie) {
			if (size.width < minWidth) {
				container.setStyle('width', minWidth.toString()+'px');
			} else {
				container.setStyle('width', size.width + 10);
			}
			if (size.height >= 200) {
				container.setStyle('height', 200);
			}
		}


		if (window.ie) {
			var size = container.getCoordinates();
			this.iframe.setStyle('left', position.left + 1);
			this.iframe.setStyle('top', position.top);
			this.iframe.setStyle('width',size.width);
			this.iframe.setStyle('height',size.height);
		}


		this.hidden = event.target;

		if (!window.opera) {
			this.hidden.setStyle('position', 'relative');
			this.hidden.setStyle('left', '-5000px');
		}

		var pos = container.getCoordinates();

		close.setStyle('position', 'absolute');
		close.setStyle('top', pos.bottom);
		close.setStyle('left', pos.left);
		close.setStyle('width', pos.width-6);


		close.setStyle('display', '');
		if (window.ie) {
			this.iframe.setStyle('display', '');
		}
	},

	showSelection: function() {
		/*var size = this.container[this.showed.id].getCoordinates();
		if (this.selectedText[this.showed.id].length > size.width / ) {
			this.selectedText[this.showed.id] = this.selectedText[this.showed.id].substr(0, 50) + ' ...';
		}*/
		//if (window.ie) {
			$(this.showed.id+'field').value = this.selectedText[this.showed.id];
		/*} else {
			var box = $(this.showed.id+'box');
			if (box == null) {
				var pos = $(this.showed.id+'field').getCoordinates();
				var box = new Element('div', {
					'id':this.showed.id+'box',
					'styles':{
						'background-color': '#fff',
						'position':'absolute',
						'left':pos.left + 2,
						'top':pos.top + 2,
						'width':pos.width - 25,
						'overflow': 'ignore',
						'height': pos.height - 2
					}}).injectAfter($(this.showed.id+'field'));
			}
			box.innerHTML = this.selectedText[this.showed.id];
		}*/

	},

	hideAll: function() {
		//if (!this.notHide) {
			if (this.hidden != null) {
				this.hidden.setStyle('position', '');
				this.showed.setStyle('display', 'none');
				this.statusBar[this.showed.id].setStyle('display', 'none');
				this.showSelection();
				if (window.ie) {
					this.iframe.setStyle('display', 'none');
				}
			}
		//}
		this.notHide = false;
	}


});
SelectCheckBox.implement(new Events, new Options);



function ShowOrHideCommission(id) {
	var inquiry = document.getElementById(id);
	inquiry.className = (inquiry.className == 'inquiryCollapsed') ? 'inquiryExpanded' : 'inquiryCollapsed';
}

var components = new Array();
window.addEvent('domready', function() {
	stepForm = new StepForm();
	var selects = new SelectCheckBox();

	new mCalendar($$('.datePicker'));
	
	var id = $time().toString() + 'cpv';
	components[id] = new treeSelect($('cpvComponent'), id);

	id = $time().toString() + 'nut';
	components[id] = new treeSelect($('cpvComponentNut'), id, { dataSource: 'nut' });

});
