/* FlashDetect
 * (c) 2008 Nick Stakenburg (www.nickstakenburg.com)
 */
var FlashDetect = {
  options: {
    appearDelay: .5,
    fadeDelay: 6,
    images: '../images/flashdetect/',
    message: 'Flash player #{version} required, click to download',
    updateLink: 'http://www.adobe.com/go/getflashplayer/',
    requiredVersion: 9
  },
  Browser: { IE: !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1) },
  OS: { Windows: navigator.appVersion.toLowerCase().indexOf("win") != -1 }
};

(function() {
Object.extend(FlashDetect, {
  start: function() {
    // get the image directory
    if (/^(https?:\/\/|\/)/.test(this.options.images))
      this.images = this.options.images;
    else {
      var srcMatch = /flashdetect(?:-[\w\d.]+)?\.js(.*)/;
      this.images = (($$('head script[src]').find(function(s) {
        return s.src.match(srcMatch);
      }) || {}).src || '').replace(srcMatch, '') + this.options.images;
    }

    // kijk of flash beschikbaar is
    var navigatorPlugins = (navigator.plugins && navigator.plugins.length),
     detectPlugin = function(name) {
      var detected = false;
      if (navigatorPlugins) {
        detected = ($A(navigator.plugins).pluck('name').join(',').indexOf(name) >= 0);
      }
      else {
        try { detected = new ActiveXObject(name); }
        catch (e) {}
      }
      return !!detected;
    };
    
    this.plugin = navigatorPlugins ? { flash: detectPlugin('Shockwave Flash') } :
      { flash: detectPlugin('ShockwaveFlash.ShockwaveFlash') };
    
    if (!this.plugin.flash || !detectFlashVersion(this.options.requiredVersion, 0, 0))
      this.show();
  },

  build: function() {
    this.flashdetect = new Element('div', { id: 'flashdetect' })
    .setOpacity(0)
    .insert(this.messageLink = new Element('a', {
      className: 'flashdetect_messageLink',
      target: '_blank',
      href: this.options.updateLink
    })
    .insert(new Element('div', { className: 'flashdetect_icon' })
      .setPngBackground(this.images + 'flash.png'))
    .insert(this.message = new Element('span', { className: 'flashdetect_message' })
      .update(this.options.message.replace('#{version}', this.options.requiredVersion)
    )));

    $(document.body).insert(this.flashdetect);
    this.addEvents();
  },

  addEvents: function() {
    this.flashdetect.observe('mouseover', FlashDetect.clearFade)
    .observe('mouseout', function() {
      FlashDetect.fade({ delay: FlashDetect.options.fadeDelay })
    });
  },

  show: function() {
    if (!FlashDetect.flashdetect) FlashDetect.build();
    FlashDetect.flashdetect.setOpacity(0).show();
    this.appear({ fadeAfter: true, delay: FlashDetect.options.appearDelay });
  },

  appear: function(delay) {
    FlashDetect.clearFade();
    var options = arguments[0] || {};
    return (function() {
      Appear(FlashDetect.flashdetect, { afterFinish: function() {
        if (options.fadeAfter)
          FlashDetect.fade({ delay: FlashDetect.options.fadeDelay });
      }});
    }).delay(options.delay || 0.01);
  },

  clearFade: function() {
    if (FlashDetect._fadeTimer) {
      window.clearTimeout(FlashDetect._fadeTimer);
      FlashDetect._fadeTimer = null;
    }
  },

  fade: function() {
    var options = arguments[0] || {};
    FlashDetect._fadeTimer = window.setTimeout(function() {
      Fade(FlashDetect.flashdetect);
    }, (options.delay || 0.01) * 1000);
  }
});

// helpers
function Appear(element) {
  var current = $(element).getOpacity(),
   options = arguments[1] || {};
  if (!element.visible()) element.show();
  if (current < 1) {
    setTimeout(function() {
      element.setOpacity(current += 0.05);
      Appear(element, options);
    }, 0.01);
  }
  else {
    if (FlashDetect.Browser.IE && element.style.filter)
      element.style.removeAttribute('filter');
    if (options.afterFinish) options.afterFinish.call();
  }
}

function Fade(element) {
  var current = $(element).getOpacity(),
   options = arguments[1] || {};
  if (current > 0) {
    setTimeout(function() {
      element.setOpacity(current -= 0.05);
      Fade(element, options);
    }, 0.01);
  }
  else {
    element.hide()
    if (options.afterFinish) options.afterFinish.call();
  }
}

function setPngBackground(element, url) {
  element = $(element);
  var options = Object.extend({
    align: 'top left',
    repeat: 'no-repeat',
    sizingMethod: 'crop',
    backgroundColor: ''
  }, arguments[2] || {});

  element.setStyle(arguments.callee.IEBelow7 ? {
    filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' +
      url + '\'\', sizingMethod=\'' + options.sizingMethod + '\')'
  } : {
    background: options.backgroundColor + ' url(' + url + ') ' +
      options.align + ' ' + options.repeat
  });
  return element;
}
setPngBackground.IEBelow7 = FlashDetect.Browser.IE &&
  parseFloat(/MSIE ([\d.]+)/.exec(navigator.userAgent)[1]) < 7;
Element.addMethods({ setPngBackground: setPngBackground });

function controlVersion() {
  var version, axo, e;

  // Flash 7.x+
  try {
    axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    version = axo.GetVariable("$version");
  } catch (e) { }

  // Flash 6.x
  if (!version) {
    try {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
      version = "WIN 6,0,21,0";
      axo.AllowScriptAccess = "always";
      version = axo.GetVariable("$version");
    } catch (e) {}
  }

  // Flash 4.x 5.x
  if (!version) {
    try {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
      version = axo.GetVariable("$version");
    } catch (e) { }
  }

  // Flash 3.x
  if (!version) {
    try {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
      version = "WIN 3,0,18,0";
    } catch (e) { }
  }

  // Flash 2.x
  if (!version) {
    try {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      version = "WIN 2,0,0,11";
    } catch (e) { version = -1; }
  }
  return version;
}

function getFlashVersion() {
  var version = -1;
  if (navigator.plugins && navigator.plugins.length > 0) {
    if (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']) {
      var swVer2 = navigator.plugins['Shockwave Flash 2.0'] ? ' 2.0' : '',
       flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description,
       descArray = flashDescription.split(' '),
       tempArrayMajor = descArray[2].split('.'),
       major = tempArrayMajor[0],
       minor = tempArrayMajor[1],
       revision = descArray[3];
      if (revision == '')
        revision = descArray[4];
      if (revision[0] == 'd')
        revision = revision.substring(1);
      else if (revision[0] == 'r') {
        revision = revision.substring(1);
        var dIndex = revision.indexOf('d');
        if (dIndex > 0)
          revision = revision.substring(0, dIndex);
      }
      version = major + '.' + minor + '.' + revision;
      return version;
    }
  }
  else if (FlashDetect.Browser.IE && FlashDetect.OS.Windows) {
    version = controlVersion();
  }
  return version;
}

function detectFlashVersion(reqMajor, reqMinor, reqRevision) {
  var versionString = getFlashVersion();
  if (versionString == -1 ) {
    return false;
  }
  else if (versionString != 0) {
    var versionArray = (FlashDetect.Browser.IE && FlashDetect.OS.Windows) ?
     versionString.split(" ")[1].split(",") :
     versionString.split(".");

    var Version = {
      major: versionArray[0],
      minor: versionArray[1],
      revision: versionArray[2]
    };

    if (Version.major > parseFloat(reqMajor))
      return true;
    else if (Version.major == parseFloat(reqMajor)) {
      if (Version.minor > parseFloat(reqMinor))
        return true;
      else if (Version.minor == parseFloat(reqMinor)) {
        if (Version.revision >= parseFloat(reqRevision))
          return true;
      }
    }
    return false;
  }
}

document.observe('dom:loaded', FlashDetect.start.bind(FlashDetect));
})();
