$(document).ready(function() {
  var imgs = '';
  var switches = '';
  var j = 0;
  var k = 0;
  var s;
  for(var i = 0; i < count; i++) {
    if(i == 0 && dir == 'osrodki')
    {
       imgs += '<a href="/pl/oferta/polecane.html"><img src="images/rotator/'+dir+'/'+(i+1)+'.jpg" id="start'+i+'" /></a>';
    } else {
       imgs += '<img src="images/rotator/'+dir+'/'+(i+1)+'.jpg" id="start'+i+'" />';
    }
    switches = '<div class="switch switch'+i+'">'+(i+1)+'</div>' + switches;
  }
  $("body").append("<div class=\"box-wide rotate\"><div class=\"rotate-container\">"+imgs+"<div class=\"rotate-switches\">"+switches+"<div class=\"bg\"></div></div></div></div>");
  $(".switch0").addClass("active");
  $(".rotate img").load(function() {
    j++;
    if(j == count) {
      $(".rotate").css("display", "block");
      $(".rotate-switches .bg").fadeTo(1, 0.4);
      $(".rotate-switches").animate({bottom : '+=0'}, 500, function() {
        $(".rotate-switches").animate({bottom : '-=0'}, 1200);
      });
      bind_switches();
      s_interval();
    }
  });
  function switch_img(thisone, nextone) {
    if(thisone != nextone)
    {
      $(".rotate-switches .switch").unbind("click");
      $("#start"+thisone).fadeOut(1000, function(){
        bind_switches();
     });
       $("#start"+nextone).fadeIn(1000);
      $(".switch"+thisone).removeClass("active");
      $(".switch"+nextone).addClass("active");
    }
  }
  function s_interval() {
    s = setInterval(function() {
      thisone = k%count;
      nextone = (k+1)%count;
      k++;
      switch_img(thisone, nextone);
    }, 6000);
  }
  function c_interval() {
    clearInterval(s);
  }
  function bind_switches() {
    $(".rotate-switches .switch").click(function() {
      thisone = k%count;
      nextone = $(this).html()-1;
      if(thisone != nextone) {
        c_interval();
        k = nextone;
        switch_img(thisone, nextone);
        s_interval();
      }
    });
  }

  $('.rotate').live('mouseover',function(){
    c_interval();
  });
  
  $('.rotate').live('mouseout',function(){
    s_interval();
  });

});
