/*
 * GovVid object, developed by the Dutch Ministry of Health, Welfare and Sport and 'Werkgroep Stijlgids' of the New Media Commission (CNM)
 * inspired on:
 *    - swfobject (http://blog.deconcept.com/swfobject/)
 *    - GTObject (http://blog.deconcept.com/2005/01/26/web-standards-compliant-javascript-quicktime-detect-and-embed/)
 *
 * Author:      Marc Gerritsen (m.gerritsen@minvws.nl)
 * Version:     0.7 (11-12-2007)
 * Works on:    Internet Explorer 6/7, Firefox 1.5/2, Safari 2, Opera 9
 * Description:   Can detect flash version and sees if Quicktime is installed
 *          Generates correct HTML for embedded movie and audio
 *          Can replace a HTML element with the movie/audio html
 *
 *
 * Usage:
 *     myMovie = new GovVid("id", width, height);
 *     myMovie.addMovie("filename"); // supports mov, mp4, wmv, flv
 *     mymovie.addImage("filename"); // adds start image for flv player, only for movies
 *     for flv use path from flvplayer file
 *     myMovie.addCaption("flv","filename"); //adds caption file for flv player, only for movies
 *     myMovie.addAudio("filename"); //supports mp3, can display single mp3 file without movie, or add mp3 as audio description for flvmovie
 *     myMovie.write("htmlelementid"); // script puts movie html inside html element
 *
 * Changes:
 *  (5-11-2007)   - added movieObject.addFlashVars("usecaptions","false"); on line 149
 *  (11-12-2007)  - added addAudio function for adding mp3 files
 *          - changed function names to prevent problems when using javascript frameworks like prototype.js
 *          - replaced Flvplayer for Mediaplayer from Jeroen Wijering (can also play single mp3 files)
 *
 */
// change these filenames if you want to use different files
// leave empty if you don't need asp files
var contentDispositionFile = "content-disposition.asp";
var statisticsFile = "statistics/statistics.asp";
var mediaplayerFile = "/views/pagetypes/video/flash/mediaplayer.swf";
var debug = false;
var arFileTypes = new Array();

arFileTypes["jwmedia"]    = new Array("flv","mp3","mp4");
arFileTypes["quicktime"]  = new Array("smil","mov","mp3");
arFileTypes["winmedia"]   = new Array("asx","wmv","mp3","wma");

//GovVid object
GovVid = function(id, width, height) {
  this.id = id;
  this.width = width;
  this.height = height;
  this.movies = new Object();
  this.audioFiles = new Object();
  this.captions = new Object();
  this.image = "";
};

//add movie function, adds movie to object, myMovie.addMovie("filename");
GovVid.prototype.addMovie = function(filename) {
  var temp = filename.split("/");
  var thefile = temp[temp.length - 1];
  var file = thefile.split(".");
  var type = file[file.length - 1];
  //if(type == "mp4") type = "mov";
  this.movies[type] = filename;
};

//add movie function, adds movie to object, myMovie.addMovie("filename");
GovVid.prototype.addAudio = function(filename) {
  var temp = filename.split("/");
  var thefile = temp[temp.length - 1];
  var file = thefile.split(".");
  var type = file[file.length - 1];
  this.audioFiles[type] = filename;
};

//adds image to object, myMovie.addImage("filename");
GovVid.prototype.addImage = function(filename) {
  this.image = filename;
};

//adds caption to object, myMovie.addCaption("flv","filename");
GovVid.prototype.addCaption = function(type, filename) {
  this.captions[type] = filename;
};

GovVid.prototype.inArray = function (needleArray,haystackArray) {
  var key;
  var key2;
  for(key in haystackArray) {
    for(key2 in needleArray) {
      //alert(key + " : " + needleArray[key2]);
      if(key == needleArray[key2]) return key;
    }
  }
  return false;
};

