var NG = new Class({
	initialize : function() {
		var footer = $('footer');
		var h = $('container').getPosition().y + $('container').getSize().y;
		var h2 = window.getSize().y - footer.getSize().y - 33;
		if (h2 > h) { h = h2; }
		$('footer').setStyles( { 'position' : 'absolute', 'top' : h + 33 } );

		var h = $('container').getPosition().y;
		$('adsenseleft').setStyles( { 
			'position' : 'absolute',
			'top' : h,
			'left' : (window.getSize().x / 2 - 390 - 168) + "px"
		});
		$('adsenseright').setStyles( {
			'position' : 'absolute',
			'top' : h,
			'left' : (window.getSize().x / 2 + 390 + 8) + "px"
		});			
	}
});

window.addEvent('domready', function() { new NG(); });

showBranches = function(list) {
	var parent = list[0].parent_branche_code;	
	var ul;

	if (parent.length) {
		ul = $('branche' + parent + 'List');
	}
	else {
		ul = $('brancheList');
	}

	var len = list.length;
	for (i = 0; i < len; i++) {
		var li = new Element('li');		
		var a = new Element(list[i].num_children > 0 ? 'a' : 'span', { 'href' : 'javascript:;', 'html' : (list[i].name), 'id' : ('b' + list[i].code) });
		var aBelow = new Element('a', {'href' : 'javascript:;', 'html' : '&laquo;kies&raquo;', 'style' : 'font-weight:bold' });
		aBelow.store('item', list[i]);
		var subUl = new Element('ul', { 'id' : ('branche' + list[i].code + 'List') });
		aBelow.addEvent('click', function() {
			$('b' + brancheCode).setStyle('text-decoration', '');
			$('branche').set('html', this.retrieve('item').name);
			$('branche_hidden').set('value', this.retrieve('item').code);
			$('changeB').setStyle('display', 'none');
			brancheCode = this.retrieve('item').code;
			$('b' + brancheCode).setStyle('text-decoration', 'underline');
		});
		if (list[i].num_children > 0) {
			a.addEvent('click', function() {
				requester.get({'code' : this.get('id').substring(1)});
			});
		}
		if (list[i].code == brancheCode) {
			a.setStyle('text-decoration', 'underline');
		}
		li.adopt(a);
		li.adopt(new Element('span', { 'html' : '&nbsp;' }));
		li.adopt(aBelow);
		li.adopt(subUl);
		ul.adopt(li);
	}
	new NG();
}

var branchesFetched = 0;
var requester = new Request.JSON({url : 'branches/json', onSuccess : showBranches, 'link' : 'chain'});

changeBranche = function() {
	var tr = $('changeB');

	if (tr.getStyle('display') == 'none') {
		tr.setStyle('display', '');
	}
	else {
		tr.setStyle('display', 'none');
		return;
 	}

	if (!branchesFetched) {
		branchesFetched = 1;
		requester.get();
		if (path.length) {
			path.each(function(item) { requester.get({'code' : item })});
		}
		
	}
}
