/**
 * @author Georg Nebel
 * Rotierende Top-Jobs
 */
var elmRelPosition = new Array();
var rotateTopElement = 0;

jQuery.fn.listrotate = function(options){
	settings = jQuery.extend({
		pause: 0,
		duration:2500
	},options);
	
	init(this,settings);
	
	function init(container,settings){
//		container.after("<div id='debug'>Test</div>"); //Test

		var rotCont = container.children().first();
		var elms = rotCont.children();
		var contHeight = container.innerHeight();
		var elemsLenght = elms.length;
		//container.wrapInner("<div id='tobjobs-rotate' />");
		if(rotCont.height()>contHeight) {
			for(var i=0; i<elemsLenght; i++){
				var elm = $(elms[i]);
				elmRelPosition[i] = elm.position().top;
				if (elmRelPosition[i] < contHeight){
					rotCont.append(elm.clone());
				}
			}
			elms = rotCont.children();
			elmRelPosition[i] = $(elms[i]).position().top;
			if(settings.pause==0){
				settings.duration = settings.duration * i;
			}	
			shift(container,settings);
		}
		container.mouseover( function(){
			rotCont.stop(true);
		});
		container.mouseout( function(){
			rotateTopElement=elmRelPosition.length-2;
			shift(container,settings);

		});
	};
	
	function shift(container,settings){
		var rotCont = container.children().first();		
		if(rotateTopElement>=elmRelPosition.length-1){
			rotateTopElement = 0;
			rotCont.css({top:0});
		}
		if(settings.pause==0){
			rotateTopElement=elmRelPosition.length-2; // full shift
		}
		

		var elmPosStart = rotCont.position().top;
		var elmPos =  -elmRelPosition[++rotateTopElement] ;
		var rotDur = settings.duration * (elmPosStart-elmPos) / (-elmPos);
//		$('#debug').text( elmPosStart + ' - ' + elmPos  + ' - ' + rotDur);	
		rotCont.animate({
			top: elmPos},rotDur,'linear',
			function(){
				setTimeout( function() {
					shift(container,settings);
				},settings.pause);				
			}
		);


	};
};
$(document).ready(function(){
	$("#topjobs").listrotate();
});