//writes correct movie to html element
GovVid.prototype.write = function(elementid) {
  //get element with id
  var element = document.getElementById(elementid);
  if (element) {
    //set with to parentnode: TODO: maybe only on li elements
    element.parentNode.style.width = parseInt(this.width,10) + "px";
    $("#toggle_list_"+elementid).hide();
    var a = $('<a href="#" id="a_list_'+elementid+'"></a>');
    $("#list_"+elementid).wrapInner(a);
    $("#a_list_"+elementid).toggle(function(){
      $("#toggle_list_"+elementid).show();
      return false;
    },
    function(){
      $("#toggle_list_"+elementid).hide();
      return false;
    });
  }
  var display = false;
  var version = GovVid_getFlashPlayerVersion();
  var height;
  if(version.major > 7) {
    if(mediaplayerFile == undefined || mediaplayerFile == "") {
      alert("voor het afspelen met de flash plugin, is de jwmediaplayer vereist.\n vul de variable mediaplayerFile met de juiste waarde.");
      return false;
    }
    height = parseInt(this.height,10) + 20;
    if(display = this.inArray(arFileTypes["jwmedia"],this.movies)) {
      //alert("play movie in jwmediplayer");
      var movieObject = new GovVidMovie(mediaplayerFile, this.id, this.width, height);
      movieObject.addFlashVars("autostart", "false");
      // set image if there is a image defined
      if(this.image != "") movieObject.addFlashVars("image", this.image);
      // set caption if there is caption
      if (this.captions["flv"] != undefined) movieObject.addFlashVars("captions", this.captions["flv"]);
      if (this.audioFiles["mp3"] != undefined) movieObject.addFlashVars("audio", this.audioFiles["mp3"]);
      movieObject.addFlashVars("usecaptions","false");
      movieObject.addFlashVars("overstretch","false");
      movieObject.addFlashVars("file", this.movies[display]); //path from flash file location
      if(statisticsFile != undefined && statisticsFile != "") {
        movieObject.addFlashVars("callback",statisticsFile);
        movieObject.addFlashVars("logevents",statisticsFile);
      }
      movieObject.addFlashVars("showdigits","total");
      movieObject.addFlashVars("showbuttons","true");
      movieObject.addFlashVars("bufferlength","5");
      movieObject.addFlashVars("backcolor","0x000000");
      movieObject.addFlashVars("frontcolor","0xFFFFFF");
      movieObject.addFlashVars("lightcolor","0xFFFFFF");
      movieObject.showMovie(elementid,"flash");
      //element.innerHTML = movieObject.getFlashHTML();
      return true;
    }
    else if(display = this.inArray(arFileTypes["jwmedia"],this.audioFiles)) {
      //alert("play audio in jwmediaplayer");
      var audioObject = new GovVidMovie(mediaplayerFile, this.id, this.width, height);
      audioObject.addFlashVars("file", this.audioFiles[display]); //path from flash file location
      if(statisticsFile != undefined && statisticsFile != "") {
        audioObject.addFlashVars("callback",statisticsFile);
        audioObject.addFlashVars("logevents",statisticsFile);
      }
      audioObject.addFlashVars("showdigits","total");
      audioObject.addFlashVars("showbuttons","true");
      audioObject.addFlashVars("bufferlength","5");
      audioObject.addFlashVars("backcolor","0x000000");
      audioObject.addFlashVars("frontcolor","0xFFFFFF");
      audioObject.addFlashVars("lightcolor","0xFFFFFF");
      audioObject.showMovie(elementid,"flash");
      //element.innerHTML =  audioObject.getFlashHTML();
      return true;
    }
  }
  if (GovVid_isQTInstalled() && !display) {
    // Toon quicktime
    height = parseInt(this.height,10) + 16;
    if(display = this.inArray(arFileTypes["quicktime"],this.movies)) {
      if(display == "smil") height = parseInt(this.height,10) + 115;
      var movieObject = new GovVidMovie(this.movies[display], this.id, this.width, height);
      movieObject.addParam("autostart", "false");
      movieObject.addParam("autoplay", "false");
      movieObject.addParam("controller", "true");
      movieObject.addParam("target", "myself");
      movieObject.showMovie(elementid,"quicktime");
      return true;
    }
    else if(display = this.inArray(arFileTypes["quicktime"],this.audioFiles)) {
      //alert("play audio in quicktime");
      var audioObject = new GovVidMovie(this.audioFiles[display], this.id, this.width, height);
      audioObject.addParam("autostart", "false");
      audioObject.addParam("autoplay", "false");
      audioObject.addParam("controller", "true");
      audioObject.addParam("target", "myself");
      audioObject.showMovie(elementid,"quicktime");
      return true;
    }
  }
  if (!display && GovVid_isWMPInstalled()) {
    // Toon windows media player
    height = parseInt(this.height,10) + 46;
    if(display = this.inArray(arFileTypes["winmedia"],this.movies)) {
      //alert("play movie in wimmedia");
      var movieObject = new GovVidMovie(this.movies[display], this.id, this.width, height);
      movieObject.addParam("src", this.movies[display]);
      movieObject.addParam("Showcontrols", "true");
      movieObject.addParam("autoStart", "false");
      movieObject.showMovie(elementid,"winmedia");
      return true;
    }
    else if(display = this.inArray(arFileTypes["winmedia"],this.audioFiles)) {
      //alert("play audio in wimmedia");
      var audioObject = new GovVidMovie(this.audioFiles[display], this.id, this.width, height);
      audioObject.addParam("src", this.audioFiles[display]);
      audioObject.addParam("Showcontrols", "true");
      audioObject.addParam("autoStart", "false");
      audioObject.showMovie(elementid,"winmedia");
      return true;
    }
  }
  if (!display) {
    var div = document.getElementById(elementid);
    div.innerHTML += '<p>Op uw systeem kan dit media bestand niet worden afgespeeld. Download <a href="http://get.adobe.com/flashplayer/" target="_blank">Adobe Flash Player</a> voor het beste resultaat.</p>';
  }
  return false;
};

