var rotatorsCnt = 0;
var shownElements = 3;
var rotatorPos = 0;
var rotatorMoving = false;
var rotatorHover = false;
$(function() {
	$(".rotators").each(function() {
		var $this=$(this), subels = $(".rotatorEl", $this), nextLink=$(".next", $this.next()), prevLink=$(".prev", $this.next());
    $(".rotatorEl", $this).hide();
    rotatorsCnt = $(".rotatorEl",this).length;
    nextLink.click(function(){
      rotatorMove('-');
      return false;
    });
    prevLink.click(function(){
      rotatorMove('+');
      return false;
    });
	});
	rotatorInit();
  setTimeout(function(){ rotatorAutoMove(); }, 5000 );

});

function rotatorAutoMove(){
  if (!rotatorMoving && !rotatorHover){
    rotatorMove('-');
  }
  setTimeout(function(){ rotatorAutoMove(); }, 5000 );
}

function rotatorMove(dir){
  if (!rotatorMoving){
    var w = getWidth($(".rEl:eq(0)"));
    rotatorMoving = true;
    $(".rotatorsFrame").animate({left: dir+'='+w},1000,function(){
      if (dir == '-') rotatorPos = (rotatorPos+1)%rotatorsCnt;
      else rotatorPos = (rotatorPos+rotatorsCnt-1)%rotatorsCnt;
      rotatorInit();
      rotatorMoving = false;
    });
  }
}

function rotatorInit(){
  var startElement = rotatorPos;
  var count = 0;
  var startPos = 0;
  $(".rEl").remove();
  $(".rotatorsFrame").css('left','0px');
  for (var i = startElement; i<startElement+shownElements+2; i++){
    el = $(".rotatorEl:eq("+(i%rotatorsCnt)+")");
    el2 = el.clone().appendTo($(".rotatorsFrame"));
    el2.addClass("rEl");
    if (count==0) startPos = getWidth(el2) * -1;
    el2.css({left : startPos+'px'});
    el2.show();
    count++;
    startPos += getWidth(el2);
    el2.mouseover(function(){
      rotatorHover = true;
    });
    el2.mouseout(function(){
      rotatorHover = false;
    });
  }
}
function getWidth(element){
  var totalWidth = element.width();
  totalWidth += parseInt(element.css("padding-left"), 10) + parseInt(element.css("padding-right"), 10); //Total Padding Width
  totalWidth += parseInt(element.css("margin-left"), 10) + parseInt(element.css("margin-right"), 10); //Total Margin Width
  return totalWidth;
}
