// flag to decide whether to run the kv-changing interval or not
var runInterval = true;
// rotation delay in milliseconds
var kvInterval = 10000;

function changeKeyvisual(current, next){
  $('#kv_'+current).fadeOut(500, function(){
    var title = $('#kv_'+current).attr('title');
    $('#kv_'+next).fadeIn(500);
  });
}

function getCurrentPos() {
  var id = $('img.keyvisual:visible').attr('id');
  if(!id) return 0; // don't rotate if no KeyVisual objects are found
  else return parseInt(id.substr(3,4));
}

function nextKv(kvCounter){
  var nextPos = 1;
  var currentPos = getCurrentPos();
  if (currentPos == kvCounter) {
    nextPos = 1;
  } else {
    nextPos = currentPos + 1;
  }
  changeKeyvisual(currentPos, nextPos);
}

function prevKv(kvCounter){
  var nextPos = 1;
  var currentPos = getCurrentPos();
  if (currentPos == 1) {
    nextPos = kvCounter;
  } else {
    nextPos = currentPos - 1;
  }
  changeKeyvisual(currentPos, nextPos);
}

function kvRotation(){
  if (runInterval){
    var kvCounter = $('img.keyvisual').length;
    if (kvCounter > 1) {
      nextKv(kvCounter);
    }
  }
}

$(document).ready(function(){
  if($('#kv_1') != null) {
    window.setInterval('kvRotation()', kvInterval);
  }
});