// movie object and functions
GovVidMovie = function(filename, id, width, height) {
  this.filename = filename;
  this.id = id;
  this.width = width;
  this.height = height;
  this.params = new Object();
  this.flashvars = new Object();
};

// function add params to Movie object
GovVidMovie.prototype.addParam = function(name, value) {
  this.params[name] = value;
};

// function that is used by other Movie functions
GovVidMovie.prototype.getParams = function() {
  return this.params;
};

// function to add flash variables to object
GovVidMovie.prototype.addFlashVars = function(name, value) {
  this.flashvars[name] = value;
};

// function that is used by other functions
GovVidMovie.prototype.getFlashVars = function() {
  return this.flashvars;
};

// function that is used by other functions
GovVidMovie.prototype.getParamTags = function() {
  var paramTags = "";
  for (var param in this.getParams()) {
    paramTags += '<param name="' + param + '" value="' + this.params[param] + '" />\n';
  }
  if (paramTags == "") {
    paramTags = null;
  }
  return paramTags;
};

/*
 * HTML generator functions
 *
 *
 */
// function that generates quicktime html
GovVidMovie.prototype.getQuicktimeHTML = function() {
  var qtHTML = "";
  qtHTML += "<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\" width=\"" + this.width + "\" height=\"" + this.height + "\">\n";
  qtHTML += "<param name=\"src\" value=\"" + this.filename + "\" />\n";
  if (this.getParamTags() != null) {
    qtHTML += this.getParamTags();
  }
  qtHTML += "<!--[if !IE]>-->\n";
  qtHTML += "<object type=\"video/quicktime\" data=\"" + this.filename + "\" width=\"" + this.width + "\" height=\"" + this.height + "\">\n";
  if (this.getParamTags() != null) {
    qtHTML += this.getParamTags();
  }
  qtHTML += "</object>\n";
  qtHTML += "<!--<![endif]-->\n";
  qtHTML += "</object>\n";
  return qtHTML;
};

