YUI().use('anim', 'io', 'history', 'debug', function(Y) {

	function hideDivs(selector) {
		var nodes = Y.all(selector);
		//Y.log("obiektów to togglowania: "+nodes._nodes.length);
		nodes.each(function(node) {
			var title = node.get('previousSibling');
			title.addClass('pointer');
			var anim = slider(node, function() {
				title.append('<span class="show">zobacz&nbsp;&raquo;</span>');
			});
			anim.run();
		})
		if(nodes._nodes.length>=1) {
			Y.on("click", toggleit, '.pointer');
		}
	}
	
	function hideMenuItems(selector) {
		var nodes = Y.all(selector);
		nodes.each(function(node) {
			var parent = node.ancestor('li'), ul = node.one('ul') ,anim;
			if(ul) {
				if(!node.anim) {
					node.addClass('expanded');
					node.anim = slider(ul, function(){
						node.toggleClass('collapsed');
						node.toggleClass('expanded');
					});
				}
				anim = node.anim;
				anim.run();
			}
			node.one('a.lvl_2').on('mouseover', function(){
				anim.set('reverse', !anim.get('reverse'));
				anim.run();
			})
		})
	}
	
	function slider(node, endFn) {
		var height = node.getComputedStyle('height');
		var anim = new Y.Anim({
			node: node,
			to: { height: "0px" },
			from: {height : height},
			easing: Y.Easing.backIn
		});
		if(Y.Lang.isFunction(endFn)) {
			anim.on('end', endFn);
		}
		return anim;
	}

	function toggleit(){
		var that = this;
		this.toggleClass('closed');
		var rev = this.hasClass('closed');
		//Y.log('closing: '+rev);
		var position = this.getY();
		var center = 0.5*(this.get('docHeight'))
		var wincenter = 0.5*(this.get('winHeight'))

		function toggle() {
			that.one('.show').set('innerHTML', rev?'&laquo;&nbsp;zwiń':'zobacz&nbsp;&raquo;');
			var n = that.get('nextSibling');
			var content = n.plug(Y.Plugin.NodeFX, {
				to: { height: 0 },
				from: {
					height: function(node) { // dynamic in case of change
						return node.get('scrollHeight'); // get expanded height (offsetHeight may be zero)
					}
				},
				reverse: rev,
				easing: Y.Easing.easeBoth,
				duration: 0.5
			});
			content.fx.run();
		}

		if(rev && position>wincenter) {
			node = window;
			var move = new Y.Anim({
				node: node,
				to: {
					scroll: function(node) {
						return [position, position-300]
					}
				},
				easing: Y.Easing.easeOut
			})
			move.on('end', toggle());
			move.run();
		} else {
			toggle();
		}
	}

	function slideit(e){
		var that = this;
		if(!that.hasClass('outer')) {
			e.preventDefault();
			var url = this.get('href');
			ind = url.lastIndexOf('/')
			path = url.slice(ind+1);
			url = url.replace(path, "/remote"+path);
			node = Y.one("#content_inner");
			var anim = new Y.Anim({
				node: node,
				to: { marginLeft:  "999px" },
				easing: Y.Easing.backIn
			});
			anim.on('end', function() {
				Y.History.navigate('nav', path);
			});
			if(Y.History.getCurrentState('nav') !== path) {
				Y.one('#main_loader').removeClass('hidden');
				anim.run();
			}
		}
	}

	var bind_events = function() {
		hideDivs(".hide");
		Y.on("click", slideit, 'a');
		Y.on('submit', send_mail, '#contact-form');
		$(function() {
			$('a.gallery').lightBox(); // Select all links with lightbox class
  		});
	}
	
	Y.on('domready', function() {
		hideMenuItems("li.lvl_2");
		Y.on("click", slideit, '#main_menu a');
		bind_events();
	});

	function send_mail(e) {
		e.preventDefault();

		var that = this;
		var name = Y.one('#contact-form-input-name');
		var contact = Y.one('#contact-form-input-contact');
		var question = Y.one('#contact-form-input-question');


		var info = '<span class="validate"></span>';

		var valid = true;
		if(name.get('value')==='') {
			name.previous('label').append(info);
			name.previous('label').one('.validate').set('text', '[Wpisz imię]');
			valid = false;
		}
		if(contact.get('value')==='') {
			contact.previous('label').append(info);
			contact.previous('label').one('.validate').set('text', '[Wpisz formę kontaktu]');
			valid = false;
		}
		if(question.get('value')==='') {
			question.previous('label').append(info);
			question.previous('label').one('.validate').set('text', '[Wpisz pytanie]');
			valid = false;
		}

		if(valid) {
			var url = that.get('action');
			ind = url.lastIndexOf('/')
			path = url.slice(ind+1);
			url = url.replace(path, "remote_"+path);
			var cfg = {
				method: 'POST',
				form: {
					id: that,
					useDisabled: true
				},
				on: {
					start: function(id, args) {
						pageTracker._trackPageview("/"+url );
						that.append('<div id="sending">Trwa wysyłanie formularza...</div>');
					},
					success: function (id, o, args) {
						that.set('innerHTML', o.responseText);
					},
					failure: function (id, o, args) {
						that.prepend('<p class="error">Wystąpił problem z połączeniem. Prosimy spróbować później.</p>');
						Y.one('#sending').remove();
					}
				}
			};
			Y.io(url, cfg);
		}
		return false;
	}

	Y.History.subscribe('history:ready', initializeNavigationBar);
	Y.History.initialize('#yui-history-field', '#yui-history-iframe');

	var bookmarkedSection = Y.History.getBookmarkedState('nav');
	var querySection = window.location.pathname;
	querySection = querySection.slice(1);
	var initSection = bookmarkedSection || querySection || 'strona-glowna';

	Y.History.register('nav', initSection).subscribe('history:moduleStateChange', loadSection);

	function initializeNavigationBar() {
		currentSection = Y.History.getCurrentState('nav');
		Y.log('teraz jestesmy tu: '+currentSection);
		Y.log('adres wskazuje na: '+querySection)
		Y.log('bookmarkedSelection: '.bookmarkedSelection);
		if(querySection!==currentSection) {
			loadSection(currentSection);
		}
	}

	function loadSection(url) {
		Y.log("Load selection odpalone...");
		cfg = {
			on: {
				start: function(){
					pageTracker._trackPageview("/"+url );
				},
				success: function (id, o, args) {
					Y.one('#content').set('innerHTML', '<div id="content_inner">'+o.responseText+'</div>');
					Y.one("#content_inner").set('id', "content_inner1");
					Y.one('#main_loader').addClass('hidden');
					var anim = new Y.Anim({
						node: Y.one("#content_inner1"),
						to: { marginLeft:  0 },
						easing: Y.Easing.backOut
					});
					anim.on('end', function() {
						if(Y.one("#content_inner1")) {
							Y.one("#content_inner1").set('id', "content_inner");
						}
						Y.all('#main_menu li').removeClass('active');
						if(window.that === undefined) {
							var a_id = url.slice(0, url.indexOf('.'));
							var a = Y.one("#menu-"+a_id);
						} else {
							var a = that
						}
						while(a.ancestor('li')) {
							a = a.ancestor('li');
							a.addClass('active');
						}
						bind_events();
						animateBg(url);
					})
					anim.run();
				},
				failure: function (id, o, args) {
					//Y.one("#content_inner").remove;
					Y.get('#content').set('innerHTML', '<div id="content_inner"><h2><span>Przepraszamy!</span> Wystąpił problem z połączeniem z wybraną stroną. Poczekaj chwilę lub wróć do strony głównej.</h2></div>');

				}
			}
		};
		Y.io('remote/'+url, cfg);
	}

	var bgAnim = new Y.Anim({
		node: '#bg2',
		from : { opacity: 1},
		to: { opacity: 0 },
		duration: 0.5
	})
	bgAnim.on('end', function() {
		Y.later(15000, this, function() {
			this.set('reverse', !this.get('reverse'));
			this.run();
		});
	})
	
	var that = this;

	Y.later(15000, bgAnim, function(){
		this.run();
	});

	var bgAnim3 = new Y.Anim({
		node: '#bg3',
		from: {opacity: 0},
		to: { opacity: 1 },
		duration: 0.5
	})
	
	function animateBg(state) {
		if(state === 'projekt-fitbells.html') {
			Y.one('#bg3').setStyle('opacity', '0');
			Y.one('#bg3').removeClass('hidden');
			bgAnim3.set('reverse', false);

			bgAnim3.run();
		} else {
			if(!Y.one('#bg3').hasClass('hidden') && Y.one('#bg3').getStyle('opacity') === '1') {
				bgAnim3.set('reverse', true);
				bgAnim3.run();
				
			}
		}
	}

});
