/* CSS background image */
function newImage(url, cssClass, title) {
  var $div = $("<div>").css("background-image", "url(" + url + ")");
  if (cssClass) $div.addClass(cssClass);
  if (title) $div.attr("title", title);
  var html = $div.wrap("<div>").parent().html();
  $div.unwrap();
  return html;
}

var flash_contentVersion = 8;
var flash_contentPathSuffix = '/flash/';
var flash_defaultImage = '/www/images/common/1x1.gif';

/*
 FlashReplace is developed by Robert Nyman, http://www.robertnyman.com. License and downloads: http://code.google.com/p/flashreplace/
 */
var FlashReplace = {
  elmToReplace : null,
  flashIsInstalled : null,
  defaultFlashVersion : 8,
  replace : function (elmToReplace, src, id, width, height, version, params) {
    this.elmToReplace = document.getElementById(elmToReplace);
    this.flashIsInstalled = this.checkForFlash(version || this.defaultFlashVersion);
    if (this.elmToReplace && this.flashIsInstalled) {
      var obj = '<object' + ((window.ActiveXObject) ? ' id="' + id + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" data="' + src + '"' : '');
      obj += ' width="' + width + '"';
      obj += ' height="' + height + '"';
      obj += '>';
      var param = '<param';
      param += ' name="movie"';
      param += ' value="' + src + '"';
      param += '>';
      param += '';
      var extraParams = '';
      var extraAttributes = '';
      for (var i in params) {
        extraParams += '<param name="' + i + '" value="' + params[i] + '">';
        extraAttributes += ' ' + i + '="' + params[i] + '"';
      }
      var embed = '<embed id="' + id + '" src="' + src + '" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '"';
      var embedEnd = extraAttributes + '></embed>';
      var objEnd = '</object>';
      this.elmToReplace.innerHTML = obj + param + extraParams + embed + embedEnd + objEnd;
      return true;
    }
    return false;
  },

  checkForFlash : function (version) {
    this.flashIsInstalled = false;
    var flash;
    if (window.ActiveXObject) {
      try {
        flash = new ActiveXObject(("ShockwaveFlash.ShockwaveFlash." + version));
        this.flashIsInstalled = true;
      }
      catch(e) {
        // Throws an error if the version isn't available
      }
    }
    else if (navigator.plugins && navigator.mimeTypes.length > 0) {
      flash = navigator.plugins["Shockwave Flash"];
      if (flash) {
        var flashVersion = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+)\s.*/, "$1");
        if (flashVersion >= version) {
          this.flashIsInstalled = true;
        }
      }
    }
    return this.flashIsInstalled;
  }
};

function flash_write(siteName, fileBaseName, width, height) {
  var path = '/site/' + siteName + flash_contentPathSuffix;
  var swfFilePath = path + fileBaseName + '.swf';
  var jpgFilePath = path + fileBaseName + '.jpg';

  document.write('<div class="flash-static" id="' + fileBaseName + '"></div>');

  if (!FlashReplace.replace(fileBaseName, swfFilePath, fileBaseName + '-id', width, height, flash_contentVersion,
  {
    wmode : "transparent",
    quality: "high",
    bgcolor: "#ffffff"
  })) {
    var elem = document.getElementById(fileBaseName);
    if (elem) {
      elem.innerHTML = '<img src="' + jpgFilePath + '" alt="Flash Movie" ' +
                       'border="0" width="' + width + '" height="' + height + '">';
    }
  }
}

function flash_sfId(filepath) {
  var x = 'x' + new Date().getTime() + 'x';

  for (var i = 0; i < filepath.length; ++i) {
    var c = filepath.charAt(i).toLowerCase();
    if ((c >= 0 && c <= 9) || (c >= 'a' || c <= 'z')) {
      x = x + c;
    } else {
      x = x + '_';
    }
  }

  return x;
}

function flash_component(swfFilePath, width, height) {
  var backupImage;
  var backupImageUrl;
  var containerIdForFlash;
  var flCompId = flash_sfId(swfFilePath);
  if (arguments.length > 3) {
    backupImage = arguments[3];
  }
  if (arguments.length > 4) {
    backupImageUrl = arguments[4];
  }
  if (arguments.length > 5) {
    containerIdForFlash = arguments[5];
  }
  document.write('<div class="flash-component" id="' + flCompId + '"></div>');
  if (!containerIdForFlash) containerIdForFlash = flCompId;
  if (!FlashReplace.replace(containerIdForFlash, swfFilePath, flCompId + '-id', width, height, flash_contentVersion,
  {
    wmode : "transparent",
    quality: "high",
    bgcolor: "#ffffff"
  })) {
    var elem = document.getElementById(containerIdForFlash);
    if (elem) {
      if (!backupImage || backupImage == '' || backupImage == 'null') {
        backupImage = flash_defaultImage;
      }
      var htmlSrc = '<img src="' + backupImage + '" alt="Flash Movie" ' +
                    'border="0" width="' + width + '" height="' + height + '">';

      if (!(!backupImageUrl || backupImageUrl == '' || backupImageUrl == 'null')) {
        htmlSrc = '<a href="' + backupImageUrl + '">' + htmlSrc + '</a>';
      }

      elem.innerHTML = htmlSrc;
    }
  }
}