// function that generates windows media player html
GovVidMovie.prototype.getWinmediaHTML = function() {
  var wHTML = '';
  wHTML = '<object id="' + this.id + '" width=' + this.width + ' height=' + this.height + ' classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" standby="Loading Windows Media Player components..." type="application/x-oleobject" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112">';
  wHTML += '<param name="filename" value="' + this.filename + '">';
  if (this.getParamTags() != null) {
    wHTML += this.getParamTags();
  }
  wHTML += '<embed type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/ en/download/" src="' + this.filename + '" id="' + this.id + '" name="' + this.id + '" width="' + this.width + '" height="' + this.height + '"';
  for (var param in this.getParams()) {
    wHTML += ' ' + param + '="' + this.params[param] + '"';
  }
  wHTML += '></embed></object>';
  return wHTML;
};

// function that generates flash html, different for ie or navigator browsers
GovVidMovie.prototype.getFlashHTML = function() {
  var swfHTML = "";
  var flashVars = "";
  // do flashvars
  if(this.flashvars) {
    for (var param in this.getFlashVars()) {
      flashVars += param + '=' + this.flashvars[param] + '&';
    }
  }
  if(navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length){
    swfHTML = '<embed type="application/x-shockwave-flash" src="'+ this.filename + '" width="' + this.width + '" height="' + this.height + '"';
    swfHTML += ' id="' + this.id + '" name="' + this.id + '" allowfullscreen=true';
    for (var param in this.getParams()) {
      swfHTML += ' ' + param + '="' + this.params[param] + '"';
    }
    if(flashVars != '') swfHTML += ' flashvars="' + flashVars + '"';
    swfHTML += "/>";
  }
  else{
    swfHTML = "<object id=\"" + this.id + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + this.width + "\" height=\"" + this.height + "\">";
    swfHTML += "<param name=\"movie\" value=\"" + this.filename + "\" />";
    swfHTML += "<param name=\"allowfullscreen\" value=\"true\" />";
    swfHTML += "<param name=\"wmode\" value=\"opaque\" />";
    if (this.getParamTags() != null) {
      swfHTML += this.getParamTags();
    }
    if(flashVars != '') swfHTML += "<param name=\"flashvars\" value=\""+ flashVars +"\" />";
    swfHTML+="</object>";
  }
  return swfHTML;
};

// replace element with movie html, the get+movie+HTML functions
GovVidMovie.prototype.showMovie = function(elementID, filetype) {
  var element = document.getElementById(elementID);
  if(filetype == 'flash') {
    element.innerHTML =  this.getFlashHTML();
  } else if (filetype == 'quicktime') {
    element.innerHTML = this.getQuicktimeHTML();
  } else if (filetype == 'winmedia') {
    element.innerHTML = this.getWinmediaHTML();
  }
};

/*
 * Detector functions
 *
 *
 */
// Function gets flashplayer version, if flash is not installed it returns major:0 minor:0 revision:0
function GovVid_getFlashPlayerVersion(){
  var version = new FlashPlayerVersion([0,0,0]);
  if(navigator.plugins && navigator.mimeTypes.length){
    var x=navigator.plugins["Shockwave Flash"];
    if(x && x.description){
      version = new FlashPlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));
    }
  }
  else {
    try{
      var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    }
    catch(e){
      try{
        var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
        version = new FlashPlayerVersion([6,0,21]);
        axo.AllowScriptAccess="always";
      }
      catch(e){
        if(version.major==6){return version;}
      }
      try{
        axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      }
      catch(e){}
    }
    if(axo!=null){
      version=new FlashPlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
    }
  }
  return version;
};

// object used by the getFlashPlayerVersion function
FlashPlayerVersion = function(player){
  this.major = player[0]!=null?parseInt(player[0],10):0;
  this.minor = player[1]!=null?parseInt(player[1],10):0;
  this.rev    = player[2]!=null?parseInt(player[2],10):0;
};

