/* Name:        CDF Plugin
 * Version:     1.0
 * Authors:     Sean Jordan and Bob Kuo, Wolfram Research
 * Description: Detects if user has the Mathematica Browser Plugin installed and embeds the document
 * License:     MIT License <http://www.wolfram.com/cdf-player/plugin/v1.0/LICENSE>
 * Copyright:   2011 Wolfram Research
 */

var cdf_plugin = function() { this.init(window.onload); };

cdf_plugin.prototype = {
  init: function(callback) {
    this.jobs = [];
    this.has_plugin = false;
    var self = this;
    window.onload = function() {
      if(typeof ActiveXObject != 'undefined') {
        // IE compatible browsers
        try {
          var control = new ActiveXObject("Mathematica.Control");
          if(control) {
            self.has_plugin = true;
          }
        } catch (e) { }
      } else if(navigator.plugins && navigator.plugins.length > 0) {
        // Mozilla and WebKit browsers
        for(var i = 0; i < navigator.plugins.length; i++) {
          if(navigator.plugins[i].name.indexOf("Wolfram Mathematica") !== -1) {
            self.has_plugin = true;
            break;
          }
        }
      }

      // Do not clobber an existing window.onload
      if(callback) {
        callback();
      }

      self._runJobs();

    };
  },

  _runJobs: function() {
    if (this.has_plugin) {
      for (var i = 0; i < this.jobs.length; i++) {
        var el = document.getElementById(this.jobs[i].element);
        if (el) {
          var parent = el.parentNode;
          // Replace given element with embed code
          parent.innerHTML = '<object classid="clsid:612AB921-E294-41AA-8E98-87E7E057EF33" width="' + this.jobs[i].width + '" height="' + this.jobs[i].height + '" type="application/vnd.wolfram.mathematica"><param name="src" value="' + this.jobs[i].src + '"><embed width="' + this.jobs[i].width + '" height="' + this.jobs[i].height + '" src="' + this.jobs[i].src + '" type="application/vnd.wolfram.mathematica"></object>';
        }
      }
    }
  },

  addCDFObject: function(element, src, width, height, fullscreen, toolbar) {
    // Optional arguments
    fullscreen = fullscreen || false;
    toolbar = toolbar || true;

    // This functional will be called before the document is ready
    // So queue up a job
    this.jobs.push({
      "element": element,
      "src": src,
      "width": width,
      "height": height,
      "fullscreen": fullscreen,
      "toolbar": toolbar
    });
  }
};