var IBERollingImages = Class.extend(
  {
    init : function(args) {
      this.args = $.extend({
                             rollingImages : undefined,
                             placeHolderId : undefined,
                             cssClass : ''
                           }, args);
      validateArgument(args.rollingImages, {rules:{allowUndefined:false}}, "args.rollingImages");
      validateArgument(args.placeHolderId, {rules:{allowUndefined:false}}, "args.placeHolderId");
      validateArgument(args.cssClass, {rules:{allowUndefined:false, requireString : true}}, "args.placeHolderId");

      this.rollingImages = args.rollingImages;
      this.placeHolderId = args.placeHolderId;
      this.cssClass = args.cssClass;
    },

    startSlideShow : function() {
      var that = this,
        $placeHolder = $('#' + that.placeHolderId),
        images = [],
        prevIndex = 0,
        nextIndex = 0,
        duration = 0,
        numImages = that.rollingImages.length;

      function textStyleFunctionCallback(c) {
        var r = '';
        r += 'z-index: 300;';
        r += 'position:absolute;';
        r += 'width:100%;';
        r += 'left:0px;';
        if (c) {
          if (c.indexOf('middle') >= 0) {
            r += 'top:40%;';
          } else if (c.indexOf('top') >= 0) {
            r += 'top:0;';
          } else if (c.indexOf('bottom') >= 0) {
            r += 'bottom:0;';
          }
        }
        return r;
      }

      function getTextConfigHtml(rollingImageItem) {
        var textConfigDiv = '', config = rollingImageItem.textConfig;
        if (config && config.length) {
          for (var i = 0; i < config.length; ++i) {
            textConfigDiv += '<div style="' + textStyleFunctionCallback(config[i].cssClass) + '" class="tc rc ' + config[i].cssClass + '"><div class="t ' + config[i].cssClass + '">' + config[i].displayText + '</div></div>';
          }
        }
        return textConfigDiv;
      }

      function createHtmlForRollingImageItem(rollingImageItem) {
        var img = new Image();
        img.src = rollingImageItem.imageSrc;

        return '<a href="' + rollingImageItem.href + '"' +
               (rollingImageItem.hrefId ? (' id="' + rollingImageItem.hrefId + '"') : '') +
               (!rollingImageItem.hrefId && rollingImageItem.title ? (' title="' + rollingImageItem.title + '"') : '') +
               (rollingImageItem.target ? (' target="' + rollingImageItem.target + '"') : '') +
               ' class="none absolute ri-a">' +
               getTextConfigHtml(rollingImageItem) +
               '<div class="t-im"><img src="' + rollingImageItem.imageSrc + '"' +
               (rollingImageItem.title ? (' alt="' + rollingImageItem.title + '"') : '') +
               ' class="' + that.cssClass + ' im"/>' +
               '</div></a>';
      }

      function setPrevAndNextIndex() {
        prevIndex = nextIndex;
        nextIndex = ((prevIndex + 1) > (numImages - 1)) ? 0 : (prevIndex + 1);
      }

      function slideshow() {
        setPrevAndNextIndex();
        createImgHtmlAndAppendToDom(nextIndex);
        var imageToHide = images[prevIndex], imageToShow = images[nextIndex],
          displayTimeInMilliSeconds = Math.max(2000, that.rollingImages[nextIndex].displayTimeInSeconds * 1000);
        setTimeout(function() {
          $(imageToHide).fadeOut(duration);
          $(imageToShow).fadeIn(duration, function() {
            slideshow();
          });
        }, displayTimeInMilliSeconds);
      }

      function createImgHtmlAndAppendToDom(index) {
        if (index !== undefined && index < numImages && images.length < numImages) {
          var rollingImage = that.rollingImages[index], $html = $(createHtmlForRollingImageItem(rollingImage));
          $placeHolder.append($html);
          images.push($html);
        }
      }

      function setLongestTransitionDuration() {
        for (var i = 0; i < numImages; i++) {
          duration = Math.max(duration, that.rollingImages[i].transitionTimeMilliseconds);
        }
      }

      function setup() {
        if (numImages) {
          setLongestTransitionDuration();
          createImgHtmlAndAppendToDom(0);
          $(images[0]).fadeIn('fast');
        }
        if (numImages > 1) slideshow();
      }

      setup();
    }
  });