// function checks if quicktime is installed
function GovVid_isQTInstalled() {
  var qtInstalled = false;
  var qtObj = false;
  if (navigator.plugins && navigator.plugins.length) {
    var navigatorLength = navigator.plugins.length;
    for (var i=0; i < navigatorLength; i++ ) {
      var plugin = navigator.plugins[i];
      if (plugin.name.indexOf("QuickTime") > -1) {
        qtInstalled = true;
      }
    }
  } else {
    execScript('on error resume next: qtObj = IsObject(CreateObject("QuickTimeCheckObject.QuickTimeCheck.1"))','VBScript');
    qtInstalled = qtObj;
  }
  return qtInstalled;
}

// function checks if mediaplayer is installed, only for Firefox
function GovVid_isWMPInstalled() {
  var wmpInstalled = false;
  if (navigator.plugins && navigator.plugins.length) {
    var navigatorLength = navigator.plugins.length;
    for (var i=0; i < navigatorLength; i++ ) {
      var plugin = navigator.plugins[i];

      if (plugin.name.indexOf("MediaPlayer") > -1) {
        wmpInstalled = true;
      }
    }
  }
  else {
    return true;
  }
  return wmpInstalled;
}

/*
 * General functions / html functions
 *
 *
 */
// function hides or shows an element with stylesheet classes
function GovVid_toggle(objid) {
  var el = document.getElementById(objid);
  if ( el.className == 'close' ) el.className = 'open';
  else el.className = 'close';
}

// do stuff with links to binary files (not needed for pilot video files)
function openBinary() {
  if(contentDispositionFile != undefined && contentDispositionFile != "") {
    var filetypes = new Array("pdf", "wmv", "mov", "mp4", "flv", "3gp","mp3");
    var myAnchors = document.getElementsByTagName('a');
    var myAnchorsLength = myAnchors.length;
    for (i=0; i<myAnchorsLength ;i++)  {
      var anchor = myAnchors[i];
      var url = String(anchor.getAttribute('href'));
      var arUrl = url.split(".");
      var filetype = arUrl[arUrl.length-1];
      if(GovVid_in_array(filetypes, filetype.toLowerCase())) {
        var myfile = anchor.href.replace(document.location.href.substring(0,document.location.href.lastIndexOf("/")+1),'');
        //myfile = myfile.replace("http://www.minvws.nl/video",""); //TODO: no urls
        anchor.href = contentDispositionFile + "?file=" + myfile;
        anchor.onclick = function () {
          this.href = this.href;
        };
      }
      else if (anchor.className == "transcription") {
        anchor.onclick = function () {
          return newWin(this.href,'500','500');
        };
      }
    }
  }
}

// toggle list
function GovVid_makeListToggle(liID) {
  var element = document.getElementById(liID);
  if(element) {
    var parent = GovVid_getParentByClassname("moviecontent", element);
    if(!parent) parent = GovVid_getParentByClassname("audiocontent", element);
    if(parent)
      var elements = GovVid_getElementsByClassName("toggle","LI",parent);
    else
      var elements = GovVid_getElementsByClassName("toggle","LI");
    //loop elements
    var elementsLength = elements.length;
    for(var i = 0; i < elementsLength; i++) {
      var ulID = "govVid_ToggleMenu_" + i + liID;
      var toggleEl = "";
      var header  = "";
      var childNodesLength = elements[i].childNodes.length;
      for (var j = 0; j < childNodesLength ; j++ ){
        var tagName = elements[i].childNodes[j].tagName;
        if ((tagName == "H2" || tagName == "H3" || tagName == "H4" || tagName == "H5" || tagName == "H6" || tagName == "SPAN" || tagName == "A") && header == "") {
          header = elements[i].childNodes[j];
          var headerID = "govVid_ToggleLink_" + i +  liID;
          // add link to download video header
          if(tagName == "A") {
            header.id = headerID;
            header.onclick = "GovVid_toggle(\'" + ulID  + "\'); GovVid_toggle(this.id); return false;";
          } else {
            header.innerHTML = '<a href="#" id="' + headerID + '" onclick="GovVid_toggle(\'' + ulID  + '\'); GovVid_toggle(this.id); return false;">' + header.innerHTML + '</a>';
          }
          GovVid_toggle(headerID);
        }
        if((tagName == "UL" || tagName == "DIV" || tagName == "P") && toggleEl == "") {
          toggleEl = elements[i].childNodes[j];
          toggleEl.id = ulID;
          GovVid_toggle(ulID);
        }
      }
    }
  }
  else alert("id '" + liID + "'not found!");
}

