/*=====================================================================
 * Image Rotation code using the Scriptaculous JavaScript framework.
 *
 * Includes limited support for IE5 on the Mac - which isn't supported
 * by the Scriptaculous framework.
 *=====================================================================*/

// Global detect Mac IE...not supported by Prototype.js
var SOCS_isIEMAC = (navigator.userAgent.indexOf('Mac') != -1 && navigator.userAgent.indexOf('MSIE') != -1);

// Limited support for IE5 on the Mac = display 1st image
function SOCS_IEMAC_ImageRotator(imageList, imagePath, alignment) {
  // Default passed in variables in case some are missing
  var imageList = imageList || '';
  var imagePath = imagePath || '';
  var alignment = alignment || 'left';

  // Validation
  if (imagePath == '') throw 'SOCS_IEMAC_ImageRotator.imagePath is empty';

  if (this.imageList != '') {
    var images = imageList.split(',');

    // Pick a random image from the array - if more than one
    var i = 0;
    if (images.length > 1) {
      // Generate a seed for the random number generator
      var randSeed = new Date().getSeconds();
      i = Math.floor(Math.random(randSeed) * images.length);
    }
    document.getElementById('imgRotator1').src = imagePath + images[i];

    // Need to NOT float the imgRotator div - will disappear in IE5 on the mac if floated,
    // but IE6-7 on Win needs it.
    if (alignment == 'right') {
      // Additional rules needed if image rotator is aligned to the right
      document.getElementById('imgRotator').style.cssText = 'float:none; position:absolute; left:100%;';
    } else {
      document.getElementById('imgRotator').style.cssText = 'float:none;';
    }
  } else {
    // No images - hide the img tag
    document.getElementById('imgRotator1').style.cssText = 'display:none;';
  }
}

var SOCS_ImageRotator = Class.create();
SOCS_ImageRotator.prototype = {
  // Constructor
  initialize: function(imageList, imagePath, imageWait, fadeDuration, maxImages) {
    // Default passed in variables in case some are missing
    this.imageList = imageList || '';
    this.imagePath = imagePath || '';
    this.imageWait = imageWait * 1000 || 5000;
    this.fadeDuration = fadeDuration || 1;
    this.maxImages = maxImages || 999999; // Magic number will ensure number of images in array is used

    // Validation
    if (this.imagePath == '') throw 'SOCS_ImageRotator.imagePath is empty';

    // -1 passed in means "turn off" the rotator
    if (this.maxImages == -1) this.maxImages = 0;

    // Cache the first <img> tag
    this.firstImgTag = $('imgRotator1');

    this.imageIndex = this.numImages = 0;

    if (this.imageList != '') {
      // Create an array of images from the comma-delimited string and then get the image count
      this.images = this.imageList.split(",");
      this.numImages = this.images.length;
    }

    if (this.numImages > 0) {
      // Cache how many images will be used in the rotation
      this.numImages = (this.numImages > this.maxImages ? this.maxImages : this.numImages);

      if (this.numImages > 1) {
        // Shuffle the array if there are more than two images
        this.shuffle();

        // If multiple images, set it up so that the rest of the code runs when the page is done loading
        Event.observe(window, 'load', this.initRotation.bind(this));
      }

      // Assign an image to the 1st <img>
      this.firstImgTag.src = this.imagePath + this.images[0];
    } else {
      // If no images, hide the 1st <img>
      this.firstImgTag.hide();
    }
  },

  // Build remaining <img> tags and start the rotation
  initRotation: function () {
    // Hack - Until jQuery rewrite
    // Cache a couple things at the beginning - that will be used EACH time an image is faded.
    if ($('flag_mask') != undefined) {
      this.flagMaskExists = true;
      // No test for existence of 'logoImage1' - cuz 'flag_mask' is nested inside 'logoImage1'
      this.logoImage1 = $('logoImage1');
    } else {
      this.flagMaskExists = false;
    }

    this.buildImageTags();
    setInterval(this.displayNextImage.bind(this), this.imageWait);
  },

  // Creates the remaining <img> tags and adds them to the DOM
  buildImageTags: function () {
    // Create a template for the HTML
    var imgTemplate = new Template('<img id="imgRotator#{id}" src="#{src}" alt="" width="#{width}" height="#{height}" />');

    var tmp = this.firstImgTag;
    var width = this.firstImgTag.width;
    var height = this.firstImgTag.height;

    // Add up to "numImages" more <img> tags - 1st already exists, so start at #2
    $R(2, this.numImages).each(function(n) {
      new Insertion.After(tmp, imgTemplate.evaluate({
                                                      id: n,
                                                      src: this.imagePath + this.images[n-1],
                                                      width: width,
                                                      height: height
                                                    }));

      // Move the pointer to the <img> tag just created and hide it
      tmp = tmp.next('img');
      if (tmp) tmp.hide();
    }.bind(this));
  },

  // Uses Scriptaculous to fade/appear each image in the rotation - starting over when last image is reached
  displayNextImage: function () {
    var fadeIndex = this.imageIndex + 1;

    // Hack until jQuery rewrite - IE6-7 need the PNG mask to be placed "above" the images that are fading EACH time the
    // images fade - comment out to see what happens when the transition occurs.
    if (this.flagMaskExists) this.logoImage1.style.zIndex = '2';

    // Make sure image to fade is above the image to show
    $('imgRotator' + fadeIndex).style.zIndex = '1';

    // Increment to the next image rolling over the counter if necessary
    this.imageIndex++;
    if (this.imageIndex == this.numImages) this.imageIndex = 0;

    // Make sure image to show is below the image to fade and then show the image
    $('imgRotator' + (this.imageIndex + 1)).style.zIndex = '0';
    $('imgRotator' + (this.imageIndex + 1)).show();

    // Fade the image - doing it this way the user doesn't see the background behind the images
    // as one fades and the other appears.
    Effect.Fade('imgRotator' + fadeIndex, { duration:this.fadeDuration, from:1.0, to:0.0 });
  },

  // Randomly interchange elements in the images array
  shuffle: function () {
    // Generate a seed for the random number generator
    var randSeed = new Date().getSeconds();
    var i = this.images.length, j, t;

    while( i ) {
      j = Math.floor( ( i-- ) * Math.random(randSeed) );
      t = this.images[i];
      this.images[i] = this.images[j];
      this.images[j] = t;
    }
  }
}

