var F4GKImage = function(adimage, adalttext, adlink, adtracking) {
  var cacheImage = function(theImage) {
	var x = new Image();
	x.src = theImage;
	return x;
  }

  this.adAltText = adalttext;
  this.adImage = cacheImage(adimage);
  if (adtracking == "") {
    this.adLink = adlink;
  } else {
    this.adLink = "javascript:clickThru('" + adtracking + "','" + adlink + "');";
  }
}


var F4GKImageRotator = function(rotatorId) {
  this.ads = new Array();
  this.speed = 10000;  // rotation * 100
  this.lastIndex = 0;
  this.maxIndex = 0;
  this.linkElement = "#link-" + rotatorId;
  this.imageElement = "#img-" + rotatorId;
  this.intervalId = 0;
}

F4GKImageRotator.prototype.addImage = function(newImage) {
  this.ads.push(newImage);
}

F4GKImageRotator.prototype.setSpeed = function(newSpeed) {
  if (newSpeed != 0) {
    this.speed = newSpeed * 100;
  }
}

F4GKImageRotator.prototype.rotate = function() {
  this.lastIndex++;
  if (this.lastIndex >= this.maxIndex) {
    this.lastIndex = 0;
  }

  jQuery(document).find(this.linkElement).attr("href", this.ads[this.lastIndex].adLink);
  jQuery(document).find(this.imageElement).attr("src", this.ads[this.lastIndex].adImage.src).attr("alt", this.ads[this.lastIndex].adAltText);
}

F4GKImageRotator.prototype.stopRotate = function() {
  if (this.intervalId != 0) {
    clearInterval(this.intervalId);
  }
}

F4GKImageRotator.prototype.startRotate = function() {
  if (this.intervalId == 0 && this.ads.length > 0) {
    this.maxIndex = this.ads.length;
    this.intervalId = setInterval(bind(this, this.rotate), this.speed);
  }
}


var F4GKRotator = function() {
  this.rotators = new Array();
}

F4GKRotator.prototype.startRotate = function() {
  for(aRotator in this.rotators) {
    this.rotators[aRotator].startRotate();
  }
}

F4GKRotator.prototype.stopRotate = function() {
  for(rotator in this.rotators) {
    this.rotators[aRotator].stopRotate();
  }
}

F4GKRotator.prototype.add = function(rotatorid, adimage) {
  if (this.rotators[rotatorid] == undefined) {
    this.rotators[rotatorid] = new F4GKImageRotator(rotatorid);
  }
  var rotator = this.rotators[rotatorid];
  rotator.addImage(adimage);
}

F4GKRotator.prototype.setOptions = function(rotatorid, rotationSpeed) {
  if (this.rotators[rotatorid] != undefined) {
    this.rotators[rotatorid].setSpeed(rotationSpeed);
  }
}

function bind(obj, meth) {
  return function() { 
    meth.call(obj); 
  }; 
}