// funtion to check if a value is in a array, returns true or false
function GovVid_in_array(myArray, value) {
  var myArrayLength = myArray.length;
  for(var i=0; i < myArrayLength; i++) {
    if(myArray[i] == value) return true;
  }
  return false;
}

function GovVid_getElementsByClassName(className, tag, elm){
  var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
  var tag = tag || "*";
  var elm = elm || document;
  var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
  var returnElements = [];
  var current;
  var length = elements.length;
  for(var i=0; i<length; i++){
    current = elements[i];
    if(testClass.test(current.className)){
      returnElements.push(current);
    }
  }
  return returnElements;
}

function GovVid_getParentByClassname(className, elm) {
  var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
  while(elm.tagName != "BODY") {
    if(testClass.test(elm.className)){
      return elm;
    }
    elm = elm.parentNode;
  }
  return false;
}

// flvplayer functions
var currentPosition;
var currentVolume;
function loadFile(caps) { thisMovie("mediaplayer").loadFile(fil); };
function thisMovie(movieName) {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
};

function sendEvent(typ,prm) {
  thisMovie("mediaplayer").sendEvent(typ,prm);
};

function getUpdate(typ,pr1,pr2) {
  if(typ == "time") { currentPosition = pr1; }
  else if(typ == "volume") { currentVolume = pr1; }
};

// on $(document).ready
(function($){
  $(function() {
    $("span.flashWrapper").ReplaceByFlashMovie();
  });
 /*
  Replaces an a-tag by a flashmovie
  */
  $.createFlashMovie = function (targetObj,flashUrl,w,h,id) {
    var type = flashUrl.toLowerCase().split('.');
    type = type[type.length -1];
    if (type == 'swf') {
      targetObj.removeChild(targetObj.firstChild);
      var o = document.createElement("object");
      o.id = id;
      o.width = w;
      o.height = h;
      var p1 = document.createElement("param");
      p1.name = "movie";
      p1.value = flashUrl;
      o.appendChild(p1);
      var p2 = document.createElement("param");
      p2.name = "quality";
      p2.value = "high";
      var p3 = document.createElement("param");
      p3.name = "wmode";
      p3.value = "transparent";
      o.appendChild(p3);
      var p4 = document.createElement("param");
      p4.name = "play";
      p4.value = "true";
      o.appendChild(p3);
      var em = document.createElement("embed");
      em.src = flashUrl;
      em.type = "application/x-shockwave-flash";
      em.quality = "high";
      em.wmode = "transparent";
      em.play = "true";
      em.id = id;
      em.width = w;
      em.height = h;
      targetObjParent = targetObj.parentNode;
      targetObjParent.removeChild(targetObj);
      try {
        o.appendChild(em);
        targetObjParent.appendChild(o);
      }
      catch (e) {
        targetObjParent.appendChild(em);
      }
    }
    else {
      var movie = new GovVid(id, w, h);
      movie.addMovie(flashUrl);
      movie.write(id); // writes movie to divID    targetObj.removeChild(targetObj.firstChild);
    }
  };

 /*
  Chain functions down here
  */
  
 /*
  Replaces links by an iframe with src = href
  Returns the filtered wrapped set
  */
  $.fn.ReplaceByFlashMovie = function() {
    $(this).makeId("movie").each(function() {
      var movie = $(this).find("a[href]");
      var dims = movie.attr('title').split('Flash: ')[1];
      var width = (dims && dims != '')?dims.split(',')[0]:249;
      var height = (dims && dims != '')?dims.split(',')[1]:249;
      var id = $(this).attr('id');

      $.createFlashMovie(this,movie.attr("href"),width,height,id);
    }); 
  };
})(jQuery); 


