YUI().use('node', 'anim', 'event', function(Y) {

	var titles;
	var titlesY;
	var lastindex;

	var curheadY;
	var curheadNode;

	var curscroll;
	var tmpcont;
	var scrollani;

	var init = function () {
		titles = Y.all('#contcol h1');
		curheadNode = Y.one('#curtitle h1');
		curheadY = parseInt( Y.one('#curtitlehidden h1').getY() );

		scrollani = new Y.Anim({
			node: document,
			duration: 1,
			easing: Y.Easing.easeOut
		});

		lastindex = titles.size() -1;
		titlesY = Array();
		titles.each(getpos);

		Y.all('#subnav a').on('click', autoscroll);

	/*
		console.log(titlesY );
		console.log(lastindex);
		console.log(curheadNode);
		console.log(curheadY);
	*/
		Y.on("scroll", dyntitle, window, Y);

		dyntitle();
	}

	var getpos = function(curnode, curindex, listinstance){
		titlesY[curindex] = parseInt( curnode.getY() ) -50;
	}

	var dyntitle = function (){
		//alert('scroled');
		curscroll = parseInt( curheadNode.get('docScrollY') );
		titles.some(checkpos);
	}

	var checkpos = function(curnode, curindex, listinstance){

		var tmpy = titlesY[curindex] - curscroll;
		//console.log(tmpy );
		if(tmpy <  curheadY){
			tmpcont = curnode.get('text');
			if(curindex == lastindex){
				curheadNode.setContent( tmpcont );
				return true;
			}else{
				return false;
			}
			return false;
		}else{
			curheadNode.setContent( tmpcont );
			return true;
		}
	}

	var autoscroll = function (e){
		e.preventDefault();

		//console.log( e.target.getAttribute('href') );
		var targetnode = Y.one( e.target.getAttribute('href') );
		var to = parseInt( targetnode.getY() - curheadY )  -30;
		//window.scrollTo(0, to);

		
		scrollani.set('to', { scroll: [0, to] });
		scrollani.run();


		//dyntitle();
	}


	

	Y.on("load", init, window, Y);

});


